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