Clean merge -> gc7-branch
[cacao.git] / src / mm / boehm-gc / include / gc.h
1 /* 
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
4  * Copyright 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright 1999 by Hewlett-Packard Company.  All rights reserved.
6  * Copyright (C) 2007 Free Software Foundation, Inc
7  *
8  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
10  *
11  * Permission is hereby granted to use or copy this program
12  * for any purpose,  provided the above notices are retained on all copies.
13  * Permission to modify the code and to distribute modified code is granted,
14  * provided the above notices are retained, and a notice that the code was
15  * modified is included with the above copyright notice.
16  */
17
18 /*
19  * Note that this defines a large number of tuning hooks, which can
20  * safely be ignored in nearly all cases.  For normal use it suffices
21  * to call only GC_MALLOC and perhaps GC_REALLOC.
22  * For better performance, also look at GC_MALLOC_ATOMIC, and
23  * GC_enable_incremental.  If you need an action to be performed
24  * immediately before an object is collected, look at GC_register_finalizer.
25  * If you are using Solaris threads, look at the end of this file.
26  * Everything else is best ignored unless you encounter performance
27  * problems.
28  */
29  
30 #ifndef _GC_H
31
32 # define _GC_H
33
34 # include "gc_config_macros.h"
35
36 # ifdef __cplusplus
37     extern "C" {
38 # endif
39
40
41 /* Define word and signed_word to be unsigned and signed types of the   */
42 /* size as char * or void *.  There seems to be no way to do this       */
43 /* even semi-portably.  The following is probably no better/worse       */
44 /* than almost anything else.                                           */
45 /* The ANSI standard suggests that size_t and ptr_diff_t might be       */
46 /* better choices.  But those had incorrect definitions on some older   */
47 /* systems.  Notably "typedef int size_t" is WRONG.                     */
48 #ifndef _WIN64
49   typedef unsigned long GC_word;
50   typedef long GC_signed_word;
51 #else
52   /* Win64 isn't really supported yet, but this is the first step. And  */
53   /* it might cause error messages to show up in more plausible places. */
54   /* This needs basetsd.h, which is included by windows.h.              */
55   typedef unsigned long long GC_word;
56   typedef long long GC_signed_word;
57 #endif
58
59 /* Public read-only variables */
60
61 GC_API GC_word GC_gc_no;/* Counter incremented per collection.          */
62                         /* Includes empty GCs at startup.               */
63
64 GC_API int GC_parallel; /* GC is parallelized for performance on        */
65                         /* multiprocessors.  Currently set only         */
66                         /* implicitly if collector is built with        */
67                         /* -DPARALLEL_MARK and if either:               */
68                         /*  Env variable GC_NPROC is set to > 1, or     */
69                         /*  GC_NPROC is not set and this is an MP.      */
70                         /* If GC_parallel is set, incremental           */
71                         /* collection is only partially functional,     */
72                         /* and may not be desirable.                    */
73                         
74
75 /* Public R/W variables */
76
77 GC_API void * (*GC_oom_fn) (size_t bytes_requested);
78                         /* When there is insufficient memory to satisfy */
79                         /* an allocation request, we return             */
80                         /* (*GC_oom_fn)().  By default this just        */
81                         /* returns 0.                                   */
82                         /* If it returns, it must return 0 or a valid   */
83                         /* pointer to a previously allocated heap       */
84                         /* object.                                      */
85
86 GC_API int GC_find_leak;
87                         /* Do not actually garbage collect, but simply  */
88                         /* report inaccessible memory that was not      */
89                         /* deallocated with GC_free.  Initial value     */
90                         /* is determined by FIND_LEAK macro.            */
91
92 GC_API int GC_all_interior_pointers;
93                         /* Arrange for pointers to object interiors to  */
94                         /* be recognized as valid.  May not be changed  */
95                         /* after GC initialization.                     */
96                         /* Initial value is determined by               */
97                         /* -DALL_INTERIOR_POINTERS.                     */
98                         /* Unless DONT_ADD_BYTE_AT_END is defined, this */
99                         /* also affects whether sizes are increased by  */
100                         /* at least a byte to allow "off the end"       */
101                         /* pointer recognition.                         */
102                         /* MUST BE 0 or 1.                              */
103
104 GC_API int GC_finalize_on_demand;
105                         /* If nonzero, finalizers will only be run in   */
106                         /* response to an explicit GC_invoke_finalizers */
107                         /* call.  The default is determined by whether  */
108                         /* the FINALIZE_ON_DEMAND macro is defined      */
109                         /* when the collector is built.                 */
110
111 GC_API int GC_java_finalization;
112                         /* Mark objects reachable from finalizable      */
113                         /* objects in a separate postpass.  This makes  */
114                         /* it a bit safer to use non-topologically-     */
115                         /* ordered finalization.  Default value is      */
116                         /* determined by JAVA_FINALIZATION macro.       */
117                         /* Enables register_finalizer_unreachable to    */
118                         /* work correctly.                              */
119
120 GC_API void (* GC_finalizer_notifier)(void);
121                         /* Invoked by the collector when there are      */
122                         /* objects to be finalized.  Invoked at most    */
123                         /* once per GC cycle.  Never invoked unless     */
124                         /* GC_finalize_on_demand is set.                */
125                         /* Typically this will notify a finalization    */
126                         /* thread, which will call GC_invoke_finalizers */
127                         /* in response.                                 */
128
129 GC_API int GC_dont_gc;  /* != 0 ==> Dont collect.  In versions 6.2a1+,  */
130                         /* this overrides explicit GC_gcollect() calls. */
131                         /* Used as a counter, so that nested enabling   */
132                         /* and disabling work correctly.  Should        */
133                         /* normally be updated with GC_enable() and     */
134                         /* GC_disable() calls.                          */
135                         /* Direct assignment to GC_dont_gc is           */
136                         /* deprecated.                                  */
137
138 GC_API int GC_dont_expand;
139                         /* Dont expand heap unless explicitly requested */
140                         /* or forced to.                                */
141
142 GC_API int GC_use_entire_heap;
143                 /* Causes the nonincremental collector to use the       */
144                 /* entire heap before collecting.  This was the only    */
145                 /* option for GC versions < 5.0.  This sometimes        */
146                 /* results in more large block fragmentation, since     */
147                 /* very larg blocks will tend to get broken up          */
148                 /* during each GC cycle.  It is likely to result in a   */
149                 /* larger working set, but lower collection             */
150                 /* frequencies, and hence fewer instructions executed   */
151                 /* in the collector.                                    */
152
153 GC_API int GC_full_freq;    /* Number of partial collections between    */
154                             /* full collections.  Matters only if       */
155                             /* GC_incremental is set.                   */
156                             /* Full collections are also triggered if   */
157                             /* the collector detects a substantial      */
158                             /* increase in the number of in-use heap    */
159                             /* blocks.  Values in the tens are now      */
160                             /* perfectly reasonable, unlike for         */
161                             /* earlier GC versions.                     */
162                         
163 GC_API GC_word GC_non_gc_bytes;
164                         /* Bytes not considered candidates for collection. */
165                         /* Used only to control scheduling of collections. */
166                         /* Updated by GC_malloc_uncollectable and GC_free. */
167                         /* Wizards only.                                   */
168
169 GC_API int GC_no_dls;
170                         /* Don't register dynamic library data segments. */
171                         /* Wizards only.  Should be used only if the     */
172                         /* application explicitly registers all roots.   */
173                         /* In Microsoft Windows environments, this will  */
174                         /* usually also prevent registration of the      */
175                         /* main data segment as part of the root set.    */
176
177 GC_API GC_word GC_free_space_divisor;
178                         /* We try to make sure that we allocate at      */
179                         /* least N/GC_free_space_divisor bytes between  */
180                         /* collections, where N is twice the number     */
181                         /* of traced bytes, plus the number of untraced */
182                         /* bytes (bytes in "atomic" objects), plus      */
183                         /* a rough estimate of the root set size.       */
184                         /* N approximates GC tracing work per GC.       */
185                         /* Initially, GC_free_space_divisor = 3.        */
186                         /* Increasing its value will use less space     */
187                         /* but more collection time.  Decreasing it     */
188                         /* will appreciably decrease collection time    */
189                         /* at the expense of space.                     */
190
191 GC_API GC_word GC_max_retries;
192                         /* The maximum number of GCs attempted before   */
193                         /* reporting out of memory after heap           */
194                         /* expansion fails.  Initially 0.               */
195                         
196
197 GC_API char *GC_stackbottom;    /* Cool end of user stack.              */
198                                 /* May be set in the client prior to    */
199                                 /* calling any GC_ routines.  This      */
200                                 /* avoids some overhead, and            */
201                                 /* potentially some signals that can    */
202                                 /* confuse debuggers.  Otherwise the    */
203                                 /* collector attempts to set it         */
204                                 /* automatically.                       */
205                                 /* For multithreaded code, this is the  */
206                                 /* cold end of the stack for the        */
207                                 /* primordial thread.                   */      
208                                 
209 GC_API int GC_dont_precollect;  /* Don't collect as part of             */
210                                 /* initialization.  Should be set only  */
211                                 /* if the client wants a chance to      */
212                                 /* manually initialize the root set     */
213                                 /* before the first collection.         */
214                                 /* Interferes with blacklisting.        */
215                                 /* Wizards only.                        */
216
217 GC_API unsigned long GC_time_limit;
218                                 /* If incremental collection is enabled, */
219                                 /* We try to terminate collections       */
220                                 /* after this many milliseconds.  Not a  */
221                                 /* hard time bound.  Setting this to     */
222                                 /* GC_TIME_UNLIMITED will essentially    */
223                                 /* disable incremental collection while  */
224                                 /* leaving generational collection       */
225                                 /* enabled.                              */
226 #       define GC_TIME_UNLIMITED 999999
227                                 /* Setting GC_time_limit to this value   */
228                                 /* will disable the "pause time exceeded"*/
229                                 /* tests.                                */
230
231 /* Public procedures */
232
233 /* Initialize the collector.  This is only required when using thread-local
234  * allocation, since unlike the regular allocation routines, GC_local_malloc
235  * is not self-initializing.  If you use GC_local_malloc you should arrange
236  * to call this somehow (e.g. from a constructor) before doing any allocation.
237  * For win32 threads, it needs to be called explicitly.
238  */
239 GC_API void GC_init(void);
240
241 /* Added for cacao */
242 int GC_signum1();   
243 int GC_signum2();   
244 /* cacao END */
245
246 /*
247  * general purpose allocation routines, with roughly malloc calling conv.
248  * The atomic versions promise that no relevant pointers are contained
249  * in the object.  The nonatomic versions guarantee that the new object
250  * is cleared.  GC_malloc_stubborn promises that no changes to the object
251  * will occur after GC_end_stubborn_change has been called on the
252  * result of GC_malloc_stubborn. GC_malloc_uncollectable allocates an object
253  * that is scanned for pointers to collectable objects, but is not itself
254  * collectable.  The object is scanned even if it does not appear to
255  * be reachable.  GC_malloc_uncollectable and GC_free called on the resulting
256  * object implicitly update GC_non_gc_bytes appropriately.
257  *
258  * Note that the GC_malloc_stubborn support is stubbed out by default
259  * starting in 6.0.  GC_malloc_stubborn is an alias for GC_malloc unless
260  * the collector is built with STUBBORN_ALLOC defined.
261  */
262 GC_API void * GC_malloc(size_t size_in_bytes);
263 GC_API void * GC_malloc_atomic(size_t size_in_bytes);
264 GC_API char * GC_strdup (const char *str);
265 GC_API void * GC_malloc_uncollectable(size_t size_in_bytes);
266 GC_API void * GC_malloc_stubborn(size_t size_in_bytes);
267
268 /* The following is only defined if the library has been suitably       */
269 /* compiled:                                                            */
270 GC_API void * GC_malloc_atomic_uncollectable(size_t size_in_bytes);
271
272 /* Explicitly deallocate an object.  Dangerous if used incorrectly.     */
273 /* Requires a pointer to the base of an object.                         */
274 /* If the argument is stubborn, it should not be changeable when freed. */
275 /* An object should not be enable for finalization when it is           */
276 /* explicitly deallocated.                                              */
277 /* GC_free(0) is a no-op, as required by ANSI C for free.               */
278 GC_API void GC_free(void * object_addr);
279
280 /*
281  * Stubborn objects may be changed only if the collector is explicitly informed.
282  * The collector is implicitly informed of coming change when such
283  * an object is first allocated.  The following routines inform the
284  * collector that an object will no longer be changed, or that it will
285  * once again be changed.  Only nonNIL pointer stores into the object
286  * are considered to be changes.  The argument to GC_end_stubborn_change
287  * must be exacly the value returned by GC_malloc_stubborn or passed to
288  * GC_change_stubborn.  (In the second case it may be an interior pointer
289  * within 512 bytes of the beginning of the objects.)
290  * There is a performance penalty for allowing more than
291  * one stubborn object to be changed at once, but it is acceptable to
292  * do so.  The same applies to dropping stubborn objects that are still
293  * changeable.
294  */
295 GC_API void GC_change_stubborn(void *);
296 GC_API void GC_end_stubborn_change(void *);
297
298 /* Return a pointer to the base (lowest address) of an object given     */
299 /* a pointer to a location within the object.                           */
300 /* I.e. map an interior pointer to the corresponding bas pointer.       */
301 /* Note that with debugging allocation, this returns a pointer to the   */
302 /* actual base of the object, i.e. the debug information, not to        */
303 /* the base of the user object.                                         */
304 /* Return 0 if displaced_pointer doesn't point to within a valid        */
305 /* object.                                                              */
306 /* Note that a deallocated object in the garbage collected heap         */
307 /* may be considered valid, even if it has been deallocated with        */
308 /* GC_free.                                                             */
309 GC_API void * GC_base(void * displaced_pointer);
310
311 /* Given a pointer to the base of an object, return its size in bytes.  */
312 /* The returned size may be slightly larger than what was originally    */
313 /* requested.                                                           */
314 GC_API size_t GC_size(void * object_addr);
315
316 /* For compatibility with C library.  This is occasionally faster than  */
317 /* a malloc followed by a bcopy.  But if you rely on that, either here  */
318 /* or with the standard C library, your code is broken.  In my          */
319 /* opinion, it shouldn't have been invented, but now we're stuck. -HB   */
320 /* The resulting object has the same kind as the original.              */
321 /* If the argument is stubborn, the result will have changes enabled.   */
322 /* It is an error to have changes enabled for the original object.      */
323 /* Follows ANSI comventions for NULL old_object.                        */
324 GC_API void * GC_realloc(void * old_object, size_t new_size_in_bytes);
325                                    
326 /* Explicitly increase the heap size.   */
327 /* Returns 0 on failure, 1 on success.  */
328 GC_API int GC_expand_hp(size_t number_of_bytes);
329
330 /* Limit the heap size to n bytes.  Useful when you're debugging,       */
331 /* especially on systems that don't handle running out of memory well.  */
332 /* n == 0 ==> unbounded.  This is the default.                          */
333 GC_API void GC_set_max_heap_size(GC_word n);
334
335 GC_API GC_word GC_get_max_heap_size(void);
336
337 /* Inform the collector that a certain section of statically allocated  */
338 /* memory contains no pointers to garbage collected memory.  Thus it    */
339 /* need not be scanned.  This is sometimes important if the application */
340 /* maps large read/write files into the address space, which could be   */
341 /* mistaken for dynamic library data segments on some systems.          */
342 GC_API void GC_exclude_static_roots(void * low_address,
343                                     void * high_address_plus_1);
344
345 /* Clear the set of root segments.  Wizards only. */
346 GC_API void GC_clear_roots(void);
347
348 /* Add a root segment.  Wizards only. */
349 GC_API void GC_add_roots(void * low_address, void * high_address_plus_1);
350
351 /* Remove a root segment.  Wizards only. */
352 GC_API void GC_remove_roots(void * low_address, void * high_address_plus_1);
353
354 /* Add a displacement to the set of those considered valid by the       */
355 /* collector.  GC_register_displacement(n) means that if p was returned */
356 /* by GC_malloc, then (char *)p + n will be considered to be a valid    */
357 /* pointer to p.  N must be small and less than the size of p.          */
358 /* (All pointers to the interior of objects from the stack are          */
359 /* considered valid in any case.  This applies to heap objects and      */
360 /* static data.)                                                        */
361 /* Preferably, this should be called before any other GC procedures.    */
362 /* Calling it later adds to the probability of excess memory            */
363 /* retention.                                                           */
364 /* This is a no-op if the collector has recognition of                  */
365 /* arbitrary interior pointers enabled, which is now the default.       */
366 GC_API void GC_register_displacement(size_t n);
367
368 /* The following version should be used if any debugging allocation is  */
369 /* being done.                                                          */
370 GC_API void GC_debug_register_displacement(size_t n);
371
372 /* Explicitly trigger a full, world-stop collection.    */
373 GC_API void GC_gcollect(void);
374
375 /* Trigger a full world-stopped collection.  Abort the collection if    */
376 /* and when stop_func returns a nonzero value.  Stop_func will be       */
377 /* called frequently, and should be reasonably fast.  This works even   */
378 /* if virtual dirty bits, and hence incremental collection is not       */
379 /* available for this architecture.  Collections can be aborted faster  */
380 /* than normal pause times for incremental collection.  However,        */
381 /* aborted collections do no useful work; the next collection needs     */
382 /* to start from the beginning.                                         */
383 /* Return 0 if the collection was aborted, 1 if it succeeded.           */
384 typedef int (* GC_stop_func)(void);
385 GC_API int GC_try_to_collect(GC_stop_func stop_func);
386
387 /* Return the number of bytes in the heap.  Excludes collector private  */
388 /* data structures.  Includes empty blocks and fragmentation loss.      */
389 /* Includes some pages that were allocated but never written.           */
390 GC_API size_t GC_get_heap_size(void);
391
392 /* Return a lower bound on the number of free bytes in the heap.        */
393 GC_API size_t GC_get_free_bytes(void);
394
395 /* Return the number of bytes allocated since the last collection.      */
396 GC_API size_t GC_get_bytes_since_gc(void);
397
398 /* Return the total number of bytes allocated in this process.          */
399 /* Never decreases, except due to wrapping.                             */
400 GC_API size_t GC_get_total_bytes(void);
401
402 /* Disable garbage collection.  Even GC_gcollect calls will be          */
403 /* ineffective.                                                         */
404 GC_API void GC_disable(void);
405
406 /* Reenable garbage collection.  GC_disable() and GC_enable() calls     */
407 /* nest.  Garbage collection is enabled if the number of calls to both  */
408 /* both functions is equal.                                             */
409 GC_API void GC_enable(void);
410
411 /* Enable incremental/generational collection.  */
412 /* Not advisable unless dirty bits are          */
413 /* available or most heap objects are           */
414 /* pointerfree(atomic) or immutable.            */
415 /* Don't use in leak finding mode.              */
416 /* Ignored if GC_dont_gc is true.               */
417 /* Only the generational piece of this is       */
418 /* functional if GC_parallel is TRUE            */
419 /* or if GC_time_limit is GC_TIME_UNLIMITED.    */
420 /* Causes GC_local_gcj_malloc() to revert to    */
421 /* locked allocation.  Must be called           */
422 /* before any GC_local_gcj_malloc() calls.      */
423 /* For best performance, should be called as early as possible. */
424 /* On some platforms, calling it later may have adverse effects.*/
425 /* Safe to call before GC_INIT().  Includes a GC_init() call.   */
426 GC_API void GC_enable_incremental(void);
427
428 /* Does incremental mode write-protect pages?  Returns zero or  */
429 /* more of the following, or'ed together:                       */
430 #define GC_PROTECTS_POINTER_HEAP  1 /* May protect non-atomic objs.     */
431 #define GC_PROTECTS_PTRFREE_HEAP  2
432 #define GC_PROTECTS_STATIC_DATA   4 /* Currently never.                 */
433 #define GC_PROTECTS_STACK         8 /* Probably impractical.            */
434
435 #define GC_PROTECTS_NONE 0
436 GC_API int GC_incremental_protection_needs(void);
437
438 /* Perform some garbage collection work, if appropriate.        */
439 /* Return 0 if there is no more work to be done.                */
440 /* Typically performs an amount of work corresponding roughly   */
441 /* to marking from one page.  May do more work if further       */
442 /* progress requires it, e.g. if incremental collection is      */
443 /* disabled.  It is reasonable to call this in a wait loop      */
444 /* until it returns 0.                                          */
445 GC_API int GC_collect_a_little(void);
446
447 /* Allocate an object of size lb bytes.  The client guarantees that     */
448 /* as long as the object is live, it will be referenced by a pointer    */
449 /* that points to somewhere within the first 256 bytes of the object.   */
450 /* (This should normally be declared volatile to prevent the compiler   */
451 /* from invalidating this assertion.)  This routine is only useful      */
452 /* if a large array is being allocated.  It reduces the chance of       */
453 /* accidentally retaining such an array as a result of scanning an      */
454 /* integer that happens to be an address inside the array.  (Actually,  */
455 /* it reduces the chance of the allocator not finding space for such    */
456 /* an array, since it will try hard to avoid introducing such a false   */
457 /* reference.)  On a SunOS 4.X or MS Windows system this is recommended */
458 /* for arrays likely to be larger than 100K or so.  For other systems,  */
459 /* or if the collector is not configured to recognize all interior      */
460 /* pointers, the threshold is normally much higher.                     */
461 GC_API void * GC_malloc_ignore_off_page(size_t lb);
462 GC_API void * GC_malloc_atomic_ignore_off_page(size_t lb);
463
464 #if defined(__sgi) && !defined(__GNUC__) && _COMPILER_VERSION >= 720
465 #   define GC_ADD_CALLER
466 #   define GC_RETURN_ADDR (GC_word)__return_address
467 #endif
468
469 #if defined(__linux__) || defined(__GLIBC__)
470 # include <features.h>
471 # if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1 || __GLIBC__ > 2) \
472      && !defined(__ia64__)
473 #   ifndef GC_HAVE_BUILTIN_BACKTRACE
474 /* #     define GC_HAVE_BUILTIN_BACKTRACE */
475 #   endif
476 # endif
477 # if defined(__i386__) || defined(__x86_64__)
478 #   define GC_CAN_SAVE_CALL_STACKS
479 # endif
480 #endif
481
482 #if defined(_MSC_VER) && _MSC_VER >= 1200 /* version 12.0+ (MSVC 6.0+)  */ \
483     && !defined(_AMD64_)
484 # ifndef GC_HAVE_NO_BUILTIN_BACKTRACE
485 #   define GC_HAVE_BUILTIN_BACKTRACE
486 # endif
487 #endif
488
489 #if defined(GC_HAVE_BUILTIN_BACKTRACE) && !defined(GC_CAN_SAVE_CALL_STACKS)
490 # define GC_CAN_SAVE_CALL_STACKS
491 #endif
492
493 #if defined(__sparc__)
494 #   define GC_CAN_SAVE_CALL_STACKS
495 #endif
496
497 /* If we're on an a platform on which we can't save call stacks, but    */
498 /* gcc is normally used, we go ahead and define GC_ADD_CALLER.          */
499 /* We make this decision independent of whether gcc is actually being   */
500 /* used, in order to keep the interface consistent, and allow mixing    */
501 /* of compilers.                                                        */
502 /* This may also be desirable if it is possible but expensive to        */
503 /* retrieve the call chain.                                             */
504 #if (defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) \
505      || defined(__FreeBSD__) || defined(__DragonFly__)) & !defined(GC_CAN_SAVE_CALL_STACKS)
506 # define GC_ADD_CALLER
507 # if __GNUC__ >= 3 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95) 
508     /* gcc knows how to retrieve return address, but we don't know */
509     /* how to generate call stacks.                                */
510 #   define GC_RETURN_ADDR (GC_word)__builtin_return_address(0)
511 # else
512     /* Just pass 0 for gcc compatibility. */
513 #   define GC_RETURN_ADDR 0
514 # endif
515 #endif
516
517 #ifdef GC_ADD_CALLER
518 #  define GC_EXTRAS GC_RETURN_ADDR, __FILE__, __LINE__
519 #  define GC_EXTRA_PARAMS GC_word ra, const char * s, int i
520 #else
521 #  define GC_EXTRAS __FILE__, __LINE__
522 #  define GC_EXTRA_PARAMS const char * s, int i
523 #endif
524
525 /* Debugging (annotated) allocation.  GC_gcollect will check            */
526 /* objects allocated in this way for overwrites, etc.                   */
527 GC_API void * GC_debug_malloc(size_t size_in_bytes, GC_EXTRA_PARAMS);
528 GC_API void * GC_debug_malloc_atomic(size_t size_in_bytes, GC_EXTRA_PARAMS);
529 GC_API char * GC_debug_strdup(const char *str, GC_EXTRA_PARAMS);
530 GC_API void * GC_debug_malloc_uncollectable
531         (size_t size_in_bytes, GC_EXTRA_PARAMS);
532 GC_API void * GC_debug_malloc_stubborn
533         (size_t size_in_bytes, GC_EXTRA_PARAMS);
534 GC_API void * GC_debug_malloc_ignore_off_page
535         (size_t size_in_bytes, GC_EXTRA_PARAMS);
536 GC_API void * GC_debug_malloc_atomic_ignore_off_page
537         (size_t size_in_bytes, GC_EXTRA_PARAMS);
538 GC_API void GC_debug_free (void * object_addr);
539 GC_API void * GC_debug_realloc
540         (void * old_object, size_t new_size_in_bytes, GC_EXTRA_PARAMS);
541 GC_API void GC_debug_change_stubborn(void *);
542 GC_API void GC_debug_end_stubborn_change(void *);
543
544 /* Routines that allocate objects with debug information (like the      */
545 /* above), but just fill in dummy file and line number information.     */
546 /* Thus they can serve as drop-in malloc/realloc replacements.  This    */
547 /* can be useful for two reasons:                                       */
548 /* 1) It allows the collector to be built with DBG_HDRS_ALL defined     */
549 /*    even if some allocation calls come from 3rd party libraries       */
550 /*    that can't be recompiled.                                         */
551 /* 2) On some platforms, the file and line information is redundant,    */
552 /*    since it can be reconstructed from a stack trace.  On such        */
553 /*    platforms it may be more convenient not to recompile, e.g. for    */
554 /*    leak detection.  This can be accomplished by instructing the      */
555 /*    linker to replace malloc/realloc with these.                      */
556 GC_API void * GC_debug_malloc_replacement (size_t size_in_bytes);
557 GC_API void * GC_debug_realloc_replacement
558               (void * object_addr, size_t size_in_bytes);
559                                  
560 # ifdef GC_DEBUG
561 #   define GC_MALLOC(sz) GC_debug_malloc(sz, GC_EXTRAS)
562 #   define GC_MALLOC_ATOMIC(sz) GC_debug_malloc_atomic(sz, GC_EXTRAS)
563 #   define GC_STRDUP(s) GC_debug_strdup((s), GC_EXTRAS)
564 #   define GC_MALLOC_UNCOLLECTABLE(sz) \
565                         GC_debug_malloc_uncollectable(sz, GC_EXTRAS)
566 #   define GC_MALLOC_IGNORE_OFF_PAGE(sz) \
567                         GC_debug_malloc_ignore_off_page(sz, GC_EXTRAS)
568 #   define GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE(sz) \
569                         GC_debug_malloc_atomic_ignore_off_page(sz, GC_EXTRAS)
570 #   define GC_REALLOC(old, sz) GC_debug_realloc(old, sz, GC_EXTRAS)
571 #   define GC_FREE(p) GC_debug_free(p)
572 #   define GC_REGISTER_FINALIZER(p, f, d, of, od) \
573         GC_debug_register_finalizer(p, f, d, of, od)
574 #   define GC_REGISTER_FINALIZER_IGNORE_SELF(p, f, d, of, od) \
575         GC_debug_register_finalizer_ignore_self(p, f, d, of, od)
576 #   define GC_REGISTER_FINALIZER_NO_ORDER(p, f, d, of, od) \
577         GC_debug_register_finalizer_no_order(p, f, d, of, od)
578 #   define GC_REGISTER_FINALIZER_UNREACHABLE(p, f, d, of, od) \
579         GC_debug_register_finalizer_unreachable(p, f, d, of, od)
580 #   define GC_MALLOC_STUBBORN(sz) GC_debug_malloc_stubborn(sz, GC_EXTRAS);
581 #   define GC_CHANGE_STUBBORN(p) GC_debug_change_stubborn(p)
582 #   define GC_END_STUBBORN_CHANGE(p) GC_debug_end_stubborn_change(p)
583 #   define GC_GENERAL_REGISTER_DISAPPEARING_LINK(link, obj) \
584         GC_general_register_disappearing_link(link, GC_base(obj))
585 #   define GC_REGISTER_DISPLACEMENT(n) GC_debug_register_displacement(n)
586 # else
587 #   define GC_MALLOC(sz) GC_malloc(sz)
588 #   define GC_MALLOC_ATOMIC(sz) GC_malloc_atomic(sz)
589 #   define GC_STRDUP(s) GC_strdup(s)
590 #   define GC_MALLOC_UNCOLLECTABLE(sz) GC_malloc_uncollectable(sz)
591 #   define GC_MALLOC_IGNORE_OFF_PAGE(sz) \
592                         GC_malloc_ignore_off_page(sz)
593 #   define GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE(sz) \
594                         GC_malloc_atomic_ignore_off_page(sz)
595 #   define GC_REALLOC(old, sz) GC_realloc(old, sz)
596 #   define GC_FREE(p) GC_free(p)
597 #   define GC_REGISTER_FINALIZER(p, f, d, of, od) \
598         GC_register_finalizer(p, f, d, of, od)
599 #   define GC_REGISTER_FINALIZER_IGNORE_SELF(p, f, d, of, od) \
600         GC_register_finalizer_ignore_self(p, f, d, of, od)
601 #   define GC_REGISTER_FINALIZER_NO_ORDER(p, f, d, of, od) \
602         GC_register_finalizer_no_order(p, f, d, of, od)
603 #   define GC_REGISTER_FINALIZER_UNREACHABLE(p, f, d, of, od) \
604         GC_register_finalizer_unreachable(p, f, d, of, od)
605 #   define GC_MALLOC_STUBBORN(sz) GC_malloc_stubborn(sz)
606 #   define GC_CHANGE_STUBBORN(p) GC_change_stubborn(p)
607 #   define GC_END_STUBBORN_CHANGE(p) GC_end_stubborn_change(p)
608 #   define GC_GENERAL_REGISTER_DISAPPEARING_LINK(link, obj) \
609         GC_general_register_disappearing_link(link, obj)
610 #   define GC_REGISTER_DISPLACEMENT(n) GC_register_displacement(n)
611 # endif
612 /* The following are included because they are often convenient, and    */
613 /* reduce the chance for a misspecifed size argument.  But calls may    */
614 /* expand to something syntactically incorrect if t is a complicated    */
615 /* type expression.                                                     */
616 # define GC_NEW(t) (t *)GC_MALLOC(sizeof (t))
617 # define GC_NEW_ATOMIC(t) (t *)GC_MALLOC_ATOMIC(sizeof (t))
618 # define GC_NEW_STUBBORN(t) (t *)GC_MALLOC_STUBBORN(sizeof (t))
619 # define GC_NEW_UNCOLLECTABLE(t) (t *)GC_MALLOC_UNCOLLECTABLE(sizeof (t))
620
621 /* Finalization.  Some of these primitives are grossly unsafe.          */
622 /* The idea is to make them both cheap, and sufficient to build         */
623 /* a safer layer, closer to Modula-3, Java, or PCedar finalization.     */
624 /* The interface represents my conclusions from a long discussion       */
625 /* with Alan Demers, Dan Greene, Carl Hauser, Barry Hayes,              */
626 /* Christian Jacobi, and Russ Atkinson.  It's not perfect, and          */
627 /* probably nobody else agrees with it.     Hans-J. Boehm  3/13/92      */
628 typedef void (*GC_finalization_proc) (void * obj, void * client_data);
629
630 GC_API void GC_register_finalizer(void * obj, GC_finalization_proc fn,
631                                   void * cd, GC_finalization_proc *ofn,
632                                   void * *ocd);
633 GC_API void GC_debug_register_finalizer
634                  (void * obj, GC_finalization_proc fn, void * cd,
635                   GC_finalization_proc *ofn, void * *ocd);
636         /* When obj is no longer accessible, invoke             */
637         /* (*fn)(obj, cd).  If a and b are inaccessible, and    */
638         /* a points to b (after disappearing links have been    */
639         /* made to disappear), then only a will be              */
640         /* finalized.  (If this does not create any new         */
641         /* pointers to b, then b will be finalized after the    */
642         /* next collection.)  Any finalizable object that       */
643         /* is reachable from itself by following one or more    */
644         /* pointers will not be finalized (or collected).       */
645         /* Thus cycles involving finalizable objects should     */
646         /* be avoided, or broken by disappearing links.         */
647         /* All but the last finalizer registered for an object  */
648         /* is ignored.                                          */
649         /* Finalization may be removed by passing 0 as fn.      */
650         /* Finalizers are implicitly unregistered just before   */
651         /* they are invoked.                                    */
652         /* The old finalizer and client data are stored in      */
653         /* *ofn and *ocd.                                       */ 
654         /* Fn is never invoked on an accessible object,         */
655         /* provided hidden pointers are converted to real       */
656         /* pointers only if the allocation lock is held, and    */
657         /* such conversions are not performed by finalization   */
658         /* routines.                                            */
659         /* If GC_register_finalizer is aborted as a result of   */
660         /* a signal, the object may be left with no             */
661         /* finalization, even if neither the old nor new        */
662         /* finalizer were NULL.                                 */
663         /* Obj should be the nonNULL starting address of an     */
664         /* object allocated by GC_malloc or friends.            */
665         /* Note that any garbage collectable object referenced  */
666         /* by cd will be considered accessible until the        */
667         /* finalizer is invoked.                                */
668
669 /* Another versions of the above follow.  It ignores            */
670 /* self-cycles, i.e. pointers from a finalizable object to      */
671 /* itself.  There is a stylistic argument that this is wrong,   */
672 /* but it's unavoidable for C++, since the compiler may         */
673 /* silently introduce these.  It's also benign in that specific */
674 /* case.  And it helps if finalizable objects are split to      */
675 /* avoid cycles.                                                */
676 /* Note that cd will still be viewed as accessible, even if it  */
677 /* refers to the object itself.                                 */
678 GC_API void GC_register_finalizer_ignore_self
679                 (void * obj, GC_finalization_proc fn, void * cd,
680                  GC_finalization_proc *ofn, void * *ocd);
681 GC_API void GC_debug_register_finalizer_ignore_self
682                 (void * obj, GC_finalization_proc fn, void * cd,
683                  GC_finalization_proc *ofn, void * *ocd);
684
685 /* Another version of the above.  It ignores all cycles.        */
686 /* It should probably only be used by Java implementations.     */
687 /* Note that cd will still be viewed as accessible, even if it  */
688 /* refers to the object itself.                                 */
689 GC_API void GC_register_finalizer_no_order
690                 (void * obj, GC_finalization_proc fn, void * cd,
691                  GC_finalization_proc *ofn, void * *ocd);
692 GC_API void GC_debug_register_finalizer_no_order
693                 (void * obj, GC_finalization_proc fn, void * cd,
694                  GC_finalization_proc *ofn, void * *ocd);
695
696 /* This is a special finalizer that is useful when an object's  */
697 /* finalizer must be run when the object is known to be no      */
698 /* longer reachable, not even from other finalizable objects.   */
699 /* It behaves like "normal" finalization, except that the       */
700 /* finalizer is not run while the object is reachable from      */
701 /* other objects specifying unordered finalization.             */
702 /* Effectively it allows an object referenced, possibly         */
703 /* indirectly, from an unordered finalizable object to override */
704 /* the unordered finalization request.                          */
705 /* This can be used in combination with finalizer_no_order so   */
706 /* as to release resources that must not be released while an   */
707 /* object can still be brought back to life by other            */
708 /* finalizers.                                                  */
709 /* Only works if GC_java_finalization is set.  Probably only    */
710 /* of interest when implementing a language that requires       */
711 /* unordered finalization (e.g. Java, C#).                      */
712 GC_API void GC_register_finalizer_unreachable
713                  (void * obj, GC_finalization_proc fn, void * cd,
714                   GC_finalization_proc *ofn, void * *ocd);
715 GC_API void GC_debug_register_finalizer_unreachable
716                  (void * obj, GC_finalization_proc fn, void * cd,
717                   GC_finalization_proc *ofn, void * *ocd);
718
719 /* The following routine may be used to break cycles between    */
720 /* finalizable objects, thus causing cyclic finalizable         */
721 /* objects to be finalized in the correct order.  Standard      */
722 /* use involves calling GC_register_disappearing_link(&p),      */
723 /* where p is a pointer that is not followed by finalization    */
724 /* code, and should not be considered in determining            */
725 /* finalization order.                                          */
726 GC_API int GC_register_disappearing_link(void * * link );
727         /* Link should point to a field of a heap allocated     */
728         /* object obj.  *link will be cleared when obj is       */
729         /* found to be inaccessible.  This happens BEFORE any   */
730         /* finalization code is invoked, and BEFORE any         */
731         /* decisions about finalization order are made.         */
732         /* This is useful in telling the finalizer that         */
733         /* some pointers are not essential for proper           */
734         /* finalization.  This may avoid finalization cycles.   */
735         /* Note that obj may be resurrected by another          */
736         /* finalizer, and thus the clearing of *link may        */
737         /* be visible to non-finalization code.                 */
738         /* There's an argument that an arbitrary action should  */
739         /* be allowed here, instead of just clearing a pointer. */
740         /* But this causes problems if that action alters, or   */
741         /* examines connectivity.                               */
742         /* Returns 1 if link was already registered, 0          */
743         /* otherwise.                                           */
744         /* Only exists for backward compatibility.  See below:  */
745         
746 GC_API int GC_general_register_disappearing_link (void * * link, void * obj);
747         /* A slight generalization of the above. *link is       */
748         /* cleared when obj first becomes inaccessible.  This   */
749         /* can be used to implement weak pointers easily and    */
750         /* safely. Typically link will point to a location      */
751         /* holding a disguised pointer to obj.  (A pointer      */
752         /* inside an "atomic" object is effectively             */
753         /* disguised.)   In this way soft                       */
754         /* pointers are broken before any object                */
755         /* reachable from them are finalized.  Each link        */
756         /* May be registered only once, i.e. with one obj       */
757         /* value.  This was added after a long email discussion */
758         /* with John Ellis.                                     */
759         /* Obj must be a pointer to the first word of an object */
760         /* we allocated.  It is unsafe to explicitly deallocate */
761         /* the object containing link.  Explicitly deallocating */
762         /* obj may or may not cause link to eventually be       */
763         /* cleared.                                             */
764         /* This can be used to implement certain types of       */
765         /* weak pointers.  Note however that this generally     */
766         /* requires that thje allocation lock is held (see      */
767         /* GC_call_with_allock_lock() below) when the disguised */
768         /* pointer is accessed.  Otherwise a strong pointer     */
769         /* could be recreated between the time the collector    */
770         /* decides to reclaim the object and the link is        */
771         /* cleared.                                             */
772
773 GC_API int GC_unregister_disappearing_link (void * * link);
774         /* Returns 0 if link was not actually registered.       */
775         /* Undoes a registration by either of the above two     */
776         /* routines.                                            */
777
778 GC_API void GC_finalize_all();
779
780 /* Returns !=0  if GC_invoke_finalizers has something to do.            */
781 GC_API int GC_should_invoke_finalizers(void);
782
783 GC_API int GC_invoke_finalizers(void);
784         /* Run finalizers for all objects that are ready to     */
785         /* be finalized.  Return the number of finalizers       */
786         /* that were run.  Normally this is also called         */
787         /* implicitly during some allocations.  If              */
788         /* GC-finalize_on_demand is nonzero, it must be called  */
789         /* explicitly.                                          */
790
791 /* Explicitly tell the collector that an object is reachable    */
792 /* at a particular program point.  This prevents the argument   */
793 /* pointer from being optimized away, even it is otherwise no   */
794 /* longer needed.  It should have no visible effect in the      */
795 /* absence of finalizers or disappearing links.  But it may be  */
796 /* needed to prevent finalizers from running while the          */
797 /* associated external resource is still in use.                */
798 /* The function is sometimes called keep_alive in other         */
799 /* settings.                                                    */
800 # if defined(__GNUC__) && !defined(__INTEL_COMPILER)
801 #   define GC_reachable_here(ptr) \
802     __asm__ volatile(" " : : "X"(ptr) : "memory");
803 # else
804     GC_API void GC_noop1(GC_word x);
805 #   define GC_reachable_here(ptr) GC_noop1((GC_word)(ptr));
806 #endif
807
808 /* GC_set_warn_proc can be used to redirect or filter warning messages. */
809 /* p may not be a NULL pointer.                                         */
810 typedef void (*GC_warn_proc) (char *msg, GC_word arg);
811 GC_API GC_warn_proc GC_set_warn_proc(GC_warn_proc p);
812     /* Returns old warning procedure.   */
813
814 GC_API GC_word GC_set_free_space_divisor(GC_word value);
815     /* Set free_space_divisor.  See above for definition.       */
816     /* Returns old value.                                       */
817         
818 /* The following is intended to be used by a higher level       */
819 /* (e.g. Java-like) finalization facility.  It is expected      */
820 /* that finalization code will arrange for hidden pointers to   */
821 /* disappear.  Otherwise objects can be accessed after they     */
822 /* have been collected.                                         */
823 /* Note that putting pointers in atomic objects or in           */
824 /* nonpointer slots of "typed" objects is equivalent to         */
825 /* disguising them in this way, and may have other advantages.  */
826 # if defined(I_HIDE_POINTERS) || defined(GC_I_HIDE_POINTERS)
827     typedef GC_word GC_hidden_pointer;
828 #   define HIDE_POINTER(p) (~(GC_hidden_pointer)(p))
829 #   define REVEAL_POINTER(p) ((void *)(HIDE_POINTER(p)))
830     /* Converting a hidden pointer to a real pointer requires verifying */
831     /* that the object still exists.  This involves acquiring the       */
832     /* allocator lock to avoid a race with the collector.               */
833 # endif /* I_HIDE_POINTERS */
834
835 typedef void * (*GC_fn_type) (void * client_data);
836 GC_API void * GC_call_with_alloc_lock (GC_fn_type fn, void * client_data);
837
838 /* These routines are intended to explicitly notify the collector       */
839 /* of new threads.  Often this is unnecessary because thread creation   */
840 /* is implicitly intercepted by the collector, using header-file        */
841 /* defines, or linker-based interception.  In the long run the intent   */
842 /* is to always make redundant registration safe.  In the short run,    */
843 /* this is being implemented a platform at a time.                      */
844 /* The interface is complicated by the fact that we probably will not   */
845 /* ever be able to automatically determine the stack base for thread    */
846 /* stacks on all platforms.                                             */
847
848 /* Structure representing the base of a thread stack.  On most          */
849 /* platforms this contains just a single address.                       */
850 struct GC_stack_base {
851         void * mem_base;        /* Base of memory stack.        */
852 #       if defined(__ia64) || defined(__ia64__)
853           void * reg_base;      /* Base of separate register stack.     */
854 #       endif
855 };
856
857 typedef void * (*GC_stack_base_func)(struct GC_stack_base *sb, void *arg);
858
859 /* Call a function with a stack base structure corresponding to         */
860 /* somewhere in the GC_call_with_stack_base frame.  This often can      */
861 /* be used to provide a sufficiently accurate stack base.  And we       */
862 /* implement it everywhere.                                             */
863 void * GC_call_with_stack_base(GC_stack_base_func fn, void *arg);
864
865 /* Register the current thread, with the indicated stack base, as       */
866 /* a new thread whose stack(s) should be traced by the GC.  If a        */
867 /* platform does not implicitly do so, this must be called before a     */
868 /* thread can allocate garbage collected memory, or assign pointers     */
869 /* to the garbage collected heap.  Once registered, a thread will be    */
870 /* stopped during garbage collections.                                  */
871 /* Return codes:        */
872 #define GC_SUCCESS 0
873 #define GC_DUPLICATE 1  /* Was already registered.      */
874 #define GC_NO_THREADS 2 /* No thread support in GC.     */
875 #define GC_UNIMPLEMENTED 3      /* Not yet implemented on this platform. */
876 int GC_register_my_thread(struct GC_stack_base *);
877
878 /* Unregister the current thread.  The thread may no longer allocate    */
879 /* garbage collected memory or manipulate pointers to the               */
880 /* garbage collected heap after making this call.                       */
881 /* Specifically, if it wants to return or otherwise communicate a       */
882 /* pointer to the garbage-collected heap to another thread, it must     */
883 /* do this before calling GC_unregister_my_thread, most probably        */
884 /* by saving it in a global data structure.                             */
885 int GC_unregister_my_thread(void);
886
887 /* Attempt to fill in the GC_stack_base structure with the stack base   */
888 /* for this thread.  This appears to be required to implement anything  */
889 /* like the JNI AttachCurrentThread in an environment in which new      */
890 /* threads are not automatically registered with the collector.         */
891 /* It is also unfortunately hard to implement well on many platforms.   */
892 /* Returns GC_SUCCESS or GC_UNIMPLEMENTED.                              */
893 int GC_get_stack_base(struct GC_stack_base *);
894
895 /* The following routines are primarily intended for use with a         */
896 /* preprocessor which inserts calls to check C pointer arithmetic.      */
897 /* They indicate failure by invoking the corresponding _print_proc.     */
898
899 /* Check that p and q point to the same object.                 */
900 /* Fail conspicuously if they don't.                            */
901 /* Returns the first argument.                                  */
902 /* Succeeds if neither p nor q points to the heap.              */
903 /* May succeed if both p and q point to between heap objects.   */
904 GC_API void * GC_same_obj (void * p, void * q);
905
906 /* Checked pointer pre- and post- increment operations.  Note that      */
907 /* the second argument is in units of bytes, not multiples of the       */
908 /* object size.  This should either be invoked from a macro, or the     */
909 /* call should be automatically generated.                              */
910 GC_API void * GC_pre_incr (void * *p, size_t how_much);
911 GC_API void * GC_post_incr (void * *p, size_t how_much);
912
913 /* Check that p is visible                                              */
914 /* to the collector as a possibly pointer containing location.          */
915 /* If it isn't fail conspicuously.                                      */
916 /* Returns the argument in all cases.  May erroneously succeed          */
917 /* in hard cases.  (This is intended for debugging use with             */
918 /* untyped allocations.  The idea is that it should be possible, though */
919 /* slow, to add such a call to all indirect pointer stores.)            */
920 /* Currently useless for multithreaded worlds.                          */
921 GC_API void * GC_is_visible (void * p);
922
923 /* Check that if p is a pointer to a heap page, then it points to       */
924 /* a valid displacement within a heap object.                           */
925 /* Fail conspicuously if this property does not hold.                   */
926 /* Uninteresting with GC_all_interior_pointers.                         */
927 /* Always returns its argument.                                         */
928 GC_API void * GC_is_valid_displacement (void *  p);
929
930 /* Explicitly dump the GC state.  This is most often called from the    */
931 /* debugger, or by setting the GC_DUMP_REGULARLY environment variable,  */
932 /* but it may be useful to call it from client code during debugging.   */
933 void GC_dump(void);
934
935 /* Safer, but slow, pointer addition.  Probably useful mainly with      */
936 /* a preprocessor.  Useful only for heap pointers.                      */
937 #ifdef GC_DEBUG
938 #   define GC_PTR_ADD3(x, n, type_of_result) \
939         ((type_of_result)GC_same_obj((x)+(n), (x)))
940 #   define GC_PRE_INCR3(x, n, type_of_result) \
941         ((type_of_result)GC_pre_incr(&(x), (n)*sizeof(*x))
942 #   define GC_POST_INCR2(x, type_of_result) \
943         ((type_of_result)GC_post_incr(&(x), sizeof(*x))
944 #   ifdef __GNUC__
945 #       define GC_PTR_ADD(x, n) \
946             GC_PTR_ADD3(x, n, typeof(x))
947 #       define GC_PRE_INCR(x, n) \
948             GC_PRE_INCR3(x, n, typeof(x))
949 #       define GC_POST_INCR(x, n) \
950             GC_POST_INCR3(x, typeof(x))
951 #   else
952         /* We can't do this right without typeof, which ANSI    */
953         /* decided was not sufficiently useful.  Repeatedly     */
954         /* mentioning the arguments seems too dangerous to be   */
955         /* useful.  So does not casting the result.             */
956 #       define GC_PTR_ADD(x, n) ((x)+(n))
957 #   endif
958 #else   /* !GC_DEBUG */
959 #   define GC_PTR_ADD3(x, n, type_of_result) ((x)+(n))
960 #   define GC_PTR_ADD(x, n) ((x)+(n))
961 #   define GC_PRE_INCR3(x, n, type_of_result) ((x) += (n))
962 #   define GC_PRE_INCR(x, n) ((x) += (n))
963 #   define GC_POST_INCR2(x, n, type_of_result) ((x)++)
964 #   define GC_POST_INCR(x, n) ((x)++)
965 #endif
966
967 /* Safer assignment of a pointer to a nonstack location.        */
968 #ifdef GC_DEBUG
969 #   define GC_PTR_STORE(p, q) \
970         (*(void **)GC_is_visible(p) = GC_is_valid_displacement(q))
971 #else /* !GC_DEBUG */
972 #   define GC_PTR_STORE(p, q) *((p) = (q))
973 #endif
974
975 /* Functions called to report pointer checking errors */
976 GC_API void (*GC_same_obj_print_proc) (void * p, void * q);
977
978 GC_API void (*GC_is_valid_displacement_print_proc) (void * p);
979
980 GC_API void (*GC_is_visible_print_proc) (void * p);
981
982
983 /* For pthread support, we generally need to intercept a number of      */
984 /* thread library calls.  We do that here by macro defining them.       */
985
986 #if !defined(GC_USE_LD_WRAP) && \
987     (defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS))
988 # include "gc_pthread_redirects.h"
989 #endif
990
991 # if defined(PCR) || defined(GC_SOLARIS_THREADS) || \
992      defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
993         /* Any flavor of threads.       */
994 /* This returns a list of objects, linked through their first           */
995 /* word.  Its use can greatly reduce lock contention problems, since    */
996 /* the allocation lock can be acquired and released many fewer times.   */
997 /* It is used internally by gc_local_alloc.h, which provides a simpler  */
998 /* programming interface on Linux.                                      */
999 void * GC_malloc_many(size_t lb);
1000 #define GC_NEXT(p) (*(void * *)(p))     /* Retrieve the next element    */
1001                                         /* in returned list.            */
1002 extern void GC_thr_init(void);  /* Needed for Solaris/X86 ??    */
1003
1004 #endif /* THREADS */
1005
1006 /* Register a callback to control the scanning of dynamic libraries.
1007    When the GC scans the static data of a dynamic library, it will
1008    first call a user-supplied routine with filename of the library and
1009    the address and length of the memory region.  This routine should
1010    return nonzero if that region should be scanned.  */
1011 GC_API void 
1012 GC_register_has_static_roots_callback
1013   (int (*callback)(const char *, void *, size_t));
1014
1015
1016 #if defined(GC_WIN32_THREADS) && !defined(__CYGWIN32__) \
1017         && !defined(__CYGWIN__) \
1018         && !defined(GC_PTHREADS)
1019
1020 #ifdef __cplusplus
1021     }  /* Including windows.h in an extern "C" context no longer works. */
1022 #endif
1023
1024 # include <windows.h>
1025
1026 #ifdef __cplusplus
1027     extern "C" {
1028 #endif
1029   /*
1030    * All threads must be created using GC_CreateThread or GC_beginthreadex,
1031    * or must explicitly call GC_register_my_thread,
1032    * so that they will be recorded in the thread table.
1033    * For backwards compatibility, it is possible to build the GC
1034    * with GC_DLL defined, and to call GC_use_DllMain().
1035    * This implicitly registers all created threads, but appears to be
1036    * less robust.
1037    *
1038    * Currently the collector expects all threads to fall through and
1039    * terminate normally, or call GC_endthreadex() or GC_ExitThread,
1040    * so that the thread is properly unregistered.  (An explicit call
1041    * to GC_unregister_my_thread() should also work, but risks unregistering
1042    * the thread twice.)
1043    */
1044    GC_API HANDLE WINAPI GC_CreateThread(
1045       LPSECURITY_ATTRIBUTES lpThreadAttributes,
1046       DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress,
1047       LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId );
1048
1049
1050    GC_API uintptr_t GC_beginthreadex(
1051      void *security, unsigned stack_size,
1052      unsigned ( __stdcall *start_address )( void * ),
1053      void *arglist, unsigned initflag, unsigned *thrdaddr);
1054
1055    GC_API void GC_endthreadex(unsigned retval);
1056
1057    GC_API void WINAPI GC_ExitThread(DWORD dwExitCode);
1058
1059 # if defined(_WIN32_WCE)
1060   /*
1061    * win32_threads.c implements the real WinMain, which will start a new thread
1062    * to call GC_WinMain after initializing the garbage collector.
1063    */
1064   GC_API int WINAPI GC_WinMain(
1065       HINSTANCE hInstance,
1066       HINSTANCE hPrevInstance,
1067       LPWSTR lpCmdLine,
1068       int nCmdShow );
1069 #  ifndef GC_BUILD
1070 #    define WinMain GC_WinMain
1071 #  endif
1072 # endif /* defined(_WIN32_WCE) */
1073
1074   /*
1075    * Use implicit thread registration via DllMain.
1076    */
1077 GC_API void GC_use_DllMain(void);
1078
1079 # define CreateThread GC_CreateThread
1080 # define ExitThread GC_ExitThread
1081 # define _beginthreadex GC_beginthreadex
1082 # define _endthreadex GC_endthreadex
1083 # define _beginthread { > "Please use _beginthreadex instead of _beginthread" < }
1084
1085 #endif /* defined(GC_WIN32_THREADS)  && !cygwin */
1086
1087  /*
1088   * Fully portable code should call GC_INIT() from the main program
1089   * before making any other GC_ calls.  On most platforms this is a
1090   * no-op and the collector self-initializes.  But a number of platforms
1091   * make that too hard.
1092   * A GC_INIT call is required if the collector is built with THREAD_LOCAL_ALLOC
1093   * defined and the initial allocation call is not to GC_malloc().
1094   */
1095 #if defined(__CYGWIN32__) || defined (_AIX)
1096     /*
1097      * Similarly gnu-win32 DLLs need explicit initialization from
1098      * the main program, as does AIX.
1099      */
1100 #   ifdef __CYGWIN32__
1101       extern int _data_start__[];
1102       extern int _data_end__[];
1103       extern int _bss_start__[];
1104       extern int _bss_end__[];
1105 #     define GC_MAX(x,y) ((x) > (y) ? (x) : (y))
1106 #     define GC_MIN(x,y) ((x) < (y) ? (x) : (y))
1107 #     define GC_DATASTART ((void *) GC_MIN(_data_start__, _bss_start__))
1108 #     define GC_DATAEND  ((void *) GC_MAX(_data_end__, _bss_end__))
1109 #     if defined(GC_DLL)
1110 #       define GC_INIT() { GC_add_roots(GC_DATASTART, GC_DATAEND); \
1111                            GC_gcollect(); /* For blacklisting. */}
1112 #     else
1113         /* Main program init not required  */
1114 #       define GC_INIT() { GC_init(); }
1115 #     endif
1116 #   endif
1117 #   if defined(_AIX)
1118       extern int _data[], _end[];
1119 #     define GC_DATASTART ((void *)((ulong)_data))
1120 #     define GC_DATAEND ((void *)((ulong)_end))
1121 #     define GC_INIT() { GC_add_roots(GC_DATASTART, GC_DATAEND); }
1122 #   endif
1123 #else
1124 #   define GC_INIT() { GC_init(); }
1125 #endif
1126
1127 #if !defined(_WIN32_WCE) \
1128     && ((defined(_MSDOS) || defined(_MSC_VER)) && (_M_IX86 >= 300) \
1129         || defined(_WIN32) && !defined(__CYGWIN32__) && !defined(__CYGWIN__))
1130   /* win32S may not free all resources on process exit.  */
1131   /* This explicitly deallocates the heap.               */
1132     GC_API void GC_win32_free_heap ();
1133 #endif
1134
1135 #if ( defined(_AMIGA) && !defined(GC_AMIGA_MAKINGLIB) )
1136   /* Allocation really goes through GC_amiga_allocwrapper_do */
1137 # include "gc_amiga_redirects.h"
1138 #endif
1139
1140 #if defined(GC_REDIRECT_TO_LOCAL) && !defined(GC_LOCAL_ALLOC_H)
1141 #  include  "gc_local_alloc.h"
1142 #endif
1143
1144 #ifdef __cplusplus
1145     }  /* end of extern "C" */
1146 #endif
1147
1148 #endif /* _GC_H */