Fix unbounded heap growth in case of intensive disappearing links usage
[platform/upstream/libgc.git] / finalize.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) 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright (C) 2007 Free Software Foundation, Inc
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 #include "private/gc_pmark.h"
18
19 #ifndef GC_NO_FINALIZATION
20 # include "javaxfc.h" /* to get GC_finalize_all() as extern "C" */
21
22 /* Type of mark procedure used for marking from finalizable object.     */
23 /* This procedure normally does not mark the object, only its           */
24 /* descendants.                                                         */
25 typedef void (* finalization_mark_proc)(ptr_t /* finalizable_obj_ptr */);
26
27 #define HASH3(addr,size,log_size) \
28         ((((word)(addr) >> 3) ^ ((word)(addr) >> (3 + (log_size)))) \
29          & ((size) - 1))
30 #define HASH2(addr,log_size) HASH3(addr, (word)1 << (log_size), log_size)
31
32 struct hash_chain_entry {
33     word hidden_key;
34     struct hash_chain_entry * next;
35 };
36
37 struct disappearing_link {
38     struct hash_chain_entry prolog;
39 #   define dl_hidden_link prolog.hidden_key
40                                 /* Field to be cleared.         */
41 #   define dl_next(x) (struct disappearing_link *)((x) -> prolog.next)
42 #   define dl_set_next(x, y) \
43                 (void)((x)->prolog.next = (struct hash_chain_entry *)(y))
44     word dl_hidden_obj;         /* Pointer to object base       */
45 };
46
47 struct dl_hashtbl_s {
48     struct disappearing_link **head;
49     signed_word log_size;
50     word entries;
51 };
52
53 STATIC struct dl_hashtbl_s GC_dl_hashtbl = {
54     /* head */ NULL, /* log_size */ -1, /* entries */ 0 };
55 #ifndef GC_LONG_REFS_NOT_NEEDED
56   STATIC struct dl_hashtbl_s GC_ll_hashtbl = { NULL, -1, 0 };
57 #endif
58
59 struct finalizable_object {
60     struct hash_chain_entry prolog;
61 #   define fo_hidden_base prolog.hidden_key
62                                 /* Pointer to object base.      */
63                                 /* No longer hidden once object */
64                                 /* is on finalize_now queue.    */
65 #   define fo_next(x) (struct finalizable_object *)((x) -> prolog.next)
66 #   define fo_set_next(x,y) ((x)->prolog.next = (struct hash_chain_entry *)(y))
67     GC_finalization_proc fo_fn; /* Finalizer.                   */
68     ptr_t fo_client_data;
69     word fo_object_size;        /* In bytes.                    */
70     finalization_mark_proc fo_mark_proc;        /* Mark-through procedure */
71 };
72
73 static signed_word log_fo_table_size = -1;
74
75 STATIC struct fnlz_roots_s {
76   struct finalizable_object **fo_head;
77   /* List of objects that should be finalized now: */
78   struct finalizable_object *finalize_now;
79 } GC_fnlz_roots = { NULL, NULL };
80
81 #ifdef AO_HAVE_store
82   /* Update finalize_now atomically as GC_should_invoke_finalizers does */
83   /* not acquire the allocation lock.                                   */
84 # define SET_FINALIZE_NOW(fo) \
85             AO_store((volatile AO_t *)&GC_fnlz_roots.finalize_now, (AO_t)(fo))
86 #else
87 # define SET_FINALIZE_NOW(fo) (void)(GC_fnlz_roots.finalize_now = (fo))
88 #endif /* !THREADS */
89
90 GC_API void GC_CALL GC_push_finalizer_structures(void)
91 {
92   GC_ASSERT((word)&GC_dl_hashtbl.head % sizeof(word) == 0);
93   GC_ASSERT((word)&GC_fnlz_roots % sizeof(word) == 0);
94 # ifndef GC_LONG_REFS_NOT_NEEDED
95     GC_ASSERT((word)&GC_ll_hashtbl.head % sizeof(word) == 0);
96     GC_PUSH_ALL_SYM(GC_ll_hashtbl.head);
97 # endif
98   GC_PUSH_ALL_SYM(GC_dl_hashtbl.head);
99   GC_PUSH_ALL_SYM(GC_fnlz_roots);
100 }
101
102 /* Threshold of log_size to initiate full collection before growing     */
103 /* a hash table.                                                        */
104 #ifndef GC_ON_GROW_LOG_SIZE_MIN
105 # define GC_ON_GROW_LOG_SIZE_MIN 12
106 #endif
107
108 /* Double the size of a hash table. *log_size_ptr is the log of its     */
109 /* current size.  May be a no-op.                                       */
110 /* *table is a pointer to an array of hash headers.  If we succeed, we  */
111 /* update both *table and *log_size_ptr.  Lock is held.                 */
112 STATIC void GC_grow_table(struct hash_chain_entry ***table,
113                           signed_word *log_size_ptr, word *entries_ptr)
114 {
115     word i;
116     struct hash_chain_entry *p;
117     signed_word log_old_size = *log_size_ptr;
118     signed_word log_new_size = log_old_size + 1;
119     word old_size = log_old_size == -1 ? 0 : (word)1 << log_old_size;
120     word new_size = (word)1 << log_new_size;
121     /* FIXME: Power of 2 size often gets rounded up to one more page. */
122     struct hash_chain_entry **new_table;
123
124     GC_ASSERT(I_HOLD_LOCK());
125     /* Avoid growing the table in case of at least 25% of entries can   */
126     /* be deleted by enforcing a collection.  Ignored for small tables. */
127     if (log_old_size >= GC_ON_GROW_LOG_SIZE_MIN) {
128       (void)GC_try_to_collect_inner(GC_never_stop_func);
129       /* GC_finalize might decrease entries value.  */
130       if (*entries_ptr < ((word)1 << log_old_size) - (*entries_ptr >> 2))
131         return;
132     }
133
134     new_table = (struct hash_chain_entry **)
135                     GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
136                         (size_t)new_size * sizeof(struct hash_chain_entry *),
137                         NORMAL);
138     if (new_table == 0) {
139         if (*table == 0) {
140             ABORT("Insufficient space for initial table allocation");
141         } else {
142             return;
143         }
144     }
145     for (i = 0; i < old_size; i++) {
146       p = (*table)[i];
147       while (p != 0) {
148         ptr_t real_key = (ptr_t)GC_REVEAL_POINTER(p->hidden_key);
149         struct hash_chain_entry *next = p -> next;
150         size_t new_hash = HASH3(real_key, new_size, log_new_size);
151
152         p -> next = new_table[new_hash];
153         new_table[new_hash] = p;
154         p = next;
155       }
156     }
157     *log_size_ptr = log_new_size;
158     *table = new_table;
159 }
160
161 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
162 {
163     ptr_t base;
164
165     base = (ptr_t)GC_base(link);
166     if (base == 0)
167         ABORT("Bad arg to GC_register_disappearing_link");
168     return(GC_general_register_disappearing_link(link, base));
169 }
170
171 STATIC int GC_register_disappearing_link_inner(
172                         struct dl_hashtbl_s *dl_hashtbl, void **link,
173                         const void *obj, const char *tbl_log_name)
174 {
175     struct disappearing_link *curr_dl;
176     size_t index;
177     struct disappearing_link * new_dl;
178     DCL_LOCK_STATE;
179
180     if (EXPECT(GC_find_leak, FALSE)) return GC_UNIMPLEMENTED;
181     LOCK();
182     GC_ASSERT(obj != NULL && GC_base_C(obj) == obj);
183     if (dl_hashtbl -> log_size == -1
184         || dl_hashtbl -> entries > ((word)1 << dl_hashtbl -> log_size)) {
185         GC_grow_table((struct hash_chain_entry ***)&dl_hashtbl -> head,
186                       &dl_hashtbl -> log_size, &dl_hashtbl -> entries);
187 #       ifdef LINT2
188           if (dl_hashtbl->log_size < 0) ABORT("log_size is negative");
189 #       endif
190         GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
191                            1 << (unsigned)dl_hashtbl -> log_size);
192     }
193     index = HASH2(link, dl_hashtbl -> log_size);
194     for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
195          curr_dl = dl_next(curr_dl)) {
196         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
197             curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
198             UNLOCK();
199             return GC_DUPLICATE;
200         }
201     }
202     new_dl = (struct disappearing_link *)
203         GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
204     if (0 == new_dl) {
205       GC_oom_func oom_fn = GC_oom_fn;
206       UNLOCK();
207       new_dl = (struct disappearing_link *)
208                 (*oom_fn)(sizeof(struct disappearing_link));
209       if (0 == new_dl) {
210         return GC_NO_MEMORY;
211       }
212       /* It's not likely we'll make it here, but ... */
213       LOCK();
214       /* Recalculate index since the table may grow.    */
215       index = HASH2(link, dl_hashtbl -> log_size);
216       /* Check again that our disappearing link not in the table. */
217       for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
218            curr_dl = dl_next(curr_dl)) {
219         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
220           curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
221           UNLOCK();
222 #         ifndef DBG_HDRS_ALL
223             /* Free unused new_dl returned by GC_oom_fn() */
224             GC_free((void *)new_dl);
225 #         endif
226           return GC_DUPLICATE;
227         }
228       }
229     }
230     new_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
231     new_dl -> dl_hidden_link = GC_HIDE_POINTER(link);
232     dl_set_next(new_dl, dl_hashtbl -> head[index]);
233     dl_hashtbl -> head[index] = new_dl;
234     dl_hashtbl -> entries++;
235     UNLOCK();
236     return GC_SUCCESS;
237 }
238
239 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
240                                                          const void * obj)
241 {
242     if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
243         ABORT("Bad arg to GC_general_register_disappearing_link");
244     return GC_register_disappearing_link_inner(&GC_dl_hashtbl, link, obj,
245                                                "dl");
246 }
247
248 #ifdef DBG_HDRS_ALL
249 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
250 #else
251 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
252 #endif
253
254 /* Unregisters given link and returns the link entry to free.   */
255 /* Assume the lock is held.                                     */
256 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
257                                 struct dl_hashtbl_s *dl_hashtbl, void **link)
258 {
259     struct disappearing_link *curr_dl;
260     struct disappearing_link *prev_dl = NULL;
261     size_t index;
262
263     if (dl_hashtbl->log_size == -1)
264         return NULL; /* prevent integer shift by a negative amount */
265
266     index = HASH2(link, dl_hashtbl->log_size);
267     for (curr_dl = dl_hashtbl -> head[index]; curr_dl;
268          curr_dl = dl_next(curr_dl)) {
269         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
270             /* Remove found entry from the table. */
271             if (NULL == prev_dl) {
272                 dl_hashtbl -> head[index] = dl_next(curr_dl);
273             } else {
274                 dl_set_next(prev_dl, dl_next(curr_dl));
275             }
276             dl_hashtbl -> entries--;
277             break;
278         }
279         prev_dl = curr_dl;
280     }
281     return curr_dl;
282 }
283
284 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
285 {
286     struct disappearing_link *curr_dl;
287     DCL_LOCK_STATE;
288
289     if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
290
291     LOCK();
292     curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
293     UNLOCK();
294     if (NULL == curr_dl) return 0;
295     FREE_DL_ENTRY(curr_dl);
296     return 1;
297 }
298
299 /* Toggle-ref support.  */
300 #ifndef GC_TOGGLE_REFS_NOT_NEEDED
301   typedef union {
302     /* Lowest bit is used to distinguish between choices.       */
303     void *strong_ref;
304     GC_hidden_pointer weak_ref;
305   } GCToggleRef;
306
307   STATIC GC_toggleref_func GC_toggleref_callback = 0;
308   STATIC GCToggleRef *GC_toggleref_arr = NULL;
309   STATIC int GC_toggleref_array_size = 0;
310   STATIC int GC_toggleref_array_capacity = 0;
311
312   GC_INNER void GC_process_togglerefs(void)
313   {
314     int i;
315     int new_size = 0;
316
317     GC_ASSERT(I_HOLD_LOCK());
318     for (i = 0; i < GC_toggleref_array_size; ++i) {
319       GCToggleRef r = GC_toggleref_arr[i];
320       void *obj = r.strong_ref;
321
322       if (((word)obj & 1) != 0) {
323         obj = GC_REVEAL_POINTER(r.weak_ref);
324       }
325       if (NULL == obj) {
326         continue;
327       }
328       switch (GC_toggleref_callback(obj)) {
329       case GC_TOGGLE_REF_DROP:
330         break;
331       case GC_TOGGLE_REF_STRONG:
332         GC_toggleref_arr[new_size++].strong_ref = obj;
333         break;
334       case GC_TOGGLE_REF_WEAK:
335         GC_toggleref_arr[new_size++].weak_ref = GC_HIDE_POINTER(obj);
336         break;
337       default:
338         ABORT("Bad toggle-ref status returned by callback");
339       }
340     }
341
342     if (new_size < GC_toggleref_array_size) {
343       BZERO(&GC_toggleref_arr[new_size],
344             (GC_toggleref_array_size - new_size) * sizeof(GCToggleRef));
345       GC_toggleref_array_size = new_size;
346     }
347   }
348
349   STATIC void GC_normal_finalize_mark_proc(ptr_t);
350
351   static void push_and_mark_object(void *p)
352   {
353     GC_normal_finalize_mark_proc((ptr_t)p);
354     while (!GC_mark_stack_empty()) {
355       MARK_FROM_MARK_STACK();
356     }
357     GC_set_mark_bit(p);
358     if (GC_mark_state != MS_NONE) {
359       while (!GC_mark_some(0)) {
360         /* Empty. */
361       }
362     }
363   }
364
365   STATIC void GC_mark_togglerefs(void)
366   {
367     int i;
368     if (NULL == GC_toggleref_arr)
369       return;
370
371     /* TODO: Hide GC_toggleref_arr to avoid its marking from roots. */
372     GC_set_mark_bit(GC_toggleref_arr);
373     for (i = 0; i < GC_toggleref_array_size; ++i) {
374       void *obj = GC_toggleref_arr[i].strong_ref;
375       if (obj != NULL && ((word)obj & 1) == 0) {
376         push_and_mark_object(obj);
377       }
378     }
379   }
380
381   STATIC void GC_clear_togglerefs(void)
382   {
383     int i;
384     for (i = 0; i < GC_toggleref_array_size; ++i) {
385       if ((GC_toggleref_arr[i].weak_ref & 1) != 0) {
386         if (!GC_is_marked(GC_REVEAL_POINTER(GC_toggleref_arr[i].weak_ref))) {
387           GC_toggleref_arr[i].weak_ref = 0;
388         } else {
389           /* No need to copy, BDWGC is a non-moving collector.    */
390         }
391       }
392     }
393   }
394
395   GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func fn)
396   {
397     DCL_LOCK_STATE;
398
399     LOCK();
400     GC_toggleref_callback = fn;
401     UNLOCK();
402   }
403
404   GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void)
405   {
406     GC_toggleref_func fn;
407     DCL_LOCK_STATE;
408
409     LOCK();
410     fn = GC_toggleref_callback;
411     UNLOCK();
412     return fn;
413   }
414
415   static GC_bool ensure_toggleref_capacity(int capacity_inc)
416   {
417     GC_ASSERT(capacity_inc >= 0);
418     GC_ASSERT(I_HOLD_LOCK());
419     if (NULL == GC_toggleref_arr) {
420       GC_toggleref_array_capacity = 32; /* initial capacity */
421       GC_toggleref_arr = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
422                         GC_toggleref_array_capacity * sizeof(GCToggleRef),
423                         NORMAL);
424       if (NULL == GC_toggleref_arr)
425         return FALSE;
426     }
427     if ((unsigned)GC_toggleref_array_size + (unsigned)capacity_inc
428         >= (unsigned)GC_toggleref_array_capacity) {
429       GCToggleRef *new_array;
430       while ((unsigned)GC_toggleref_array_capacity
431               < (unsigned)GC_toggleref_array_size + (unsigned)capacity_inc) {
432         GC_toggleref_array_capacity *= 2;
433         if (GC_toggleref_array_capacity < 0) /* overflow */
434           return FALSE;
435       }
436
437       new_array = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
438                         GC_toggleref_array_capacity * sizeof(GCToggleRef),
439                         NORMAL);
440       if (NULL == new_array)
441         return FALSE;
442       if (EXPECT(GC_toggleref_array_size > 0, TRUE))
443         BCOPY(GC_toggleref_arr, new_array,
444               GC_toggleref_array_size * sizeof(GCToggleRef));
445       GC_INTERNAL_FREE(GC_toggleref_arr);
446       GC_toggleref_arr = new_array;
447     }
448     return TRUE;
449   }
450
451   GC_API int GC_CALL GC_toggleref_add(void *obj, int is_strong_ref)
452   {
453     int res = GC_SUCCESS;
454     DCL_LOCK_STATE;
455
456     GC_ASSERT(NONNULL_ARG_NOT_NULL(obj));
457     LOCK();
458     if (GC_toggleref_callback != 0) {
459       if (!ensure_toggleref_capacity(1)) {
460         res = GC_NO_MEMORY;
461       } else {
462         GC_toggleref_arr[GC_toggleref_array_size++].strong_ref =
463                         is_strong_ref ? obj : (void *)GC_HIDE_POINTER(obj);
464       }
465     }
466     UNLOCK();
467     return res;
468   }
469 #endif /* !GC_TOGGLE_REFS_NOT_NEEDED */
470
471 /* Finalizer callback support. */
472 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
473
474 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
475 {
476   DCL_LOCK_STATE;
477
478   LOCK();
479   GC_object_finalized_proc = fn;
480   UNLOCK();
481 }
482
483 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
484 {
485   GC_await_finalize_proc fn;
486   DCL_LOCK_STATE;
487
488   LOCK();
489   fn = GC_object_finalized_proc;
490   UNLOCK();
491   return fn;
492 }
493
494 #ifndef GC_LONG_REFS_NOT_NEEDED
495   GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
496   {
497     if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
498         ABORT("Bad arg to GC_register_long_link");
499     return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj,
500                                                "long dl");
501   }
502
503   GC_API int GC_CALL GC_unregister_long_link(void * * link)
504   {
505     struct disappearing_link *curr_dl;
506     DCL_LOCK_STATE;
507
508     if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
509
510     LOCK();
511     curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
512     UNLOCK();
513     if (NULL == curr_dl) return 0;
514     FREE_DL_ENTRY(curr_dl);
515     return 1;
516   }
517 #endif /* !GC_LONG_REFS_NOT_NEEDED */
518
519 #ifndef GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED
520   /* Moves a link.  Assume the lock is held.    */
521   STATIC int GC_move_disappearing_link_inner(
522                                 struct dl_hashtbl_s *dl_hashtbl,
523                                 void **link, void **new_link)
524   {
525     struct disappearing_link *curr_dl, *prev_dl, *new_dl;
526     size_t curr_index, new_index;
527     word curr_hidden_link;
528     word new_hidden_link;
529
530     if (dl_hashtbl->log_size == -1)
531         return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
532
533     /* Find current link.       */
534     curr_index = HASH2(link, dl_hashtbl -> log_size);
535     curr_hidden_link = GC_HIDE_POINTER(link);
536     prev_dl = NULL;
537     for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
538          curr_dl = dl_next(curr_dl)) {
539       if (curr_dl -> dl_hidden_link == curr_hidden_link)
540         break;
541       prev_dl = curr_dl;
542     }
543
544     if (NULL == curr_dl) {
545       return GC_NOT_FOUND;
546     }
547
548     if (link == new_link) {
549       return GC_SUCCESS; /* Nothing to do.      */
550     }
551
552     /* link found; now check new_link not present.      */
553     new_index = HASH2(new_link, dl_hashtbl -> log_size);
554     new_hidden_link = GC_HIDE_POINTER(new_link);
555     for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
556          new_dl = dl_next(new_dl)) {
557       if (new_dl -> dl_hidden_link == new_hidden_link) {
558         /* Target already registered; bail.     */
559         return GC_DUPLICATE;
560       }
561     }
562
563     /* Remove from old, add to new, update link.        */
564     if (NULL == prev_dl) {
565       dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
566     } else {
567       dl_set_next(prev_dl, dl_next(curr_dl));
568     }
569     curr_dl -> dl_hidden_link = new_hidden_link;
570     dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
571     dl_hashtbl -> head[new_index] = curr_dl;
572     return GC_SUCCESS;
573   }
574
575   GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
576   {
577     int result;
578     DCL_LOCK_STATE;
579
580     if (((word)new_link & (ALIGNMENT-1)) != 0
581         || !NONNULL_ARG_NOT_NULL(new_link))
582       ABORT("Bad new_link arg to GC_move_disappearing_link");
583     if (((word)link & (ALIGNMENT-1)) != 0)
584       return GC_NOT_FOUND; /* Nothing to do. */
585
586     LOCK();
587     result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
588     UNLOCK();
589     return result;
590   }
591
592 # ifndef GC_LONG_REFS_NOT_NEEDED
593     GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
594     {
595       int result;
596       DCL_LOCK_STATE;
597
598       if (((word)new_link & (ALIGNMENT-1)) != 0
599           || !NONNULL_ARG_NOT_NULL(new_link))
600         ABORT("Bad new_link arg to GC_move_long_link");
601       if (((word)link & (ALIGNMENT-1)) != 0)
602         return GC_NOT_FOUND; /* Nothing to do. */
603
604       LOCK();
605       result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
606       UNLOCK();
607       return result;
608     }
609 # endif /* !GC_LONG_REFS_NOT_NEEDED */
610 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
611
612 /* Possible finalization_marker procedures.  Note that mark stack       */
613 /* overflow is handled by the caller, and is not a disaster.            */
614 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
615 {
616     hdr * hhdr = HDR(p);
617
618     PUSH_OBJ(p, hhdr, GC_mark_stack_top,
619              &(GC_mark_stack[GC_mark_stack_size]));
620 }
621
622 /* This only pays very partial attention to the mark descriptor.        */
623 /* It does the right thing for normal and atomic objects, and treats    */
624 /* most others as normal.                                               */
625 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
626 {
627     hdr * hhdr = HDR(p);
628     word descr = hhdr -> hb_descr;
629     ptr_t q;
630     ptr_t scan_limit;
631     ptr_t target_limit = p + hhdr -> hb_sz - 1;
632
633     if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
634        scan_limit = p + descr - sizeof(word);
635     } else {
636        scan_limit = target_limit + 1 - sizeof(word);
637     }
638     for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
639         word r = *(word *)q;
640
641         if (r < (word)p || r > (word)target_limit) {
642             GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
643         }
644     }
645 }
646
647 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
648
649 /* Possible finalization_marker procedures.  Note that mark stack       */
650 /* overflow is handled by the caller, and is not a disaster.            */
651
652 /* GC_unreachable_finalize_mark_proc is an alias for normal marking,    */
653 /* but it is explicitly tested for, and triggers different              */
654 /* behavior.  Objects registered in this way are not finalized          */
655 /* if they are reachable by other finalizable objects, even if those    */
656 /* other objects specify no ordering.                                   */
657 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
658 {
659     GC_normal_finalize_mark_proc(p);
660 }
661
662 /* Register a finalization function.  See gc.h for details.     */
663 /* The last parameter is a procedure that determines            */
664 /* marking for finalization ordering.  Any objects marked       */
665 /* by that procedure will be guaranteed to not have been        */
666 /* finalized when this finalizer is invoked.                    */
667 STATIC void GC_register_finalizer_inner(void * obj,
668                                         GC_finalization_proc fn, void *cd,
669                                         GC_finalization_proc *ofn, void **ocd,
670                                         finalization_mark_proc mp)
671 {
672     struct finalizable_object * curr_fo;
673     size_t index;
674     struct finalizable_object *new_fo = 0;
675     hdr *hhdr = NULL; /* initialized to prevent warning. */
676     DCL_LOCK_STATE;
677
678     if (EXPECT(GC_find_leak, FALSE)) return;
679     LOCK();
680     if (log_fo_table_size == -1
681         || GC_fo_entries > ((word)1 << log_fo_table_size)) {
682         GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
683                       &log_fo_table_size, &GC_fo_entries);
684 #       ifdef LINT2
685           if (log_fo_table_size < 0) ABORT("log_size is negative");
686 #       endif
687         GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
688                            1 << (unsigned)log_fo_table_size);
689     }
690     /* in the THREADS case we hold allocation lock.             */
691     for (;;) {
692       struct finalizable_object *prev_fo = NULL;
693       GC_oom_func oom_fn;
694
695       index = HASH2(obj, log_fo_table_size);
696       curr_fo = GC_fnlz_roots.fo_head[index];
697       while (curr_fo != 0) {
698         GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
699         if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
700           /* Interruption by a signal in the middle of this     */
701           /* should be safe.  The client may see only *ocd      */
702           /* updated, but we'll declare that to be his problem. */
703           if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
704           if (ofn) *ofn = curr_fo -> fo_fn;
705           /* Delete the structure for obj.      */
706           if (prev_fo == 0) {
707             GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
708           } else {
709             fo_set_next(prev_fo, fo_next(curr_fo));
710           }
711           if (fn == 0) {
712             GC_fo_entries--;
713             /* May not happen if we get a signal.  But a high   */
714             /* estimate will only make the table larger than    */
715             /* necessary.                                       */
716 #           if !defined(THREADS) && !defined(DBG_HDRS_ALL)
717               GC_free((void *)curr_fo);
718 #           endif
719           } else {
720             curr_fo -> fo_fn = fn;
721             curr_fo -> fo_client_data = (ptr_t)cd;
722             curr_fo -> fo_mark_proc = mp;
723             /* Reinsert it.  We deleted it first to maintain    */
724             /* consistency in the event of a signal.            */
725             if (prev_fo == 0) {
726               GC_fnlz_roots.fo_head[index] = curr_fo;
727             } else {
728               fo_set_next(prev_fo, curr_fo);
729             }
730           }
731           UNLOCK();
732 #         ifndef DBG_HDRS_ALL
733             if (EXPECT(new_fo != 0, FALSE)) {
734               /* Free unused new_fo returned by GC_oom_fn() */
735               GC_free((void *)new_fo);
736             }
737 #         endif
738           return;
739         }
740         prev_fo = curr_fo;
741         curr_fo = fo_next(curr_fo);
742       }
743       if (EXPECT(new_fo != 0, FALSE)) {
744         /* new_fo is returned by GC_oom_fn().   */
745         GC_ASSERT(fn != 0);
746 #       ifdef LINT2
747           if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
748 #       endif
749         break;
750       }
751       if (fn == 0) {
752         if (ocd) *ocd = 0;
753         if (ofn) *ofn = 0;
754         UNLOCK();
755         return;
756       }
757       GET_HDR(obj, hhdr);
758       if (EXPECT(0 == hhdr, FALSE)) {
759         /* We won't collect it, hence finalizer wouldn't be run. */
760         if (ocd) *ocd = 0;
761         if (ofn) *ofn = 0;
762         UNLOCK();
763         return;
764       }
765       new_fo = (struct finalizable_object *)
766         GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
767       if (EXPECT(new_fo != 0, TRUE))
768         break;
769       oom_fn = GC_oom_fn;
770       UNLOCK();
771       new_fo = (struct finalizable_object *)
772                 (*oom_fn)(sizeof(struct finalizable_object));
773       if (0 == new_fo) {
774         /* No enough memory.  *ocd and *ofn remains unchanged.  */
775         return;
776       }
777       /* It's not likely we'll make it here, but ... */
778       LOCK();
779       /* Recalculate index since the table may grow and         */
780       /* check again that our finalizer is not in the table.    */
781     }
782     GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
783     if (ocd) *ocd = 0;
784     if (ofn) *ofn = 0;
785     new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
786     new_fo -> fo_fn = fn;
787     new_fo -> fo_client_data = (ptr_t)cd;
788     new_fo -> fo_object_size = hhdr -> hb_sz;
789     new_fo -> fo_mark_proc = mp;
790     fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
791     GC_fo_entries++;
792     GC_fnlz_roots.fo_head[index] = new_fo;
793     UNLOCK();
794 }
795
796 GC_API void GC_CALL GC_register_finalizer(void * obj,
797                                   GC_finalization_proc fn, void * cd,
798                                   GC_finalization_proc *ofn, void ** ocd)
799 {
800     GC_register_finalizer_inner(obj, fn, cd, ofn,
801                                 ocd, GC_normal_finalize_mark_proc);
802 }
803
804 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
805                                GC_finalization_proc fn, void * cd,
806                                GC_finalization_proc *ofn, void ** ocd)
807 {
808     GC_register_finalizer_inner(obj, fn, cd, ofn,
809                                 ocd, GC_ignore_self_finalize_mark_proc);
810 }
811
812 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
813                                GC_finalization_proc fn, void * cd,
814                                GC_finalization_proc *ofn, void ** ocd)
815 {
816     GC_register_finalizer_inner(obj, fn, cd, ofn,
817                                 ocd, GC_null_finalize_mark_proc);
818 }
819
820 static GC_bool need_unreachable_finalization = FALSE;
821         /* Avoid the work if this isn't used.   */
822
823 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
824                                GC_finalization_proc fn, void * cd,
825                                GC_finalization_proc *ofn, void ** ocd)
826 {
827     need_unreachable_finalization = TRUE;
828     GC_ASSERT(GC_java_finalization);
829     GC_register_finalizer_inner(obj, fn, cd, ofn,
830                                 ocd, GC_unreachable_finalize_mark_proc);
831 }
832
833 #ifndef NO_DEBUGGING
834   STATIC void GC_dump_finalization_links(
835                                 const struct dl_hashtbl_s *dl_hashtbl)
836   {
837     size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
838                                 (size_t)1 << dl_hashtbl->log_size;
839     size_t i;
840
841     for (i = 0; i < dl_size; i++) {
842       struct disappearing_link *curr_dl;
843
844       for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
845            curr_dl = dl_next(curr_dl)) {
846         ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
847         ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
848
849         GC_printf("Object: %p, link: %p\n",
850                   (void *)real_ptr, (void *)real_link);
851       }
852     }
853   }
854
855   GC_API void GC_CALL GC_dump_finalization(void)
856   {
857     struct finalizable_object * curr_fo;
858     size_t fo_size = log_fo_table_size == -1 ? 0 :
859                                 (size_t)1 << log_fo_table_size;
860     size_t i;
861
862     GC_printf("Disappearing (short) links:\n");
863     GC_dump_finalization_links(&GC_dl_hashtbl);
864 #   ifndef GC_LONG_REFS_NOT_NEEDED
865       GC_printf("Disappearing long links:\n");
866       GC_dump_finalization_links(&GC_ll_hashtbl);
867 #   endif
868     GC_printf("Finalizers:\n");
869     for (i = 0; i < fo_size; i++) {
870       for (curr_fo = GC_fnlz_roots.fo_head[i];
871            curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
872         ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
873
874         GC_printf("Finalizable object: %p\n", (void *)real_ptr);
875       }
876     }
877   }
878 #endif /* !NO_DEBUGGING */
879
880 #ifndef SMALL_CONFIG
881   STATIC word GC_old_dl_entries = 0; /* for stats printing */
882 # ifndef GC_LONG_REFS_NOT_NEEDED
883     STATIC word GC_old_ll_entries = 0;
884 # endif
885 #endif /* !SMALL_CONFIG */
886
887 #ifndef THREADS
888   /* Global variables to minimize the level of recursion when a client  */
889   /* finalizer allocates memory.                                        */
890   STATIC int GC_finalizer_nested = 0;
891                         /* Only the lowest byte is used, the rest is    */
892                         /* padding for proper global data alignment     */
893                         /* required for some compilers (like Watcom).   */
894   STATIC unsigned GC_finalizer_skipped = 0;
895
896   /* Checks and updates the level of finalizers recursion.              */
897   /* Returns NULL if GC_invoke_finalizers() should not be called by the */
898   /* collector (to minimize the risk of a deep finalizers recursion),   */
899   /* otherwise returns a pointer to GC_finalizer_nested.                */
900   STATIC unsigned char *GC_check_finalizer_nested(void)
901   {
902     unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
903     if (nesting_level) {
904       /* We are inside another GC_invoke_finalizers().          */
905       /* Skip some implicitly-called GC_invoke_finalizers()     */
906       /* depending on the nesting (recursion) level.            */
907       if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
908       GC_finalizer_skipped = 0;
909     }
910     *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
911     return (unsigned char *)&GC_finalizer_nested;
912   }
913 #endif /* THREADS */
914
915 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
916   { \
917     size_t i; \
918     size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
919                                 (size_t)1 << dl_hashtbl->log_size; \
920     for (i = 0; i < dl_size; i++) { \
921       struct disappearing_link *prev_dl = NULL; \
922       curr_dl = dl_hashtbl -> head[i]; \
923       while (curr_dl) {
924
925 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
926         prev_dl = curr_dl; \
927         curr_dl = dl_next(curr_dl); \
928       } \
929     } \
930   }
931
932 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
933   { \
934     next_dl = dl_next(curr_dl); \
935     if (NULL == prev_dl) { \
936         dl_hashtbl -> head[i] = next_dl; \
937     } else { \
938         dl_set_next(prev_dl, next_dl); \
939     } \
940     GC_clear_mark_bit(curr_dl); \
941     dl_hashtbl -> entries--; \
942     curr_dl = next_dl; \
943     continue; \
944   }
945
946 GC_INLINE void GC_make_disappearing_links_disappear(
947                                 struct dl_hashtbl_s* dl_hashtbl)
948 {
949     struct disappearing_link *curr, *next;
950
951     ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
952         ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
953         ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
954
955         if (!GC_is_marked(real_ptr)) {
956             *(word *)real_link = 0;
957             GC_clear_mark_bit(curr);
958             DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
959         }
960     ITERATE_DL_HASHTBL_END(curr, prev)
961 }
962
963 GC_INLINE void GC_remove_dangling_disappearing_links(
964                                 struct dl_hashtbl_s* dl_hashtbl)
965 {
966     struct disappearing_link *curr, *next;
967
968     ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
969         ptr_t real_link =
970                 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
971
972         if (NULL != real_link && !GC_is_marked(real_link)) {
973             GC_clear_mark_bit(curr);
974             DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
975         }
976     ITERATE_DL_HASHTBL_END(curr, prev)
977 }
978
979 /* Called with held lock (but the world is running).                    */
980 /* Cause disappearing links to disappear and unreachable objects to be  */
981 /* enqueued for finalization.                                           */
982 GC_INNER void GC_finalize(void)
983 {
984     struct finalizable_object * curr_fo, * prev_fo, * next_fo;
985     ptr_t real_ptr;
986     size_t i;
987     size_t fo_size = log_fo_table_size == -1 ? 0 :
988                                 (size_t)1 << log_fo_table_size;
989
990 #   ifndef SMALL_CONFIG
991       /* Save current GC_[dl/ll]_entries value for stats printing */
992       GC_old_dl_entries = GC_dl_hashtbl.entries;
993 #     ifndef GC_LONG_REFS_NOT_NEEDED
994         GC_old_ll_entries = GC_ll_hashtbl.entries;
995 #     endif
996 #   endif
997
998 #   ifndef GC_TOGGLE_REFS_NOT_NEEDED
999       GC_mark_togglerefs();
1000 #   endif
1001     GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
1002
1003   /* Mark all objects reachable via chains of 1 or more pointers        */
1004   /* from finalizable objects.                                          */
1005     GC_ASSERT(GC_mark_state == MS_NONE);
1006     for (i = 0; i < fo_size; i++) {
1007       for (curr_fo = GC_fnlz_roots.fo_head[i];
1008            curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1009         GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
1010         real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1011         if (!GC_is_marked(real_ptr)) {
1012             GC_MARKED_FOR_FINALIZATION(real_ptr);
1013             GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
1014             if (GC_is_marked(real_ptr)) {
1015                 WARN("Finalization cycle involving %p\n", real_ptr);
1016             }
1017         }
1018       }
1019     }
1020   /* Enqueue for finalization all objects that are still                */
1021   /* unreachable.                                                       */
1022     GC_bytes_finalized = 0;
1023     for (i = 0; i < fo_size; i++) {
1024       curr_fo = GC_fnlz_roots.fo_head[i];
1025       prev_fo = 0;
1026       while (curr_fo != 0) {
1027         real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1028         if (!GC_is_marked(real_ptr)) {
1029             if (!GC_java_finalization) {
1030               GC_set_mark_bit(real_ptr);
1031             }
1032             /* Delete from hash table */
1033               next_fo = fo_next(curr_fo);
1034               if (NULL == prev_fo) {
1035                 GC_fnlz_roots.fo_head[i] = next_fo;
1036               } else {
1037                 fo_set_next(prev_fo, next_fo);
1038               }
1039               GC_fo_entries--;
1040               if (GC_object_finalized_proc)
1041                 GC_object_finalized_proc(real_ptr);
1042
1043             /* Add to list of objects awaiting finalization.    */
1044               fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1045               SET_FINALIZE_NOW(curr_fo);
1046               /* unhide object pointer so any future collections will   */
1047               /* see it.                                                */
1048               curr_fo -> fo_hidden_base =
1049                         (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1050               GC_bytes_finalized +=
1051                         curr_fo -> fo_object_size
1052                         + sizeof(struct finalizable_object);
1053             GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1054             curr_fo = next_fo;
1055         } else {
1056             prev_fo = curr_fo;
1057             curr_fo = fo_next(curr_fo);
1058         }
1059       }
1060     }
1061
1062   if (GC_java_finalization) {
1063     /* make sure we mark everything reachable from objects finalized
1064        using the no_order mark_proc */
1065       for (curr_fo = GC_fnlz_roots.finalize_now;
1066            curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1067         real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1068         if (!GC_is_marked(real_ptr)) {
1069             if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1070                 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1071             }
1072             if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1073                 GC_set_mark_bit(real_ptr);
1074             }
1075         }
1076       }
1077
1078     /* now revive finalize-when-unreachable objects reachable from
1079        other finalizable objects */
1080       if (need_unreachable_finalization) {
1081         curr_fo = GC_fnlz_roots.finalize_now;
1082 #       if defined(GC_ASSERTIONS) || defined(LINT2)
1083           if (curr_fo != NULL && log_fo_table_size < 0)
1084             ABORT("log_size is negative");
1085 #       endif
1086         prev_fo = NULL;
1087         while (curr_fo != NULL) {
1088           next_fo = fo_next(curr_fo);
1089           if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1090             real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1091             if (!GC_is_marked(real_ptr)) {
1092               GC_set_mark_bit(real_ptr);
1093             } else {
1094               if (NULL == prev_fo) {
1095                 SET_FINALIZE_NOW(next_fo);
1096               } else {
1097                 fo_set_next(prev_fo, next_fo);
1098               }
1099               curr_fo -> fo_hidden_base =
1100                                 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1101               GC_bytes_finalized -=
1102                   curr_fo->fo_object_size + sizeof(struct finalizable_object);
1103
1104               i = HASH2(real_ptr, log_fo_table_size);
1105               fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1106               GC_fo_entries++;
1107               GC_fnlz_roots.fo_head[i] = curr_fo;
1108               curr_fo = prev_fo;
1109             }
1110           }
1111           prev_fo = curr_fo;
1112           curr_fo = next_fo;
1113         }
1114       }
1115   }
1116
1117   GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1118 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1119     GC_clear_togglerefs();
1120 # endif
1121 # ifndef GC_LONG_REFS_NOT_NEEDED
1122     GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1123     GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1124 # endif
1125
1126   if (GC_fail_count) {
1127     /* Don't prevent running finalizers if there has been an allocation */
1128     /* failure recently.                                                */
1129 #   ifdef THREADS
1130       GC_reset_finalizer_nested();
1131 #   else
1132       GC_finalizer_nested = 0;
1133 #   endif
1134   }
1135 }
1136
1137 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1138
1139   /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
1140   STATIC void GC_enqueue_all_finalizers(void)
1141   {
1142     struct finalizable_object * next_fo;
1143     int i;
1144     int fo_size;
1145
1146     fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1147     GC_bytes_finalized = 0;
1148     for (i = 0; i < fo_size; i++) {
1149       struct finalizable_object * curr_fo = GC_fnlz_roots.fo_head[i];
1150
1151       GC_fnlz_roots.fo_head[i] = NULL;
1152       while (curr_fo != NULL) {
1153           ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1154
1155           GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1156           GC_set_mark_bit(real_ptr);
1157
1158           next_fo = fo_next(curr_fo);
1159
1160           /* Add to list of objects awaiting finalization.      */
1161           fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1162           SET_FINALIZE_NOW(curr_fo);
1163
1164           /* unhide object pointer so any future collections will       */
1165           /* see it.                                                    */
1166           curr_fo -> fo_hidden_base =
1167                         (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1168           GC_bytes_finalized +=
1169                 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1170           curr_fo = next_fo;
1171         }
1172     }
1173     GC_fo_entries = 0;  /* all entries deleted from the hash table */
1174   }
1175
1176   /* Invoke all remaining finalizers that haven't yet been run.
1177    * This is needed for strict compliance with the Java standard,
1178    * which can make the runtime guarantee that all finalizers are run.
1179    * Unfortunately, the Java standard implies we have to keep running
1180    * finalizers until there are no more left, a potential infinite loop.
1181    * YUCK.
1182    * Note that this is even more dangerous than the usual Java
1183    * finalizers, in that objects reachable from static variables
1184    * may have been finalized when these finalizers are run.
1185    * Finalizers run at this point must be prepared to deal with a
1186    * mostly broken world.
1187    * This routine is externally callable, so is called without
1188    * the allocation lock.
1189    */
1190   GC_API void GC_CALL GC_finalize_all(void)
1191   {
1192     DCL_LOCK_STATE;
1193
1194     LOCK();
1195     while (GC_fo_entries > 0) {
1196       GC_enqueue_all_finalizers();
1197       UNLOCK();
1198       GC_invoke_finalizers();
1199       /* Running the finalizers in this thread is arguably not a good   */
1200       /* idea when we should be notifying another thread to run them.   */
1201       /* But otherwise we don't have a great way to wait for them to    */
1202       /* run.                                                           */
1203       LOCK();
1204     }
1205     UNLOCK();
1206   }
1207
1208 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1209
1210 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1211 /* finalizers can only be called from some kind of "safe state" and     */
1212 /* getting into that safe state is expensive.)                          */
1213 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1214 {
1215 # ifdef AO_HAVE_load
1216     return AO_load((volatile AO_t *)&GC_fnlz_roots.finalize_now) != 0;
1217 # else
1218     return GC_fnlz_roots.finalize_now != NULL;
1219 # endif /* !THREADS */
1220 }
1221
1222 /* Invoke finalizers for all objects that are ready to be finalized.    */
1223 /* Should be called without allocation lock.                            */
1224 GC_API int GC_CALL GC_invoke_finalizers(void)
1225 {
1226     int count = 0;
1227     word bytes_freed_before = 0; /* initialized to prevent warning. */
1228     DCL_LOCK_STATE;
1229
1230     while (GC_should_invoke_finalizers()) {
1231         struct finalizable_object * curr_fo;
1232
1233 #       ifdef THREADS
1234             LOCK();
1235 #       endif
1236         if (count == 0) {
1237             bytes_freed_before = GC_bytes_freed;
1238             /* Don't do this outside, since we need the lock. */
1239         }
1240         curr_fo = GC_fnlz_roots.finalize_now;
1241 #       ifdef THREADS
1242             if (curr_fo != NULL)
1243                 SET_FINALIZE_NOW(fo_next(curr_fo));
1244             UNLOCK();
1245             if (curr_fo == 0) break;
1246 #       else
1247             GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1248 #       endif
1249         fo_set_next(curr_fo, 0);
1250         (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1251                               curr_fo -> fo_client_data);
1252         curr_fo -> fo_client_data = 0;
1253         ++count;
1254         /* Explicit freeing of curr_fo is probably a bad idea.  */
1255         /* It throws off accounting if nearly all objects are   */
1256         /* finalizable.  Otherwise it should not matter.        */
1257     }
1258     /* bytes_freed_before is initialized whenever count != 0 */
1259     if (count != 0
1260 #         if defined(THREADS) && !defined(THREAD_SANITIZER)
1261             /* A quick check whether some memory was freed.     */
1262             /* The race with GC_free() is safe to be ignored    */
1263             /* because we only need to know if the current      */
1264             /* thread has deallocated something.                */
1265             && bytes_freed_before != GC_bytes_freed
1266 #         endif
1267        ) {
1268         LOCK();
1269         GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1270         UNLOCK();
1271     }
1272     return count;
1273 }
1274
1275 static word last_finalizer_notification = 0;
1276
1277 GC_INNER void GC_notify_or_invoke_finalizers(void)
1278 {
1279     GC_finalizer_notifier_proc notifier_fn = 0;
1280 #   if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1281       static word last_back_trace_gc_no = 1;    /* Skip first one. */
1282 #   endif
1283     DCL_LOCK_STATE;
1284
1285 #   if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1286        && !defined(MAKE_BACK_GRAPH)
1287       /* Quick check (while unlocked) for an empty finalization queue.  */
1288       if (!GC_should_invoke_finalizers())
1289         return;
1290 #   endif
1291     LOCK();
1292
1293     /* This is a convenient place to generate backtraces if appropriate, */
1294     /* since that code is not callable with the allocation lock.         */
1295 #   if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1296       if (GC_gc_no > last_back_trace_gc_no) {
1297 #       ifdef KEEP_BACK_PTRS
1298           long i;
1299           /* Stops when GC_gc_no wraps; that's OK.      */
1300           last_back_trace_gc_no = (word)(-1);  /* disable others. */
1301           for (i = 0; i < GC_backtraces; ++i) {
1302               /* FIXME: This tolerates concurrent heap mutation,        */
1303               /* which may cause occasional mysterious results.         */
1304               /* We need to release the GC lock, since GC_print_callers */
1305               /* acquires it.  It probably shouldn't.                   */
1306               UNLOCK();
1307               GC_generate_random_backtrace_no_gc();
1308               LOCK();
1309           }
1310           last_back_trace_gc_no = GC_gc_no;
1311 #       endif
1312 #       ifdef MAKE_BACK_GRAPH
1313           if (GC_print_back_height) {
1314             UNLOCK();
1315             GC_print_back_graph_stats();
1316             LOCK();
1317           }
1318 #       endif
1319       }
1320 #   endif
1321     if (NULL == GC_fnlz_roots.finalize_now) {
1322       UNLOCK();
1323       return;
1324     }
1325
1326     if (!GC_finalize_on_demand) {
1327       unsigned char *pnested = GC_check_finalizer_nested();
1328       UNLOCK();
1329       /* Skip GC_invoke_finalizers() if nested */
1330       if (pnested != NULL) {
1331         (void) GC_invoke_finalizers();
1332         *pnested = 0; /* Reset since no more finalizers. */
1333 #       ifndef THREADS
1334           GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1335 #       endif   /* Otherwise GC can run concurrently and add more */
1336       }
1337       return;
1338     }
1339
1340     /* These variables require synchronization to avoid data races.     */
1341     if (last_finalizer_notification != GC_gc_no) {
1342         last_finalizer_notification = GC_gc_no;
1343         notifier_fn = GC_finalizer_notifier;
1344     }
1345     UNLOCK();
1346     if (notifier_fn != 0)
1347         (*notifier_fn)(); /* Invoke the notifier */
1348 }
1349
1350 #ifndef SMALL_CONFIG
1351 # ifndef GC_LONG_REFS_NOT_NEEDED
1352 #   define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1353 # else
1354 #   define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1355 # endif
1356
1357   GC_INNER void GC_print_finalization_stats(void)
1358   {
1359     struct finalizable_object *fo;
1360     unsigned long ready = 0;
1361
1362     GC_log_printf("%lu finalization entries;"
1363                   " %lu/%lu short/long disappearing links alive\n",
1364                   (unsigned long)GC_fo_entries,
1365                   (unsigned long)GC_dl_hashtbl.entries,
1366                   (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1367                                                 GC_ll_hashtbl.entries, 0));
1368
1369     for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1370       ++ready;
1371     GC_log_printf("%lu finalization-ready objects;"
1372                   " %ld/%ld short/long links cleared\n",
1373                   ready,
1374                   (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1375                   (long)IF_LONG_REFS_PRESENT_ELSE(
1376                               GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1377   }
1378 #endif /* !SMALL_CONFIG */
1379
1380 #endif /* !GC_NO_FINALIZATION */