pthread.cpp 31 KB

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