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