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