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