]> git.saurik.com Git - apple/libpthread.git/blob - src/pthread.c
libpthread-454.40.3.tar.gz
[apple/libpthread.git] / src / pthread.c
1 /*
2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /*
24 * Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991
25 * All Rights Reserved
26 *
27 * Permission to use, copy, modify, and distribute this software and
28 * its documentation for any purpose and without fee is hereby granted,
29 * provided that the above copyright notice appears in all copies and
30 * that both the copyright notice and this permission notice appear in
31 * supporting documentation.
32 *
33 * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
34 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
35 * FOR A PARTICULAR PURPOSE.
36 *
37 * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
38 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
39 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
40 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
41 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
42 *
43 */
44 /*
45 * MkLinux
46 */
47
48 /*
49 * POSIX Pthread Library
50 */
51
52 #include "internal.h"
53
54 #include <stdlib.h>
55 #include <errno.h>
56 #include <signal.h>
57 #include <unistd.h>
58 #include <mach/mach_init.h>
59 #include <mach/mach_vm.h>
60 #include <mach/mach_sync_ipc.h>
61 #include <sys/time.h>
62 #include <sys/resource.h>
63 #include <sys/sysctl.h>
64 #include <sys/queue.h>
65 #include <sys/ulock.h>
66 #include <sys/mman.h>
67 #include <machine/vmparam.h>
68 #define __APPLE_API_PRIVATE
69 #include <machine/cpu_capabilities.h>
70 #if __has_include(<ptrauth.h>)
71 #include <ptrauth.h>
72 #endif // __has_include(<ptrauth.h>)
73 #include <os/thread_self_restrict.h>
74 #include <os/tsd.h>
75
76 // Default stack size is 512KB; independent of the main thread's stack size.
77 #define DEFAULT_STACK_SIZE (size_t)(512 * 1024)
78
79 //
80 // Global constants
81 //
82
83 /*
84 * The pthread may be offset into a page. In that event, by contract
85 * with the kernel, the allocation will extend PTHREAD_SIZE from the
86 * start of the next page. There's also one page worth of allocation
87 * below stacksize for the guard page. <rdar://problem/19941744>
88 */
89 #define PTHREAD_SIZE ((size_t)mach_vm_round_page(sizeof(struct pthread_s)))
90 #define PTHREAD_ALLOCADDR(stackaddr, stacksize) ((stackaddr - stacksize) - vm_page_size)
91 #define PTHREAD_ALLOCSIZE(stackaddr, stacksize) ((round_page((uintptr_t)stackaddr) + PTHREAD_SIZE) - (uintptr_t)PTHREAD_ALLOCADDR(stackaddr, stacksize))
92
93 static const pthread_attr_t _pthread_attr_default = {
94 .sig = _PTHREAD_ATTR_SIG,
95 .stacksize = 0,
96 .detached = PTHREAD_CREATE_JOINABLE,
97 .inherit = _PTHREAD_DEFAULT_INHERITSCHED,
98 .policy = _PTHREAD_DEFAULT_POLICY,
99 .defaultguardpage = true,
100 // compile time constant for _pthread_default_priority(0)
101 .qosclass = (1U << (THREAD_QOS_LEGACY - 1 + _PTHREAD_PRIORITY_QOS_CLASS_SHIFT)) |
102 ((uint8_t)-1 & _PTHREAD_PRIORITY_PRIORITY_MASK),
103 };
104
105 #if PTHREAD_LAYOUT_SPI
106
107 const struct pthread_layout_offsets_s pthread_layout_offsets = {
108 .plo_version = 1,
109 .plo_pthread_tsd_base_offset = offsetof(struct pthread_s, tsd),
110 .plo_pthread_tsd_base_address_offset = 0,
111 .plo_pthread_tsd_entry_size = sizeof(((struct pthread_s *)NULL)->tsd[0]),
112 };
113
114 #endif // PTHREAD_LAYOUT_SPI
115
116 //
117 // Global exported variables
118 //
119
120 // This global should be used (carefully) by anyone needing to know if a
121 // pthread (other than the main thread) has been created.
122 int __is_threaded = 0;
123 const int __unix_conforming = 1; // we're always conformant, but it's exported
124
125 //
126 // Global internal variables
127 //
128
129 // _pthread_list_lock protects _pthread_count, access to the __pthread_head
130 // list. Externally imported by pthread_cancelable.c.
131 struct __pthread_list __pthread_head = TAILQ_HEAD_INITIALIZER(__pthread_head);
132 _pthread_lock _pthread_list_lock = _PTHREAD_LOCK_INITIALIZER;
133
134 uint32_t _main_qos;
135
136 #if VARIANT_DYLD
137 // The main thread's pthread_t
138 struct pthread_s _main_thread OS_ALIGNED(64);
139 #else // VARIANT_DYLD
140 pthread_t _main_thread_ptr;
141 void *(*_pthread_malloc)(size_t);
142 void (*_pthread_free)(void *);
143 #endif // VARIANT_DYLD
144
145 #if PTHREAD_DEBUG_LOG
146 #include <fcntl.h>
147 int _pthread_debuglog;
148 uint64_t _pthread_debugstart;
149 #endif
150
151 //
152 // Global static variables
153 //
154 static bool __workq_newapi;
155 static uint8_t default_priority;
156 #if !VARIANT_DYLD
157 static uint8_t max_priority;
158 static uint8_t min_priority;
159 #endif // !VARIANT_DYLD
160 static int _pthread_count = 1;
161 static int pthread_concurrency;
162 uintptr_t _pthread_ptr_munge_token;
163
164 static void (*exitf)(int) = __exit;
165
166 // work queue support data
167 OS_NORETURN OS_COLD
168 static void
169 __pthread_invalid_keventfunction(void **events, int *nevents)
170 {
171 PTHREAD_CLIENT_CRASH(0, "Invalid kqworkq setup");
172 }
173
174 OS_NORETURN OS_COLD
175 static void
176 __pthread_invalid_workloopfunction(uint64_t *workloop_id, void **events, int *nevents)
177 {
178 PTHREAD_CLIENT_CRASH(0, "Invalid kqwl setup");
179 }
180 static pthread_workqueue_function2_t __libdispatch_workerfunction;
181 static pthread_workqueue_function_kevent_t __libdispatch_keventfunction = &__pthread_invalid_keventfunction;
182 static pthread_workqueue_function_workloop_t __libdispatch_workloopfunction = &__pthread_invalid_workloopfunction;
183 static int __pthread_supported_features; // supported feature set
184
185 #if defined(__i386__) || defined(__x86_64__)
186 static mach_vm_address_t __pthread_stack_hint = 0xB0000000;
187 #elif defined(__arm__) || defined(__arm64__)
188 static mach_vm_address_t __pthread_stack_hint = 0x30000000;
189 #else
190 #error no __pthread_stack_hint for this architecture
191 #endif
192
193 //
194 // Function prototypes
195 //
196
197 // pthread primitives
198 static inline void _pthread_struct_init(pthread_t t, const pthread_attr_t *attrs,
199 void *stack, size_t stacksize, void *freeaddr, size_t freesize);
200
201 #if VARIANT_DYLD
202 static void _pthread_set_self_dyld(void);
203 #endif // VARIANT_DYLD
204 static inline void _pthread_set_self_internal(pthread_t);
205
206 static inline void __pthread_started_thread(pthread_t t);
207
208 static void _pthread_exit(pthread_t self, void *value_ptr) __dead2;
209
210 static inline void _pthread_introspection_thread_create(pthread_t t);
211 static inline void _pthread_introspection_thread_start(pthread_t t);
212 static inline void _pthread_introspection_thread_terminate(pthread_t t);
213 static inline void _pthread_introspection_thread_destroy(pthread_t t);
214
215 /*
216 * Flags filed passed to bsdthread_create and back in pthread_start
217 * 31 <---------------------------------> 0
218 * _________________________________________
219 * | flags(8) | policy(8) | importance(16) |
220 * -----------------------------------------
221 */
222 #define PTHREAD_START_CUSTOM 0x01000000 // <rdar://problem/34501401>
223 #define PTHREAD_START_SETSCHED 0x02000000
224 // was PTHREAD_START_DETACHED 0x04000000
225 #define PTHREAD_START_QOSCLASS 0x08000000
226 #define PTHREAD_START_TSD_BASE_SET 0x10000000
227 #define PTHREAD_START_SUSPENDED 0x20000000
228 #define PTHREAD_START_QOSCLASS_MASK 0x00ffffff
229 #define PTHREAD_START_POLICY_BITSHIFT 16
230 #define PTHREAD_START_POLICY_MASK 0xff
231 #define PTHREAD_START_IMPORTANCE_MASK 0xffff
232
233 #pragma mark pthread attrs
234
235 int
236 pthread_attr_destroy(pthread_attr_t *attr)
237 {
238 int ret = EINVAL;
239 if (attr->sig == _PTHREAD_ATTR_SIG) {
240 attr->sig = 0;
241 ret = 0;
242 }
243 return ret;
244 }
245
246 int
247 pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
248 {
249 int ret = EINVAL;
250 if (attr->sig == _PTHREAD_ATTR_SIG) {
251 *detachstate = attr->detached;
252 ret = 0;
253 }
254 return ret;
255 }
256
257 int
258 pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched)
259 {
260 int ret = EINVAL;
261 if (attr->sig == _PTHREAD_ATTR_SIG) {
262 *inheritsched = attr->inherit;
263 ret = 0;
264 }
265 return ret;
266 }
267
268 static OS_ALWAYS_INLINE void
269 _pthread_attr_get_schedparam(const pthread_attr_t *attr,
270 struct sched_param *param)
271 {
272 if (attr->schedset) {
273 *param = attr->param;
274 } else {
275 param->sched_priority = default_priority;
276 param->quantum = 10; /* quantum isn't public yet */
277 }
278 }
279
280 int
281 pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param)
282 {
283 int ret = EINVAL;
284 if (attr->sig == _PTHREAD_ATTR_SIG) {
285 _pthread_attr_get_schedparam(attr, param);
286 ret = 0;
287 }
288 return ret;
289 }
290
291 int
292 pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy)
293 {
294 int ret = EINVAL;
295 if (attr->sig == _PTHREAD_ATTR_SIG) {
296 *policy = attr->policy;
297 ret = 0;
298 }
299 return ret;
300 }
301
302 int
303 pthread_attr_init(pthread_attr_t *attr)
304 {
305 *attr = _pthread_attr_default;
306 return 0;
307 }
308
309 int
310 pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
311 {
312 int ret = EINVAL;
313 if (attr->sig == _PTHREAD_ATTR_SIG &&
314 (detachstate == PTHREAD_CREATE_JOINABLE ||
315 detachstate == PTHREAD_CREATE_DETACHED)) {
316 attr->detached = detachstate;
317 ret = 0;
318 }
319 return ret;
320 }
321
322 int
323 pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched)
324 {
325 int ret = EINVAL;
326 if (attr->sig == _PTHREAD_ATTR_SIG &&
327 (inheritsched == PTHREAD_INHERIT_SCHED ||
328 inheritsched == PTHREAD_EXPLICIT_SCHED)) {
329 attr->inherit = inheritsched;
330 ret = 0;
331 }
332 return ret;
333 }
334
335 int
336 pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param)
337 {
338 int ret = EINVAL;
339 if (attr->sig == _PTHREAD_ATTR_SIG) {
340 /* TODO: Validate sched_param fields */
341 attr->param = *param;
342 attr->schedset = 1;
343 ret = 0;
344 }
345 return ret;
346 }
347
348 #define _PTHREAD_POLICY_IS_FIXEDPRI(x) ((x) == SCHED_RR || (x) == SCHED_FIFO)
349
350 int
351 pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
352 {
353 int ret = EINVAL;
354 if (attr->sig == _PTHREAD_ATTR_SIG && (policy == SCHED_OTHER ||
355 policy == SCHED_RR || policy == SCHED_FIFO)) {
356 if (!_PTHREAD_POLICY_IS_FIXEDPRI(policy)) {
357 /* non-fixedpri policy should remove cpupercent */
358 attr->cpupercentset = 0;
359 }
360 attr->policy = policy;
361 attr->policyset = 1;
362 ret = 0;
363 }
364 return ret;
365 }
366
367 int
368 pthread_attr_setscope(pthread_attr_t *attr, int scope)
369 {
370 int ret = EINVAL;
371 if (attr->sig == _PTHREAD_ATTR_SIG) {
372 if (scope == PTHREAD_SCOPE_SYSTEM) {
373 // No attribute yet for the scope.
374 ret = 0;
375 } else if (scope == PTHREAD_SCOPE_PROCESS) {
376 ret = ENOTSUP;
377 }
378 }
379 return ret;
380 }
381
382 int
383 pthread_attr_getscope(const pthread_attr_t *attr, int *scope)
384 {
385 int ret = EINVAL;
386 if (attr->sig == _PTHREAD_ATTR_SIG) {
387 *scope = PTHREAD_SCOPE_SYSTEM;
388 ret = 0;
389 }
390 return ret;
391 }
392
393 int
394 pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr)
395 {
396 int ret = EINVAL;
397 if (attr->sig == _PTHREAD_ATTR_SIG) {
398 *stackaddr = attr->stackaddr;
399 ret = 0;
400 }
401 return ret;
402 }
403
404 int
405 pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr)
406 {
407 int ret = EINVAL;
408 if (attr->sig == _PTHREAD_ATTR_SIG &&
409 ((mach_vm_address_t)stackaddr & vm_page_mask) == 0) {
410 attr->stackaddr = stackaddr;
411 attr->defaultguardpage = false;
412 attr->guardsize = 0;
413 ret = 0;
414 }
415 return ret;
416 }
417
418 static inline size_t
419 _pthread_attr_stacksize(const pthread_attr_t *attr)
420 {
421 return attr->stacksize ? attr->stacksize : DEFAULT_STACK_SIZE;
422 }
423
424 int
425 pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
426 {
427 int ret = EINVAL;
428 if (attr->sig == _PTHREAD_ATTR_SIG) {
429 *stacksize = _pthread_attr_stacksize(attr);
430 ret = 0;
431 }
432 return ret;
433 }
434
435 int
436 pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
437 {
438 #if TARGET_OS_OSX
439 // If the caller is doing something reasonable, help them out.
440 if (stacksize % 0x1000 == 0) {
441 stacksize = round_page(stacksize);
442 }
443 #endif // TARGET_OS_OSX
444
445 int ret = EINVAL;
446 if (attr->sig == _PTHREAD_ATTR_SIG &&
447 ((stacksize & vm_page_mask) == 0) &&
448 stacksize >= PTHREAD_STACK_MIN) {
449 attr->stacksize = stacksize;
450 ret = 0;
451 }
452 return ret;
453 }
454
455 int
456 pthread_attr_getstack(const pthread_attr_t *attr, void **stackaddr, size_t * stacksize)
457 {
458 int ret = EINVAL;
459 if (attr->sig == _PTHREAD_ATTR_SIG) {
460 *stackaddr = (void *)((uintptr_t)attr->stackaddr - attr->stacksize);
461 *stacksize = _pthread_attr_stacksize(attr);
462 ret = 0;
463 }
464 return ret;
465 }
466
467 // Per SUSv3, the stackaddr is the base address, the lowest addressable byte
468 // address. This is not the same as in pthread_attr_setstackaddr.
469 int
470 pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize)
471 {
472 int ret = EINVAL;
473 if (attr->sig == _PTHREAD_ATTR_SIG &&
474 (((mach_vm_address_t)stackaddr & vm_page_mask) == 0) &&
475 ((stacksize & vm_page_mask) == 0) &&
476 stacksize >= PTHREAD_STACK_MIN) {
477 attr->stackaddr = (void *)((uintptr_t)stackaddr + stacksize);
478 attr->stacksize = stacksize;
479 ret = 0;
480 }
481 return ret;
482 }
483
484 int
485 pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize)
486 {
487 #if TARGET_OS_OSX
488 // If the caller is doing something reasonable, help them out.
489 if (guardsize % 0x1000 == 0) {
490 guardsize = round_page(guardsize);
491 }
492 #endif // TARGET_OS_OSX
493
494 int ret = EINVAL;
495 if (attr->sig == _PTHREAD_ATTR_SIG &&
496 (guardsize & vm_page_mask) == 0) {
497 /* Guardsize of 0 is valid, means no guard */
498 attr->defaultguardpage = false;
499 attr->guardsize = guardsize;
500 ret = 0;
501 }
502 return ret;
503 }
504
505 static inline size_t
506 _pthread_attr_guardsize(const pthread_attr_t *attr)
507 {
508 return attr->defaultguardpage ? vm_page_size : attr->guardsize;
509 }
510
511 int
512 pthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize)
513 {
514 int ret = EINVAL;
515 if (attr->sig == _PTHREAD_ATTR_SIG) {
516 *guardsize = _pthread_attr_guardsize(attr);
517 ret = 0;
518 }
519 return ret;
520 }
521
522 int
523 pthread_attr_setcpupercent_np(pthread_attr_t *attr, int percent,
524 unsigned long refillms)
525 {
526 int ret = EINVAL;
527 if (attr->sig == _PTHREAD_ATTR_SIG && percent < UINT8_MAX &&
528 refillms < _PTHREAD_ATTR_REFILLMS_MAX && attr->policyset &&
529 _PTHREAD_POLICY_IS_FIXEDPRI(attr->policy)) {
530 attr->cpupercent = percent;
531 attr->refillms = (uint32_t)(refillms & 0x00ffffff);
532 attr->cpupercentset = 1;
533 ret = 0;
534 }
535 return ret;
536 }
537
538 #pragma mark pthread lifetime
539
540 // Allocate a thread structure, stack and guard page.
541 //
542 // The thread structure may optionally be placed in the same allocation as the
543 // stack, residing above the top of the stack. This cannot be done if a
544 // custom stack address is provided.
545 //
546 // Similarly the guard page cannot be allocated if a custom stack address is
547 // provided.
548 //
549 // The allocated thread structure is initialized with values that indicate how
550 // it should be freed.
551
552 static pthread_t
553 _pthread_allocate(const pthread_attr_t *attrs, void **stack,
554 bool from_mach_thread)
555 {
556 mach_vm_address_t allocaddr = __pthread_stack_hint;
557 size_t allocsize, guardsize, stacksize, pthreadoff;
558 kern_return_t kr;
559 pthread_t t;
560
561 if (os_unlikely(attrs->stacksize != 0 &&
562 attrs->stacksize < PTHREAD_STACK_MIN)) {
563 PTHREAD_CLIENT_CRASH(attrs->stacksize, "Stack size in attrs is too small");
564 }
565
566 if (os_unlikely((mach_vm_address_t)attrs->stackaddr & vm_page_mask)) {
567 PTHREAD_CLIENT_CRASH(attrs->stackaddr, "Unaligned stack addr in attrs");
568 }
569
570 // Allocate a pthread structure if necessary
571
572 if (attrs->stackaddr != NULL) {
573 allocsize = PTHREAD_SIZE;
574 guardsize = 0;
575 pthreadoff = 0;
576 // <rdar://problem/42588315> if the attrs struct specifies a custom
577 // stack address but not a custom size, using ->stacksize here instead
578 // of _pthread_attr_stacksize stores stacksize as zero, indicating
579 // that the stack size is unknown.
580 stacksize = attrs->stacksize;
581 } else {
582 guardsize = _pthread_attr_guardsize(attrs);
583 stacksize = _pthread_attr_stacksize(attrs) + PTHREAD_T_OFFSET;
584 pthreadoff = stacksize + guardsize;
585 allocsize = pthreadoff + PTHREAD_SIZE;
586 allocsize = mach_vm_round_page(allocsize);
587 }
588
589 kr = mach_vm_map(mach_task_self(), &allocaddr, allocsize, vm_page_size - 1,
590 VM_MAKE_TAG(VM_MEMORY_STACK)| VM_FLAGS_ANYWHERE, MEMORY_OBJECT_NULL,
591 0, FALSE, VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
592
593 if (kr != KERN_SUCCESS) {
594 kr = mach_vm_allocate(mach_task_self(), &allocaddr, allocsize,
595 VM_MAKE_TAG(VM_MEMORY_STACK)| VM_FLAGS_ANYWHERE);
596 } else if (__syscall_logger && !from_mach_thread) {
597 // libsyscall will not output malloc stack logging events when
598 // VM_MEMORY_STACK is passed in to facilitate mach thread promotion.
599 // To avoid losing the stack traces for normal p-thread create
600 // operations, libpthread must pretend to be the vm syscall and log
601 // the allocations. <rdar://36418708>
602 int eventTypeFlags = stack_logging_type_vm_allocate |
603 stack_logging_type_mapped_file_or_shared_mem;
604 __syscall_logger(eventTypeFlags | VM_MAKE_TAG(VM_MEMORY_STACK),
605 (uintptr_t)mach_task_self(), (uintptr_t)allocsize, 0,
606 (uintptr_t)allocaddr, 0);
607 }
608
609 if (kr != KERN_SUCCESS) {
610 *stack = NULL;
611 return NULL;
612 } else if (__syscall_logger && !from_mach_thread) {
613 // libsyscall will not output malloc stack logging events when
614 // VM_MEMORY_STACK is passed in to facilitate mach thread promotion.
615 // To avoid losing the stack traces for normal p-thread create
616 // operations, libpthread must pretend to be the vm syscall and log
617 // the allocations. <rdar://36418708>
618 int eventTypeFlags = stack_logging_type_vm_allocate;
619 __syscall_logger(eventTypeFlags | VM_MAKE_TAG(VM_MEMORY_STACK),
620 (uintptr_t)mach_task_self(), (uintptr_t)allocsize, 0,
621 (uintptr_t)allocaddr, 0);
622 }
623
624 // The stack grows down.
625 // Set the guard page at the lowest address of the
626 // newly allocated stack. Return the highest address
627 // of the stack.
628 if (guardsize) {
629 (void)mach_vm_protect(mach_task_self(), allocaddr, guardsize,
630 FALSE, VM_PROT_NONE);
631 }
632
633 // Thread structure resides at the top of the stack (when using a
634 // custom stack, allocsize == PTHREAD_SIZE, so places the pthread_t
635 // at allocaddr).
636 t = (pthread_t)(allocaddr + pthreadoff);
637 if (attrs->stackaddr) {
638 *stack = attrs->stackaddr;
639 } else {
640 *stack = t;
641 }
642
643 _pthread_struct_init(t, attrs, *stack, stacksize, allocaddr, allocsize);
644 return t;
645 }
646
647 OS_NOINLINE
648 void
649 _pthread_deallocate(pthread_t t, bool from_mach_thread)
650 {
651 kern_return_t ret;
652
653 // Don't free the main thread.
654 if (t != main_thread()) {
655 if (!from_mach_thread) { // see __pthread_add_thread
656 _pthread_introspection_thread_destroy(t);
657 }
658 ret = mach_vm_deallocate(mach_task_self(), t->freeaddr, t->freesize);
659 if (ret != KERN_SUCCESS) {
660 PTHREAD_INTERNAL_CRASH(ret, "Unable to deallocate stack");
661 }
662 }
663 }
664
665 #pragma clang diagnostic push
666 #pragma clang diagnostic ignored "-Wreturn-stack-address"
667
668 OS_NOINLINE
669 static void*
670 _pthread_current_stack_address(void)
671 {
672 int a;
673 return &a;
674 }
675
676 #pragma clang diagnostic pop
677
678 static void
679 _pthread_joiner_wake(pthread_t thread)
680 {
681 uint32_t *exit_gate = &thread->tl_exit_gate;
682
683 for (;;) {
684 int ret = __ulock_wake(UL_UNFAIR_LOCK | ULF_NO_ERRNO, exit_gate, 0);
685 if (ret == 0 || ret == -ENOENT) {
686 return;
687 }
688 if (ret != -EINTR) {
689 PTHREAD_INTERNAL_CRASH(-ret, "pthread_join() wake failure");
690 }
691 }
692 }
693
694 static void
695 _pthread_dealloc_reply_port(pthread_t self)
696 {
697 mach_port_t port = _pthread_tsd_slot(self, MIG_REPLY);
698 if (port != MACH_PORT_NULL) {
699 // this will also set the TSD to MACH_PORT_NULL
700 mig_dealloc_reply_port(port);
701 }
702 }
703
704 static void
705 _pthread_dealloc_special_reply_port(pthread_t self)
706 {
707 mach_port_t port = _pthread_tsd_slot(self, MACH_SPECIAL_REPLY);
708 if (port != MACH_PORT_NULL) {
709 _pthread_tsd_slot(self, MACH_SPECIAL_REPLY) = MACH_PORT_NULL;
710 thread_destruct_special_reply_port(port, THREAD_SPECIAL_REPLY_PORT_ALL);
711 }
712 }
713
714 // Terminates the thread if called from the currently running thread.
715 OS_NORETURN OS_NOINLINE OS_NOT_TAIL_CALLED
716 static void
717 _pthread_terminate(pthread_t t, void *exit_value)
718 {
719 _pthread_introspection_thread_terminate(t);
720
721 uintptr_t freeaddr = (uintptr_t)t->freeaddr;
722 size_t freesize = t->freesize;
723 bool should_exit;
724
725 // the size of just the stack
726 size_t freesize_stack = t->freesize;
727
728 // We usually pass our structure+stack to bsdthread_terminate to free, but
729 // if we get told to keep the pthread_t structure around then we need to
730 // adjust the free size and addr in the pthread_t to just refer to the
731 // structure and not the stack. If we do end up deallocating the
732 // structure, this is useless work since no one can read the result, but we
733 // can't do it after the call to pthread_remove_thread because it isn't
734 // safe to dereference t after that.
735 if ((void*)t > t->freeaddr && (void*)t < t->freeaddr + t->freesize){
736 // Check to ensure the pthread structure itself is part of the
737 // allocation described by freeaddr/freesize, in which case we split and
738 // only deallocate the area below the pthread structure. In the event of a
739 // custom stack, the freeaddr/size will be the pthread structure itself, in
740 // which case we shouldn't free anything (the final else case).
741 freesize_stack = trunc_page((uintptr_t)t - (uintptr_t)freeaddr);
742
743 // describe just the remainder for deallocation when the pthread_t goes away
744 t->freeaddr += freesize_stack;
745 t->freesize -= freesize_stack;
746 } else if (t == main_thread()) {
747 freeaddr = t->stackaddr - pthread_get_stacksize_np(t);
748 uintptr_t stackborder = trunc_page((uintptr_t)_pthread_current_stack_address());
749 freesize_stack = stackborder - freeaddr;
750 } else {
751 freesize_stack = 0;
752 }
753
754 mach_port_t kport = _pthread_tsd_slot(t, MACH_THREAD_SELF);
755 bool keep_thread_struct = false, needs_wake = false;
756 semaphore_t custom_stack_sema = MACH_PORT_NULL;
757
758 _pthread_dealloc_special_reply_port(t);
759 _pthread_dealloc_reply_port(t);
760
761 _pthread_lock_lock(&_pthread_list_lock);
762
763 // This piece of code interacts with pthread_join. It will always:
764 // - set tl_exit_gate to MACH_PORT_DEAD (thread exited)
765 // - set tl_exit_value to the value passed to pthread_exit()
766 // - decrement _pthread_count, so that we can exit the process when all
767 // threads exited even if not all of them were joined.
768 t->tl_exit_gate = MACH_PORT_DEAD;
769 t->tl_exit_value = exit_value;
770 should_exit = (--_pthread_count <= 0);
771
772 // If we see a joiner, we prepost that the join has to succeed,
773 // and the joiner is committed to finish (even if it was canceled)
774 if (t->tl_join_ctx) {
775 custom_stack_sema = _pthread_joiner_prepost_wake(t); // unsets tl_joinable
776 needs_wake = true;
777 }
778
779 // Joinable threads that have no joiner yet are kept on the thread list
780 // so that pthread_join() can later discover the thread when it is joined,
781 // and will have to do the pthread_t cleanup.
782 if (t->tl_joinable) {
783 t->tl_joiner_cleans_up = keep_thread_struct = true;
784 } else {
785 TAILQ_REMOVE(&__pthread_head, t, tl_plist);
786 }
787
788 _pthread_lock_unlock(&_pthread_list_lock);
789
790 if (needs_wake) {
791 // When we found a waiter, we want to drop the very contended list lock
792 // before we do the syscall in _pthread_joiner_wake(). Then, we decide
793 // who gets to cleanup the pthread_t between the joiner and the exiting
794 // thread:
795 // - the joiner tries to set tl_join_ctx to NULL
796 // - the exiting thread tries to set tl_joiner_cleans_up to true
797 // Whoever does it first commits the other guy to cleanup the pthread_t
798 _pthread_joiner_wake(t);
799 _pthread_lock_lock(&_pthread_list_lock);
800 if (t->tl_join_ctx) {
801 t->tl_joiner_cleans_up = true;
802 keep_thread_struct = true;
803 }
804 _pthread_lock_unlock(&_pthread_list_lock);
805 }
806
807 //
808 // /!\ dereferencing `t` past this point is not safe /!\
809 //
810
811 if (keep_thread_struct || t == main_thread()) {
812 // Use the adjusted freesize of just the stack that we computed above.
813 freesize = freesize_stack;
814 } else {
815 _pthread_introspection_thread_destroy(t);
816 }
817
818 // Check if there is nothing to free because the thread has a custom
819 // stack allocation and is joinable.
820 if (freesize == 0) {
821 freeaddr = 0;
822 }
823 if (should_exit) {
824 exitf(0);
825 }
826 __bsdthread_terminate((void *)freeaddr, freesize, kport, custom_stack_sema);
827 PTHREAD_INTERNAL_CRASH(t, "thread didn't terminate");
828 }
829
830 OS_NORETURN
831 static void
832 _pthread_terminate_invoke(pthread_t t, void *exit_value)
833 {
834 #if PTHREAD_T_OFFSET
835 void *p = NULL;
836 // <rdar://problem/25688492> During pthread termination there is a race
837 // between pthread_join and pthread_terminate; if the joiner is responsible
838 // for cleaning up the pthread_t struct, then it may destroy some part of the
839 // stack with it on 16k OSes. So that this doesn't cause _pthread_terminate()
840 // to crash because its stack has been removed from under its feet, just make
841 // sure termination happens in a part of the stack that is not on the same
842 // page as the pthread_t.
843 if (trunc_page((uintptr_t)__builtin_frame_address(0)) ==
844 trunc_page((uintptr_t)t)) {
845 p = alloca(PTHREAD_T_OFFSET);
846 }
847 // And this __asm__ volatile is needed to stop the compiler from optimising
848 // away the alloca() completely.
849 __asm__ volatile ("" : : "r"(p) );
850 #endif
851 _pthread_terminate(t, exit_value);
852 }
853
854 #pragma mark pthread start / body
855
856 void
857 _pthread_start(pthread_t self, mach_port_t kport,
858 __unused void *(*fun)(void *), __unused void *arg,
859 __unused size_t stacksize, unsigned int pflags)
860 {
861 if (os_unlikely(pflags & PTHREAD_START_SUSPENDED)) {
862 PTHREAD_INTERNAL_CRASH(pflags,
863 "kernel without PTHREAD_START_SUSPENDED support");
864 }
865 if (os_unlikely((pflags & PTHREAD_START_TSD_BASE_SET) == 0)) {
866 PTHREAD_INTERNAL_CRASH(pflags,
867 "thread_set_tsd_base() wasn't called by the kernel");
868 }
869 PTHREAD_DEBUG_ASSERT(MACH_PORT_VALID(kport));
870 PTHREAD_DEBUG_ASSERT(_pthread_tsd_slot(self, MACH_THREAD_SELF) == kport);
871 _pthread_validate_signature(self);
872 _pthread_markcancel_if_canceled(self, kport);
873
874 _pthread_set_self_internal(self);
875 __pthread_started_thread(self);
876 _pthread_exit(self, (self->fun)(self->arg));
877 }
878
879 OS_ALWAYS_INLINE
880 static inline void
881 _pthread_struct_init(pthread_t t, const pthread_attr_t *attrs,
882 void *stackaddr, size_t stacksize, void *freeaddr, size_t freesize)
883 {
884 _pthread_init_signature(t);
885 _pthread_tsd_slot(t, PTHREAD_SELF) = t;
886 _pthread_tsd_slot(t, ERRNO) = &t->err_no;
887 if (attrs->schedset == 0) {
888 _pthread_tsd_slot(t, PTHREAD_QOS_CLASS) = attrs->qosclass;
889 } else {
890 _pthread_tsd_slot(t, PTHREAD_QOS_CLASS) =
891 _pthread_unspecified_priority();
892 }
893 _pthread_tsd_slot(t, PTR_MUNGE) = _pthread_ptr_munge_token;
894 t->tl_has_custom_stack = (attrs->stackaddr != NULL);
895
896 _pthread_lock_init(&t->lock);
897
898 t->stackaddr = stackaddr;
899 t->stackbottom = stackaddr - stacksize;
900 t->freeaddr = freeaddr;
901 t->freesize = freesize;
902
903 t->guardsize = _pthread_attr_guardsize(attrs);
904 t->tl_joinable = (attrs->detached == PTHREAD_CREATE_JOINABLE);
905 t->inherit = attrs->inherit;
906 t->tl_policy = attrs->policy;
907 t->schedset = attrs->schedset;
908 _pthread_attr_get_schedparam(attrs, &t->tl_param);
909 t->cancel_state = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
910 }
911
912 #pragma mark pthread public interface
913
914 /* Non portable public api to know whether this process has(had) atleast one thread
915 * apart from main thread. There could be race if there is a thread in the process of
916 * creation at the time of call . It does not tell whether there are more than one thread
917 * at this point of time.
918 */
919 int
920 pthread_is_threaded_np(void)
921 {
922 return __is_threaded;
923 }
924
925 mach_port_t
926 pthread_mach_thread_np(pthread_t t)
927 {
928 mach_port_t kport = MACH_PORT_NULL;
929 (void)_pthread_is_valid(t, &kport);
930 return kport;
931 }
932
933 pthread_t
934 pthread_from_mach_thread_np(mach_port_t kernel_thread)
935 {
936 pthread_t p = NULL;
937
938 /* No need to wait as mach port is already known */
939 _pthread_lock_lock(&_pthread_list_lock);
940
941 TAILQ_FOREACH(p, &__pthread_head, tl_plist) {
942 if (_pthread_tsd_slot(p, MACH_THREAD_SELF) == kernel_thread) {
943 break;
944 }
945 }
946
947 _pthread_lock_unlock(&_pthread_list_lock);
948
949 return p;
950 }
951
952 size_t
953 pthread_get_stacksize_np(pthread_t t)
954 {
955 size_t size = 0;
956
957 if (t == NULL) {
958 return ESRCH; // XXX bug?
959 }
960
961 #if TARGET_OS_OSX
962 // The default rlimit based allocations will be provided with a stacksize
963 // of the current limit and a freesize of the max. However, custom
964 // allocations will just have the guard page to free. If we aren't in the
965 // latter case, call into rlimit to determine the current stack size. In
966 // the event that the current limit == max limit then we'll fall down the
967 // fast path, but since it's unlikely that the limit is going to be lowered
968 // after it's been change to the max, we should be fine.
969 //
970 // Of course, on arm rlim_cur == rlim_max and there's only the one guard
971 // page. So, we can skip all this there.
972 if (t == main_thread()) {
973 size_t stacksize = t->stackaddr - t->stackbottom;
974
975 if (stacksize + vm_page_size != t->freesize) {
976 // We want to call getrlimit() just once, as it's relatively
977 // expensive
978 static size_t rlimit_stack;
979
980 if (rlimit_stack == 0) {
981 struct rlimit limit;
982 int ret = getrlimit(RLIMIT_STACK, &limit);
983
984 if (ret == 0) {
985 rlimit_stack = (size_t) limit.rlim_cur;
986 }
987 }
988
989 if (rlimit_stack == 0 || rlimit_stack > t->freesize) {
990 return stacksize;
991 } else {
992 return round_page(rlimit_stack);
993 }
994 }
995 }
996 #endif /* TARGET_OS_OSX */
997
998 if (t == pthread_self() || t == main_thread()) {
999 size = t->stackaddr - t->stackbottom;;
1000 goto out;
1001 }
1002
1003 if (_pthread_validate_thread_and_list_lock(t)) {
1004 size = t->stackaddr - t->stackbottom;;
1005 _pthread_lock_unlock(&_pthread_list_lock);
1006 }
1007
1008 out:
1009 // <rdar://problem/42588315> binary compatibility issues force us to return
1010 // DEFAULT_STACK_SIZE here when we do not know the size of the stack
1011 return size ? size : DEFAULT_STACK_SIZE;
1012 }
1013
1014 void *
1015 pthread_get_stackaddr_np(pthread_t t)
1016 {
1017 // since the main thread will not get de-allocated from underneath us
1018 if (t == pthread_self() || t == main_thread()) {
1019 return t->stackaddr;
1020 }
1021
1022 if (!_pthread_validate_thread_and_list_lock(t)) {
1023 return (void *)(uintptr_t)ESRCH; // XXX bug?
1024 }
1025
1026 void *addr = t->stackaddr;
1027 _pthread_lock_unlock(&_pthread_list_lock);
1028 return addr;
1029 }
1030
1031 pthread_t
1032 pthread_main_thread_np(void)
1033 {
1034 return main_thread();
1035 }
1036
1037 /* returns non-zero if the current thread is the main thread */
1038 int
1039 pthread_main_np(void)
1040 {
1041 return pthread_self() == main_thread();
1042 }
1043
1044 static int
1045 _pthread_threadid_slow(pthread_t thread, uint64_t *thread_id)
1046 {
1047 unsigned int info_count = THREAD_IDENTIFIER_INFO_COUNT;
1048 mach_port_t thport = _pthread_tsd_slot(thread, MACH_THREAD_SELF);
1049 struct thread_identifier_info info;
1050 kern_return_t kr;
1051
1052 kr = thread_info(thport, THREAD_IDENTIFIER_INFO,
1053 (thread_info_t)&info, &info_count);
1054 if (kr == KERN_SUCCESS && info.thread_id) {
1055 *thread_id = info.thread_id;
1056 #if __LP64__
1057 os_atomic_store(&thread->thread_id, info.thread_id, relaxed);
1058 #else
1059 os_atomic_store_wide(&thread->thread_id, info.thread_id, relaxed);
1060 #endif
1061 return 0;
1062 }
1063 return EINVAL;
1064 }
1065
1066 /*
1067 * if we are passed in a pthread_t that is NULL, then we return the current
1068 * thread's thread_id. So folks don't have to call pthread_self, in addition to
1069 * us doing it, if they just want their thread_id.
1070 */
1071 int
1072 pthread_threadid_np(pthread_t thread, uint64_t *thread_id)
1073 {
1074 int res = 0;
1075 pthread_t self = pthread_self();
1076
1077 if (thread_id == NULL) {
1078 return EINVAL;
1079 }
1080
1081 if (thread == NULL || thread == self) {
1082 *thread_id = self->thread_id;
1083 } else if (!_pthread_validate_thread_and_list_lock(thread)) {
1084 res = ESRCH;
1085 } else {
1086 #if __LP64__
1087 *thread_id = os_atomic_load(&thread->thread_id, relaxed);
1088 #else
1089 *thread_id = os_atomic_load_wide(&thread->thread_id, relaxed);
1090 #endif
1091 if (os_unlikely(*thread_id == 0)) {
1092 // there is a race at init because the thread sets its own TID.
1093 // correct this by asking mach
1094 res = _pthread_threadid_slow(thread, thread_id);
1095 }
1096 _pthread_lock_unlock(&_pthread_list_lock);
1097 }
1098 return res;
1099 }
1100
1101 int
1102 pthread_cpu_number_np(size_t *cpu_id)
1103 {
1104 if (cpu_id == NULL) {
1105 errno = EINVAL;
1106 return errno;
1107 }
1108
1109 *cpu_id = _os_cpu_number();
1110 return 0;
1111 }
1112
1113 int
1114 pthread_getname_np(pthread_t thread, char *threadname, size_t len)
1115 {
1116 if (thread == pthread_self()) {
1117 strlcpy(threadname, thread->pthread_name, len);
1118 return 0;
1119 }
1120
1121 if (!_pthread_validate_thread_and_list_lock(thread)) {
1122 return ESRCH;
1123 }
1124
1125 strlcpy(threadname, thread->pthread_name, len);
1126 _pthread_lock_unlock(&_pthread_list_lock);
1127 return 0;
1128 }
1129
1130 int
1131 pthread_setname_np(const char *name)
1132 {
1133 int res;
1134 pthread_t self = pthread_self();
1135
1136 size_t len = 0;
1137 if (name != NULL) {
1138 len = strlen(name);
1139 }
1140
1141 _pthread_validate_signature(self);
1142
1143 res = __proc_info(5, getpid(), 2, (uint64_t)0, (void*)name, (int)len);
1144 if (res == 0) {
1145 if (len > 0) {
1146 strlcpy(self->pthread_name, name, MAXTHREADNAMESIZE);
1147 } else {
1148 bzero(self->pthread_name, MAXTHREADNAMESIZE);
1149 }
1150 }
1151 return res;
1152
1153 }
1154
1155 void
1156 pthread_jit_write_protect_np(int enable)
1157 {
1158 if (!os_thread_self_restrict_rwx_is_supported()) {
1159 return;
1160 }
1161
1162 if (enable) {
1163 os_thread_self_restrict_rwx_to_rx();
1164 } else {
1165 os_thread_self_restrict_rwx_to_rw();
1166 }
1167 }
1168
1169 int pthread_jit_write_protect_supported_np()
1170 {
1171 return os_thread_self_restrict_rwx_is_supported();
1172 }
1173
1174 OS_ALWAYS_INLINE
1175 static inline void
1176 __pthread_add_thread(pthread_t t, mach_port_t self, bool from_mach_thread)
1177 {
1178 _pthread_lock_lock(&_pthread_list_lock, self);
1179 TAILQ_INSERT_TAIL(&__pthread_head, t, tl_plist);
1180 _pthread_count++;
1181 _pthread_lock_unlock(&_pthread_list_lock, self);
1182
1183 if (!from_mach_thread) {
1184 // PR-26275485: Mach threads will likely crash trying to run
1185 // introspection code. Since the fall out from the introspection
1186 // code not seeing the injected thread is likely less than crashing
1187 // in the introspection code, just don't make the call.
1188 _pthread_introspection_thread_create(t);
1189 }
1190 }
1191
1192 OS_ALWAYS_INLINE
1193 static inline void
1194 __pthread_undo_add_thread(pthread_t t, mach_port_t self)
1195 {
1196 _pthread_lock_lock(&_pthread_list_lock, self);
1197 TAILQ_REMOVE(&__pthread_head, t, tl_plist);
1198 _pthread_count--;
1199 _pthread_lock_unlock(&_pthread_list_lock, self);
1200 }
1201
1202 OS_ALWAYS_INLINE
1203 static inline void
1204 __pthread_started_thread(pthread_t t)
1205 {
1206 mach_port_t kport = _pthread_tsd_slot(t, MACH_THREAD_SELF);
1207 if (os_unlikely(!MACH_PORT_VALID(kport))) {
1208 PTHREAD_CLIENT_CRASH(kport,
1209 "Unable to allocate thread port, possible port leak");
1210 }
1211 _pthread_introspection_thread_start(t);
1212 }
1213
1214 #define _PTHREAD_CREATE_NONE 0x0
1215 #define _PTHREAD_CREATE_FROM_MACH_THREAD 0x1
1216 #define _PTHREAD_CREATE_SUSPENDED 0x2
1217
1218 static int
1219 _pthread_create(pthread_t *thread, const pthread_attr_t *attrs,
1220 void *(*start_routine)(void *), void *arg, unsigned int create_flags)
1221 {
1222 pthread_t t = NULL;
1223 void *stack = NULL;
1224 bool from_mach_thread = (create_flags & _PTHREAD_CREATE_FROM_MACH_THREAD);
1225 mach_port_t self_kport;
1226 int rc = 0;
1227
1228 if (attrs == NULL) {
1229 attrs = &_pthread_attr_default;
1230 } else if (attrs->sig != _PTHREAD_ATTR_SIG) {
1231 return EINVAL;
1232 }
1233
1234 unsigned int flags = PTHREAD_START_CUSTOM;
1235 if (attrs->schedset != 0) {
1236 struct sched_param p;
1237 _pthread_attr_get_schedparam(attrs, &p);
1238 flags |= PTHREAD_START_SETSCHED;
1239 flags |= ((attrs->policy & PTHREAD_START_POLICY_MASK) << PTHREAD_START_POLICY_BITSHIFT);
1240 flags |= (p.sched_priority & PTHREAD_START_IMPORTANCE_MASK);
1241 } else if (attrs->qosclass != 0) {
1242 flags |= PTHREAD_START_QOSCLASS;
1243 flags |= (attrs->qosclass & PTHREAD_START_QOSCLASS_MASK);
1244 }
1245 if (create_flags & _PTHREAD_CREATE_SUSPENDED) {
1246 flags |= PTHREAD_START_SUSPENDED;
1247 }
1248
1249 __is_threaded = 1;
1250
1251 t = _pthread_allocate(attrs, &stack, from_mach_thread);
1252 if (t == NULL) {
1253 return EAGAIN;
1254 }
1255
1256 if (os_unlikely(from_mach_thread)) {
1257 self_kport = mach_thread_self();
1258 } else {
1259 self_kport = _pthread_mach_thread_self_direct();
1260 }
1261
1262 t->arg = arg;
1263 t->fun = start_routine;
1264 __pthread_add_thread(t, self_kport, from_mach_thread);
1265
1266 if (__bsdthread_create(start_routine, arg, stack, t, flags) ==
1267 (pthread_t)-1) {
1268 if (errno == EMFILE) {
1269 PTHREAD_CLIENT_CRASH(0,
1270 "Unable to allocate thread port, possible port leak");
1271 }
1272 __pthread_undo_add_thread(t, self_kport);
1273 _pthread_deallocate(t, from_mach_thread);
1274 t = NULL;
1275 rc = EAGAIN;
1276 }
1277 if (from_mach_thread) {
1278 mach_port_deallocate(mach_task_self(), self_kport);
1279 }
1280
1281 // n.b. if a thread is created detached and exits, t will be invalid
1282 *thread = t;
1283 return rc;
1284 }
1285
1286 int
1287 pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1288 void *(*start_routine)(void *), void *arg)
1289 {
1290 unsigned int flags = _PTHREAD_CREATE_NONE;
1291 return _pthread_create(thread, attr, start_routine, arg, flags);
1292 }
1293
1294 int
1295 pthread_create_from_mach_thread(pthread_t *thread, const pthread_attr_t *attr,
1296 void *(*start_routine)(void *), void *arg)
1297 {
1298 unsigned int flags = _PTHREAD_CREATE_FROM_MACH_THREAD;
1299 return _pthread_create(thread, attr, start_routine, arg, flags);
1300 }
1301
1302 int
1303 pthread_create_suspended_np(pthread_t *thread, const pthread_attr_t *attr,
1304 void *(*start_routine)(void *), void *arg)
1305 {
1306 unsigned int flags = _PTHREAD_CREATE_SUSPENDED;
1307 return _pthread_create(thread, attr, start_routine, arg, flags);
1308 }
1309
1310 int
1311 pthread_detach(pthread_t thread)
1312 {
1313 int res = 0;
1314 bool join = false, wake = false;
1315
1316 if (!_pthread_validate_thread_and_list_lock(thread)) {
1317 return ESRCH;
1318 }
1319
1320 if (!thread->tl_joinable) {
1321 res = EINVAL;
1322 } else if (thread->tl_exit_gate == MACH_PORT_DEAD) {
1323 // Join the thread if it's already exited.
1324 join = true;
1325 } else {
1326 thread->tl_joinable = false; // _pthread_joiner_prepost_wake uses this
1327 if (thread->tl_join_ctx) {
1328 (void)_pthread_joiner_prepost_wake(thread);
1329 wake = true;
1330 }
1331 }
1332 _pthread_lock_unlock(&_pthread_list_lock);
1333
1334 if (join) {
1335 pthread_join(thread, NULL);
1336 } else if (wake) {
1337 _pthread_joiner_wake(thread);
1338 }
1339 return res;
1340 }
1341
1342 int
1343 pthread_kill(pthread_t th, int sig)
1344 {
1345 if (sig < 0 || sig > NSIG) {
1346 return EINVAL;
1347 }
1348
1349 mach_port_t kport = MACH_PORT_NULL;
1350 {
1351 if (!_pthread_is_valid(th, &kport)) {
1352 return ESRCH;
1353 }
1354 }
1355
1356 int ret = __pthread_kill(kport, sig);
1357
1358 if (ret == -1) {
1359 ret = errno;
1360 }
1361 return ret;
1362 }
1363
1364 int
1365 __pthread_workqueue_setkill(int enable)
1366 {
1367 {
1368 return __bsdthread_ctl(BSDTHREAD_CTL_WORKQ_ALLOW_KILL, enable, 0, 0);
1369 }
1370 }
1371
1372 /*
1373 * Terminate a thread.
1374 */
1375
1376 OS_NORETURN
1377 static void
1378 _pthread_exit(pthread_t self, void *exit_value)
1379 {
1380 struct __darwin_pthread_handler_rec *handler;
1381
1382 // Disable signal delivery while we clean up
1383 __disable_threadsignal(1);
1384
1385 // Set cancel state to disable and type to deferred
1386 _pthread_setcancelstate_exit(self, exit_value);
1387
1388 while ((handler = self->__cleanup_stack) != 0) {
1389 (handler->__routine)(handler->__arg);
1390 self->__cleanup_stack = handler->__next;
1391 }
1392 _pthread_tsd_cleanup(self);
1393
1394 // Clear per-thread semaphore cache
1395 os_put_cached_semaphore(SEMAPHORE_NULL);
1396
1397 _pthread_terminate_invoke(self, exit_value);
1398 }
1399
1400 void
1401 pthread_exit(void *exit_value)
1402 {
1403 pthread_t self = pthread_self();
1404 if (os_unlikely(self->wqthread)) {
1405 PTHREAD_CLIENT_CRASH(0, "pthread_exit() called from a thread "
1406 "not created by pthread_create()");
1407 }
1408 _pthread_validate_signature(self);
1409 _pthread_exit(self, exit_value);
1410 }
1411
1412 int
1413 pthread_self_is_exiting_np(void)
1414 {
1415 return (os_atomic_load(&pthread_self()->cancel_state, relaxed) &
1416 _PTHREAD_CANCEL_EXITING) != 0;
1417 }
1418
1419 int
1420 pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param)
1421 {
1422 if (!_pthread_validate_thread_and_list_lock(thread)) {
1423 return ESRCH;
1424 }
1425
1426 if (policy) *policy = thread->tl_policy;
1427 if (param) *param = thread->tl_param;
1428 _pthread_lock_unlock(&_pthread_list_lock);
1429 return 0;
1430 }
1431
1432 OS_ALWAYS_INLINE
1433 static inline int
1434 pthread_setschedparam_internal(pthread_t thread, mach_port_t kport, int policy,
1435 const struct sched_param *param)
1436 {
1437 policy_base_data_t bases;
1438 policy_base_t base;
1439 mach_msg_type_number_t count;
1440 kern_return_t ret;
1441
1442 if (os_unlikely(thread->wqthread)) {
1443 return ENOTSUP;
1444 }
1445
1446 switch (policy) {
1447 case SCHED_OTHER:
1448 bases.ts.base_priority = param->sched_priority;
1449 base = (policy_base_t)&bases.ts;
1450 count = POLICY_TIMESHARE_BASE_COUNT;
1451 break;
1452 case SCHED_FIFO:
1453 bases.fifo.base_priority = param->sched_priority;
1454 base = (policy_base_t)&bases.fifo;
1455 count = POLICY_FIFO_BASE_COUNT;
1456 break;
1457 case SCHED_RR:
1458 bases.rr.base_priority = param->sched_priority;
1459 /* quantum isn't public yet */
1460 bases.rr.quantum = param->quantum;
1461 base = (policy_base_t)&bases.rr;
1462 count = POLICY_RR_BASE_COUNT;
1463 break;
1464 default:
1465 return EINVAL;
1466 }
1467 ret = thread_policy(kport, policy, base, count, TRUE);
1468 return (ret != KERN_SUCCESS) ? EINVAL : 0;
1469 }
1470
1471 int
1472 pthread_setschedparam(pthread_t t, int policy, const struct sched_param *param)
1473 {
1474 mach_port_t kport = MACH_PORT_NULL;
1475 int bypass = 1;
1476
1477 // since the main thread will not get de-allocated from underneath us
1478 if (t == pthread_self() || t == main_thread()) {
1479 _pthread_validate_signature(t);
1480 kport = _pthread_tsd_slot(t, MACH_THREAD_SELF);
1481 } else {
1482 bypass = 0;
1483 if (!_pthread_is_valid(t, &kport)) {
1484 return ESRCH;
1485 }
1486 }
1487
1488 int res = pthread_setschedparam_internal(t, kport, policy, param);
1489 if (res) return res;
1490
1491 if (bypass) {
1492 _pthread_lock_lock(&_pthread_list_lock);
1493 } else if (!_pthread_validate_thread_and_list_lock(t)) {
1494 // Ensure the thread is still valid.
1495 return ESRCH;
1496 }
1497
1498 t->tl_policy = policy;
1499 t->tl_param = *param;
1500 _pthread_lock_unlock(&_pthread_list_lock);
1501 return 0;
1502 }
1503
1504 int
1505 sched_get_priority_min(int policy)
1506 {
1507 return default_priority - 16;
1508 }
1509
1510 int
1511 sched_get_priority_max(int policy)
1512 {
1513 return default_priority + 16;
1514 }
1515
1516 int
1517 pthread_equal(pthread_t t1, pthread_t t2)
1518 {
1519 return (t1 == t2);
1520 }
1521
1522 OS_NOINLINE
1523 void
1524 _pthread_set_self(pthread_t p)
1525 {
1526 #if VARIANT_DYLD
1527 if (os_likely(!p)) {
1528 return _pthread_set_self_dyld();
1529 }
1530 #endif // VARIANT_DYLD
1531 _pthread_set_self_internal(p);
1532 _thread_set_tsd_base(&p->tsd[0]);
1533 }
1534
1535 #if VARIANT_DYLD
1536 // _pthread_set_self_dyld is noinline+noexport to allow the option for
1537 // static libsyscall to adopt this as the entry point from mach_init if
1538 // desired
1539 OS_NOINLINE
1540 static void
1541 _pthread_set_self_dyld(void)
1542 {
1543 pthread_t p = main_thread();
1544 p->thread_id = __thread_selfid();
1545
1546 if (os_unlikely(p->thread_id == -1ull)) {
1547 PTHREAD_INTERNAL_CRASH(0, "failed to set thread_id");
1548 }
1549
1550 // <rdar://problem/40930651> pthread self and the errno address are the
1551 // bare minimium TSD setup that dyld needs to actually function. Without
1552 // this, TSD access will fail and crash if it uses bits of Libc prior to
1553 // library initialization. __pthread_init will finish the initialization
1554 // during library init.
1555 _pthread_tsd_slot(p, PTHREAD_SELF) = p;
1556 _pthread_tsd_slot(p, ERRNO) = &p->err_no;
1557 _thread_set_tsd_base(&p->tsd[0]);
1558 }
1559 #endif // VARIANT_DYLD
1560
1561 OS_ALWAYS_INLINE
1562 static inline void
1563 _pthread_set_self_internal(pthread_t p)
1564 {
1565 #if __LP64__
1566 os_atomic_store(&p->thread_id, __thread_selfid(), relaxed);
1567 #else
1568 os_atomic_store_wide(&p->thread_id, __thread_selfid(), relaxed);
1569 #endif
1570
1571 if (os_unlikely(p->thread_id == -1ull)) {
1572 PTHREAD_INTERNAL_CRASH(0, "failed to set thread_id");
1573 }
1574 }
1575
1576 // <rdar://problem/28984807> pthread_once should have an acquire barrier
1577 OS_ALWAYS_INLINE
1578 static inline void
1579 _os_once_acquire(os_once_t *predicate, void *context, os_function_t function)
1580 {
1581 if (OS_EXPECT(os_atomic_load(predicate, acquire), ~0l) != ~0l) {
1582 _os_once(predicate, context, function);
1583 OS_COMPILER_CAN_ASSUME(*predicate == ~0l);
1584 }
1585 }
1586
1587 struct _pthread_once_context {
1588 pthread_once_t *pthread_once;
1589 void (*routine)(void);
1590 };
1591
1592 static void
1593 __pthread_once_handler(void *context)
1594 {
1595 struct _pthread_once_context *ctx = context;
1596 pthread_cleanup_push((void*)__os_once_reset, &ctx->pthread_once->once);
1597 ctx->routine();
1598 pthread_cleanup_pop(0);
1599 ctx->pthread_once->sig = _PTHREAD_ONCE_SIG;
1600 }
1601
1602 int
1603 pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
1604 {
1605 struct _pthread_once_context ctx = { once_control, init_routine };
1606 do {
1607 _os_once_acquire(&once_control->once, &ctx, __pthread_once_handler);
1608 } while (once_control->sig == _PTHREAD_ONCE_SIG_init);
1609 return 0;
1610 }
1611
1612 int
1613 pthread_getconcurrency(void)
1614 {
1615 return pthread_concurrency;
1616 }
1617
1618 int
1619 pthread_setconcurrency(int new_level)
1620 {
1621 if (new_level < 0) {
1622 return EINVAL;
1623 }
1624 pthread_concurrency = new_level;
1625 return 0;
1626 }
1627
1628 /*
1629 * Perform package initialization - called automatically when application starts
1630 */
1631
1632 #if !VARIANT_DYLD
1633 static unsigned long
1634 _pthread_strtoul(const char *p, const char **endptr, int base)
1635 {
1636 uintptr_t val = 0;
1637
1638 // Expect hex string starting with "0x"
1639 if ((base == 16 || base == 0) && p && p[0] == '0' && p[1] == 'x') {
1640 p += 2;
1641 while (1) {
1642 char c = *p;
1643 if ('0' <= c && c <= '9') {
1644 val = (val << 4) + (c - '0');
1645 } else if ('a' <= c && c <= 'f') {
1646 val = (val << 4) + (c - 'a' + 10);
1647 } else if ('A' <= c && c <= 'F') {
1648 val = (val << 4) + (c - 'A' + 10);
1649 } else {
1650 break;
1651 }
1652 ++p;
1653 }
1654 }
1655
1656 *endptr = (char *)p;
1657 return val;
1658 }
1659
1660 static int
1661 parse_main_stack_params(const char *apple[],
1662 void **stackaddr,
1663 size_t *stacksize,
1664 void **allocaddr,
1665 size_t *allocsize)
1666 {
1667 const char *p = _simple_getenv(apple, "main_stack");
1668 if (!p) return 0;
1669
1670 int ret = 0;
1671 const char *s = p;
1672
1673 *stackaddr = _pthread_strtoul(s, &s, 16);
1674 if (*s != ',') goto out;
1675
1676 *stacksize = _pthread_strtoul(s + 1, &s, 16);
1677 if (*s != ',') goto out;
1678
1679 *allocaddr = _pthread_strtoul(s + 1, &s, 16);
1680 if (*s != ',') goto out;
1681
1682 *allocsize = _pthread_strtoul(s + 1, &s, 16);
1683 if (*s != ',' && *s != 0) goto out;
1684
1685 ret = 1;
1686 out:
1687 bzero((char *)p, strlen(p));
1688 return ret;
1689 }
1690
1691 static void
1692 parse_ptr_munge_params(const char *envp[], const char *apple[])
1693 {
1694 const char *p, *s;
1695 uintptr_t token = 0;
1696 p = _simple_getenv(apple, "ptr_munge");
1697 if (p) {
1698 token = _pthread_strtoul(p, &s, 16);
1699 bzero((char *)p, strlen(p));
1700 }
1701 /*
1702 * In DEBUG we allow the environment variable to override the kernel
1703 * security setting, including setting it to 0 which is helpful during
1704 * debugging sessions.
1705 *
1706 * For other cases, the token must be set by the kernel or the environment
1707 * variable to a non 0 value.
1708 */
1709 #if !DEBUG
1710 if (!token) {
1711 #endif
1712 p = _simple_getenv(envp, "PTHREAD_PTR_MUNGE_TOKEN");
1713 if (p) {
1714 uintptr_t t = _pthread_strtoul(p, &s, 16);
1715 if (t) token = t;
1716 }
1717 #if !DEBUG
1718 }
1719
1720 if (!token) {
1721 PTHREAD_INTERNAL_CRASH(token, "Token from the kernel is 0");
1722 }
1723 #endif // !DEBUG
1724
1725 _pthread_ptr_munge_token = token;
1726 // we need to refresh the main thread signature now that we changed
1727 // the munge token. We need to do it while TSAN will not look at it
1728 _pthread_init_signature(_main_thread_ptr);
1729 }
1730
1731 int
1732 __pthread_init(const struct _libpthread_functions *pthread_funcs,
1733 const char *envp[], const char *apple[],
1734 const struct ProgramVars *vars __unused)
1735 {
1736 // Save our provided pushed-down functions
1737 if (pthread_funcs) {
1738 exitf = pthread_funcs->exit;
1739
1740 if (pthread_funcs->version >= 2) {
1741 _pthread_malloc = pthread_funcs->malloc;
1742 _pthread_free = pthread_funcs->free;
1743 }
1744 }
1745
1746 // libpthread.a in dyld "owns" the main thread structure itself and sets
1747 // up the tsd to point to it. So take the pthread_self() from there
1748 // and make it our main thread point.
1749 pthread_t thread = _pthread_self_direct();
1750 if (os_unlikely(thread == NULL)) {
1751 PTHREAD_INTERNAL_CRASH(0, "PTHREAD_SELF TSD not initialized");
1752 }
1753 _main_thread_ptr = thread;
1754 // this needs to be done early so that pthread_self() works in TSAN
1755 _pthread_init_signature(thread);
1756
1757 //
1758 // Get host information
1759 //
1760
1761 kern_return_t kr;
1762 host_flavor_t flavor = HOST_PRIORITY_INFO;
1763 mach_msg_type_number_t count = HOST_PRIORITY_INFO_COUNT;
1764 host_priority_info_data_t priority_info;
1765 host_t host = mach_host_self();
1766 kr = host_info(host, flavor, (host_info_t)&priority_info, &count);
1767 if (kr != KERN_SUCCESS) {
1768 PTHREAD_INTERNAL_CRASH(kr, "host_info() failed");
1769 } else {
1770 default_priority = (uint8_t)priority_info.user_priority;
1771 min_priority = (uint8_t)priority_info.minimum_priority;
1772 max_priority = (uint8_t)priority_info.maximum_priority;
1773 }
1774 mach_port_deallocate(mach_task_self(), host);
1775
1776 //
1777 // Set up the main thread structure
1778 //
1779
1780 // Get the address and size of the main thread's stack from the kernel.
1781 void *stackaddr = 0;
1782 size_t stacksize = 0;
1783 void *allocaddr = 0;
1784 size_t allocsize = 0;
1785 if (!parse_main_stack_params(apple, &stackaddr, &stacksize, &allocaddr, &allocsize) ||
1786 stackaddr == NULL || stacksize == 0) {
1787 // Fall back to previous bevhaior.
1788 size_t len = sizeof(stackaddr);
1789 int mib[] = { CTL_KERN, KERN_USRSTACK };
1790 if (__sysctl(mib, 2, &stackaddr, &len, NULL, 0) != 0) {
1791 #if defined(__LP64__)
1792 stackaddr = (void *)USRSTACK64;
1793 #else
1794 stackaddr = (void *)USRSTACK;
1795 #endif
1796 }
1797 stacksize = DFLSSIZ;
1798 allocaddr = 0;
1799 allocsize = 0;
1800 }
1801
1802 // Initialize random ptr_munge token from the kernel.
1803 parse_ptr_munge_params(envp, apple);
1804
1805 PTHREAD_DEBUG_ASSERT(_pthread_attr_default.qosclass ==
1806 _pthread_default_priority(0));
1807 _pthread_struct_init(thread, &_pthread_attr_default,
1808 stackaddr, stacksize, allocaddr, allocsize);
1809 thread->tl_joinable = true;
1810
1811 // Finish initialization with common code that is reinvoked on the
1812 // child side of a fork.
1813
1814 // Finishes initialization of main thread attributes.
1815 // Initializes the thread list and add the main thread.
1816 // Calls _pthread_set_self() to prepare the main thread for execution.
1817 _pthread_main_thread_init(thread);
1818
1819 struct _pthread_registration_data registration_data;
1820 // Set up kernel entry points with __bsdthread_register.
1821 _pthread_bsdthread_init(&registration_data);
1822
1823 // Have pthread_key and pthread_mutex do their init envvar checks.
1824 _pthread_key_global_init(envp);
1825 _pthread_mutex_global_init(envp, &registration_data);
1826
1827 #if PTHREAD_DEBUG_LOG
1828 _SIMPLE_STRING path = _simple_salloc();
1829 _simple_sprintf(path, "/var/tmp/libpthread.%d.log", getpid());
1830 _pthread_debuglog = open(_simple_string(path),
1831 O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0666);
1832 _simple_sfree(path);
1833 _pthread_debugstart = mach_absolute_time();
1834 #endif
1835
1836 return 0;
1837 }
1838 #endif // !VARIANT_DYLD
1839
1840 void
1841 _pthread_main_thread_init(pthread_t p)
1842 {
1843 TAILQ_INIT(&__pthread_head);
1844 _pthread_lock_init(&_pthread_list_lock);
1845 _pthread_lock_init(&p->lock);
1846 p->__cleanup_stack = NULL;
1847 p->tl_join_ctx = NULL;
1848 p->tl_exit_gate = MACH_PORT_NULL;
1849 _pthread_tsd_slot(p, MACH_THREAD_SELF) = mach_thread_self();
1850 _pthread_tsd_slot(p, MIG_REPLY) = mach_reply_port();
1851 _pthread_tsd_slot(p, MACH_SPECIAL_REPLY) = MACH_PORT_NULL;
1852 _pthread_tsd_slot(p, SEMAPHORE_CACHE) = SEMAPHORE_NULL;
1853
1854 // Initialize the list of threads with the new main thread.
1855 TAILQ_INSERT_HEAD(&__pthread_head, p, tl_plist);
1856 _pthread_count = 1;
1857
1858 _pthread_introspection_thread_start(p);
1859 }
1860
1861 void
1862 _pthread_main_thread_postfork_init(pthread_t p)
1863 {
1864 _pthread_main_thread_init(p);
1865 _pthread_set_self_internal(p);
1866 }
1867
1868 int
1869 sched_yield(void)
1870 {
1871 swtch_pri(0);
1872 return 0;
1873 }
1874
1875 // Libsystem knows about this symbol and exports it to libsyscall
1876 int
1877 pthread_current_stack_contains_np(const void *addr, size_t length)
1878 {
1879 uintptr_t begin = (uintptr_t) addr, end;
1880 uintptr_t stack_base = (uintptr_t) _pthread_self_direct()->stackbottom;
1881 uintptr_t stack_top = (uintptr_t) _pthread_self_direct()->stackaddr;
1882
1883 if (stack_base == stack_top) {
1884 return -ENOTSUP;
1885 }
1886
1887 if (__builtin_add_overflow(begin, length, &end)) {
1888 return -EINVAL;
1889 }
1890
1891 return stack_base <= begin && end <= stack_top;
1892 }
1893
1894 // Libsystem knows about this symbol and exports it to libsyscall
1895
1896 void
1897 _pthread_clear_qos_tsd(mach_port_t port)
1898 {
1899 pthread_priority_t pp = _pthread_unspecified_priority();
1900
1901 if (port == MACH_PORT_NULL || _pthread_mach_thread_self_direct() == port) {
1902 /* Clear the current thread's TSD, that can be done inline. */
1903 _pthread_setspecific_direct(_PTHREAD_TSD_SLOT_PTHREAD_QOS_CLASS, pp);
1904 } else {
1905 pthread_t p;
1906
1907 _pthread_lock_lock(&_pthread_list_lock);
1908
1909 TAILQ_FOREACH(p, &__pthread_head, tl_plist) {
1910 mach_port_t kp = _pthread_tsd_slot(p, MACH_THREAD_SELF);
1911 if (port == kp) {
1912 _pthread_tsd_slot(p, PTHREAD_QOS_CLASS) = pp;
1913 break;
1914 }
1915 }
1916
1917 _pthread_lock_unlock(&_pthread_list_lock);
1918 }
1919 }
1920
1921 #pragma mark pthread/stack_np.h public interface
1922
1923 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__)
1924 #if __ARM64_ARCH_8_32__
1925 /*
1926 * arm64_32 uses 64-bit sizes for the frame pointer and
1927 * return address of a stack frame.
1928 */
1929 typedef uint64_t frame_data_addr_t;
1930 #else
1931 typedef uintptr_t frame_data_addr_t;
1932 #endif
1933
1934 struct frame_data {
1935 frame_data_addr_t frame_addr_next;
1936 frame_data_addr_t ret_addr;
1937 };
1938 #else
1939 #error ********** Unimplemented architecture
1940 #endif
1941
1942 uintptr_t
1943 pthread_stack_frame_decode_np(uintptr_t frame_addr, uintptr_t *return_addr)
1944 {
1945 struct frame_data *frame = (struct frame_data *)frame_addr;
1946
1947 if (return_addr) {
1948 #if __has_feature(ptrauth_calls)
1949 *return_addr = (uintptr_t)ptrauth_strip((void *)frame->ret_addr,
1950 ptrauth_key_return_address);
1951 #else
1952 *return_addr = (uintptr_t)frame->ret_addr;
1953 #endif /* __has_feature(ptrauth_calls) */
1954 }
1955
1956 #if __has_feature(ptrauth_calls)
1957 return (uintptr_t)ptrauth_strip((void *)frame->frame_addr_next,
1958 ptrauth_key_frame_pointer);
1959 #endif /* __has_feature(ptrauth_calls) */
1960 return (uintptr_t)frame->frame_addr_next;
1961 }
1962
1963 #pragma mark pthread workqueue support routines
1964
1965 void
1966 _pthread_bsdthread_init(struct _pthread_registration_data *data)
1967 {
1968 bzero(data, sizeof(*data));
1969 data->version = sizeof(struct _pthread_registration_data);
1970 data->dispatch_queue_offset = __PTK_LIBDISPATCH_KEY0 * sizeof(void *);
1971 data->return_to_kernel_offset = __TSD_RETURN_TO_KERNEL * sizeof(void *);
1972 data->tsd_offset = offsetof(struct pthread_s, tsd);
1973 data->mach_thread_self_offset = __TSD_MACH_THREAD_SELF * sizeof(void *);
1974 data->joinable_offset_bits = CHAR_BIT * (offsetof(struct pthread_s, tl_policy) + 1);
1975
1976 int rv = __bsdthread_register(thread_start, start_wqthread, (int)PTHREAD_SIZE,
1977 (void*)data, (uintptr_t)sizeof(*data), data->dispatch_queue_offset);
1978
1979 if (rv > 0) {
1980 int required_features =
1981 PTHREAD_FEATURE_FINEPRIO |
1982 PTHREAD_FEATURE_BSDTHREADCTL |
1983 PTHREAD_FEATURE_SETSELF |
1984 PTHREAD_FEATURE_QOS_MAINTENANCE |
1985 PTHREAD_FEATURE_QOS_DEFAULT;
1986 if ((rv & required_features) != required_features) {
1987 PTHREAD_INTERNAL_CRASH(rv, "Missing required kernel support");
1988 }
1989 __pthread_supported_features = rv;
1990 }
1991
1992 /*
1993 * TODO: differentiate between (-1, EINVAL) after fork (which has the side
1994 * effect of resetting the child's stack_addr_hint before bailing out) and
1995 * (-1, EINVAL) because of invalid arguments. We'd probably like to treat
1996 * the latter as fatal.
1997 *
1998 * <rdar://problem/36451838>
1999 */
2000
2001 pthread_priority_t main_qos = (pthread_priority_t)data->main_qos;
2002
2003 if (_pthread_priority_thread_qos(main_qos) != THREAD_QOS_UNSPECIFIED) {
2004 _pthread_set_main_qos(main_qos);
2005 _pthread_tsd_slot(main_thread(), PTHREAD_QOS_CLASS) = main_qos;
2006 }
2007
2008 if (data->stack_addr_hint) {
2009 __pthread_stack_hint = data->stack_addr_hint;
2010 }
2011
2012 if (__libdispatch_workerfunction != NULL) {
2013 // prepare the kernel for workq action
2014 (void)__workq_open();
2015 }
2016 }
2017
2018 OS_NOINLINE
2019 static void
2020 _pthread_wqthread_legacy_worker_wrap(pthread_priority_t pp)
2021 {
2022 /* Old thread priorities are inverted from where we have them in
2023 * the new flexible priority scheme. The highest priority is zero,
2024 * up to 2, with background at 3.
2025 */
2026 pthread_workqueue_function_t func = (pthread_workqueue_function_t)__libdispatch_workerfunction;
2027 bool overcommit = (pp & _PTHREAD_PRIORITY_OVERCOMMIT_FLAG);
2028 int opts = overcommit ? WORKQ_ADDTHREADS_OPTION_OVERCOMMIT : 0;
2029
2030 switch (_pthread_priority_thread_qos(pp)) {
2031 case THREAD_QOS_USER_INITIATED:
2032 return (*func)(WORKQ_HIGH_PRIOQUEUE, opts, NULL);
2033 case THREAD_QOS_LEGACY:
2034 /* B&I builders can't pass a QOS_CLASS_DEFAULT thread to dispatch, for fear of the QoS being
2035 * picked up by NSThread (et al) and transported around the system. So change the TSD to
2036 * make this thread look like QOS_CLASS_USER_INITIATED even though it will still run as legacy.
2037 */
2038 _pthread_setspecific_direct(_PTHREAD_TSD_SLOT_PTHREAD_QOS_CLASS,
2039 _pthread_priority_make_from_thread_qos(THREAD_QOS_USER_INITIATED, 0, 0));
2040 return (*func)(WORKQ_DEFAULT_PRIOQUEUE, opts, NULL);
2041 case THREAD_QOS_UTILITY:
2042 return (*func)(WORKQ_LOW_PRIOQUEUE, opts, NULL);
2043 case THREAD_QOS_BACKGROUND:
2044 return (*func)(WORKQ_BG_PRIOQUEUE, opts, NULL);
2045 }
2046 PTHREAD_INTERNAL_CRASH(pp, "Invalid pthread priority for the legacy interface");
2047 }
2048
2049 OS_ALWAYS_INLINE
2050 static inline pthread_priority_t
2051 _pthread_wqthread_priority(int flags)
2052 {
2053 pthread_priority_t pp = 0;
2054 thread_qos_t qos;
2055
2056 if (flags & WQ_FLAG_THREAD_KEVENT) {
2057 pp |= _PTHREAD_PRIORITY_NEEDS_UNBIND_FLAG;
2058 }
2059 if (flags & WQ_FLAG_THREAD_EVENT_MANAGER) {
2060 return pp | _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG;
2061 }
2062
2063 if (flags & WQ_FLAG_THREAD_OVERCOMMIT) {
2064 pp |= _PTHREAD_PRIORITY_OVERCOMMIT_FLAG;
2065 }
2066 if (flags & WQ_FLAG_THREAD_PRIO_QOS) {
2067 qos = (thread_qos_t)(flags & WQ_FLAG_THREAD_PRIO_MASK);
2068 pp = _pthread_priority_make_from_thread_qos(qos, 0, pp);
2069 } else if (flags & WQ_FLAG_THREAD_PRIO_SCHED) {
2070 pp |= _PTHREAD_PRIORITY_SCHED_PRI_MASK;
2071 pp |= (flags & WQ_FLAG_THREAD_PRIO_MASK);
2072 } else {
2073 PTHREAD_INTERNAL_CRASH(flags, "Missing priority");
2074 }
2075 return pp;
2076 }
2077
2078 OS_NOINLINE
2079 static void
2080 _pthread_wqthread_setup(pthread_t self, mach_port_t kport, void *stacklowaddr,
2081 int flags)
2082 {
2083 void *stackaddr = self;
2084 size_t stacksize = (uintptr_t)self - (uintptr_t)stacklowaddr;
2085
2086 _pthread_struct_init(self, &_pthread_attr_default, stackaddr, stacksize,
2087 PTHREAD_ALLOCADDR(stackaddr, stacksize),
2088 PTHREAD_ALLOCSIZE(stackaddr, stacksize));
2089
2090 _pthread_tsd_slot(self, MACH_THREAD_SELF) = kport;
2091 self->wqthread = 1;
2092 self->wqkillset = 0;
2093 self->tl_joinable = false;
2094
2095 // Update the running thread count and set childrun bit.
2096 if (os_unlikely((flags & WQ_FLAG_THREAD_TSD_BASE_SET) == 0)) {
2097 PTHREAD_INTERNAL_CRASH(flags,
2098 "thread_set_tsd_base() wasn't called by the kernel");
2099 }
2100 _pthread_set_self_internal(self);
2101 __pthread_add_thread(self, kport, false);
2102 __pthread_started_thread(self);
2103 }
2104
2105 OS_NORETURN OS_NOINLINE
2106 static void
2107 _pthread_wqthread_exit(pthread_t self)
2108 {
2109 const thread_qos_t WORKQ_THREAD_QOS_CLEANUP = THREAD_QOS_LEGACY;
2110 pthread_priority_t pp = _pthread_tsd_slot(self, PTHREAD_QOS_CLASS);
2111 thread_qos_t qos;
2112
2113 qos = _pthread_priority_thread_qos(pp);
2114 if (qos == THREAD_QOS_UNSPECIFIED || qos > WORKQ_THREAD_QOS_CLEANUP) {
2115 // Reset QoS to something low for the cleanup process
2116 pp = _pthread_priority_make_from_thread_qos(WORKQ_THREAD_QOS_CLEANUP, 0, 0);
2117 _pthread_tsd_slot(self, PTHREAD_QOS_CLASS) = pp;
2118 }
2119
2120 _pthread_exit(self, NULL);
2121 }
2122
2123 // workqueue entry point from kernel
2124 void
2125 _pthread_wqthread(pthread_t self, mach_port_t kport, void *stacklowaddr,
2126 void *keventlist, int flags, int nkevents)
2127 {
2128 if ((flags & WQ_FLAG_THREAD_REUSE) == 0) {
2129 _pthread_wqthread_setup(self, kport, stacklowaddr, flags);
2130 }
2131
2132 pthread_priority_t pp;
2133
2134 if (flags & WQ_FLAG_THREAD_OUTSIDEQOS) {
2135 self->wq_outsideqos = 1;
2136 pp = _pthread_priority_make_from_thread_qos(THREAD_QOS_LEGACY, 0,
2137 _PTHREAD_PRIORITY_FALLBACK_FLAG);
2138 } else {
2139 self->wq_outsideqos = 0;
2140 pp = _pthread_wqthread_priority(flags);
2141 }
2142
2143 self->tsd[_PTHREAD_TSD_SLOT_PTHREAD_QOS_CLASS] = (void *)pp;
2144
2145 // avoid spills on the stack hard to keep used stack space minimal
2146 if (os_unlikely(nkevents == WORKQ_EXIT_THREAD_NKEVENT)) {
2147 _pthread_wqthread_exit(self);
2148 } else if (flags & WQ_FLAG_THREAD_WORKLOOP) {
2149 kqueue_id_t *kqidptr = (kqueue_id_t *)keventlist - 1;
2150 self->fun = (void *(*)(void*))__libdispatch_workloopfunction;
2151 self->arg = keventlist;
2152 self->wq_nevents = nkevents;
2153 (*__libdispatch_workloopfunction)(kqidptr, &self->arg, &self->wq_nevents);
2154 __workq_kernreturn(WQOPS_THREAD_WORKLOOP_RETURN, self->arg, self->wq_nevents, 0);
2155 } else if (flags & WQ_FLAG_THREAD_KEVENT) {
2156 self->fun = (void *(*)(void*))__libdispatch_keventfunction;
2157 self->arg = keventlist;
2158 self->wq_nevents = nkevents;
2159 (*__libdispatch_keventfunction)(&self->arg, &self->wq_nevents);
2160 __workq_kernreturn(WQOPS_THREAD_KEVENT_RETURN, self->arg, self->wq_nevents, 0);
2161 } else {
2162 self->fun = (void *(*)(void*))__libdispatch_workerfunction;
2163 self->arg = (void *)(uintptr_t)pp;
2164 self->wq_nevents = 0;
2165 if (os_likely(__workq_newapi)) {
2166 (*__libdispatch_workerfunction)(pp);
2167 } else {
2168 _pthread_wqthread_legacy_worker_wrap(pp);
2169 }
2170 __workq_kernreturn(WQOPS_THREAD_RETURN, NULL, 0, 0);
2171 }
2172
2173 _os_set_crash_log_cause_and_message(self->err_no,
2174 "BUG IN LIBPTHREAD: __workq_kernreturn returned");
2175 /*
2176 * 52858993: we should never return but the compiler insists on outlining,
2177 * so the __builtin_trap() is in _start_wqthread in pthread_asm.s
2178 */
2179 }
2180
2181 #pragma mark pthread workqueue API for libdispatch
2182
2183 _Static_assert(WORKQ_KEVENT_EVENT_BUFFER_LEN == WQ_KEVENT_LIST_LEN,
2184 "Kernel and userland should agree on the event list size");
2185
2186 void
2187 pthread_workqueue_setdispatchoffset_np(int offset)
2188 {
2189 __workq_kernreturn(WQOPS_QUEUE_NEWSPISUPP, NULL, offset, 0x00);
2190 }
2191
2192 int
2193 pthread_workqueue_setup(struct pthread_workqueue_config *cfg, size_t cfg_size)
2194 {
2195 int rv = EBUSY;
2196 struct workq_dispatch_config wdc_cfg;
2197 size_t min_size = 0;
2198
2199 if (cfg_size < sizeof(uint32_t)) {
2200 return EINVAL;
2201 }
2202
2203 switch (cfg->version) {
2204 case 1:
2205 min_size = offsetof(struct pthread_workqueue_config, queue_label_offs);
2206 break;
2207 case 2:
2208 min_size = sizeof(struct pthread_workqueue_config);
2209 break;
2210 default:
2211 return EINVAL;
2212 }
2213
2214 if (!cfg || cfg_size < min_size) {
2215 return EINVAL;
2216 }
2217
2218 if (cfg->flags & ~PTHREAD_WORKQUEUE_CONFIG_SUPPORTED_FLAGS ||
2219 cfg->version < PTHREAD_WORKQUEUE_CONFIG_MIN_SUPPORTED_VERSION) {
2220 return ENOTSUP;
2221 }
2222
2223 if (__libdispatch_workerfunction == NULL) {
2224 __workq_newapi = true;
2225
2226 wdc_cfg.wdc_version = WORKQ_DISPATCH_CONFIG_VERSION;
2227 wdc_cfg.wdc_flags = 0;
2228 wdc_cfg.wdc_queue_serialno_offs = cfg->queue_serialno_offs;
2229 #if WORKQ_DISPATCH_CONFIG_VERSION >= 2
2230 wdc_cfg.wdc_queue_label_offs = cfg->queue_label_offs;
2231 #endif
2232
2233 // Tell the kernel about dispatch internals
2234 rv = (int) __workq_kernreturn(WQOPS_SETUP_DISPATCH, &wdc_cfg, sizeof(wdc_cfg), 0);
2235 if (rv == -1) {
2236 return errno;
2237 } else {
2238 __libdispatch_keventfunction = cfg->kevent_cb;
2239 __libdispatch_workloopfunction = cfg->workloop_cb;
2240 __libdispatch_workerfunction = cfg->workq_cb;
2241
2242 // Prepare the kernel for workq action
2243 (void)__workq_open();
2244 if (__is_threaded == 0) {
2245 __is_threaded = 1;
2246 }
2247
2248 return 0;
2249 }
2250 }
2251
2252 return rv;
2253 }
2254
2255 int
2256 _pthread_workqueue_init_with_workloop(pthread_workqueue_function2_t queue_func,
2257 pthread_workqueue_function_kevent_t kevent_func,
2258 pthread_workqueue_function_workloop_t workloop_func,
2259 int offset, int flags)
2260 {
2261 struct pthread_workqueue_config cfg = {
2262 .version = PTHREAD_WORKQUEUE_CONFIG_VERSION,
2263 .flags = 0,
2264 .workq_cb = queue_func,
2265 .kevent_cb = kevent_func,
2266 .workloop_cb = workloop_func,
2267 .queue_serialno_offs = offset,
2268 .queue_label_offs = 0,
2269 };
2270
2271 return pthread_workqueue_setup(&cfg, sizeof(cfg));
2272 }
2273
2274 int
2275 _pthread_workqueue_init_with_kevent(pthread_workqueue_function2_t queue_func,
2276 pthread_workqueue_function_kevent_t kevent_func,
2277 int offset, int flags)
2278 {
2279 return _pthread_workqueue_init_with_workloop(queue_func, kevent_func, NULL, offset, flags);
2280 }
2281
2282 int
2283 _pthread_workqueue_init(pthread_workqueue_function2_t func, int offset, int flags)
2284 {
2285 return _pthread_workqueue_init_with_kevent(func, NULL, offset, flags);
2286 }
2287
2288 int
2289 pthread_workqueue_setdispatch_np(pthread_workqueue_function_t worker_func)
2290 {
2291 struct pthread_workqueue_config cfg = {
2292 .version = PTHREAD_WORKQUEUE_CONFIG_VERSION,
2293 .flags = 0,
2294 .workq_cb = (uint64_t)(pthread_workqueue_function2_t)worker_func,
2295 .kevent_cb = 0,
2296 .workloop_cb = 0,
2297 .queue_serialno_offs = 0,
2298 .queue_label_offs = 0,
2299 };
2300
2301 return pthread_workqueue_setup(&cfg, sizeof(cfg));
2302 }
2303
2304 int
2305 _pthread_workqueue_supported(void)
2306 {
2307 if (os_unlikely(!__pthread_supported_features)) {
2308 PTHREAD_INTERNAL_CRASH(0, "libpthread has not been initialized");
2309 }
2310
2311 return __pthread_supported_features;
2312 }
2313
2314 int
2315 pthread_workqueue_addthreads_np(int queue_priority, int options, int numthreads)
2316 {
2317 int res = 0;
2318
2319 // Cannot add threads without a worker function registered.
2320 if (__libdispatch_workerfunction == NULL) {
2321 return EPERM;
2322 }
2323
2324 pthread_priority_t kp = 0;
2325 int compat_priority = queue_priority & WQ_FLAG_THREAD_PRIO_MASK;
2326 int flags = 0;
2327
2328 if (options & WORKQ_ADDTHREADS_OPTION_OVERCOMMIT) {
2329 flags = _PTHREAD_PRIORITY_OVERCOMMIT_FLAG;
2330 }
2331
2332 #pragma clang diagnostic push
2333 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2334 kp = _pthread_qos_class_encode_workqueue(compat_priority, flags);
2335 #pragma clang diagnostic pop
2336
2337 res = __workq_kernreturn(WQOPS_QUEUE_REQTHREADS, NULL, numthreads, (int)kp);
2338 if (res == -1) {
2339 res = errno;
2340 }
2341 return res;
2342 }
2343
2344 bool
2345 _pthread_workqueue_should_narrow(pthread_priority_t pri)
2346 {
2347 int res = __workq_kernreturn(WQOPS_SHOULD_NARROW, NULL, (int)pri, 0);
2348 if (res == -1) {
2349 return false;
2350 }
2351 return res;
2352 }
2353
2354 int
2355 _pthread_workqueue_addthreads(int numthreads, pthread_priority_t priority)
2356 {
2357 int res = 0;
2358
2359 if (__libdispatch_workerfunction == NULL) {
2360 return EPERM;
2361 }
2362
2363 #if TARGET_OS_OSX
2364 // <rdar://problem/37687655> Legacy simulators fail to boot
2365 //
2366 // Older sims set the deprecated _PTHREAD_PRIORITY_ROOTQUEUE_FLAG wrongly,
2367 // which is aliased to _PTHREAD_PRIORITY_SCHED_PRI_FLAG and that XNU
2368 // validates and rejects.
2369 //
2370 // As a workaround, forcefully unset this bit that cannot be set here
2371 // anyway.
2372 priority &= ~_PTHREAD_PRIORITY_SCHED_PRI_FLAG;
2373 #endif
2374
2375 res = __workq_kernreturn(WQOPS_QUEUE_REQTHREADS, NULL, numthreads, (int)priority);
2376 if (res == -1) {
2377 res = errno;
2378 }
2379 return res;
2380 }
2381
2382 int
2383 _pthread_workqueue_set_event_manager_priority(pthread_priority_t priority)
2384 {
2385 int res = __workq_kernreturn(WQOPS_SET_EVENT_MANAGER_PRIORITY, NULL, (int)priority, 0);
2386 if (res == -1) {
2387 res = errno;
2388 }
2389 return res;
2390 }
2391
2392 int
2393 _pthread_workloop_create(uint64_t workloop_id, uint64_t options, pthread_attr_t *attr)
2394 {
2395 struct kqueue_workloop_params params = {
2396 .kqwlp_version = sizeof(struct kqueue_workloop_params),
2397 .kqwlp_id = workloop_id,
2398 .kqwlp_flags = 0,
2399 };
2400
2401 if (!attr) {
2402 return EINVAL;
2403 }
2404
2405 if (attr->schedset) {
2406 params.kqwlp_flags |= KQ_WORKLOOP_CREATE_SCHED_PRI;
2407 params.kqwlp_sched_pri = attr->param.sched_priority;
2408 }
2409
2410 if (attr->policyset) {
2411 params.kqwlp_flags |= KQ_WORKLOOP_CREATE_SCHED_POL;
2412 params.kqwlp_sched_pol = attr->policy;
2413 }
2414
2415 if (attr->cpupercentset) {
2416 params.kqwlp_flags |= KQ_WORKLOOP_CREATE_CPU_PERCENT;
2417 params.kqwlp_cpu_percent = attr->cpupercent;
2418 params.kqwlp_cpu_refillms = attr->refillms;
2419 }
2420
2421 int res = __kqueue_workloop_ctl(KQ_WORKLOOP_CREATE, 0, &params,
2422 sizeof(params));
2423 if (res == -1) {
2424 res = errno;
2425 }
2426 return res;
2427 }
2428
2429 int
2430 _pthread_workloop_destroy(uint64_t workloop_id)
2431 {
2432 struct kqueue_workloop_params params = {
2433 .kqwlp_version = sizeof(struct kqueue_workloop_params),
2434 .kqwlp_id = workloop_id,
2435 };
2436
2437 int res = __kqueue_workloop_ctl(KQ_WORKLOOP_DESTROY, 0, &params,
2438 sizeof(params));
2439 if (res == -1) {
2440 res = errno;
2441 }
2442 return res;
2443 }
2444
2445 #pragma mark Introspection SPI for libpthread.
2446
2447 static pthread_introspection_hook_t _pthread_introspection_hook;
2448
2449 pthread_introspection_hook_t
2450 pthread_introspection_hook_install(pthread_introspection_hook_t hook)
2451 {
2452 pthread_introspection_hook_t prev;
2453 prev = _pthread_atomic_xchg_ptr((void**)&_pthread_introspection_hook, hook);
2454 return prev;
2455 }
2456
2457 static inline void
2458 _pthread_introspection_call_hook(unsigned int event,
2459 pthread_t thread, void *addr, size_t size)
2460 {
2461 pthread_t self = pthread_self();
2462 uint16_t old = self->introspection;
2463 self->introspection = (uint16_t)event;
2464 _pthread_introspection_hook(event, thread, addr, size);
2465 self->introspection = old;
2466 }
2467
2468 OS_NOINLINE
2469 static void
2470 _pthread_introspection_hook_callout_thread_create(pthread_t t)
2471 {
2472 _pthread_introspection_call_hook(PTHREAD_INTROSPECTION_THREAD_CREATE, t, t,
2473 PTHREAD_SIZE);
2474 }
2475
2476 static inline void
2477 _pthread_introspection_thread_create(pthread_t t)
2478 {
2479 if (os_fastpath(!_pthread_introspection_hook)) return;
2480 _pthread_introspection_hook_callout_thread_create(t);
2481 }
2482
2483 OS_NOINLINE
2484 static void
2485 _pthread_introspection_hook_callout_thread_start(pthread_t t)
2486 {
2487 size_t freesize;
2488 void *freeaddr;
2489 if (t == main_thread()) {
2490 size_t stacksize = t->stackaddr - t->stackbottom;
2491 freesize = stacksize + t->guardsize;
2492 freeaddr = t->stackaddr - freesize;
2493 } else {
2494 freesize = t->freesize - PTHREAD_SIZE;
2495 freeaddr = t->freeaddr;
2496 }
2497 _pthread_introspection_call_hook(PTHREAD_INTROSPECTION_THREAD_START, t,
2498 freeaddr, freesize);
2499 }
2500
2501 static inline void
2502 _pthread_introspection_thread_start(pthread_t t)
2503 {
2504 if (os_fastpath(!_pthread_introspection_hook)) return;
2505 _pthread_introspection_hook_callout_thread_start(t);
2506 }
2507
2508 OS_NOINLINE
2509 static void
2510 _pthread_introspection_hook_callout_thread_terminate(pthread_t t)
2511 {
2512 size_t freesize;
2513 void *freeaddr;
2514 if (t == main_thread()) {
2515 size_t stacksize = t->stackaddr - t->stackbottom;
2516 freesize = stacksize + t->guardsize;
2517 freeaddr = t->stackaddr - freesize;
2518 } else {
2519 freesize = t->freesize - PTHREAD_SIZE;
2520 freeaddr = t->freeaddr;
2521 }
2522 _pthread_introspection_call_hook(PTHREAD_INTROSPECTION_THREAD_TERMINATE, t,
2523 freeaddr, freesize);
2524 }
2525
2526 static inline void
2527 _pthread_introspection_thread_terminate(pthread_t t)
2528 {
2529 if (os_fastpath(!_pthread_introspection_hook)) return;
2530 _pthread_introspection_hook_callout_thread_terminate(t);
2531 }
2532
2533 OS_NOINLINE
2534 static void
2535 _pthread_introspection_hook_callout_thread_destroy(pthread_t t)
2536 {
2537 _pthread_introspection_call_hook(PTHREAD_INTROSPECTION_THREAD_DESTROY, t, t,
2538 PTHREAD_SIZE);
2539 }
2540
2541 static inline void
2542 _pthread_introspection_thread_destroy(pthread_t t)
2543 {
2544 if (os_fastpath(!_pthread_introspection_hook)) return;
2545 _pthread_introspection_hook_callout_thread_destroy(t);
2546 }
2547
2548 #pragma mark libplatform shims
2549 #if !VARIANT_DYLD
2550
2551 #include <platform/string.h>
2552
2553 // pthread_setup initializes large structures to 0,
2554 // which the compiler turns into a library call to memset.
2555 //
2556 // To avoid linking against Libc, provide a simple wrapper
2557 // that calls through to the libplatform primitives
2558
2559 #undef memset
2560 PTHREAD_NOEXPORT
2561 void *
2562 memset(void *b, int c, size_t len)
2563 {
2564 return _platform_memset(b, c, len);
2565 }
2566
2567 #undef bzero
2568 PTHREAD_NOEXPORT
2569 void
2570 bzero(void *s, size_t n)
2571 {
2572 _platform_bzero(s, n);
2573 }
2574
2575 #undef memcpy
2576 PTHREAD_NOEXPORT
2577 void *
2578 memcpy(void* a, const void* b, unsigned long s)
2579 {
2580 return _platform_memmove(a, b, s);
2581 }
2582
2583 #endif // !VARIANT_DYLD