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