2007-02-01 Geoff Norton <gnorton@customerdna.com>
[mono.git] / libgc / include / private / gc_priv.h
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) 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
6  *
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 # ifndef GC_PRIVATE_H
20 # define GC_PRIVATE_H
21
22 #if defined(mips) && defined(SYSTYPE_BSD) && defined(sony_news)
23     /* sony RISC NEWS, NEWSOS 4 */
24 #   define BSD_TIME
25 /*    typedef long ptrdiff_t;   -- necessary on some really old systems */
26 #endif
27
28 #if defined(mips) && defined(SYSTYPE_BSD43)
29     /* MIPS RISCOS 4 */
30 #   define BSD_TIME
31 #endif
32
33 #ifdef DGUX
34 #   include <sys/types.h>
35 #   include <sys/time.h>
36 #   include <sys/resource.h>
37 #endif /* DGUX */
38
39 #ifdef BSD_TIME
40 #   include <sys/types.h>
41 #   include <sys/time.h>
42 #   include <sys/resource.h>
43 #endif /* BSD_TIME */
44
45 # ifndef _GC_H
46 #   include "../gc.h"
47 # endif
48
49 # ifndef GC_MARK_H
50 #   include "../gc_mark.h"
51 # endif
52
53 typedef GC_word word;
54 typedef GC_signed_word signed_word;
55
56 typedef int GC_bool;
57 # define TRUE 1
58 # define FALSE 0
59
60 typedef char * ptr_t;   /* A generic pointer to which we can add        */
61                         /* byte displacements.                          */
62                         /* Preferably identical to caddr_t, if it       */
63                         /* exists.                                      */
64                         
65 # ifndef GCCONFIG_H
66 #   include "gcconfig.h"
67 # endif
68
69 # ifndef HEADERS_H
70 #   include "gc_hdrs.h"
71 # endif
72
73 #if defined(__STDC__)
74 #   include <stdlib.h>
75 #   if !(defined( sony_news ) )
76 #       include <stddef.h>
77 #   endif
78 #   define VOLATILE volatile
79 #else
80 #   ifdef MSWIN32
81 #       include <stdlib.h>
82 #   endif
83 #   define VOLATILE
84 #endif
85
86 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
87 /* This doesn't work in some earlier gcc versions */
88 # define EXPECT(expr, outcome) __builtin_expect(expr,outcome)
89   /* Equivalent to (expr), but predict that usually (expr)==outcome. */
90 #else
91 # define EXPECT(expr, outcome) (expr)
92 #endif
93
94 # ifndef GC_LOCKS_H
95 #   include "gc_locks.h"
96 # endif
97
98 # ifdef STACK_GROWS_DOWN
99 #   define COOLER_THAN >
100 #   define HOTTER_THAN <
101 #   define MAKE_COOLER(x,y) if ((word)(x)+(y) > (word)(x)) {(x) += (y);} \
102                             else {(x) = (word)ONES;}
103 #   define MAKE_HOTTER(x,y) (x) -= (y)
104 # else
105 #   define COOLER_THAN <
106 #   define HOTTER_THAN >
107 #   define MAKE_COOLER(x,y) if ((word)(x)-(y) < (word)(x)) {(x) -= (y);} else {(x) = 0;}
108 #   define MAKE_HOTTER(x,y) (x) += (y)
109 # endif
110
111 #if defined(AMIGA) && defined(__SASC)
112 #   define GC_FAR __far
113 #else
114 #   define GC_FAR
115 #endif
116
117
118 /*********************************/
119 /*                               */
120 /* Definitions for conservative  */
121 /* collector                     */
122 /*                               */
123 /*********************************/
124
125 /*********************************/
126 /*                               */
127 /* Easily changeable parameters  */
128 /*                               */
129 /*********************************/
130
131 /* #define STUBBORN_ALLOC */
132                     /* Enable stubborm allocation, and thus a limited   */
133                     /* form of incremental collection w/o dirty bits.   */
134
135 /* #define ALL_INTERIOR_POINTERS */
136                     /* Forces all pointers into the interior of an      */
137                     /* object to be considered valid.  Also causes the  */
138                     /* sizes of all objects to be inflated by at least  */
139                     /* one byte.  This should suffice to guarantee      */
140                     /* that in the presence of a compiler that does     */
141                     /* not perform garbage-collector-unsafe             */
142                     /* optimizations, all portable, strictly ANSI       */
143                     /* conforming C programs should be safely usable    */
144                     /* with malloc replaced by GC_malloc and free       */
145                     /* calls removed.  There are several disadvantages: */
146                     /* 1. There are probably no interesting, portable,  */
147                     /*    strictly ANSI conforming C programs.          */
148                     /* 2. This option makes it hard for the collector   */
149                     /*    to allocate space that is not ``pointed to''  */
150                     /*    by integers, etc.  Under SunOS 4.X with a     */
151                     /*    statically linked libc, we empiricaly         */
152                     /*    observed that it would be difficult to        */
153                     /*    allocate individual objects larger than 100K. */
154                     /*    Even if only smaller objects are allocated,   */
155                     /*    more swap space is likely to be needed.       */
156                     /*    Fortunately, much of this will never be       */
157                     /*    touched.                                      */
158                     /* If you can easily avoid using this option, do.   */
159                     /* If not, try to keep individual objects small.    */
160                     /* This is now really controlled at startup,        */
161                     /* through GC_all_interior_pointers.                */
162                     
163 #define PRINTSTATS  /* Print garbage collection statistics              */
164                     /* For less verbose output, undefine in reclaim.c   */
165
166 #define PRINTTIMES  /* Print the amount of time consumed by each garbage   */
167                     /* collection.                                         */
168
169 #define PRINTBLOCKS /* Print object sizes associated with heap blocks,     */
170                     /* whether the objects are atomic or composite, and    */
171                     /* whether or not the block was found to be empty      */
172                     /* during the reclaim phase.  Typically generates       */
173                     /* about one screenful per garbage collection.         */
174 #undef PRINTBLOCKS
175
176 #ifdef SILENT
177 #  ifdef PRINTSTATS
178 #    undef PRINTSTATS
179 #  endif
180 #  ifdef PRINTTIMES
181 #    undef PRINTTIMES
182 #  endif
183 #  ifdef PRINTNBLOCKS
184 #    undef PRINTNBLOCKS
185 #  endif
186 #endif
187
188 #if defined(PRINTSTATS) && !defined(GATHERSTATS)
189 #   define GATHERSTATS
190 #endif
191
192 #if defined(PRINTSTATS) || !defined(SMALL_CONFIG)
193 #   define CONDPRINT  /* Print some things if GC_print_stats is set */
194 #endif
195
196 #define GC_INVOKE_FINALIZERS() GC_notify_or_invoke_finalizers()
197
198 #define MERGE_SIZES /* Round up some object sizes, so that fewer distinct */
199                     /* free lists are actually maintained.  This applies  */
200                     /* only to the top level routines in misc.c, not to   */
201                     /* user generated code that calls GC_allocobj and     */
202                     /* GC_allocaobj directly.                             */
203                     /* Slows down average programs slightly.  May however */
204                     /* substantially reduce fragmentation if allocation   */
205                     /* request sizes are widely scattered.                */
206                     /* May save significant amounts of space for obj_map  */
207                     /* entries.                                           */
208
209 #if defined(USE_MARK_BYTES) && !defined(ALIGN_DOUBLE)
210 #  define ALIGN_DOUBLE
211    /* We use one byte for every 2 words, which doesn't allow for        */
212    /* odd numbered words to have mark bits.                             */
213 #endif
214
215 #if defined(GC_GCJ_SUPPORT) && ALIGNMENT < 8 && !defined(ALIGN_DOUBLE)
216    /* GCJ's Hashtable synchronization code requires 64-bit alignment.  */
217 #  define ALIGN_DOUBLE
218 #endif
219
220 /* ALIGN_DOUBLE requires MERGE_SIZES at present. */
221 # if defined(ALIGN_DOUBLE) && !defined(MERGE_SIZES)
222 #   define MERGE_SIZES
223 # endif
224
225 #if !defined(DONT_ADD_BYTE_AT_END)
226 # define EXTRA_BYTES GC_all_interior_pointers
227 #else
228 # define EXTRA_BYTES 0
229 #endif
230
231
232 # ifndef LARGE_CONFIG
233 #   define MINHINCR 16   /* Minimum heap increment, in blocks of HBLKSIZE  */
234                          /* Must be multiple of largest page size.         */
235 #   define MAXHINCR 2048 /* Maximum heap increment, in blocks              */
236 # else
237 #   define MINHINCR 64
238 #   define MAXHINCR 4096
239 # endif
240
241 # define TIME_LIMIT 50     /* We try to keep pause times from exceeding  */
242                            /* this by much. In milliseconds.             */
243
244 # define BL_LIMIT GC_black_list_spacing
245                            /* If we need a block of N bytes, and we have */
246                            /* a block of N + BL_LIMIT bytes available,   */
247                            /* and N > BL_LIMIT,                          */
248                            /* but all possible positions in it are       */
249                            /* blacklisted, we just use it anyway (and    */
250                            /* print a warning, if warnings are enabled). */
251                            /* This risks subsequently leaking the block  */
252                            /* due to a false reference.  But not using   */
253                            /* the block risks unreasonable immediate     */
254                            /* heap growth.                               */
255
256 /*********************************/
257 /*                               */
258 /* Stack saving for debugging    */
259 /*                               */
260 /*********************************/
261
262 #ifdef NEED_CALLINFO
263     struct callinfo {
264         word ci_pc;     /* Caller, not callee, pc       */
265 #       if NARGS > 0
266             word ci_arg[NARGS]; /* bit-wise complement to avoid retention */
267 #       endif
268 #       if defined(ALIGN_DOUBLE) && (NFRAMES * (NARGS + 1)) % 2 == 1
269             /* Likely alignment problem. */
270             word ci_dummy;
271 #       endif
272     };
273 #endif
274
275 #ifdef SAVE_CALL_CHAIN
276
277 /* Fill in the pc and argument information for up to NFRAMES of my      */
278 /* callers.  Ignore my frame and my callers frame.                      */
279 void GC_save_callers GC_PROTO((struct callinfo info[NFRAMES]));
280   
281 void GC_print_callers GC_PROTO((struct callinfo info[NFRAMES]));
282
283 #endif
284
285
286 /*********************************/
287 /*                               */
288 /* OS interface routines         */
289 /*                               */
290 /*********************************/
291
292 #ifdef BSD_TIME
293 #   undef CLOCK_TYPE
294 #   undef GET_TIME
295 #   undef MS_TIME_DIFF
296 #   define CLOCK_TYPE struct timeval
297 #   define GET_TIME(x) { struct rusage rusage; \
298                          getrusage (RUSAGE_SELF,  &rusage); \
299                          x = rusage.ru_utime; }
300 #   define MS_TIME_DIFF(a,b) ((double) (a.tv_sec - b.tv_sec) * 1000.0 \
301                                + (double) (a.tv_usec - b.tv_usec) / 1000.0)
302 #else /* !BSD_TIME */
303 # if defined(MSWIN32) || defined(MSWINCE)
304 #   include <windows.h>
305 #   include <winbase.h>
306 #   define CLOCK_TYPE DWORD
307 #   define GET_TIME(x) x = GetTickCount()
308 #   define MS_TIME_DIFF(a,b) ((long)((a)-(b)))
309 # else /* !MSWIN32, !MSWINCE, !BSD_TIME */
310 #   include <time.h>
311 #   if !defined(__STDC__) && defined(SPARC) && defined(SUNOS4)
312       clock_t clock();  /* Not in time.h, where it belongs      */
313 #   endif
314 #   if defined(FREEBSD) && !defined(CLOCKS_PER_SEC)
315 #     include <machine/limits.h>
316 #     define CLOCKS_PER_SEC CLK_TCK
317 #   endif
318 #   if !defined(CLOCKS_PER_SEC)
319 #     define CLOCKS_PER_SEC 1000000
320 /*
321  * This is technically a bug in the implementation.  ANSI requires that
322  * CLOCKS_PER_SEC be defined.  But at least under SunOS4.1.1, it isn't.
323  * Also note that the combination of ANSI C and POSIX is incredibly gross
324  * here. The type clock_t is used by both clock() and times().  But on
325  * some machines these use different notions of a clock tick,  CLOCKS_PER_SEC
326  * seems to apply only to clock.  Hence we use it here.  On many machines,
327  * including SunOS, clock actually uses units of microseconds (which are
328  * not really clock ticks).
329  */
330 #   endif
331 #   define CLOCK_TYPE clock_t
332 #   define GET_TIME(x) x = clock()
333 #   define MS_TIME_DIFF(a,b) ((unsigned long) \
334                 (1000.0*(double)((a)-(b))/(double)CLOCKS_PER_SEC))
335 # endif /* !MSWIN32 */
336 #endif /* !BSD_TIME */
337
338 /* We use bzero and bcopy internally.  They may not be available.       */
339 # if defined(SPARC) && defined(SUNOS4)
340 #   define BCOPY_EXISTS
341 # endif
342 # if defined(M68K) && defined(AMIGA)
343 #   define BCOPY_EXISTS
344 # endif
345 # if defined(M68K) && defined(NEXT)
346 #   define BCOPY_EXISTS
347 # endif
348 # if defined(VAX)
349 #   define BCOPY_EXISTS
350 # endif
351 # if defined(AMIGA)
352 #   include <string.h>
353 #   define BCOPY_EXISTS
354 # endif
355 # if defined(DARWIN)
356 #   include <string.h>
357 #   define BCOPY_EXISTS
358 # endif
359
360 # ifndef BCOPY_EXISTS
361 #   include <string.h>
362 #   define BCOPY(x,y,n) memcpy(y, x, (size_t)(n))
363 #   define BZERO(x,n)  memset(x, 0, (size_t)(n))
364 # else
365 #   define BCOPY(x,y,n) bcopy((char *)(x),(char *)(y),(int)(n))
366 #   define BZERO(x,n) bzero((char *)(x),(int)(n))
367 # endif
368
369 #if defined(DARWIN)
370 #       if defined(POWERPC)
371 #               define GC_MACH_THREAD_STATE_FLAVOR PPC_THREAD_STATE
372 #       elif defined(I386)
373 #               define GC_MACH_THREAD_STATE_FLAVOR i386_THREAD_STATE
374 #       else
375 #               define GC_MACH_THREAD_STATE_FLAVOR MACHINE_THREAD_STATE
376 #       endif
377 #endif
378
379 /* Delay any interrupts or signals that may abort this thread.  Data    */
380 /* structures are in a consistent state outside this pair of calls.     */
381 /* ANSI C allows both to be empty (though the standard isn't very       */
382 /* clear on that point).  Standard malloc implementations are usually   */
383 /* neither interruptable nor thread-safe, and thus correspond to        */
384 /* empty definitions.                                                   */
385 /* It probably doesn't make any sense to declare these to be nonempty   */
386 /* if the code is being optimized, since signal safety relies on some   */
387 /* ordering constraints that are typically not obeyed by optimizing     */
388 /* compilers.                                                           */
389 # ifdef PCR
390 #   define DISABLE_SIGNALS() \
391                  PCR_Th_SetSigMask(PCR_allSigsBlocked,&GC_old_sig_mask)
392 #   define ENABLE_SIGNALS() \
393                 PCR_Th_SetSigMask(&GC_old_sig_mask, NIL)
394 # else
395 #   if defined(THREADS) || defined(AMIGA)  \
396         || defined(MSWIN32) || defined(MSWINCE) || defined(MACOS) \
397         || defined(DJGPP) || defined(NO_SIGNALS) 
398                         /* Also useful for debugging.           */
399         /* Should probably use thr_sigsetmask for GC_SOLARIS_THREADS. */
400 #     define DISABLE_SIGNALS()
401 #     define ENABLE_SIGNALS()
402 #   else
403 #     define DISABLE_SIGNALS() GC_disable_signals()
404         void GC_disable_signals();
405 #     define ENABLE_SIGNALS() GC_enable_signals()
406         void GC_enable_signals();
407 #   endif
408 # endif
409
410 /*
411  * Stop and restart mutator threads.
412  */
413 # ifdef PCR
414 #     include "th/PCR_ThCtl.h"
415 #     define STOP_WORLD() \
416         PCR_ThCtl_SetExclusiveMode(PCR_ThCtl_ExclusiveMode_stopNormal, \
417                                    PCR_allSigsBlocked, \
418                                    PCR_waitForever)
419 #     define START_WORLD() \
420         PCR_ThCtl_SetExclusiveMode(PCR_ThCtl_ExclusiveMode_null, \
421                                    PCR_allSigsBlocked, \
422                                    PCR_waitForever);
423 # else
424 #   if defined(GC_SOLARIS_THREADS) || defined(GC_WIN32_THREADS) \
425         || defined(GC_PTHREADS)
426       void GC_stop_world();
427       void GC_start_world();
428 #     define STOP_WORLD() GC_stop_world()
429 #     define START_WORLD() GC_start_world()
430 #   else
431 #     define STOP_WORLD()
432 #     define START_WORLD()
433 #   endif
434 # endif
435
436 /* Abandon ship */
437 # ifdef PCR
438 #   define ABORT(s) PCR_Base_Panic(s)
439 # else
440 #   ifdef SMALL_CONFIG
441 #       define ABORT(msg) abort();
442 #   else
443         GC_API void GC_abort GC_PROTO((GC_CONST char * msg));
444 #       define ABORT(msg) GC_abort(msg);
445 #   endif
446 # endif
447
448 /* Exit abnormally, but without making a mess (e.g. out of memory) */
449 # ifdef PCR
450 #   define EXIT() PCR_Base_Exit(1,PCR_waitForever)
451 # else
452 #   define EXIT() (void)exit(1)
453 # endif
454
455 /* Print warning message, e.g. almost out of memory.    */
456 # define WARN(msg,arg) (*GC_current_warn_proc)("GC Warning: " msg, (GC_word)(arg))
457 extern GC_warn_proc GC_current_warn_proc;
458
459 /* Get environment entry */
460 #if !defined(NO_GETENV)
461 #   if defined(EMPTY_GETENV_RESULTS)
462         /* Workaround for a reputed Wine bug.   */
463         static inline char * fixed_getenv(const char *name)
464         {
465           char * tmp = getenv(name);
466           if (tmp == 0 || strlen(tmp) == 0)
467             return 0;
468           return tmp;
469         }
470 #       define GETENV(name) fixed_getenv(name)
471 #   else
472 #       define GETENV(name) getenv(name)
473 #   endif
474 #else
475 #   define GETENV(name) 0
476 #endif
477
478 /*********************************/
479 /*                               */
480 /* Word-size-dependent defines   */
481 /*                               */
482 /*********************************/
483
484 #if CPP_WORDSZ == 32
485 #  define WORDS_TO_BYTES(x)   ((x)<<2)
486 #  define BYTES_TO_WORDS(x)   ((x)>>2)
487 #  define LOGWL               ((word)5)    /* log[2] of CPP_WORDSZ */
488 #  define modWORDSZ(n) ((n) & 0x1f)        /* n mod size of word            */
489 #  if ALIGNMENT != 4
490 #       define UNALIGNED
491 #  endif
492 #endif
493
494 #if CPP_WORDSZ == 64
495 #  define WORDS_TO_BYTES(x)   ((x)<<3)
496 #  define BYTES_TO_WORDS(x)   ((x)>>3)
497 #  define LOGWL               ((word)6)    /* log[2] of CPP_WORDSZ */
498 #  define modWORDSZ(n) ((n) & 0x3f)        /* n mod size of word            */
499 #  if ALIGNMENT != 8
500 #       define UNALIGNED
501 #  endif
502 #endif
503
504 #define WORDSZ ((word)CPP_WORDSZ)
505 #define SIGNB  ((word)1 << (WORDSZ-1))
506 #define BYTES_PER_WORD      ((word)(sizeof (word)))
507 #define ONES                ((word)(signed_word)(-1))
508 #define divWORDSZ(n) ((n) >> LOGWL)        /* divide n by size of word      */
509
510 /*********************/
511 /*                   */
512 /*  Size Parameters  */
513 /*                   */
514 /*********************/
515
516 /*  heap block size, bytes. Should be power of 2 */
517
518 #ifndef HBLKSIZE
519 # ifdef SMALL_CONFIG
520 #   define CPP_LOG_HBLKSIZE 10
521 # else
522 #   if (CPP_WORDSZ == 32) || (defined(HPUX) && defined(HP_PA))
523       /* HPUX/PA seems to use 4K pages with the 64 bit ABI */
524 #     define CPP_LOG_HBLKSIZE 12
525 #   else
526 #     define CPP_LOG_HBLKSIZE 13
527 #   endif
528 # endif
529 #else
530 # if HBLKSIZE == 512
531 #   define CPP_LOG_HBLKSIZE 9
532 # endif
533 # if HBLKSIZE == 1024
534 #   define CPP_LOG_HBLKSIZE 10
535 # endif
536 # if HBLKSIZE == 2048
537 #   define CPP_LOG_HBLKSIZE 11
538 # endif
539 # if HBLKSIZE == 4096
540 #   define CPP_LOG_HBLKSIZE 12
541 # endif
542 # if HBLKSIZE == 8192
543 #   define CPP_LOG_HBLKSIZE 13
544 # endif
545 # if HBLKSIZE == 16384
546 #   define CPP_LOG_HBLKSIZE 14
547 # endif
548 # ifndef CPP_LOG_HBLKSIZE
549     --> fix HBLKSIZE
550 # endif
551 # undef HBLKSIZE
552 #endif
553 # define CPP_HBLKSIZE (1 << CPP_LOG_HBLKSIZE)
554 # define LOG_HBLKSIZE   ((word)CPP_LOG_HBLKSIZE)
555 # define HBLKSIZE ((word)CPP_HBLKSIZE)
556
557
558 /*  max size objects supported by freelist (larger objects may be   */
559 /*  allocated, but less efficiently)                                */
560
561 #define CPP_MAXOBJBYTES (CPP_HBLKSIZE/2)
562 #define MAXOBJBYTES ((word)CPP_MAXOBJBYTES)
563 #define CPP_MAXOBJSZ    BYTES_TO_WORDS(CPP_MAXOBJBYTES)
564 #define MAXOBJSZ ((word)CPP_MAXOBJSZ)
565                 
566 # define divHBLKSZ(n) ((n) >> LOG_HBLKSIZE)
567
568 # define HBLK_PTR_DIFF(p,q) divHBLKSZ((ptr_t)p - (ptr_t)q)
569         /* Equivalent to subtracting 2 hblk pointers.   */
570         /* We do it this way because a compiler should  */
571         /* find it hard to use an integer division      */
572         /* instead of a shift.  The bundled SunOS 4.1   */
573         /* o.w. sometimes pessimizes the subtraction to */
574         /* involve a call to .div.                      */
575  
576 # define modHBLKSZ(n) ((n) & (HBLKSIZE-1))
577  
578 # define HBLKPTR(objptr) ((struct hblk *)(((word) (objptr)) & ~(HBLKSIZE-1)))
579
580 # define HBLKDISPL(objptr) (((word) (objptr)) & (HBLKSIZE-1))
581
582 /* Round up byte allocation requests to integral number of words, etc. */
583 # define ROUNDED_UP_WORDS(n) \
584         BYTES_TO_WORDS((n) + (WORDS_TO_BYTES(1) - 1 + EXTRA_BYTES))
585 # ifdef ALIGN_DOUBLE
586 #       define ALIGNED_WORDS(n) \
587             (BYTES_TO_WORDS((n) + WORDS_TO_BYTES(2) - 1 + EXTRA_BYTES) & ~1)
588 # else
589 #       define ALIGNED_WORDS(n) ROUNDED_UP_WORDS(n)
590 # endif
591 # define SMALL_OBJ(bytes) ((bytes) <= (MAXOBJBYTES - EXTRA_BYTES))
592 # define ADD_SLOP(bytes) ((bytes) + EXTRA_BYTES)
593 # ifndef MIN_WORDS
594     /* MIN_WORDS is the size of the smallest allocated object.  */
595     /* 1 and 2 are the only valid values.                       */
596     /* 2 must be used if:                                       */
597     /* - GC_gcj_malloc can be used for objects of requested     */
598     /*   size  smaller than 2 words, or                         */
599     /* - USE_MARK_BYTES is defined.                             */
600 #   if defined(USE_MARK_BYTES) || defined(GC_GCJ_SUPPORT)
601 #     define MIN_WORDS 2        /* Smallest allocated object.   */
602 #   else
603 #     define MIN_WORDS 1
604 #   endif
605 # endif
606
607
608 /*
609  * Hash table representation of sets of pages.  This assumes it is
610  * OK to add spurious entries to sets.
611  * Used by black-listing code, and perhaps by dirty bit maintenance code.
612  */
613  
614 # ifdef LARGE_CONFIG
615 #   define LOG_PHT_ENTRIES  20  /* Collisions likely at 1M blocks,      */
616                                 /* which is >= 4GB.  Each table takes   */
617                                 /* 128KB, some of which may never be    */
618                                 /* touched.                             */
619 # else
620 #   ifdef SMALL_CONFIG
621 #     define LOG_PHT_ENTRIES  14 /* Collisions are likely if heap grows */
622                                  /* to more than 16K hblks = 64MB.      */
623                                  /* Each hash table occupies 2K bytes.   */
624 #   else /* default "medium" configuration */
625 #     define LOG_PHT_ENTRIES  16 /* Collisions are likely if heap grows */
626                                  /* to more than 64K hblks >= 256MB.    */
627                                  /* Each hash table occupies 8K bytes.  */
628                                  /* Even for somewhat smaller heaps,    */
629                                  /* say half that, collisions may be an */
630                                  /* issue because we blacklist          */
631                                  /* addresses outside the heap.         */
632 #   endif
633 # endif
634 # define PHT_ENTRIES ((word)1 << LOG_PHT_ENTRIES)
635 # define PHT_SIZE (PHT_ENTRIES >> LOGWL)
636 typedef word page_hash_table[PHT_SIZE];
637
638 # define PHT_HASH(addr) ((((word)(addr)) >> LOG_HBLKSIZE) & (PHT_ENTRIES - 1))
639
640 # define get_pht_entry_from_index(bl, index) \
641                 (((bl)[divWORDSZ(index)] >> modWORDSZ(index)) & 1)
642 # define set_pht_entry_from_index(bl, index) \
643                 (bl)[divWORDSZ(index)] |= (word)1 << modWORDSZ(index)
644 # define clear_pht_entry_from_index(bl, index) \
645                 (bl)[divWORDSZ(index)] &= ~((word)1 << modWORDSZ(index))
646 /* And a dumb but thread-safe version of set_pht_entry_from_index.      */
647 /* This sets (many) extra bits.                                         */
648 # define set_pht_entry_from_index_safe(bl, index) \
649                 (bl)[divWORDSZ(index)] = ONES
650         
651
652
653 /********************************************/
654 /*                                          */
655 /*    H e a p   B l o c k s                 */
656 /*                                          */
657 /********************************************/
658
659 /*  heap block header */
660 #define HBLKMASK   (HBLKSIZE-1)
661
662 #define BITS_PER_HBLK (CPP_HBLKSIZE * 8)
663
664 #define MARK_BITS_PER_HBLK (BITS_PER_HBLK/CPP_WORDSZ)
665            /* upper bound                                    */
666            /* We allocate 1 bit/word, unless USE_MARK_BYTES  */
667            /* is defined.  Only the first word               */
668            /* in each object is actually marked.             */
669
670 # ifdef USE_MARK_BYTES
671 #   define MARK_BITS_SZ (MARK_BITS_PER_HBLK/2)
672         /* Unlike the other case, this is in units of bytes.            */
673         /* We actually allocate only every second mark bit, since we    */
674         /* force all objects to be doubleword aligned.                  */
675         /* However, each mark bit is allocated as a byte.               */
676 # else
677 #   define MARK_BITS_SZ (MARK_BITS_PER_HBLK/CPP_WORDSZ)
678 # endif
679
680 /* We maintain layout maps for heap blocks containing objects of a given */
681 /* size.  Each entry in this map describes a byte offset and has the     */
682 /* following type.                                                       */
683 typedef unsigned char map_entry_type;
684
685 struct hblkhdr {
686     word hb_sz;  /* If in use, size in words, of objects in the block. */
687                  /* if free, the size in bytes of the whole block      */
688     struct hblk * hb_next;      /* Link field for hblk free list         */
689                                 /* and for lists of chunks waiting to be */
690                                 /* reclaimed.                            */
691     struct hblk * hb_prev;      /* Backwards link for free list.        */
692     word hb_descr;              /* object descriptor for marking.  See  */
693                                 /* mark.h.                              */
694     map_entry_type * hb_map;    
695                         /* A pointer to a pointer validity map of the block. */
696                         /* See GC_obj_map.                                   */
697                         /* Valid for all blocks with headers.                */
698                         /* Free blocks point to GC_invalid_map.              */
699     unsigned char hb_obj_kind;
700                          /* Kind of objects in the block.  Each kind    */
701                          /* identifies a mark procedure and a set of    */
702                          /* list headers.  Sometimes called regions.    */
703     unsigned char hb_flags;
704 #       define IGNORE_OFF_PAGE  1       /* Ignore pointers that do not  */
705                                         /* point to the first page of   */
706                                         /* this object.                 */
707 #       define WAS_UNMAPPED 2   /* This is a free block, which has      */
708                                 /* been unmapped from the address       */
709                                 /* space.                               */
710                                 /* GC_remap must be invoked on it       */
711                                 /* before it can be reallocated.        */
712                                 /* Only set with USE_MUNMAP.            */
713     unsigned short hb_last_reclaimed;
714                                 /* Value of GC_gc_no when block was     */
715                                 /* last allocated or swept. May wrap.   */
716                                 /* For a free block, this is maintained */
717                                 /* only for USE_MUNMAP, and indicates   */
718                                 /* when the header was allocated, or    */
719                                 /* when the size of the block last      */
720                                 /* changed.                             */
721 #   ifdef USE_MARK_BYTES
722       union {
723         char _hb_marks[MARK_BITS_SZ];
724                             /* The i'th byte is 1 if the object         */
725                             /* starting at word 2i is marked, 0 o.w.    */
726         word dummy;     /* Force word alignment of mark bytes. */
727       } _mark_byte_union;
728 #     define hb_marks _mark_byte_union._hb_marks
729 #   else
730       word hb_marks[MARK_BITS_SZ];
731                             /* Bit i in the array refers to the             */
732                             /* object starting at the ith word (header      */
733                             /* INCLUDED) in the heap block.                 */
734                             /* The lsb of word 0 is numbered 0.             */
735                             /* Unused bits are invalid, and are             */
736                             /* occasionally set, e.g for uncollectable      */
737                             /* objects.                                     */
738 #   endif /* !USE_MARK_BYTES */
739 };
740
741 /*  heap block body */
742
743 # define BODY_SZ (HBLKSIZE/sizeof(word))
744
745 struct hblk {
746     word hb_body[BODY_SZ];
747 };
748
749 # define HBLK_IS_FREE(hdr) ((hdr) -> hb_map == GC_invalid_map)
750
751 # define OBJ_SZ_TO_BLOCKS(sz) \
752     divHBLKSZ(WORDS_TO_BYTES(sz) + HBLKSIZE-1)
753     /* Size of block (in units of HBLKSIZE) needed to hold objects of   */
754     /* given sz (in words).                                             */
755
756 /* Object free list link */
757 # define obj_link(p) (*(ptr_t *)(p))
758
759 # define LOG_MAX_MARK_PROCS 6
760 # define MAX_MARK_PROCS (1 << LOG_MAX_MARK_PROCS)
761
762 /* Root sets.  Logically private to mark_rts.c.  But we don't want the  */
763 /* tables scanned, so we put them here.                                 */
764 /* MAX_ROOT_SETS is the maximum number of ranges that can be    */
765 /* registered as static roots.                                  */
766 # ifdef LARGE_CONFIG
767 #   define MAX_ROOT_SETS 4096
768 # else
769 #   ifdef PCR
770 #     define MAX_ROOT_SETS 1024
771 #   else
772 #     if defined(MSWIN32) || defined(MSWINCE)
773 #       define MAX_ROOT_SETS 1024
774             /* Under NT, we add only written pages, which can result    */
775             /* in many small root sets.                                 */
776 #     else
777 #       define MAX_ROOT_SETS 1024
778 #     endif
779 #   endif
780 # endif
781
782 # define MAX_EXCLUSIONS (MAX_ROOT_SETS/4)
783 /* Maximum number of segments that can be excluded from root sets.      */
784
785 /*
786  * Data structure for excluded static roots.
787  */
788 struct exclusion {
789     ptr_t e_start;
790     ptr_t e_end;
791 };
792
793 /* Data structure for list of root sets.                                */
794 /* We keep a hash table, so that we can filter out duplicate additions. */
795 /* Under Win32, we need to do a better job of filtering overlaps, so    */
796 /* we resort to sequential search, and pay the price.                   */
797 struct roots {
798         ptr_t r_start;
799         ptr_t r_end;
800 #       if !defined(MSWIN32) && !defined(MSWINCE)
801           struct roots * r_next;
802 #       endif
803         GC_bool r_tmp;
804                 /* Delete before registering new dynamic libraries */
805 };
806
807 #if !defined(MSWIN32) && !defined(MSWINCE)
808     /* Size of hash table index to roots.       */
809 #   define LOG_RT_SIZE 6
810 #   define RT_SIZE (1 << LOG_RT_SIZE) /* Power of 2, may be != MAX_ROOT_SETS */
811 #endif
812
813 /* Lists of all heap blocks and free lists      */
814 /* as well as other random data structures      */
815 /* that should not be scanned by the            */
816 /* collector.                                   */
817 /* These are grouped together in a struct       */
818 /* so that they can be easily skipped by the    */
819 /* GC_mark routine.                             */
820 /* The ordering is weird to make GC_malloc      */
821 /* faster by keeping the important fields       */
822 /* sufficiently close together that a           */
823 /* single load of a base register will do.      */
824 /* Scalars that could easily appear to          */
825 /* be pointers are also put here.               */
826 /* The main fields should precede any           */
827 /* conditionally included fields, so that       */
828 /* gc_inl.h will work even if a different set   */
829 /* of macros is defined when the client is      */
830 /* compiled.                                    */
831
832 struct _GC_arrays {
833   word _heapsize;
834   word _max_heapsize;
835   word _requested_heapsize;     /* Heap size due to explicit expansion */
836   ptr_t _last_heap_addr;
837   ptr_t _prev_heap_addr;
838   word _large_free_bytes;
839         /* Total bytes contained in blocks on large object free */
840         /* list.                                                */
841   word _large_allocd_bytes;
842         /* Total number of bytes in allocated large objects blocks.     */
843         /* For the purposes of this counter and the next one only, a    */
844         /* large object is one that occupies a block of at least        */
845         /* 2*HBLKSIZE.                                                  */
846   word _max_large_allocd_bytes;
847         /* Maximum number of bytes that were ever allocated in          */
848         /* large object blocks.  This is used to help decide when it    */
849         /* is safe to split up a large block.                           */
850   word _words_allocd_before_gc;
851                 /* Number of words allocated before this        */
852                 /* collection cycle.                            */
853 # ifndef SEPARATE_GLOBALS
854     word _words_allocd;
855         /* Number of words allocated during this collection cycle */
856 # endif
857   word _words_wasted;
858         /* Number of words wasted due to internal fragmentation */
859         /* in large objects, or due to dropping blacklisted     */
860         /* blocks, since last gc.  Approximate.                 */
861   word _words_finalized;
862         /* Approximate number of words in objects (and headers) */
863         /* That became ready for finalization in the last       */
864         /* collection.                                          */
865   word _non_gc_bytes_at_gc;
866         /* Number of explicitly managed bytes of storage        */
867         /* at last collection.                                  */
868   word _mem_freed;
869         /* Number of explicitly deallocated words of memory     */
870         /* since last collection.                               */
871   word _finalizer_mem_freed;
872         /* Words of memory explicitly deallocated while         */
873         /* finalizers were running.  Used to approximate mem.   */
874         /* explicitly deallocated by finalizers.                */
875   ptr_t _scratch_end_ptr;
876   ptr_t _scratch_last_end_ptr;
877         /* Used by headers.c, and can easily appear to point to */
878         /* heap.                                                */
879   GC_mark_proc _mark_procs[MAX_MARK_PROCS];
880         /* Table of user-defined mark procedures.  There is     */
881         /* a small number of these, which can be referenced     */
882         /* by DS_PROC mark descriptors.  See gc_mark.h.         */
883
884 # ifndef SEPARATE_GLOBALS
885     ptr_t _objfreelist[MAXOBJSZ+1];
886                           /* free list for objects */
887     ptr_t _aobjfreelist[MAXOBJSZ+1];
888                           /* free list for atomic objs  */
889 # endif
890
891   ptr_t _uobjfreelist[MAXOBJSZ+1];
892                           /* uncollectable but traced objs      */
893                           /* objects on this and auobjfreelist  */
894                           /* are always marked, except during   */
895                           /* garbage collections.               */
896 # ifdef ATOMIC_UNCOLLECTABLE
897     ptr_t _auobjfreelist[MAXOBJSZ+1];
898 # endif
899                           /* uncollectable but traced objs      */
900
901 # ifdef GATHERSTATS
902     word _composite_in_use;
903                 /* Number of words in accessible composite      */
904                 /* objects.                                     */
905     word _atomic_in_use;
906                 /* Number of words in accessible atomic         */
907                 /* objects.                                     */
908 # endif
909 # ifdef USE_MUNMAP
910     word _unmapped_bytes;
911 # endif
912 # ifdef MERGE_SIZES
913     unsigned _size_map[WORDS_TO_BYTES(MAXOBJSZ+1)];
914         /* Number of words to allocate for a given allocation request in */
915         /* bytes.                                                        */
916 # endif 
917
918 # ifdef STUBBORN_ALLOC
919     ptr_t _sobjfreelist[MAXOBJSZ+1];
920 # endif
921                           /* free list for immutable objects    */
922   map_entry_type * _obj_map[MAXOBJSZ+1];
923                        /* If not NIL, then a pointer to a map of valid  */
924                        /* object addresses. _obj_map[sz][i] is j if the */
925                        /* address block_start+i is a valid pointer      */
926                        /* to an object at block_start +                 */
927                        /* WORDS_TO_BYTES(BYTES_TO_WORDS(i) - j)         */
928                        /* I.e. j is a word displacement from the        */
929                        /* object beginning.                             */
930                        /* The entry is OBJ_INVALID if the corresponding */
931                        /* address is not a valid pointer.  It is        */
932                        /* OFFSET_TOO_BIG if the value j would be too    */
933                        /* large to fit in the entry.  (Note that the    */
934                        /* size of these entries matters, both for       */
935                        /* space consumption and for cache utilization.) */
936 #   define OFFSET_TOO_BIG 0xfe
937 #   define OBJ_INVALID 0xff
938 #   define MAP_ENTRY(map, bytes) (map)[bytes]
939 #   define MAP_ENTRIES HBLKSIZE
940 #   define MAP_SIZE MAP_ENTRIES
941 #   define CPP_MAX_OFFSET (OFFSET_TOO_BIG - 1)  
942 #   define MAX_OFFSET ((word)CPP_MAX_OFFSET)
943     /* The following are used only if GC_all_interior_ptrs != 0 */
944 #       define VALID_OFFSET_SZ \
945           (CPP_MAX_OFFSET > WORDS_TO_BYTES(CPP_MAXOBJSZ)? \
946            CPP_MAX_OFFSET+1 \
947            : WORDS_TO_BYTES(CPP_MAXOBJSZ)+1)
948         char _valid_offsets[VALID_OFFSET_SZ];
949                                 /* GC_valid_offsets[i] == TRUE ==> i    */
950                                 /* is registered as a displacement.     */
951         char _modws_valid_offsets[sizeof(word)];
952                                 /* GC_valid_offsets[i] ==>                */
953                                 /* GC_modws_valid_offsets[i%sizeof(word)] */
954 #   define OFFSET_VALID(displ) \
955           (GC_all_interior_pointers || GC_valid_offsets[displ])
956 # ifdef STUBBORN_ALLOC
957     page_hash_table _changed_pages;
958         /* Stubborn object pages that were changes since last call to   */
959         /* GC_read_changed.                                             */
960     page_hash_table _prev_changed_pages;
961         /* Stubborn object pages that were changes before last call to  */
962         /* GC_read_changed.                                             */
963 # endif
964 # if defined(PROC_VDB) || defined(MPROTECT_VDB)
965     page_hash_table _grungy_pages; /* Pages that were dirty at last        */
966                                      /* GC_read_dirty.                     */
967 # endif
968 # ifdef MPROTECT_VDB
969     VOLATILE page_hash_table _dirty_pages;      
970                         /* Pages dirtied since last GC_read_dirty. */
971 # endif
972 # ifdef PROC_VDB
973     page_hash_table _written_pages;     /* Pages ever dirtied   */
974 # endif
975 # ifdef LARGE_CONFIG
976 #   if CPP_WORDSZ > 32
977 #     define MAX_HEAP_SECTS 4096        /* overflows at roughly 64 GB      */
978 #   else
979 #     define MAX_HEAP_SECTS 768         /* Separately added heap sections. */
980 #   endif
981 # else
982 #   ifdef SMALL_CONFIG
983 #     define MAX_HEAP_SECTS 128         /* Roughly 256MB (128*2048*1K)  */
984 #   else
985 #     define MAX_HEAP_SECTS 384         /* Roughly 3GB                  */
986 #   endif
987 # endif
988   struct HeapSect {
989       ptr_t hs_start; word hs_bytes;
990   } _heap_sects[MAX_HEAP_SECTS];
991 # if defined(MSWIN32) || defined(MSWINCE)
992     ptr_t _heap_bases[MAX_HEAP_SECTS];
993                 /* Start address of memory regions obtained from kernel. */
994 # endif
995 # ifdef MSWINCE
996     word _heap_lengths[MAX_HEAP_SECTS];
997                 /* Commited lengths of memory regions obtained from kernel. */
998 # endif
999   struct roots _static_roots[MAX_ROOT_SETS];
1000 # if !defined(MSWIN32) && !defined(MSWINCE)
1001     struct roots * _root_index[RT_SIZE];
1002 # endif
1003   struct exclusion _excl_table[MAX_EXCLUSIONS];
1004   /* Block header index; see gc_headers.h */
1005   bottom_index * _all_nils;
1006   bottom_index * _top_index [TOP_SZ];
1007 #ifdef SAVE_CALL_CHAIN
1008   struct callinfo _last_stack[NFRAMES]; /* Stack at last garbage collection.*/
1009                                         /* Useful for debugging mysterious  */
1010                                         /* object disappearances.           */
1011                                         /* In the multithreaded case, we    */
1012                                         /* currently only save the calling  */
1013                                         /* stack.                           */
1014 #endif
1015 };
1016
1017 GC_API GC_FAR struct _GC_arrays GC_arrays; 
1018
1019 # ifndef SEPARATE_GLOBALS
1020 #   define GC_objfreelist GC_arrays._objfreelist
1021 #   define GC_aobjfreelist GC_arrays._aobjfreelist
1022 #   define GC_words_allocd GC_arrays._words_allocd
1023 # endif
1024 # define GC_uobjfreelist GC_arrays._uobjfreelist
1025 # ifdef ATOMIC_UNCOLLECTABLE
1026 #   define GC_auobjfreelist GC_arrays._auobjfreelist
1027 # endif
1028 # define GC_sobjfreelist GC_arrays._sobjfreelist
1029 # define GC_valid_offsets GC_arrays._valid_offsets
1030 # define GC_modws_valid_offsets GC_arrays._modws_valid_offsets
1031 # ifdef STUBBORN_ALLOC
1032 #    define GC_changed_pages GC_arrays._changed_pages
1033 #    define GC_prev_changed_pages GC_arrays._prev_changed_pages
1034 # endif
1035 # define GC_obj_map GC_arrays._obj_map
1036 # define GC_last_heap_addr GC_arrays._last_heap_addr
1037 # define GC_prev_heap_addr GC_arrays._prev_heap_addr
1038 # define GC_words_wasted GC_arrays._words_wasted
1039 # define GC_large_free_bytes GC_arrays._large_free_bytes
1040 # define GC_large_allocd_bytes GC_arrays._large_allocd_bytes
1041 # define GC_max_large_allocd_bytes GC_arrays._max_large_allocd_bytes
1042 # define GC_words_finalized GC_arrays._words_finalized
1043 # define GC_non_gc_bytes_at_gc GC_arrays._non_gc_bytes_at_gc
1044 # define GC_mem_freed GC_arrays._mem_freed
1045 # define GC_finalizer_mem_freed GC_arrays._finalizer_mem_freed
1046 # define GC_scratch_end_ptr GC_arrays._scratch_end_ptr
1047 # define GC_scratch_last_end_ptr GC_arrays._scratch_last_end_ptr
1048 # define GC_mark_procs GC_arrays._mark_procs
1049 # define GC_heapsize GC_arrays._heapsize
1050 # define GC_max_heapsize GC_arrays._max_heapsize
1051 # define GC_requested_heapsize GC_arrays._requested_heapsize
1052 # define GC_words_allocd_before_gc GC_arrays._words_allocd_before_gc
1053 # define GC_heap_sects GC_arrays._heap_sects
1054 # define GC_last_stack GC_arrays._last_stack
1055 # ifdef USE_MUNMAP
1056 #   define GC_unmapped_bytes GC_arrays._unmapped_bytes
1057 # endif
1058 # if defined(MSWIN32) || defined(MSWINCE)
1059 #   define GC_heap_bases GC_arrays._heap_bases
1060 # endif
1061 # ifdef MSWINCE
1062 #   define GC_heap_lengths GC_arrays._heap_lengths
1063 # endif
1064 # define GC_static_roots GC_arrays._static_roots
1065 # define GC_root_index GC_arrays._root_index
1066 # define GC_excl_table GC_arrays._excl_table
1067 # define GC_all_nils GC_arrays._all_nils
1068 # define GC_top_index GC_arrays._top_index
1069 # if defined(PROC_VDB) || defined(MPROTECT_VDB)
1070 #   define GC_grungy_pages GC_arrays._grungy_pages
1071 # endif
1072 # ifdef MPROTECT_VDB
1073 #   define GC_dirty_pages GC_arrays._dirty_pages
1074 # endif
1075 # ifdef PROC_VDB
1076 #   define GC_written_pages GC_arrays._written_pages
1077 # endif
1078 # ifdef GATHERSTATS
1079 #   define GC_composite_in_use GC_arrays._composite_in_use
1080 #   define GC_atomic_in_use GC_arrays._atomic_in_use
1081 # endif
1082 # ifdef MERGE_SIZES
1083 #   define GC_size_map GC_arrays._size_map
1084 # endif
1085
1086 # define beginGC_arrays ((ptr_t)(&GC_arrays))
1087 # define endGC_arrays (((ptr_t)(&GC_arrays)) + (sizeof GC_arrays))
1088
1089 #define USED_HEAP_SIZE (GC_heapsize - GC_large_free_bytes)
1090
1091 /* Object kinds: */
1092 # define MAXOBJKINDS 16
1093
1094 extern struct obj_kind {
1095    ptr_t *ok_freelist;  /* Array of free listheaders for this kind of object */
1096                         /* Point either to GC_arrays or to storage allocated */
1097                         /* with GC_scratch_alloc.                            */
1098    struct hblk **ok_reclaim_list;
1099                         /* List headers for lists of blocks waiting to be */
1100                         /* swept.                                         */
1101    word ok_descriptor;  /* Descriptor template for objects in this      */
1102                         /* block.                                       */
1103    GC_bool ok_relocate_descr;
1104                         /* Add object size in bytes to descriptor       */
1105                         /* template to obtain descriptor.  Otherwise    */
1106                         /* template is used as is.                      */
1107    GC_bool ok_init;   /* Clear objects before putting them on the free list. */
1108 } GC_obj_kinds[MAXOBJKINDS];
1109
1110 # define beginGC_obj_kinds ((ptr_t)(&GC_obj_kinds))
1111 # define endGC_obj_kinds (beginGC_obj_kinds + (sizeof GC_obj_kinds))
1112
1113 /* Variables that used to be in GC_arrays, but need to be accessed by   */
1114 /* inline allocation code.  If they were in GC_arrays, the inlined      */
1115 /* allocation code would include GC_arrays offsets (as it did), which   */
1116 /* introduce maintenance problems.                                      */
1117
1118 #ifdef SEPARATE_GLOBALS
1119   word GC_words_allocd;
1120         /* Number of words allocated during this collection cycle */
1121   ptr_t GC_objfreelist[MAXOBJSZ+1];
1122                           /* free list for NORMAL objects */
1123 # define beginGC_objfreelist ((ptr_t)(&GC_objfreelist))
1124 # define endGC_objfreelist (beginGC_objfreelist + sizeof(GC_objfreelist))
1125
1126   ptr_t GC_aobjfreelist[MAXOBJSZ+1];
1127                           /* free list for atomic (PTRFREE) objs        */
1128 # define beginGC_aobjfreelist ((ptr_t)(&GC_aobjfreelist))
1129 # define endGC_aobjfreelist (beginGC_aobjfreelist + sizeof(GC_aobjfreelist))
1130 #endif
1131
1132 /* Predefined kinds: */
1133 # define PTRFREE 0
1134 # define NORMAL  1
1135 # define UNCOLLECTABLE 2
1136 # ifdef ATOMIC_UNCOLLECTABLE
1137 #   define AUNCOLLECTABLE 3
1138 #   define STUBBORN 4
1139 #   define IS_UNCOLLECTABLE(k) (((k) & ~1) == UNCOLLECTABLE)
1140 # else
1141 #   define STUBBORN 3
1142 #   define IS_UNCOLLECTABLE(k) ((k) == UNCOLLECTABLE)
1143 # endif
1144
1145 extern int GC_n_kinds;
1146
1147 GC_API word GC_fo_entries;
1148
1149 extern word GC_n_heap_sects;    /* Number of separately added heap      */
1150                                 /* sections.                            */
1151
1152 extern word GC_page_size;
1153
1154 # if defined(MSWIN32) || defined(MSWINCE)
1155   struct _SYSTEM_INFO;
1156   extern struct _SYSTEM_INFO GC_sysinfo;
1157   extern word GC_n_heap_bases;  /* See GC_heap_bases.   */
1158 # endif
1159
1160 extern word GC_total_stack_black_listed;
1161                         /* Number of bytes on stack blacklist.  */
1162
1163 extern word GC_black_list_spacing;
1164                         /* Average number of bytes between blacklisted  */
1165                         /* blocks. Approximate.                         */
1166                         /* Counts only blocks that are                  */
1167                         /* "stack-blacklisted", i.e. that are           */
1168                         /* problematic in the interior of an object.    */
1169
1170 extern map_entry_type * GC_invalid_map;
1171                         /* Pointer to the nowhere valid hblk map */
1172                         /* Blocks pointing to this map are free. */
1173
1174 extern struct hblk * GC_hblkfreelist[];
1175                                 /* List of completely empty heap blocks */
1176                                 /* Linked through hb_next field of      */
1177                                 /* header structure associated with     */
1178                                 /* block.                               */
1179
1180 extern GC_bool GC_objects_are_marked;   /* There are marked objects in  */
1181                                         /* the heap.                    */
1182
1183 #ifndef SMALL_CONFIG
1184   extern GC_bool GC_incremental;
1185                         /* Using incremental/generational collection. */
1186 # define TRUE_INCREMENTAL \
1187         (GC_incremental && GC_time_limit != GC_TIME_UNLIMITED)
1188         /* True incremental, not just generational, mode */
1189 #else
1190 # define GC_incremental FALSE
1191                         /* Hopefully allow optimizer to remove some code. */
1192 # define TRUE_INCREMENTAL FALSE
1193 #endif
1194
1195 extern GC_bool GC_dirty_maintained;
1196                                 /* Dirty bits are being maintained,     */
1197                                 /* either for incremental collection,   */
1198                                 /* or to limit the root set.            */
1199
1200 extern word GC_root_size;       /* Total size of registered root sections */
1201
1202 extern GC_bool GC_debugging_started;    /* GC_debug_malloc has been called. */ 
1203
1204 extern long GC_large_alloc_warn_interval;
1205         /* Interval between unsuppressed warnings.      */
1206
1207 extern long GC_large_alloc_warn_suppressed;
1208         /* Number of warnings suppressed so far.        */
1209
1210 #ifdef THREADS
1211   extern GC_bool GC_world_stopped;
1212 #endif
1213
1214 /* Operations */
1215 # ifndef abs
1216 #   define abs(x)  ((x) < 0? (-(x)) : (x))
1217 # endif
1218
1219
1220 /*  Marks are in a reserved area in                          */
1221 /*  each heap block.  Each word has one mark bit associated  */
1222 /*  with it. Only those corresponding to the beginning of an */
1223 /*  object are used.                                         */
1224
1225 /* Set mark bit correctly, even if mark bits may be concurrently        */
1226 /* accessed.                                                            */
1227 #ifdef PARALLEL_MARK
1228 # define OR_WORD(addr, bits) \
1229         { word old; \
1230           do { \
1231             old = *((volatile word *)addr); \
1232           } while (!GC_compare_and_exchange((addr), old, old | (bits))); \
1233         }
1234 # define OR_WORD_EXIT_IF_SET(addr, bits, exit_label) \
1235         { word old; \
1236           word my_bits = (bits); \
1237           do { \
1238             old = *((volatile word *)addr); \
1239             if (old & my_bits) goto exit_label; \
1240           } while (!GC_compare_and_exchange((addr), old, old | my_bits)); \
1241         }
1242 #else
1243 # define OR_WORD(addr, bits) *(addr) |= (bits)
1244 # define OR_WORD_EXIT_IF_SET(addr, bits, exit_label) \
1245         { \
1246           word old = *(addr); \
1247           word my_bits = (bits); \
1248           if (old & my_bits) goto exit_label; \
1249           *(addr) = (old | my_bits); \
1250         }
1251 #endif
1252
1253 /* Mark bit operations */
1254
1255 /*
1256  * Retrieve, set, clear the mark bit corresponding
1257  * to the nth word in a given heap block.
1258  *
1259  * (Recall that bit n corresponds to object beginning at word n
1260  * relative to the beginning of the block, including unused words)
1261  */
1262
1263 #ifdef USE_MARK_BYTES
1264 # define mark_bit_from_hdr(hhdr,n) ((hhdr)->hb_marks[(n) >> 1])
1265 # define set_mark_bit_from_hdr(hhdr,n) ((hhdr)->hb_marks[(n)>>1]) = 1
1266 # define clear_mark_bit_from_hdr(hhdr,n) ((hhdr)->hb_marks[(n)>>1]) = 0
1267 #else /* !USE_MARK_BYTES */
1268 # define mark_bit_from_hdr(hhdr,n) (((hhdr)->hb_marks[divWORDSZ(n)] \
1269                             >> (modWORDSZ(n))) & (word)1)
1270 # define set_mark_bit_from_hdr(hhdr,n) \
1271                             OR_WORD((hhdr)->hb_marks+divWORDSZ(n), \
1272                                     (word)1 << modWORDSZ(n))
1273 # define clear_mark_bit_from_hdr(hhdr,n) (hhdr)->hb_marks[divWORDSZ(n)] \
1274                                 &= ~((word)1 << modWORDSZ(n))
1275 #endif /* !USE_MARK_BYTES */
1276
1277 /* Important internal collector routines */
1278
1279 ptr_t GC_approx_sp GC_PROTO((void));
1280   
1281 GC_bool GC_should_collect GC_PROTO((void));
1282   
1283 void GC_apply_to_all_blocks GC_PROTO(( \
1284     void (*fn) GC_PROTO((struct hblk *h, word client_data)), \
1285     word client_data));
1286                         /* Invoke fn(hbp, client_data) for each         */
1287                         /* allocated heap block.                        */
1288 struct hblk * GC_next_used_block GC_PROTO((struct hblk * h));
1289                         /* Return first in-use block >= h       */
1290 struct hblk * GC_prev_block GC_PROTO((struct hblk * h));
1291                         /* Return last block <= h.  Returned block      */
1292                         /* is managed by GC, but may or may not be in   */
1293                         /* use.                                         */
1294 void GC_mark_init GC_PROTO((void));
1295 void GC_clear_marks GC_PROTO((void));   /* Clear mark bits for all heap objects. */
1296 void GC_invalidate_mark_state GC_PROTO((void));
1297                                         /* Tell the marker that marked     */
1298                                         /* objects may point to unmarked   */
1299                                         /* ones, and roots may point to    */
1300                                         /* unmarked objects.               */
1301                                         /* Reset mark stack.               */
1302 GC_bool GC_mark_stack_empty GC_PROTO((void));
1303 GC_bool GC_mark_some GC_PROTO((ptr_t cold_gc_frame));
1304                         /* Perform about one pages worth of marking     */
1305                         /* work of whatever kind is needed.  Returns    */
1306                         /* quickly if no collection is in progress.     */
1307                         /* Return TRUE if mark phase finished.          */
1308 void GC_initiate_gc GC_PROTO((void));
1309                                 /* initiate collection.                 */
1310                                 /* If the mark state is invalid, this   */
1311                                 /* becomes full colleection.  Otherwise */
1312                                 /* it's partial.                        */
1313 void GC_push_all GC_PROTO((ptr_t bottom, ptr_t top));
1314                                 /* Push everything in a range           */
1315                                 /* onto mark stack.                     */
1316 void GC_push_selected GC_PROTO(( \
1317     ptr_t bottom, \
1318     ptr_t top, \
1319     int (*dirty_fn) GC_PROTO((struct hblk *h)), \
1320     void (*push_fn) GC_PROTO((ptr_t bottom, ptr_t top)) ));
1321                                   /* Push all pages h in [b,t) s.t.     */
1322                                   /* select_fn(h) != 0 onto mark stack. */
1323 #ifndef SMALL_CONFIG
1324   void GC_push_conditional GC_PROTO((ptr_t b, ptr_t t, GC_bool all));
1325 #else
1326 # define GC_push_conditional(b, t, all) GC_push_all(b, t)
1327 #endif
1328                                 /* Do either of the above, depending    */
1329                                 /* on the third arg.                    */
1330 void GC_push_all_stack GC_PROTO((ptr_t b, ptr_t t));
1331                                     /* As above, but consider           */
1332                                     /*  interior pointers as valid      */
1333 void GC_push_all_eager GC_PROTO((ptr_t b, ptr_t t));
1334                                     /* Same as GC_push_all_stack, but   */
1335                                     /* ensures that stack is scanned    */
1336                                     /* immediately, not just scheduled  */
1337                                     /* for scanning.                    */
1338 #ifndef THREADS
1339   void GC_push_all_stack_partially_eager GC_PROTO(( \
1340       ptr_t bottom, ptr_t top, ptr_t cold_gc_frame ));
1341                         /* Similar to GC_push_all_eager, but only the   */
1342                         /* part hotter than cold_gc_frame is scanned    */
1343                         /* immediately.  Needed to ensure that callee-  */
1344                         /* save registers are not missed.               */
1345 #else
1346   /* In the threads case, we push part of the current thread stack      */
1347   /* with GC_push_all_eager when we push the registers.  This gets the  */
1348   /* callee-save registers that may disappear.  The remainder of the    */
1349   /* stacks are scheduled for scanning in *GC_push_other_roots, which   */
1350   /* is thread-package-specific.                                        */
1351 #endif
1352 void GC_push_current_stack GC_PROTO((ptr_t cold_gc_frame));
1353                         /* Push enough of the current stack eagerly to  */
1354                         /* ensure that callee-save registers saved in   */
1355                         /* GC frames are scanned.                       */
1356                         /* In the non-threads case, schedule entire     */
1357                         /* stack for scanning.                          */
1358 void GC_push_roots GC_PROTO((GC_bool all, ptr_t cold_gc_frame));
1359                         /* Push all or dirty roots.     */
1360 extern void (*GC_push_other_roots) GC_PROTO((void));
1361                         /* Push system or application specific roots    */
1362                         /* onto the mark stack.  In some environments   */
1363                         /* (e.g. threads environments) this is          */
1364                         /* predfined to be non-zero.  A client supplied */
1365                         /* replacement should also call the original    */
1366                         /* function.                                    */
1367 extern void GC_push_gc_structures GC_PROTO((void));
1368                         /* Push GC internal roots.  These are normally  */
1369                         /* included in the static data segment, and     */
1370                         /* Thus implicitly pushed.  But we must do this */
1371                         /* explicitly if normal root processing is      */
1372                         /* disabled.  Calls the following:              */
1373         extern void GC_push_finalizer_structures GC_PROTO((void));
1374         extern void GC_push_stubborn_structures GC_PROTO((void));
1375 #       ifdef THREADS
1376           extern void GC_push_thread_structures GC_PROTO((void));
1377 #       endif
1378 extern void (*GC_start_call_back) GC_PROTO((void));
1379                         /* Called at start of full collections.         */
1380                         /* Not called if 0.  Called with allocation     */
1381                         /* lock held.                                   */
1382                         /* 0 by default.                                */
1383 # if defined(USE_GENERIC_PUSH_REGS)
1384   void GC_generic_push_regs GC_PROTO((ptr_t cold_gc_frame));
1385 # else
1386   void GC_push_regs GC_PROTO((void));
1387 # endif
1388 # if defined(SPARC) || defined(IA64)
1389   /* Cause all stacked registers to be saved in memory.  Return a       */
1390   /* pointer to the top of the corresponding memory stack.              */
1391   word GC_save_regs_in_stack GC_PROTO((void));
1392 # endif
1393                         /* Push register contents onto mark stack.      */
1394                         /* If NURSERY is defined, the default push      */
1395                         /* action can be overridden with GC_push_proc   */
1396
1397 # ifdef NURSERY
1398     extern void (*GC_push_proc)(ptr_t);
1399 # endif
1400 # if defined(MSWIN32) || defined(MSWINCE)
1401   void __cdecl GC_push_one GC_PROTO((word p));
1402 # else
1403   void GC_push_one GC_PROTO((word p));
1404                               /* If p points to an object, mark it    */
1405                               /* and push contents on the mark stack  */
1406                               /* Pointer recognition test always      */
1407                               /* accepts interior pointers, i.e. this */
1408                               /* is appropriate for pointers found on */
1409                               /* stack.                               */
1410 # endif
1411 # if defined(PRINT_BLACK_LIST) || defined(KEEP_BACK_PTRS)
1412   void GC_mark_and_push_stack GC_PROTO((word p, ptr_t source));
1413                                 /* Ditto, omits plausibility test       */
1414 # else
1415   void GC_mark_and_push_stack GC_PROTO((word p));
1416 # endif
1417 void GC_push_marked GC_PROTO((struct hblk * h, hdr * hhdr));
1418                 /* Push contents of all marked objects in h onto        */
1419                 /* mark stack.                                          */
1420 #ifdef SMALL_CONFIG
1421 # define GC_push_next_marked_dirty(h) GC_push_next_marked(h)
1422 #else
1423   struct hblk * GC_push_next_marked_dirty GC_PROTO((struct hblk * h));
1424                 /* Invoke GC_push_marked on next dirty block above h.   */
1425                 /* Return a pointer just past the end of this block.    */
1426 #endif /* !SMALL_CONFIG */
1427 struct hblk * GC_push_next_marked GC_PROTO((struct hblk * h));
1428                 /* Ditto, but also mark from clean pages.       */
1429 struct hblk * GC_push_next_marked_uncollectable GC_PROTO((struct hblk * h));
1430                 /* Ditto, but mark only from uncollectable pages.       */
1431 GC_bool GC_stopped_mark GC_PROTO((GC_stop_func stop_func));
1432                         /* Stop world and mark from all roots   */
1433                         /* and rescuers.                        */
1434 void GC_clear_hdr_marks GC_PROTO((hdr * hhdr));
1435                                     /* Clear the mark bits in a header */
1436 void GC_set_hdr_marks GC_PROTO((hdr * hhdr));
1437                                     /* Set the mark bits in a header */
1438 void GC_set_fl_marks GC_PROTO((ptr_t p));
1439                                     /* Set all mark bits associated with */
1440                                     /* a free list.                      */
1441 void GC_add_roots_inner GC_PROTO((char * b, char * e, GC_bool tmp));
1442 void GC_remove_roots_inner GC_PROTO((char * b, char * e));
1443 GC_bool GC_is_static_root GC_PROTO((ptr_t p));
1444                 /* Is the address p in one of the registered static     */
1445                 /* root sections?                                       */
1446 # if defined(MSWIN32) || defined(_WIN32_WCE_EMULATION)
1447 GC_bool GC_is_tmp_root GC_PROTO((ptr_t p));
1448                 /* Is the address p in one of the temporary static      */
1449                 /* root sections?                                       */
1450 # endif
1451 void GC_register_dynamic_libraries GC_PROTO((void));
1452                 /* Add dynamic library data sections to the root set. */
1453
1454 GC_bool GC_register_main_static_data GC_PROTO((void));
1455                 /* We need to register the main data segment.  Returns  */
1456                 /* TRUE unless this is done implicitly as part of       */
1457                 /* dynamic library registration.                        */
1458   
1459 /* Machine dependent startup routines */
1460 ptr_t GC_get_stack_base GC_PROTO((void));       /* Cold end of stack */
1461 #ifdef IA64
1462   ptr_t GC_get_register_stack_base GC_PROTO((void));
1463                                         /* Cold end of register stack.  */
1464 #endif
1465 void GC_register_data_segments GC_PROTO((void));
1466   
1467 /* Black listing: */
1468 void GC_bl_init GC_PROTO((void));
1469 # ifdef PRINT_BLACK_LIST
1470       void GC_add_to_black_list_normal GC_PROTO((word p, ptr_t source));
1471                         /* Register bits as a possible future false     */
1472                         /* reference from the heap or static data       */
1473 #     define GC_ADD_TO_BLACK_LIST_NORMAL(bits, source) \
1474                 if (GC_all_interior_pointers) { \
1475                   GC_add_to_black_list_stack(bits, (ptr_t)(source)); \
1476                 } else { \
1477                   GC_add_to_black_list_normal(bits, (ptr_t)(source)); \
1478                 }
1479 # else
1480       void GC_add_to_black_list_normal GC_PROTO((word p));
1481 #     define GC_ADD_TO_BLACK_LIST_NORMAL(bits, source) \
1482                 if (GC_all_interior_pointers) { \
1483                   GC_add_to_black_list_stack(bits); \
1484                 } else { \
1485                   GC_add_to_black_list_normal(bits); \
1486                 }
1487 # endif
1488
1489 # ifdef PRINT_BLACK_LIST
1490     void GC_add_to_black_list_stack GC_PROTO((word p, ptr_t source));
1491 # else
1492     void GC_add_to_black_list_stack GC_PROTO((word p));
1493 # endif
1494 struct hblk * GC_is_black_listed GC_PROTO((struct hblk * h, word len));
1495                         /* If there are likely to be false references   */
1496                         /* to a block starting at h of the indicated    */
1497                         /* length, then return the next plausible       */
1498                         /* starting location for h that might avoid     */
1499                         /* these false references.                      */
1500 void GC_promote_black_lists GC_PROTO((void));
1501                         /* Declare an end to a black listing phase.     */
1502 void GC_unpromote_black_lists GC_PROTO((void));
1503                         /* Approximately undo the effect of the above.  */
1504                         /* This actually loses some information, but    */
1505                         /* only in a reasonably safe way.               */
1506 word GC_number_stack_black_listed GC_PROTO(( \
1507         struct hblk *start, struct hblk *endp1));
1508                         /* Return the number of (stack) blacklisted     */
1509                         /* blocks in the range for statistical          */
1510                         /* purposes.                                    */
1511                         
1512 ptr_t GC_scratch_alloc GC_PROTO((word bytes));
1513                                 /* GC internal memory allocation for    */
1514                                 /* small objects.  Deallocation is not  */
1515                                 /* possible.                            */
1516         
1517 /* Heap block layout maps: */                   
1518 void GC_invalidate_map GC_PROTO((hdr * hhdr));
1519                                 /* Remove the object map associated     */
1520                                 /* with the block.  This identifies     */
1521                                 /* the block as invalid to the mark     */
1522                                 /* routines.                            */
1523 GC_bool GC_add_map_entry GC_PROTO((word sz));
1524                                 /* Add a heap block map for objects of  */
1525                                 /* size sz to obj_map.                  */
1526                                 /* Return FALSE on failure.             */
1527 void GC_register_displacement_inner GC_PROTO((word offset));
1528                                 /* Version of GC_register_displacement  */
1529                                 /* that assumes lock is already held    */
1530                                 /* and signals are already disabled.    */
1531   
1532 /*  hblk allocation: */         
1533 void GC_new_hblk GC_PROTO((word size_in_words, int kind));
1534                                 /* Allocate a new heap block, and build */
1535                                 /* a free list in it.                   */                              
1536
1537 ptr_t GC_build_fl GC_PROTO((struct hblk *h, word sz,
1538                            GC_bool clear,  ptr_t list));
1539                                 /* Build a free list for objects of     */
1540                                 /* size sz in block h.  Append list to  */
1541                                 /* end of the free lists.  Possibly     */
1542                                 /* clear objects on the list.  Normally */
1543                                 /* called by GC_new_hblk, but also      */
1544                                 /* called explicitly without GC lock.   */
1545
1546 struct hblk * GC_allochblk GC_PROTO(( \
1547         word size_in_words, int kind, unsigned flags));
1548                                 /* Allocate a heap block, inform        */
1549                                 /* the marker that block is valid       */
1550                                 /* for objects of indicated size.       */
1551
1552 ptr_t GC_alloc_large GC_PROTO((word lw, int k, unsigned flags));
1553                         /* Allocate a large block of size lw words.     */
1554                         /* The block is not cleared.                    */
1555                         /* Flags is 0 or IGNORE_OFF_PAGE.               */
1556                         /* Calls GC_allchblk to do the actual           */
1557                         /* allocation, but also triggers GC and/or      */
1558                         /* heap expansion as appropriate.               */
1559                         /* Does not update GC_words_allocd, but does    */
1560                         /* other accounting.                            */
1561
1562 ptr_t GC_alloc_large_and_clear GC_PROTO((word lw, int k, unsigned flags));
1563                         /* As above, but clear block if appropriate     */
1564                         /* for kind k.                                  */
1565
1566 void GC_freehblk GC_PROTO((struct hblk * p));
1567                                 /* Deallocate a heap block and mark it  */
1568                                 /* as invalid.                          */
1569                                 
1570 /*  Misc GC: */
1571 void GC_init_inner GC_PROTO((void));
1572 GC_bool GC_expand_hp_inner GC_PROTO((word n));
1573 void GC_start_reclaim GC_PROTO((int abort_if_found));
1574                                 /* Restore unmarked objects to free     */
1575                                 /* lists, or (if abort_if_found is      */
1576                                 /* TRUE) report them.                   */
1577                                 /* Sweeping of small object pages is    */
1578                                 /* largely deferred.                    */
1579 void GC_continue_reclaim GC_PROTO((word sz, int kind));
1580                                 /* Sweep pages of the given size and    */
1581                                 /* kind, as long as possible, and       */
1582                                 /* as long as the corr. free list is    */
1583                                 /* empty.                               */
1584 void GC_reclaim_or_delete_all GC_PROTO((void));
1585                                 /* Arrange for all reclaim lists to be  */
1586                                 /* empty.  Judiciously choose between   */
1587                                 /* sweeping and discarding each page.   */
1588 GC_bool GC_reclaim_all GC_PROTO((GC_stop_func stop_func, GC_bool ignore_old));
1589                                 /* Reclaim all blocks.  Abort (in a     */
1590                                 /* consistent state) if f returns TRUE. */
1591 GC_bool GC_block_empty GC_PROTO((hdr * hhdr));
1592                                 /* Block completely unmarked?   */
1593 GC_bool GC_never_stop_func GC_PROTO((void));
1594                                 /* Returns FALSE.               */
1595 GC_bool GC_try_to_collect_inner GC_PROTO((GC_stop_func f));
1596
1597                                 /* Collect; caller must have acquired   */
1598                                 /* lock and disabled signals.           */
1599                                 /* Collection is aborted if f returns   */
1600                                 /* TRUE.  Returns TRUE if it completes  */
1601                                 /* successfully.                        */
1602 # define GC_gcollect_inner() \
1603         (void) GC_try_to_collect_inner(GC_never_stop_func)
1604 void GC_finish_collection GC_PROTO((void));
1605                                 /* Finish collection.  Mark bits are    */
1606                                 /* consistent and lock is still held.   */
1607 GC_bool GC_collect_or_expand GC_PROTO(( \
1608         word needed_blocks, GC_bool ignore_off_page));
1609                                 /* Collect or expand heap in an attempt */
1610                                 /* make the indicated number of free    */
1611                                 /* blocks available.  Should be called  */
1612                                 /* until the blocks are available or    */
1613                                 /* until it fails by returning FALSE.   */
1614
1615 extern GC_bool GC_is_initialized;       /* GC_init() has been run.      */
1616
1617 #if defined(MSWIN32) || defined(MSWINCE)
1618   void GC_deinit GC_PROTO((void));
1619                                 /* Free any resources allocated by      */
1620                                 /* GC_init                              */
1621 #endif
1622
1623 void GC_collect_a_little_inner GC_PROTO((int n));
1624                                 /* Do n units worth of garbage          */
1625                                 /* collection work, if appropriate.     */
1626                                 /* A unit is an amount appropriate for  */
1627                                 /* HBLKSIZE bytes of allocation.        */
1628 /* ptr_t GC_generic_malloc GC_PROTO((word lb, int k)); */
1629                                 /* Allocate an object of the given      */
1630                                 /* kind.  By default, there are only    */
1631                                 /* a few kinds: composite(pointerfree), */
1632                                 /* atomic, uncollectable, etc.          */
1633                                 /* We claim it's possible for clever    */
1634                                 /* client code that understands GC      */
1635                                 /* internals to add more, e.g. to       */
1636                                 /* communicate object layout info       */
1637                                 /* to the collector.                    */
1638                                 /* The actual decl is in gc_mark.h.     */
1639 ptr_t GC_generic_malloc_ignore_off_page GC_PROTO((size_t b, int k));
1640                                 /* As above, but pointers past the      */
1641                                 /* first page of the resulting object   */
1642                                 /* are ignored.                         */
1643 ptr_t GC_generic_malloc_inner GC_PROTO((word lb, int k));
1644                                 /* Ditto, but I already hold lock, etc. */
1645 ptr_t GC_generic_malloc_words_small_inner GC_PROTO((word lw, int k));
1646                                 /* Analogous to the above, but assumes  */
1647                                 /* a small object size, and bypasses    */
1648                                 /* MERGE_SIZES mechanism.               */
1649 ptr_t GC_generic_malloc_words_small GC_PROTO((size_t lw, int k));
1650                                 /* As above, but size in units of words */
1651                                 /* Bypasses MERGE_SIZES.  Assumes       */
1652                                 /* words <= MAXOBJSZ.                   */
1653 ptr_t GC_generic_malloc_inner_ignore_off_page GC_PROTO((size_t lb, int k));
1654                                 /* Allocate an object, where            */
1655                                 /* the client guarantees that there     */
1656                                 /* will always be a pointer to the      */
1657                                 /* beginning of the object while the    */
1658                                 /* object is live.                      */
1659 ptr_t GC_allocobj GC_PROTO((word sz, int kind));
1660                                 /* Make the indicated                   */
1661                                 /* free list nonempty, and return its   */
1662                                 /* head.                                */
1663
1664 void GC_free_inner(GC_PTR p);
1665   
1666 void GC_init_headers GC_PROTO((void));
1667 struct hblkhdr * GC_install_header GC_PROTO((struct hblk *h));
1668                                 /* Install a header for block h.        */
1669                                 /* Return 0 on failure, or the header   */
1670                                 /* otherwise.                           */
1671 GC_bool GC_install_counts GC_PROTO((struct hblk * h, word sz));
1672                                 /* Set up forwarding counts for block   */
1673                                 /* h of size sz.                        */
1674                                 /* Return FALSE on failure.             */
1675 void GC_remove_header GC_PROTO((struct hblk * h));
1676                                 /* Remove the header for block h.       */
1677 void GC_remove_counts GC_PROTO((struct hblk * h, word sz));
1678                                 /* Remove forwarding counts for h.      */
1679 hdr * GC_find_header GC_PROTO((ptr_t h)); /* Debugging only.            */
1680   
1681 void GC_finalize GC_PROTO((void));
1682                         /* Perform all indicated finalization actions   */
1683                         /* on unmarked objects.                         */
1684                         /* Unreachable finalizable objects are enqueued */
1685                         /* for processing by GC_invoke_finalizers.      */
1686                         /* Invoked with lock.                           */
1687
1688 void GC_notify_or_invoke_finalizers GC_PROTO((void));
1689                         /* If GC_finalize_on_demand is not set, invoke  */
1690                         /* eligible finalizers. Otherwise:              */
1691                         /* Call *GC_finalizer_notifier if there are     */
1692                         /* finalizers to be run, and we haven't called  */
1693                         /* this procedure yet this GC cycle.            */
1694
1695 GC_API GC_PTR GC_make_closure GC_PROTO((GC_finalization_proc fn, GC_PTR data));
1696 GC_API void GC_debug_invoke_finalizer GC_PROTO((GC_PTR obj, GC_PTR data));
1697                         /* Auxiliary fns to make finalization work      */
1698                         /* correctly with displaced pointers introduced */
1699                         /* by the debugging allocators.                 */
1700                         
1701 void GC_add_to_heap GC_PROTO((struct hblk *p, word bytes));
1702                         /* Add a HBLKSIZE aligned chunk to the heap.    */
1703   
1704 void GC_print_obj GC_PROTO((ptr_t p));
1705                         /* P points to somewhere inside an object with  */
1706                         /* debugging info.  Print a human readable      */
1707                         /* description of the object to stderr.         */
1708 extern void (*GC_check_heap) GC_PROTO((void));
1709                         /* Check that all objects in the heap with      */
1710                         /* debugging info are intact.                   */
1711                         /* Add any that are not to GC_smashed list.     */
1712 extern void (*GC_print_all_smashed) GC_PROTO((void));
1713                         /* Print GC_smashed if it's not empty.          */
1714                         /* Clear GC_smashed list.                       */
1715 extern void GC_print_all_errors GC_PROTO((void));
1716                         /* Print smashed and leaked objects, if any.    */
1717                         /* Clear the lists of such objects.             */
1718 extern void (*GC_print_heap_obj) GC_PROTO((ptr_t p));
1719                         /* If possible print s followed by a more       */
1720                         /* detailed description of the object           */
1721                         /* referred to by p.                            */
1722 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
1723   void GC_print_address_map GC_PROTO((void));
1724                         /* Print an address map of the process.         */
1725 #endif
1726
1727 extern GC_bool GC_have_errors;  /* We saw a smashed or leaked object.   */
1728                                 /* Call error printing routine          */
1729                                 /* occasionally.                        */
1730 extern GC_bool GC_print_stats;  /* Produce at least some logging output */
1731                                 /* Set from environment variable.       */
1732
1733 #ifndef NO_DEBUGGING
1734   extern GC_bool GC_dump_regularly;  /* Generate regular debugging dumps. */
1735 # define COND_DUMP if (GC_dump_regularly) GC_dump();
1736 #else
1737 # define COND_DUMP
1738 #endif
1739
1740 #ifdef KEEP_BACK_PTRS
1741   extern long GC_backtraces;
1742   void GC_generate_random_backtrace_no_gc(void);
1743 #endif
1744
1745 extern GC_bool GC_print_back_height;
1746
1747 #ifdef MAKE_BACK_GRAPH
1748   void GC_print_back_graph_stats(void);
1749 #endif
1750
1751 /* Macros used for collector internal allocation.       */
1752 /* These assume the collector lock is held.             */
1753 #ifdef DBG_HDRS_ALL
1754     extern GC_PTR GC_debug_generic_malloc_inner(size_t lb, int k);
1755     extern GC_PTR GC_debug_generic_malloc_inner_ignore_off_page(size_t lb,
1756                                                                 int k);
1757 #   define GC_INTERNAL_MALLOC GC_debug_generic_malloc_inner
1758 #   define GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE \
1759                  GC_debug_generic_malloc_inner_ignore_off_page
1760 #   ifdef THREADS
1761 #       define GC_INTERNAL_FREE GC_debug_free_inner
1762 #   else
1763 #       define GC_INTERNAL_FREE GC_debug_free
1764 #   endif
1765 #else
1766 #   define GC_INTERNAL_MALLOC GC_generic_malloc_inner
1767 #   define GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE \
1768                  GC_generic_malloc_inner_ignore_off_page
1769 #   ifdef THREADS
1770 #       define GC_INTERNAL_FREE GC_free_inner
1771 #   else
1772 #       define GC_INTERNAL_FREE GC_free
1773 #   endif
1774 #endif
1775
1776 /* Memory unmapping: */
1777 #ifdef USE_MUNMAP
1778   void GC_unmap_old(void);
1779   void GC_merge_unmapped(void);
1780   void GC_unmap(ptr_t start, word bytes);
1781   void GC_remap(ptr_t start, word bytes);
1782   void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2);
1783 #endif
1784
1785 /* Virtual dirty bit implementation:            */
1786 /* Each implementation exports the following:   */
1787 void GC_read_dirty GC_PROTO((void));
1788                         /* Retrieve dirty bits. */
1789 GC_bool GC_page_was_dirty GC_PROTO((struct hblk *h));
1790                         /* Read retrieved dirty bits.   */
1791 GC_bool GC_page_was_ever_dirty GC_PROTO((struct hblk *h));
1792                         /* Could the page contain valid heap pointers?  */
1793 void GC_is_fresh GC_PROTO((struct hblk *h, word n));
1794                         /* Assert the region currently contains no      */
1795                         /* valid pointers.                              */
1796 void GC_remove_protection GC_PROTO((struct hblk *h, word nblocks,
1797                                     GC_bool pointerfree));
1798                         /* h is about to be writteni or allocated.  Ensure  */
1799                         /* that it's not write protected by the virtual     */
1800                         /* dirty bit implementation.                        */
1801                         
1802 void GC_dirty_init GC_PROTO((void));
1803   
1804 /* Slow/general mark bit manipulation: */
1805 GC_API GC_bool GC_is_marked GC_PROTO((ptr_t p));
1806 void GC_clear_mark_bit GC_PROTO((ptr_t p));
1807 void GC_set_mark_bit GC_PROTO((ptr_t p));
1808   
1809 /* Stubborn objects: */
1810 void GC_read_changed GC_PROTO((void));  /* Analogous to GC_read_dirty */
1811 GC_bool GC_page_was_changed GC_PROTO((struct hblk * h));
1812                                 /* Analogous to GC_page_was_dirty */
1813 void GC_clean_changing_list GC_PROTO((void));
1814                                 /* Collect obsolete changing list entries */
1815 void GC_stubborn_init GC_PROTO((void));
1816   
1817 /* Debugging print routines: */
1818 void GC_print_block_list GC_PROTO((void));
1819 void GC_print_hblkfreelist GC_PROTO((void));
1820 void GC_print_heap_sects GC_PROTO((void));
1821 void GC_print_static_roots GC_PROTO((void));
1822 void GC_print_finalization_stats GC_PROTO((void));
1823 void GC_dump GC_PROTO((void));
1824
1825 #ifdef KEEP_BACK_PTRS
1826    void GC_store_back_pointer(ptr_t source, ptr_t dest);
1827    void GC_marked_for_finalization(ptr_t dest);
1828 #  define GC_STORE_BACK_PTR(source, dest) GC_store_back_pointer(source, dest)
1829 #  define GC_MARKED_FOR_FINALIZATION(dest) GC_marked_for_finalization(dest)
1830 #else
1831 #  define GC_STORE_BACK_PTR(source, dest) 
1832 #  define GC_MARKED_FOR_FINALIZATION(dest)
1833 #endif
1834
1835 /* Make arguments appear live to compiler */
1836 # ifdef __WATCOMC__
1837     void GC_noop(void*, ...);
1838 # else
1839 #   ifdef __DMC__
1840       GC_API void GC_noop(...);
1841 #   else
1842       GC_API void GC_noop();
1843 #   endif
1844 # endif
1845
1846 void GC_noop1 GC_PROTO((word));
1847
1848 /* Logging and diagnostic output:       */
1849 GC_API void GC_printf GC_PROTO((GC_CONST char * format, long, long, long, long, long, long));
1850                         /* A version of printf that doesn't allocate,   */
1851                         /* is restricted to long arguments, and         */
1852                         /* (unfortunately) doesn't use varargs for      */
1853                         /* portability.  Restricted to 6 args and       */
1854                         /* 1K total output length.                      */
1855                         /* (We use sprintf.  Hopefully that doesn't     */
1856                         /* allocate for long arguments.)                */
1857 # define GC_printf0(f) GC_printf(f, 0l, 0l, 0l, 0l, 0l, 0l)
1858 # define GC_printf1(f,a) GC_printf(f, (long)a, 0l, 0l, 0l, 0l, 0l)
1859 # define GC_printf2(f,a,b) GC_printf(f, (long)a, (long)b, 0l, 0l, 0l, 0l)
1860 # define GC_printf3(f,a,b,c) GC_printf(f, (long)a, (long)b, (long)c, 0l, 0l, 0l)
1861 # define GC_printf4(f,a,b,c,d) GC_printf(f, (long)a, (long)b, (long)c, \
1862                                             (long)d, 0l, 0l)
1863 # define GC_printf5(f,a,b,c,d,e) GC_printf(f, (long)a, (long)b, (long)c, \
1864                                               (long)d, (long)e, 0l)
1865 # define GC_printf6(f,a,b,c,d,e,g) GC_printf(f, (long)a, (long)b, (long)c, \
1866                                                 (long)d, (long)e, (long)g)
1867
1868 GC_API void GC_err_printf GC_PROTO((GC_CONST char * format, long, long, long, long, long, long));
1869 # define GC_err_printf0(f) GC_err_puts(f)
1870 # define GC_err_printf1(f,a) GC_err_printf(f, (long)a, 0l, 0l, 0l, 0l, 0l)
1871 # define GC_err_printf2(f,a,b) GC_err_printf(f, (long)a, (long)b, 0l, 0l, 0l, 0l)
1872 # define GC_err_printf3(f,a,b,c) GC_err_printf(f, (long)a, (long)b, (long)c, \
1873                                                   0l, 0l, 0l)
1874 # define GC_err_printf4(f,a,b,c,d) GC_err_printf(f, (long)a, (long)b, \
1875                                                     (long)c, (long)d, 0l, 0l)
1876 # define GC_err_printf5(f,a,b,c,d,e) GC_err_printf(f, (long)a, (long)b, \
1877                                                       (long)c, (long)d, \
1878                                                       (long)e, 0l)
1879 # define GC_err_printf6(f,a,b,c,d,e,g) GC_err_printf(f, (long)a, (long)b, \
1880                                                         (long)c, (long)d, \
1881                                                         (long)e, (long)g)
1882                         /* Ditto, writes to stderr.                     */
1883                         
1884 void GC_err_puts GC_PROTO((GC_CONST char *s));
1885                         /* Write s to stderr, don't buffer, don't add   */
1886                         /* newlines, don't ...                          */
1887
1888 #if defined(LINUX) && !defined(SMALL_CONFIG)
1889   void GC_err_write GC_PROTO((GC_CONST char *buf, size_t len));
1890                         /* Write buf to stderr, don't buffer, don't add */
1891                         /* newlines, don't ...                          */
1892 #endif
1893
1894
1895 # ifdef GC_ASSERTIONS
1896 #       define GC_ASSERT(expr) if(!(expr)) {\
1897                 GC_err_printf2("Assertion failure: %s:%ld\n", \
1898                                 __FILE__, (unsigned long)__LINE__); \
1899                 ABORT("assertion failure"); }
1900 # else 
1901 #       define GC_ASSERT(expr)
1902 # endif
1903
1904 /* Check a compile time assertion at compile time.  The error   */
1905 /* message for failure is a bit baroque, but ...                */
1906 #if defined(mips) && !defined(__GNUC__)
1907 /* DOB: MIPSPro C gets an internal error taking the sizeof an array type. 
1908    This code works correctly (ugliness is to avoid "unused var" warnings) */
1909 # define GC_STATIC_ASSERT(expr) do { if (0) { char j[(expr)? 1 : -1]; j[0]='\0'; j[0]=j[0]; } } while(0)
1910 #else
1911 # define GC_STATIC_ASSERT(expr) sizeof(char[(expr)? 1 : -1])
1912 #endif
1913
1914 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
1915     /* We need additional synchronization facilities from the thread    */
1916     /* support.  We believe these are less performance critical         */
1917     /* than the main garbage collector lock; standard pthreads-based    */
1918     /* implementations should be sufficient.                            */
1919
1920     /* The mark lock and condition variable.  If the GC lock is also    */
1921     /* acquired, the GC lock must be acquired first.  The mark lock is  */
1922     /* used to both protect some variables used by the parallel         */
1923     /* marker, and to protect GC_fl_builder_count, below.               */
1924     /* GC_notify_all_marker() is called when                            */ 
1925     /* the state of the parallel marker changes                         */
1926     /* in some significant way (see gc_mark.h for details).  The        */
1927     /* latter set of events includes incrementing GC_mark_no.           */
1928     /* GC_notify_all_builder() is called when GC_fl_builder_count       */
1929     /* reaches 0.                                                       */
1930
1931      extern void GC_acquire_mark_lock();
1932      extern void GC_release_mark_lock();
1933      extern void GC_notify_all_builder();
1934      /* extern void GC_wait_builder(); */
1935      extern void GC_wait_for_reclaim();
1936
1937      extern word GC_fl_builder_count;   /* Protected by mark lock.      */
1938 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
1939 # ifdef PARALLEL_MARK
1940      extern void GC_notify_all_marker();
1941      extern void GC_wait_marker();
1942      extern word GC_mark_no;            /* Protected by mark lock.      */
1943
1944      extern void GC_help_marker(word my_mark_no);
1945                 /* Try to help out parallel marker for mark cycle       */
1946                 /* my_mark_no.  Returns if the mark cycle finishes or   */
1947                 /* was already done, or there was nothing to do for     */
1948                 /* some other reason.                                   */
1949 # endif /* PARALLEL_MARK */
1950
1951 # if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS)
1952   /* We define the thread suspension signal here, so that we can refer  */
1953   /* to it in the dirty bit implementation, if necessary.  Ideally we   */
1954   /* would allocate a (real-time ?) signal using the standard mechanism.*/
1955   /* unfortunately, there is no standard mechanism.  (There is one      */
1956   /* in Linux glibc, but it's not exported.)  Thus we continue to use   */
1957   /* the same hard-coded signals we've always used.                     */
1958 #  if !defined(SIG_SUSPEND)
1959 #   if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS) || defined(GC_NETBSD_THREADS)
1960 #    if defined(SPARC) && !defined(SIGPWR)
1961        /* SPARC/Linux doesn't properly define SIGPWR in <signal.h>.
1962         * It is aliased to SIGLOST in asm/signal.h, though.             */
1963 #      define SIG_SUSPEND SIGLOST
1964 #    else
1965        /* Linuxthreads itself uses SIGUSR1 and SIGUSR2.                 */
1966 #      define SIG_SUSPEND SIGPWR
1967 #    endif
1968 #   else  /* !GC_LINUX_THREADS */
1969 #     if defined(_SIGRTMIN)
1970 #       define SIG_SUSPEND _SIGRTMIN + 6
1971 #     else
1972 #       define SIG_SUSPEND SIGRTMIN + 6
1973 #     endif       
1974 #   endif
1975 #  endif /* !SIG_SUSPEND */
1976   
1977 # endif
1978
1979 # endif /* GC_PRIVATE_H */