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