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