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