forked from ivmai/bdwgc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
win32_threads.c
1861 lines (1688 loc) · 68.8 KB
/
win32_threads.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 Development 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"
#if defined(GC_WIN32_THREADS)
/* The allocator lock definition. */
#ifndef USE_PTHREAD_LOCKS
# ifdef USE_RWLOCK
GC_INNER SRWLOCK GC_allocate_ml;
# else
GC_INNER CRITICAL_SECTION GC_allocate_ml;
# endif
#endif /* !USE_PTHREAD_LOCKS */
#undef CreateThread
#undef ExitThread
#undef _beginthreadex
#undef _endthreadex
#if !defined(GC_PTHREADS) && !defined(MSWINCE)
# include <errno.h> /* for errno, EAGAIN */
# include <process.h> /* For _beginthreadex, _endthreadex */
#endif
static ptr_t copy_ptr_regs(word *regs, const CONTEXT *pcontext);
#ifndef GC_NO_THREADS_DISCOVERY
/* This code operates in two distinct modes, depending on */
/* the setting of GC_win32_dll_threads. */
/* If GC_win32_dll_threads is set, all threads in the process */
/* are implicitly registered with the GC by DllMain. */
/* No explicit registration is required, and attempts at */
/* explicit registration are ignored. This mode is */
/* very different from the Posix operation of the collector. */
/* In this mode access to the thread table is lock-free. */
/* Hence there is a static limit on the number of threads. */
/* GC_DISCOVER_TASK_THREADS should be used if DllMain-based */
/* thread registration is required but it is impossible to */
/* call GC_use_threads_discovery before other GC routines. */
# ifndef GC_DISCOVER_TASK_THREADS
/* GC_win32_dll_threads must be set (if needed) at the */
/* application initialization time, i.e. before any */
/* collector or thread calls. We make it a "dynamic" */
/* option only to avoid multiple library versions. */
GC_INNER GC_bool GC_win32_dll_threads = FALSE;
# endif
#else
/* If GC_win32_dll_threads is FALSE (or the collector is */
/* built without GC_DLL defined), things operate in a way */
/* that is very similar to Posix platforms, and new threads */
/* must be registered with the collector, e.g. by using */
/* preprocessor-based interception of the thread primitives. */
/* In this case, we use a real data structure for the thread */
/* table. Note that there is no equivalent of linker-based */
/* call interception, since we don't have ELF-like */
/* facilities. The Windows analog appears to be "API */
/* hooking", which really seems to be a standard way to */
/* do minor binary rewriting (?). I'd prefer not to have */
/* the basic collector rely on such facilities, but an */
/* optional package that intercepts thread calls this way */
/* would probably be nice. */
# undef MAX_THREADS
# define MAX_THREADS 1 /* dll_thread_table[] is always empty. */
#endif /* GC_NO_THREADS_DISCOVERY */
/* We have two versions of the thread table. Which one */
/* we use depends on whether GC_win32_dll_threads */
/* is set. Note that before initialization, we don't */
/* add any entries to either table, even if DllMain is */
/* called. The main thread will be added on */
/* initialization. */
/* GC_use_threads_discovery() is currently incompatible with pthreads */
/* and WinCE. It might be possible to get DllMain-based thread */
/* registration to work with Cygwin, but if you try it then you are on */
/* your own. */
GC_API void GC_CALL GC_use_threads_discovery(void)
{
# ifdef GC_NO_THREADS_DISCOVERY
ABORT("GC DllMain-based thread registration unsupported");
# else
/* Turn on GC_win32_dll_threads. */
GC_ASSERT(!GC_is_initialized);
/* Note that GC_use_threads_discovery is expected to be called by */
/* the client application (not from DllMain) at start-up. */
# ifndef GC_DISCOVER_TASK_THREADS
GC_win32_dll_threads = TRUE;
# endif
GC_init();
# ifdef CPPCHECK
GC_noop1((word)(GC_funcptr_uint)&GC_DllMain);
# endif
# endif
}
#ifndef GC_NO_THREADS_DISCOVERY
/* We track thread attachments while the world is supposed to be */
/* stopped. Unfortunately, we cannot stop them from starting, since */
/* blocking in DllMain seems to cause the world to deadlock. Thus, */
/* we have to recover if we notice this in the middle of marking. */
STATIC volatile AO_t GC_attached_thread = FALSE;
/* We assumed that volatile ==> memory ordering, at least among */
/* volatiles. This code should consistently use atomic_ops. */
STATIC volatile GC_bool GC_please_stop = FALSE;
#elif defined(GC_ASSERTIONS)
STATIC GC_bool GC_please_stop = FALSE;
#endif /* GC_NO_THREADS_DISCOVERY && GC_ASSERTIONS */
#if defined(WRAP_MARK_SOME) && !defined(GC_PTHREADS)
/* Return TRUE if an thread was attached since we last asked or */
/* since GC_attached_thread was explicitly reset. */
GC_INNER GC_bool GC_started_thread_while_stopped(void)
{
# ifndef GC_NO_THREADS_DISCOVERY
if (GC_win32_dll_threads) {
# ifdef AO_HAVE_compare_and_swap_release
if (AO_compare_and_swap_release(&GC_attached_thread, TRUE,
FALSE /* stored */))
return TRUE;
# else
AO_nop_full(); /* Prior heap reads need to complete earlier. */
if (AO_load(&GC_attached_thread)) {
AO_store(&GC_attached_thread, FALSE);
return TRUE;
}
# endif
}
# endif
return FALSE;
}
#endif /* WRAP_MARK_SOME */
/* Thread table used if GC_win32_dll_threads is set. */
/* This is a fixed size array. */
/* Since we use runtime conditionals, both versions */
/* are always defined. */
# ifndef MAX_THREADS
# define MAX_THREADS 512
# endif
/* Things may get quite slow for large numbers of threads, */
/* since we look them up with sequential search. */
static volatile struct GC_Thread_Rep dll_thread_table[MAX_THREADS];
#ifndef GC_NO_THREADS_DISCOVERY
static struct GC_StackContext_Rep dll_crtn_table[MAX_THREADS];
#endif
STATIC volatile LONG GC_max_thread_index = 0;
/* Largest index in dll_thread_table */
/* that was ever used. */
/* This may be called from DllMain, and hence operates under unusual */
/* constraints. In particular, it must be lock-free if */
/* GC_win32_dll_threads is set. Always called from the thread being */
/* added. If GC_win32_dll_threads is not set, we already hold the */
/* allocator lock except possibly during single-threaded startup code. */
/* Does not initialize thread-local free lists. */
GC_INNER GC_thread GC_register_my_thread_inner(const struct GC_stack_base *sb,
thread_id_t self_id)
{
GC_thread me;
# ifdef GC_NO_THREADS_DISCOVERY
GC_ASSERT(I_HOLD_LOCK());
# endif
/* The following should be a no-op according to the Win32 */
/* documentation. There is empirical evidence that it */
/* isn't. - HB */
# if defined(MPROTECT_VDB) && !defined(CYGWIN32)
if (GC_auto_incremental
# ifdef GWW_VDB
&& !GC_gww_dirty_init()
# endif
)
GC_set_write_fault_handler();
# endif
# ifndef GC_NO_THREADS_DISCOVERY
if (GC_win32_dll_threads) {
int i;
/* It appears to be unsafe to acquire a lock here, since this */
/* code is apparently not preemptible on some systems. */
/* (This is based on complaints, not on Microsoft's official */
/* documentation, which says this should perform "only simple */
/* initialization tasks".) */
/* Hence we make do with nonblocking synchronization. */
/* It has been claimed that DllMain is really only executed with */
/* a particular system lock held, and thus careful use of locking */
/* around code that doesn't call back into the system libraries */
/* might be OK. But this has not been tested across all Win32 */
/* variants. */
for (i = 0;
InterlockedExchange(&dll_thread_table[i].tm.long_in_use, 1) != 0;
i++) {
/* Compare-and-swap would make this cleaner, but that's not */
/* supported before Windows 98 and NT 4.0. In Windows 2000, */
/* InterlockedExchange is supposed to be replaced by */
/* InterlockedExchangePointer, but that's not really what I */
/* want here. */
/* FIXME: We should eventually declare Windows 95 dead and use */
/* AO_ primitives here. */
if (i == MAX_THREADS - 1)
ABORT("Too many threads");
}
/* Update GC_max_thread_index if necessary. The following is */
/* safe, and unlike CompareExchange-based solutions seems to work */
/* on all Windows 95 and later platforms. Unfortunately, */
/* GC_max_thread_index may be temporarily out of bounds, so */
/* readers have to compensate. */
while (i > GC_max_thread_index) {
InterlockedIncrement((LONG *)&GC_max_thread_index);
/* Cast away volatile for older versions of Win32 headers. */
}
if (EXPECT(GC_max_thread_index >= MAX_THREADS, FALSE)) {
/* We overshot due to simultaneous increments. */
/* Setting it to MAX_THREADS-1 is always safe. */
GC_max_thread_index = MAX_THREADS - 1;
}
me = (GC_thread)(dll_thread_table + i);
me -> crtn = &dll_crtn_table[i];
} else
# endif
/* else */ /* Not using DllMain */ {
me = GC_new_thread(self_id);
}
# ifdef GC_PTHREADS
me -> pthread_id = pthread_self();
# endif
# ifndef MSWINCE
/* GetCurrentThread() returns a pseudohandle (a const value). */
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
GetCurrentProcess(),
(HANDLE*)&(me -> handle),
0 /* dwDesiredAccess */, FALSE /* bInheritHandle */,
DUPLICATE_SAME_ACCESS)) {
ABORT_ARG1("DuplicateHandle failed",
": errcode= 0x%X", (unsigned)GetLastError());
}
# endif
# if defined(WOW64_THREAD_CONTEXT_WORKAROUND) && defined(MSWINRT_FLAVOR)
/* Lookup TIB value via a call to NtCurrentTeb() on thread */
/* registration rather than calling GetThreadSelectorEntry() which */
/* is not available on UWP. */
me -> tib = (PNT_TIB)NtCurrentTeb();
# endif
me -> crtn -> last_stack_min = ADDR_LIMIT;
GC_record_stack_base(me -> crtn, sb);
/* Up until this point, GC_push_all_stacks considers this thread */
/* invalid. */
/* Up until this point, this entry is viewed as reserved but invalid */
/* by GC_win32_dll_lookup_thread. */
((volatile struct GC_Thread_Rep *)me) -> id = self_id;
# ifndef GC_NO_THREADS_DISCOVERY
if (GC_win32_dll_threads) {
if (GC_please_stop) {
AO_store(&GC_attached_thread, TRUE);
AO_nop_full(); /* Later updates must become visible after this. */
}
/* We'd like to wait here, but can't, since waiting in DllMain */
/* provokes deadlocks. */
/* Thus we force marking to be restarted instead. */
} else
# endif
/* else */ {
GC_ASSERT(!GC_please_stop);
/* Otherwise both we and the thread stopping code would be */
/* holding the allocator lock. */
}
return me;
}
/*
* GC_max_thread_index may temporarily be larger than MAX_THREADS.
* To avoid subscript errors, we check on access.
*/
GC_INLINE LONG GC_get_max_thread_index(void)
{
LONG my_max = GC_max_thread_index;
if (EXPECT(my_max >= MAX_THREADS, FALSE)) return MAX_THREADS - 1;
return my_max;
}
#ifndef GC_NO_THREADS_DISCOVERY
/* Search in dll_thread_table and return the GC_thread entity */
/* corresponding to the given thread id. */
/* May be called without a lock, but should be called in contexts in */
/* which the requested thread cannot be asynchronously deleted, e.g. */
/* from the thread itself. */
GC_INNER GC_thread GC_win32_dll_lookup_thread(thread_id_t id)
{
int i;
LONG my_max = GC_get_max_thread_index();
GC_ASSERT(GC_win32_dll_threads);
for (i = 0; i <= my_max; i++) {
if (AO_load_acquire(&dll_thread_table[i].tm.in_use)
&& dll_thread_table[i].id == id)
break; /* Must still be in use, since nobody else can */
/* store our thread id. */
}
return i <= my_max ? (GC_thread)(dll_thread_table + i) : NULL;
}
#endif /* !GC_NO_THREADS_DISCOVERY */
#ifdef GC_PTHREADS
/* A quick-and-dirty cache of the mapping between pthread_t */
/* and Win32 thread id. */
# define PTHREAD_MAP_SIZE 512
thread_id_t GC_pthread_map_cache[PTHREAD_MAP_SIZE] = {0};
# define PTHREAD_MAP_INDEX(pthread_id) \
((NUMERIC_THREAD_ID(pthread_id) >> 5) % PTHREAD_MAP_SIZE)
/* It appears pthread_t is really a pointer type ... */
# define SET_PTHREAD_MAP_CACHE(pthread_id, win32_id) \
(void)(GC_pthread_map_cache[PTHREAD_MAP_INDEX(pthread_id)] = (win32_id))
# define GET_PTHREAD_MAP_CACHE(pthread_id) \
GC_pthread_map_cache[PTHREAD_MAP_INDEX(pthread_id)]
GC_INNER void GC_win32_cache_self_pthread(thread_id_t self_id)
{
pthread_t self = pthread_self();
GC_ASSERT(I_HOLD_LOCK());
SET_PTHREAD_MAP_CACHE(self, self_id);
}
/* Return a GC_thread corresponding to a given pthread_t, or */
/* NULL if it is not there. We assume that this is only */
/* called for pthread ids that have not yet terminated or are */
/* still joinable, and cannot be terminated concurrently. */
GC_INNER GC_thread GC_lookup_by_pthread(pthread_t thread)
{
/* TODO: search in dll_thread_table instead when DllMain-based */
/* thread registration is made compatible with pthreads (and */
/* turned on). */
thread_id_t id;
GC_thread p;
int hv;
GC_ASSERT(I_HOLD_READER_LOCK());
id = GET_PTHREAD_MAP_CACHE(thread);
/* We first try the cache. */
for (p = GC_threads[THREAD_TABLE_INDEX(id)];
p != NULL; p = p -> tm.next) {
if (EXPECT(THREAD_EQUAL(p -> pthread_id, thread), TRUE))
return p;
}
/* If that fails, we use a very slow approach. */
for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
for (p = GC_threads[hv]; p != NULL; p = p -> tm.next) {
if (THREAD_EQUAL(p -> pthread_id, thread))
return p;
}
}
return NULL;
}
#endif /* GC_PTHREADS */
#ifdef WOW64_THREAD_CONTEXT_WORKAROUND
# ifndef CONTEXT_EXCEPTION_ACTIVE
# define CONTEXT_EXCEPTION_ACTIVE 0x08000000
# define CONTEXT_EXCEPTION_REQUEST 0x40000000
# define CONTEXT_EXCEPTION_REPORTING 0x80000000
# endif
static GC_bool isWow64; /* Is running 32-bit code on Win64? */
# define GET_THREAD_CONTEXT_FLAGS (isWow64 \
? CONTEXT_INTEGER | CONTEXT_CONTROL \
| CONTEXT_EXCEPTION_REQUEST | CONTEXT_SEGMENTS \
: CONTEXT_INTEGER | CONTEXT_CONTROL)
#elif defined(I386) || defined(XMM_CANT_STORE_PTRS)
# define GET_THREAD_CONTEXT_FLAGS (CONTEXT_INTEGER | CONTEXT_CONTROL)
#else
# define GET_THREAD_CONTEXT_FLAGS (CONTEXT_INTEGER | CONTEXT_CONTROL \
| CONTEXT_FLOATING_POINT)
#endif /* !WOW64_THREAD_CONTEXT_WORKAROUND && !I386 */
/* Suspend the given thread, if it's still active. */
STATIC void GC_suspend(GC_thread t)
{
# ifndef MSWINCE
DWORD exitCode;
# ifdef RETRY_GET_THREAD_CONTEXT
int retry_cnt;
# define MAX_SUSPEND_THREAD_RETRIES (1000 * 1000)
# endif
# endif
GC_ASSERT(I_HOLD_LOCK());
# if defined(DEBUG_THREADS) && !defined(MSWINCE) \
&& (!defined(MSWIN32) || defined(CONSOLE_LOG))
GC_log_printf("Suspending 0x%x\n", (int)t->id);
# endif
GC_win32_unprotect_thread(t);
GC_acquire_dirty_lock();
# ifdef MSWINCE
/* SuspendThread() will fail if thread is running kernel code. */
while (SuspendThread(THREAD_HANDLE(t)) == (DWORD)-1) {
GC_release_dirty_lock();
Sleep(10); /* in millis */
GC_acquire_dirty_lock();
}
# elif defined(RETRY_GET_THREAD_CONTEXT)
for (retry_cnt = 0;;) {
/* Apparently the Windows 95 GetOpenFileName call creates */
/* a thread that does not properly get cleaned up, and */
/* SuspendThread on its descriptor may provoke a crash. */
/* This reduces the probability of that event, though it still */
/* appears there is a race here. */
if (GetExitCodeThread(t -> handle, &exitCode)
&& exitCode != STILL_ACTIVE) {
GC_release_dirty_lock();
# ifdef GC_PTHREADS
t -> crtn -> stack_end = NULL; /* prevent stack from being pushed */
# else
/* This breaks pthread_join on Cygwin, which is guaranteed to */
/* only see user threads. */
GC_delete_thread(t);
# endif
return;
}
if (SuspendThread(t -> handle) != (DWORD)-1) {
CONTEXT context;
context.ContextFlags = GET_THREAD_CONTEXT_FLAGS;
if (GetThreadContext(t -> handle, &context)) {
/* TODO: WoW64 extra workaround: if CONTEXT_EXCEPTION_ACTIVE */
/* then Sleep(1) and retry. */
t->context_sp = copy_ptr_regs(t->context_regs, &context);
break; /* success; the context pointer registers are saved */
}
/* Resume the thread, try to suspend it in a better location. */
if (ResumeThread(t -> handle) == (DWORD)-1)
ABORT("ResumeThread failed in suspend loop");
}
if (retry_cnt > 1) {
GC_release_dirty_lock();
Sleep(0); /* yield */
GC_acquire_dirty_lock();
}
if (++retry_cnt >= MAX_SUSPEND_THREAD_RETRIES)
ABORT("SuspendThread loop failed"); /* something must be wrong */
}
# else
if (GetExitCodeThread(t -> handle, &exitCode)
&& exitCode != STILL_ACTIVE) {
GC_release_dirty_lock();
# ifdef GC_PTHREADS
t -> crtn -> stack_end = NULL; /* prevent stack from being pushed */
# else
GC_delete_thread(t);
# endif
return;
}
if (SuspendThread(t -> handle) == (DWORD)-1)
ABORT("SuspendThread failed");
# endif
t -> flags |= IS_SUSPENDED;
GC_release_dirty_lock();
if (GC_on_thread_event)
GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED, THREAD_HANDLE(t));
}
#if defined(GC_ASSERTIONS) \
&& ((defined(MSWIN32) && !defined(CONSOLE_LOG)) || defined(MSWINCE))
GC_INNER GC_bool GC_write_disabled = FALSE;
/* TRUE only if GC_stop_world() acquired GC_write_cs. */
#endif
GC_INNER void GC_stop_world(void)
{
thread_id_t self_id = GetCurrentThreadId();
GC_ASSERT(I_HOLD_LOCK());
GC_ASSERT(GC_thr_initialized);
/* This code is the same as in pthread_stop_world.c */
# ifdef PARALLEL_MARK
if (GC_parallel) {
GC_acquire_mark_lock();
GC_ASSERT(GC_fl_builder_count == 0);
/* We should have previously waited for it to become zero. */
}
# endif /* PARALLEL_MARK */
# if !defined(GC_NO_THREADS_DISCOVERY) || defined(GC_ASSERTIONS)
GC_please_stop = TRUE;
# endif
# if (defined(MSWIN32) && !defined(CONSOLE_LOG)) || defined(MSWINCE)
GC_ASSERT(!GC_write_disabled);
EnterCriticalSection(&GC_write_cs);
/* It's not allowed to call GC_printf() (and friends) here down to */
/* LeaveCriticalSection (same applies recursively to GC_suspend, */
/* GC_delete_thread, GC_get_max_thread_index, GC_size and */
/* GC_remove_protection). */
# ifdef GC_ASSERTIONS
GC_write_disabled = TRUE;
# endif
# endif
# ifndef GC_NO_THREADS_DISCOVERY
if (GC_win32_dll_threads) {
int i;
int my_max;
/* Any threads being created during this loop will end up setting */
/* GC_attached_thread when they start. This will force marking */
/* to restart. This is not ideal, but hopefully correct. */
AO_store(&GC_attached_thread, FALSE);
my_max = (int)GC_get_max_thread_index();
for (i = 0; i <= my_max; i++) {
GC_thread p = (GC_thread)(dll_thread_table + i);
if (p -> crtn -> stack_end != NULL && (p -> flags & DO_BLOCKING) == 0
&& p -> id != self_id) {
GC_suspend(p);
}
}
} else
# endif
/* else */ {
GC_thread p;
int i;
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != NULL; p = p -> tm.next)
if (p -> crtn -> stack_end != NULL && p -> id != self_id
&& (p -> flags & (FINISHED | DO_BLOCKING)) == 0)
GC_suspend(p);
}
}
# if (defined(MSWIN32) && !defined(CONSOLE_LOG)) || defined(MSWINCE)
# ifdef GC_ASSERTIONS
GC_write_disabled = FALSE;
# endif
LeaveCriticalSection(&GC_write_cs);
# endif
# ifdef PARALLEL_MARK
if (GC_parallel)
GC_release_mark_lock();
# endif
}
GC_INNER void GC_start_world(void)
{
# ifdef GC_ASSERTIONS
thread_id_t self_id = GetCurrentThreadId();
# endif
GC_ASSERT(I_HOLD_LOCK());
if (GC_win32_dll_threads) {
LONG my_max = GC_get_max_thread_index();
int i;
for (i = 0; i <= my_max; i++) {
GC_thread p = (GC_thread)(dll_thread_table + i);
if ((p -> flags & IS_SUSPENDED) != 0) {
# ifdef DEBUG_THREADS
GC_log_printf("Resuming 0x%x\n", (int)p->id);
# endif
GC_ASSERT(p -> id != self_id);
GC_ASSERT(*(ptr_t *)CAST_AWAY_VOLATILE_PVOID(
&(p -> crtn -> stack_end)) != NULL);
if (ResumeThread(THREAD_HANDLE(p)) == (DWORD)-1)
ABORT("ResumeThread failed");
p -> flags &= (unsigned char)~IS_SUSPENDED;
if (GC_on_thread_event)
GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, THREAD_HANDLE(p));
}
/* Else thread is unregistered or not suspended. */
}
} else {
GC_thread p;
int i;
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != NULL; p = p -> tm.next) {
if ((p -> flags & IS_SUSPENDED) != 0) {
# ifdef DEBUG_THREADS
GC_log_printf("Resuming 0x%x\n", (int)p->id);
# endif
GC_ASSERT(p -> id != self_id
&& *(ptr_t *)&(p -> crtn -> stack_end) != NULL);
if (ResumeThread(THREAD_HANDLE(p)) == (DWORD)-1)
ABORT("ResumeThread failed");
GC_win32_unprotect_thread(p);
p -> flags &= (unsigned char)~IS_SUSPENDED;
if (GC_on_thread_event)
GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, THREAD_HANDLE(p));
} else {
# ifdef DEBUG_THREADS
GC_log_printf("Not resuming thread 0x%x as it is not suspended\n",
(int)p->id);
# endif
}
}
}
}
# if !defined(GC_NO_THREADS_DISCOVERY) || defined(GC_ASSERTIONS)
GC_please_stop = FALSE;
# endif
}
#ifdef MSWINCE
/* The VirtualQuery calls below won't work properly on some old WinCE */
/* versions, but since each stack is restricted to an aligned 64 KiB */
/* region of virtual memory we can just take the next lowest multiple */
/* of 64 KiB. The result of this macro must not be used as its */
/* argument later and must not be used as the lower bound for sp */
/* check (since the stack may be bigger than 64 KiB). */
# define GC_wince_evaluate_stack_min(s) \
(ptr_t)(((word)(s) - 1) & ~(word)0xFFFF)
#elif defined(GC_ASSERTIONS)
# define GC_dont_query_stack_min FALSE
#endif
/* A cache holding the results of the recent VirtualQuery call. */
/* Protected by the allocator lock. */
static ptr_t last_address = 0;
static MEMORY_BASIC_INFORMATION last_info;
/* Probe stack memory region (starting at "s") to find out its */
/* lowest address (i.e. stack top). */
/* S must be a mapped address inside the region, NOT the first */
/* unmapped address. */
STATIC ptr_t GC_get_stack_min(ptr_t s)
{
ptr_t bottom;
GC_ASSERT(I_HOLD_LOCK());
if (s != last_address) {
VirtualQuery(s, &last_info, sizeof(last_info));
last_address = s;
}
do {
bottom = (ptr_t)last_info.BaseAddress;
VirtualQuery(bottom - 1, &last_info, sizeof(last_info));
last_address = bottom - 1;
} while ((last_info.Protect & PAGE_READWRITE)
&& !(last_info.Protect & PAGE_GUARD));
return bottom;
}
/* Return true if the page at s has protections appropriate */
/* for a stack page. */
static GC_bool may_be_in_stack(ptr_t s)
{
GC_ASSERT(I_HOLD_LOCK());
if (s != last_address) {
VirtualQuery(s, &last_info, sizeof(last_info));
last_address = s;
}
return (last_info.Protect & PAGE_READWRITE)
&& !(last_info.Protect & PAGE_GUARD);
}
/* Copy all registers that might point into the heap. Frame */
/* pointer registers are included in case client code was */
/* compiled with the 'omit frame pointer' optimization. */
/* The context register values are stored to regs argument */
/* which is expected to be of PUSHED_REGS_COUNT length exactly. */
/* The functions returns the context stack pointer value. */
static ptr_t copy_ptr_regs(word *regs, const CONTEXT *pcontext) {
ptr_t sp;
int cnt = 0;
# define context (*pcontext)
# define PUSH1(reg) (regs[cnt++] = (word)pcontext->reg)
# define PUSH2(r1,r2) (PUSH1(r1), PUSH1(r2))
# define PUSH4(r1,r2,r3,r4) (PUSH2(r1,r2), PUSH2(r3,r4))
# define PUSH8_LH(r1,r2,r3,r4) (PUSH4(r1.Low,r1.High,r2.Low,r2.High), \
PUSH4(r3.Low,r3.High,r4.Low,r4.High))
# if defined(I386)
# ifdef WOW64_THREAD_CONTEXT_WORKAROUND
PUSH2(ContextFlags, SegFs); /* cannot contain pointers */
# endif
PUSH4(Edi,Esi,Ebx,Edx), PUSH2(Ecx,Eax), PUSH1(Ebp);
sp = (ptr_t)context.Esp;
# elif defined(X86_64)
PUSH4(Rax,Rcx,Rdx,Rbx); PUSH2(Rbp, Rsi); PUSH1(Rdi);
PUSH4(R8, R9, R10, R11); PUSH4(R12, R13, R14, R15);
# ifndef XMM_CANT_STORE_PTRS
PUSH8_LH(Xmm0, Xmm1, Xmm2, Xmm3);
PUSH8_LH(Xmm4, Xmm5, Xmm6, Xmm7);
PUSH8_LH(Xmm8, Xmm9, Xmm10, Xmm11);
PUSH8_LH(Xmm12, Xmm13, Xmm14, Xmm15);
# endif
sp = (ptr_t)context.Rsp;
# elif defined(ARM32)
PUSH4(R0,R1,R2,R3),PUSH4(R4,R5,R6,R7),PUSH4(R8,R9,R10,R11);
PUSH1(R12);
sp = (ptr_t)context.Sp;
# elif defined(AARCH64)
PUSH4(X0,X1,X2,X3),PUSH4(X4,X5,X6,X7),PUSH4(X8,X9,X10,X11);
PUSH4(X12,X13,X14,X15),PUSH4(X16,X17,X18,X19),PUSH4(X20,X21,X22,X23);
PUSH4(X24,X25,X26,X27),PUSH1(X28);
PUSH1(Lr);
sp = (ptr_t)context.Sp;
# elif defined(SHx)
PUSH4(R0,R1,R2,R3), PUSH4(R4,R5,R6,R7), PUSH4(R8,R9,R10,R11);
PUSH2(R12,R13), PUSH1(R14);
sp = (ptr_t)context.R15;
# elif defined(MIPS)
PUSH4(IntAt,IntV0,IntV1,IntA0), PUSH4(IntA1,IntA2,IntA3,IntT0);
PUSH4(IntT1,IntT2,IntT3,IntT4), PUSH4(IntT5,IntT6,IntT7,IntS0);
PUSH4(IntS1,IntS2,IntS3,IntS4), PUSH4(IntS5,IntS6,IntS7,IntT8);
PUSH4(IntT9,IntK0,IntK1,IntS8);
sp = (ptr_t)context.IntSp;
# elif defined(PPC)
PUSH4(Gpr0, Gpr3, Gpr4, Gpr5), PUSH4(Gpr6, Gpr7, Gpr8, Gpr9);
PUSH4(Gpr10,Gpr11,Gpr12,Gpr14), PUSH4(Gpr15,Gpr16,Gpr17,Gpr18);
PUSH4(Gpr19,Gpr20,Gpr21,Gpr22), PUSH4(Gpr23,Gpr24,Gpr25,Gpr26);
PUSH4(Gpr27,Gpr28,Gpr29,Gpr30), PUSH1(Gpr31);
sp = (ptr_t)context.Gpr1;
# elif defined(ALPHA)
PUSH4(IntV0,IntT0,IntT1,IntT2), PUSH4(IntT3,IntT4,IntT5,IntT6);
PUSH4(IntT7,IntS0,IntS1,IntS2), PUSH4(IntS3,IntS4,IntS5,IntFp);
PUSH4(IntA0,IntA1,IntA2,IntA3), PUSH4(IntA4,IntA5,IntT8,IntT9);
PUSH4(IntT10,IntT11,IntT12,IntAt);
sp = (ptr_t)context.IntSp;
# elif defined(CPPCHECK)
GC_noop1_ptr(regs);
sp = (ptr_t)(word)cnt; /* to workaround "cnt not used" false positive */
# else
# error Architecture is not supported
# endif
# undef context
# undef PUSH1
# undef PUSH2
# undef PUSH4
# undef PUSH8_LH
GC_ASSERT(cnt == PUSHED_REGS_COUNT);
return sp;
}
STATIC word GC_push_stack_for(GC_thread thread, thread_id_t self_id,
GC_bool *pfound_me)
{
GC_bool is_self = FALSE;
ptr_t sp, stack_min;
GC_stack_context_t crtn = thread -> crtn;
ptr_t stack_end = crtn -> stack_end;
struct GC_traced_stack_sect_s *traced_stack_sect = crtn -> traced_stack_sect;
GC_ASSERT(I_HOLD_LOCK());
if (EXPECT(NULL == stack_end, FALSE)) return 0;
if (thread -> id == self_id) {
GC_ASSERT((thread -> flags & DO_BLOCKING) == 0);
sp = GC_approx_sp();
is_self = TRUE;
*pfound_me = TRUE;
} else if ((thread -> flags & DO_BLOCKING) != 0) {
/* Use saved sp value for blocked threads. */
sp = crtn -> stack_ptr;
} else {
# ifdef RETRY_GET_THREAD_CONTEXT
/* We cache context when suspending the thread since it may */
/* require looping. */
word *regs = thread -> context_regs;
if ((thread -> flags & IS_SUSPENDED) != 0) {
sp = thread -> context_sp;
} else
# else
word regs[PUSHED_REGS_COUNT];
# endif
/* else */ {
CONTEXT context;
/* For unblocked threads call GetThreadContext(). */
context.ContextFlags = GET_THREAD_CONTEXT_FLAGS;
if (GetThreadContext(THREAD_HANDLE(thread), &context)) {
sp = copy_ptr_regs(regs, &context);
} else {
# ifdef RETRY_GET_THREAD_CONTEXT
/* At least, try to use the stale context if saved. */
sp = thread -> context_sp;
if (NULL == sp) {
/* Skip the current thread, anyway its stack will */
/* be pushed when the world is stopped. */
return 0;
}
# else
*(volatile ptr_t *)&sp = NULL;
/* to avoid "might be uninitialized" compiler warning */
ABORT("GetThreadContext failed");
# endif
}
}
# ifdef THREAD_LOCAL_ALLOC
GC_ASSERT((thread -> flags & IS_SUSPENDED) != 0 || !GC_world_stopped);
# endif
# ifndef WOW64_THREAD_CONTEXT_WORKAROUND
GC_push_many_regs(regs, PUSHED_REGS_COUNT);
# else
GC_push_many_regs(regs + 2, PUSHED_REGS_COUNT - 2);
/* skip ContextFlags and SegFs */
/* WoW64 workaround. */
if (isWow64) {
DWORD ContextFlags = (DWORD)regs[0];
if ((ContextFlags & CONTEXT_EXCEPTION_REPORTING) != 0
&& (ContextFlags & (CONTEXT_EXCEPTION_ACTIVE
/* | CONTEXT_SERVICE_ACTIVE */)) != 0) {
PNT_TIB tib;
# ifdef MSWINRT_FLAVOR
tib = thread -> tib;
# else
WORD SegFs = (WORD)regs[1];
LDT_ENTRY selector;
if (!GetThreadSelectorEntry(THREAD_HANDLE(thread), SegFs,
&selector))
ABORT("GetThreadSelectorEntry failed");
tib = (PNT_TIB)(selector.BaseLow
| (selector.HighWord.Bits.BaseMid << 16)
| (selector.HighWord.Bits.BaseHi << 24));
# endif
# ifdef DEBUG_THREADS
GC_log_printf("TIB stack limit/base: %p .. %p\n",
(void *)(tib -> StackLimit),
(void *)(tib -> StackBase));
# endif
GC_ASSERT(!HOTTER_THAN((ptr_t)(tib -> StackBase), stack_end));
if (stack_end != crtn -> initial_stack_base
/* We are in a coroutine (old-style way of the support). */
&& (ADDR(stack_end) <= (word)(tib -> StackLimit)
|| (word)(tib -> StackBase) < ADDR(stack_end))) {
/* The coroutine stack is not within TIB stack. */
WARN("GetThreadContext might return stale register values"
" including ESP= %p\n", sp);
/* TODO: Because of WoW64 bug, there is no guarantee that */
/* sp really points to the stack top but, for now, we do */
/* our best as the TIB stack limit/base cannot be used */
/* while we are inside a coroutine. */
} else {
/* GetThreadContext() might return stale register values, */
/* so we scan the entire stack region (down to the stack */
/* limit). There is no 100% guarantee that all the */
/* registers are pushed but we do our best (the proper */
/* solution would be to fix it inside Windows). */
sp = (ptr_t)(tib -> StackLimit);
}
} /* else */
# ifdef DEBUG_THREADS
else {
static GC_bool logged;
if (!logged
&& (ContextFlags & CONTEXT_EXCEPTION_REPORTING) == 0) {
GC_log_printf("CONTEXT_EXCEPTION_REQUEST not supported\n");
logged = TRUE;
}
}
# endif
}
# endif /* WOW64_THREAD_CONTEXT_WORKAROUND */
} /* not current thread */
# ifdef STACKPTR_CORRECTOR_AVAILABLE
if (GC_sp_corrector != 0)
GC_sp_corrector((void **)&sp, (void *)(thread -> pthread_id));
# endif
/* Set stack_min to the lowest address in the thread stack, */
/* or to an address in the thread stack no larger than sp, */
/* taking advantage of the old value to avoid slow traversals */
/* of large stacks. */
if (crtn -> last_stack_min == ADDR_LIMIT) {
# ifdef MSWINCE
if (GC_dont_query_stack_min) {
stack_min = GC_wince_evaluate_stack_min(traced_stack_sect != NULL ?
(ptr_t)traced_stack_sect : stack_end);
/* Keep last_stack_min value unmodified. */
} else
# endif
/* else */ {
stack_min = GC_get_stack_min(traced_stack_sect != NULL ?
(ptr_t)traced_stack_sect : stack_end);
GC_win32_unprotect_thread(thread);
crtn -> last_stack_min = stack_min;
}
} else {
/* First, adjust the latest known minimum stack address if we */
/* are inside GC_call_with_gc_active(). */
if (traced_stack_sect != NULL
&& ADDR_LT((ptr_t)traced_stack_sect, crtn -> last_stack_min)) {
GC_win32_unprotect_thread(thread);
crtn -> last_stack_min = (ptr_t)traced_stack_sect;
}
if (ADDR_INSIDE(sp, crtn -> last_stack_min, stack_end)) {
stack_min = sp;
} else {
/* In the current thread it is always safe to use sp value. */
if (may_be_in_stack(is_self && ADDR_LT(sp, crtn -> last_stack_min)
? sp : crtn -> last_stack_min)) {
stack_min = (ptr_t)last_info.BaseAddress;
/* Do not probe rest of the stack if sp is correct. */
if (!ADDR_INSIDE(sp, stack_min, stack_end))
stack_min = GC_get_stack_min(crtn -> last_stack_min);
} else {
/* Stack shrunk? Is this possible? */
stack_min = GC_get_stack_min(stack_end);
}
GC_win32_unprotect_thread(thread);
crtn -> last_stack_min = stack_min;
}
}
GC_ASSERT(GC_dont_query_stack_min
|| stack_min == GC_get_stack_min(stack_end)
|| (ADDR_GE(sp, stack_min) && ADDR_LT(stack_min, stack_end)
&& ADDR_LT(GC_get_stack_min(stack_end), stack_min)));
if (ADDR_INSIDE(sp, stack_min, stack_end)) {
# ifdef DEBUG_THREADS
GC_log_printf("Pushing stack for 0x%x from sp %p to %p from 0x%x\n",
(int)(thread -> id), (void *)sp, (void *)stack_end,
(int)self_id);
# endif
GC_push_all_stack_sections(sp, stack_end, traced_stack_sect);
} else {
/* If not current thread then it is possible for sp to point to */
/* the guarded (untouched yet) page just below the current */
/* stack_min of the thread. */
if (is_self || ADDR_GE(sp, stack_end)
|| ADDR_LT(sp + GC_page_size, stack_min))
WARN("Thread stack pointer %p out of range, pushing everything\n", sp);
# ifdef DEBUG_THREADS
GC_log_printf("Pushing stack for 0x%x from (min) %p to %p from 0x%x\n",
(int)(thread -> id), (void *)stack_min, (void *)stack_end,
(int)self_id);
# endif
/* Push everything - ignore "traced stack section" data. */
GC_push_all_stack(stack_min, stack_end);
}
return stack_end - sp; /* stack grows down */
}
/* Should do exactly the right thing if the world is stopped; should */
/* not fail if it is not. */
GC_INNER void GC_push_all_stacks(void)
{
thread_id_t self_id = GetCurrentThreadId();
GC_bool found_me = FALSE;
# ifndef SMALL_CONFIG
unsigned nthreads = 0;
# endif
word total_size = 0;
GC_ASSERT(I_HOLD_LOCK());
GC_ASSERT(GC_thr_initialized);
# ifndef GC_NO_THREADS_DISCOVERY
if (GC_win32_dll_threads) {
int i;
LONG my_max = GC_get_max_thread_index();
for (i = 0; i <= my_max; i++) {
GC_thread p = (GC_thread)(dll_thread_table + i);
if (p -> tm.in_use) {
# ifndef SMALL_CONFIG
++nthreads;
# endif
total_size += GC_push_stack_for(p, self_id, &found_me);
}
}
} else
# endif
/* else */ {
int i;
for (i = 0; i < THREAD_TABLE_SZ; i++) {
GC_thread p;
for (p = GC_threads[i]; p != NULL; p = p -> tm.next) {