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