TIVI-153: Add as dependency for Iputils
[profile/ivi/gc.git] / alloc.c
1 /*
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1996 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1998 by Silicon Graphics.  All rights reserved.
5  * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
6  *
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
10  * Permission is hereby granted to use or copy this program
11  * for any purpose,  provided the above notices are retained on all copies.
12  * Permission to modify the code and to distribute modified code is granted,
13  * provided the above notices are retained, and a notice that the code was
14  * modified is included with the above copyright notice.
15  *
16  */
17
18
19 # include "private/gc_priv.h"
20
21 # include <stdio.h>
22 # if !defined(MACOS) && !defined(MSWINCE)
23 #   include <signal.h>
24 #   include <sys/types.h>
25 # endif
26
27 /*
28  * Separate free lists are maintained for different sized objects
29  * up to MAXOBJBYTES.
30  * The call GC_allocobj(i,k) ensures that the freelist for
31  * kind k objects of size i points to a non-empty
32  * free list. It returns a pointer to the first entry on the free list.
33  * In a single-threaded world, GC_allocobj may be called to allocate
34  * an object of (small) size i as follows:
35  *
36  *            opp = &(GC_objfreelist[i]);
37  *            if (*opp == 0) GC_allocobj(i, NORMAL);
38  *            ptr = *opp;
39  *            *opp = obj_link(ptr);
40  *
41  * Note that this is very fast if the free list is non-empty; it should
42  * only involve the execution of 4 or 5 simple instructions.
43  * All composite objects on freelists are cleared, except for
44  * their first word.
45  */
46
47 /*
48  *  The allocator uses GC_allochblk to allocate large chunks of objects.
49  * These chunks all start on addresses which are multiples of
50  * HBLKSZ.   Each allocated chunk has an associated header,
51  * which can be located quickly based on the address of the chunk.
52  * (See headers.c for details.) 
53  * This makes it possible to check quickly whether an
54  * arbitrary address corresponds to an object administered by the
55  * allocator.
56  */
57
58 word GC_non_gc_bytes = 0;  /* Number of bytes not intended to be collected */
59
60 word GC_gc_no = 0;
61
62 #ifndef SMALL_CONFIG
63   int GC_incremental = 0;  /* By default, stop the world.       */
64 #endif
65
66 int GC_parallel = FALSE;   /* By default, parallel GC is off.   */
67
68 int GC_full_freq = 19;     /* Every 20th collection is a full   */
69                            /* collection, whether we need it    */
70                            /* or not.                           */
71
72 GC_bool GC_need_full_gc = FALSE;
73                            /* Need full GC do to heap growth.   */
74
75 #ifdef THREADS
76   GC_bool GC_world_stopped = FALSE;
77 # define IF_THREADS(x) x
78 #else
79 # define IF_THREADS(x)
80 #endif
81
82 word GC_used_heap_size_after_full = 0;
83
84 char * GC_copyright[] =
85 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
86 "Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved. ",
87 "Copyright (c) 1996-1998 by Silicon Graphics.  All rights reserved. ",
88 "Copyright (c) 1999-2001 by Hewlett-Packard Company.  All rights reserved. ",
89 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
90 " EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.",
91 "See source code for details." };
92
93 /* Version macros are now defined in gc_version.h, which is included by */
94 /* gc.h, which is included by gc_priv.h".                               */
95
96 #ifndef GC_NO_VERSION_VAR
97
98 unsigned GC_version = ((GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) | GC_TMP_ALPHA_VERSION);
99
100 #endif /* GC_NO_VERSION_VAR */
101
102 /* some more variables */
103
104 extern signed_word GC_bytes_found; /* Number of reclaimed bytes         */
105                                   /* after garbage collection           */
106
107 GC_bool GC_dont_expand = 0;
108
109 word GC_free_space_divisor = 3;
110
111 extern GC_bool GC_collection_in_progress();
112                 /* Collection is in progress, or was abandoned. */
113
114 int GC_never_stop_func (void) { return(0); }
115
116 unsigned long GC_time_limit = TIME_LIMIT;
117
118 CLOCK_TYPE GC_start_time;       /* Time at which we stopped world.      */
119                                 /* used only in GC_timeout_stop_func.   */
120
121 int GC_n_attempts = 0;          /* Number of attempts at finishing      */
122                                 /* collection within GC_time_limit.     */
123
124 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
125 #   define GC_timeout_stop_func GC_never_stop_func
126 #else
127   int GC_timeout_stop_func (void)
128   {
129     CLOCK_TYPE current_time;
130     static unsigned count = 0;
131     unsigned long time_diff;
132     
133     if ((count++ & 3) != 0) return(0);
134     GET_TIME(current_time);
135     time_diff = MS_TIME_DIFF(current_time,GC_start_time);
136     if (time_diff >= GC_time_limit) {
137         if (GC_print_stats) {
138             GC_log_printf("Abandoning stopped marking after ");
139             GC_log_printf("%lu msecs", time_diff);
140             GC_log_printf("(attempt %d)\n", GC_n_attempts);
141         }
142         return(1);
143     }
144     return(0);
145   }
146 #endif /* !SMALL_CONFIG */
147
148 /* Return the minimum number of words that must be allocated between    */
149 /* collections to amortize the collection cost.                         */
150 static word min_bytes_allocd()
151 {
152 #   ifdef THREADS
153         /* We punt, for now. */
154         signed_word stack_size = 10000;
155 #   else
156         int dummy;
157         signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
158 #   endif
159     word total_root_size;           /* includes double stack size,      */
160                                     /* since the stack is expensive     */
161                                     /* to scan.                         */
162     word scan_size;             /* Estimate of memory to be scanned     */
163                                 /* during normal GC.                    */
164     
165     if (stack_size < 0) stack_size = -stack_size;
166     total_root_size = 2 * stack_size + GC_root_size;
167     scan_size = 2 * GC_composite_in_use + GC_atomic_in_use/4
168                 + total_root_size;
169     if (TRUE_INCREMENTAL) {
170         return scan_size / (2 * GC_free_space_divisor);
171     } else {
172         return scan_size / GC_free_space_divisor;
173     }
174 }
175
176 /* Return the number of bytes allocated, adjusted for explicit storage  */
177 /* management, etc..  This number is used in deciding when to trigger   */
178 /* collections.                                                         */
179 word GC_adj_bytes_allocd(void)
180 {
181     signed_word result;
182     signed_word expl_managed =
183                 (signed_word)GC_non_gc_bytes
184                 - (signed_word)GC_non_gc_bytes_at_gc;
185     
186     /* Don't count what was explicitly freed, or newly allocated for    */
187     /* explicit management.  Note that deallocating an explicitly       */
188     /* managed object should not alter result, assuming the client      */
189     /* is playing by the rules.                                         */
190     result = (signed_word)GC_bytes_allocd
191              + (signed_word)GC_bytes_dropped
192              - (signed_word)GC_bytes_freed 
193              + (signed_word)GC_finalizer_bytes_freed
194              - expl_managed;
195     if (result > (signed_word)GC_bytes_allocd) {
196         result = GC_bytes_allocd;
197         /* probably client bug or unfortunate scheduling */
198     }
199     result += GC_bytes_finalized;
200         /* We count objects enqueued for finalization as though they    */
201         /* had been reallocated this round. Finalization is user        */
202         /* visible progress.  And if we don't count this, we have       */
203         /* stability problems for programs that finalize all objects.   */
204     if (result < (signed_word)(GC_bytes_allocd >> 3)) {
205         /* Always count at least 1/8 of the allocations.  We don't want */
206         /* to collect too infrequently, since that would inhibit        */
207         /* coalescing of free storage blocks.                           */
208         /* This also makes us partially robust against client bugs.     */
209         return(GC_bytes_allocd >> 3);
210     } else {
211         return(result);
212     }
213 }
214
215
216 /* Clear up a few frames worth of garbage left at the top of the stack. */
217 /* This is used to prevent us from accidentally treating garbade left   */
218 /* on the stack by other parts of the collector as roots.  This         */
219 /* differs from the code in misc.c, which actually tries to keep the    */
220 /* stack clear of long-lived, client-generated garbage.                 */
221 void GC_clear_a_few_frames()
222 {
223 #   define NWORDS 64
224     word frames[NWORDS];
225     int i;
226     
227     for (i = 0; i < NWORDS; i++) frames[i] = 0;
228 }
229
230 /* Heap size at which we need a collection to avoid expanding past      */
231 /* limits used by blacklisting.                                         */
232 static word GC_collect_at_heapsize = (word)(-1);
233
234 /* Have we allocated enough to amortize a collection? */
235 GC_bool GC_should_collect(void)
236 {
237     static word last_min_bytes_allocd;
238     static word last_gc_no;
239     if (last_gc_no != GC_gc_no) {
240       last_gc_no = GC_gc_no;
241       last_min_bytes_allocd = min_bytes_allocd();
242     }
243     return(GC_adj_bytes_allocd() >= last_min_bytes_allocd
244            || GC_heapsize >= GC_collect_at_heapsize);
245 }
246
247
248 void GC_notify_full_gc(void)
249 {
250     if (GC_start_call_back != (void (*) (void))0) {
251         (*GC_start_call_back)();
252     }
253 }
254
255 GC_bool GC_is_full_gc = FALSE;
256
257 /* 
258  * Initiate a garbage collection if appropriate.
259  * Choose judiciously
260  * between partial, full, and stop-world collections.
261  */
262 void GC_maybe_gc(void)
263 {
264     static int n_partial_gcs = 0;
265
266     GC_ASSERT(I_HOLD_LOCK());
267     if (GC_should_collect()) {
268         if (!GC_incremental) {
269             GC_gcollect_inner();
270             n_partial_gcs = 0;
271             return;
272         } else {
273 #         ifdef PARALLEL_MARK
274             GC_wait_for_reclaim();
275 #         endif
276           if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
277             if (GC_print_stats) {
278                 GC_log_printf(
279                   "***>Full mark for collection %lu after %ld allocd bytes\n",
280                   (unsigned long)GC_gc_no+1,
281                   (long)GC_bytes_allocd);
282             }
283             GC_promote_black_lists();
284             (void)GC_reclaim_all((GC_stop_func)0, TRUE);
285             GC_clear_marks();
286             n_partial_gcs = 0;
287             GC_notify_full_gc();
288             GC_is_full_gc = TRUE;
289           } else {
290             n_partial_gcs++;
291           }
292         }
293         /* We try to mark with the world stopped.       */
294         /* If we run out of time, this turns into       */
295         /* incremental marking.                 */
296 #       ifndef NO_CLOCK
297           if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
298 #       endif
299         if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED? 
300                             GC_never_stop_func : GC_timeout_stop_func)) {
301 #           ifdef SAVE_CALL_CHAIN
302                 GC_save_callers(GC_last_stack);
303 #           endif
304             GC_finish_collection();
305         } else {
306             if (!GC_is_full_gc) {
307                 /* Count this as the first attempt */
308                 GC_n_attempts++;
309             }
310         }
311     }
312 }
313
314
315 /*
316  * Stop the world garbage collection.  Assumes lock held, signals disabled.
317  * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
318  * Return TRUE if we successfully completed the collection.
319  */
320 GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
321 {
322     CLOCK_TYPE start_time, current_time;
323     if (GC_dont_gc) return FALSE;
324     if (GC_incremental && GC_collection_in_progress()) {
325       if (GC_print_stats) {
326         GC_log_printf(
327             "GC_try_to_collect_inner: finishing collection in progress\n");
328       }
329       /* Just finish collection already in progress.    */
330         while(GC_collection_in_progress()) {
331             if (stop_func()) return(FALSE);
332             GC_collect_a_little_inner(1);
333         }
334     }
335     if (stop_func == GC_never_stop_func) GC_notify_full_gc();
336     if (GC_print_stats) {
337         GET_TIME(start_time);
338         GC_log_printf(
339            "Initiating full world-stop collection %lu after %ld allocd bytes\n",
340            (unsigned long)GC_gc_no+1, (long)GC_bytes_allocd);
341     }
342     GC_promote_black_lists();
343     /* Make sure all blocks have been reclaimed, so sweep routines      */
344     /* don't see cleared mark bits.                                     */
345     /* If we're guaranteed to finish, then this is unnecessary.         */
346     /* In the find_leak case, we have to finish to guarantee that       */
347     /* previously unmarked objects are not reported as leaks.           */
348 #       ifdef PARALLEL_MARK
349             GC_wait_for_reclaim();
350 #       endif
351         if ((GC_find_leak || stop_func != GC_never_stop_func)
352             && !GC_reclaim_all(stop_func, FALSE)) {
353             /* Aborted.  So far everything is still consistent. */
354             return(FALSE);
355         }
356     GC_invalidate_mark_state();  /* Flush mark stack.   */
357     GC_clear_marks();
358 #   ifdef SAVE_CALL_CHAIN
359         GC_save_callers(GC_last_stack);
360 #   endif
361     GC_is_full_gc = TRUE;
362     if (!GC_stopped_mark(stop_func)) {
363       if (!GC_incremental) {
364         /* We're partially done and have no way to complete or use      */
365         /* current work.  Reestablish invariants as cheaply as          */
366         /* possible.                                                    */
367         GC_invalidate_mark_state();
368         GC_unpromote_black_lists();
369       } /* else we claim the world is already still consistent.  We'll  */
370         /* finish incrementally.                                        */
371       return(FALSE);
372     }
373     GC_finish_collection();
374     if (GC_print_stats) {
375         GET_TIME(current_time);
376         GC_log_printf("Complete collection took %lu msecs\n",
377                   MS_TIME_DIFF(current_time,start_time));
378     }
379     return(TRUE);
380 }
381
382
383
384 /*
385  * Perform n units of garbage collection work.  A unit is intended to touch
386  * roughly GC_RATE pages.  Every once in a while, we do more than that.
387  * This needs to be a fairly large number with our current incremental
388  * GC strategy, since otherwise we allocate too much during GC, and the
389  * cleanup gets expensive.
390  */
391 # define GC_RATE 10 
392 # define MAX_PRIOR_ATTEMPTS 1
393         /* Maximum number of prior attempts at world stop marking       */
394         /* A value of 1 means that we finish the second time, no matter */
395         /* how long it takes.  Doesn't count the initial root scan      */
396         /* for a full GC.                                               */
397
398 int GC_deficit = 0;     /* The number of extra calls to GC_mark_some    */
399                         /* that we have made.                           */
400
401 void GC_collect_a_little_inner(int n)
402 {
403     int i;
404     
405     if (GC_dont_gc) return;
406     if (GC_incremental && GC_collection_in_progress()) {
407         for (i = GC_deficit; i < GC_RATE*n; i++) {
408             if (GC_mark_some((ptr_t)0)) {
409                 /* Need to finish a collection */
410 #               ifdef SAVE_CALL_CHAIN
411                     GC_save_callers(GC_last_stack);
412 #               endif
413 #               ifdef PARALLEL_MARK
414                     GC_wait_for_reclaim();
415 #               endif
416                 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
417                     && GC_time_limit != GC_TIME_UNLIMITED) {
418                   GET_TIME(GC_start_time);
419                   if (!GC_stopped_mark(GC_timeout_stop_func)) {
420                     GC_n_attempts++;
421                     break;
422                   }
423                 } else {
424                   (void)GC_stopped_mark(GC_never_stop_func);
425                 }
426                 GC_finish_collection();
427                 break;
428             }
429         }
430         if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
431         if (GC_deficit < 0) GC_deficit = 0;
432     } else {
433         GC_maybe_gc();
434     }
435 }
436
437 int GC_collect_a_little(void)
438 {
439     int result;
440     DCL_LOCK_STATE;
441
442     LOCK();
443     GC_collect_a_little_inner(1);
444     result = (int)GC_collection_in_progress();
445     UNLOCK();
446     if (!result && GC_debugging_started) GC_print_all_smashed();
447     return(result);
448 }
449
450 # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
451   void GC_add_current_malloc_heap();
452 # endif
453 /*
454  * Assumes lock is held, signals are disabled.
455  * We stop the world.
456  * If stop_func() ever returns TRUE, we may fail and return FALSE.
457  * Increment GC_gc_no if we succeed.
458  */
459 GC_bool GC_stopped_mark(GC_stop_func stop_func)
460 {
461     unsigned i;
462     int dummy;
463     CLOCK_TYPE start_time, current_time;
464         
465     if (GC_print_stats)
466         GET_TIME(start_time);
467
468 #   if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
469         GC_add_current_malloc_heap();
470 #   endif
471 #   if defined(REGISTER_LIBRARIES_EARLY)
472         GC_cond_register_dynamic_libraries();
473 #   endif
474     STOP_WORLD();
475     IF_THREADS(GC_world_stopped = TRUE);
476     if (GC_print_stats) {
477         GC_log_printf("--> Marking for collection %lu ",
478                   (unsigned long)GC_gc_no + 1);
479         GC_log_printf("after %lu allocd bytes\n",
480                    (unsigned long) GC_bytes_allocd);
481     }
482 #   ifdef MAKE_BACK_GRAPH
483       if (GC_print_back_height) {
484         GC_build_back_graph();
485       }
486 #   endif
487
488     /* Mark from all roots.  */
489         /* Minimize junk left in my registers and on the stack */
490             GC_clear_a_few_frames();
491             GC_noop(0,0,0,0,0,0);
492         GC_initiate_gc();
493         for(i = 0;;i++) {
494             if ((*stop_func)()) {
495                     if (GC_print_stats) {
496                         GC_log_printf("Abandoned stopped marking after ");
497                         GC_log_printf("%u iterations\n", i);
498                     }
499                     GC_deficit = i; /* Give the mutator a chance. */
500                     IF_THREADS(GC_world_stopped = FALSE);
501                     START_WORLD();
502                     return(FALSE);
503             }
504             if (GC_mark_some((ptr_t)(&dummy))) break;
505         }
506         
507     GC_gc_no++;
508     if (GC_print_stats) {
509       GC_log_printf("Collection %lu reclaimed %ld bytes",
510                     (unsigned long)GC_gc_no - 1,
511                     (long)GC_bytes_found);
512       GC_log_printf(" ---> heapsize = %lu bytes\n",
513                 (unsigned long) GC_heapsize);
514         /* Printf arguments may be pushed in funny places.  Clear the   */
515         /* space.                                                       */
516       GC_log_printf("");
517     }
518
519     /* Check all debugged objects for consistency */
520         if (GC_debugging_started) {
521             (*GC_check_heap)();
522         }
523     
524     IF_THREADS(GC_world_stopped = FALSE);
525     START_WORLD();
526     if (GC_print_stats) {
527       GET_TIME(current_time);
528       GC_log_printf("World-stopped marking took %lu msecs\n",
529                     MS_TIME_DIFF(current_time,start_time));
530     }
531     return(TRUE);
532 }
533
534 /* Set all mark bits for the free list whose first entry is q   */
535 void GC_set_fl_marks(ptr_t q)
536 {
537    ptr_t p;
538    struct hblk * h, * last_h = 0;
539    hdr *hhdr;  /* gcc "might be uninitialized" warning is bogus. */
540    IF_PER_OBJ(size_t sz;)
541    unsigned bit_no;
542
543    for (p = q; p != 0; p = obj_link(p)){
544         h = HBLKPTR(p);
545         if (h != last_h) {
546           last_h = h; 
547           hhdr = HDR(h);
548           IF_PER_OBJ(sz = hhdr->hb_sz;)
549         }
550         bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
551         if (!mark_bit_from_hdr(hhdr, bit_no)) {
552           set_mark_bit_from_hdr(hhdr, bit_no);
553           ++hhdr -> hb_n_marks;
554         }
555    }
556 }
557
558 #ifdef GC_ASSERTIONS
559 /* Check that all mark bits for the free list whose first entry is q    */
560 /* are set.                                                             */
561 void GC_check_fl_marks(ptr_t q)
562 {
563    ptr_t p;
564
565    for (p = q; p != 0; p = obj_link(p)){
566         if (!GC_is_marked(p)) {
567             GC_err_printf("Unmarked object %p on list %p\n", p, q);
568             ABORT("Unmarked local free list entry.");
569         }
570    }
571 }
572 #endif
573
574 /* Clear all mark bits for the free list whose first entry is q */
575 /* Decrement GC_bytes_found by number of bytes on free list.    */
576 void GC_clear_fl_marks(ptr_t q)
577 {
578    ptr_t p;
579    struct hblk * h, * last_h = 0;
580    hdr *hhdr;
581    size_t sz;
582    unsigned bit_no;
583
584    for (p = q; p != 0; p = obj_link(p)){
585         h = HBLKPTR(p);
586         if (h != last_h) {
587           last_h = h; 
588           hhdr = HDR(h);
589           sz = hhdr->hb_sz;  /* Normally set only once. */
590         }
591         bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
592         if (mark_bit_from_hdr(hhdr, bit_no)) {
593           size_t n_marks = hhdr -> hb_n_marks - 1;
594           clear_mark_bit_from_hdr(hhdr, bit_no);
595 #         ifdef PARALLEL_MARK
596             /* Appr. count, don't decrement to zero! */
597             if (0 != n_marks) {
598               hhdr -> hb_n_marks = n_marks;
599             }
600 #         else
601             hhdr -> hb_n_marks = n_marks;
602 #         endif
603         }
604         GC_bytes_found -= sz;
605    }
606 }
607
608 #if defined(GC_ASSERTIONS) && defined(THREADS) && defined(THREAD_LOCAL_ALLOC)
609 extern void GC_check_tls(void);
610 #endif
611
612 /* Finish up a collection.  Assumes lock is held, signals are disabled, */
613 /* but the world is otherwise running.                                  */
614 void GC_finish_collection()
615 {
616     CLOCK_TYPE start_time;
617     CLOCK_TYPE finalize_time;
618     CLOCK_TYPE done_time;
619         
620 #   if defined(GC_ASSERTIONS) && defined(THREADS) \
621        && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
622         /* Check that we marked some of our own data.           */
623         /* FIXME: Add more checks.                              */
624         GC_check_tls();
625 #   endif
626
627     if (GC_print_stats)
628       GET_TIME(start_time);
629
630     GC_bytes_found = 0;
631 #   if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
632         if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
633           GC_print_address_map();
634         }
635 #   endif
636     COND_DUMP;
637     if (GC_find_leak) {
638       /* Mark all objects on the free list.  All objects should be */
639       /* marked when we're done.                                   */
640         {
641           word size;            /* current object size          */
642           unsigned kind;
643           ptr_t q;
644
645           for (kind = 0; kind < GC_n_kinds; kind++) {
646             for (size = 1; size <= MAXOBJGRANULES; size++) {
647               q = GC_obj_kinds[kind].ok_freelist[size];
648               if (q != 0) GC_set_fl_marks(q);
649             }
650           }
651         }
652         GC_start_reclaim(TRUE);
653           /* The above just checks; it doesn't really reclaim anything. */
654     }
655
656     GC_finalize();
657 #   ifdef STUBBORN_ALLOC
658       GC_clean_changing_list();
659 #   endif
660
661     if (GC_print_stats)
662       GET_TIME(finalize_time);
663
664     if (GC_print_back_height) {
665 #     ifdef MAKE_BACK_GRAPH
666         GC_traverse_back_graph();
667 #     else
668 #       ifndef SMALL_CONFIG
669           GC_err_printf("Back height not available: "
670                         "Rebuild collector with -DMAKE_BACK_GRAPH\n");
671 #       endif
672 #     endif
673     }
674
675     /* Clear free list mark bits, in case they got accidentally marked   */
676     /* (or GC_find_leak is set and they were intentionally marked).      */
677     /* Also subtract memory remaining from GC_bytes_found count.         */
678     /* Note that composite objects on free list are cleared.             */
679     /* Thus accidentally marking a free list is not a problem;  only     */
680     /* objects on the list itself will be marked, and that's fixed here. */
681       {
682         word size;              /* current object size          */
683         ptr_t q;        /* pointer to current object    */
684         unsigned kind;
685
686         for (kind = 0; kind < GC_n_kinds; kind++) {
687           for (size = 1; size <= MAXOBJGRANULES; size++) {
688             q = GC_obj_kinds[kind].ok_freelist[size];
689             if (q != 0) GC_clear_fl_marks(q);
690           }
691         }
692       }
693
694
695     if (GC_print_stats == VERBOSE)
696         GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n",
697                   (long)GC_bytes_found);
698     
699     /* Reconstruct free lists to contain everything not marked */
700         GC_start_reclaim(FALSE);
701         if (GC_print_stats) {
702           GC_log_printf("Heap contains %lu pointer-containing "
703                         "+ %lu pointer-free reachable bytes\n",
704                         (unsigned long)GC_composite_in_use,
705                         (unsigned long)GC_atomic_in_use);
706         }
707         if (GC_is_full_gc)  {
708             GC_used_heap_size_after_full = USED_HEAP_SIZE;
709             GC_need_full_gc = FALSE;
710         } else {
711             GC_need_full_gc =
712                  USED_HEAP_SIZE - GC_used_heap_size_after_full
713                  > min_bytes_allocd();
714         }
715
716     if (GC_print_stats == VERBOSE) {
717         GC_log_printf(
718                   "Immediately reclaimed %ld bytes in heap of size %lu bytes",
719                   (long)GC_bytes_found,
720                   (unsigned long)GC_heapsize);
721 #       ifdef USE_MUNMAP
722           GC_log_printf("(%lu unmapped)", (unsigned long)GC_unmapped_bytes);
723 #       endif
724         GC_log_printf("\n");
725     }
726
727     /* Reset or increment counters for next cycle */
728       GC_n_attempts = 0;
729       GC_is_full_gc = FALSE;
730       GC_bytes_allocd_before_gc += GC_bytes_allocd;
731       GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
732       GC_bytes_allocd = 0;
733       GC_bytes_dropped = 0;
734       GC_bytes_freed = 0;
735       GC_finalizer_bytes_freed = 0;
736       
737 #   ifdef USE_MUNMAP
738       GC_unmap_old();
739 #   endif
740     if (GC_print_stats) {
741         GET_TIME(done_time);
742         GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n",
743                       MS_TIME_DIFF(finalize_time,start_time),
744                       MS_TIME_DIFF(done_time,finalize_time));
745     }
746 }
747
748 /* Externally callable routine to invoke full, stop-world collection */
749 int GC_try_to_collect(GC_stop_func stop_func)
750 {
751     int result;
752     DCL_LOCK_STATE;
753     
754     if (!GC_is_initialized) GC_init();
755     if (GC_debugging_started) GC_print_all_smashed();
756     GC_INVOKE_FINALIZERS();
757     LOCK();
758     ENTER_GC();
759     if (!GC_is_initialized) GC_init_inner();
760     /* Minimize junk left in my registers */
761       GC_noop(0,0,0,0,0,0);
762     result = (int)GC_try_to_collect_inner(stop_func);
763     EXIT_GC();
764     UNLOCK();
765     if(result) {
766         if (GC_debugging_started) GC_print_all_smashed();
767         GC_INVOKE_FINALIZERS();
768     }
769     return(result);
770 }
771
772 void GC_gcollect(void)
773 {
774     (void)GC_try_to_collect(GC_never_stop_func);
775     if (GC_have_errors) GC_print_all_errors();
776 }
777
778 word GC_n_heap_sects = 0;       /* Number of sections currently in heap. */
779
780 #ifdef USE_PROC_FOR_LIBRARIES
781   word GC_n_memory = 0;         /* Number of GET_MEM allocated memory   */
782                                 /* sections.                            */
783 #endif
784
785 #ifdef USE_PROC_FOR_LIBRARIES
786   /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
787   /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set.       */
788   void GC_add_to_our_memory(ptr_t p, size_t bytes)
789   {
790     if (0 == p) return;
791     GC_our_memory[GC_n_memory].hs_start = p;
792     GC_our_memory[GC_n_memory].hs_bytes = bytes;
793     GC_n_memory++;
794   }
795 #endif
796 /*
797  * Use the chunk of memory starting at p of size bytes as part of the heap.
798  * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
799  */
800 void GC_add_to_heap(struct hblk *p, size_t bytes)
801 {
802     hdr * phdr;
803     word endp;
804     
805     if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
806         ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
807     }
808     while ((word)p <= HBLKSIZE) {
809         /* Can't handle memory near address zero. */
810         ++p;
811         bytes -= HBLKSIZE;
812         if (0 == bytes) return;
813     }
814     endp = (word)p + bytes;
815     if (endp <= (word)p) {
816         /* Address wrapped. */
817         bytes -= HBLKSIZE;
818         if (0 == bytes) return;
819         endp -= HBLKSIZE;
820     }
821     phdr = GC_install_header(p);
822     if (0 == phdr) {
823         /* This is extremely unlikely. Can't add it.  This will         */
824         /* almost certainly result in a 0 return from the allocator,    */
825         /* which is entirely appropriate.                               */
826         return;
827     }
828     GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
829     GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
830     GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
831     GC_n_heap_sects++;
832     phdr -> hb_sz = bytes;
833     phdr -> hb_flags = 0;
834     GC_freehblk(p);
835     GC_heapsize += bytes;
836     if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
837         || GC_least_plausible_heap_addr == 0) {
838         GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
839                 /* Making it a little smaller than necessary prevents   */
840                 /* us from getting a false hit from the variable        */
841                 /* itself.  There's some unintentional reflection       */
842                 /* here.                                                */
843     }
844     if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
845         GC_greatest_plausible_heap_addr = (void *)endp;
846     }
847 }
848
849 # if !defined(NO_DEBUGGING)
850 void GC_print_heap_sects(void)
851 {
852     unsigned i;
853     
854     GC_printf("Total heap size: %lu\n", (unsigned long) GC_heapsize);
855     for (i = 0; i < GC_n_heap_sects; i++) {
856         ptr_t start = GC_heap_sects[i].hs_start;
857         size_t len = GC_heap_sects[i].hs_bytes;
858         struct hblk *h;
859         unsigned nbl = 0;
860         
861         GC_printf("Section %d from %p to %p ", i,
862                    start, start + len);
863         for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
864             if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
865         }
866         GC_printf("%lu/%lu blacklisted\n", (unsigned long)nbl,
867                    (unsigned long)(len/HBLKSIZE));
868     }
869 }
870 # endif
871
872 void * GC_least_plausible_heap_addr = (void *)ONES;
873 void * GC_greatest_plausible_heap_addr = 0;
874
875 static INLINE word GC_max(word x, word y)
876 {
877     return(x > y? x : y);
878 }
879
880 static INLINE word GC_min(word x, word y)
881 {
882     return(x < y? x : y);
883 }
884
885 void GC_set_max_heap_size(GC_word n)
886 {
887     GC_max_heapsize = n;
888 }
889
890 GC_word GC_max_retries = 0;
891
892 /*
893  * this explicitly increases the size of the heap.  It is used
894  * internally, but may also be invoked from GC_expand_hp by the user.
895  * The argument is in units of HBLKSIZE.
896  * Tiny values of n are rounded up.
897  * Returns FALSE on failure.
898  */
899 GC_bool GC_expand_hp_inner(word n)
900 {
901     word bytes;
902     struct hblk * space;
903     word expansion_slop;        /* Number of bytes by which we expect the */
904                                 /* heap to expand soon.                   */
905
906     if (n < MINHINCR) n = MINHINCR;
907     bytes = n * HBLKSIZE;
908     /* Make sure bytes is a multiple of GC_page_size */
909       {
910         word mask = GC_page_size - 1;
911         bytes += mask;
912         bytes &= ~mask;
913       }
914     
915     if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
916         /* Exceeded self-imposed limit */
917         return(FALSE);
918     }
919     space = GET_MEM(bytes);
920     GC_add_to_our_memory((ptr_t)space, bytes);
921     if( space == 0 ) {
922         if (GC_print_stats) {
923             GC_log_printf("Failed to expand heap by %ld bytes\n",
924                           (unsigned long)bytes);
925         }
926         return(FALSE);
927     }
928     if (GC_print_stats) {
929         GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n",
930                       (unsigned long)bytes,
931                       (unsigned long)GC_bytes_allocd);
932     }
933     /* Adjust heap limits generously for blacklisting to work better.   */
934     /* GC_add_to_heap performs minimal adjustment need for correctness. */
935     expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
936     if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
937         || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
938         /* Assume the heap is growing up */
939         word new_limit = (word)space + bytes + expansion_slop;
940         if (new_limit > (word)space) {
941           GC_greatest_plausible_heap_addr =
942             (void *)GC_max((word)GC_greatest_plausible_heap_addr,
943                            (word)new_limit);
944         }
945     } else {
946         /* Heap is growing down */
947         word new_limit = (word)space - expansion_slop;
948         if (new_limit < (word)space) {
949           GC_least_plausible_heap_addr =
950             (void *)GC_min((word)GC_least_plausible_heap_addr,
951                            (word)space - expansion_slop);
952         }
953     }
954     GC_prev_heap_addr = GC_last_heap_addr;
955     GC_last_heap_addr = (ptr_t)space;
956     GC_add_to_heap(space, bytes);
957     /* Force GC before we are likely to allocate past expansion_slop */
958       GC_collect_at_heapsize =
959          GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
960 #     if defined(LARGE_CONFIG)
961         if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
962          GC_collect_at_heapsize = (word)(-1);
963 #     endif
964     return(TRUE);
965 }
966
967 /* Really returns a bool, but it's externally visible, so that's clumsy. */
968 /* Arguments is in bytes.                                               */
969 int GC_expand_hp(size_t bytes)
970 {
971     int result;
972     DCL_LOCK_STATE;
973     
974     LOCK();
975     if (!GC_is_initialized) GC_init_inner();
976     result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
977     if (result) GC_requested_heapsize += bytes;
978     UNLOCK();
979     return(result);
980 }
981
982 unsigned GC_fail_count = 0;  
983                         /* How many consecutive GC/expansion failures?  */
984                         /* Reset by GC_allochblk.                       */
985
986 GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page)
987 {
988     if (!GC_incremental && !GC_dont_gc &&
989         ((GC_dont_expand && GC_bytes_allocd > 0) || GC_should_collect())) {
990       GC_gcollect_inner();
991     } else {
992       word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
993                            + needed_blocks;
994       
995       if (blocks_to_get > MAXHINCR) {
996           word slop;
997           
998           /* Get the minimum required to make it likely that we         */
999           /* can satisfy the current request in the presence of black-  */
1000           /* listing.  This will probably be more than MAXHINCR.        */
1001           if (ignore_off_page) {
1002               slop = 4;
1003           } else {
1004               slop = 2*divHBLKSZ(BL_LIMIT);
1005               if (slop > needed_blocks) slop = needed_blocks;
1006           }
1007           if (needed_blocks + slop > MAXHINCR) {
1008               blocks_to_get = needed_blocks + slop;
1009           } else {
1010               blocks_to_get = MAXHINCR;
1011           }
1012       }
1013       if (!GC_expand_hp_inner(blocks_to_get)
1014         && !GC_expand_hp_inner(needed_blocks)) {
1015         if (GC_fail_count++ < GC_max_retries) {
1016             WARN("Out of Memory!  Trying to continue ...\n", 0);
1017             GC_gcollect_inner();
1018         } else {
1019 #           if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1020               WARN("Out of Memory!  Returning NIL!\n", 0);
1021 #           endif
1022             return(FALSE);
1023         }
1024       } else {
1025           if (GC_fail_count && GC_print_stats) {
1026               GC_printf("Memory available again ...\n");
1027           }
1028       }
1029     }
1030     return(TRUE);
1031 }
1032
1033 /*
1034  * Make sure the object free list for size gran (in granules) is not empty.
1035  * Return a pointer to the first object on the free list.
1036  * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1037  * Assumes we hold the allocator lock and signals are disabled.
1038  *
1039  */
1040 ptr_t GC_allocobj(size_t gran, int kind)
1041 {
1042     void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
1043     GC_bool tried_minor = FALSE;
1044     
1045     if (gran == 0) return(0);
1046
1047     while (*flh == 0) {
1048       ENTER_GC();
1049       /* Do our share of marking work */
1050         if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1051       /* Sweep blocks for objects of this size */
1052         GC_continue_reclaim(gran, kind);
1053       EXIT_GC();
1054       if (*flh == 0) {
1055         GC_new_hblk(gran, kind);
1056       }
1057       if (*flh == 0) {
1058         ENTER_GC();
1059         if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1060             && ! tried_minor ) {
1061             GC_collect_a_little_inner(1);
1062             tried_minor = TRUE;
1063         } else {
1064           if (!GC_collect_or_expand((word)1,FALSE)) {
1065             EXIT_GC();
1066             return(0);
1067           }
1068         }
1069         EXIT_GC();
1070       }
1071     }
1072     /* Successful allocation; reset failure count.      */
1073     GC_fail_count = 0;
1074     
1075     return(*flh);
1076 }