This repository was archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathpthread.c
More file actions
2813 lines (2431 loc) · 75.3 KB
/
pthread.c
File metadata and controls
2813 lines (2431 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2013 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appears in all copies and
* that both the copyright notice and this permission notice appear in
* supporting documentation.
*
* OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
* NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/*
* MkLinux
*/
/*
* POSIX Pthread Library
*/
#include "internal.h"
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <mach/mach_init.h>
#include <mach/mach_vm.h>
#include <mach/mach_sync_ipc.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/sysctl.h>
#include <sys/queue.h>
#include <sys/ulock.h>
#include <sys/mman.h>
#include <machine/vmparam.h>
#define __APPLE_API_PRIVATE
#include <machine/cpu_capabilities.h>
#if __has_include(<ptrauth.h>)
#include <ptrauth.h>
#endif // __has_include(<ptrauth.h>)
#include <os/thread_self_restrict.h>
#include <os/tsd.h>
#if _PTHREAD_CONFIG_JIT_WRITE_PROTECT
#include <mach-o/dyld_priv.h>
#include <mach-o/loader.h>
#include <mach-o/getsect.h>
#endif // _PTHREAD_CONFIG_JIT_WRITE_PROTECT
// Default stack size is 512KB; independent of the main thread's stack size.
#define DEFAULT_STACK_SIZE (size_t)(512 * 1024)
//
// Global constants
//
/*
* The pthread may be offset into a page. In that event, by contract
* with the kernel, the allocation will extend PTHREAD_SIZE from the
* start of the next page. There's also one page worth of allocation
* below stacksize for the guard page. <rdar://problem/19941744>
*/
#define PTHREAD_SIZE ((size_t)mach_vm_round_page(sizeof(struct pthread_s)))
#define PTHREAD_ALLOCADDR(stackaddr, stacksize) ((stackaddr - stacksize) - vm_page_size)
#define PTHREAD_ALLOCSIZE(stackaddr, stacksize) ((round_page((uintptr_t)stackaddr) + PTHREAD_SIZE) - (uintptr_t)PTHREAD_ALLOCADDR(stackaddr, stacksize))
static const pthread_attr_t _pthread_attr_default = {
.sig = _PTHREAD_ATTR_SIG,
.stacksize = 0,
.detached = PTHREAD_CREATE_JOINABLE,
.inherit = _PTHREAD_DEFAULT_INHERITSCHED,
.policy = _PTHREAD_DEFAULT_POLICY,
.defaultguardpage = true,
// compile time constant for _pthread_default_priority(0)
.qosclass = (1U << (THREAD_QOS_LEGACY - 1 + _PTHREAD_PRIORITY_QOS_CLASS_SHIFT)) |
((uint8_t)-1 & _PTHREAD_PRIORITY_PRIORITY_MASK),
};
#if PTHREAD_LAYOUT_SPI
const struct pthread_layout_offsets_s pthread_layout_offsets = {
.plo_version = 1,
.plo_pthread_tsd_base_offset = offsetof(struct pthread_s, tsd),
.plo_pthread_tsd_base_address_offset = 0,
.plo_pthread_tsd_entry_size = sizeof(((struct pthread_s *)NULL)->tsd[0]),
};
#endif // PTHREAD_LAYOUT_SPI
//
// Global exported variables
//
// This global should be used (carefully) by anyone needing to know if a
// pthread (other than the main thread) has been created.
int __is_threaded = 0;
const int __unix_conforming = 1; // we're always conformant, but it's exported
//
// Global internal variables
//
// _pthread_list_lock protects _pthread_count, access to the __pthread_head
// list. Externally imported by pthread_cancelable.c.
struct __pthread_list __pthread_head = TAILQ_HEAD_INITIALIZER(__pthread_head);
_pthread_lock _pthread_list_lock = _PTHREAD_LOCK_INITIALIZER;
uint32_t _main_qos;
#if VARIANT_DYLD
// The main thread's pthread_t
struct pthread_s _main_thread OS_ALIGNED(64);
#else // VARIANT_DYLD
pthread_t _main_thread_ptr;
void *(*_pthread_malloc)(size_t);
void (*_pthread_free)(void *);
#endif // VARIANT_DYLD
#if PTHREAD_DEBUG_LOG
#include <fcntl.h>
int _pthread_debuglog;
uint64_t _pthread_debugstart;
#endif
//
// Global static variables
//
static bool __workq_newapi;
static uint8_t default_priority;
#if !VARIANT_DYLD
static uint8_t max_priority;
static uint8_t min_priority;
#endif // !VARIANT_DYLD
static int _pthread_count = 1;
static int pthread_concurrency;
uintptr_t _pthread_ptr_munge_token;
static void (*exitf)(int) = __exit;
// work queue support data
OS_NORETURN OS_COLD
static void
__pthread_invalid_keventfunction(void **events, int *nevents)
{
PTHREAD_CLIENT_CRASH(0, "Invalid kqworkq setup");
}
OS_NORETURN OS_COLD
static void
__pthread_invalid_workloopfunction(uint64_t *workloop_id, void **events, int *nevents)
{
PTHREAD_CLIENT_CRASH(0, "Invalid kqwl setup");
}
static pthread_workqueue_function2_t __libdispatch_workerfunction;
static pthread_workqueue_function_kevent_t __libdispatch_keventfunction = &__pthread_invalid_keventfunction;
static pthread_workqueue_function_workloop_t __libdispatch_workloopfunction = &__pthread_invalid_workloopfunction;
static int __pthread_supported_features; // supported feature set
#if defined(__i386__) || defined(__x86_64__)
static mach_vm_address_t __pthread_stack_hint = 0xB0000000;
#elif defined(__arm__) || defined(__arm64__)
static mach_vm_address_t __pthread_stack_hint = 0x30000000;
#else
#error no __pthread_stack_hint for this architecture
#endif
//
// Function prototypes
//
// pthread primitives
static inline void _pthread_struct_init(pthread_t t, const pthread_attr_t *attrs,
void *stack, size_t stacksize, void *freeaddr, size_t freesize);
#if VARIANT_DYLD
static void _pthread_set_self_dyld(void);
#endif // VARIANT_DYLD
static inline void _pthread_set_self_internal(pthread_t);
static inline void __pthread_started_thread(pthread_t t);
static void _pthread_exit(pthread_t self, void *value_ptr) __dead2;
static inline void _pthread_introspection_thread_create(pthread_t t);
static inline void _pthread_introspection_thread_start(pthread_t t);
static inline void _pthread_introspection_thread_terminate(pthread_t t);
static inline void _pthread_introspection_thread_destroy(pthread_t t);
/*
* Flags filed passed to bsdthread_create and back in pthread_start
* 31 <---------------------------------> 0
* _________________________________________
* | flags(8) | policy(8) | importance(16) |
* -----------------------------------------
*/
#define PTHREAD_START_CUSTOM 0x01000000 // <rdar://problem/34501401>
#define PTHREAD_START_SETSCHED 0x02000000
// was PTHREAD_START_DETACHED 0x04000000
#define PTHREAD_START_QOSCLASS 0x08000000
#define PTHREAD_START_TSD_BASE_SET 0x10000000
#define PTHREAD_START_SUSPENDED 0x20000000
#define PTHREAD_START_QOSCLASS_MASK 0x00ffffff
#define PTHREAD_START_POLICY_BITSHIFT 16
#define PTHREAD_START_POLICY_MASK 0xff
#define PTHREAD_START_IMPORTANCE_MASK 0xffff
#pragma mark pthread attrs
int
pthread_attr_destroy(pthread_attr_t *attr)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
attr->sig = 0;
ret = 0;
}
return ret;
}
int
pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*detachstate = attr->detached;
ret = 0;
}
return ret;
}
int
pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*inheritsched = attr->inherit;
ret = 0;
}
return ret;
}
static OS_ALWAYS_INLINE void
_pthread_attr_get_schedparam(const pthread_attr_t *attr,
struct sched_param *param)
{
if (attr->schedset) {
*param = attr->param;
} else {
param->sched_priority = default_priority;
param->quantum = 10; /* quantum isn't public yet */
}
}
int
pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
_pthread_attr_get_schedparam(attr, param);
ret = 0;
}
return ret;
}
int
pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*policy = attr->policy;
ret = 0;
}
return ret;
}
int
pthread_attr_init(pthread_attr_t *attr)
{
*attr = _pthread_attr_default;
return 0;
}
int
pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
(detachstate == PTHREAD_CREATE_JOINABLE ||
detachstate == PTHREAD_CREATE_DETACHED)) {
attr->detached = detachstate;
ret = 0;
}
return ret;
}
int
pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
(inheritsched == PTHREAD_INHERIT_SCHED ||
inheritsched == PTHREAD_EXPLICIT_SCHED)) {
attr->inherit = inheritsched;
ret = 0;
}
return ret;
}
int
pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
/* TODO: Validate sched_param fields */
attr->param = *param;
attr->schedset = 1;
ret = 0;
}
return ret;
}
#define _PTHREAD_POLICY_IS_FIXEDPRI(x) ((x) == SCHED_RR || (x) == SCHED_FIFO)
int
pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG && (policy == SCHED_OTHER ||
policy == SCHED_RR || policy == SCHED_FIFO)) {
if (!_PTHREAD_POLICY_IS_FIXEDPRI(policy)) {
/* non-fixedpri policy should remove cpupercent */
attr->cpupercentset = 0;
}
attr->policy = policy;
attr->policyset = 1;
ret = 0;
}
return ret;
}
int
pthread_attr_setscope(pthread_attr_t *attr, int scope)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
if (scope == PTHREAD_SCOPE_SYSTEM) {
// No attribute yet for the scope.
ret = 0;
} else if (scope == PTHREAD_SCOPE_PROCESS) {
ret = ENOTSUP;
}
}
return ret;
}
int
pthread_attr_getscope(const pthread_attr_t *attr, int *scope)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*scope = PTHREAD_SCOPE_SYSTEM;
ret = 0;
}
return ret;
}
int
pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*stackaddr = attr->stackaddr;
ret = 0;
}
return ret;
}
int
pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
((mach_vm_address_t)stackaddr & vm_page_mask) == 0) {
attr->stackaddr = stackaddr;
attr->defaultguardpage = false;
attr->guardsize = 0;
ret = 0;
}
return ret;
}
static inline size_t
_pthread_attr_stacksize(const pthread_attr_t *attr)
{
return attr->stacksize ? attr->stacksize : DEFAULT_STACK_SIZE;
}
int
pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*stacksize = _pthread_attr_stacksize(attr);
ret = 0;
}
return ret;
}
int
pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
{
#if TARGET_OS_OSX
// If the caller is doing something reasonable, help them out.
if (stacksize % 0x1000 == 0) {
stacksize = round_page(stacksize);
}
#endif // TARGET_OS_OSX
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
((stacksize & vm_page_mask) == 0) &&
stacksize >= PTHREAD_STACK_MIN) {
attr->stacksize = stacksize;
ret = 0;
}
return ret;
}
int
pthread_attr_getstack(const pthread_attr_t *attr, void **stackaddr, size_t * stacksize)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*stackaddr = (void *)((uintptr_t)attr->stackaddr - attr->stacksize);
*stacksize = _pthread_attr_stacksize(attr);
ret = 0;
}
return ret;
}
// Per SUSv3, the stackaddr is the base address, the lowest addressable byte
// address. This is not the same as in pthread_attr_setstackaddr.
int
pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
(((mach_vm_address_t)stackaddr & vm_page_mask) == 0) &&
((stacksize & vm_page_mask) == 0) &&
stacksize >= PTHREAD_STACK_MIN) {
attr->stackaddr = (void *)((uintptr_t)stackaddr + stacksize);
attr->stacksize = stacksize;
ret = 0;
}
return ret;
}
int
pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize)
{
#if TARGET_OS_OSX
// If the caller is doing something reasonable, help them out.
if (guardsize % 0x1000 == 0) {
guardsize = round_page(guardsize);
}
#endif // TARGET_OS_OSX
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG &&
(guardsize & vm_page_mask) == 0) {
/* Guardsize of 0 is valid, means no guard */
attr->defaultguardpage = false;
attr->guardsize = guardsize;
ret = 0;
}
return ret;
}
static inline size_t
_pthread_attr_guardsize(const pthread_attr_t *attr)
{
return attr->defaultguardpage ? vm_page_size : attr->guardsize;
}
int
pthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG) {
*guardsize = _pthread_attr_guardsize(attr);
ret = 0;
}
return ret;
}
int
pthread_attr_setcpupercent_np(pthread_attr_t *attr, int percent,
unsigned long refillms)
{
int ret = EINVAL;
if (attr->sig == _PTHREAD_ATTR_SIG && percent < UINT8_MAX &&
refillms < _PTHREAD_ATTR_REFILLMS_MAX && attr->policyset &&
_PTHREAD_POLICY_IS_FIXEDPRI(attr->policy)) {
attr->cpupercent = percent;
attr->refillms = (uint32_t)(refillms & 0x00ffffff);
attr->cpupercentset = 1;
ret = 0;
}
return ret;
}
#pragma mark pthread lifetime
// Allocate a thread structure, stack and guard page.
//
// The thread structure may optionally be placed in the same allocation as the
// stack, residing above the top of the stack. This cannot be done if a
// custom stack address is provided.
//
// Similarly the guard page cannot be allocated if a custom stack address is
// provided.
//
// The allocated thread structure is initialized with values that indicate how
// it should be freed.
static pthread_t
_pthread_allocate(const pthread_attr_t *attrs, void **stack,
bool from_mach_thread)
{
mach_vm_address_t allocaddr = __pthread_stack_hint;
size_t allocsize, guardsize, stacksize, pthreadoff;
kern_return_t kr;
pthread_t t;
if (os_unlikely(attrs->stacksize != 0 &&
attrs->stacksize < PTHREAD_STACK_MIN)) {
PTHREAD_CLIENT_CRASH(attrs->stacksize, "Stack size in attrs is too small");
}
if (os_unlikely((mach_vm_address_t)attrs->stackaddr & vm_page_mask)) {
PTHREAD_CLIENT_CRASH(attrs->stackaddr, "Unaligned stack addr in attrs");
}
// Allocate a pthread structure if necessary
if (attrs->stackaddr != NULL) {
allocsize = PTHREAD_SIZE;
guardsize = 0;
pthreadoff = 0;
// <rdar://problem/42588315> if the attrs struct specifies a custom
// stack address but not a custom size, using ->stacksize here instead
// of _pthread_attr_stacksize stores stacksize as zero, indicating
// that the stack size is unknown.
stacksize = attrs->stacksize;
} else {
guardsize = _pthread_attr_guardsize(attrs);
stacksize = _pthread_attr_stacksize(attrs) + PTHREAD_T_OFFSET;
pthreadoff = stacksize + guardsize;
allocsize = pthreadoff + PTHREAD_SIZE;
allocsize = mach_vm_round_page(allocsize);
}
kr = mach_vm_map(mach_task_self(), &allocaddr, allocsize, vm_page_size - 1,
VM_MAKE_TAG(VM_MEMORY_STACK)| VM_FLAGS_ANYWHERE, MEMORY_OBJECT_NULL,
0, FALSE, VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
if (kr != KERN_SUCCESS) {
kr = mach_vm_allocate(mach_task_self(), &allocaddr, allocsize,
VM_MAKE_TAG(VM_MEMORY_STACK)| VM_FLAGS_ANYWHERE);
} else if (__syscall_logger && !from_mach_thread) {
// libsyscall will not output malloc stack logging events when
// VM_MEMORY_STACK is passed in to facilitate mach thread promotion.
// To avoid losing the stack traces for normal p-thread create
// operations, libpthread must pretend to be the vm syscall and log
// the allocations. <rdar://36418708>
int eventTypeFlags = stack_logging_type_vm_allocate |
stack_logging_type_mapped_file_or_shared_mem;
__syscall_logger(eventTypeFlags | VM_MAKE_TAG(VM_MEMORY_STACK),
(uintptr_t)mach_task_self(), (uintptr_t)allocsize, 0,
(uintptr_t)allocaddr, 0);
}
if (kr != KERN_SUCCESS) {
*stack = NULL;
return NULL;
} else if (__syscall_logger && !from_mach_thread) {
// libsyscall will not output malloc stack logging events when
// VM_MEMORY_STACK is passed in to facilitate mach thread promotion.
// To avoid losing the stack traces for normal p-thread create
// operations, libpthread must pretend to be the vm syscall and log
// the allocations. <rdar://36418708>
int eventTypeFlags = stack_logging_type_vm_allocate;
__syscall_logger(eventTypeFlags | VM_MAKE_TAG(VM_MEMORY_STACK),
(uintptr_t)mach_task_self(), (uintptr_t)allocsize, 0,
(uintptr_t)allocaddr, 0);
}
// The stack grows down.
// Set the guard page at the lowest address of the
// newly allocated stack. Return the highest address
// of the stack.
if (guardsize) {
(void)mach_vm_protect(mach_task_self(), allocaddr, guardsize,
FALSE, VM_PROT_NONE);
}
// Thread structure resides at the top of the stack (when using a
// custom stack, allocsize == PTHREAD_SIZE, so places the pthread_t
// at allocaddr).
t = (pthread_t)(allocaddr + pthreadoff);
if (attrs->stackaddr) {
*stack = attrs->stackaddr;
} else {
*stack = t;
}
_pthread_struct_init(t, attrs, *stack, stacksize, allocaddr, allocsize);
return t;
}
OS_NOINLINE
void
_pthread_deallocate(pthread_t t, bool from_mach_thread)
{
kern_return_t ret;
// Don't free the main thread.
if (t != main_thread()) {
if (!from_mach_thread) { // see __pthread_add_thread
_pthread_introspection_thread_destroy(t);
}
ret = mach_vm_deallocate(mach_task_self(), t->freeaddr, t->freesize);
if (ret != KERN_SUCCESS) {
PTHREAD_INTERNAL_CRASH(ret, "Unable to deallocate stack");
}
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreturn-stack-address"
OS_NOINLINE
static void*
_pthread_current_stack_address(void)
{
int a;
return &a;
}
#pragma clang diagnostic pop
static void
_pthread_joiner_wake(pthread_t thread)
{
uint32_t *exit_gate = &thread->tl_exit_gate;
for (;;) {
int ret = __ulock_wake(UL_UNFAIR_LOCK | ULF_NO_ERRNO, exit_gate, 0);
if (ret == 0 || ret == -ENOENT) {
return;
}
if (ret != -EINTR) {
PTHREAD_INTERNAL_CRASH(-ret, "pthread_join() wake failure");
}
}
}
static void
_pthread_dealloc_reply_port(pthread_t self)
{
mach_port_t port = _pthread_tsd_slot(self, MIG_REPLY);
if (port != MACH_PORT_NULL) {
// this will also set the TSD to MACH_PORT_NULL
mig_dealloc_reply_port(port);
}
}
static void
_pthread_dealloc_special_reply_port(pthread_t self)
{
mach_port_t port = _pthread_tsd_slot(self, MACH_SPECIAL_REPLY);
if (port != MACH_PORT_NULL) {
_pthread_tsd_slot(self, MACH_SPECIAL_REPLY) = MACH_PORT_NULL;
thread_destruct_special_reply_port(port, THREAD_SPECIAL_REPLY_PORT_ALL);
}
}
// Terminates the thread if called from the currently running thread.
OS_NORETURN OS_NOINLINE OS_NOT_TAIL_CALLED
static void
_pthread_terminate(pthread_t t, void *exit_value)
{
_pthread_introspection_thread_terminate(t);
uintptr_t freeaddr = (uintptr_t)t->freeaddr;
size_t freesize = t->freesize;
bool should_exit;
// the size of just the stack
size_t freesize_stack = t->freesize;
// We usually pass our structure+stack to bsdthread_terminate to free, but
// if we get told to keep the pthread_t structure around then we need to
// adjust the free size and addr in the pthread_t to just refer to the
// structure and not the stack. If we do end up deallocating the
// structure, this is useless work since no one can read the result, but we
// can't do it after the call to pthread_remove_thread because it isn't
// safe to dereference t after that.
if ((void*)t > t->freeaddr && (void*)t < t->freeaddr + t->freesize){
// Check to ensure the pthread structure itself is part of the
// allocation described by freeaddr/freesize, in which case we split and
// only deallocate the area below the pthread structure. In the event of a
// custom stack, the freeaddr/size will be the pthread structure itself, in
// which case we shouldn't free anything (the final else case).
freesize_stack = trunc_page((uintptr_t)t - (uintptr_t)freeaddr);
// describe just the remainder for deallocation when the pthread_t goes away
t->freeaddr += freesize_stack;
t->freesize -= freesize_stack;
} else if (t == main_thread()) {
freeaddr = t->stackaddr - pthread_get_stacksize_np(t);
uintptr_t stackborder = trunc_page((uintptr_t)_pthread_current_stack_address());
freesize_stack = stackborder - freeaddr;
} else {
freesize_stack = 0;
}
mach_port_t kport = _pthread_tsd_slot(t, MACH_THREAD_SELF);
bool keep_thread_struct = false, needs_wake = false;
semaphore_t custom_stack_sema = MACH_PORT_NULL;
_pthread_dealloc_special_reply_port(t);
_pthread_dealloc_reply_port(t);
_pthread_lock_lock(&_pthread_list_lock);
// This piece of code interacts with pthread_join. It will always:
// - set tl_exit_gate to MACH_PORT_DEAD (thread exited)
// - set tl_exit_value to the value passed to pthread_exit()
// - decrement _pthread_count, so that we can exit the process when all
// threads exited even if not all of them were joined.
t->tl_exit_gate = MACH_PORT_DEAD;
t->tl_exit_value = exit_value;
should_exit = (--_pthread_count <= 0);
// If we see a joiner, we prepost that the join has to succeed,
// and the joiner is committed to finish (even if it was canceled)
if (t->tl_join_ctx) {
custom_stack_sema = _pthread_joiner_prepost_wake(t); // unsets tl_joinable
needs_wake = true;
}
// Joinable threads that have no joiner yet are kept on the thread list
// so that pthread_join() can later discover the thread when it is joined,
// and will have to do the pthread_t cleanup.
if (t->tl_joinable) {
t->tl_joiner_cleans_up = keep_thread_struct = true;
} else {
TAILQ_REMOVE(&__pthread_head, t, tl_plist);
}
_pthread_lock_unlock(&_pthread_list_lock);
if (needs_wake) {
// When we found a waiter, we want to drop the very contended list lock
// before we do the syscall in _pthread_joiner_wake(). Then, we decide
// who gets to cleanup the pthread_t between the joiner and the exiting
// thread:
// - the joiner tries to set tl_join_ctx to NULL
// - the exiting thread tries to set tl_joiner_cleans_up to true
// Whoever does it first commits the other guy to cleanup the pthread_t
_pthread_joiner_wake(t);
_pthread_lock_lock(&_pthread_list_lock);
if (t->tl_join_ctx) {
t->tl_joiner_cleans_up = true;
keep_thread_struct = true;
}
_pthread_lock_unlock(&_pthread_list_lock);
}
//
// /!\ dereferencing `t` past this point is not safe /!\
//
if (keep_thread_struct || t == main_thread()) {
// Use the adjusted freesize of just the stack that we computed above.
freesize = freesize_stack;
} else {
_pthread_introspection_thread_destroy(t);
}
// Check if there is nothing to free because the thread has a custom
// stack allocation and is joinable.
if (freesize == 0) {
freeaddr = 0;
}
if (should_exit) {
exitf(0);
}
__bsdthread_terminate((void *)freeaddr, freesize, kport, custom_stack_sema);
PTHREAD_INTERNAL_CRASH(t, "thread didn't terminate");
}
OS_NORETURN
static void
_pthread_terminate_invoke(pthread_t t, void *exit_value)
{
#if PTHREAD_T_OFFSET
void *p = NULL;
// <rdar://problem/25688492> During pthread termination there is a race
// between pthread_join and pthread_terminate; if the joiner is responsible
// for cleaning up the pthread_t struct, then it may destroy some part of the
// stack with it on 16k OSes. So that this doesn't cause _pthread_terminate()
// to crash because its stack has been removed from under its feet, just make
// sure termination happens in a part of the stack that is not on the same
// page as the pthread_t.
if (trunc_page((uintptr_t)__builtin_frame_address(0)) ==
trunc_page((uintptr_t)t)) {
p = alloca(PTHREAD_T_OFFSET);
}
// And this __asm__ volatile is needed to stop the compiler from optimising
// away the alloca() completely.
__asm__ volatile ("" : : "r"(p) );
#endif
_pthread_terminate(t, exit_value);
}
#pragma mark pthread start / body
void
_pthread_start(pthread_t self, mach_port_t kport,
__unused void *(*fun)(void *), __unused void *arg,
__unused size_t stacksize, unsigned int pflags)
{
if (os_unlikely(pflags & PTHREAD_START_SUSPENDED)) {
PTHREAD_INTERNAL_CRASH(pflags,
"kernel without PTHREAD_START_SUSPENDED support");
}
if (os_unlikely((pflags & PTHREAD_START_TSD_BASE_SET) == 0)) {
PTHREAD_INTERNAL_CRASH(pflags,
"thread_set_tsd_base() wasn't called by the kernel");
}
PTHREAD_DEBUG_ASSERT(MACH_PORT_VALID(kport));
PTHREAD_DEBUG_ASSERT(_pthread_tsd_slot(self, MACH_THREAD_SELF) == kport);
_pthread_validate_signature(self);
_pthread_markcancel_if_canceled(self, kport);
_pthread_set_self_internal(self);
__pthread_started_thread(self);
_pthread_exit(self, (self->fun)(self->arg));
}
OS_ALWAYS_INLINE
static inline void
_pthread_struct_init(pthread_t t, const pthread_attr_t *attrs,
void *stackaddr, size_t stacksize, void *freeaddr, size_t freesize)
{
_pthread_init_signature(t);
_pthread_tsd_slot(t, PTHREAD_SELF) = t;
_pthread_tsd_slot(t, ERRNO) = &t->err_no;
if (attrs->schedset == 0) {
_pthread_tsd_slot(t, PTHREAD_QOS_CLASS) = attrs->qosclass;
} else {
_pthread_tsd_slot(t, PTHREAD_QOS_CLASS) =
_pthread_unspecified_priority();
}
_pthread_tsd_slot(t, PTR_MUNGE) = _pthread_ptr_munge_token;
t->tl_has_custom_stack = (attrs->stackaddr != NULL);
_pthread_lock_init(&t->lock);
t->stackaddr = stackaddr;
t->stackbottom = stackaddr - stacksize;
t->freeaddr = freeaddr;
t->freesize = freesize;
t->guardsize = _pthread_attr_guardsize(attrs);
t->tl_joinable = (attrs->detached == PTHREAD_CREATE_JOINABLE);
t->inherit = attrs->inherit;
t->tl_policy = attrs->policy;
t->schedset = attrs->schedset;
_pthread_attr_get_schedparam(attrs, &t->tl_param);
t->cancel_state = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
}
#pragma mark pthread public interface
/* Non portable public api to know whether this process has(had) atleast one thread
* apart from main thread. There could be race if there is a thread in the process of
* creation at the time of call . It does not tell whether there are more than one thread
* at this point of time.
*/
int
pthread_is_threaded_np(void)
{
return __is_threaded;
}
mach_port_t
pthread_mach_thread_np(pthread_t t)
{
mach_port_t kport = MACH_PORT_NULL;
(void)_pthread_is_valid(t, &kport);
return kport;
}
pthread_t
pthread_from_mach_thread_np(mach_port_t kernel_thread)
{
pthread_t p = NULL;
/* No need to wait as mach port is already known */
_pthread_lock_lock(&_pthread_list_lock);
TAILQ_FOREACH(p, &__pthread_head, tl_plist) {
if (_pthread_tsd_slot(p, MACH_THREAD_SELF) == kernel_thread) {
break;
}
}
_pthread_lock_unlock(&_pthread_list_lock);
return p;
}
size_t
pthread_get_stacksize_np(pthread_t t)
{
size_t size = 0;
if (t == NULL) {
return ESRCH; // XXX bug?
}
#if TARGET_OS_OSX
// The default rlimit based allocations will be provided with a stacksize
// of the current limit and a freesize of the max. However, custom
// allocations will just have the guard page to free. If we aren't in the
// latter case, call into rlimit to determine the current stack size. In
// the event that the current limit == max limit then we'll fall down the
// fast path, but since it's unlikely that the limit is going to be lowered
// after it's been change to the max, we should be fine.
//
// Of course, on arm rlim_cur == rlim_max and there's only the one guard
// page. So, we can skip all this there.
if (t == main_thread()) {
size_t stacksize = t->stackaddr - t->stackbottom;
if (stacksize + vm_page_size != t->freesize) {
// We want to call getrlimit() just once, as it's relatively
// expensive
static size_t rlimit_stack;
if (rlimit_stack == 0) {
struct rlimit limit;
int ret = getrlimit(RLIMIT_STACK, &limit);
if (ret == 0) {
rlimit_stack = (size_t) limit.rlim_cur;
}
}
if (rlimit_stack == 0 || rlimit_stack > t->freesize) {
return stacksize;
} else {
return round_page(rlimit_stack);
}
}