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