forked from ivmai/bdwgc
-
Notifications
You must be signed in to change notification settings - Fork 14
/
misc.c
2225 lines (1992 loc) · 68.2 KB
/
misc.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 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
*
* 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/gc_pmark.h"
#include <stdio.h>
#include <limits.h>
#include <stdarg.h>
#ifndef MSWINCE
# include <signal.h>
#endif
#ifdef GC_SOLARIS_THREADS
# include <sys/syscall.h>
#endif
#if defined(MSWIN32) || defined(MSWINCE) \
|| (defined(CYGWIN32) && defined(GC_READ_ENV_FILE))
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
# endif
# define NOSERVICE
# include <windows.h>
#endif
#if defined(UNIX_LIKE) || defined(CYGWIN32) || defined(SYMBIAN)
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
#endif
#ifdef NONSTOP
# include <floss.h>
#endif
#ifdef THREADS
# ifdef PCR
# include "il/PCR_IL.h"
GC_INNER PCR_Th_ML GC_allocate_ml;
# elif defined(SN_TARGET_PS3)
# include <pthread.h>
GC_INNER pthread_mutex_t GC_allocate_ml;
# endif
/* For other platforms with threads, the lock and possibly */
/* GC_lock_holder variables are defined in the thread support code. */
#endif /* THREADS */
#ifdef DYNAMIC_LOADING
/* We need to register the main data segment. Returns TRUE unless */
/* this is done implicitly as part of dynamic library registration. */
# define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
#elif defined(GC_DONT_REGISTER_MAIN_STATIC_DATA)
# define GC_REGISTER_MAIN_STATIC_DATA() FALSE
#else
/* Don't unnecessarily call GC_register_main_static_data() in case */
/* dyn_load.c isn't linked in. */
# define GC_REGISTER_MAIN_STATIC_DATA() TRUE
#endif
#ifdef NEED_CANCEL_DISABLE_COUNT
__thread unsigned char GC_cancel_disable_count = 0;
#endif
GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
GC_INNER GC_bool GC_debugging_started = FALSE;
/* defined here so we don't have to load debug_malloc.o */
ptr_t GC_stackbottom = 0;
#ifdef IA64
ptr_t GC_register_stackbottom = 0;
#endif
int GC_dont_gc = FALSE;
int GC_dont_precollect = FALSE;
GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
#ifndef SMALL_CONFIG
int GC_print_stats = 0;
#endif
#ifdef GC_PRINT_BACK_HEIGHT
GC_INNER GC_bool GC_print_back_height = TRUE;
#else
GC_INNER GC_bool GC_print_back_height = FALSE;
#endif
#ifndef NO_DEBUGGING
# ifdef GC_DUMP_REGULARLY
GC_INNER GC_bool GC_dump_regularly = TRUE;
/* Generate regular debugging dumps. */
# else
GC_INNER GC_bool GC_dump_regularly = FALSE;
# endif
#endif
#ifdef KEEP_BACK_PTRS
GC_INNER long GC_backtraces = 0;
/* Number of random backtraces to generate for each GC. */
#endif
#ifdef FIND_LEAK
int GC_find_leak = 1;
#else
int GC_find_leak = 0;
#endif
#ifndef SHORT_DBG_HDRS
# ifdef GC_FINDLEAK_DELAY_FREE
GC_INNER GC_bool GC_findleak_delay_free = TRUE;
# else
GC_INNER GC_bool GC_findleak_delay_free = FALSE;
# endif
#endif /* !SHORT_DBG_HDRS */
#ifdef ALL_INTERIOR_POINTERS
int GC_all_interior_pointers = 1;
#else
int GC_all_interior_pointers = 0;
#endif
#ifdef FINALIZE_ON_DEMAND
int GC_finalize_on_demand = 1;
#else
int GC_finalize_on_demand = 0;
#endif
#ifdef JAVA_FINALIZATION
int GC_java_finalization = 1;
#else
int GC_java_finalization = 0;
#endif
/* All accesses to it should be synchronized to avoid data races. */
GC_finalizer_notifier_proc GC_finalizer_notifier =
(GC_finalizer_notifier_proc)0;
#ifdef GC_FORCE_UNMAP_ON_GCOLLECT
/* Has no effect unless USE_MUNMAP. */
/* Has no effect on implicitly-initiated garbage collections. */
GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
#else
GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
#endif
#ifndef GC_LARGE_ALLOC_WARN_INTERVAL
# define GC_LARGE_ALLOC_WARN_INTERVAL 5
#endif
GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
/* Interval between unsuppressed warnings. */
STATIC void * GC_CALLBACK GC_default_oom_fn(
size_t bytes_requested GC_ATTR_UNUSED)
{
return(0);
}
/* All accesses to it should be synchronized to avoid data races. */
GC_oom_func GC_oom_fn = GC_default_oom_fn;
#ifdef CAN_HANDLE_FORK
# ifdef HANDLE_FORK
GC_INNER int GC_handle_fork = 1;
/* The value is examined by GC_thr_init. */
# else
GC_INNER int GC_handle_fork = FALSE;
# endif
#elif !defined(HAVE_NO_FORK)
/* Same as above but with GC_CALL calling conventions. */
GC_API void GC_CALL GC_atfork_prepare(void)
{
# ifdef THREADS
ABORT("fork() handling unsupported");
# endif
}
GC_API void GC_CALL GC_atfork_parent(void)
{
/* empty */
}
GC_API void GC_CALL GC_atfork_child(void)
{
/* empty */
}
#endif /* !CAN_HANDLE_FORK && !HAVE_NO_FORK */
/* Overrides the default automatic handle-fork mode. Has effect only */
/* if called before GC_INIT. */
GC_API void GC_CALL GC_set_handle_fork(int value GC_ATTR_UNUSED)
{
# ifdef CAN_HANDLE_FORK
if (!GC_is_initialized)
GC_handle_fork = value >= -1 ? value : 1;
/* Map all negative values except for -1 to a positive one. */
# elif defined(THREADS) || (defined(DARWIN) && defined(MPROTECT_VDB))
if (!GC_is_initialized && value) {
# ifndef SMALL_CONFIG
GC_init(); /* just to initialize GC_stderr */
# endif
ABORT("fork() handling unsupported");
}
# else
/* No at-fork handler is needed in the single-threaded mode. */
# endif
}
/* Set things up so that GC_size_map[i] >= granules(i), */
/* but not too much bigger */
/* and so that size_map contains relatively few distinct entries */
/* This was originally stolen from Russ Atkinson's Cedar */
/* quantization algorithm (but we precompute it). */
STATIC void GC_init_size_map(void)
{
int i;
/* Map size 0 to something bigger. */
/* This avoids problems at lower levels. */
GC_size_map[0] = 1;
for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
GC_size_map[i] = ROUNDED_UP_GRANULES(i);
# ifndef _MSC_VER
GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
/* Seems to tickle bug in VC++ 2008 for AMD64 */
# endif
}
/* We leave the rest of the array to be filled in on demand. */
}
/* Fill in additional entries in GC_size_map, including the ith one */
/* We assume the ith entry is currently 0. */
/* Note that a filled in section of the array ending at n always */
/* has length at least n/4. */
GC_INNER void GC_extend_size_map(size_t i)
{
size_t orig_granule_sz = ROUNDED_UP_GRANULES(i);
size_t granule_sz = orig_granule_sz;
size_t byte_sz = GRANULES_TO_BYTES(granule_sz);
/* The size we try to preserve. */
/* Close to i, unless this would */
/* introduce too many distinct sizes. */
size_t smaller_than_i = byte_sz - (byte_sz >> 3);
size_t much_smaller_than_i = byte_sz - (byte_sz >> 2);
size_t low_limit; /* The lowest indexed entry we */
/* initialize. */
size_t j;
if (GC_size_map[smaller_than_i] == 0) {
low_limit = much_smaller_than_i;
while (GC_size_map[low_limit] != 0) low_limit++;
} else {
low_limit = smaller_than_i + 1;
while (GC_size_map[low_limit] != 0) low_limit++;
granule_sz = ROUNDED_UP_GRANULES(low_limit);
granule_sz += granule_sz >> 3;
if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz;
}
/* For these larger sizes, we use an even number of granules. */
/* This makes it easier to, for example, construct a 16byte-aligned */
/* allocator even if GRANULE_BYTES is 8. */
granule_sz += 1;
granule_sz &= ~1;
if (granule_sz > MAXOBJGRANULES) {
granule_sz = MAXOBJGRANULES;
}
/* If we can fit the same number of larger objects in a block, */
/* do so. */
{
size_t number_of_objs = HBLK_GRANULES/granule_sz;
GC_ASSERT(number_of_objs != 0);
granule_sz = HBLK_GRANULES/number_of_objs;
granule_sz &= ~1;
}
byte_sz = GRANULES_TO_BYTES(granule_sz);
/* We may need one extra byte; */
/* don't always fill in GC_size_map[byte_sz] */
byte_sz -= EXTRA_BYTES;
for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz;
}
/*
* The following is a gross hack to deal with a problem that can occur
* on machines that are sloppy about stack frame sizes, notably SPARC.
* Bogus pointers may be written to the stack and not cleared for
* a LONG time, because they always fall into holes in stack frames
* that are not written. We partially address this by clearing
* sections of the stack whenever we get control.
*/
# ifdef THREADS
# define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
# define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
# else
STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
STATIC ptr_t GC_min_sp = NULL;
/* Coolest stack pointer value from which */
/* we've already cleared the stack. */
STATIC ptr_t GC_high_water = NULL;
/* "hottest" stack pointer value we have seen */
/* recently. Degrades over time. */
STATIC word GC_bytes_allocd_at_reset = 0;
# define DEGRADE_RATE 50
# endif
# define CLEAR_SIZE 213 /* Granularity for GC_clear_stack_inner */
#if defined(ASM_CLEAR_CODE)
void *GC_clear_stack_inner(void *, ptr_t);
#else
/* Clear the stack up to about limit. Return arg. This function is */
/* not static because it could also be erroneously defined in .S */
/* file, so this error would be caught by the linker. */
void * GC_clear_stack_inner(void *arg, ptr_t limit)
{
volatile word dummy[CLEAR_SIZE];
BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
if ((word)GC_approx_sp() COOLER_THAN (word)limit) {
(void) GC_clear_stack_inner(arg, limit);
}
/* Make sure the recursive call is not a tail call, and the bzero */
/* call is not recognized as dead code. */
GC_noop1((word)dummy);
return(arg);
}
#endif
/* Clear some of the inaccessible part of the stack. Returns its */
/* argument, so it can be used in a tail call position, hence clearing */
/* another frame. */
GC_API void * GC_CALL GC_clear_stack(void *arg)
{
# ifndef STACK_NOT_SCANNED
ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */
# ifdef THREADS
word volatile dummy[SMALL_CLEAR_SIZE];
static unsigned random_no = 0;
/* Should be more random than it is ... */
/* Used to occasionally clear a bigger */
/* chunk. */
# endif
ptr_t limit;
# define SLOP 400
/* Extra bytes we clear every time. This clears our own */
/* activation record, and should cause more frequent */
/* clearing near the cold end of the stack, a good thing. */
# define GC_SLOP 4000
/* We make GC_high_water this much hotter than we really saw */
/* saw it, to cover for GC noise etc. above our current frame. */
# define CLEAR_THRESHOLD 100000
/* We restart the clearing process after this many bytes of */
/* allocation. Otherwise very heavily recursive programs */
/* with sparse stacks may result in heaps that grow almost */
/* without bounds. As the heap gets larger, collection */
/* frequency decreases, thus clearing frequency would decrease, */
/* thus more junk remains accessible, thus the heap gets */
/* larger ... */
# ifdef THREADS
if (++random_no % 13 == 0) {
limit = sp;
MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
limit = (ptr_t)((word)limit & ~0xf);
/* Make it sufficiently aligned for assembly */
/* implementations of GC_clear_stack_inner. */
return GC_clear_stack_inner(arg, limit);
} else {
BZERO((void *)dummy, SMALL_CLEAR_SIZE*sizeof(word));
}
# else
if (GC_gc_no > GC_stack_last_cleared) {
/* Start things over, so we clear the entire stack again */
if (GC_stack_last_cleared == 0)
GC_high_water = (ptr_t)GC_stackbottom;
GC_min_sp = GC_high_water;
GC_stack_last_cleared = GC_gc_no;
GC_bytes_allocd_at_reset = GC_bytes_allocd;
}
/* Adjust GC_high_water */
MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
if ((word)sp HOTTER_THAN (word)GC_high_water) {
GC_high_water = sp;
}
MAKE_HOTTER(GC_high_water, GC_SLOP);
limit = GC_min_sp;
MAKE_HOTTER(limit, SLOP);
if ((word)sp COOLER_THAN (word)limit) {
limit = (ptr_t)((word)limit & ~0xf);
/* Make it sufficiently aligned for assembly */
/* implementations of GC_clear_stack_inner. */
GC_min_sp = sp;
return GC_clear_stack_inner(arg, limit);
} else if (GC_bytes_allocd - GC_bytes_allocd_at_reset
> CLEAR_THRESHOLD) {
/* Restart clearing process, but limit how much clearing we do. */
GC_min_sp = sp;
MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
if ((word)GC_min_sp HOTTER_THAN (word)GC_high_water)
GC_min_sp = GC_high_water;
GC_bytes_allocd_at_reset = GC_bytes_allocd;
}
# endif
# endif
return arg;
}
/* Return a pointer to the base address of p, given a pointer to a */
/* an address within an object. Return 0 o.w. */
GC_API void * GC_CALL GC_base(void * p)
{
ptr_t r;
struct hblk *h;
bottom_index *bi;
hdr *candidate_hdr;
ptr_t limit;
r = p;
if (!EXPECT(GC_is_initialized, TRUE)) return 0;
h = HBLKPTR(r);
GET_BI(r, bi);
candidate_hdr = HDR_FROM_BI(bi, r);
if (candidate_hdr == 0) return(0);
/* If it's a pointer to the middle of a large object, move it */
/* to the beginning. */
while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
h = FORWARDED_ADDR(h,candidate_hdr);
r = (ptr_t)h;
candidate_hdr = HDR(h);
}
if (HBLK_IS_FREE(candidate_hdr)) return(0);
/* Make sure r points to the beginning of the object */
r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
{
size_t offset = HBLKDISPL(r);
word sz = candidate_hdr -> hb_sz;
size_t obj_displ = offset % sz;
r -= obj_displ;
limit = r + sz;
if ((word)limit > (word)(h + 1) && sz <= HBLKSIZE) {
return(0);
}
if ((word)p >= (word)limit) return(0);
}
return((void *)r);
}
/* Return TRUE if and only if p points to somewhere in GC heap. */
GC_API int GC_CALL GC_is_heap_ptr(const void *p)
{
bottom_index *bi;
GC_ASSERT(GC_is_initialized);
GET_BI(p, bi);
return HDR_FROM_BI(bi, p) != 0;
}
/* Return the size of an object, given a pointer to its base. */
/* (For small objects this also happens to work from interior pointers, */
/* but that shouldn't be relied upon.) */
GC_API size_t GC_CALL GC_size(const void * p)
{
hdr * hhdr = HDR(p);
return hhdr -> hb_sz;
}
/* These getters remain unsynchronized for compatibility (since some */
/* clients could call some of them from a GC callback holding the */
/* allocator lock). */
GC_API size_t GC_CALL GC_get_heap_size(void)
{
/* ignore the memory space returned to OS (i.e. count only the */
/* space owned by the garbage collector) */
return (size_t)(GC_heapsize - GC_unmapped_bytes);
}
GC_API size_t GC_CALL GC_get_free_bytes(void)
{
/* ignore the memory space returned to OS */
return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
}
GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
{
return (size_t)GC_unmapped_bytes;
}
GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
{
return (size_t)GC_bytes_allocd;
}
GC_API size_t GC_CALL GC_get_total_bytes(void)
{
return (size_t)(GC_bytes_allocd + GC_bytes_allocd_before_gc);
}
#ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
/* Return the heap usage information. This is a thread-safe (atomic) */
/* alternative for the five above getters. NULL pointer is allowed for */
/* any argument. Returned (filled in) values are of word type. */
GC_API void GC_CALL GC_get_heap_usage_safe(GC_word *pheap_size,
GC_word *pfree_bytes, GC_word *punmapped_bytes,
GC_word *pbytes_since_gc, GC_word *ptotal_bytes)
{
DCL_LOCK_STATE;
LOCK();
if (pheap_size != NULL)
*pheap_size = GC_heapsize - GC_unmapped_bytes;
if (pfree_bytes != NULL)
*pfree_bytes = GC_large_free_bytes - GC_unmapped_bytes;
if (punmapped_bytes != NULL)
*punmapped_bytes = GC_unmapped_bytes;
if (pbytes_since_gc != NULL)
*pbytes_since_gc = GC_bytes_allocd;
if (ptotal_bytes != NULL)
*ptotal_bytes = GC_bytes_allocd + GC_bytes_allocd_before_gc;
UNLOCK();
}
GC_INNER word GC_reclaimed_bytes_before_gc = 0;
/* Fill in GC statistics provided the destination is of enough size. */
static void fill_prof_stats(struct GC_prof_stats_s *pstats)
{
pstats->heapsize_full = GC_heapsize;
pstats->free_bytes_full = GC_large_free_bytes;
pstats->unmapped_bytes = GC_unmapped_bytes;
pstats->bytes_allocd_since_gc = GC_bytes_allocd;
pstats->allocd_bytes_before_gc = GC_bytes_allocd_before_gc;
pstats->non_gc_bytes = GC_non_gc_bytes;
pstats->gc_no = GC_gc_no; /* could be -1 */
# ifdef PARALLEL_MARK
pstats->markers_m1 = (word)GC_markers_m1;
# else
pstats->markers_m1 = 0; /* one marker */
# endif
pstats->bytes_reclaimed_since_gc = GC_bytes_found > 0 ?
(word)GC_bytes_found : 0;
pstats->reclaimed_bytes_before_gc = GC_reclaimed_bytes_before_gc;
}
# include <string.h> /* for memset() */
GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *pstats,
size_t stats_sz)
{
struct GC_prof_stats_s stats;
DCL_LOCK_STATE;
LOCK();
fill_prof_stats(stats_sz >= sizeof(stats) ? pstats : &stats);
UNLOCK();
if (stats_sz == sizeof(stats)) {
return sizeof(stats);
} else if (stats_sz > sizeof(stats)) {
/* Fill in the remaining part with -1. */
memset((char *)pstats + sizeof(stats), 0xff, stats_sz - sizeof(stats));
return sizeof(stats);
} else {
BCOPY(&stats, pstats, stats_sz);
return stats_sz;
}
}
# ifdef THREADS
/* The _unsafe version assumes the caller holds the allocation lock. */
GC_API size_t GC_CALL GC_get_prof_stats_unsafe(
struct GC_prof_stats_s *pstats,
size_t stats_sz)
{
struct GC_prof_stats_s stats;
if (stats_sz >= sizeof(stats)) {
fill_prof_stats(pstats);
if (stats_sz > sizeof(stats))
memset((char *)pstats + sizeof(stats), 0xff,
stats_sz - sizeof(stats));
return sizeof(stats);
} else {
fill_prof_stats(&stats);
BCOPY(&stats, pstats, stats_sz);
return stats_sz;
}
}
# endif /* THREADS */
#endif /* !GC_GET_HEAP_USAGE_NOT_NEEDED */
#if defined(GC_DARWIN_THREADS) || defined(GC_OPENBSD_UTHREADS) \
|| defined(GC_WIN32_THREADS) || (defined(NACL) && defined(THREADS))
/* GC does not use signals to suspend and restart threads. */
GC_API void GC_CALL GC_set_suspend_signal(int sig GC_ATTR_UNUSED)
{
/* empty */
}
GC_API void GC_CALL GC_set_thr_restart_signal(int sig GC_ATTR_UNUSED)
{
/* empty */
}
GC_API int GC_CALL GC_get_suspend_signal(void)
{
return -1;
}
GC_API int GC_CALL GC_get_thr_restart_signal(void)
{
return -1;
}
#endif /* GC_DARWIN_THREADS || GC_WIN32_THREADS || ... */
#if !defined(_MAX_PATH) && (defined(MSWIN32) || defined(MSWINCE) \
|| defined(CYGWIN32))
# define _MAX_PATH MAX_PATH
#endif
#ifdef GC_READ_ENV_FILE
/* This works for Win32/WinCE for now. Really useful only for WinCE. */
STATIC char *GC_envfile_content = NULL;
/* The content of the GC "env" file with CR and */
/* LF replaced to '\0'. NULL if the file is */
/* missing or empty. Otherwise, always ends */
/* with '\0'. */
STATIC unsigned GC_envfile_length = 0;
/* Length of GC_envfile_content (if non-NULL). */
# ifndef GC_ENVFILE_MAXLEN
# define GC_ENVFILE_MAXLEN 0x4000
# endif
/* The routine initializes GC_envfile_content from the GC "env" file. */
STATIC void GC_envfile_init(void)
{
# if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
HANDLE hFile;
char *content;
unsigned ofs;
unsigned len;
DWORD nBytesRead;
TCHAR path[_MAX_PATH + 0x10]; /* buffer for path + ext */
len = (unsigned)GetModuleFileName(NULL /* hModule */, path,
_MAX_PATH + 1);
/* If GetModuleFileName() has failed then len is 0. */
if (len > 4 && path[len - 4] == (TCHAR)'.') {
len -= 4; /* strip executable file extension */
}
BCOPY(TEXT(".gc.env"), &path[len], sizeof(TEXT(".gc.env")));
hFile = CreateFile(path, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL /* lpSecurityAttributes */, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL /* hTemplateFile */);
if (hFile == INVALID_HANDLE_VALUE)
return; /* the file is absent or the operation is failed */
len = (unsigned)GetFileSize(hFile, NULL);
if (len <= 1 || len >= GC_ENVFILE_MAXLEN) {
CloseHandle(hFile);
return; /* invalid file length - ignoring the file content */
}
/* At this execution point, GC_setpagesize() and GC_init_win32() */
/* must already be called (for GET_MEM() to work correctly). */
content = (char *)GET_MEM(ROUNDUP_PAGESIZE_IF_MMAP(len + 1));
if (content == NULL) {
CloseHandle(hFile);
return; /* allocation failure */
}
ofs = 0;
nBytesRead = (DWORD)-1L;
/* Last ReadFile() call should clear nBytesRead on success. */
while (ReadFile(hFile, content + ofs, len - ofs + 1, &nBytesRead,
NULL /* lpOverlapped */) && nBytesRead != 0) {
if ((ofs += nBytesRead) > len)
break;
}
CloseHandle(hFile);
if (ofs != len || nBytesRead != 0)
return; /* read operation is failed - ignoring the file content */
content[ofs] = '\0';
while (ofs-- > 0) {
if (content[ofs] == '\r' || content[ofs] == '\n')
content[ofs] = '\0';
}
GC_envfile_length = len + 1;
GC_envfile_content = content;
# endif
}
/* This routine scans GC_envfile_content for the specified */
/* environment variable (and returns its value if found). */
GC_INNER char * GC_envfile_getenv(const char *name)
{
char *p;
char *end_of_content;
unsigned namelen;
# ifndef NO_GETENV
p = getenv(name); /* try the standard getenv() first */
if (p != NULL)
return *p != '\0' ? p : NULL;
# endif
p = GC_envfile_content;
if (p == NULL)
return NULL; /* "env" file is absent (or empty) */
namelen = strlen(name);
if (namelen == 0) /* a sanity check */
return NULL;
for (end_of_content = p + GC_envfile_length;
p != end_of_content; p += strlen(p) + 1) {
if (strncmp(p, name, namelen) == 0 && *(p += namelen) == '=') {
p++; /* the match is found; skip '=' */
return *p != '\0' ? p : NULL;
}
/* If not matching then skip to the next line. */
}
return NULL; /* no match found */
}
#endif /* GC_READ_ENV_FILE */
GC_INNER GC_bool GC_is_initialized = FALSE;
#if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
GC_INNER CRITICAL_SECTION GC_write_cs;
#endif
#ifndef DONT_USE_ATEXIT
STATIC void GC_exit_check(void)
{
if (GC_find_leak) {
GC_gcollect();
}
}
#endif
#if defined(UNIX_LIKE) && !defined(NO_DEBUGGING)
static void looping_handler(int sig)
{
GC_err_printf("Caught signal %d: looping in handler\n", sig);
for (;;) {
/* empty */
}
}
static GC_bool installed_looping_handler = FALSE;
static void maybe_install_looping_handler(void)
{
/* Install looping handler before the write fault handler, so we */
/* handle write faults correctly. */
if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
GC_set_and_save_fault_handler(looping_handler);
installed_looping_handler = TRUE;
}
}
#else /* !UNIX_LIKE */
# define maybe_install_looping_handler()
#endif
#define GC_DEFAULT_STDOUT_FD 1
#define GC_DEFAULT_STDERR_FD 2
#if !defined(OS2) && !defined(MACOS) && !defined(GC_ANDROID_LOG) \
&& !defined(MSWIN32) && !defined(MSWINCE)
STATIC int GC_stdout = GC_DEFAULT_STDOUT_FD;
STATIC int GC_stderr = GC_DEFAULT_STDERR_FD;
STATIC int GC_log = GC_DEFAULT_STDERR_FD;
GC_API void GC_CALL GC_set_log_fd(int fd)
{
GC_log = fd;
}
#endif
STATIC word GC_parse_mem_size_arg(const char *str)
{
char *endptr;
word result = 0; /* bad value */
char ch;
if (*str != '\0') {
result = (word)STRTOULL(str, &endptr, 10);
ch = *endptr;
if (ch != '\0') {
if (*(endptr + 1) != '\0')
return 0;
/* Allow k, M or G suffix. */
switch (ch) {
case 'K':
case 'k':
result <<= 10;
break;
case 'M':
case 'm':
result <<= 20;
break;
case 'G':
case 'g':
result <<= 30;
break;
default:
result = 0;
}
}
}
return result;
}
#define GC_LOG_STD_NAME "gc.log"
GC_API void GC_CALL GC_init(void)
{
/* LOCK(); -- no longer does anything this early. */
word initial_heap_sz;
IF_CANCEL(int cancel_state;)
if (EXPECT(GC_is_initialized, TRUE)) return;
# ifdef REDIRECT_MALLOC
{
static GC_bool init_started = FALSE;
if (init_started)
ABORT("Redirected malloc() called during GC init");
init_started = TRUE;
}
# endif
# ifdef GC_INITIAL_HEAP_SIZE
initial_heap_sz = divHBLKSZ(GC_INITIAL_HEAP_SIZE);
# else
initial_heap_sz = (word)MINHINCR;
# endif
DISABLE_CANCEL(cancel_state);
/* Note that although we are nominally called with the */
/* allocation lock held, the allocation lock is now */
/* only really acquired once a second thread is forked.*/
/* And the initialization code needs to run before */
/* then. Thus we really don't hold any locks, and can */
/* in fact safely initialize them here. */
# ifdef THREADS
# ifndef GC_ALWAYS_MULTITHREADED
GC_ASSERT(!GC_need_to_lock);
# endif
# ifdef SN_TARGET_PS3
{
pthread_mutexattr_t mattr;
if (0 != pthread_mutexattr_init(&mattr)) {
ABORT("pthread_mutexattr_init failed");
}
if (0 != pthread_mutex_init(&GC_allocate_ml, &mattr)) {
ABORT("pthread_mutex_init failed");
}
(void)pthread_mutexattr_destroy(&mattr);
}
# endif
# endif /* THREADS */
# if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
{
# ifndef MSWINCE
BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
if (hK32)
pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
GetProcAddress (hK32,
"InitializeCriticalSectionAndSpinCount");
if (pfn)
pfn(&GC_allocate_ml, 4000);
else
# endif /* !MSWINCE */
/* else */ InitializeCriticalSection (&GC_allocate_ml);
}
# endif /* GC_WIN32_THREADS */
# if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
InitializeCriticalSection(&GC_write_cs);
# endif
GC_setpagesize();
# ifdef MSWIN32
GC_init_win32();
# endif
# ifdef GC_READ_ENV_FILE
GC_envfile_init();
# endif
# ifndef SMALL_CONFIG
# ifdef GC_PRINT_VERBOSE_STATS
/* This is useful for debugging and profiling on platforms with */
/* missing getenv() (like WinCE). */
GC_print_stats = VERBOSE;
# else
if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
GC_print_stats = VERBOSE;
} else if (0 != GETENV("GC_PRINT_STATS")) {
GC_print_stats = 1;
}
# endif
# if (defined(UNIX_LIKE) && !defined(GC_ANDROID_LOG)) \
|| defined(CYGWIN32) || defined(SYMBIAN)
{
char * file_name = GETENV("GC_LOG_FILE");
# ifdef GC_LOG_TO_FILE_ALWAYS
if (NULL == file_name)
file_name = GC_LOG_STD_NAME;
# else
if (0 != file_name)
# endif
{
int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
if (log_d < 0) {
GC_err_printf("Failed to open %s as log file\n", file_name);
} else {
char *str;
GC_log = log_d;
str = GETENV("GC_ONLY_LOG_TO_FILE");
# ifdef GC_ONLY_LOG_TO_FILE
/* The similar environment variable set to "0" */
/* overrides the effect of the macro defined. */
if (str != NULL && *str == '0' && *(str + 1) == '\0')
# else
/* Otherwise setting the environment variable */
/* to anything other than "0" will prevent from */
/* redirecting stdout/err to the log file. */
if (str == NULL || (*str == '0' && *(str + 1) == '\0'))
# endif
{
GC_stdout = log_d;
GC_stderr = log_d;
}
}
}
}
# endif
# endif /* !SMALL_CONFIG */
# if !defined(NO_DEBUGGING) && !defined(GC_DUMP_REGULARLY)
if (0 != GETENV("GC_DUMP_REGULARLY")) {
GC_dump_regularly = TRUE;
}
# endif
# ifdef KEEP_BACK_PTRS
{
char * backtraces_string = GETENV("GC_BACKTRACES");
if (0 != backtraces_string) {
GC_backtraces = atol(backtraces_string);
if (backtraces_string[0] == '\0') GC_backtraces = 1;
}
}
# endif
if (0 != GETENV("GC_FIND_LEAK")) {
GC_find_leak = 1;
}
# ifndef SHORT_DBG_HDRS
if (0 != GETENV("GC_FINDLEAK_DELAY_FREE")) {
GC_findleak_delay_free = TRUE;
}
# endif
if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
GC_all_interior_pointers = 1;
}
if (0 != GETENV("GC_DONT_GC")) {
GC_dont_gc = 1;
}
if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
GC_print_back_height = TRUE;
}
if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
GC_large_alloc_warn_interval = LONG_MAX;
}
{
char * addr_string = GETENV("GC_TRACE");
if (0 != addr_string) {
# ifndef ENABLE_TRACE
WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
# else
word addr = (word)STRTOULL(addr_string, NULL, 16);
if (addr < 0x1000)
WARN("Unlikely trace address: %p\n", addr);
GC_trace_addr = (ptr_t)addr;
# endif
}