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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
|
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/atomics.h>
#include <bionic_tls.h>
#include <sys/mman.h>
#include <pthread.h>
#include <time.h>
#include "pthread_internal.h"
#include "thread_private.h"
#include <limits.h>
#include <memory.h>
#include <assert.h>
#include <malloc.h>
extern int __pthread_clone(int (*fn)(void*), void *child_stack, int flags, void *arg);
extern void _exit_with_stack_teardown(void * stackBase, int stackSize, int retCode);
extern void _exit_thread(int retCode);
extern int __set_errno(int);
void _thread_created_hook(pid_t thread_id) __attribute__((noinline));
#define PTHREAD_ATTR_FLAG_DETACHED 0x00000001
#define PTHREAD_ATTR_FLAG_USER_STACK 0x00000002
#define DEFAULT_STACKSIZE (1024 * 1024)
#define STACKBASE 0x10000000
static uint8_t * gStackBase = (uint8_t *)STACKBASE;
static pthread_mutex_t mmap_lock = PTHREAD_MUTEX_INITIALIZER;
static const pthread_attr_t gDefaultPthreadAttr = {
.flags = 0,
.stack_base = NULL,
.stack_size = DEFAULT_STACKSIZE,
.guard_size = PAGE_SIZE,
.sched_policy = SCHED_NORMAL,
.sched_priority = 0
};
#define INIT_THREADS 1
static pthread_internal_t* gThreadList = NULL;
static pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
/* we simply malloc/free the internal pthread_internal_t structures. we may
* want to use a different allocation scheme in the future, but this one should
* be largely enough
*/
static pthread_internal_t*
_pthread_internal_alloc(void)
{
pthread_internal_t* thread;
thread = calloc( sizeof(*thread), 1 );
if (thread)
thread->intern = 1;
return thread;
}
static void
_pthread_internal_free( pthread_internal_t* thread )
{
if (thread && thread->intern) {
thread->intern = 0; /* just in case */
free (thread);
}
}
static void
_pthread_internal_remove_locked( pthread_internal_t* thread )
{
thread->next->pref = thread->pref;
thread->pref[0] = thread->next;
}
static void
_pthread_internal_remove( pthread_internal_t* thread )
{
pthread_mutex_lock(&gThreadListLock);
_pthread_internal_remove_locked(thread);
pthread_mutex_unlock(&gThreadListLock);
}
static void
_pthread_internal_add( pthread_internal_t* thread )
{
pthread_mutex_lock(&gThreadListLock);
thread->pref = &gThreadList;
thread->next = thread->pref[0];
if (thread->next)
thread->next->pref = &thread->next;
thread->pref[0] = thread;
pthread_mutex_unlock(&gThreadListLock);
}
pthread_internal_t*
__get_thread(void)
{
void** tls = (void**)__get_tls();
return (pthread_internal_t*) tls[TLS_SLOT_THREAD_ID];
}
void*
__get_stack_base(int *p_stack_size)
{
pthread_internal_t* thread = __get_thread();
*p_stack_size = thread->attr.stack_size;
return thread->attr.stack_base;
}
void __init_tls(void** tls, void* thread)
{
int nn;
((pthread_internal_t*)thread)->tls = tls;
// slot 0 must point to the tls area, this is required by the implementation
// of the x86 Linux kernel thread-local-storage
tls[TLS_SLOT_SELF] = (void*)tls;
tls[TLS_SLOT_THREAD_ID] = thread;
for (nn = TLS_SLOT_ERRNO; nn < BIONIC_TLS_SLOTS; nn++)
tls[nn] = 0;
__set_tls( (void*)tls );
}
/*
* This trampoline is called from the assembly clone() function
*/
void __thread_entry(int (*func)(void*), void *arg, void **tls)
{
int retValue;
pthread_internal_t * thrInfo;
// Wait for our creating thread to release us. This lets it have time to
// notify gdb about this thread before it starts doing anything.
pthread_mutex_t * start_mutex = (pthread_mutex_t *)&tls[TLS_SLOT_SELF];
pthread_mutex_lock(start_mutex);
pthread_mutex_destroy(start_mutex);
thrInfo = (pthread_internal_t *) tls[TLS_SLOT_THREAD_ID];
__init_tls( tls, thrInfo );
pthread_exit( (void*)func(arg) );
}
void _init_thread(pthread_internal_t * thread, pid_t kernel_id, pthread_attr_t * attr, void * stack_base)
{
if (attr == NULL) {
thread->attr = gDefaultPthreadAttr;
} else {
thread->attr = *attr;
}
thread->attr.stack_base = stack_base;
thread->kernel_id = kernel_id;
// set the scheduling policy/priority of the thread
if (thread->attr.sched_policy != SCHED_NORMAL) {
struct sched_param param;
param.sched_priority = thread->attr.sched_priority;
sched_setscheduler(kernel_id, thread->attr.sched_policy, ¶m);
}
pthread_cond_init(&thread->join_cond, NULL);
thread->join_count = 0;
thread->cleanup_stack = NULL;
_pthread_internal_add(thread);
}
/* XXX stacks not reclaimed if thread spawn fails */
/* XXX stacks address spaces should be reused if available again */
static void *mkstack(size_t size, size_t guard_size)
{
void * stack;
pthread_mutex_lock(&mmap_lock);
stack = mmap((void *)gStackBase, size,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
-1, 0);
if(stack == MAP_FAILED) {
stack = NULL;
goto done;
}
if(mprotect(stack, guard_size, PROT_NONE)){
munmap(stack, size);
stack = NULL;
goto done;
}
done:
pthread_mutex_unlock(&mmap_lock);
return stack;
}
/*
* Create a new thread. The thread's stack is layed out like so:
*
* +---------------------------+
* | pthread_internal_t |
* +---------------------------+
* | |
* | TLS area |
* | |
* +---------------------------+
* | |
* . .
* . stack area .
* . .
* | |
* +---------------------------+
* | guard page |
* +---------------------------+
*
* note that TLS[0] must be a pointer to itself, this is required
* by the thread-local storage implementation of the x86 Linux
* kernel, where the TLS pointer is read by reading fs:[0]
*/
int pthread_create(pthread_t *thread_out, pthread_attr_t const * attr,
void *(*start_routine)(void *), void * arg)
{
char* stack;
void** tls;
int tid;
pthread_mutex_t * start_mutex;
pthread_internal_t * thread;
int madestack = 0;
int old_errno = errno;
/* this will inform the rest of the C library that at least one thread
* was created. this will enforce certain functions to acquire/release
* locks (e.g. atexit()) to protect shared global structures.
*
* this works because pthread_create() is not called by the C library
* initialization routine that sets up the main thread's data structures.
*/
__isthreaded = 1;
thread = _pthread_internal_alloc();
if (thread == NULL)
return ENOMEM;
if (attr == NULL) {
attr = &gDefaultPthreadAttr;
}
// make sure the stack is PAGE_SIZE aligned
size_t stackSize = (attr->stack_size +
(PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
if (!attr->stack_base) {
stack = mkstack(stackSize, attr->guard_size);
if(stack == NULL) {
_pthread_internal_free(thread);
return ENOMEM;
}
madestack = 1;
} else {
stack = attr->stack_base;
}
// Make room for TLS
tls = (void**)(stack + stackSize - BIONIC_TLS_SLOTS*sizeof(void*));
// Create a mutex for the thread in TLS_SLOT_SELF to wait on once it starts so we can keep
// it from doing anything until after we notify the debugger about it
start_mutex = (pthread_mutex_t *) &tls[TLS_SLOT_SELF];
pthread_mutex_init(start_mutex, NULL);
pthread_mutex_lock(start_mutex);
tls[TLS_SLOT_THREAD_ID] = thread;
tid = __pthread_clone((int(*)(void*))start_routine, tls,
CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND
| CLONE_THREAD | CLONE_SYSVSEM | CLONE_DETACHED,
arg);
if(tid < 0) {
int result;
if (madestack)
munmap(stack, stackSize);
_pthread_internal_free(thread);
result = errno;
errno = old_errno;
return result;
}
_init_thread(thread, tid, (pthread_attr_t*)attr, stack);
if (!madestack)
thread->attr.flags |= PTHREAD_ATTR_FLAG_USER_STACK;
// Notify any debuggers about the new thread
pthread_mutex_lock(&gDebuggerNotificationLock);
_thread_created_hook(tid);
pthread_mutex_unlock(&gDebuggerNotificationLock);
// Let the thread do it's thing
pthread_mutex_unlock(start_mutex);
*thread_out = (pthread_t)thread;
return 0;
}
int pthread_attr_init(pthread_attr_t * attr)
{
*attr = gDefaultPthreadAttr;
return 0;
}
int pthread_attr_destroy(pthread_attr_t * attr)
{
memset(attr, 0x42, sizeof(pthread_attr_t));
return 0;
}
int pthread_attr_setdetachstate(pthread_attr_t * attr, int state)
{
if (state == PTHREAD_CREATE_DETACHED) {
attr->flags |= PTHREAD_ATTR_FLAG_DETACHED;
} else if (state == PTHREAD_CREATE_JOINABLE) {
attr->flags &= ~PTHREAD_ATTR_FLAG_DETACHED;
} else {
return EINVAL;
}
return 0;
}
int pthread_attr_getdetachstate(pthread_attr_t const * attr, int * state)
{
*state = (attr->flags & PTHREAD_ATTR_FLAG_DETACHED)
? PTHREAD_CREATE_DETACHED
: PTHREAD_CREATE_JOINABLE;
return 0;
}
int pthread_attr_setschedpolicy(pthread_attr_t * attr, int policy)
{
attr->sched_policy = policy;
return 0;
}
int pthread_attr_getschedpolicy(pthread_attr_t const * attr, int * policy)
{
*policy = attr->sched_policy;
return 0;
}
int pthread_attr_setschedparam(pthread_attr_t * attr, struct sched_param const * param)
{
attr->sched_priority = param->sched_priority;
return 0;
}
int pthread_attr_getschedparam(pthread_attr_t const * attr, struct sched_param * param)
{
param->sched_priority = attr->sched_priority;
return 0;
}
int pthread_attr_setstacksize(pthread_attr_t * attr, size_t stack_size)
{
if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
return EINVAL;
}
attr->stack_size = stack_size;
return 0;
}
int pthread_attr_getstacksize(pthread_attr_t const * attr, size_t * stack_size)
{
*stack_size = attr->stack_size;
return 0;
}
int pthread_attr_setstackaddr(pthread_attr_t * attr, void * stack_addr)
{
#if 1
// It's not clear if this is setting the top or bottom of the stack, so don't handle it for now.
return ENOSYS;
#else
if ((uint32_t)stack_addr & (PAGE_SIZE - 1)) {
return EINVAL;
}
attr->stack_base = stack_addr;
return 0;
#endif
}
int pthread_attr_getstackaddr(pthread_attr_t const * attr, void ** stack_addr)
{
*stack_addr = attr->stack_base + attr->stack_size;
return 0;
}
int pthread_attr_setstack(pthread_attr_t * attr, void * stack_base, size_t stack_size)
{
if ((stack_size & (PAGE_SIZE - 1) || stack_size < PTHREAD_STACK_MIN)) {
return EINVAL;
}
if ((uint32_t)stack_base & (PAGE_SIZE - 1)) {
return EINVAL;
}
attr->stack_base = stack_base;
attr->stack_size = stack_size;
return 0;
}
int pthread_attr_getstack(pthread_attr_t const * attr, void ** stack_base, size_t * stack_size)
{
*stack_base = attr->stack_base;
*stack_size = attr->stack_size;
return 0;
}
int pthread_attr_setguardsize(pthread_attr_t * attr, size_t guard_size)
{
if (guard_size & (PAGE_SIZE - 1) || guard_size < PAGE_SIZE) {
return EINVAL;
}
attr->guard_size = guard_size;
return 0;
}
int pthread_attr_getguardsize(pthread_attr_t const * attr, size_t * guard_size)
{
*guard_size = attr->guard_size;
return 0;
}
int pthread_getattr_np(pthread_t thid, pthread_attr_t * attr)
{
pthread_internal_t * thread = (pthread_internal_t *)thid;
*attr = thread->attr;
return 0;
}
int pthread_attr_setscope(pthread_attr_t *attr, int scope)
{
if (scope == PTHREAD_SCOPE_SYSTEM)
return 0;
if (scope == PTHREAD_SCOPE_PROCESS)
return ENOTSUP;
return EINVAL;
}
int pthread_attr_getscope(pthread_attr_t const *attr)
{
return PTHREAD_SCOPE_SYSTEM;
}
/* CAVEAT: our implementation of pthread_cleanup_push/pop doesn't support C++ exceptions
* and thread cancelation
*/
void __pthread_cleanup_push( __pthread_cleanup_t* c,
__pthread_cleanup_func_t routine,
void* arg )
{
pthread_internal_t* thread = __get_thread();
c->__cleanup_routine = routine;
c->__cleanup_arg = arg;
c->__cleanup_prev = thread->cleanup_stack;
thread->cleanup_stack = c;
}
void __pthread_cleanup_pop( __pthread_cleanup_t* c, int execute )
{
pthread_internal_t* thread = __get_thread();
thread->cleanup_stack = c->__cleanup_prev;
if (execute)
c->__cleanup_routine(c->__cleanup_arg);
}
/* used by pthread_exit() to clean all TLS keys of the current thread */
static void pthread_key_clean_all(void);
void pthread_exit(void * retval)
{
pthread_internal_t* thread = __get_thread();
void* stack_base = thread->attr.stack_base;
int stack_size = thread->attr.stack_size;
int user_stack = (thread->attr.flags & PTHREAD_ATTR_FLAG_USER_STACK) != 0;
// call the cleanup handlers first
while (thread->cleanup_stack) {
__pthread_cleanup_t* c = thread->cleanup_stack;
thread->cleanup_stack = c->__cleanup_prev;
c->__cleanup_routine(c->__cleanup_arg);
}
// call the TLS destructors, it is important to do that before removing this
// thread from the global list. this will ensure that if someone else deletes
// a TLS key, the corresponding value will be set to NULL in this thread's TLS
// space (see pthread_key_delete)
pthread_key_clean_all();
// if the thread is detached, destroy the pthread_internal_t
// otherwise, keep it in memory and signal any joiners
if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
_pthread_internal_remove(thread);
_pthread_internal_free(thread);
} else {
/* the join_count field is used to store the number of threads waiting for
* the termination of this thread with pthread_join(),
*
* if it is positive we need to signal the waiters, and we do not touch
* the count (it will be decremented by the waiters, the last one will
* also remove/free the thread structure
*
* if it is zero, we set the count value to -1 to indicate that the
* thread is in 'zombie' state: it has stopped executing, and its stack
* is gone (as well as its TLS area). when another thread calls pthread_join()
* on it, it will immediately free the thread and return.
*/
pthread_mutex_lock(&gThreadListLock);
thread->return_value = retval;
if (thread->join_count > 0) {
pthread_cond_broadcast(&thread->join_cond);
} else {
thread->join_count = -1; /* zombie thread */
}
pthread_mutex_unlock(&gThreadListLock);
}
// destroy the thread stack
if (user_stack)
_exit_thread((int)retval);
else
_exit_with_stack_teardown(stack_base, stack_size, (int)retval);
}
int pthread_join(pthread_t thid, void ** ret_val)
{
pthread_internal_t* thread = (pthread_internal_t*)thid;
int count;
// check that the thread still exists and is not detached
pthread_mutex_lock(&gThreadListLock);
for (thread = gThreadList; thread != NULL; thread = thread->next)
if (thread == (pthread_internal_t*)thid)
break;
if (!thread) {
pthread_mutex_unlock(&gThreadListLock);
return ESRCH;
}
if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
pthread_mutex_unlock(&gThreadListLock);
return EINVAL;
}
/* wait for thread death when needed
*
* if the 'join_count' is negative, this is a 'zombie' thread that
* is already dead and without stack/TLS
*
* otherwise, we need to increment 'join-count' and wait to be signaled
*/
count = thread->join_count;
if (count >= 0) {
thread->join_count += 1;
pthread_cond_wait( &thread->join_cond, &gThreadListLock );
count = --thread->join_count;
}
if (ret_val)
*ret_val = thread->return_value;
/* remove thread descriptor when we're the last joiner or when the
* thread was already a zombie.
*/
if (count <= 0) {
_pthread_internal_remove_locked(thread);
_pthread_internal_free(thread);
}
pthread_mutex_unlock(&gThreadListLock);
return 0;
}
int pthread_detach( pthread_t thid )
{
pthread_internal_t* thread;
int result = 0;
int flags;
pthread_mutex_lock(&gThreadListLock);
for (thread = gThreadList; thread != NULL; thread = thread->next)
if (thread == (pthread_internal_t*)thid)
goto FoundIt;
result = ESRCH;
goto Exit;
FoundIt:
do {
flags = thread->attr.flags;
if ( flags & PTHREAD_ATTR_FLAG_DETACHED ) {
/* thread is not joinable ! */
result = EINVAL;
goto Exit;
}
}
while ( __atomic_cmpxchg( flags, flags | PTHREAD_ATTR_FLAG_DETACHED,
(volatile int*)&thread->attr.flags ) != 0 );
Exit:
pthread_mutex_unlock(&gThreadListLock);
return result;
}
pthread_t pthread_self(void)
{
return (pthread_t)__get_thread();
}
int pthread_equal(pthread_t one, pthread_t two)
{
return (one == two ? 1 : 0);
}
int pthread_getschedparam(pthread_t thid, int * policy,
struct sched_param * param)
{
int old_errno = errno;
pthread_internal_t * thread = (pthread_internal_t *)thid;
int err = sched_getparam(thread->kernel_id, param);
if (!err) {
*policy = sched_getscheduler(thread->kernel_id);
} else {
err = errno;
errno = old_errno;
}
return err;
}
int pthread_setschedparam(pthread_t thid, int policy,
struct sched_param const * param)
{
pthread_internal_t * thread = (pthread_internal_t *)thid;
int old_errno = errno;
int ret;
ret = sched_setscheduler(thread->kernel_id, policy, param);
if (ret < 0) {
ret = errno;
errno = old_errno;
}
return ret;
}
int __futex_wait(volatile void *ftx, int val, const struct timespec *timeout);
int __futex_wake(volatile void *ftx, int count);
// mutex lock states
//
// 0: unlocked
// 1: locked, no waiters
// 2: locked, maybe waiters
/* a mutex is implemented as a 32-bit integer holding the following fields
*
* bits: name description
* 31-16 tid owner thread's kernel id (recursive and errorcheck only)
* 15-14 type mutex type
* 13-2 counter counter of recursive mutexes
* 1-0 state lock state (0, 1 or 2)
*/
#define MUTEX_OWNER(m) (((m)->value >> 16) & 0xffff)
#define MUTEX_COUNTER(m) (((m)->value >> 2) & 0xfff)
#define MUTEX_TYPE_MASK 0xc000
#define MUTEX_TYPE_NORMAL 0x0000
#define MUTEX_TYPE_RECURSIVE 0x4000
#define MUTEX_TYPE_ERRORCHECK 0x8000
#define MUTEX_COUNTER_SHIFT 2
#define MUTEX_COUNTER_MASK 0x3ffc
int pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
if (attr) {
*attr = PTHREAD_MUTEX_DEFAULT;
return 0;
} else {
return EINVAL;
}
}
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
if (attr) {
*attr = -1;
return 0;
} else {
return EINVAL;
}
}
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
{
if (attr && *attr >= PTHREAD_MUTEX_NORMAL &&
*attr <= PTHREAD_MUTEX_ERRORCHECK ) {
*type = *attr;
return 0;
}
return EINVAL;
}
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
if (attr && type >= PTHREAD_MUTEX_NORMAL &&
type <= PTHREAD_MUTEX_ERRORCHECK ) {
*attr = type;
return 0;
}
return EINVAL;
}
/* process-shared mutexes are not supported at the moment */
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
{
if (!attr)
return EINVAL;
return (pshared == PTHREAD_PROCESS_PRIVATE) ? 0 : ENOTSUP;
}
int pthread_mutexattr_getpshared(pthread_mutexattr_t *attr, int *pshared)
{
if (!attr)
return EINVAL;
*pshared = PTHREAD_PROCESS_PRIVATE;
return 0;
}
int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr)
{
if ( mutex ) {
if (attr == NULL) {
mutex->value = MUTEX_TYPE_NORMAL;
return 0;
}
switch ( *attr ) {
case PTHREAD_MUTEX_NORMAL:
mutex->value = MUTEX_TYPE_NORMAL;
return 0;
case PTHREAD_MUTEX_RECURSIVE:
mutex->value = MUTEX_TYPE_RECURSIVE;
return 0;
case PTHREAD_MUTEX_ERRORCHECK:
mutex->value = MUTEX_TYPE_ERRORCHECK;
return 0;
}
}
return EINVAL;
}
int pthread_mutex_destroy(pthread_mutex_t *mutex)
{
mutex->value = 0xdead10cc;
return 0;
}
/*
* Lock a non-recursive mutex.
*
* As noted above, there are three states:
* 0 (unlocked, no contention)
* 1 (locked, no contention)
* 2 (locked, contention)
*
* Non-recursive mutexes don't use the thread-id or counter fields, and the
* "type" value is zero, so the only bits that will be set are the ones in
* the lock state field.
*/
static __inline__ void
_normal_lock(pthread_mutex_t* mutex)
{
/*
* The common case is an unlocked mutex, so we begin by trying to
* change the lock's state from 0 to 1. __atomic_cmpxchg() returns 0
* if it made the swap successfully. If the result is nonzero, this
* lock is already held by another thread.
*/
if (__atomic_cmpxchg(0, 1, &mutex->value ) != 0) {
/*
* We want to go to sleep until the mutex is available, which
* requires promoting it to state 2. We need to swap in the new
* state value and then wait until somebody wakes us up.
*
* __atomic_swap() returns the previous value. We swap 2 in and
* see if we got zero back; if so, we have acquired the lock. If
* not, another thread still holds the lock and we wait again.
*
* The second argument to the __futex_wait() call is compared
* against the current value. If it doesn't match, __futex_wait()
* returns immediately (otherwise, it sleeps for a time specified
* by the third argument; 0 means sleep forever). This ensures
* that the mutex is in state 2 when we go to sleep on it, which
* guarantees a wake-up call.
*/
while (__atomic_swap(2, &mutex->value ) != 0)
__futex_wait(&mutex->value, 2, 0);
}
}
/*
* Release a non-recursive mutex. The caller is responsible for determining
* that we are in fact the owner of this lock.
*/
static __inline__ void
_normal_unlock(pthread_mutex_t* mutex)
{
/*
* The mutex value will be 1 or (rarely) 2. We use an atomic decrement
* to release the lock. __atomic_dec() returns the previous value;
* if it wasn't 1 we have to do some additional work.
*/
if (__atomic_dec(&mutex->value) != 1) {
/*
* Start by releasing the lock. The decrement changed it from
* "contended lock" to "uncontended lock", which means we still
* hold it, and anybody who tries to sneak in will push it back
* to state 2.
*
* Once we set it to zero the lock is up for grabs. We follow
* this with a __futex_wake() to ensure that one of the waiting
* threads has a chance to grab it.
*
* This doesn't cause a race with the swap/wait pair in
* _normal_lock(), because the __futex_wait() call there will
* return immediately if the mutex value isn't 2.
*/
mutex->value = 0;
/*
* Wake up one waiting thread. We don't know which thread will be
* woken or when it'll start executing -- futexes make no guarantees
* here. There may not even be a thread waiting.
*
* The newly-woken thread will replace the 0 we just set above
* with 2, which means that when it eventually releases the mutex
* it will also call FUTEX_WAKE. This results in one extra wake
* call whenever a lock is contended, but lets us avoid forgetting
* anyone without requiring us to track the number of sleepers.
*
* It's possible for another thread to sneak in and grab the lock
* between the zero assignment above and the wake call below. If
* the new thread is "slow" and holds the lock for a while, we'll
* wake up a sleeper, which will swap in a 2 and then go back to
* sleep since the lock is still held. If the new thread is "fast",
* running to completion before we call wake, the thread we
* eventually wake will find an unlocked mutex and will execute.
* Either way we have correct behavior and nobody is orphaned on
* the wait queue.
*/
__futex_wake(&mutex->value, 1);
}
}
static pthread_mutex_t __recursive_lock = PTHREAD_MUTEX_INITIALIZER;
static void
_recursive_lock(void)
{
_normal_lock( &__recursive_lock);
}
static void
_recursive_unlock(void)
{
_normal_unlock( &__recursive_lock );
}
#define __likely(cond) __builtin_expect(!!(cond), 1)
#define __unlikely(cond) __builtin_expect(!!(cond), 0)
int pthread_mutex_lock(pthread_mutex_t *mutex)
{
if (__likely(mutex != NULL))
{
int mtype = (mutex->value & MUTEX_TYPE_MASK);
if ( __likely(mtype == MUTEX_TYPE_NORMAL) ) {
_normal_lock(mutex);
}
else
{
int tid = __get_thread()->kernel_id;
if ( tid == MUTEX_OWNER(mutex) )
{
int oldv, counter;
if (mtype == MUTEX_TYPE_ERRORCHECK) {
/* trying to re-lock a mutex we already acquired */
return EDEADLK;
}
/*
* We own the mutex, but other threads are able to change
* the contents (e.g. promoting it to "contended"), so we
* need to hold the global lock.
*/
_recursive_lock();
oldv = mutex->value;
counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
_recursive_unlock();
}
else
{
/*
* If the new lock is available immediately, we grab it in
* the "uncontended" state.
*/
int new_lock_type = 1;
for (;;) {
int oldv;
_recursive_lock();
oldv = mutex->value;
if (oldv == mtype) { /* uncontended released lock => 1 or 2 */
mutex->value = ((tid << 16) | mtype | new_lock_type);
} else if ((oldv & 3) == 1) { /* locked state 1 => state 2 */
oldv ^= 3;
mutex->value = oldv;
}
_recursive_unlock();
if (oldv == mtype)
break;
/*
* The lock was held, possibly contended by others. From
* now on, if we manage to acquire the lock, we have to
* assume that others are still contending for it so that
* we'll wake them when we unlock it.
*/
new_lock_type = 2;
__futex_wait( &mutex->value, oldv, 0 );
}
}
}
return 0;
}
return EINVAL;
}
int pthread_mutex_unlock(pthread_mutex_t *mutex)
{
if (__likely(mutex != NULL))
{
int mtype = (mutex->value & MUTEX_TYPE_MASK);
if (__likely(mtype == MUTEX_TYPE_NORMAL)) {
_normal_unlock(mutex);
}
else
{
int tid = __get_thread()->kernel_id;
if ( tid == MUTEX_OWNER(mutex) )
{
int oldv;
_recursive_lock();
oldv = mutex->value;
if (oldv & MUTEX_COUNTER_MASK) {
mutex->value = oldv - (1 << MUTEX_COUNTER_SHIFT);
oldv = 0;
} else {
mutex->value = mtype;
}
_recursive_unlock();
if ((oldv & 3) == 2)
__futex_wake( &mutex->value, 1 );
}
else {
/* trying to unlock a lock we do not own */
return EPERM;
}
}
return 0;
}
return EINVAL;
}
int pthread_mutex_trylock(pthread_mutex_t *mutex)
{
if (__likely(mutex != NULL))
{
int mtype = (mutex->value & MUTEX_TYPE_MASK);
if ( __likely(mtype == MUTEX_TYPE_NORMAL) )
{
if (__atomic_cmpxchg(0, 1, &mutex->value) == 0)
return 0;
return EBUSY;
}
else
{
int tid = __get_thread()->kernel_id;
int oldv;
if ( tid == MUTEX_OWNER(mutex) )
{
int oldv, counter;
if (mtype == MUTEX_TYPE_ERRORCHECK) {
/* already locked by ourselves */
return EDEADLK;
}
_recursive_lock();
oldv = mutex->value;
counter = (oldv + (1 << MUTEX_COUNTER_SHIFT)) & MUTEX_COUNTER_MASK;
mutex->value = (oldv & ~MUTEX_COUNTER_MASK) | counter;
_recursive_unlock();
return 0;
}
/* try to lock it */
_recursive_lock();
oldv = mutex->value;
if (oldv == mtype) /* uncontended released lock => state 1 */
mutex->value = ((tid << 16) | mtype | 1);
_recursive_unlock();
if (oldv != mtype)
return EBUSY;
return 0;
}
}
return EINVAL;
}
/* XXX *technically* there is a race condition that could allow
* XXX a signal to be missed. If thread A is preempted in _wait()
* XXX after unlocking the mutex and before waiting, and if other
* XXX threads call signal or broadcast UINT_MAX times (exactly),
* XXX before thread A is scheduled again and calls futex_wait(),
* XXX then the signal will be lost.
*/
int pthread_cond_init(pthread_cond_t *cond,
const pthread_condattr_t *attr)
{
cond->value = 0;
return 0;
}
int pthread_cond_destroy(pthread_cond_t *cond)
{
cond->value = 0xdeadc04d;
return 0;
}
int pthread_cond_broadcast(pthread_cond_t *cond)
{
__atomic_dec(&cond->value);
__futex_wake(&cond->value, INT_MAX);
return 0;
}
int pthread_cond_signal(pthread_cond_t *cond)
{
__atomic_dec(&cond->value);
__futex_wake(&cond->value, 1);
return 0;
}
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
return pthread_cond_timedwait(cond, mutex, NULL);
}
int __pthread_cond_timedwait_relative(pthread_cond_t *cond,
pthread_mutex_t * mutex,
const struct timespec *reltime)
{
int status;
int oldvalue = cond->value;
pthread_mutex_unlock(mutex);
status = __futex_wait(&cond->value, oldvalue, reltime);
pthread_mutex_lock(mutex);
if (status == (-ETIMEDOUT)) return ETIMEDOUT;
return 0;
}
int __pthread_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t * mutex,
const struct timespec *abstime,
clockid_t clock)
{
struct timespec ts;
struct timespec * tsp;
if (abstime != NULL) {
clock_gettime(clock, &ts);
ts.tv_sec = abstime->tv_sec - ts.tv_sec;
ts.tv_nsec = abstime->tv_nsec - ts.tv_nsec;
if (ts.tv_nsec < 0) {
ts.tv_sec--;
ts.tv_nsec += 1000000000;
}
if((ts.tv_nsec < 0) || (ts.tv_sec < 0)) {
return ETIMEDOUT;
}
tsp = &ts;
} else {
tsp = NULL;
}
return __pthread_cond_timedwait_relative(cond, mutex, tsp);
}
int pthread_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t * mutex,
const struct timespec *abstime)
{
return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_REALTIME);
}
int pthread_cond_timedwait_monotonic(pthread_cond_t *cond,
pthread_mutex_t * mutex,
const struct timespec *abstime)
{
return __pthread_cond_timedwait(cond, mutex, abstime, CLOCK_MONOTONIC);
}
int pthread_cond_timeout_np(pthread_cond_t *cond,
pthread_mutex_t * mutex,
unsigned msecs)
{
int oldvalue;
struct timespec ts;
int status;
ts.tv_sec = msecs / 1000;
ts.tv_nsec = (msecs % 1000) * 1000000;
oldvalue = cond->value;
pthread_mutex_unlock(mutex);
status = __futex_wait(&cond->value, oldvalue, &ts);
pthread_mutex_lock(mutex);
if(status == (-ETIMEDOUT)) return ETIMEDOUT;
return 0;
}
/* A technical note regarding our thread-local-storage (TLS) implementation:
*
* There can be up to TLSMAP_SIZE independent TLS keys in a given process,
* though the first TLSMAP_START keys are reserved for Bionic to hold
* special thread-specific variables like errno or a pointer to
* the current thread's descriptor.
*
* while stored in the TLS area, these entries cannot be accessed through
* pthread_getspecific() / pthread_setspecific() and pthread_key_delete()
*
* also, some entries in the key table are pre-allocated (see tlsmap_lock)
* to greatly simplify and speedup some OpenGL-related operations. though the
* initialy value will be NULL on all threads.
*
* you can use pthread_getspecific()/setspecific() on these, and in theory
* you could also call pthread_key_delete() as well, though this would
* probably break some apps.
*
* The 'tlsmap_t' type defined below implements a shared global map of
* currently created/allocated TLS keys and the destructors associated
* with them. You should use tlsmap_lock/unlock to access it to avoid
* any race condition.
*
* the global TLS map simply contains a bitmap of allocated keys, and
* an array of destructors.
*
* each thread has a TLS area that is a simple array of TLSMAP_SIZE void*
* pointers. the TLS area of the main thread is stack-allocated in
* __libc_init_common, while the TLS area of other threads is placed at
* the top of their stack in pthread_create.
*
* when pthread_key_create() is called, it finds the first free key in the
* bitmap, then set it to 1, saving the destructor altogether
*
* when pthread_key_delete() is called. it will erase the key's bitmap bit
* and its destructor, and will also clear the key data in the TLS area of
* all created threads. As mandated by Posix, it is the responsability of
* the caller of pthread_key_delete() to properly reclaim the objects that
* were pointed to by these data fields (either before or after the call).
*
*/
/* TLS Map implementation
*/
#define TLSMAP_START (TLS_SLOT_MAX_WELL_KNOWN+1)
#define TLSMAP_SIZE BIONIC_TLS_SLOTS
#define TLSMAP_BITS 32
#define TLSMAP_WORDS ((TLSMAP_SIZE+TLSMAP_BITS-1)/TLSMAP_BITS)
#define TLSMAP_WORD(m,k) (m)->map[(k)/TLSMAP_BITS]
#define TLSMAP_MASK(k) (1U << ((k)&(TLSMAP_BITS-1)))
/* this macro is used to quickly check that a key belongs to a reasonable range */
#define TLSMAP_VALIDATE_KEY(key) \
((key) >= TLSMAP_START && (key) < TLSMAP_SIZE)
/* the type of tls key destructor functions */
typedef void (*tls_dtor_t)(void*);
typedef struct {
int init; /* see comment in tlsmap_lock() */
uint32_t map[TLSMAP_WORDS]; /* bitmap of allocated keys */
tls_dtor_t dtors[TLSMAP_SIZE]; /* key destructors */
} tlsmap_t;
static pthread_mutex_t _tlsmap_lock = PTHREAD_MUTEX_INITIALIZER;
static tlsmap_t _tlsmap;
/* lock the global TLS map lock and return a handle to it */
static __inline__ tlsmap_t* tlsmap_lock(void)
{
tlsmap_t* m = &_tlsmap;
pthread_mutex_lock(&_tlsmap_lock);
/* we need to initialize the first entry of the 'map' array
* with the value TLS_DEFAULT_ALLOC_MAP. doing it statically
* when declaring _tlsmap is a bit awkward and is going to
* produce warnings, so do it the first time we use the map
* instead
*/
if (__unlikely(!m->init)) {
TLSMAP_WORD(m,0) = TLS_DEFAULT_ALLOC_MAP;
m->init = 1;
}
return m;
}
/* unlock the global TLS map */
static __inline__ void tlsmap_unlock(tlsmap_t* m)
{
pthread_mutex_unlock(&_tlsmap_lock);
(void)m; /* a good compiler is a happy compiler */
}
/* test to see wether a key is allocated */
static __inline__ int tlsmap_test(tlsmap_t* m, int key)
{
return (TLSMAP_WORD(m,key) & TLSMAP_MASK(key)) != 0;
}
/* set the destructor and bit flag on a newly allocated key */
static __inline__ void tlsmap_set(tlsmap_t* m, int key, tls_dtor_t dtor)
{
TLSMAP_WORD(m,key) |= TLSMAP_MASK(key);
m->dtors[key] = dtor;
}
/* clear the destructor and bit flag on an existing key */
static __inline__ void tlsmap_clear(tlsmap_t* m, int key)
{
TLSMAP_WORD(m,key) &= ~TLSMAP_MASK(key);
m->dtors[key] = NULL;
}
/* allocate a new TLS key, return -1 if no room left */
static int tlsmap_alloc(tlsmap_t* m, tls_dtor_t dtor)
{
int key;
for ( key = TLSMAP_START; key < TLSMAP_SIZE; key++ ) {
if ( !tlsmap_test(m, key) ) {
tlsmap_set(m, key, dtor);
return key;
}
}
return -1;
}
int pthread_key_create(pthread_key_t *key, void (*destructor_function)(void *))
{
uint32_t err = ENOMEM;
tlsmap_t* map = tlsmap_lock();
int k = tlsmap_alloc(map, destructor_function);
if (k >= 0) {
*key = k;
err = 0;
}
tlsmap_unlock(map);
return err;
}
/* This deletes a pthread_key_t. note that the standard mandates that this does
* not call the destructor of non-NULL key values. Instead, it is the
* responsability of the caller to properly dispose of the corresponding data
* and resources, using any mean it finds suitable.
*
* On the other hand, this function will clear the corresponding key data
* values in all known threads. this prevents later (invalid) calls to
* pthread_getspecific() to receive invalid/stale values.
*/
int pthread_key_delete(pthread_key_t key)
{
uint32_t err;
pthread_internal_t* thr;
tlsmap_t* map;
if (!TLSMAP_VALIDATE_KEY(key)) {
return EINVAL;
}
map = tlsmap_lock();
if (!tlsmap_test(map, key)) {
err = EINVAL;
goto err1;
}
/* clear value in all threads */
pthread_mutex_lock(&gThreadListLock);
for ( thr = gThreadList; thr != NULL; thr = thr->next ) {
/* avoid zombie threads with a negative 'join_count'. these are really
* already dead and don't have a TLS area anymore.
*
* similarly, it is possible to have thr->tls == NULL for threads that
* were just recently created through pthread_create() but whose
* startup trampoline (__thread_entry) hasn't been run yet by the
* scheduler. so check for this too.
*/
if (thr->join_count < 0 || !thr->tls)
continue;
thr->tls[key] = NULL;
}
tlsmap_clear(map, key);
pthread_mutex_unlock(&gThreadListLock);
err = 0;
err1:
tlsmap_unlock(map);
return err;
}
int pthread_setspecific(pthread_key_t key, const void *ptr)
{
int err = EINVAL;
tlsmap_t* map;
if (TLSMAP_VALIDATE_KEY(key)) {
/* check that we're trying to set data for an allocated key */
map = tlsmap_lock();
if (tlsmap_test(map, key)) {
((uint32_t *)__get_tls())[key] = (uint32_t)ptr;
err = 0;
}
tlsmap_unlock(map);
}
return err;
}
void * pthread_getspecific(pthread_key_t key)
{
if (!TLSMAP_VALIDATE_KEY(key)) {
return NULL;
}
/* for performance reason, we do not lock/unlock the global TLS map
* to check that the key is properly allocated. if the key was not
* allocated, the value read from the TLS should always be NULL
* due to pthread_key_delete() clearing the values for all threads.
*/
return (void *)(((unsigned *)__get_tls())[key]);
}
/* Posix mandates that this be defined in <limits.h> but we don't have
* it just yet.
*/
#ifndef PTHREAD_DESTRUCTOR_ITERATIONS
# define PTHREAD_DESTRUCTOR_ITERATIONS 4
#endif
/* this function is called from pthread_exit() to remove all TLS key data
* from this thread's TLS area. this must call the destructor of all keys
* that have a non-NULL data value (and a non-NULL destructor).
*
* because destructors can do funky things like deleting/creating other
* keys, we need to implement this in a loop
*/
static void pthread_key_clean_all(void)
{
tlsmap_t* map;
void** tls = (void**)__get_tls();
int rounds = PTHREAD_DESTRUCTOR_ITERATIONS;
map = tlsmap_lock();
for (rounds = PTHREAD_DESTRUCTOR_ITERATIONS; rounds > 0; rounds--)
{
int kk, count = 0;
for (kk = TLSMAP_START; kk < TLSMAP_SIZE; kk++) {
if ( tlsmap_test(map, kk) )
{
void* data = tls[kk];
tls_dtor_t dtor = map->dtors[kk];
if (data != NULL && dtor != NULL)
{
/* we need to clear the key data now, this will prevent the
* destructor (or a later one) from seeing the old value if
* it calls pthread_getspecific() for some odd reason
*
* we do not do this if 'dtor == NULL' just in case another
* destructor function might be responsible for manually
* releasing the corresponding data.
*/
tls[kk] = NULL;
/* because the destructor is free to call pthread_key_create
* and/or pthread_key_delete, we need to temporarily unlock
* the TLS map
*/
tlsmap_unlock(map);
(*dtor)(data);
map = tlsmap_lock();
count += 1;
}
}
}
/* if we didn't call any destructor, there is no need to check the
* TLS data again
*/
if (count == 0)
break;
}
tlsmap_unlock(map);
}
// man says this should be in <linux/unistd.h>, but it isn't
extern int tkill(int tid, int sig);
int pthread_kill(pthread_t tid, int sig)
{
int ret;
int old_errno = errno;
pthread_internal_t * thread = (pthread_internal_t *)tid;
ret = tkill(thread->kernel_id, sig);
if (ret < 0) {
ret = errno;
errno = old_errno;
}
return ret;
}
extern int __rt_sigprocmask(int, const sigset_t *, sigset_t *, size_t);
int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
{
return __rt_sigprocmask(how, set, oset, _NSIG / 8);
}
int pthread_getcpuclockid(pthread_t tid, clockid_t *clockid)
{
const int CLOCK_IDTYPE_BITS = 3;
pthread_internal_t* thread = (pthread_internal_t*)tid;
if (!thread)
return ESRCH;
*clockid = CLOCK_THREAD_CPUTIME_ID | (thread->kernel_id << CLOCK_IDTYPE_BITS);
return 0;
}
/* NOTE: this implementation doesn't support a init function that throws a C++ exception
* or calls fork()
*/
int pthread_once( pthread_once_t* once_control, void (*init_routine)(void) )
{
static pthread_mutex_t once_lock = PTHREAD_MUTEX_INITIALIZER;
if (*once_control == PTHREAD_ONCE_INIT) {
_normal_lock( &once_lock );
if (*once_control == PTHREAD_ONCE_INIT) {
(*init_routine)();
*once_control = ~PTHREAD_ONCE_INIT;
}
_normal_unlock( &once_lock );
}
return 0;
}
|