pthread.cpp 32 KB

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