pthread.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Atomic.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Format.h>
  10. #include <AK/SinglyLinkedList.h>
  11. #include <AK/StdLibExtras.h>
  12. #include <Kernel/API/Syscall.h>
  13. #include <LibSystem/syscall.h>
  14. #include <bits/pthread_cancel.h>
  15. #include <bits/pthread_integration.h>
  16. #include <errno.h>
  17. #include <limits.h>
  18. #include <mallocdefs.h>
  19. #include <pthread.h>
  20. #include <serenity.h>
  21. #include <signal.h>
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <sys/mman.h>
  25. #include <syscall.h>
  26. #include <time.h>
  27. #include <unistd.h>
  28. namespace {
  29. using PthreadAttrImpl = Syscall::SC_create_thread_params;
  30. } // end anonymous namespace
  31. static constexpr size_t required_stack_alignment = 4 * MiB;
  32. static constexpr size_t highest_reasonable_guard_size = 32 * PAGE_SIZE;
  33. static constexpr size_t highest_reasonable_stack_size = 8 * MiB; // That's the default in Ubuntu?
  34. __thread void* s_stack_location;
  35. __thread size_t s_stack_size;
  36. __thread int s_thread_cancel_state = PTHREAD_CANCEL_ENABLE;
  37. __thread int s_thread_cancel_type = PTHREAD_CANCEL_DEFERRED;
  38. #define __RETURN_PTHREAD_ERROR(rc) \
  39. return ((rc) < 0 ? -(rc) : 0)
  40. struct CleanupHandler {
  41. void (*routine)(void*);
  42. void* argument;
  43. };
  44. static thread_local SinglyLinkedList<CleanupHandler> cleanup_handlers;
  45. static __thread bool pending_cancellation = false;
  46. extern "C" {
  47. [[noreturn]] static void exit_thread(void* code, void* stack_location, size_t stack_size)
  48. {
  49. __pthread_key_destroy_for_current_thread();
  50. syscall(SC_exit_thread, code, stack_location, stack_size);
  51. VERIFY_NOT_REACHED();
  52. }
  53. [[noreturn]] static void pthread_exit_without_cleanup_handlers(void* value_ptr)
  54. {
  55. exit_thread(value_ptr, s_stack_location, s_stack_size);
  56. }
  57. static void* pthread_create_helper(void* (*routine)(void*), void* argument, void* stack_location, size_t stack_size)
  58. {
  59. s_stack_location = stack_location;
  60. s_stack_size = stack_size;
  61. void* ret_val = routine(argument);
  62. pthread_exit_without_cleanup_handlers(ret_val);
  63. }
  64. static int create_thread(pthread_t* thread, void* (*entry)(void*), void* argument, PthreadAttrImpl* thread_params)
  65. {
  66. void** stack = (void**)((uintptr_t)thread_params->stack_location + thread_params->stack_size);
  67. auto push_on_stack = [&](void* data) {
  68. stack--;
  69. *stack = data;
  70. thread_params->stack_size -= sizeof(void*);
  71. };
  72. // We set up the stack for pthread_create_helper.
  73. // Note that we need to align the stack to 16B, accounting for
  74. // the fact that we also push 16 bytes.
  75. while (((uintptr_t)stack - 16) % 16 != 0)
  76. push_on_stack(nullptr);
  77. #if ARCH(I386)
  78. push_on_stack((void*)(uintptr_t)thread_params->stack_size);
  79. push_on_stack(thread_params->stack_location);
  80. push_on_stack(argument);
  81. push_on_stack((void*)entry);
  82. #else
  83. thread_params->rdi = (FlatPtr)entry;
  84. thread_params->rsi = (FlatPtr)argument;
  85. thread_params->rdx = (FlatPtr)thread_params->stack_location;
  86. thread_params->rcx = thread_params->stack_size;
  87. #endif
  88. VERIFY((uintptr_t)stack % 16 == 0);
  89. // Push a fake return address
  90. push_on_stack(nullptr);
  91. int rc = syscall(SC_create_thread, pthread_create_helper, thread_params);
  92. if (rc >= 0)
  93. *thread = rc;
  94. __RETURN_PTHREAD_ERROR(rc);
  95. }
  96. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html
  97. int pthread_create(pthread_t* thread, pthread_attr_t* attributes, void* (*start_routine)(void*), void* argument_to_start_routine)
  98. {
  99. if (!thread)
  100. return -EINVAL;
  101. PthreadAttrImpl default_attributes {};
  102. PthreadAttrImpl** arg_attributes = reinterpret_cast<PthreadAttrImpl**>(attributes);
  103. PthreadAttrImpl* used_attributes = arg_attributes ? *arg_attributes : &default_attributes;
  104. if (!used_attributes->stack_location) {
  105. // adjust stack size, user might have called setstacksize, which has no restrictions on size/alignment
  106. if (0 != (used_attributes->stack_size % required_stack_alignment))
  107. used_attributes->stack_size += required_stack_alignment - (used_attributes->stack_size % required_stack_alignment);
  108. used_attributes->stack_location = mmap_with_name(nullptr, used_attributes->stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, 0, 0, "Thread stack");
  109. if (!used_attributes->stack_location)
  110. return -1;
  111. }
  112. dbgln_if(PTHREAD_DEBUG, "pthread_create: Creating thread with attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  113. used_attributes,
  114. (PTHREAD_CREATE_JOINABLE == used_attributes->detach_state) ? "joinable" : "detached",
  115. used_attributes->schedule_priority,
  116. used_attributes->guard_page_size,
  117. used_attributes->stack_size,
  118. used_attributes->stack_location);
  119. return create_thread(thread, start_routine, argument_to_start_routine, used_attributes);
  120. }
  121. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_exit.html
  122. void pthread_exit(void* value_ptr)
  123. {
  124. while (!cleanup_handlers.is_empty()) {
  125. auto handler = cleanup_handlers.take_first();
  126. handler.routine(handler.argument);
  127. }
  128. pthread_exit_without_cleanup_handlers(value_ptr);
  129. }
  130. void __pthread_maybe_cancel()
  131. {
  132. // Check if we have cancellations enabled.
  133. if (s_thread_cancel_state != PTHREAD_CANCEL_ENABLE)
  134. return;
  135. // Check if a cancellation request is pending.
  136. if (!pending_cancellation)
  137. return;
  138. // Exit the thread via `pthread_exit`. This handles passing the
  139. // return value and calling the cleanup handlers for us.
  140. pthread_exit(PTHREAD_CANCELED);
  141. }
  142. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cleanup_push.html
  143. void pthread_cleanup_push(void (*routine)(void*), void* arg)
  144. {
  145. cleanup_handlers.prepend({ routine, arg });
  146. }
  147. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cleanup_pop.html
  148. void pthread_cleanup_pop(int execute)
  149. {
  150. VERIFY(!cleanup_handlers.is_empty());
  151. auto handler = cleanup_handlers.take_first();
  152. if (execute)
  153. handler.routine(handler.argument);
  154. }
  155. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_join.html
  156. int pthread_join(pthread_t thread, void** exit_value_ptr)
  157. {
  158. __pthread_maybe_cancel();
  159. int rc = syscall(SC_join_thread, thread, exit_value_ptr);
  160. __RETURN_PTHREAD_ERROR(rc);
  161. }
  162. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_kill.html
  163. int pthread_kill(pthread_t thread, int sig)
  164. {
  165. int rc = syscall(SC_kill_thread, thread, sig);
  166. __RETURN_PTHREAD_ERROR(rc);
  167. }
  168. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_detach.html
  169. int pthread_detach(pthread_t thread)
  170. {
  171. int rc = syscall(SC_detach_thread, thread);
  172. __RETURN_PTHREAD_ERROR(rc);
  173. }
  174. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_sigmask.html
  175. int pthread_sigmask(int how, sigset_t const* set, sigset_t* old_set)
  176. {
  177. if (sigprocmask(how, set, old_set))
  178. return errno;
  179. return 0;
  180. }
  181. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_destroy.html
  182. int pthread_mutex_destroy(pthread_mutex_t*)
  183. {
  184. return 0;
  185. }
  186. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_init.html
  187. int pthread_mutexattr_init(pthread_mutexattr_t* attr)
  188. {
  189. attr->type = PTHREAD_MUTEX_NORMAL;
  190. return 0;
  191. }
  192. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_destroy.html
  193. int pthread_mutexattr_destroy(pthread_mutexattr_t*)
  194. {
  195. return 0;
  196. }
  197. int pthread_mutexattr_settype(pthread_mutexattr_t* attr, int type)
  198. {
  199. if (!attr)
  200. return EINVAL;
  201. if (type != PTHREAD_MUTEX_NORMAL && type != PTHREAD_MUTEX_RECURSIVE)
  202. return EINVAL;
  203. attr->type = type;
  204. return 0;
  205. }
  206. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_gettype.html
  207. int pthread_mutexattr_gettype(pthread_mutexattr_t* attr, int* type)
  208. {
  209. *type = attr->type;
  210. return 0;
  211. }
  212. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_init.html
  213. int pthread_attr_init(pthread_attr_t* attributes)
  214. {
  215. auto* impl = new PthreadAttrImpl {};
  216. *attributes = impl;
  217. dbgln_if(PTHREAD_DEBUG, "pthread_attr_init: New thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  218. impl,
  219. (PTHREAD_CREATE_JOINABLE == impl->detach_state) ? "joinable" : "detached",
  220. impl->schedule_priority,
  221. impl->guard_page_size,
  222. impl->stack_size,
  223. impl->stack_location);
  224. return 0;
  225. }
  226. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_destroy.html
  227. int pthread_attr_destroy(pthread_attr_t* attributes)
  228. {
  229. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  230. delete attributes_impl;
  231. return 0;
  232. }
  233. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getdetachstate.html
  234. int pthread_attr_getdetachstate(pthread_attr_t const* attributes, int* p_detach_state)
  235. {
  236. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl const* const*>(attributes));
  237. if (!attributes_impl || !p_detach_state)
  238. return EINVAL;
  239. *p_detach_state = attributes_impl->detach_state;
  240. return 0;
  241. }
  242. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setdetachstate.html
  243. int pthread_attr_setdetachstate(pthread_attr_t* attributes, int detach_state)
  244. {
  245. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  246. if (!attributes_impl)
  247. return EINVAL;
  248. if (detach_state != PTHREAD_CREATE_JOINABLE && detach_state != PTHREAD_CREATE_DETACHED)
  249. return EINVAL;
  250. attributes_impl->detach_state = detach_state;
  251. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setdetachstate: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  252. attributes_impl,
  253. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  254. attributes_impl->schedule_priority,
  255. attributes_impl->guard_page_size,
  256. attributes_impl->stack_size,
  257. attributes_impl->stack_location);
  258. return 0;
  259. }
  260. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getguardsize.html
  261. int pthread_attr_getguardsize(pthread_attr_t const* attributes, size_t* p_guard_size)
  262. {
  263. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl const* const*>(attributes));
  264. if (!attributes_impl || !p_guard_size)
  265. return EINVAL;
  266. *p_guard_size = attributes_impl->reported_guard_page_size;
  267. return 0;
  268. }
  269. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setguardsize.html
  270. int pthread_attr_setguardsize(pthread_attr_t* attributes, size_t guard_size)
  271. {
  272. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  273. if (!attributes_impl)
  274. return EINVAL;
  275. size_t actual_guard_size = guard_size;
  276. // round up
  277. if (0 != (guard_size % PAGE_SIZE))
  278. actual_guard_size += PAGE_SIZE - (guard_size % PAGE_SIZE);
  279. // what is the user even doing?
  280. if (actual_guard_size > highest_reasonable_guard_size) {
  281. return EINVAL;
  282. }
  283. attributes_impl->guard_page_size = actual_guard_size;
  284. attributes_impl->reported_guard_page_size = guard_size; // POSIX, why?
  285. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setguardsize: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  286. attributes_impl,
  287. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  288. attributes_impl->schedule_priority,
  289. attributes_impl->guard_page_size,
  290. attributes_impl->stack_size,
  291. attributes_impl->stack_location);
  292. return 0;
  293. }
  294. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getschedparam.html
  295. int pthread_attr_getschedparam(pthread_attr_t const* attributes, struct sched_param* p_sched_param)
  296. {
  297. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl const* const*>(attributes));
  298. if (!attributes_impl || !p_sched_param)
  299. return EINVAL;
  300. p_sched_param->sched_priority = attributes_impl->schedule_priority;
  301. return 0;
  302. }
  303. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setschedparam.html
  304. int pthread_attr_setschedparam(pthread_attr_t* attributes, const struct sched_param* p_sched_param)
  305. {
  306. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  307. if (!attributes_impl || !p_sched_param)
  308. return EINVAL;
  309. if (p_sched_param->sched_priority < THREAD_PRIORITY_MIN || p_sched_param->sched_priority > THREAD_PRIORITY_MAX)
  310. return ENOTSUP;
  311. attributes_impl->schedule_priority = p_sched_param->sched_priority;
  312. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setschedparam: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  313. attributes_impl,
  314. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  315. attributes_impl->schedule_priority,
  316. attributes_impl->guard_page_size,
  317. attributes_impl->stack_size,
  318. attributes_impl->stack_location);
  319. return 0;
  320. }
  321. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getstack.html
  322. int pthread_attr_getstack(pthread_attr_t const* attributes, void** p_stack_ptr, size_t* p_stack_size)
  323. {
  324. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl const* const*>(attributes));
  325. if (!attributes_impl || !p_stack_ptr || !p_stack_size)
  326. return EINVAL;
  327. *p_stack_ptr = attributes_impl->stack_location;
  328. *p_stack_size = attributes_impl->stack_size;
  329. return 0;
  330. }
  331. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setstack.html
  332. int pthread_attr_setstack(pthread_attr_t* attributes, void* p_stack, size_t stack_size)
  333. {
  334. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  335. if (!attributes_impl || !p_stack)
  336. return EINVAL;
  337. // Check for required alignment on size
  338. if (0 != (stack_size % required_stack_alignment))
  339. return EINVAL;
  340. // FIXME: Check for required alignment on pointer?
  341. // FIXME: "[EACCES] The stack page(s) described by stackaddr and stacksize are not both readable and writable by the thread."
  342. // Have to check that the whole range is mapped to this process/thread? Can we defer this to create_thread?
  343. attributes_impl->stack_size = stack_size;
  344. attributes_impl->stack_location = p_stack;
  345. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setstack: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  346. attributes_impl,
  347. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  348. attributes_impl->schedule_priority,
  349. attributes_impl->guard_page_size,
  350. attributes_impl->stack_size,
  351. attributes_impl->stack_location);
  352. return 0;
  353. }
  354. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getstacksize.html
  355. int pthread_attr_getstacksize(pthread_attr_t const* attributes, size_t* p_stack_size)
  356. {
  357. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl const* const*>(attributes));
  358. if (!attributes_impl || !p_stack_size)
  359. return EINVAL;
  360. *p_stack_size = attributes_impl->stack_size;
  361. return 0;
  362. }
  363. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setstacksize.html
  364. int pthread_attr_setstacksize(pthread_attr_t* attributes, size_t stack_size)
  365. {
  366. auto* attributes_impl = *(reinterpret_cast<PthreadAttrImpl**>(attributes));
  367. if (!attributes_impl)
  368. return EINVAL;
  369. if ((stack_size < PTHREAD_STACK_MIN) || stack_size > highest_reasonable_stack_size)
  370. return EINVAL;
  371. attributes_impl->stack_size = stack_size;
  372. dbgln_if(PTHREAD_DEBUG, "pthread_attr_setstacksize: Thread attributes at {}, detach state {}, priority {}, guard page size {}, stack size {}, stack location {}",
  373. attributes_impl,
  374. (PTHREAD_CREATE_JOINABLE == attributes_impl->detach_state) ? "joinable" : "detached",
  375. attributes_impl->schedule_priority,
  376. attributes_impl->guard_page_size,
  377. attributes_impl->stack_size,
  378. attributes_impl->stack_location);
  379. return 0;
  380. }
  381. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_getscope.html
  382. int pthread_attr_getscope([[maybe_unused]] pthread_attr_t const* attributes, [[maybe_unused]] int* contention_scope)
  383. {
  384. return 0;
  385. }
  386. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setscope.html
  387. int pthread_attr_setscope([[maybe_unused]] pthread_attr_t* attributes, [[maybe_unused]] int contention_scope)
  388. {
  389. return 0;
  390. }
  391. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_getschedparam.html
  392. int pthread_getschedparam([[maybe_unused]] pthread_t thread, [[maybe_unused]] int* policy, [[maybe_unused]] struct sched_param* param)
  393. {
  394. return 0;
  395. }
  396. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_setschedparam.html
  397. int pthread_setschedparam([[maybe_unused]] pthread_t thread, [[maybe_unused]] int policy, [[maybe_unused]] const struct sched_param* param)
  398. {
  399. return 0;
  400. }
  401. static void pthread_cancel_signal_handler(int signal)
  402. {
  403. // SIGCANCEL is a custom signal that is beyond the usual range of signal numbers.
  404. // Let's make sure we know about it in case we still end up in here, but the signal
  405. // number is being mangled.
  406. VERIFY(signal == SIGCANCEL);
  407. // Note: We don't handle PTHREAD_CANCEL_ASYNCHRONOUS any different from PTHREAD_CANCEL_DEFERRED,
  408. // since ASYNCHRONOUS just means that the thread can be cancelled at any time (instead of just
  409. // at the next cancellation point) and it seems to be generally discouraged to use it at all.
  410. pending_cancellation = true;
  411. }
  412. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cancel.html
  413. // NOTE: libgcc expects this function to exist in libpthread, even if it is not implemented.
  414. int pthread_cancel(pthread_t thread)
  415. {
  416. // Set up our signal handler, which listens on SIGCANCEL and flips the cancellation indicator.
  417. // Note that signal handlers are shared across the whole process, so we can just set that up at any time.
  418. static bool set_up_cancel_handler = false;
  419. if (!set_up_cancel_handler) {
  420. struct sigaction act = {};
  421. act.sa_handler = pthread_cancel_signal_handler;
  422. sigaction(SIGCANCEL, &act, nullptr);
  423. set_up_cancel_handler = true;
  424. }
  425. return pthread_kill(thread, SIGCANCEL);
  426. }
  427. int pthread_setname_np(pthread_t thread, char const* name)
  428. {
  429. if (!name)
  430. return EFAULT;
  431. int rc = syscall(SC_set_thread_name, thread, name, strlen(name));
  432. __RETURN_PTHREAD_ERROR(rc);
  433. }
  434. int pthread_getname_np(pthread_t thread, char* buffer, size_t buffer_size)
  435. {
  436. int rc = syscall(SC_get_thread_name, thread, buffer, buffer_size);
  437. __RETURN_PTHREAD_ERROR(rc);
  438. }
  439. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_setcancelstate.html
  440. int pthread_setcancelstate(int state, int* oldstate)
  441. {
  442. if (state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE)
  443. return EINVAL;
  444. if (oldstate)
  445. *oldstate = s_thread_cancel_state;
  446. s_thread_cancel_state = state;
  447. return 0;
  448. }
  449. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_setcanceltype.html
  450. int pthread_setcanceltype(int type, int* oldtype)
  451. {
  452. if (type != PTHREAD_CANCEL_DEFERRED && type != PTHREAD_CANCEL_ASYNCHRONOUS)
  453. return EINVAL;
  454. if (oldtype)
  455. *oldtype = s_thread_cancel_type;
  456. s_thread_cancel_type = type;
  457. return 0;
  458. }
  459. constexpr static pid_t spinlock_unlock_sentinel = 0;
  460. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_spin_destroy.html
  461. int pthread_spin_destroy(pthread_spinlock_t* lock)
  462. {
  463. auto current = AK::atomic_load(&lock->m_lock);
  464. if (current != spinlock_unlock_sentinel)
  465. return EBUSY;
  466. return 0;
  467. }
  468. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_spin_init.html
  469. int pthread_spin_init(pthread_spinlock_t* lock, [[maybe_unused]] int shared)
  470. {
  471. lock->m_lock = spinlock_unlock_sentinel;
  472. return 0;
  473. }
  474. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_spin_lock.html
  475. int pthread_spin_lock(pthread_spinlock_t* lock)
  476. {
  477. auto const desired = gettid();
  478. while (true) {
  479. auto current = AK::atomic_load(&lock->m_lock);
  480. if (current == desired)
  481. return EDEADLK;
  482. if (AK::atomic_compare_exchange_strong(&lock->m_lock, current, desired, AK::MemoryOrder::memory_order_acquire))
  483. break;
  484. }
  485. return 0;
  486. }
  487. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_spin_trylock.html
  488. int pthread_spin_trylock(pthread_spinlock_t* lock)
  489. {
  490. // We expect the current value to be unlocked, as the specification
  491. // states that trylock should lock only if it is not held by ANY thread.
  492. auto current = spinlock_unlock_sentinel;
  493. auto desired = gettid();
  494. if (AK::atomic_compare_exchange_strong(&lock->m_lock, current, desired, AK::MemoryOrder::memory_order_acquire)) {
  495. return 0;
  496. } else {
  497. return EBUSY;
  498. }
  499. }
  500. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_spin_unlock.html
  501. int pthread_spin_unlock(pthread_spinlock_t* lock)
  502. {
  503. auto current = AK::atomic_load(&lock->m_lock);
  504. if (gettid() != current)
  505. return EPERM;
  506. AK::atomic_store(&lock->m_lock, spinlock_unlock_sentinel);
  507. return 0;
  508. }
  509. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_equal.html
  510. int pthread_equal(pthread_t t1, pthread_t t2)
  511. {
  512. return t1 == t2;
  513. }
  514. // FIXME: Use the fancy futex mechanism above to write an rw lock.
  515. // For the time being, let's just use a less-than-good lock to get things working.
  516. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_destroy.html
  517. int pthread_rwlock_destroy(pthread_rwlock_t* rl)
  518. {
  519. if (!rl)
  520. return 0;
  521. return 0;
  522. }
  523. // In a very non-straightforward way, this value is composed of two 32-bit integers
  524. // the top 32 bits are reserved for the ID of write-locking thread (if any)
  525. // and the bottom 32 bits are:
  526. // top 2 bits (30,31): reader wake mask, writer wake mask
  527. // middle 16 bits: information
  528. // bit 16: someone is waiting to write
  529. // bit 17: locked for write
  530. // bottom 16 bits (0..15): reader count
  531. constexpr static u32 reader_wake_mask = 1 << 30;
  532. constexpr static u32 writer_wake_mask = 1 << 31;
  533. constexpr static u32 writer_locked_mask = 1 << 17;
  534. constexpr static u32 writer_intent_mask = 1 << 16;
  535. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_init.html
  536. int pthread_rwlock_init(pthread_rwlock_t* __restrict lockp, pthread_rwlockattr_t const* __restrict attr)
  537. {
  538. // Just ignore the attributes. use defaults for now.
  539. (void)attr;
  540. // No readers, no writer, not locked at all.
  541. *lockp = 0;
  542. return 0;
  543. }
  544. // Note that this function does not care about the top 32 bits at all.
  545. static int rwlock_rdlock_maybe_timed(u32* lockp, const struct timespec* timeout = nullptr, bool only_once = false, int value_if_timeout = -1, int value_if_okay = -2)
  546. {
  547. auto current = AK::atomic_load(lockp);
  548. for (; !only_once;) {
  549. // First, see if this is locked for writing
  550. // if it's not, try to add to the counter.
  551. // If someone is waiting to write, and there is one or no other readers, let them have the lock.
  552. if (!(current & writer_locked_mask)) {
  553. auto count = (u16)current;
  554. if (!(current & writer_intent_mask) || count > 1) {
  555. ++count;
  556. auto desired = (current & 0xffff0000u) | count;
  557. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  558. if (!did_exchange)
  559. continue; // tough luck, try again.
  560. return value_if_okay;
  561. }
  562. }
  563. // If no one else is waiting for the read wake bit, set it.
  564. if (!(current & reader_wake_mask)) {
  565. auto desired = current | reader_wake_mask;
  566. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  567. if (!did_exchange)
  568. continue; // Something interesting happened!
  569. current = desired;
  570. }
  571. // Seems like someone is writing (or is interested in writing and we let them have the lock)
  572. // wait until they're done.
  573. auto rc = futex(lockp, FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG, current, timeout, nullptr, reader_wake_mask);
  574. if (rc < 0 && errno == ETIMEDOUT && timeout) {
  575. return value_if_timeout;
  576. }
  577. if (rc < 0 && errno != EAGAIN) {
  578. // Something broke. let's just bail out.
  579. return errno;
  580. }
  581. errno = 0;
  582. // Reload the 'current' value
  583. current = AK::atomic_load(lockp);
  584. }
  585. return value_if_timeout;
  586. }
  587. static int rwlock_wrlock_maybe_timed(pthread_rwlock_t* lockval_p, const struct timespec* timeout = nullptr, bool only_once = false, int value_if_timeout = -1, int value_if_okay = -2)
  588. {
  589. u32* lockp = reinterpret_cast<u32*>(lockval_p);
  590. auto current = AK::atomic_load(lockp);
  591. for (; !only_once;) {
  592. // First, see if this is locked for writing, and if there are any readers.
  593. // if not, lock it.
  594. // If someone is waiting to write, let them have the lock.
  595. if (!(current & writer_locked_mask) && ((u16)current) == 0) {
  596. if (!(current & writer_intent_mask)) {
  597. auto desired = current | writer_locked_mask | writer_intent_mask;
  598. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  599. if (!did_exchange)
  600. continue;
  601. // Now that we've locked the value, it's safe to set our thread ID.
  602. AK::atomic_store(reinterpret_cast<i32*>(lockval_p) + 1, pthread_self());
  603. return value_if_okay;
  604. }
  605. }
  606. // That didn't work, if no one else is waiting for the write bit, set it.
  607. if (!(current & writer_wake_mask)) {
  608. auto desired = current | writer_wake_mask | writer_intent_mask;
  609. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_acquire);
  610. if (!did_exchange)
  611. continue; // Something interesting happened!
  612. current = desired;
  613. }
  614. // Seems like someone is writing (or is interested in writing and we let them have the lock)
  615. // wait until they're done.
  616. auto rc = futex(lockp, FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG, current, timeout, nullptr, writer_wake_mask);
  617. if (rc < 0 && errno == ETIMEDOUT && timeout) {
  618. return value_if_timeout;
  619. }
  620. if (rc < 0 && errno != EAGAIN) {
  621. // Something broke. let's just bail out.
  622. return errno;
  623. }
  624. errno = 0;
  625. // Reload the 'current' value
  626. current = AK::atomic_load(lockp);
  627. }
  628. return value_if_timeout;
  629. }
  630. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_rdlock.html
  631. int pthread_rwlock_rdlock(pthread_rwlock_t* lockp)
  632. {
  633. if (!lockp)
  634. return EINVAL;
  635. return rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), nullptr, false, 0, 0);
  636. }
  637. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_timedrdlock.html
  638. int pthread_rwlock_timedrdlock(pthread_rwlock_t* __restrict lockp, const struct timespec* __restrict timespec)
  639. {
  640. if (!lockp)
  641. return EINVAL;
  642. auto rc = rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), timespec);
  643. if (rc == -1) // "ok"
  644. return 0;
  645. if (rc == -2) // "timed out"
  646. return 1;
  647. return rc;
  648. }
  649. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_timedwrlock.html
  650. int pthread_rwlock_timedwrlock(pthread_rwlock_t* __restrict lockp, const struct timespec* __restrict timespec)
  651. {
  652. if (!lockp)
  653. return EINVAL;
  654. auto rc = rwlock_wrlock_maybe_timed(lockp, timespec);
  655. if (rc == -1) // "ok"
  656. return 0;
  657. if (rc == -2) // "timed out"
  658. return 1;
  659. return rc;
  660. }
  661. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_tryrdlock.html
  662. int pthread_rwlock_tryrdlock(pthread_rwlock_t* lockp)
  663. {
  664. if (!lockp)
  665. return EINVAL;
  666. return rwlock_rdlock_maybe_timed(reinterpret_cast<u32*>(lockp), nullptr, true, EBUSY, 0);
  667. }
  668. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_trywrlock.html
  669. int pthread_rwlock_trywrlock(pthread_rwlock_t* lockp)
  670. {
  671. if (!lockp)
  672. return EINVAL;
  673. return rwlock_wrlock_maybe_timed(lockp, nullptr, true, EBUSY, 0);
  674. }
  675. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_unlock.html
  676. int pthread_rwlock_unlock(pthread_rwlock_t* lockval_p)
  677. {
  678. if (!lockval_p)
  679. return EINVAL;
  680. // This is a weird API, we don't really know whether we're unlocking write or read...
  681. auto lockp = reinterpret_cast<u32*>(lockval_p);
  682. auto current = AK::atomic_load(lockp, AK::MemoryOrder::memory_order_relaxed);
  683. if (current & writer_locked_mask) {
  684. // If this lock is locked for writing, its owner better be us!
  685. auto owner_id = AK::atomic_load(reinterpret_cast<i32*>(lockval_p) + 1);
  686. auto my_id = pthread_self();
  687. if (owner_id != my_id)
  688. return EINVAL; // you don't own this lock, silly.
  689. // Now just unlock it.
  690. auto desired = current & ~(writer_locked_mask | writer_intent_mask);
  691. AK::atomic_store(lockp, desired, AK::MemoryOrder::memory_order_release);
  692. // Then wake both readers and writers, if any.
  693. auto rc = futex(lockp, FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG, current, nullptr, nullptr, (current & writer_wake_mask) | reader_wake_mask);
  694. if (rc < 0)
  695. return errno;
  696. return 0;
  697. }
  698. for (;;) {
  699. auto count = (u16)current;
  700. if (!count) {
  701. // Are you crazy? this isn't even locked!
  702. return EINVAL;
  703. }
  704. --count;
  705. auto desired = (current & 0xffff0000u) | count;
  706. auto did_exchange = AK::atomic_compare_exchange_strong(lockp, current, desired, AK::MemoryOrder::memory_order_release);
  707. if (did_exchange)
  708. break;
  709. // tough luck, try again.
  710. }
  711. // Finally, unlocked at last!
  712. return 0;
  713. }
  714. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlock_wrlock.html
  715. int pthread_rwlock_wrlock(pthread_rwlock_t* lockp)
  716. {
  717. if (!lockp)
  718. return EINVAL;
  719. return rwlock_wrlock_maybe_timed(lockp, nullptr, false, 0, 0);
  720. }
  721. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlockattr_destroy.html
  722. int pthread_rwlockattr_destroy(pthread_rwlockattr_t*)
  723. {
  724. return 0;
  725. }
  726. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlockattr_getpshared.html
  727. int pthread_rwlockattr_getpshared(pthread_rwlockattr_t const* __restrict, int* __restrict)
  728. {
  729. VERIFY_NOT_REACHED();
  730. }
  731. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlockattr_init.html
  732. int pthread_rwlockattr_init(pthread_rwlockattr_t*)
  733. {
  734. VERIFY_NOT_REACHED();
  735. }
  736. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_rwlockattr_setpshared.html
  737. int pthread_rwlockattr_setpshared(pthread_rwlockattr_t*, int)
  738. {
  739. VERIFY_NOT_REACHED();
  740. }
  741. // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_atfork.html
  742. int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
  743. {
  744. if (prepare)
  745. __pthread_fork_atfork_register_prepare(prepare);
  746. if (parent)
  747. __pthread_fork_atfork_register_parent(parent);
  748. if (child)
  749. __pthread_fork_atfork_register_child(child);
  750. return 0;
  751. }
  752. } // extern "C"