-
Notifications
You must be signed in to change notification settings - Fork 406
/
pthread_support.c
3182 lines (2863 loc) · 99.1 KB
/
pthread_support.c
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) 1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1996 by Silicon Graphics. All rights reserved.
* Copyright (c) 1998 by Fergus Henderson. All rights reserved.
* Copyright (c) 2000-2008 by Hewlett-Packard Company. All rights reserved.
* Copyright (c) 2008-2022 Ivan Maidanski
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
#include "private/pthread_support.h"
/*
* Support code originally for LinuxThreads, the clone()-based kernel
* thread package for Linux which is included in libc6.
*
* This code no doubt makes some assumptions beyond what is
* guaranteed by the pthread standard, though it now does
* very little of that. It now also supports NPTL, and many
* other Posix thread implementations. We are trying to merge
* all flavors of pthread support code into this file.
*/
#ifdef THREADS
# ifdef GC_PTHREADS
# if defined(DARWIN) \
|| (defined(GC_WIN32_THREADS) && defined(EMULATE_PTHREAD_SEMAPHORE))
# include "private/darwin_semaphore.h"
# elif !defined(SN_TARGET_ORBIS) && !defined(SN_TARGET_PSP2)
# include <semaphore.h>
# endif
# include <errno.h>
# endif /* GC_PTHREADS */
# if !defined(GC_WIN32_THREADS)
# include <sched.h>
# include <time.h>
# if !defined(SN_TARGET_ORBIS) && !defined(SN_TARGET_PSP2)
# ifndef RTEMS
# include <sys/mman.h>
# endif
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/time.h>
# endif
# if defined(GC_EXPLICIT_SIGNALS_UNBLOCK) \
|| !defined(GC_NO_PTHREAD_SIGMASK) \
|| (defined(GC_PTHREADS_PARAMARK) \
&& !defined(NO_MARKER_SPECIAL_SIGMASK))
# include <signal.h>
# endif
# endif /* !GC_WIN32_THREADS */
# ifdef E2K
# include <alloca.h>
# endif
# if defined(DARWIN) || defined(ANY_BSD)
# if defined(NETBSD) || defined(OPENBSD)
# include <sys/param.h>
# endif
# include <sys/sysctl.h>
# elif defined(DGUX)
# include <sys/_int_psem.h>
# include <sys/dg_sys_info.h>
/* sem_t is an uint in DG/UX */
typedef unsigned int sem_t;
# endif
# if defined(GC_PTHREADS) && !defined(SN_TARGET_ORBIS) \
&& !defined(SN_TARGET_PSP2)
/* Undefine macros used to redirect pthread primitives. */
# undef pthread_create
# ifndef GC_NO_PTHREAD_SIGMASK
# undef pthread_sigmask
# endif
# ifndef GC_NO_PTHREAD_CANCEL
# undef pthread_cancel
# endif
# ifdef GC_HAVE_PTHREAD_EXIT
# undef pthread_exit
# endif
# undef pthread_join
# undef pthread_detach
# if defined(OSF1) && defined(_PTHREAD_USE_MANGLED_NAMES_) \
&& !defined(_PTHREAD_USE_PTDNAM_)
/* Restore the original mangled names on Tru64 UNIX. */
# define pthread_create __pthread_create
# define pthread_join __pthread_join
# define pthread_detach __pthread_detach
# ifndef GC_NO_PTHREAD_CANCEL
# define pthread_cancel __pthread_cancel
# endif
# ifdef GC_HAVE_PTHREAD_EXIT
# define pthread_exit __pthread_exit
# endif
# endif
# endif /* GC_PTHREADS */
# if !defined(GC_WIN32_THREADS) && !defined(SN_TARGET_ORBIS) \
&& !defined(SN_TARGET_PSP2)
/* TODO: Enable GC_USE_DLOPEN_WRAP for Cygwin? */
# ifdef GC_USE_LD_WRAP
# define WRAP_FUNC(f) __wrap_##f
# define REAL_FUNC(f) __real_##f
int REAL_FUNC(pthread_create)(pthread_t *,
GC_PTHREAD_CREATE_CONST pthread_attr_t *,
void *(*start_routine)(void *), void *);
int REAL_FUNC(pthread_join)(pthread_t, void **);
int REAL_FUNC(pthread_detach)(pthread_t);
# ifndef GC_NO_PTHREAD_SIGMASK
int REAL_FUNC(pthread_sigmask)(int, const sigset_t *, sigset_t *);
# endif
# ifndef GC_NO_PTHREAD_CANCEL
int REAL_FUNC(pthread_cancel)(pthread_t);
# endif
# ifdef GC_HAVE_PTHREAD_EXIT
void REAL_FUNC(pthread_exit)(void *) GC_PTHREAD_EXIT_ATTRIBUTE;
# endif
# elif defined(GC_USE_DLOPEN_WRAP)
# include <dlfcn.h>
# define WRAP_FUNC(f) f
# define REAL_FUNC(f) GC_real_##f
/* We define both GC_f and plain f to be the wrapped function. */
/* In that way plain calls work, as do calls from files that */
/* included gc.h, which redefined f to GC_f. */
/* FIXME: Needs work for DARWIN and True64 (OSF1) */
typedef int (*GC_pthread_create_t)(pthread_t *,
GC_PTHREAD_CREATE_CONST pthread_attr_t *,
void *(*)(void *), void *);
static GC_pthread_create_t REAL_FUNC(pthread_create);
# ifndef GC_NO_PTHREAD_SIGMASK
typedef int (*GC_pthread_sigmask_t)(int, const sigset_t *, sigset_t *);
static GC_pthread_sigmask_t REAL_FUNC(pthread_sigmask);
# endif
typedef int (*GC_pthread_join_t)(pthread_t, void **);
static GC_pthread_join_t REAL_FUNC(pthread_join);
typedef int (*GC_pthread_detach_t)(pthread_t);
static GC_pthread_detach_t REAL_FUNC(pthread_detach);
# ifndef GC_NO_PTHREAD_CANCEL
typedef int (*GC_pthread_cancel_t)(pthread_t);
static GC_pthread_cancel_t REAL_FUNC(pthread_cancel);
# endif
# ifdef GC_HAVE_PTHREAD_EXIT
typedef void (*GC_pthread_exit_t)(void *) GC_PTHREAD_EXIT_ATTRIBUTE;
static GC_pthread_exit_t REAL_FUNC(pthread_exit);
# endif
# else
# define WRAP_FUNC(f) GC_##f
# ifdef DGUX
# define REAL_FUNC(f) __d10_##f
# else
# define REAL_FUNC(f) f
# endif
# endif /* !GC_USE_LD_WRAP && !GC_USE_DLOPEN_WRAP */
# if defined(GC_USE_LD_WRAP) || defined(GC_USE_DLOPEN_WRAP)
/* Define GC_ functions as aliases for the plain ones, which will */
/* be intercepted. This allows files which include gc.h, and hence */
/* generate references to the GC_ symbols, to see the right ones. */
GC_API int
GC_pthread_create(pthread_t *t, GC_PTHREAD_CREATE_CONST pthread_attr_t *a,
void *(*fn)(void *), void *arg)
{
return pthread_create(t, a, fn, arg);
}
# ifndef GC_NO_PTHREAD_SIGMASK
GC_API int
GC_pthread_sigmask(int how, const sigset_t *mask, sigset_t *old)
{
return pthread_sigmask(how, mask, old);
}
# endif /* !GC_NO_PTHREAD_SIGMASK */
GC_API int
GC_pthread_join(pthread_t t, void **res)
{
return pthread_join(t, res);
}
GC_API int
GC_pthread_detach(pthread_t t)
{
return pthread_detach(t);
}
# ifndef GC_NO_PTHREAD_CANCEL
GC_API int
GC_pthread_cancel(pthread_t t)
{
return pthread_cancel(t);
}
# endif /* !GC_NO_PTHREAD_CANCEL */
# ifdef GC_HAVE_PTHREAD_EXIT
GC_API GC_PTHREAD_EXIT_ATTRIBUTE void
GC_pthread_exit(void *retval)
{
pthread_exit(retval);
}
# endif
# endif /* GC_USE_LD_WRAP || GC_USE_DLOPEN_WRAP */
# ifdef GC_USE_DLOPEN_WRAP
STATIC GC_bool GC_syms_initialized = FALSE;
/* Resolve a symbol from the dynamic library (given by a handle) */
/* and cast it to the given functional type. */
# define TYPED_DLSYM(fn, h, name) CAST_THRU_UINTPTR(fn, dlsym(h, name))
STATIC void
GC_init_real_syms(void)
{
void *dl_handle;
GC_ASSERT(!GC_syms_initialized);
# ifdef RTLD_NEXT
dl_handle = RTLD_NEXT;
# else
dl_handle = dlopen("libpthread.so.0", RTLD_LAZY);
if (NULL == dl_handle) {
/* Retry without ".0" suffix. */
dl_handle = dlopen("libpthread.so", RTLD_LAZY);
if (NULL == dl_handle)
ABORT("Couldn't open libpthread");
}
# endif
REAL_FUNC(pthread_create)
= TYPED_DLSYM(GC_pthread_create_t, dl_handle, "pthread_create");
# ifdef RTLD_NEXT
if (REAL_FUNC(pthread_create) == 0)
ABORT("pthread_create not found"
" (probably -lgc is specified after -lpthread)");
# endif
# ifndef GC_NO_PTHREAD_SIGMASK
REAL_FUNC(pthread_sigmask)
= TYPED_DLSYM(GC_pthread_sigmask_t, dl_handle, "pthread_sigmask");
# endif
REAL_FUNC(pthread_join)
= TYPED_DLSYM(GC_pthread_join_t, dl_handle, "pthread_join");
REAL_FUNC(pthread_detach)
= TYPED_DLSYM(GC_pthread_detach_t, dl_handle, "pthread_detach");
# ifndef GC_NO_PTHREAD_CANCEL
REAL_FUNC(pthread_cancel)
= TYPED_DLSYM(GC_pthread_cancel_t, dl_handle, "pthread_cancel");
# endif
# ifdef GC_HAVE_PTHREAD_EXIT
REAL_FUNC(pthread_exit)
= TYPED_DLSYM(GC_pthread_exit_t, dl_handle, "pthread_exit");
# endif
GC_syms_initialized = TRUE;
}
# define INIT_REAL_SYMS() \
if (EXPECT(GC_syms_initialized, TRUE)) { \
} else \
GC_init_real_syms()
# else
# define INIT_REAL_SYMS() (void)0
# endif /* !GC_USE_DLOPEN_WRAP */
# else
# define WRAP_FUNC(f) GC_##f
# define REAL_FUNC(f) f
# define INIT_REAL_SYMS() (void)0
# endif /* GC_WIN32_THREADS */
# if defined(MPROTECT_VDB) && defined(DARWIN)
GC_INNER int
GC_inner_pthread_create(pthread_t *t,
GC_PTHREAD_CREATE_CONST pthread_attr_t *a,
void *(*fn)(void *), void *arg)
{
INIT_REAL_SYMS();
return REAL_FUNC(pthread_create)(t, a, fn, arg);
}
# endif
# ifndef GC_ALWAYS_MULTITHREADED
GC_INNER GC_bool GC_need_to_lock = FALSE;
# endif
# ifdef THREAD_LOCAL_ALLOC
/* We must explicitly mark ptrfree and gcj free lists, since the free */
/* list links wouldn't otherwise be found. We also set them in the */
/* normal free lists, since that involves touching less memory than */
/* if we scanned them normally. */
GC_INNER void
GC_mark_thread_local_free_lists(void)
{
int i;
GC_thread p;
for (i = 0; i < THREAD_TABLE_SZ; ++i) {
for (p = GC_threads[i]; p != NULL; p = p->tm.next) {
if (!KNOWN_FINISHED(p))
GC_mark_thread_local_fls_for(&p->tlfs);
}
}
}
# if defined(GC_ASSERTIONS)
/* Check that all thread-local free-lists are completely marked. */
/* Also check that thread-specific-data structures are marked. */
void
GC_check_tls(void)
{
int i;
GC_thread p;
for (i = 0; i < THREAD_TABLE_SZ; ++i) {
for (p = GC_threads[i]; p != NULL; p = p->tm.next) {
if (!KNOWN_FINISHED(p))
GC_check_tls_for(&p->tlfs);
}
}
# if defined(USE_CUSTOM_SPECIFIC)
if (GC_thread_key != 0)
GC_check_tsd_marks(GC_thread_key);
# endif
}
# endif
# endif /* THREAD_LOCAL_ALLOC */
# ifdef GC_WIN32_THREADS
/* A macro for functions and variables which should be accessible */
/* from win32_threads.c but otherwise could be static. */
# define GC_INNER_WIN32THREAD GC_INNER
# else
# define GC_INNER_WIN32THREAD STATIC
# endif
# ifdef PARALLEL_MARK
# if defined(GC_WIN32_THREADS) || defined(USE_PROC_FOR_LIBRARIES) \
|| (defined(IA64) \
&& (defined(HAVE_PTHREAD_ATTR_GET_NP) \
|| defined(HAVE_PTHREAD_GETATTR_NP)))
/* The cold end of the stack for markers. */
GC_INNER_WIN32THREAD ptr_t GC_marker_sp[MAX_MARKERS - 1] = { 0 };
# endif /* GC_WIN32_THREADS || USE_PROC_FOR_LIBRARIES */
# if defined(IA64) && defined(USE_PROC_FOR_LIBRARIES)
static ptr_t marker_bsp[MAX_MARKERS - 1] = { 0 };
# endif
# if defined(DARWIN) && !defined(GC_NO_THREADS_DISCOVERY)
static mach_port_t marker_mach_threads[MAX_MARKERS - 1] = { 0 };
/* Used only by GC_suspend_thread_list(). */
GC_INNER GC_bool
GC_is_mach_marker(thread_act_t thread)
{
int i;
for (i = 0; i < GC_markers_m1; i++) {
if (marker_mach_threads[i] == thread)
return TRUE;
}
return FALSE;
}
# endif /* DARWIN && !GC_NO_THREADS_DISCOVERY */
# ifdef HAVE_PTHREAD_SETNAME_NP_WITH_TID_AND_ARG
/* For NetBSD. */
static void
set_marker_thread_name(unsigned id)
{
int err = pthread_setname_np(pthread_self(), "GC-marker-%zu",
NUMERIC_TO_VPTR(id));
if (EXPECT(err != 0, FALSE))
WARN("pthread_setname_np failed, errno= %" WARN_PRIdPTR "\n",
(GC_signed_word)err);
}
# elif defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID) \
|| defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID) \
|| defined(HAVE_PTHREAD_SET_NAME_NP)
# ifdef HAVE_PTHREAD_SET_NAME_NP
# include <pthread_np.h>
# endif
static void
set_marker_thread_name(unsigned id)
{
char name_buf[16]; /* pthread_setname_np may fail for longer names */
int len = sizeof("GC-marker-") - 1;
/* Compose the name manually as snprintf may be unavailable or */
/* "%u directive output may be truncated" warning may occur. */
BCOPY("GC-marker-", name_buf, len);
if (id >= 10)
name_buf[len++] = (char)('0' + (id / 10) % 10);
name_buf[len] = (char)('0' + id % 10);
name_buf[len + 1] = '\0';
# ifdef HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID
/* The iOS or OS X case. */
(void)pthread_setname_np(name_buf);
# elif defined(HAVE_PTHREAD_SET_NAME_NP)
/* The OpenBSD case. */
pthread_set_name_np(pthread_self(), name_buf);
# else
/* The case of Linux, Solaris, etc. */
if (EXPECT(pthread_setname_np(pthread_self(), name_buf) != 0, FALSE))
WARN("pthread_setname_np failed\n", 0);
# endif
}
# elif defined(GC_WIN32_THREADS) && !defined(MSWINCE)
/* A pointer to SetThreadDescription() which is available since */
/* Windows 10. The function prototype is in processthreadsapi.h. */
static FARPROC setThreadDescription_fn;
GC_INNER void
GC_init_win32_thread_naming(HMODULE hK32)
{
if (hK32)
setThreadDescription_fn = GetProcAddress(hK32, "SetThreadDescription");
}
static void
set_marker_thread_name(unsigned id)
{
WCHAR name_buf[16];
int len = sizeof(L"GC-marker-") / sizeof(WCHAR) - 1;
HRESULT hr;
if (!setThreadDescription_fn) {
/* SetThreadDescription() is missing. */
return;
}
/* Compose the name manually as swprintf may be unavailable. */
BCOPY(L"GC-marker-", name_buf, len * sizeof(WCHAR));
if (id >= 10)
name_buf[len++] = (WCHAR)('0' + (id / 10) % 10);
name_buf[len] = (WCHAR)('0' + id % 10);
name_buf[len + 1] = 0;
/* Invoke SetThreadDescription(). Cast the function pointer to word */
/* first to avoid "incompatible function types" compiler warning. */
hr = (*(HRESULT(WINAPI *)(HANDLE, const WCHAR *))(
GC_funcptr_uint)setThreadDescription_fn)(GetCurrentThread(), name_buf);
if (hr < 0)
WARN("SetThreadDescription failed\n", 0);
}
# else
# define set_marker_thread_name(id) (void)(id)
# endif
GC_INNER_WIN32THREAD
# ifdef GC_PTHREADS_PARAMARK
void *
GC_mark_thread(void *id)
# elif defined(MSWINCE)
DWORD WINAPI
GC_mark_thread(LPVOID id)
# else
unsigned __stdcall GC_mark_thread(void *id)
# endif
{
word my_mark_no = 0;
word id_n = (word)(GC_uintptr_t)id;
IF_CANCEL(int cancel_state;)
if (id_n == GC_WORD_MAX)
return 0; /* to prevent a compiler warning */
/* Mark threads are not cancellable; they should be invisible to */
/* client. */
DISABLE_CANCEL(cancel_state);
set_marker_thread_name((unsigned)id_n);
# if defined(GC_WIN32_THREADS) || defined(USE_PROC_FOR_LIBRARIES) \
|| (defined(IA64) \
&& (defined(HAVE_PTHREAD_ATTR_GET_NP) \
|| defined(HAVE_PTHREAD_GETATTR_NP)))
GC_marker_sp[id_n] = GC_approx_sp();
# endif
# if defined(IA64) && defined(USE_PROC_FOR_LIBRARIES)
marker_bsp[id_n] = GC_save_regs_in_stack();
# endif
# if defined(DARWIN) && !defined(GC_NO_THREADS_DISCOVERY)
marker_mach_threads[id_n] = mach_thread_self();
# endif
# if !defined(GC_PTHREADS_PARAMARK)
GC_marker_Id[id_n] = thread_id_self();
# endif
/* Inform GC_start_mark_threads about completion of marker data init. */
GC_acquire_mark_lock();
/* Note: the count variable may have a negative value. */
if (0 == --GC_fl_builder_count)
GC_notify_all_builder();
/* GC_mark_no is passed only to allow GC_help_marker to terminate */
/* promptly. This is important if it were called from the signal */
/* handler or from the allocator lock acquisition code. Under */
/* Linux, it is not safe to call it from a signal handler, since it */
/* uses mutexes and condition variables. Since it is called only */
/* here, the argument is unnecessary. */
for (;; ++my_mark_no) {
if (my_mark_no - GC_mark_no > (word)2) {
/* Resynchronize if we get far off, e.g. because GC_mark_no */
/* wrapped. */
my_mark_no = GC_mark_no;
}
# ifdef DEBUG_THREADS
GC_log_printf("Starting helper for mark number %lu (thread %u)\n",
(unsigned long)my_mark_no, (unsigned)id_n);
# endif
GC_help_marker(my_mark_no);
}
}
GC_INNER_WIN32THREAD int GC_available_markers_m1 = 0;
# endif /* PARALLEL_MARK */
# ifdef GC_PTHREADS_PARAMARK
# ifdef GLIBC_2_1_MUTEX_HACK
/* Ugly workaround for a linux threads bug in the final versions */
/* of glibc 2.1. Pthread_mutex_trylock sets the mutex owner */
/* field even when it fails to acquire the mutex. This causes */
/* pthread_cond_wait to die. Should not be needed for glibc 2.2. */
/* According to the man page, we should use */
/* PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, but that isn't actually */
/* defined. */
static pthread_mutex_t mark_mutex
= { 0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, { 0, 0 } };
# else
static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
# endif
# ifdef CAN_HANDLE_FORK
/* Note: this is initialized by GC_start_mark_threads_inner(). */
static pthread_cond_t mark_cv;
# else
static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
# endif
GC_INNER void
GC_start_mark_threads_inner(void)
{
int i;
pthread_attr_t attr;
# ifndef NO_MARKER_SPECIAL_SIGMASK
sigset_t set, oldset;
# endif
GC_ASSERT(I_HOLD_LOCK());
ASSERT_CANCEL_DISABLED();
if (GC_available_markers_m1 <= 0 || GC_parallel) {
/* Skip if parallel markers disabled or already started. */
return;
}
GC_wait_for_gc_completion(TRUE);
# ifdef CAN_HANDLE_FORK
/* Initialize mark_cv (for the first time), or cleanup its value */
/* after forking in the child process. All the marker threads in */
/* the parent process were blocked on this variable at fork, so */
/* pthread_cond_wait() malfunction (hang) is possible in the */
/* child process without such a cleanup. */
/* TODO: This is not portable, it is better to shortly unblock */
/* all marker threads in the parent process at fork. */
{
pthread_cond_t mark_cv_local = PTHREAD_COND_INITIALIZER;
BCOPY(&mark_cv_local, &mark_cv, sizeof(mark_cv));
}
# endif
GC_ASSERT(GC_fl_builder_count == 0);
INIT_REAL_SYMS(); /* for pthread_create */
if (pthread_attr_init(&attr) != 0)
ABORT("pthread_attr_init failed");
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
ABORT("pthread_attr_setdetachstate failed");
# ifdef DEFAULT_STACK_MAYBE_SMALL
/* Default stack size is usually too small: increase it. */
/* Otherwise marker threads or GC may run out of space. */
{
size_t old_size;
if (pthread_attr_getstacksize(&attr, &old_size) != 0)
ABORT("pthread_attr_getstacksize failed");
if (old_size < MIN_STACK_SIZE && old_size != 0 /* stack size is known */) {
if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0)
ABORT("pthread_attr_setstacksize failed");
}
}
# endif /* DEFAULT_STACK_MAYBE_SMALL */
# ifndef NO_MARKER_SPECIAL_SIGMASK
/* Apply special signal mask to GC marker threads, and don't drop */
/* user defined signals by GC marker threads. */
if (sigfillset(&set) != 0)
ABORT("sigfillset failed");
# ifdef SIGNAL_BASED_STOP_WORLD
/* These are used by GC to stop and restart the world. */
if (sigdelset(&set, GC_get_suspend_signal()) != 0
|| sigdelset(&set, GC_get_thr_restart_signal()) != 0)
ABORT("sigdelset failed");
# endif
if (EXPECT(REAL_FUNC(pthread_sigmask)(SIG_BLOCK, &set, &oldset) != 0,
FALSE)) {
WARN("pthread_sigmask set failed, no markers started\n", 0);
GC_markers_m1 = 0;
(void)pthread_attr_destroy(&attr);
return;
}
# endif /* !NO_MARKER_SPECIAL_SIGMASK */
/* To have proper GC_parallel value in GC_help_marker. */
GC_markers_m1 = GC_available_markers_m1;
for (i = 0; i < GC_available_markers_m1; ++i) {
pthread_t new_thread;
# ifdef GC_WIN32_THREADS
GC_marker_last_stack_min[i] = ADDR_LIMIT;
# endif
if (EXPECT(REAL_FUNC(pthread_create)(&new_thread, &attr, GC_mark_thread,
NUMERIC_TO_VPTR(i))
!= 0,
FALSE)) {
WARN("Marker thread %" WARN_PRIdPTR " creation failed\n",
(GC_signed_word)i);
/* Don't try to create other marker threads. */
GC_markers_m1 = i;
break;
}
}
# ifndef NO_MARKER_SPECIAL_SIGMASK
/* Restore previous signal mask. */
if (EXPECT(REAL_FUNC(pthread_sigmask)(SIG_SETMASK, &oldset, NULL) != 0,
FALSE)) {
WARN("pthread_sigmask restore failed\n", 0);
}
# endif
(void)pthread_attr_destroy(&attr);
GC_wait_for_markers_init();
GC_COND_LOG_PRINTF("Started %d mark helper threads\n", GC_markers_m1);
}
# endif /* GC_PTHREADS_PARAMARK */
/* A hash table to keep information about the registered threads. */
/* Not used if GC_win32_dll_threads is set. */
GC_INNER GC_thread GC_threads[THREAD_TABLE_SZ] = { 0 };
/* It may not be safe to allocate when we register the first thread. */
/* Note that next and status fields are unused, but there might be some */
/* other fields (crtn) to be pushed. */
static struct GC_StackContext_Rep first_crtn;
static struct GC_Thread_Rep first_thread;
/* A place to retain a pointer to an allocated object while a thread */
/* registration is ongoing. Protected by the allocator lock. */
static GC_stack_context_t saved_crtn = NULL;
# ifdef GC_ASSERTIONS
GC_INNER GC_bool GC_thr_initialized = FALSE;
# endif
GC_INNER void
GC_push_thread_structures(void)
{
GC_ASSERT(I_HOLD_LOCK());
# if !defined(GC_NO_THREADS_DISCOVERY) && defined(GC_WIN32_THREADS)
if (GC_win32_dll_threads) {
/* Unlike the other threads implementations, the thread table */
/* here contains no pointers to the collectible heap (note also */
/* that GC_PTHREADS is incompatible with DllMain-based thread */
/* registration). Thus we have no private structures we need */
/* to preserve. */
} else
# endif
/* else */ {
GC_push_all(&GC_threads, (ptr_t)(&GC_threads) + sizeof(GC_threads));
GC_ASSERT(NULL == first_thread.tm.next);
# ifdef GC_PTHREADS
GC_ASSERT(NULL == first_thread.status);
# endif
GC_PUSH_ALL_SYM(first_thread.crtn);
GC_PUSH_ALL_SYM(saved_crtn);
}
# if defined(THREAD_LOCAL_ALLOC) && defined(USE_CUSTOM_SPECIFIC)
GC_PUSH_ALL_SYM(GC_thread_key);
# endif
}
# if defined(MPROTECT_VDB) && defined(GC_WIN32_THREADS)
GC_INNER void
GC_win32_unprotect_thread(GC_thread t)
{
GC_ASSERT(I_HOLD_LOCK());
if (!GC_win32_dll_threads && GC_auto_incremental) {
GC_stack_context_t crtn = t->crtn;
if (crtn != &first_crtn) {
GC_ASSERT(SMALL_OBJ(GC_size(crtn)));
GC_remove_protection(HBLKPTR(crtn), 1, FALSE);
}
if (t != &first_thread) {
GC_ASSERT(SMALL_OBJ(GC_size(t)));
GC_remove_protection(HBLKPTR(t), 1, FALSE);
}
}
}
# endif /* MPROTECT_VDB && GC_WIN32_THREADS */
# ifdef DEBUG_THREADS
STATIC int
GC_count_threads(void)
{
int i;
int count = 0;
# if !defined(GC_NO_THREADS_DISCOVERY) && defined(GC_WIN32_THREADS)
if (GC_win32_dll_threads)
return -1; /* not implemented */
# endif
GC_ASSERT(I_HOLD_READER_LOCK());
for (i = 0; i < THREAD_TABLE_SZ; ++i) {
GC_thread p;
for (p = GC_threads[i]; p != NULL; p = p->tm.next) {
if (!KNOWN_FINISHED(p))
++count;
}
}
return count;
}
# endif /* DEBUG_THREADS */
/* Add a thread to GC_threads. We assume it wasn't already there. */
/* The id field is set by the caller. */
GC_INNER_WIN32THREAD GC_thread
GC_new_thread(thread_id_t self_id)
{
int hv = THREAD_TABLE_INDEX(self_id);
GC_thread result;
GC_ASSERT(I_HOLD_LOCK());
# ifdef DEBUG_THREADS
GC_log_printf("Creating thread %p\n", THREAD_ID_TO_VPTR(self_id));
for (result = GC_threads[hv]; result != NULL; result = result->tm.next)
if (!THREAD_ID_EQUAL(result->id, self_id)) {
GC_log_printf("Hash collision at GC_threads[%d]\n", hv);
break;
}
# endif
if (EXPECT(NULL == first_thread.crtn, FALSE)) {
result = &first_thread;
first_thread.crtn = &first_crtn;
GC_ASSERT(NULL == GC_threads[hv]);
# ifdef CPPCHECK
GC_noop1((unsigned char)first_thread.flags_pad[0]);
# if defined(THREAD_SANITIZER) && defined(SIGNAL_BASED_STOP_WORLD)
GC_noop1((unsigned char)first_crtn.dummy[0]);
# endif
# ifndef GC_NO_FINALIZATION
GC_noop1((unsigned char)first_crtn.fnlz_pad[0]);
# endif
# endif
} else {
GC_stack_context_t crtn;
GC_ASSERT(!GC_win32_dll_threads);
GC_ASSERT(!GC_in_thread_creation);
GC_in_thread_creation = TRUE; /* OK to collect from unknown thread */
crtn = (GC_stack_context_t)GC_INTERNAL_MALLOC(
sizeof(struct GC_StackContext_Rep), NORMAL);
/* The current stack is not scanned until the thread is */
/* registered, thus crtn pointer is to be retained in the */
/* global data roots for a while (and pushed explicitly if */
/* a collection occurs here). */
GC_ASSERT(NULL == saved_crtn);
saved_crtn = crtn;
result
= (GC_thread)GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
/* No more collections till thread is registered. */
saved_crtn = NULL;
GC_in_thread_creation = FALSE;
if (NULL == crtn || NULL == result)
ABORT("Failed to allocate memory for thread registering");
result->crtn = crtn;
}
/* The id field is not set here. */
# ifdef USE_TKILL_ON_ANDROID
result->kernel_id = gettid();
# endif
result->tm.next = GC_threads[hv];
GC_threads[hv] = result;
# ifdef NACL
GC_nacl_initialize_gc_thread(result);
# endif
GC_ASSERT(0 == result->flags);
if (EXPECT(result != &first_thread, TRUE))
GC_dirty(result);
return result;
}
/* Delete a thread from GC_threads. We assume it is there. (The code */
/* intentionally traps if it was not.) It is also safe to delete the */
/* main thread. If GC_win32_dll_threads is set, it should be called */
/* only from the thread being deleted. If a thread has been joined, */
/* but we have not yet been notified, then there may be more than one */
/* thread in the table with the same thread id - this is OK because we */
/* delete a specific one. */
GC_INNER_WIN32THREAD void
GC_delete_thread(GC_thread t)
{
# if defined(GC_WIN32_THREADS) && !defined(MSWINCE)
CloseHandle(t->handle);
# endif
# if !defined(GC_NO_THREADS_DISCOVERY) && defined(GC_WIN32_THREADS)
if (GC_win32_dll_threads) {
/* This is intended to be lock-free. It is either called */
/* synchronously from the thread being deleted, or by the joining */
/* thread. In this branch asynchronous changes to (*t) are */
/* possible. Note that it is not allowed to call GC_printf (and */
/* the friends) here, see GC_stop_world() in win32_threads.c for */
/* the information. */
t->crtn->stack_end = NULL;
t->id = 0;
/* The thread is not suspended. */
t->flags = 0;
# ifdef RETRY_GET_THREAD_CONTEXT
t->context_sp = NULL;
# endif
AO_store_release(&t->tm.in_use, FALSE);
} else
# endif
/* else */ {
thread_id_t id = t->id;
int hv = THREAD_TABLE_INDEX(id);
GC_thread p;
GC_thread prev = NULL;
GC_ASSERT(I_HOLD_LOCK());
# if defined(DEBUG_THREADS) && !defined(MSWINCE) \
&& (!defined(MSWIN32) || defined(CONSOLE_LOG))
GC_log_printf("Deleting thread %p, n_threads= %d\n", THREAD_ID_TO_VPTR(id),
GC_count_threads());
# endif
for (p = GC_threads[hv]; p != t; p = p->tm.next) {
prev = p;
}
if (NULL == prev) {
GC_threads[hv] = p->tm.next;
} else {
GC_ASSERT(prev != &first_thread);
prev->tm.next = p->tm.next;
GC_dirty(prev);
}
if (EXPECT(p != &first_thread, TRUE)) {
# ifdef DARWIN
mach_port_deallocate(mach_task_self(), p->mach_thread);
# endif
GC_ASSERT(p->crtn != &first_crtn);
GC_INTERNAL_FREE(p->crtn);
GC_INTERNAL_FREE(p);
}
}
}
/* Return a GC_thread corresponding to a given thread id, or */
/* NULL if it is not there. Caller holds the allocator lock */
/* at least in the reader mode or otherwise inhibits updates. */
/* If there is more than one thread with the given id, we */
/* return the most recent one. */
GC_INNER GC_thread
GC_lookup_thread(thread_id_t id)
{
GC_thread p;
# if !defined(GC_NO_THREADS_DISCOVERY) && defined(GC_WIN32_THREADS)
if (GC_win32_dll_threads)
return GC_win32_dll_lookup_thread(id);
# endif
for (p = GC_threads[THREAD_TABLE_INDEX(id)]; p != NULL; p = p->tm.next) {
if (EXPECT(THREAD_ID_EQUAL(p->id, id), TRUE))
break;
}
return p;
}
/* Same as GC_self_thread_inner() but acquires the allocator lock (in */
/* the reader mode). */
STATIC GC_thread
GC_self_thread(void)
{
GC_thread p;
READER_LOCK();
p = GC_self_thread_inner();
READER_UNLOCK();
return p;
}
# ifndef GC_NO_FINALIZATION
/* Called by GC_finalize() (in case of an allocation failure observed). */
GC_INNER void
GC_reset_finalizer_nested(void)
{
GC_ASSERT(I_HOLD_LOCK());
GC_self_thread_inner()->crtn->finalizer_nested = 0;
}
/* Checks and updates the thread-local level of finalizers recursion. */
/* Returns NULL if GC_invoke_finalizers() should not be called by the */
/* collector (to minimize the risk of a deep finalizers recursion), */
/* otherwise returns a pointer to the thread-local finalizer_nested. */
/* Called by GC_notify_or_invoke_finalizers() only. */
GC_INNER unsigned char *
GC_check_finalizer_nested(void)
{
GC_thread me;
GC_stack_context_t crtn;
unsigned nesting_level;
GC_ASSERT(I_HOLD_LOCK());
me = GC_self_thread_inner();
# if defined(INCLUDE_LINUX_THREAD_DESCR) && defined(REDIRECT_MALLOC)
/* As noted in GC_pthread_start, an allocation may happen in */
/* GC_get_stack_base, causing GC_notify_or_invoke_finalizers */
/* to be called before the thread gets registered. */
if (EXPECT(NULL == me, FALSE))
return NULL;
# endif
crtn = me->crtn;
nesting_level = crtn->finalizer_nested;
if (nesting_level) {
/* We are inside another GC_invoke_finalizers(). */
/* Skip some implicitly-called GC_invoke_finalizers() */
/* depending on the nesting (recursion) level. */
if ((unsigned)(++crtn->finalizer_skipped) < (1U << nesting_level))
return NULL;
crtn->finalizer_skipped = 0;
}
crtn->finalizer_nested = (unsigned char)(nesting_level + 1);
return &crtn->finalizer_nested;
}
# endif /* !GC_NO_FINALIZATION */
# define ADDR_INSIDE_OBJ(p, obj) \
ADDR_INSIDE(p, (ptr_t)(&(obj)), (ptr_t)(&(obj)) + sizeof(obj))
# if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
/* This is called from thread-local GC_malloc(). */
GC_bool
GC_is_thread_tsd_valid(void *tsd)
{
GC_thread me = GC_self_thread();
return ADDR_INSIDE_OBJ((ptr_t)tsd, me->tlfs);
}
# endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */
GC_API int GC_CALL
GC_thread_is_registered(void)
{
/* TODO: Use GC_get_tlfs() instead. */
GC_thread me = GC_self_thread();
return me != NULL && !KNOWN_FINISHED(me);
}
GC_API void GC_CALL
GC_register_altstack(void *normstack, size_t normstack_size, void *altstack,
size_t altstack_size)
{
# ifdef GC_WIN32_THREADS
/* TODO: Implement */
UNUSED_ARG(normstack);
UNUSED_ARG(normstack_size);
UNUSED_ARG(altstack);
UNUSED_ARG(altstack_size);
# else