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