]> granicus.if.org Git - gc/blob - misc.c
Remove redundant check of GC_free argument in register_finalizer
[gc] / misc.c
1 /*
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1994 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
5  *
6  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
7  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
8  *
9  * Permission is hereby granted to use or copy this program
10  * for any purpose,  provided the above notices are retained on all copies.
11  * Permission to modify the code and to distribute modified code is granted,
12  * provided the above notices are retained, and a notice that the code was
13  * modified is included with the above copyright notice.
14  */
15
16 #include "private/gc_pmark.h"
17
18 #include <stdio.h>
19 #include <limits.h>
20 #include <stdarg.h>
21
22 #ifndef MSWINCE
23 # include <signal.h>
24 #endif
25
26 #ifdef GC_SOLARIS_THREADS
27 # include <sys/syscall.h>
28 #endif
29
30 #if defined(MSWIN32) || defined(MSWINCE) \
31     || (defined(CYGWIN32) && defined(GC_READ_ENV_FILE))
32 # ifndef WIN32_LEAN_AND_MEAN
33 #   define WIN32_LEAN_AND_MEAN 1
34 # endif
35 # define NOSERVICE
36 # include <windows.h>
37 #endif
38
39 #if defined(UNIX_LIKE) || defined(CYGWIN32) || defined(SYMBIAN)
40 # include <fcntl.h>
41 # include <sys/types.h>
42 # include <sys/stat.h>
43 #endif
44
45 #ifdef NONSTOP
46 # include <floss.h>
47 #endif
48
49 #ifdef THREADS
50 # ifdef PCR
51 #   include "il/PCR_IL.h"
52     GC_INNER PCR_Th_ML GC_allocate_ml;
53 # elif defined(SN_TARGET_PSP2)
54     GC_INNER WapiMutex GC_allocate_ml_PSP2 = { 0, NULL };
55 # elif defined(SN_TARGET_ORBIS) || defined(SN_TARGET_PS3)
56 #   include <pthread.h>
57     GC_INNER pthread_mutex_t GC_allocate_ml;
58 # endif
59   /* For other platforms with threads, the lock and possibly            */
60   /* GC_lock_holder variables are defined in the thread support code.   */
61 #endif /* THREADS */
62
63 #ifdef DYNAMIC_LOADING
64   /* We need to register the main data segment.  Returns  TRUE unless   */
65   /* this is done implicitly as part of dynamic library registration.   */
66 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
67 #elif defined(GC_DONT_REGISTER_MAIN_STATIC_DATA)
68 # define GC_REGISTER_MAIN_STATIC_DATA() FALSE
69 #else
70   /* Don't unnecessarily call GC_register_main_static_data() in case    */
71   /* dyn_load.c isn't linked in.                                        */
72 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
73 #endif
74
75 #ifdef NEED_CANCEL_DISABLE_COUNT
76   __thread unsigned char GC_cancel_disable_count = 0;
77 #endif
78
79 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
80
81 GC_INNER GC_bool GC_debugging_started = FALSE;
82                 /* defined here so we don't have to load dbg_mlc.o */
83
84 ptr_t GC_stackbottom = 0;
85
86 #ifdef IA64
87   ptr_t GC_register_stackbottom = 0;
88 #endif
89
90 int GC_dont_gc = FALSE;
91
92 int GC_dont_precollect = FALSE;
93
94 GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
95
96 #if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
97   int GC_print_stats = 0;
98 #endif
99
100 #ifdef GC_PRINT_BACK_HEIGHT
101   GC_INNER GC_bool GC_print_back_height = TRUE;
102 #else
103   GC_INNER GC_bool GC_print_back_height = FALSE;
104 #endif
105
106 #ifndef NO_DEBUGGING
107 # ifdef GC_DUMP_REGULARLY
108     GC_INNER GC_bool GC_dump_regularly = TRUE;
109                                 /* Generate regular debugging dumps. */
110 # else
111     GC_INNER GC_bool GC_dump_regularly = FALSE;
112 # endif
113 # ifndef NO_CLOCK
114     STATIC CLOCK_TYPE GC_init_time;
115                 /* The time that the GC was initialized at.     */
116 # endif
117 #endif /* !NO_DEBUGGING */
118
119 #ifdef KEEP_BACK_PTRS
120   GC_INNER long GC_backtraces = 0;
121                 /* Number of random backtraces to generate for each GC. */
122 #endif
123
124 #ifdef FIND_LEAK
125   int GC_find_leak = 1;
126 #else
127   int GC_find_leak = 0;
128 #endif
129
130 #ifndef SHORT_DBG_HDRS
131 # ifdef GC_FINDLEAK_DELAY_FREE
132     GC_INNER GC_bool GC_findleak_delay_free = TRUE;
133 # else
134     GC_INNER GC_bool GC_findleak_delay_free = FALSE;
135 # endif
136 #endif /* !SHORT_DBG_HDRS */
137
138 #ifdef ALL_INTERIOR_POINTERS
139   int GC_all_interior_pointers = 1;
140 #else
141   int GC_all_interior_pointers = 0;
142 #endif
143
144 #ifdef FINALIZE_ON_DEMAND
145   int GC_finalize_on_demand = 1;
146 #else
147   int GC_finalize_on_demand = 0;
148 #endif
149
150 #ifdef JAVA_FINALIZATION
151   int GC_java_finalization = 1;
152 #else
153   int GC_java_finalization = 0;
154 #endif
155
156 /* All accesses to it should be synchronized to avoid data races.       */
157 GC_finalizer_notifier_proc GC_finalizer_notifier =
158                                         (GC_finalizer_notifier_proc)0;
159
160 #ifdef GC_FORCE_UNMAP_ON_GCOLLECT
161   /* Has no effect unless USE_MUNMAP.                           */
162   /* Has no effect on implicitly-initiated garbage collections. */
163   GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
164 #else
165   GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
166 #endif
167
168 #ifndef GC_LARGE_ALLOC_WARN_INTERVAL
169 # define GC_LARGE_ALLOC_WARN_INTERVAL 5
170 #endif
171 GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
172                         /* Interval between unsuppressed warnings.      */
173
174 STATIC void * GC_CALLBACK GC_default_oom_fn(
175                                         size_t bytes_requested GC_ATTR_UNUSED)
176 {
177     return(0);
178 }
179
180 /* All accesses to it should be synchronized to avoid data races.       */
181 GC_oom_func GC_oom_fn = GC_default_oom_fn;
182
183 #ifdef CAN_HANDLE_FORK
184 # ifdef HANDLE_FORK
185     GC_INNER int GC_handle_fork = 1;
186                         /* The value is examined by GC_thr_init.        */
187 # else
188     GC_INNER int GC_handle_fork = FALSE;
189 # endif
190
191 #elif !defined(HAVE_NO_FORK)
192
193   /* Same as above but with GC_CALL calling conventions.  */
194   GC_API void GC_CALL GC_atfork_prepare(void)
195   {
196 #   ifdef THREADS
197       ABORT("fork() handling unsupported");
198 #   endif
199   }
200
201   GC_API void GC_CALL GC_atfork_parent(void)
202   {
203     /* empty */
204   }
205
206   GC_API void GC_CALL GC_atfork_child(void)
207   {
208     /* empty */
209   }
210 #endif /* !CAN_HANDLE_FORK && !HAVE_NO_FORK */
211
212 /* Overrides the default automatic handle-fork mode.  Has effect only   */
213 /* if called before GC_INIT.                                            */
214 GC_API void GC_CALL GC_set_handle_fork(int value GC_ATTR_UNUSED)
215 {
216 # ifdef CAN_HANDLE_FORK
217     if (!GC_is_initialized)
218       GC_handle_fork = value >= -1 ? value : 1;
219                 /* Map all negative values except for -1 to a positive one. */
220 # elif defined(THREADS) || (defined(DARWIN) && defined(MPROTECT_VDB))
221     if (!GC_is_initialized && value) {
222 #     ifndef SMALL_CONFIG
223         GC_init(); /* to initialize GC_manual_vdb and GC_stderr */
224 #       ifndef THREADS
225           if (GC_manual_vdb)
226             return;
227 #       endif
228 #     endif
229       ABORT("fork() handling unsupported");
230     }
231 # else
232     /* No at-fork handler is needed in the single-threaded mode.        */
233 # endif
234 }
235
236 /* Set things up so that GC_size_map[i] >= granules(i),                 */
237 /* but not too much bigger                                              */
238 /* and so that size_map contains relatively few distinct entries        */
239 /* This was originally stolen from Russ Atkinson's Cedar                */
240 /* quantization algorithm (but we precompute it).                       */
241 STATIC void GC_init_size_map(void)
242 {
243     size_t i;
244
245     /* Map size 0 to something bigger.                  */
246     /* This avoids problems at lower levels.            */
247       GC_size_map[0] = 1;
248     for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
249         GC_size_map[i] = ROUNDED_UP_GRANULES(i);
250 #       ifndef _MSC_VER
251           GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
252           /* Seems to tickle bug in VC++ 2008 for AMD64 */
253 #       endif
254     }
255     /* We leave the rest of the array to be filled in on demand. */
256 }
257
258 /*
259  * The following is a gross hack to deal with a problem that can occur
260  * on machines that are sloppy about stack frame sizes, notably SPARC.
261  * Bogus pointers may be written to the stack and not cleared for
262  * a LONG time, because they always fall into holes in stack frames
263  * that are not written.  We partially address this by clearing
264  * sections of the stack whenever we get control.
265  */
266
267 #ifndef SMALL_CLEAR_SIZE
268 # define SMALL_CLEAR_SIZE 256   /* Clear this much every time.  */
269 #endif
270
271 #if defined(ALWAYS_SMALL_CLEAR_STACK) || defined(STACK_NOT_SCANNED)
272   GC_API void * GC_CALL GC_clear_stack(void *arg)
273   {
274 #   ifndef STACK_NOT_SCANNED
275       word volatile dummy[SMALL_CLEAR_SIZE];
276       BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
277 #   endif
278     return arg;
279   }
280 #else
281
282 # ifdef THREADS
283 #   define BIG_CLEAR_SIZE 2048  /* Clear this much now and then.        */
284 # else
285     STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
286     STATIC ptr_t GC_min_sp = NULL;
287                         /* Coolest stack pointer value from which       */
288                         /* we've already cleared the stack.             */
289     STATIC ptr_t GC_high_water = NULL;
290                         /* "hottest" stack pointer value we have seen   */
291                         /* recently.  Degrades over time.               */
292     STATIC word GC_bytes_allocd_at_reset = 0;
293 #   define DEGRADE_RATE 50
294 # endif
295
296 # if defined(ASM_CLEAR_CODE)
297     void *GC_clear_stack_inner(void *, ptr_t);
298 # else
299     /* Clear the stack up to about limit.  Return arg.  This function   */
300     /* is not static because it could also be erroneously defined in .S */
301     /* file, so this error would be caught by the linker.               */
302     void *GC_clear_stack_inner(void *arg,
303 #                           if defined(__APPLE_CC__) && !GC_CLANG_PREREQ(6, 0)
304                                volatile /* to workaround some bug */
305 #                           endif
306                                ptr_t limit)
307     {
308 #     define CLEAR_SIZE 213 /* granularity */
309       volatile word dummy[CLEAR_SIZE];
310
311       BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
312       if ((word)GC_approx_sp() COOLER_THAN (word)limit) {
313         (void)GC_clear_stack_inner(arg, limit);
314       }
315       /* Make sure the recursive call is not a tail call, and the bzero */
316       /* call is not recognized as dead code.                           */
317 #     if defined(CPPCHECK)
318         GC_noop1(dummy[0]);
319 #     else
320         GC_noop1(COVERT_DATAFLOW(dummy));
321 #     endif
322       return(arg);
323     }
324 # endif /* !ASM_CLEAR_CODE */
325
326 # ifdef THREADS
327     /* Used to occasionally clear a bigger chunk.       */
328     /* TODO: Should be more random than it is ...       */
329     GC_ATTR_NO_SANITIZE_THREAD
330     static unsigned next_random_no(void)
331     {
332       static unsigned random_no = 0;
333       return ++random_no % 13;
334     }
335 # endif /* THREADS */
336
337 /* Clear some of the inaccessible part of the stack.  Returns its       */
338 /* argument, so it can be used in a tail call position, hence clearing  */
339 /* another frame.                                                       */
340   GC_API void * GC_CALL GC_clear_stack(void *arg)
341   {
342     ptr_t sp = GC_approx_sp();  /* Hotter than actual sp */
343 #   ifdef THREADS
344         word volatile dummy[SMALL_CLEAR_SIZE];
345 #   endif
346
347 #   define SLOP 400
348         /* Extra bytes we clear every time.  This clears our own        */
349         /* activation record, and should cause more frequent            */
350         /* clearing near the cold end of the stack, a good thing.       */
351 #   define GC_SLOP 4000
352         /* We make GC_high_water this much hotter than we really saw    */
353         /* it, to cover for GC noise etc. above our current frame.      */
354 #   define CLEAR_THRESHOLD 100000
355         /* We restart the clearing process after this many bytes of     */
356         /* allocation.  Otherwise very heavily recursive programs       */
357         /* with sparse stacks may result in heaps that grow almost      */
358         /* without bounds.  As the heap gets larger, collection         */
359         /* frequency decreases, thus clearing frequency would decrease, */
360         /* thus more junk remains accessible, thus the heap gets        */
361         /* larger ...                                                   */
362 #   ifdef THREADS
363       if (next_random_no() == 0) {
364         ptr_t limit = sp;
365
366         MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
367         limit = (ptr_t)((word)limit & ~0xf);
368                         /* Make it sufficiently aligned for assembly    */
369                         /* implementations of GC_clear_stack_inner.     */
370         return GC_clear_stack_inner(arg, limit);
371       }
372       BZERO((void *)dummy, SMALL_CLEAR_SIZE*sizeof(word));
373 #   else
374       if (GC_gc_no > GC_stack_last_cleared) {
375         /* Start things over, so we clear the entire stack again */
376         if (GC_stack_last_cleared == 0)
377           GC_high_water = (ptr_t)GC_stackbottom;
378         GC_min_sp = GC_high_water;
379         GC_stack_last_cleared = GC_gc_no;
380         GC_bytes_allocd_at_reset = GC_bytes_allocd;
381       }
382       /* Adjust GC_high_water */
383       MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
384       if ((word)sp HOTTER_THAN (word)GC_high_water) {
385           GC_high_water = sp;
386       }
387       MAKE_HOTTER(GC_high_water, GC_SLOP);
388       {
389         ptr_t limit = GC_min_sp;
390
391         MAKE_HOTTER(limit, SLOP);
392         if ((word)sp COOLER_THAN (word)limit) {
393           limit = (ptr_t)((word)limit & ~0xf);
394                           /* Make it sufficiently aligned for assembly  */
395                           /* implementations of GC_clear_stack_inner.   */
396           GC_min_sp = sp;
397           return GC_clear_stack_inner(arg, limit);
398         }
399       }
400       if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
401         /* Restart clearing process, but limit how much clearing we do. */
402         GC_min_sp = sp;
403         MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
404         if ((word)GC_min_sp HOTTER_THAN (word)GC_high_water)
405           GC_min_sp = GC_high_water;
406         GC_bytes_allocd_at_reset = GC_bytes_allocd;
407       }
408 #   endif
409     return arg;
410   }
411
412 #endif /* !ALWAYS_SMALL_CLEAR_STACK && !STACK_NOT_SCANNED */
413
414 /* Return a pointer to the base address of p, given a pointer to a      */
415 /* an address within an object.  Return 0 o.w.                          */
416 GC_API void * GC_CALL GC_base(void * p)
417 {
418     ptr_t r;
419     struct hblk *h;
420     bottom_index *bi;
421     hdr *candidate_hdr;
422
423     r = (ptr_t)p;
424     if (!EXPECT(GC_is_initialized, TRUE)) return 0;
425     h = HBLKPTR(r);
426     GET_BI(r, bi);
427     candidate_hdr = HDR_FROM_BI(bi, r);
428     if (candidate_hdr == 0) return(0);
429     /* If it's a pointer to the middle of a large object, move it       */
430     /* to the beginning.                                                */
431         while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
432            h = FORWARDED_ADDR(h,candidate_hdr);
433            r = (ptr_t)h;
434            candidate_hdr = HDR(h);
435         }
436     if (HBLK_IS_FREE(candidate_hdr)) return(0);
437     /* Make sure r points to the beginning of the object */
438         r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
439         {
440             size_t offset = HBLKDISPL(r);
441             word sz = candidate_hdr -> hb_sz;
442             size_t obj_displ = offset % sz;
443             ptr_t limit;
444
445             r -= obj_displ;
446             limit = r + sz;
447             if ((word)limit > (word)(h + 1) && sz <= HBLKSIZE) {
448                 return(0);
449             }
450             if ((word)p >= (word)limit) return(0);
451         }
452     return((void *)r);
453 }
454
455 /* Return TRUE if and only if p points to somewhere in GC heap. */
456 GC_API int GC_CALL GC_is_heap_ptr(const void *p)
457 {
458     bottom_index *bi;
459
460     GC_ASSERT(GC_is_initialized);
461     GET_BI(p, bi);
462     return HDR_FROM_BI(bi, p) != 0;
463 }
464
465 /* Return the size of an object, given a pointer to its base.           */
466 /* (For small objects this also happens to work from interior pointers, */
467 /* but that shouldn't be relied upon.)                                  */
468 GC_API size_t GC_CALL GC_size(const void * p)
469 {
470     hdr * hhdr = HDR(p);
471
472     return (size_t)hhdr->hb_sz;
473 }
474
475
476 /* These getters remain unsynchronized for compatibility (since some    */
477 /* clients could call some of them from a GC callback holding the       */
478 /* allocator lock).                                                     */
479 GC_API size_t GC_CALL GC_get_heap_size(void)
480 {
481     /* ignore the memory space returned to OS (i.e. count only the      */
482     /* space owned by the garbage collector)                            */
483     return (size_t)(GC_heapsize - GC_unmapped_bytes);
484 }
485
486 GC_API size_t GC_CALL GC_get_free_bytes(void)
487 {
488     /* ignore the memory space returned to OS */
489     return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
490 }
491
492 GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
493 {
494     return (size_t)GC_unmapped_bytes;
495 }
496
497 GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
498 {
499     return (size_t)GC_bytes_allocd;
500 }
501
502 GC_API size_t GC_CALL GC_get_total_bytes(void)
503 {
504     return (size_t)(GC_bytes_allocd + GC_bytes_allocd_before_gc);
505 }
506
507 #ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
508
509 GC_API size_t GC_CALL GC_get_size_map_at(int i)
510 {
511   if ((unsigned)i > MAXOBJBYTES)
512     return GC_SIZE_MAX;
513   return GRANULES_TO_BYTES(GC_size_map[i]);
514 }
515
516 /* Return the heap usage information.  This is a thread-safe (atomic)   */
517 /* alternative for the five above getters.  NULL pointer is allowed for */
518 /* any argument.  Returned (filled in) values are of word type.         */
519 GC_API void GC_CALL GC_get_heap_usage_safe(GC_word *pheap_size,
520                         GC_word *pfree_bytes, GC_word *punmapped_bytes,
521                         GC_word *pbytes_since_gc, GC_word *ptotal_bytes)
522 {
523   DCL_LOCK_STATE;
524
525   LOCK();
526   if (pheap_size != NULL)
527     *pheap_size = GC_heapsize - GC_unmapped_bytes;
528   if (pfree_bytes != NULL)
529     *pfree_bytes = GC_large_free_bytes - GC_unmapped_bytes;
530   if (punmapped_bytes != NULL)
531     *punmapped_bytes = GC_unmapped_bytes;
532   if (pbytes_since_gc != NULL)
533     *pbytes_since_gc = GC_bytes_allocd;
534   if (ptotal_bytes != NULL)
535     *ptotal_bytes = GC_bytes_allocd + GC_bytes_allocd_before_gc;
536   UNLOCK();
537 }
538
539   GC_INNER word GC_reclaimed_bytes_before_gc = 0;
540
541   /* Fill in GC statistics provided the destination is of enough size.  */
542   static void fill_prof_stats(struct GC_prof_stats_s *pstats)
543   {
544     pstats->heapsize_full = GC_heapsize;
545     pstats->free_bytes_full = GC_large_free_bytes;
546     pstats->unmapped_bytes = GC_unmapped_bytes;
547     pstats->bytes_allocd_since_gc = GC_bytes_allocd;
548     pstats->allocd_bytes_before_gc = GC_bytes_allocd_before_gc;
549     pstats->non_gc_bytes = GC_non_gc_bytes;
550     pstats->gc_no = GC_gc_no; /* could be -1 */
551 #   ifdef PARALLEL_MARK
552       pstats->markers_m1 = (word)((signed_word)GC_markers_m1);
553 #   else
554       pstats->markers_m1 = 0; /* one marker */
555 #   endif
556     pstats->bytes_reclaimed_since_gc = GC_bytes_found > 0 ?
557                                         (word)GC_bytes_found : 0;
558     pstats->reclaimed_bytes_before_gc = GC_reclaimed_bytes_before_gc;
559     pstats->expl_freed_bytes_since_gc = GC_bytes_freed; /* since gc-7.7 */
560   }
561
562 # include <string.h> /* for memset() */
563
564   GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *pstats,
565                                           size_t stats_sz)
566   {
567     struct GC_prof_stats_s stats;
568     DCL_LOCK_STATE;
569
570     LOCK();
571     fill_prof_stats(stats_sz >= sizeof(stats) ? pstats : &stats);
572     UNLOCK();
573
574     if (stats_sz == sizeof(stats)) {
575       return sizeof(stats);
576     } else if (stats_sz > sizeof(stats)) {
577       /* Fill in the remaining part with -1.    */
578       memset((char *)pstats + sizeof(stats), 0xff, stats_sz - sizeof(stats));
579       return sizeof(stats);
580     } else {
581       if (EXPECT(stats_sz > 0, TRUE))
582         BCOPY(&stats, pstats, stats_sz);
583       return stats_sz;
584     }
585   }
586
587 # ifdef THREADS
588     /* The _unsafe version assumes the caller holds the allocation lock. */
589     GC_API size_t GC_CALL GC_get_prof_stats_unsafe(
590                                             struct GC_prof_stats_s *pstats,
591                                             size_t stats_sz)
592     {
593       struct GC_prof_stats_s stats;
594
595       if (stats_sz >= sizeof(stats)) {
596         fill_prof_stats(pstats);
597         if (stats_sz > sizeof(stats))
598           memset((char *)pstats + sizeof(stats), 0xff,
599                  stats_sz - sizeof(stats));
600         return sizeof(stats);
601       } else {
602         if (EXPECT(stats_sz > 0, TRUE)) {
603           fill_prof_stats(&stats);
604           BCOPY(&stats, pstats, stats_sz);
605         }
606         return stats_sz;
607       }
608     }
609 # endif /* THREADS */
610
611 #endif /* !GC_GET_HEAP_USAGE_NOT_NEEDED */
612
613 #if defined(GC_DARWIN_THREADS) || defined(GC_OPENBSD_UTHREADS) \
614     || defined(GC_WIN32_THREADS) || (defined(NACL) && defined(THREADS))
615   /* GC does not use signals to suspend and restart threads.    */
616   GC_API void GC_CALL GC_set_suspend_signal(int sig GC_ATTR_UNUSED)
617   {
618     /* empty */
619   }
620
621   GC_API void GC_CALL GC_set_thr_restart_signal(int sig GC_ATTR_UNUSED)
622   {
623     /* empty */
624   }
625
626   GC_API int GC_CALL GC_get_suspend_signal(void)
627   {
628     return -1;
629   }
630
631   GC_API int GC_CALL GC_get_thr_restart_signal(void)
632   {
633     return -1;
634   }
635 #endif /* GC_DARWIN_THREADS || GC_WIN32_THREADS || ... */
636
637 #if !defined(_MAX_PATH) && (defined(MSWIN32) || defined(MSWINCE) \
638                             || defined(CYGWIN32))
639 # define _MAX_PATH MAX_PATH
640 #endif
641
642 #ifdef GC_READ_ENV_FILE
643   /* This works for Win32/WinCE for now.  Really useful only for WinCE. */
644   STATIC char *GC_envfile_content = NULL;
645                         /* The content of the GC "env" file with CR and */
646                         /* LF replaced to '\0'.  NULL if the file is    */
647                         /* missing or empty.  Otherwise, always ends    */
648                         /* with '\0'.                                   */
649   STATIC unsigned GC_envfile_length = 0;
650                         /* Length of GC_envfile_content (if non-NULL).  */
651
652 # ifndef GC_ENVFILE_MAXLEN
653 #   define GC_ENVFILE_MAXLEN 0x4000
654 # endif
655
656 # define GC_ENV_FILE_EXT ".gc.env"
657
658   /* The routine initializes GC_envfile_content from the GC "env" file. */
659   STATIC void GC_envfile_init(void)
660   {
661 #   if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
662       HANDLE hFile;
663       char *content;
664       unsigned ofs;
665       unsigned len;
666       DWORD nBytesRead;
667       TCHAR path[_MAX_PATH + 0x10]; /* buffer for path + ext */
668       len = (unsigned)GetModuleFileName(NULL /* hModule */, path,
669                                         _MAX_PATH + 1);
670       /* If GetModuleFileName() has failed then len is 0. */
671       if (len > 4 && path[len - 4] == (TCHAR)'.') {
672         len -= 4; /* strip executable file extension */
673       }
674       BCOPY(TEXT(GC_ENV_FILE_EXT), &path[len], sizeof(TEXT(GC_ENV_FILE_EXT)));
675       hFile = CreateFile(path, GENERIC_READ,
676                          FILE_SHARE_READ | FILE_SHARE_WRITE,
677                          NULL /* lpSecurityAttributes */, OPEN_EXISTING,
678                          FILE_ATTRIBUTE_NORMAL, NULL /* hTemplateFile */);
679       if (hFile == INVALID_HANDLE_VALUE)
680         return; /* the file is absent or the operation is failed */
681       len = (unsigned)GetFileSize(hFile, NULL);
682       if (len <= 1 || len >= GC_ENVFILE_MAXLEN) {
683         CloseHandle(hFile);
684         return; /* invalid file length - ignoring the file content */
685       }
686       /* At this execution point, GC_setpagesize() and GC_init_win32()  */
687       /* must already be called (for GET_MEM() to work correctly).      */
688       content = (char *)GET_MEM(ROUNDUP_PAGESIZE_IF_MMAP((size_t)len + 1));
689       if (content == NULL) {
690         CloseHandle(hFile);
691         return; /* allocation failure */
692       }
693       ofs = 0;
694       nBytesRead = (DWORD)-1L;
695           /* Last ReadFile() call should clear nBytesRead on success. */
696       while (ReadFile(hFile, content + ofs, len - ofs + 1, &nBytesRead,
697                       NULL /* lpOverlapped */) && nBytesRead != 0) {
698         if ((ofs += nBytesRead) > len)
699           break;
700       }
701       CloseHandle(hFile);
702       if (ofs != len || nBytesRead != 0)
703         return; /* read operation is failed - ignoring the file content */
704       content[ofs] = '\0';
705       while (ofs-- > 0) {
706        if (content[ofs] == '\r' || content[ofs] == '\n')
707          content[ofs] = '\0';
708       }
709       GC_ASSERT(NULL == GC_envfile_content);
710       GC_envfile_length = len + 1;
711       GC_envfile_content = content;
712 #   endif
713   }
714
715   /* This routine scans GC_envfile_content for the specified            */
716   /* environment variable (and returns its value if found).             */
717   GC_INNER char * GC_envfile_getenv(const char *name)
718   {
719     char *p;
720     char *end_of_content;
721     unsigned namelen;
722 #   ifndef NO_GETENV
723       p = getenv(name); /* try the standard getenv() first */
724       if (p != NULL)
725         return *p != '\0' ? p : NULL;
726 #   endif
727     p = GC_envfile_content;
728     if (p == NULL)
729       return NULL; /* "env" file is absent (or empty) */
730     namelen = strlen(name);
731     if (namelen == 0) /* a sanity check */
732       return NULL;
733     for (end_of_content = p + GC_envfile_length;
734          p != end_of_content; p += strlen(p) + 1) {
735       if (strncmp(p, name, namelen) == 0 && *(p += namelen) == '=') {
736         p++; /* the match is found; skip '=' */
737         return *p != '\0' ? p : NULL;
738       }
739       /* If not matching then skip to the next line. */
740     }
741     return NULL; /* no match found */
742   }
743 #endif /* GC_READ_ENV_FILE */
744
745 GC_INNER GC_bool GC_is_initialized = FALSE;
746
747 GC_API int GC_CALL GC_is_init_called(void)
748 {
749   return GC_is_initialized;
750 }
751
752 #if (defined(MSWIN32) || defined(MSWINCE) || defined(MSWIN_XBOX1)) \
753     && defined(THREADS)
754   GC_INNER CRITICAL_SECTION GC_write_cs;
755 #endif
756
757 #ifndef DONT_USE_ATEXIT
758 # if !defined(PCR) && !defined(SMALL_CONFIG)
759     /* A dedicated variable to avoid a garbage collection on abort.     */
760     /* GC_find_leak cannot be used for this purpose as otherwise        */
761     /* TSan finds a data race (between GC_default_on_abort and, e.g.,   */
762     /* GC_finish_collection).                                           */
763     static GC_bool skip_gc_atexit = FALSE;
764 # else
765 #   define skip_gc_atexit FALSE
766 # endif
767
768   STATIC void GC_exit_check(void)
769   {
770     if (GC_find_leak && !skip_gc_atexit) {
771 #     ifdef THREADS
772         GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
773         GC_gcollect();
774         GC_in_thread_creation = FALSE;
775 #     else
776         GC_gcollect();
777 #     endif
778     }
779   }
780 #endif
781
782 #if defined(UNIX_LIKE) && !defined(NO_DEBUGGING)
783   static void looping_handler(int sig)
784   {
785     GC_err_printf("Caught signal %d: looping in handler\n", sig);
786     for (;;) {
787        /* empty */
788     }
789   }
790
791   static GC_bool installed_looping_handler = FALSE;
792
793   static void maybe_install_looping_handler(void)
794   {
795     /* Install looping handler before the write fault handler, so we    */
796     /* handle write faults correctly.                                   */
797     if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
798       GC_set_and_save_fault_handler(looping_handler);
799       installed_looping_handler = TRUE;
800     }
801   }
802
803 #else /* !UNIX_LIKE */
804 # define maybe_install_looping_handler()
805 #endif
806
807 #define GC_DEFAULT_STDOUT_FD 1
808 #define GC_DEFAULT_STDERR_FD 2
809
810 #if !defined(OS2) && !defined(MACOS) && !defined(GC_ANDROID_LOG) \
811     && !defined(NN_PLATFORM_CTR) && !defined(NINTENDO_SWITCH) \
812     && !defined(MSWIN32) && !defined(MSWINCE)
813   STATIC int GC_stdout = GC_DEFAULT_STDOUT_FD;
814   STATIC int GC_stderr = GC_DEFAULT_STDERR_FD;
815   STATIC int GC_log = GC_DEFAULT_STDERR_FD;
816
817   GC_API void GC_CALL GC_set_log_fd(int fd)
818   {
819     GC_log = fd;
820   }
821 #endif
822
823 #ifdef MSGBOX_ON_ERROR
824   STATIC void GC_win32_MessageBoxA(const char *msg, const char *caption,
825                                    unsigned flags)
826   {
827 #   ifndef DONT_USE_USER32_DLL
828       /* Use static binding to "user32.dll".    */
829       (void)MessageBoxA(NULL, msg, caption, flags);
830 #   else
831       /* This simplifies linking - resolve "MessageBoxA" at run-time. */
832       HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll"));
833       if (hU32) {
834         FARPROC pfn = GetProcAddress(hU32, "MessageBoxA");
835         if (pfn)
836           (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)(
837                               NULL /* hWnd */, msg, caption, flags);
838         (void)FreeLibrary(hU32);
839       }
840 #   endif
841   }
842 #endif /* MSGBOX_ON_ERROR */
843
844 #if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
845   static void callee_saves_pushed_dummy_fn(ptr_t data GC_ATTR_UNUSED,
846                                            void * context GC_ATTR_UNUSED) {}
847 #endif
848
849 #ifndef SMALL_CONFIG
850 # ifdef MANUAL_VDB
851     static GC_bool manual_vdb_allowed = TRUE;
852 # else
853     static GC_bool manual_vdb_allowed = FALSE;
854 # endif
855
856   GC_API void GC_CALL GC_set_manual_vdb_allowed(int value)
857   {
858     manual_vdb_allowed = (GC_bool)value;
859   }
860
861   GC_API int GC_CALL GC_get_manual_vdb_allowed(void)
862   {
863     return (int)manual_vdb_allowed;
864   }
865 #endif /* !SMALL_CONFIG */
866
867 STATIC word GC_parse_mem_size_arg(const char *str)
868 {
869   word result = 0; /* bad value */
870
871   if (*str != '\0') {
872     char *endptr;
873     char ch;
874
875     result = (word)STRTOULL(str, &endptr, 10);
876     ch = *endptr;
877     if (ch != '\0') {
878       if (*(endptr + 1) != '\0')
879         return 0;
880       /* Allow k, M or G suffix. */
881       switch (ch) {
882       case 'K':
883       case 'k':
884         result <<= 10;
885         break;
886       case 'M':
887       case 'm':
888         result <<= 20;
889         break;
890       case 'G':
891       case 'g':
892         result <<= 30;
893         break;
894       default:
895         result = 0;
896       }
897     }
898   }
899   return result;
900 }
901
902 #define GC_LOG_STD_NAME "gc.log"
903
904 GC_API void GC_CALL GC_init(void)
905 {
906     /* LOCK(); -- no longer does anything this early. */
907     word initial_heap_sz;
908     IF_CANCEL(int cancel_state;)
909 #   if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
910       DCL_LOCK_STATE;
911 #   endif
912
913     if (EXPECT(GC_is_initialized, TRUE)) return;
914 #   ifdef REDIRECT_MALLOC
915       {
916         static GC_bool init_started = FALSE;
917         if (init_started)
918           ABORT("Redirected malloc() called during GC init");
919         init_started = TRUE;
920       }
921 #   endif
922
923 #   if defined(GC_INITIAL_HEAP_SIZE) && !defined(CPPCHECK)
924       initial_heap_sz = GC_INITIAL_HEAP_SIZE;
925 #   else
926       initial_heap_sz = MINHINCR * HBLKSIZE;
927 #   endif
928
929     DISABLE_CANCEL(cancel_state);
930     /* Note that although we are nominally called with the */
931     /* allocation lock held, the allocation lock is now    */
932     /* only really acquired once a second thread is forked.*/
933     /* And the initialization code needs to run before     */
934     /* then.  Thus we really don't hold any locks, and can */
935     /* in fact safely initialize them here.                */
936 #   ifdef THREADS
937 #     ifndef GC_ALWAYS_MULTITHREADED
938         GC_ASSERT(!GC_need_to_lock);
939 #     endif
940 #     ifdef SN_TARGET_PS3
941         {
942           pthread_mutexattr_t mattr;
943
944           if (0 != pthread_mutexattr_init(&mattr)) {
945             ABORT("pthread_mutexattr_init failed");
946           }
947           if (0 != pthread_mutex_init(&GC_allocate_ml, &mattr)) {
948             ABORT("pthread_mutex_init failed");
949           }
950           (void)pthread_mutexattr_destroy(&mattr);
951         }
952 #     endif
953 #   endif /* THREADS */
954 #   if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
955 #     ifndef SPIN_COUNT
956 #       define SPIN_COUNT 4000
957 #     endif
958 #     ifdef MSWINRT_FLAVOR
959         InitializeCriticalSectionAndSpinCount(&GC_allocate_ml, SPIN_COUNT);
960 #     else
961         {
962 #         ifndef MSWINCE
963             BOOL (WINAPI *pfn)(LPCRITICAL_SECTION, DWORD) = 0;
964             HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
965             if (hK32)
966               pfn = (BOOL (WINAPI *)(LPCRITICAL_SECTION, DWORD))
967                       GetProcAddress(hK32,
968                                      "InitializeCriticalSectionAndSpinCount");
969             if (pfn) {
970               pfn(&GC_allocate_ml, SPIN_COUNT);
971             } else
972 #         endif /* !MSWINCE */
973           /* else */ InitializeCriticalSection(&GC_allocate_ml);
974         }
975 #     endif
976 #   endif /* GC_WIN32_THREADS */
977 #   if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
978       InitializeCriticalSection(&GC_write_cs);
979 #   endif
980     GC_setpagesize();
981 #   ifdef MSWIN32
982       GC_init_win32();
983 #   endif
984 #   ifdef GC_READ_ENV_FILE
985       GC_envfile_init();
986 #   endif
987 #   if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
988 #     ifdef GC_PRINT_VERBOSE_STATS
989         /* This is useful for debugging and profiling on platforms with */
990         /* missing getenv() (like WinCE).                               */
991         GC_print_stats = VERBOSE;
992 #     else
993         if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
994           GC_print_stats = VERBOSE;
995         } else if (0 != GETENV("GC_PRINT_STATS")) {
996           GC_print_stats = 1;
997         }
998 #     endif
999 #   endif
1000 #   if ((defined(UNIX_LIKE) && !defined(GC_ANDROID_LOG)) \
1001         || defined(CYGWIN32) || defined(SYMBIAN)) && !defined(SMALL_CONFIG)
1002         {
1003           char * file_name = TRUSTED_STRING(GETENV("GC_LOG_FILE"));
1004 #         ifdef GC_LOG_TO_FILE_ALWAYS
1005             if (NULL == file_name)
1006               file_name = GC_LOG_STD_NAME;
1007 #         else
1008             if (0 != file_name)
1009 #         endif
1010           {
1011             int log_d = open(file_name, O_CREAT | O_WRONLY | O_APPEND, 0644);
1012             if (log_d < 0) {
1013               GC_err_printf("Failed to open %s as log file\n", file_name);
1014             } else {
1015               char *str;
1016               GC_log = log_d;
1017               str = GETENV("GC_ONLY_LOG_TO_FILE");
1018 #             ifdef GC_ONLY_LOG_TO_FILE
1019                 /* The similar environment variable set to "0"  */
1020                 /* overrides the effect of the macro defined.   */
1021                 if (str != NULL && *str == '0' && *(str + 1) == '\0')
1022 #             else
1023                 /* Otherwise setting the environment variable   */
1024                 /* to anything other than "0" will prevent from */
1025                 /* redirecting stdout/err to the log file.      */
1026                 if (str == NULL || (*str == '0' && *(str + 1) == '\0'))
1027 #             endif
1028               {
1029                 GC_stdout = log_d;
1030                 GC_stderr = log_d;
1031               }
1032             }
1033           }
1034         }
1035 #   endif
1036 #   if !defined(NO_DEBUGGING) && !defined(GC_DUMP_REGULARLY)
1037       if (0 != GETENV("GC_DUMP_REGULARLY")) {
1038         GC_dump_regularly = TRUE;
1039       }
1040 #   endif
1041 #   ifdef KEEP_BACK_PTRS
1042       {
1043         char * backtraces_string = GETENV("GC_BACKTRACES");
1044         if (0 != backtraces_string) {
1045           GC_backtraces = atol(backtraces_string);
1046           if (backtraces_string[0] == '\0') GC_backtraces = 1;
1047         }
1048       }
1049 #   endif
1050     if (0 != GETENV("GC_FIND_LEAK")) {
1051       GC_find_leak = 1;
1052     }
1053 #   ifndef SHORT_DBG_HDRS
1054       if (0 != GETENV("GC_FINDLEAK_DELAY_FREE")) {
1055         GC_findleak_delay_free = TRUE;
1056       }
1057 #   endif
1058     if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
1059       GC_all_interior_pointers = 1;
1060     }
1061     if (0 != GETENV("GC_DONT_GC")) {
1062       GC_dont_gc = 1;
1063     }
1064     if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
1065       GC_print_back_height = TRUE;
1066     }
1067     if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
1068       GC_large_alloc_warn_interval = LONG_MAX;
1069     }
1070     {
1071       char * addr_string = GETENV("GC_TRACE");
1072       if (0 != addr_string) {
1073 #       ifndef ENABLE_TRACE
1074           WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
1075 #       else
1076           word addr = (word)STRTOULL(addr_string, NULL, 16);
1077           if (addr < 0x1000)
1078               WARN("Unlikely trace address: %p\n", (void *)addr);
1079           GC_trace_addr = (ptr_t)addr;
1080 #       endif
1081       }
1082     }
1083 #   ifdef GC_COLLECT_AT_MALLOC
1084       {
1085         char * string = GETENV("GC_COLLECT_AT_MALLOC");
1086         if (0 != string) {
1087           size_t min_lb = (size_t)STRTOULL(string, NULL, 10);
1088           if (min_lb > 0)
1089             GC_dbg_collect_at_malloc_min_lb = min_lb;
1090         }
1091       }
1092 #   endif
1093 #   if !defined(GC_DISABLE_INCREMENTAL) && !defined(NO_CLOCK)
1094       {
1095         char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
1096         if (0 != time_limit_string) {
1097           long time_limit = atol(time_limit_string);
1098           if (time_limit > 0) {
1099             GC_time_limit = time_limit;
1100           }
1101         }
1102       }
1103 #   endif
1104 #   ifndef SMALL_CONFIG
1105       {
1106         char * full_freq_string = GETENV("GC_FULL_FREQUENCY");
1107         if (full_freq_string != NULL) {
1108           int full_freq = atoi(full_freq_string);
1109           if (full_freq > 0)
1110             GC_full_freq = full_freq;
1111         }
1112       }
1113 #   endif
1114     {
1115       char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
1116       if (0 != interval_string) {
1117         long interval = atol(interval_string);
1118         if (interval <= 0) {
1119           WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
1120                "bad value: Ignoring\n", 0);
1121         } else {
1122           GC_large_alloc_warn_interval = interval;
1123         }
1124       }
1125     }
1126     {
1127         char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR");
1128         if (space_divisor_string != NULL) {
1129           int space_divisor = atoi(space_divisor_string);
1130           if (space_divisor > 0)
1131             GC_free_space_divisor = (unsigned)space_divisor;
1132         }
1133     }
1134 #   ifdef USE_MUNMAP
1135       {
1136         char * string = GETENV("GC_UNMAP_THRESHOLD");
1137         if (string != NULL) {
1138           if (*string == '0' && *(string + 1) == '\0') {
1139             /* "0" is used to disable unmapping. */
1140             GC_unmap_threshold = 0;
1141           } else {
1142             int unmap_threshold = atoi(string);
1143             if (unmap_threshold > 0)
1144               GC_unmap_threshold = unmap_threshold;
1145           }
1146         }
1147       }
1148       {
1149         char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT");
1150         if (string != NULL) {
1151           if (*string == '0' && *(string + 1) == '\0') {
1152             /* "0" is used to turn off the mode. */
1153             GC_force_unmap_on_gcollect = FALSE;
1154           } else {
1155             GC_force_unmap_on_gcollect = TRUE;
1156           }
1157         }
1158       }
1159       {
1160         char * string = GETENV("GC_USE_ENTIRE_HEAP");
1161         if (string != NULL) {
1162           if (*string == '0' && *(string + 1) == '\0') {
1163             /* "0" is used to turn off the mode. */
1164             GC_use_entire_heap = FALSE;
1165           } else {
1166             GC_use_entire_heap = TRUE;
1167           }
1168         }
1169       }
1170 #   endif
1171 #   if !defined(NO_DEBUGGING) && !defined(NO_CLOCK)
1172       GET_TIME(GC_init_time);
1173 #   endif
1174     maybe_install_looping_handler();
1175 #   if ALIGNMENT > GC_DS_TAGS
1176       /* Adjust normal object descriptor for extra allocation.  */
1177       if (EXTRA_BYTES != 0)
1178         GC_obj_kinds[NORMAL].ok_descriptor = (word)(-ALIGNMENT) | GC_DS_LENGTH;
1179 #   endif
1180     GC_exclude_static_roots_inner(beginGC_arrays, endGC_arrays);
1181     GC_exclude_static_roots_inner(beginGC_obj_kinds, endGC_obj_kinds);
1182 #   ifdef SEPARATE_GLOBALS
1183       GC_exclude_static_roots_inner(beginGC_objfreelist, endGC_objfreelist);
1184       GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist);
1185 #   endif
1186 #   if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
1187         WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
1188         /* If thread stacks are cached, they tend to be scanned in      */
1189         /* entirety as part of the root set.  This will grow them to    */
1190         /* maximum size, and is generally not desirable.                */
1191 #   endif
1192 #   if defined(SEARCH_FOR_DATA_START)
1193         GC_init_linux_data_start();
1194 #   endif
1195 #   if defined(NETBSD) && defined(__ELF__)
1196         GC_init_netbsd_elf();
1197 #   endif
1198 #   if !defined(THREADS) || defined(GC_PTHREADS) \
1199         || defined(NN_PLATFORM_CTR) || defined(NINTENDO_SWITCH) \
1200         || defined(GC_WIN32_THREADS) || defined(GC_SOLARIS_THREADS)
1201       if (GC_stackbottom == 0) {
1202         GC_stackbottom = GC_get_main_stack_base();
1203 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
1204           GC_register_stackbottom = GC_get_register_stack_base();
1205 #       endif
1206       } else {
1207 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
1208           if (GC_register_stackbottom == 0) {
1209             WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
1210             /* The following may fail, since we may rely on             */
1211             /* alignment properties that may not hold with a user set   */
1212             /* GC_stackbottom.                                          */
1213             GC_register_stackbottom = GC_get_register_stack_base();
1214           }
1215 #       endif
1216       }
1217 #   endif
1218 #   if !defined(CPPCHECK)
1219       GC_STATIC_ASSERT(sizeof(ptr_t) == sizeof(word));
1220       GC_STATIC_ASSERT(sizeof(signed_word) == sizeof(word));
1221 #     if !defined(_AUX_SOURCE) || defined(__GNUC__)
1222         GC_STATIC_ASSERT((word)(-1) > (word)0);
1223         /* word should be unsigned */
1224 #     endif
1225       /* We no longer check for ((void*)(-1) > NULL) since all pointers */
1226       /* are explicitly cast to word in every less/greater comparison.  */
1227       GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0);
1228 #   endif
1229     GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
1230 #   ifndef THREADS
1231       GC_ASSERT(!((word)GC_stackbottom HOTTER_THAN (word)GC_approx_sp()));
1232 #   endif
1233 #   ifndef GC_DISABLE_INCREMENTAL
1234       if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
1235 #       if defined(BASE_ATOMIC_OPS_EMULATED) || defined(CHECKSUMS) \
1236            || defined(REDIRECT_MALLOC) || defined(REDIRECT_MALLOC_IN_HEADER) \
1237            || defined(SMALL_CONFIG)
1238           /* TODO: Implement CHECKSUMS for manual VDB. */
1239 #       else
1240           if (manual_vdb_allowed) {
1241               GC_manual_vdb = TRUE;
1242               GC_incremental = TRUE;
1243           } else
1244 #       endif
1245         /* else */ {
1246           /* For GWW_VDB on Win32, this needs to happen before any      */
1247           /* heap memory is allocated.                                  */
1248           GC_incremental = GC_dirty_init();
1249           GC_ASSERT(GC_bytes_allocd == 0);
1250         }
1251       }
1252 #   endif
1253
1254     /* Add initial guess of root sets.  Do this first, since sbrk(0)    */
1255     /* might be used.                                                   */
1256       if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
1257     GC_init_headers();
1258     GC_bl_init();
1259     GC_mark_init();
1260     {
1261         char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
1262         if (sz_str != NULL) {
1263           initial_heap_sz = GC_parse_mem_size_arg(sz_str);
1264           if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
1265             WARN("Bad initial heap size %s - ignoring it.\n", sz_str);
1266           }
1267         }
1268     }
1269     {
1270         char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
1271         if (sz_str != NULL) {
1272           word max_heap_sz = GC_parse_mem_size_arg(sz_str);
1273           if (max_heap_sz < initial_heap_sz) {
1274             WARN("Bad maximum heap size %s - ignoring it.\n", sz_str);
1275           }
1276           if (0 == GC_max_retries) GC_max_retries = 2;
1277           GC_set_max_heap_size(max_heap_sz);
1278         }
1279     }
1280 #   if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1281         LOCK(); /* just to set GC_lock_holder */
1282 #   endif
1283     if (!GC_expand_hp_inner(divHBLKSZ(initial_heap_sz))) {
1284         GC_err_printf("Can't start up: not enough memory\n");
1285         EXIT();
1286     } else {
1287         GC_requested_heapsize += initial_heap_sz;
1288     }
1289     if (GC_all_interior_pointers)
1290       GC_initialize_offsets();
1291     GC_register_displacement_inner(0L);
1292 #   if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
1293       if (!GC_all_interior_pointers) {
1294         /* TLS ABI uses pointer-sized offsets for dtv. */
1295         GC_register_displacement_inner(sizeof(void *));
1296       }
1297 #   endif
1298     GC_init_size_map();
1299 #   ifdef PCR
1300       if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
1301           != PCR_ERes_okay) {
1302           ABORT("Can't lock load state");
1303       } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
1304           ABORT("Can't unlock load state");
1305       }
1306       PCR_IL_Unlock();
1307       GC_pcr_install();
1308 #   endif
1309     GC_is_initialized = TRUE;
1310 #   if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
1311         GC_thr_init();
1312 #       ifdef PARALLEL_MARK
1313           /* Actually start helper threads.     */
1314 #         if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1315             UNLOCK();
1316 #         endif
1317           GC_start_mark_threads_inner();
1318 #         if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1319             LOCK();
1320 #         endif
1321 #       endif
1322 #   endif
1323     COND_DUMP;
1324     /* Get black list set up and/or incremental GC started */
1325     if (!GC_dont_precollect || GC_incremental) {
1326         GC_gcollect_inner();
1327     }
1328 #   if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1329         UNLOCK();
1330 #   endif
1331 #   if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
1332       /* Ensure getcontext_works is set to avoid potential data race.   */
1333       if (GC_dont_gc || GC_dont_precollect)
1334         GC_with_callee_saves_pushed(callee_saves_pushed_dummy_fn, NULL);
1335 #   endif
1336 #   ifndef DONT_USE_ATEXIT
1337       if (GC_find_leak) {
1338         /* This is to give us at least one chance to detect leaks.        */
1339         /* This may report some very benign leaks, but ...                */
1340         atexit(GC_exit_check);
1341       }
1342 #   endif
1343
1344     /* The rest of this again assumes we don't really hold      */
1345     /* the allocation lock.                                     */
1346 #   if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC) \
1347        || (defined(GC_ALWAYS_MULTITHREADED) && defined(GC_WIN32_THREADS) \
1348            && !defined(GC_NO_THREADS_DISCOVERY))
1349         /* Make sure marker threads are started and thread local */
1350         /* allocation is initialized, in case we didn't get      */
1351         /* called from GC_init_parallel.                         */
1352         GC_init_parallel();
1353 #   endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
1354
1355 #   if defined(DYNAMIC_LOADING) && defined(DARWIN)
1356         /* This must be called WITHOUT the allocation lock held */
1357         /* and before any threads are created.                  */
1358         GC_init_dyld();
1359 #   endif
1360     RESTORE_CANCEL(cancel_state);
1361 }
1362
1363 GC_API void GC_CALL GC_enable_incremental(void)
1364 {
1365 # if !defined(GC_DISABLE_INCREMENTAL) && !defined(KEEP_BACK_PTRS)
1366     DCL_LOCK_STATE;
1367     /* If we are keeping back pointers, the GC itself dirties all */
1368     /* pages on which objects have been marked, making            */
1369     /* incremental GC pointless.                                  */
1370     if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) {
1371       LOCK();
1372       if (!GC_incremental) {
1373         GC_setpagesize();
1374         /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
1375         maybe_install_looping_handler(); /* Before write fault handler! */
1376         if (!GC_is_initialized) {
1377           UNLOCK();
1378           GC_incremental = TRUE; /* indicate intention to turn it on */
1379           GC_init();
1380           LOCK();
1381         } else {
1382 #         if !defined(BASE_ATOMIC_OPS_EMULATED) && !defined(CHECKSUMS) \
1383              && !defined(REDIRECT_MALLOC) \
1384              && !defined(REDIRECT_MALLOC_IN_HEADER) && !defined(SMALL_CONFIG)
1385             if (manual_vdb_allowed) {
1386               GC_manual_vdb = TRUE;
1387               GC_incremental = TRUE;
1388             } else
1389 #         endif
1390           /* else */ {
1391             GC_incremental = GC_dirty_init();
1392           }
1393         }
1394         if (GC_incremental && !GC_dont_gc) {
1395                                 /* Can't easily do it if GC_dont_gc.    */
1396           IF_CANCEL(int cancel_state;)
1397
1398           DISABLE_CANCEL(cancel_state);
1399           if (GC_bytes_allocd > 0) {
1400             /* There may be unmarked reachable objects. */
1401             GC_gcollect_inner();
1402           }
1403             /* else we're OK in assuming everything's   */
1404             /* clean since nothing can point to an      */
1405             /* unmarked object.                         */
1406           GC_read_dirty(FALSE);
1407           RESTORE_CANCEL(cancel_state);
1408         }
1409       }
1410       UNLOCK();
1411       return;
1412     }
1413 # endif
1414   GC_init();
1415 }
1416
1417 #if defined(THREADS)
1418   GC_API void GC_CALL GC_start_mark_threads(void)
1419   {
1420 #   if defined(PARALLEL_MARK) && defined(CAN_HANDLE_FORK) \
1421        && !defined(THREAD_SANITIZER)
1422       /* TSan does not support threads creation in the child process.   */
1423       IF_CANCEL(int cancel_state;)
1424
1425       DISABLE_CANCEL(cancel_state);
1426       GC_start_mark_threads_inner();
1427       RESTORE_CANCEL(cancel_state);
1428 #   else
1429       /* No action since parallel markers are disabled (or no POSIX fork). */
1430       GC_ASSERT(I_DONT_HOLD_LOCK());
1431 #   endif
1432   }
1433 #endif
1434
1435   GC_API void GC_CALL GC_deinit(void)
1436   {
1437     if (GC_is_initialized) {
1438       /* Prevent duplicate resource close.  */
1439       GC_is_initialized = FALSE;
1440 #     if defined(THREADS) && (defined(MSWIN32) || defined(MSWINCE))
1441         DeleteCriticalSection(&GC_write_cs);
1442         DeleteCriticalSection(&GC_allocate_ml);
1443 #     endif
1444     }
1445   }
1446
1447 #if defined(MSWIN32) || defined(MSWINCE)
1448
1449 # if defined(_MSC_VER) && defined(_DEBUG) && !defined(MSWINCE)
1450 #   include <crtdbg.h>
1451 # endif
1452
1453   STATIC HANDLE GC_log = 0;
1454
1455 # ifdef THREADS
1456 #   if defined(PARALLEL_MARK) && !defined(GC_ALWAYS_MULTITHREADED)
1457 #     define IF_NEED_TO_LOCK(x) if (GC_parallel || GC_need_to_lock) x
1458 #   else
1459 #     define IF_NEED_TO_LOCK(x) if (GC_need_to_lock) x
1460 #   endif
1461 # else
1462 #   define IF_NEED_TO_LOCK(x)
1463 # endif /* !THREADS */
1464
1465 # ifdef MSWINRT_FLAVOR
1466 #   include <windows.storage.h>
1467
1468     /* This API is defined in roapi.h, but we cannot include it here    */
1469     /* since it does not compile in C.                                  */
1470     DECLSPEC_IMPORT HRESULT WINAPI RoGetActivationFactory(
1471                                         HSTRING activatableClassId,
1472                                         REFIID iid, void** factory);
1473
1474     static GC_bool getWinRTLogPath(wchar_t* buf, size_t bufLen)
1475     {
1476       static const GUID kIID_IApplicationDataStatics = {
1477         0x5612147B, 0xE843, 0x45E3,
1478         0x94, 0xD8, 0x06, 0x16, 0x9E, 0x3C, 0x8E, 0x17
1479       };
1480       static const GUID kIID_IStorageItem = {
1481         0x4207A996, 0xCA2F, 0x42F7,
1482         0xBD, 0xE8, 0x8B, 0x10, 0x45, 0x7A, 0x7F, 0x30
1483       };
1484       GC_bool result = FALSE;
1485       HSTRING_HEADER appDataClassNameHeader;
1486       HSTRING appDataClassName;
1487       __x_ABI_CWindows_CStorage_CIApplicationDataStatics* appDataStatics = 0;
1488
1489       GC_ASSERT(bufLen > 0);
1490       if (SUCCEEDED(WindowsCreateStringReference(
1491                       RuntimeClass_Windows_Storage_ApplicationData,
1492                       (sizeof(RuntimeClass_Windows_Storage_ApplicationData)-1)
1493                         / sizeof(wchar_t),
1494                       &appDataClassNameHeader, &appDataClassName))
1495           && SUCCEEDED(RoGetActivationFactory(appDataClassName,
1496                                               &kIID_IApplicationDataStatics,
1497                                               &appDataStatics))) {
1498         __x_ABI_CWindows_CStorage_CIApplicationData* appData = NULL;
1499         __x_ABI_CWindows_CStorage_CIStorageFolder* tempFolder = NULL;
1500         __x_ABI_CWindows_CStorage_CIStorageItem* tempFolderItem = NULL;
1501         HSTRING tempPath = NULL;
1502
1503         if (SUCCEEDED(appDataStatics->lpVtbl->get_Current(appDataStatics,
1504                                                           &appData))
1505             && SUCCEEDED(appData->lpVtbl->get_TemporaryFolder(appData,
1506                                                               &tempFolder))
1507             && SUCCEEDED(tempFolder->lpVtbl->QueryInterface(tempFolder,
1508                                                         &kIID_IStorageItem,
1509                                                         &tempFolderItem))
1510             && SUCCEEDED(tempFolderItem->lpVtbl->get_Path(tempFolderItem,
1511                                                           &tempPath))) {
1512           UINT32 tempPathLen;
1513           const wchar_t* tempPathBuf =
1514                           WindowsGetStringRawBuffer(tempPath, &tempPathLen);
1515
1516           buf[0] = '\0';
1517           if (wcsncat_s(buf, bufLen, tempPathBuf, tempPathLen) == 0
1518               && wcscat_s(buf, bufLen, L"\\") == 0
1519               && wcscat_s(buf, bufLen, TEXT(GC_LOG_STD_NAME)) == 0)
1520             result = TRUE;
1521           WindowsDeleteString(tempPath);
1522         }
1523
1524         if (tempFolderItem != NULL)
1525           tempFolderItem->lpVtbl->Release(tempFolderItem);
1526         if (tempFolder != NULL)
1527           tempFolder->lpVtbl->Release(tempFolder);
1528         if (appData != NULL)
1529           appData->lpVtbl->Release(appData);
1530         appDataStatics->lpVtbl->Release(appDataStatics);
1531       }
1532       return result;
1533     }
1534 # endif /* MSWINRT_FLAVOR */
1535
1536   STATIC HANDLE GC_CreateLogFile(void)
1537   {
1538     HANDLE hFile;
1539 # ifdef MSWINRT_FLAVOR
1540       TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
1541
1542       hFile = INVALID_HANDLE_VALUE;
1543       if (getWinRTLogPath(pathBuf, _MAX_PATH + 1)) {
1544         CREATEFILE2_EXTENDED_PARAMETERS extParams;
1545
1546         BZERO(&extParams, sizeof(extParams));
1547         extParams.dwSize = sizeof(extParams);
1548         extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
1549         extParams.dwFileFlags = GC_print_stats == VERBOSE ? 0
1550                                     : FILE_FLAG_WRITE_THROUGH;
1551         hFile = CreateFile2(pathBuf, GENERIC_WRITE, FILE_SHARE_READ,
1552                             CREATE_ALWAYS, &extParams);
1553       }
1554
1555 # else
1556     TCHAR *logPath;
1557     BOOL appendToFile = FALSE;
1558 #   if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
1559       TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
1560
1561       logPath = pathBuf;
1562 #   endif
1563
1564     /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */
1565 #   ifndef NO_GETENV_WIN32
1566       if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), pathBuf,
1567                                  _MAX_PATH + 1) - 1U < (DWORD)_MAX_PATH) {
1568         appendToFile = TRUE;
1569       } else
1570 #   endif
1571     /* else */ {
1572       /* Env var not found or its value too long.       */
1573 #     ifdef OLD_WIN32_LOG_FILE
1574         logPath = TEXT(GC_LOG_STD_NAME);
1575 #     else
1576         int len = (int)GetModuleFileName(NULL /* hModule */, pathBuf,
1577                                          _MAX_PATH + 1);
1578         /* If GetModuleFileName() has failed then len is 0. */
1579         if (len > 4 && pathBuf[len - 4] == (TCHAR)'.') {
1580           len -= 4; /* strip executable file extension */
1581         }
1582         BCOPY(TEXT(".") TEXT(GC_LOG_STD_NAME), &pathBuf[len],
1583               sizeof(TEXT(".") TEXT(GC_LOG_STD_NAME)));
1584 #     endif
1585     }
1586
1587     hFile = CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ,
1588                        NULL /* lpSecurityAttributes */,
1589                        appendToFile ? OPEN_ALWAYS : CREATE_ALWAYS,
1590                        GC_print_stats == VERBOSE ? FILE_ATTRIBUTE_NORMAL :
1591                             /* immediately flush writes unless very verbose */
1592                             FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
1593                        NULL /* hTemplateFile */);
1594
1595 #   ifndef NO_GETENV_WIN32
1596       if (appendToFile && hFile != INVALID_HANDLE_VALUE) {
1597         LONG posHigh = 0;
1598         (void)SetFilePointer(hFile, 0, &posHigh, FILE_END);
1599                                   /* Seek to file end (ignoring any error) */
1600       }
1601 #   endif
1602 # endif
1603     return hFile;
1604   }
1605
1606   STATIC int GC_write(const char *buf, size_t len)
1607   {
1608       BOOL res;
1609       DWORD written;
1610 #     if defined(THREADS) && defined(GC_ASSERTIONS)
1611         static GC_bool inside_write = FALSE;
1612                         /* to prevent infinite recursion at abort.      */
1613         if (inside_write)
1614           return -1;
1615 #     endif
1616
1617       if (len == 0)
1618           return 0;
1619       IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs));
1620 #     if defined(THREADS) && defined(GC_ASSERTIONS)
1621         if (GC_write_disabled) {
1622           inside_write = TRUE;
1623           ABORT("Assertion failure: GC_write called with write_disabled");
1624         }
1625 #     endif
1626       if (GC_log == 0) {
1627         GC_log = GC_CreateLogFile();
1628       }
1629       if (GC_log == INVALID_HANDLE_VALUE) {
1630         IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1631 #       ifdef NO_DEBUGGING
1632           /* Ignore open log failure (e.g., it might be caused by       */
1633           /* read-only folder of the client application).               */
1634           return 0;
1635 #       else
1636           return -1;
1637 #       endif
1638       }
1639       res = WriteFile(GC_log, buf, (DWORD)len, &written, NULL);
1640 #     if defined(_MSC_VER) && defined(_DEBUG) && !defined(NO_CRT)
1641 #         ifdef MSWINCE
1642               /* There is no CrtDbgReport() in WinCE */
1643               {
1644                   WCHAR wbuf[1024];
1645                   /* Always use Unicode variant of OutputDebugString() */
1646                   wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */,
1647                                 buf, len, wbuf,
1648                                 sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0;
1649                   OutputDebugStringW(wbuf);
1650               }
1651 #         else
1652               _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
1653 #         endif
1654 #     endif
1655       IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1656       return res ? (int)written : -1;
1657   }
1658
1659   /* TODO: This is pretty ugly ... */
1660 # define WRITE(f, buf, len) GC_write(buf, len)
1661
1662 #elif defined(OS2) || defined(MACOS)
1663   STATIC FILE * GC_stdout = NULL;
1664   STATIC FILE * GC_stderr = NULL;
1665   STATIC FILE * GC_log = NULL;
1666
1667   /* Initialize GC_log (and the friends) passed to GC_write().  */
1668   STATIC void GC_set_files(void)
1669   {
1670     if (GC_stdout == NULL) {
1671       GC_stdout = stdout;
1672     }
1673     if (GC_stderr == NULL) {
1674       GC_stderr = stderr;
1675     }
1676     if (GC_log == NULL) {
1677       GC_log = stderr;
1678     }
1679   }
1680
1681   GC_INLINE int GC_write(FILE *f, const char *buf, size_t len)
1682   {
1683     int res = fwrite(buf, 1, len, f);
1684     fflush(f);
1685     return res;
1686   }
1687
1688 # define WRITE(f, buf, len) (GC_set_files(), GC_write(f, buf, len))
1689
1690 #elif defined(GC_ANDROID_LOG)
1691
1692 # include <android/log.h>
1693
1694 # ifndef GC_ANDROID_LOG_TAG
1695 #   define GC_ANDROID_LOG_TAG "BDWGC"
1696 # endif
1697
1698 # define GC_stdout ANDROID_LOG_DEBUG
1699 # define GC_stderr ANDROID_LOG_ERROR
1700 # define GC_log GC_stdout
1701
1702 # define WRITE(level, buf, unused_len) \
1703                 __android_log_write(level, GC_ANDROID_LOG_TAG, buf)
1704
1705 # elif defined(NN_PLATFORM_CTR)
1706     int n3ds_log_write(const char* text, int length);
1707 #   define WRITE(level, buf, len) n3ds_log_write(buf, len)
1708 # elif defined(NINTENDO_SWITCH)
1709     int switch_log_write(const char* text, int length);
1710 #   define WRITE(level, buf, len) switch_log_write(buf, len)
1711
1712 #else
1713 # if !defined(AMIGA) && !defined(MSWIN_XBOX1) && !defined(SN_TARGET_ORBIS) \
1714      && !defined(SN_TARGET_PSP2) && !defined(__CC_ARM)
1715 #   include <unistd.h>
1716 # endif
1717
1718   STATIC int GC_write(int fd, const char *buf, size_t len)
1719   {
1720 #   if defined(ECOS) || defined(SN_TARGET_ORBIS) || defined(SN_TARGET_PSP2) \
1721        || defined(NOSYS)
1722 #     ifdef ECOS
1723         /* FIXME: This seems to be defined nowhere at present.  */
1724         /* _Jv_diag_write(buf, len); */
1725 #     else
1726         /* No writing.  */
1727 #     endif
1728       return len;
1729 #   else
1730       int bytes_written = 0;
1731       IF_CANCEL(int cancel_state;)
1732
1733       DISABLE_CANCEL(cancel_state);
1734       while ((unsigned)bytes_written < len) {
1735 #        ifdef GC_SOLARIS_THREADS
1736              int result = syscall(SYS_write, fd, buf + bytes_written,
1737                                              len - bytes_written);
1738 #        else
1739              int result = write(fd, buf + bytes_written, len - bytes_written);
1740 #        endif
1741
1742          if (-1 == result) {
1743              RESTORE_CANCEL(cancel_state);
1744              return(result);
1745          }
1746          bytes_written += result;
1747       }
1748       RESTORE_CANCEL(cancel_state);
1749       return(bytes_written);
1750 #   endif
1751   }
1752
1753 # define WRITE(f, buf, len) GC_write(f, buf, len)
1754 #endif /* !MSWIN32 && !OS2 && !MACOS && !GC_ANDROID_LOG */
1755
1756 #define BUFSZ 1024
1757
1758 #if defined(DJGPP) || defined(__STRICT_ANSI__)
1759   /* vsnprintf is missing in DJGPP (v2.0.3) */
1760 # define GC_VSNPRINTF(buf, bufsz, format, args) vsprintf(buf, format, args)
1761 #elif defined(_MSC_VER)
1762 # ifdef MSWINCE
1763     /* _vsnprintf is deprecated in WinCE */
1764 #   define GC_VSNPRINTF StringCchVPrintfA
1765 # else
1766 #   define GC_VSNPRINTF _vsnprintf
1767 # endif
1768 #else
1769 # define GC_VSNPRINTF vsnprintf
1770 #endif
1771
1772 /* A version of printf that is unlikely to call malloc, and is thus safer */
1773 /* to call from the collector in case malloc has been bound to GC_malloc. */
1774 /* Floating point arguments and formats should be avoided, since FP       */
1775 /* conversion is more likely to allocate memory.                          */
1776 /* Assumes that no more than BUFSZ-1 characters are written at once.      */
1777 #define GC_PRINTF_FILLBUF(buf, format) \
1778         do { \
1779           va_list args; \
1780           va_start(args, format); \
1781           (buf)[sizeof(buf) - 1] = 0x15; /* guard */ \
1782           (void)GC_VSNPRINTF(buf, sizeof(buf) - 1, format, args); \
1783           va_end(args); \
1784           if ((buf)[sizeof(buf) - 1] != 0x15) \
1785             ABORT("GC_printf clobbered stack"); \
1786         } while (0)
1787
1788 void GC_printf(const char *format, ...)
1789 {
1790     if (!GC_quiet) {
1791       char buf[BUFSZ + 1];
1792
1793       GC_PRINTF_FILLBUF(buf, format);
1794 #     ifdef NACL
1795         (void)WRITE(GC_stdout, buf, strlen(buf));
1796         /* Ignore errors silently.      */
1797 #     else
1798         if (WRITE(GC_stdout, buf, strlen(buf)) < 0)
1799           ABORT("write to stdout failed");
1800 #     endif
1801     }
1802 }
1803
1804 void GC_err_printf(const char *format, ...)
1805 {
1806     char buf[BUFSZ + 1];
1807
1808     GC_PRINTF_FILLBUF(buf, format);
1809     GC_err_puts(buf);
1810 }
1811
1812 void GC_log_printf(const char *format, ...)
1813 {
1814     char buf[BUFSZ + 1];
1815
1816     GC_PRINTF_FILLBUF(buf, format);
1817 #   ifdef NACL
1818       (void)WRITE(GC_log, buf, strlen(buf));
1819 #   else
1820       if (WRITE(GC_log, buf, strlen(buf)) < 0)
1821         ABORT("write to GC log failed");
1822 #   endif
1823 }
1824
1825 #ifndef GC_ANDROID_LOG
1826
1827 # define GC_warn_printf GC_err_printf
1828
1829 #else
1830
1831   GC_INNER void GC_info_log_printf(const char *format, ...)
1832   {
1833     char buf[BUFSZ + 1];
1834
1835     GC_PRINTF_FILLBUF(buf, format);
1836     (void)WRITE(ANDROID_LOG_INFO, buf, 0 /* unused */);
1837   }
1838
1839   GC_INNER void GC_verbose_log_printf(const char *format, ...)
1840   {
1841     char buf[BUFSZ + 1];
1842
1843     GC_PRINTF_FILLBUF(buf, format);
1844     (void)WRITE(ANDROID_LOG_VERBOSE, buf, 0); /* ignore write errors */
1845   }
1846
1847   STATIC void GC_warn_printf(const char *format, ...)
1848   {
1849     char buf[BUFSZ + 1];
1850
1851     GC_PRINTF_FILLBUF(buf, format);
1852     (void)WRITE(ANDROID_LOG_WARN, buf, 0);
1853   }
1854
1855 #endif /* GC_ANDROID_LOG */
1856
1857 void GC_err_puts(const char *s)
1858 {
1859     (void)WRITE(GC_stderr, s, strlen(s)); /* ignore errors */
1860 }
1861
1862 STATIC void GC_CALLBACK GC_default_warn_proc(char *msg, GC_word arg)
1863 {
1864     /* TODO: Add assertion on arg comply with msg (format).     */
1865     GC_warn_printf(msg, arg);
1866 }
1867
1868 GC_INNER GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1869
1870 /* This is recommended for production code (release). */
1871 GC_API void GC_CALLBACK GC_ignore_warn_proc(char *msg, GC_word arg)
1872 {
1873     if (GC_print_stats) {
1874       /* Don't ignore warnings if stats printing is on. */
1875       GC_default_warn_proc(msg, arg);
1876     }
1877 }
1878
1879 GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p)
1880 {
1881     DCL_LOCK_STATE;
1882     GC_ASSERT(NONNULL_ARG_NOT_NULL(p));
1883 #   ifdef GC_WIN32_THREADS
1884 #     ifdef CYGWIN32
1885         /* Need explicit GC_INIT call */
1886         GC_ASSERT(GC_is_initialized);
1887 #     else
1888         if (!GC_is_initialized) GC_init();
1889 #     endif
1890 #   endif
1891     LOCK();
1892     GC_current_warn_proc = p;
1893     UNLOCK();
1894 }
1895
1896 GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void)
1897 {
1898     GC_warn_proc result;
1899     DCL_LOCK_STATE;
1900     LOCK();
1901     result = GC_current_warn_proc;
1902     UNLOCK();
1903     return(result);
1904 }
1905
1906 #if !defined(PCR) && !defined(SMALL_CONFIG)
1907   /* Print (or display) a message before abnormal exit (including       */
1908   /* abort).  Invoked from ABORT(msg) macro (there msg is non-NULL)     */
1909   /* and from EXIT() macro (msg is NULL in that case).                  */
1910   STATIC void GC_CALLBACK GC_default_on_abort(const char *msg)
1911   {
1912 #   ifndef DONT_USE_ATEXIT
1913       skip_gc_atexit = TRUE; /* disable at-exit GC_gcollect() */
1914 #   endif
1915
1916     if (msg != NULL) {
1917 #     ifdef MSGBOX_ON_ERROR
1918         GC_win32_MessageBoxA(msg, "Fatal error in GC", MB_ICONERROR | MB_OK);
1919         /* Also duplicate msg to GC log file.   */
1920 #     endif
1921
1922 #   ifndef GC_ANDROID_LOG
1923       /* Avoid calling GC_err_printf() here, as GC_on_abort() could be  */
1924       /* called from it.  Note 1: this is not an atomic output.         */
1925       /* Note 2: possible write errors are ignored.                     */
1926 #     if defined(THREADS) && defined(GC_ASSERTIONS) \
1927          && (defined(MSWIN32) || defined(MSWINCE))
1928         if (!GC_write_disabled)
1929 #     endif
1930       {
1931         if (WRITE(GC_stderr, msg, strlen(msg)) >= 0)
1932           (void)WRITE(GC_stderr, "\n", 1);
1933       }
1934 #   else
1935       __android_log_assert("*" /* cond */, GC_ANDROID_LOG_TAG, "%s\n", msg);
1936 #   endif
1937     }
1938
1939 #   if !defined(NO_DEBUGGING) && !defined(GC_ANDROID_LOG)
1940       if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1941             /* In many cases it's easier to debug a running process.    */
1942             /* It's arguably nicer to sleep, but that makes it harder   */
1943             /* to look at the thread if the debugger doesn't know much  */
1944             /* about threads.                                           */
1945             for(;;) {
1946               /* Empty */
1947             }
1948       }
1949 #   endif
1950   }
1951
1952   GC_abort_func GC_on_abort = GC_default_on_abort;
1953
1954   GC_API void GC_CALL GC_set_abort_func(GC_abort_func fn)
1955   {
1956       DCL_LOCK_STATE;
1957       GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
1958       LOCK();
1959       GC_on_abort = fn;
1960       UNLOCK();
1961   }
1962
1963   GC_API GC_abort_func GC_CALL GC_get_abort_func(void)
1964   {
1965       GC_abort_func fn;
1966       DCL_LOCK_STATE;
1967       LOCK();
1968       fn = GC_on_abort;
1969       UNLOCK();
1970       return fn;
1971   }
1972 #endif /* !SMALL_CONFIG */
1973
1974 GC_API void GC_CALL GC_enable(void)
1975 {
1976     DCL_LOCK_STATE;
1977
1978     LOCK();
1979     GC_ASSERT(GC_dont_gc != 0); /* ensure no counter underflow */
1980     GC_dont_gc--;
1981     UNLOCK();
1982 }
1983
1984 GC_API void GC_CALL GC_disable(void)
1985 {
1986     DCL_LOCK_STATE;
1987     LOCK();
1988     GC_dont_gc++;
1989     UNLOCK();
1990 }
1991
1992 GC_API int GC_CALL GC_is_disabled(void)
1993 {
1994     return GC_dont_gc != 0;
1995 }
1996
1997 /* Helper procedures for new kind creation.     */
1998 GC_API void ** GC_CALL GC_new_free_list_inner(void)
1999 {
2000     void *result;
2001
2002     GC_ASSERT(I_HOLD_LOCK());
2003     result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1) * sizeof(ptr_t), PTRFREE);
2004     if (NULL == result) ABORT("Failed to allocate freelist for new kind");
2005     BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
2006     return (void **)result;
2007 }
2008
2009 GC_API void ** GC_CALL GC_new_free_list(void)
2010 {
2011     void ** result;
2012     DCL_LOCK_STATE;
2013     LOCK();
2014     result = GC_new_free_list_inner();
2015     UNLOCK();
2016     return result;
2017 }
2018
2019 GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr,
2020                                           int adjust, int clear)
2021 {
2022     unsigned result = GC_n_kinds;
2023
2024     GC_ASSERT(adjust == FALSE || adjust == TRUE);
2025     /* If an object is not needed to be cleared (when moved to the      */
2026     /* free list) then its descriptor should be zero to denote          */
2027     /* a pointer-free object (and, as a consequence, the size of the    */
2028     /* object should not be added to the descriptor template).          */
2029     GC_ASSERT(clear == TRUE
2030               || (descr == 0 && adjust == FALSE && clear == FALSE));
2031     if (result < MAXOBJKINDS) {
2032       GC_n_kinds++;
2033       GC_obj_kinds[result].ok_freelist = fl;
2034       GC_obj_kinds[result].ok_reclaim_list = 0;
2035       GC_obj_kinds[result].ok_descriptor = descr;
2036       GC_obj_kinds[result].ok_relocate_descr = adjust;
2037       GC_obj_kinds[result].ok_init = (GC_bool)clear;
2038 #     ifdef ENABLE_DISCLAIM
2039         GC_obj_kinds[result].ok_mark_unconditionally = FALSE;
2040         GC_obj_kinds[result].ok_disclaim_proc = 0;
2041 #     endif
2042     } else {
2043       ABORT("Too many kinds");
2044     }
2045     return result;
2046 }
2047
2048 GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust,
2049                                     int clear)
2050 {
2051     unsigned result;
2052     DCL_LOCK_STATE;
2053     LOCK();
2054     result = GC_new_kind_inner(fl, descr, adjust, clear);
2055     UNLOCK();
2056     return result;
2057 }
2058
2059 GC_API unsigned GC_CALL GC_new_proc_inner(GC_mark_proc proc)
2060 {
2061     unsigned result = GC_n_mark_procs;
2062
2063     if (result < MAX_MARK_PROCS) {
2064       GC_n_mark_procs++;
2065       GC_mark_procs[result] = proc;
2066     } else {
2067       ABORT("Too many mark procedures");
2068     }
2069     return result;
2070 }
2071
2072 GC_API unsigned GC_CALL GC_new_proc(GC_mark_proc proc)
2073 {
2074     unsigned result;
2075     DCL_LOCK_STATE;
2076     LOCK();
2077     result = GC_new_proc_inner(proc);
2078     UNLOCK();
2079     return result;
2080 }
2081
2082 GC_API void * GC_CALL GC_call_with_alloc_lock(GC_fn_type fn, void *client_data)
2083 {
2084     void * result;
2085     DCL_LOCK_STATE;
2086
2087 #   ifdef THREADS
2088       LOCK();
2089 #   endif
2090     result = (*fn)(client_data);
2091 #   ifdef THREADS
2092       UNLOCK();
2093 #   endif
2094     return(result);
2095 }
2096
2097 GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
2098 {
2099     struct GC_stack_base base;
2100     void *result;
2101
2102     base.mem_base = (void *)&base;
2103 #   ifdef IA64
2104       base.reg_base = (void *)GC_save_regs_in_stack();
2105       /* Unnecessarily flushes register stack,          */
2106       /* but that probably doesn't hurt.                */
2107 #   endif
2108     result = fn(&base, arg);
2109     /* Strongly discourage the compiler from treating the above */
2110     /* as a tail call.                                          */
2111     GC_noop1(COVERT_DATAFLOW(&base));
2112     return result;
2113 }
2114
2115 #ifndef THREADS
2116
2117 GC_INNER ptr_t GC_blocked_sp = NULL;
2118         /* NULL value means we are not inside GC_do_blocking() call. */
2119 # ifdef IA64
2120     STATIC ptr_t GC_blocked_register_sp = NULL;
2121 # endif
2122
2123 GC_INNER struct GC_traced_stack_sect_s *GC_traced_stack_sect = NULL;
2124
2125 /* This is nearly the same as in win32_threads.c        */
2126 GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
2127                                              void * client_data)
2128 {
2129     struct GC_traced_stack_sect_s stacksect;
2130     GC_ASSERT(GC_is_initialized);
2131
2132     /* Adjust our stack bottom pointer (this could happen if    */
2133     /* GC_get_main_stack_base() is unimplemented or broken for  */
2134     /* the platform).                                           */
2135     if ((word)GC_stackbottom HOTTER_THAN (word)(&stacksect))
2136       GC_stackbottom = (ptr_t)COVERT_DATAFLOW(&stacksect);
2137
2138     if (GC_blocked_sp == NULL) {
2139       /* We are not inside GC_do_blocking() - do nothing more.  */
2140       client_data = fn(client_data);
2141       /* Prevent treating the above as a tail call.     */
2142       GC_noop1(COVERT_DATAFLOW(&stacksect));
2143       return client_data; /* result */
2144     }
2145
2146     /* Setup new "stack section".       */
2147     stacksect.saved_stack_ptr = GC_blocked_sp;
2148 #   ifdef IA64
2149       /* This is the same as in GC_call_with_stack_base().      */
2150       stacksect.backing_store_end = GC_save_regs_in_stack();
2151       /* Unnecessarily flushes register stack,          */
2152       /* but that probably doesn't hurt.                */
2153       stacksect.saved_backing_store_ptr = GC_blocked_register_sp;
2154 #   endif
2155     stacksect.prev = GC_traced_stack_sect;
2156     GC_blocked_sp = NULL;
2157     GC_traced_stack_sect = &stacksect;
2158
2159     client_data = fn(client_data);
2160     GC_ASSERT(GC_blocked_sp == NULL);
2161     GC_ASSERT(GC_traced_stack_sect == &stacksect);
2162
2163 #   if defined(CPPCHECK)
2164       GC_noop1((word)GC_traced_stack_sect - (word)GC_blocked_sp);
2165 #   endif
2166     /* Restore original "stack section".        */
2167     GC_traced_stack_sect = stacksect.prev;
2168 #   ifdef IA64
2169       GC_blocked_register_sp = stacksect.saved_backing_store_ptr;
2170 #   endif
2171     GC_blocked_sp = stacksect.saved_stack_ptr;
2172
2173     return client_data; /* result */
2174 }
2175
2176 /* This is nearly the same as in win32_threads.c        */
2177 STATIC void GC_do_blocking_inner(ptr_t data, void * context GC_ATTR_UNUSED)
2178 {
2179     struct blocking_data * d = (struct blocking_data *) data;
2180     GC_ASSERT(GC_is_initialized);
2181     GC_ASSERT(GC_blocked_sp == NULL);
2182 #   ifdef SPARC
2183         GC_blocked_sp = GC_save_regs_in_stack();
2184 #   else
2185         GC_blocked_sp = (ptr_t) &d; /* save approx. sp */
2186 #   endif
2187 #   ifdef IA64
2188         GC_blocked_register_sp = GC_save_regs_in_stack();
2189 #   endif
2190
2191     d -> client_data = (d -> fn)(d -> client_data);
2192
2193 #   ifdef SPARC
2194         GC_ASSERT(GC_blocked_sp != NULL);
2195 #   else
2196         GC_ASSERT(GC_blocked_sp == (ptr_t)(&d));
2197 #   endif
2198 #   if defined(CPPCHECK)
2199       GC_noop1((word)GC_blocked_sp);
2200 #   endif
2201     GC_blocked_sp = NULL;
2202 }
2203
2204   GC_API void GC_CALL GC_set_stackbottom(void *gc_thread_handle,
2205                                          const struct GC_stack_base *sb)
2206   {
2207     GC_ASSERT(sb -> mem_base != NULL);
2208     GC_ASSERT(NULL == gc_thread_handle || &GC_stackbottom == gc_thread_handle);
2209     GC_ASSERT(NULL == GC_blocked_sp
2210               && NULL == GC_traced_stack_sect); /* for now */
2211     (void)gc_thread_handle;
2212
2213     GC_stackbottom = (char *)sb->mem_base;
2214 #   ifdef IA64
2215       GC_register_stackbottom = (ptr_t)sb->reg_base;
2216 #   endif
2217   }
2218
2219   GC_API void * GC_CALL GC_get_my_stackbottom(struct GC_stack_base *sb)
2220   {
2221     GC_ASSERT(GC_is_initialized);
2222     sb -> mem_base = GC_stackbottom;
2223 #   ifdef IA64
2224       sb -> reg_base = GC_register_stackbottom;
2225 #   endif
2226     return &GC_stackbottom; /* gc_thread_handle */
2227   }
2228 #endif /* !THREADS */
2229
2230 GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data)
2231 {
2232     struct blocking_data my_data;
2233
2234     my_data.fn = fn;
2235     my_data.client_data = client_data;
2236     GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
2237     return my_data.client_data; /* result */
2238 }
2239
2240 #if !defined(NO_DEBUGGING)
2241   GC_API void GC_CALL GC_dump(void)
2242   {
2243     DCL_LOCK_STATE;
2244
2245     LOCK();
2246     GC_dump_named(NULL);
2247     UNLOCK();
2248   }
2249
2250   GC_API void GC_CALL GC_dump_named(const char *name)
2251   {
2252 #   ifndef NO_CLOCK
2253       CLOCK_TYPE current_time;
2254
2255       GET_TIME(current_time);
2256 #   endif
2257     if (name != NULL) {
2258       GC_printf("***GC Dump %s\n", name);
2259     } else {
2260       GC_printf("***GC Dump collection #%lu\n", (unsigned long)GC_gc_no);
2261     }
2262 #   ifndef NO_CLOCK
2263       /* Note that the time is wrapped in ~49 days if sizeof(long)==4.  */
2264       GC_printf("Time since GC init: %lu ms\n",
2265                 MS_TIME_DIFF(current_time, GC_init_time));
2266 #   endif
2267
2268     GC_printf("\n***Static roots:\n");
2269     GC_print_static_roots();
2270     GC_printf("\n***Heap sections:\n");
2271     GC_print_heap_sects();
2272     GC_printf("\n***Free blocks:\n");
2273     GC_print_hblkfreelist();
2274     GC_printf("\n***Blocks in use:\n");
2275     GC_print_block_list();
2276   }
2277 #endif /* !NO_DEBUGGING */
2278
2279 static void block_add_size(struct hblk *h, word pbytes)
2280 {
2281   hdr *hhdr = HDR(h);
2282   *(word *)pbytes += (WORDS_TO_BYTES(hhdr->hb_sz) + (HBLKSIZE - 1))
2283                         & ~(word)(HBLKSIZE - 1);
2284 }
2285
2286 GC_API size_t GC_CALL GC_get_memory_use(void)
2287 {
2288   word bytes = 0;
2289   DCL_LOCK_STATE;
2290
2291   LOCK();
2292   GC_apply_to_all_blocks(block_add_size, (word)(&bytes));
2293   UNLOCK();
2294   return (size_t)bytes;
2295 }
2296
2297 /* Getter functions for the public Read-only variables.                 */
2298
2299 /* GC_get_gc_no() is unsynchronized and should be typically called      */
2300 /* inside the context of GC_call_with_alloc_lock() to prevent data      */
2301 /* races (on multiprocessors).                                          */
2302 GC_API GC_word GC_CALL GC_get_gc_no(void)
2303 {
2304     return GC_gc_no;
2305 }
2306
2307 #ifdef THREADS
2308   GC_API int GC_CALL GC_get_parallel(void)
2309   {
2310     /* GC_parallel is initialized at start-up.  */
2311     return GC_parallel;
2312   }
2313
2314   GC_API void GC_CALL GC_alloc_lock(void)
2315   {
2316     DCL_LOCK_STATE;
2317     LOCK();
2318   }
2319
2320   GC_API void GC_CALL GC_alloc_unlock(void)
2321   {
2322     /* no DCL_LOCK_STATE */
2323     UNLOCK();
2324   }
2325
2326   GC_INNER GC_on_thread_event_proc GC_on_thread_event = 0;
2327
2328   GC_API void GC_CALL GC_set_on_thread_event(GC_on_thread_event_proc fn)
2329   {
2330     /* fn may be 0 (means no event notifier). */
2331     DCL_LOCK_STATE;
2332     LOCK();
2333     GC_on_thread_event = fn;
2334     UNLOCK();
2335   }
2336
2337   GC_API GC_on_thread_event_proc GC_CALL GC_get_on_thread_event(void)
2338   {
2339     GC_on_thread_event_proc fn;
2340     DCL_LOCK_STATE;
2341     LOCK();
2342     fn = GC_on_thread_event;
2343     UNLOCK();
2344     return fn;
2345   }
2346 #endif /* THREADS */
2347
2348 /* Setter and getter functions for the public R/W function variables.   */
2349 /* These functions are synchronized (like GC_set_warn_proc() and        */
2350 /* GC_get_warn_proc()).                                                 */
2351
2352 GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn)
2353 {
2354     GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
2355     DCL_LOCK_STATE;
2356     LOCK();
2357     GC_oom_fn = fn;
2358     UNLOCK();
2359 }
2360
2361 GC_API GC_oom_func GC_CALL GC_get_oom_fn(void)
2362 {
2363     GC_oom_func fn;
2364     DCL_LOCK_STATE;
2365     LOCK();
2366     fn = GC_oom_fn;
2367     UNLOCK();
2368     return fn;
2369 }
2370
2371 GC_API void GC_CALL GC_set_on_heap_resize(GC_on_heap_resize_proc fn)
2372 {
2373     /* fn may be 0 (means no event notifier). */
2374     DCL_LOCK_STATE;
2375     LOCK();
2376     GC_on_heap_resize = fn;
2377     UNLOCK();
2378 }
2379
2380 GC_API GC_on_heap_resize_proc GC_CALL GC_get_on_heap_resize(void)
2381 {
2382     GC_on_heap_resize_proc fn;
2383     DCL_LOCK_STATE;
2384     LOCK();
2385     fn = GC_on_heap_resize;
2386     UNLOCK();
2387     return fn;
2388 }
2389
2390 GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc fn)
2391 {
2392     /* fn may be 0 (means no finalizer notifier). */
2393     DCL_LOCK_STATE;
2394     LOCK();
2395     GC_finalizer_notifier = fn;
2396     UNLOCK();
2397 }
2398
2399 GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void)
2400 {
2401     GC_finalizer_notifier_proc fn;
2402     DCL_LOCK_STATE;
2403     LOCK();
2404     fn = GC_finalizer_notifier;
2405     UNLOCK();
2406     return fn;
2407 }
2408
2409 /* Setter and getter functions for the public numeric R/W variables.    */
2410 /* It is safe to call these functions even before GC_INIT().            */
2411 /* These functions are unsynchronized and should be typically called    */
2412 /* inside the context of GC_call_with_alloc_lock() (if called after     */
2413 /* GC_INIT()) to prevent data races (unless it is guaranteed the        */
2414 /* collector is not multi-threaded at that execution point).            */
2415
2416 GC_API void GC_CALL GC_set_find_leak(int value)
2417 {
2418     /* value is of boolean type. */
2419     GC_find_leak = value;
2420 }
2421
2422 GC_API int GC_CALL GC_get_find_leak(void)
2423 {
2424     return GC_find_leak;
2425 }
2426
2427 GC_API void GC_CALL GC_set_all_interior_pointers(int value)
2428 {
2429     DCL_LOCK_STATE;
2430
2431     GC_all_interior_pointers = value ? 1 : 0;
2432     if (GC_is_initialized) {
2433       /* It is not recommended to change GC_all_interior_pointers value */
2434       /* after GC is initialized but it seems GC could work correctly   */
2435       /* even after switching the mode.                                 */
2436       LOCK();
2437       GC_initialize_offsets(); /* NOTE: this resets manual offsets as well */
2438       if (!GC_all_interior_pointers)
2439         GC_bl_init_no_interiors();
2440       UNLOCK();
2441     }
2442 }
2443
2444 GC_API int GC_CALL GC_get_all_interior_pointers(void)
2445 {
2446     return GC_all_interior_pointers;
2447 }
2448
2449 GC_API void GC_CALL GC_set_finalize_on_demand(int value)
2450 {
2451     GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2452     /* value is of boolean type. */
2453     GC_finalize_on_demand = value;
2454 }
2455
2456 GC_API int GC_CALL GC_get_finalize_on_demand(void)
2457 {
2458     return GC_finalize_on_demand;
2459 }
2460
2461 GC_API void GC_CALL GC_set_java_finalization(int value)
2462 {
2463     GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2464     /* value is of boolean type. */
2465     GC_java_finalization = value;
2466 }
2467
2468 GC_API int GC_CALL GC_get_java_finalization(void)
2469 {
2470     return GC_java_finalization;
2471 }
2472
2473 GC_API void GC_CALL GC_set_dont_expand(int value)
2474 {
2475     GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2476     /* value is of boolean type. */
2477     GC_dont_expand = value;
2478 }
2479
2480 GC_API int GC_CALL GC_get_dont_expand(void)
2481 {
2482     return GC_dont_expand;
2483 }
2484
2485 GC_API void GC_CALL GC_set_no_dls(int value)
2486 {
2487     GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2488     /* value is of boolean type. */
2489     GC_no_dls = value;
2490 }
2491
2492 GC_API int GC_CALL GC_get_no_dls(void)
2493 {
2494     return GC_no_dls;
2495 }
2496
2497 GC_API void GC_CALL GC_set_non_gc_bytes(GC_word value)
2498 {
2499     GC_non_gc_bytes = value;
2500 }
2501
2502 GC_API GC_word GC_CALL GC_get_non_gc_bytes(void)
2503 {
2504     return GC_non_gc_bytes;
2505 }
2506
2507 GC_API void GC_CALL GC_set_free_space_divisor(GC_word value)
2508 {
2509     GC_ASSERT(value > 0);
2510     GC_free_space_divisor = value;
2511 }
2512
2513 GC_API GC_word GC_CALL GC_get_free_space_divisor(void)
2514 {
2515     return GC_free_space_divisor;
2516 }
2517
2518 GC_API void GC_CALL GC_set_max_retries(GC_word value)
2519 {
2520     GC_ASSERT((GC_signed_word)value != -1);
2521                         /* -1 was used to retrieve old value in gc-7.2 */
2522     GC_max_retries = value;
2523 }
2524
2525 GC_API GC_word GC_CALL GC_get_max_retries(void)
2526 {
2527     return GC_max_retries;
2528 }
2529
2530 GC_API void GC_CALL GC_set_dont_precollect(int value)
2531 {
2532     GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2533     /* value is of boolean type. */
2534     GC_dont_precollect = value;
2535 }
2536
2537 GC_API int GC_CALL GC_get_dont_precollect(void)
2538 {
2539     return GC_dont_precollect;
2540 }
2541
2542 GC_API void GC_CALL GC_set_full_freq(int value)
2543 {
2544     GC_ASSERT(value >= 0);
2545     GC_full_freq = value;
2546 }
2547
2548 GC_API int GC_CALL GC_get_full_freq(void)
2549 {
2550     return GC_full_freq;
2551 }
2552
2553 GC_API void GC_CALL GC_set_time_limit(unsigned long value)
2554 {
2555     GC_ASSERT((long)value != -1L);
2556                         /* -1 was used to retrieve old value in gc-7.2 */
2557     GC_time_limit = value;
2558 }
2559
2560 GC_API unsigned long GC_CALL GC_get_time_limit(void)
2561 {
2562     return GC_time_limit;
2563 }
2564
2565 GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int value)
2566 {
2567     GC_force_unmap_on_gcollect = (GC_bool)value;
2568 }
2569
2570 GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void)
2571 {
2572     return (int)GC_force_unmap_on_gcollect;
2573 }
2574
2575 GC_API void GC_CALL GC_abort_on_oom(void)
2576 {
2577     GC_err_printf("Insufficient memory for the allocation\n");
2578     EXIT();
2579 }
2580
2581 #ifdef THREADS
2582   GC_API void GC_CALL GC_stop_world_external(void)
2583   {
2584     GC_ASSERT(GC_is_initialized);
2585     LOCK();
2586 #   ifdef THREAD_LOCAL_ALLOC
2587       GC_ASSERT(!GC_world_stopped);
2588 #   endif
2589     STOP_WORLD();
2590 #   ifdef THREAD_LOCAL_ALLOC
2591       GC_world_stopped = TRUE;
2592 #   endif
2593   }
2594
2595   GC_API void GC_CALL GC_start_world_external(void)
2596   {
2597 #   ifdef THREAD_LOCAL_ALLOC
2598       GC_ASSERT(GC_world_stopped);
2599       GC_world_stopped = FALSE;
2600 #   else
2601       GC_ASSERT(GC_is_initialized);
2602 #   endif
2603     START_WORLD();
2604     UNLOCK();
2605   }
2606 #endif /* THREADS */