Merge pull request #1079 from esdrubal/webclient_cancel
[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 /* Finalizer proc support */
370 static void (*GC_object_finalized_proc) (GC_PTR obj);
371
372 void
373 GC_set_finalizer_notify_proc (void (*proc) (GC_PTR obj))
374 {
375         GC_object_finalized_proc = proc;
376 }
377
378
379 static void push_and_mark_object (GC_PTR p)
380 {
381     hdr * hhdr = HDR(p);
382
383     PUSH_OBJ((word *)p, hhdr, GC_mark_stack_top,
384              &(GC_mark_stack[GC_mark_stack_size]));
385
386         while (!GC_mark_stack_empty()) MARK_FROM_MARK_STACK();
387         GC_set_mark_bit (p);
388         if (GC_mark_state != MS_NONE)
389         while (!GC_mark_some((ptr_t)0)) {}
390 }
391
392 static void GC_mark_togglerefs ()
393 {
394         int i;
395         if (!GC_toggleref_array)
396                 return;
397
398         GC_set_mark_bit ((GC_PTR)GC_toggleref_array);
399         for (i = 0; i < GC_toggleref_array_size; ++i) {
400                 if (GC_toggleref_array [i].strong_ref) {
401                         GC_PTR object = GC_toggleref_array [i].strong_ref;
402
403                         push_and_mark_object (object);
404                 }
405         }
406 }
407
408 static void GC_clear_togglerefs ()
409 {
410         int i;
411         for (i = 0; i < GC_toggleref_array_size; ++i) {
412                 if (GC_toggleref_array [i].weak_ref) {
413                         GC_PTR object = REVEAL_POINTER (GC_toggleref_array [i].weak_ref);
414
415                         if (!GC_is_marked (object)) {
416                                 GC_toggleref_array [i].weak_ref = (GC_hidden_pointer)NULL; /* We defer compaction to only happen on the callback step. */
417                         } else {
418                                 /*No need to copy, boehm is non-moving */
419                         }
420                 }
421         }
422 }
423
424
425
426 void GC_toggleref_register_callback(int (*proccess_toggleref) (GC_PTR obj))
427 {
428         GC_toggleref_callback = proccess_toggleref;
429 }
430
431 static void
432 ensure_toggleref_capacity (int capacity)
433 {
434         if (!GC_toggleref_array) {
435                 GC_toggleref_array_capacity = 32;
436                 GC_toggleref_array = (GCToggleRef *) GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE (GC_toggleref_array_capacity * sizeof (GCToggleRef), NORMAL);
437         }
438         if (GC_toggleref_array_size + capacity >= GC_toggleref_array_capacity) {
439                 GCToggleRef *tmp;
440                 int old_capacity = GC_toggleref_array_capacity;
441                 while (GC_toggleref_array_capacity < GC_toggleref_array_size + capacity)
442                         GC_toggleref_array_capacity *= 2;
443
444                 tmp = (GCToggleRef *) GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE (GC_toggleref_array_capacity * sizeof (GCToggleRef), NORMAL);
445                 memcpy (tmp, GC_toggleref_array, GC_toggleref_array_size * sizeof (GCToggleRef));
446                 GC_INTERNAL_FREE (GC_toggleref_array);
447                 GC_toggleref_array = tmp;
448         }
449 }
450
451 void
452 GC_toggleref_add (GC_PTR object, int strong_ref)
453 {
454     DCL_LOCK_STATE;
455 # ifdef THREADS
456         DISABLE_SIGNALS();
457         LOCK();
458 # endif
459
460         if (!GC_toggleref_callback)
461                 goto end;
462
463         ensure_toggleref_capacity (1);
464         GC_toggleref_array [GC_toggleref_array_size].strong_ref = strong_ref ? object : NULL;
465         GC_toggleref_array [GC_toggleref_array_size].weak_ref = strong_ref ? (GC_hidden_pointer)NULL : HIDE_POINTER (object);
466         ++GC_toggleref_array_size;
467
468 end:
469 # ifdef THREADS
470         UNLOCK();
471         ENABLE_SIGNALS();
472 # endif
473 }
474
475
476
477 # if defined(__STDC__) || defined(__cplusplus)
478     int GC_register_long_link(GC_PTR * link, GC_PTR obj)
479 # else
480     int GC_register_long_link(link, obj)
481     GC_PTR * link;
482         GC_PTR obj;
483 # endif
484 {
485     return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj);      
486 }
487
488 # if defined(__STDC__) || defined(__cplusplus)
489     int GC_unregister_long_link(GC_PTR * link)
490 # else
491     int GC_unregister_long_link(link)
492     GC_PTR * link;
493 # endif
494 {
495         return GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
496 }
497
498 /* Possible finalization_marker procedures.  Note that mark stack       */
499 /* overflow is handled by the caller, and is not a disaster.            */
500 GC_API void GC_normal_finalize_mark_proc(p)
501 ptr_t p;
502 {
503     hdr * hhdr = HDR(p);
504     
505     PUSH_OBJ((word *)p, hhdr, GC_mark_stack_top,
506              &(GC_mark_stack[GC_mark_stack_size]));
507 }
508
509 /* This only pays very partial attention to the mark descriptor.        */
510 /* It does the right thing for normal and atomic objects, and treats    */
511 /* most others as normal.                                               */
512 GC_API void GC_ignore_self_finalize_mark_proc(p)
513 ptr_t p;
514 {
515     hdr * hhdr = HDR(p);
516     word descr = hhdr -> hb_descr;
517     ptr_t q, r;
518     ptr_t scan_limit;
519     ptr_t target_limit = p + WORDS_TO_BYTES(hhdr -> hb_sz) - 1;
520     
521     if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
522        scan_limit = p + descr - sizeof(word);
523     } else {
524        scan_limit = target_limit + 1 - sizeof(word);
525     }
526     for (q = p; q <= scan_limit; q += ALIGNMENT) {
527         r = *(ptr_t *)q;
528         if (r < p || r > target_limit) {
529             GC_PUSH_ONE_HEAP((word)r, q);
530         }
531     }
532 }
533
534 /*ARGSUSED*/
535 GC_API void GC_null_finalize_mark_proc(p)
536 ptr_t p;
537 {
538 }
539
540
541
542 /* Register a finalization function.  See gc.h for details.     */
543 /* in the nonthreads case, we try to avoid disabling signals,   */
544 /* since it can be expensive.  Threads packages typically       */
545 /* make it cheaper.                                             */
546 /* The last parameter is a procedure that determines            */
547 /* marking for finalization ordering.  Any objects marked       */
548 /* by that procedure will be guaranteed to not have been        */
549 /* finalized when this finalizer is invoked.                    */
550 GC_API void GC_register_finalizer_inner(obj, fn, cd, ofn, ocd, mp)
551 GC_PTR obj;
552 GC_finalization_proc fn;
553 GC_PTR cd;
554 GC_finalization_proc * ofn;
555 GC_PTR * ocd;
556 finalization_mark_proc * mp;
557 {
558     ptr_t base;
559     struct finalizable_object * curr_fo, * prev_fo;
560     int index;
561     struct finalizable_object *new_fo;
562     hdr *hhdr;
563     DCL_LOCK_STATE;
564
565 #   ifdef THREADS
566         DISABLE_SIGNALS();
567         LOCK();
568 #   endif
569     if (log_fo_table_size == -1
570         || GC_fo_entries > ((word)1 << log_fo_table_size)) {
571 #       ifndef THREADS
572             DISABLE_SIGNALS();
573 #       endif
574         GC_grow_table((struct hash_chain_entry ***)(&fo_head),
575                       &log_fo_table_size);
576 #       ifdef CONDPRINT
577           if (GC_print_stats) {
578             GC_printf1("Grew fo table to %lu entries\n",
579                         (unsigned long)(1 << log_fo_table_size));
580           }
581 #       endif
582 #       ifndef THREADS
583             ENABLE_SIGNALS();
584 #       endif
585     }
586     /* in the THREADS case signals are disabled and we hold allocation  */
587     /* lock; otherwise neither is true.  Proceed carefully.             */
588     base = (ptr_t)obj;
589     index = HASH2(base, log_fo_table_size);
590     prev_fo = 0; curr_fo = fo_head[index];
591     while (curr_fo != 0) {
592         if (curr_fo -> fo_hidden_base == HIDE_POINTER(base)) {
593             /* Interruption by a signal in the middle of this   */
594             /* should be safe.  The client may see only *ocd    */
595             /* updated, but we'll declare that to be his        */
596             /* problem.                                         */
597             if (ocd) *ocd = (GC_PTR) curr_fo -> fo_client_data;
598             if (ofn) *ofn = curr_fo -> fo_fn;
599             /* Delete the structure for base. */
600                 if (prev_fo == 0) {
601                   fo_head[index] = fo_next(curr_fo);
602                 } else {
603                   fo_set_next(prev_fo, fo_next(curr_fo));
604                 }
605             if (fn == 0) {
606                 GC_fo_entries--;
607                   /* May not happen if we get a signal.  But a high     */
608                   /* estimate will only make the table larger than      */
609                   /* necessary.                                         */
610 #               if !defined(THREADS) && !defined(DBG_HDRS_ALL)
611                   GC_free((GC_PTR)curr_fo);
612 #               endif
613             } else {
614                 curr_fo -> fo_fn = fn;
615                 curr_fo -> fo_client_data = (ptr_t)cd;
616                 curr_fo -> fo_mark_proc = mp;
617                 /* Reinsert it.  We deleted it first to maintain        */
618                 /* consistency in the event of a signal.                */
619                 if (prev_fo == 0) {
620                   fo_head[index] = curr_fo;
621                 } else {
622                   fo_set_next(prev_fo, curr_fo);
623                 }
624             }
625 #           ifdef THREADS
626                 UNLOCK();
627                 ENABLE_SIGNALS();
628 #           endif
629             return;
630         }
631         prev_fo = curr_fo;
632         curr_fo = fo_next(curr_fo);
633     }
634     if (ofn) *ofn = 0;
635     if (ocd) *ocd = 0;
636     if (fn == 0) {
637 #       ifdef THREADS
638             UNLOCK();
639             ENABLE_SIGNALS();
640 #       endif
641         return;
642     }
643     GET_HDR(base, hhdr);
644     if (0 == hhdr) {
645       /* We won't collect it, hence finalizer wouldn't be run. */
646 #     ifdef THREADS
647           UNLOCK();
648           ENABLE_SIGNALS();
649 #     endif
650       return;
651     }
652     new_fo = (struct finalizable_object *)
653         GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
654     if (0 == new_fo) {
655 #     ifdef THREADS
656         UNLOCK();
657         ENABLE_SIGNALS();
658 #     endif
659       new_fo = (struct finalizable_object *)
660               GC_oom_fn(sizeof(struct finalizable_object));
661       if (0 == new_fo) {
662         GC_finalization_failures++;
663         return;
664       }
665       /* It's not likely we'll make it here, but ... */
666 #     ifdef THREADS
667         DISABLE_SIGNALS();
668         LOCK();
669 #     endif
670     }
671     new_fo -> fo_hidden_base = (word)HIDE_POINTER(base);
672     new_fo -> fo_fn = fn;
673     new_fo -> fo_client_data = (ptr_t)cd;
674     new_fo -> fo_object_size = hhdr -> hb_sz;
675     new_fo -> fo_mark_proc = mp;
676     fo_set_next(new_fo, fo_head[index]);
677     GC_fo_entries++;
678     fo_head[index] = new_fo;
679 #   ifdef THREADS
680         UNLOCK();
681         ENABLE_SIGNALS();
682 #   endif
683 }
684
685 # if defined(__STDC__)
686     void GC_register_finalizer(void * obj,
687                                GC_finalization_proc fn, void * cd,
688                                GC_finalization_proc *ofn, void ** ocd)
689 # else
690     void GC_register_finalizer(obj, fn, cd, ofn, ocd)
691     GC_PTR obj;
692     GC_finalization_proc fn;
693     GC_PTR cd;
694     GC_finalization_proc * ofn;
695     GC_PTR * ocd;
696 # endif
697 {
698     GC_register_finalizer_inner(obj, fn, cd, ofn,
699                                 ocd, GC_normal_finalize_mark_proc);
700 }
701
702 # if defined(__STDC__)
703     void GC_register_finalizer_ignore_self(void * obj,
704                                GC_finalization_proc fn, void * cd,
705                                GC_finalization_proc *ofn, void ** ocd)
706 # else
707     void GC_register_finalizer_ignore_self(obj, fn, cd, ofn, ocd)
708     GC_PTR obj;
709     GC_finalization_proc fn;
710     GC_PTR cd;
711     GC_finalization_proc * ofn;
712     GC_PTR * ocd;
713 # endif
714 {
715     GC_register_finalizer_inner(obj, fn, cd, ofn,
716                                 ocd, GC_ignore_self_finalize_mark_proc);
717 }
718
719 # if defined(__STDC__)
720     void GC_register_finalizer_no_order(void * obj,
721                                GC_finalization_proc fn, void * cd,
722                                GC_finalization_proc *ofn, void ** ocd)
723 # else
724     void GC_register_finalizer_no_order(obj, fn, cd, ofn, ocd)
725     GC_PTR obj;
726     GC_finalization_proc fn;
727     GC_PTR cd;
728     GC_finalization_proc * ofn;
729     GC_PTR * ocd;
730 # endif
731 {
732     GC_register_finalizer_inner(obj, fn, cd, ofn,
733                                 ocd, GC_null_finalize_mark_proc);
734 }
735
736 #ifndef NO_DEBUGGING
737
738 static void GC_dump_finalization_links(struct dl_hashtbl_s *dl_hashtbl)
739 {
740   struct disappearing_link *curr_dl;
741   ptr_t real_ptr, real_link;
742   size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
743                               1 << dl_hashtbl->log_size;
744   int i;
745
746   for (i = 0; i < dl_size; i++) {
747     for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
748          curr_dl = dl_next(curr_dl)) {
749       real_ptr = (ptr_t)REVEAL_POINTER(curr_dl -> dl_hidden_obj);
750       real_link = (ptr_t)REVEAL_POINTER(curr_dl -> dl_hidden_link);
751       GC_printf2("Object: %lx, link: %lx\n", real_ptr, real_link);
752     }
753   }
754 }
755
756 void GC_dump_finalization()
757 {
758     struct finalizable_object * curr_fo;
759     ptr_t real_ptr;
760     int fo_size = (log_fo_table_size == -1 ) ? 0 : (1 << log_fo_table_size);
761     int i;
762
763     GC_printf0("Disappearing (short) links:\n");
764     GC_dump_finalization_links(&GC_dl_hashtbl);
765     GC_printf0("Disappearing long links:\n");
766     GC_dump_finalization_links(&GC_ll_hashtbl);
767
768     GC_printf0("Finalizers:\n");
769     for (i = 0; i < fo_size; i++) {
770       for (curr_fo = fo_head[i]; curr_fo != 0; curr_fo = fo_next(curr_fo)) {
771         real_ptr = (ptr_t)REVEAL_POINTER(curr_fo -> fo_hidden_base);
772         GC_printf1("Finalizable object: 0x%lx\n", real_ptr);
773       }
774     }
775 }
776 #endif
777
778 static void GC_make_disappearing_links_disappear(struct dl_hashtbl_s *dl_hashtbl)
779 {
780     struct disappearing_link * curr_dl, * prev_dl, * next_dl;
781     ptr_t real_ptr, real_link;
782     register int i;
783     int dl_size = (dl_hashtbl -> log_size == -1 ) ? 0 : (1 << dl_hashtbl -> log_size);
784
785     for (i = 0; i < dl_size; i++) {
786       curr_dl = dl_hashtbl -> head[i];
787       prev_dl = 0;
788       while (curr_dl != 0) {
789         real_ptr = (ptr_t)REVEAL_POINTER(curr_dl -> dl_hidden_obj);
790         real_link = (ptr_t)REVEAL_POINTER(curr_dl -> dl_hidden_link);
791         if (!GC_is_marked(real_ptr)) {
792             *(word *)real_link = 0;
793             next_dl = dl_next(curr_dl);
794             if (prev_dl == 0) {
795                 dl_hashtbl -> head[i] = next_dl;
796             } else {
797                 dl_set_next(prev_dl, next_dl);
798             }
799             GC_clear_mark_bit((ptr_t)curr_dl);
800             dl_hashtbl -> entries--;
801             curr_dl = next_dl;
802         } else {
803             prev_dl = curr_dl;
804             curr_dl = dl_next(curr_dl);
805         }
806       }
807     }
808 }
809
810 static void GC_remove_dangling_disappearing_links(struct dl_hashtbl_s *dl_hashtbl)
811 {
812     struct disappearing_link * curr_dl, * prev_dl, * next_dl;
813     ptr_t real_ptr, real_link;
814     register int i;
815     int dl_size = (dl_hashtbl -> log_size == -1 ) ? 0 : (1 << dl_hashtbl -> log_size);
816
817     for (i = 0; i < dl_size; i++) {
818       curr_dl = dl_hashtbl -> head[i];
819       prev_dl = 0;
820       while (curr_dl != 0) {
821         real_link = GC_base((ptr_t)REVEAL_POINTER(curr_dl -> dl_hidden_link));
822         if (real_link != 0 && !GC_is_marked(real_link)) {
823             next_dl = dl_next(curr_dl);
824             if (prev_dl == 0) {
825                 dl_hashtbl -> head[i] = next_dl;
826             } else {
827                 dl_set_next(prev_dl, next_dl);
828             }
829             GC_clear_mark_bit((ptr_t)curr_dl);
830             dl_hashtbl -> entries--;
831             curr_dl = next_dl;
832         } else {
833             prev_dl = curr_dl;
834             curr_dl = dl_next(curr_dl);
835         }
836       }
837     }
838 }
839
840 /* Called with world stopped.  Cause disappearing links to disappear,   */
841 /* and invoke finalizers.                                               */
842 void GC_finalize()
843 {
844     struct finalizable_object * curr_fo, * prev_fo, * next_fo;
845     ptr_t real_ptr;
846     register int i;
847     int fo_size = (log_fo_table_size == -1 ) ? 0 : (1 << log_fo_table_size);
848
849         GC_mark_togglerefs();
850
851   /* Make non-tracking disappearing links disappear */
852         GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
853
854   /* Mark all objects reachable via chains of 1 or more pointers        */
855   /* from finalizable objects.                                          */
856     GC_ASSERT(GC_mark_state == MS_NONE);
857     for (i = 0; i < fo_size; i++) {
858       for (curr_fo = fo_head[i]; curr_fo != 0; curr_fo = fo_next(curr_fo)) {
859         real_ptr = (ptr_t)REVEAL_POINTER(curr_fo -> fo_hidden_base);
860         if (!GC_is_marked(real_ptr)) {
861             GC_MARKED_FOR_FINALIZATION(real_ptr);
862             GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
863             if (GC_is_marked(real_ptr)) {
864                 WARN("Finalization cycle involving %lx\n", real_ptr);
865             }
866         }
867       }
868     }
869   /* Enqueue for finalization all objects that are still                */
870   /* unreachable.                                                       */
871     GC_words_finalized = 0;
872     for (i = 0; i < fo_size; i++) {
873       curr_fo = fo_head[i];
874       prev_fo = 0;
875       while (curr_fo != 0) {
876         real_ptr = (ptr_t)REVEAL_POINTER(curr_fo -> fo_hidden_base);
877         if (!GC_is_marked(real_ptr)) {
878             if (!GC_java_finalization) {
879               GC_set_mark_bit(real_ptr);
880             }
881             /* Delete from hash table */
882               next_fo = fo_next(curr_fo);
883               if (prev_fo == 0) {
884                 fo_head[i] = next_fo;
885               } else {
886                 fo_set_next(prev_fo, next_fo);
887               }
888               GC_fo_entries--;
889
890                           if (GC_object_finalized_proc)
891                                   GC_object_finalized_proc (real_ptr);
892
893             /* Add to list of objects awaiting finalization.    */
894               fo_set_next(curr_fo, GC_finalize_now);
895               GC_finalize_now = curr_fo;
896               /* unhide object pointer so any future collections will   */
897               /* see it.                                                */
898               curr_fo -> fo_hidden_base = 
899                         (word) REVEAL_POINTER(curr_fo -> fo_hidden_base);
900               GC_words_finalized +=
901                         ALIGNED_WORDS(curr_fo -> fo_object_size)
902                         + ALIGNED_WORDS(sizeof(struct finalizable_object));
903             GC_ASSERT(GC_is_marked(GC_base((ptr_t)curr_fo)));
904             curr_fo = next_fo;
905         } else {
906             prev_fo = curr_fo;
907             curr_fo = fo_next(curr_fo);
908         }
909       }
910     }
911
912   if (GC_java_finalization) {
913     /* make sure we mark everything reachable from objects finalized
914        using the no_order mark_proc */
915       for (curr_fo = GC_finalize_now; 
916          curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
917         real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
918         if (!GC_is_marked(real_ptr)) {
919             if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
920                 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
921             }
922             GC_set_mark_bit(real_ptr);
923         }
924       }
925   }
926
927   /* Remove dangling disappearing links. */
928   GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
929
930         GC_clear_togglerefs ();
931
932   /* Make long links disappear and remove dangling ones. */
933   GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
934   GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
935 }
936
937 #ifndef JAVA_FINALIZATION_NOT_NEEDED
938
939 /* Enqueue all remaining finalizers to be run - Assumes lock is
940  * held, and signals are disabled */
941 void GC_enqueue_all_finalizers()
942 {
943     struct finalizable_object * curr_fo, * prev_fo, * next_fo;
944     ptr_t real_ptr;
945     register int i;
946     int fo_size;
947     
948     fo_size = (log_fo_table_size == -1 ) ? 0 : (1 << log_fo_table_size);
949     GC_words_finalized = 0;
950     for (i = 0; i < fo_size; i++) {
951         curr_fo = fo_head[i];
952         prev_fo = 0;
953       while (curr_fo != 0) {
954           real_ptr = (ptr_t)REVEAL_POINTER(curr_fo -> fo_hidden_base);
955           GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
956           GC_set_mark_bit(real_ptr);
957  
958           /* Delete from hash table */
959           next_fo = fo_next(curr_fo);
960           if (prev_fo == 0) {
961               fo_head[i] = next_fo;
962           } else {
963               fo_set_next(prev_fo, next_fo);
964           }
965           GC_fo_entries--;
966
967           /* Add to list of objects awaiting finalization.      */
968           fo_set_next(curr_fo, GC_finalize_now);
969           GC_finalize_now = curr_fo;
970
971           /* unhide object pointer so any future collections will       */
972           /* see it.                                            */
973           curr_fo -> fo_hidden_base = 
974                         (word) REVEAL_POINTER(curr_fo -> fo_hidden_base);
975
976           GC_words_finalized +=
977                 ALIGNED_WORDS(curr_fo -> fo_object_size)
978                         + ALIGNED_WORDS(sizeof(struct finalizable_object));
979           curr_fo = next_fo;
980         }
981     }
982
983     return;
984 }
985
986 /* Invoke all remaining finalizers that haven't yet been run. 
987  * This is needed for strict compliance with the Java standard, 
988  * which can make the runtime guarantee that all finalizers are run.
989  * Unfortunately, the Java standard implies we have to keep running
990  * finalizers until there are no more left, a potential infinite loop.
991  * YUCK.
992  * Note that this is even more dangerous than the usual Java
993  * finalizers, in that objects reachable from static variables
994  * may have been finalized when these finalizers are run.
995  * Finalizers run at this point must be prepared to deal with a
996  * mostly broken world.
997  * This routine is externally callable, so is called without 
998  * the allocation lock. 
999  */
1000 GC_API void GC_finalize_all()
1001 {
1002     DCL_LOCK_STATE;
1003
1004     DISABLE_SIGNALS();
1005     LOCK();
1006     while (GC_fo_entries > 0) {
1007       GC_enqueue_all_finalizers();
1008       UNLOCK();
1009       ENABLE_SIGNALS();
1010       GC_INVOKE_FINALIZERS();
1011       DISABLE_SIGNALS();
1012       LOCK();
1013     }
1014     UNLOCK();
1015     ENABLE_SIGNALS();
1016 }
1017 #endif
1018
1019 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1020 /* finalizers can only be called from some kind of `safe state' and     */
1021 /* getting into that safe state is expensive.)                          */
1022 int GC_should_invoke_finalizers GC_PROTO((void))
1023 {
1024     return GC_finalize_now != 0;
1025 }
1026
1027 /* Invoke finalizers for all objects that are ready to be finalized.    */
1028 /* Should be called without allocation lock.                            */
1029 int GC_invoke_finalizers()
1030 {
1031     struct finalizable_object * curr_fo;
1032     int count = 0;
1033     word mem_freed_before;
1034     DCL_LOCK_STATE;
1035     
1036     while (GC_finalize_now != 0) {
1037 #       ifdef THREADS
1038             DISABLE_SIGNALS();
1039             LOCK();
1040 #       endif
1041         if (count == 0) {
1042             mem_freed_before = GC_mem_freed;
1043         }
1044         curr_fo = GC_finalize_now;
1045 #       ifdef THREADS
1046             if (curr_fo != 0) GC_finalize_now = fo_next(curr_fo);
1047             UNLOCK();
1048             ENABLE_SIGNALS();
1049             if (curr_fo == 0) break;
1050 #       else
1051             GC_finalize_now = fo_next(curr_fo);
1052 #       endif
1053         fo_set_next(curr_fo, 0);
1054         (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1055                               curr_fo -> fo_client_data);
1056         curr_fo -> fo_client_data = 0;
1057         ++count;
1058 #       ifdef UNDEFINED
1059             /* This is probably a bad idea.  It throws off accounting if */
1060             /* nearly all objects are finalizable.  O.w. it shouldn't    */
1061             /* matter.                                                   */
1062             GC_free((GC_PTR)curr_fo);
1063 #       endif
1064     }
1065     if (count != 0 && mem_freed_before != GC_mem_freed) {
1066         LOCK();
1067         GC_finalizer_mem_freed += (GC_mem_freed - mem_freed_before);
1068         UNLOCK();
1069     }
1070     return count;
1071 }
1072
1073 void (* GC_finalizer_notifier)() = (void (*) GC_PROTO((void)))0;
1074
1075 static GC_word last_finalizer_notification = 0;
1076
1077 void GC_notify_or_invoke_finalizers GC_PROTO((void))
1078 {
1079     /* This is a convenient place to generate backtraces if appropriate, */
1080     /* since that code is not callable with the allocation lock.         */
1081 #   if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1082       static word last_back_trace_gc_no = 1;    /* Skip first one. */
1083
1084       if (GC_gc_no > last_back_trace_gc_no) {
1085         word i;
1086
1087 #       ifdef KEEP_BACK_PTRS
1088           LOCK();
1089           /* Stops when GC_gc_no wraps; that's OK.      */
1090           last_back_trace_gc_no = (word)(-1);  /* disable others. */
1091           for (i = 0; i < GC_backtraces; ++i) {
1092               /* FIXME: This tolerates concurrent heap mutation,        */
1093               /* which may cause occasional mysterious results.         */
1094               /* We need to release the GC lock, since GC_print_callers */
1095               /* acquires it.  It probably shouldn't.                   */
1096               UNLOCK();
1097               GC_generate_random_backtrace_no_gc();
1098               LOCK();
1099           }
1100           last_back_trace_gc_no = GC_gc_no;
1101           UNLOCK();
1102 #       endif
1103 #       ifdef MAKE_BACK_GRAPH
1104           if (GC_print_back_height)
1105             GC_print_back_graph_stats();
1106 #       endif
1107       }
1108 #   endif
1109     if (GC_finalize_now == 0) return;
1110     if (!GC_finalize_on_demand) {
1111         (void) GC_invoke_finalizers();
1112 #       ifndef THREADS
1113           GC_ASSERT(GC_finalize_now == 0);
1114 #       endif   /* Otherwise GC can run concurrently and add more */
1115         return;
1116     }
1117     if (GC_finalizer_notifier != (void (*) GC_PROTO((void)))0
1118         && last_finalizer_notification != GC_gc_no) {
1119         last_finalizer_notification = GC_gc_no;
1120         GC_finalizer_notifier();
1121     }
1122 }
1123
1124 # ifdef __STDC__
1125     GC_PTR GC_call_with_alloc_lock(GC_fn_type fn,
1126                                          GC_PTR client_data)
1127 # else
1128     GC_PTR GC_call_with_alloc_lock(fn, client_data)
1129     GC_fn_type fn;
1130     GC_PTR client_data;
1131 # endif
1132 {
1133     GC_PTR result;
1134     DCL_LOCK_STATE;
1135     
1136 #   ifdef THREADS
1137       DISABLE_SIGNALS();
1138       LOCK();
1139       SET_LOCK_HOLDER();
1140 #   endif
1141     result = (*fn)(client_data);
1142 #   ifdef THREADS
1143 #     ifndef GC_ASSERTIONS
1144         UNSET_LOCK_HOLDER();
1145 #     endif /* o.w. UNLOCK() does it implicitly */
1146       UNLOCK();
1147       ENABLE_SIGNALS();
1148 #   endif
1149     return(result);
1150 }
1151
1152 #if !defined(NO_DEBUGGING)
1153
1154 void GC_print_finalization_stats()
1155 {
1156     struct finalizable_object *fo = GC_finalize_now;
1157     size_t ready = 0;
1158
1159     GC_printf3("%lu finalization table entries; %lu/%lu short/long disappearing links alive\n",
1160                GC_fo_entries, (unsigned long)GC_dl_hashtbl.entries, (unsigned long)GC_ll_hashtbl.entries);
1161     for (; 0 != fo; fo = fo_next(fo)) ++ready;
1162     GC_printf1("%lu objects are eligible for immediate finalization\n", ready);
1163 }
1164
1165 #endif /* NO_DEBUGGING */