pthread.cpp 31 KB

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