pthread.cpp 32 KB

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