1 // boehm.cc - interface between libjava and Boehm GC.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
20 #include <java/lang/Class.h>
21 #include <java/lang/reflect/Modifier.h>
22 #include <java-interp.h>
24 // More nastiness: the GC wants to define TRUE and FALSE. We don't
25 // need the Java definitions (themselves a hack), so we undefine them.
29 // We include two autoconf headers. Avoid multiple definition warnings.
32 #undef PACKAGE_TARNAME
33 #undef PACKAGE_VERSION
44 #include <gc_config.h>
46 // Set GC_DEBUG before including gc.h!
47 #ifdef LIBGCJ_GC_DEBUG
53 #include <javaxfc.h> // GC_finalize_all declaration.
55 #ifdef THREAD_LOCAL_ALLOC
56 # define GC_REDIRECT_TO_LOCAL
57 # include <gc_local_alloc.h>
60 // From boehm's misc.c
65 #define MAYBE_MARK(Obj, Top, Limit, Source) \
66 Top=GC_MARK_AND_PUSH((GC_PTR) Obj, Top, Limit, (GC_PTR *) Source)
68 // `kind' index used when allocating Java arrays.
69 static int array_kind_x;
71 // Freelist used for Java arrays.
72 static void **array_free_list;
74 static int _Jv_GC_has_static_roots (const char *filename, void *, size_t);
78 // This is called by the GC during the mark phase. It marks a Java
79 // object. We use `void *' arguments and return, and not what the
80 // Boehm GC wants, to avoid pollution in our headers.
82 _Jv_MarkObj (void *addr, void *msp, void *msl, void *env)
84 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
85 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
87 if (env == (void *)1) /* Object allocated with debug allocator. */
88 addr = (GC_PTR)GC_USR_PTR_FROM_BASE(addr);
89 jobject obj = (jobject) addr;
91 _Jv_VTable *dt = *(_Jv_VTable **) addr;
92 // The object might not yet have its vtable set, or it might
93 // really be an object on the freelist. In either case, the vtable slot
94 // will either be 0, or it will point to a cleared object.
95 // This assumes Java objects have size at least 3 words,
96 // including the header. But this should remain true, since this
97 // should only be used with debugging allocation or with large objects.
98 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
99 return mark_stack_ptr;
100 jclass klass = dt->clas;
104 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
106 # ifndef JV_HASH_SYNCHRONIZATION
107 // Every object has a sync_info pointer.
108 p = (GC_PTR) obj->sync_info;
109 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
112 if (__builtin_expect (klass == &java::lang::Class::class$, false))
114 // Currently we allocate some of the memory referenced from class objects
115 // as pointerfree memory, and then mark it more intelligently here.
116 // We ensure that the ClassClass mark descriptor forces invocation of
118 // Correctness of this is subtle, but it looks OK to me for now. For the incremental
119 // collector, we need to make sure that the class object is written whenever
120 // any of the subobjects are altered and may need rescanning. This may be tricky
121 // during construction, and this may not be the right way to do this with
122 // incremental collection.
123 // If we overflow the mark stack, we will rescan the class object, so we should
124 // be OK. The same applies if we redo the mark phase because win32 unmapped part
125 // of our root set. - HB
126 jclass c = (jclass) addr;
128 p = (GC_PTR) c->name;
129 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
130 p = (GC_PTR) c->superclass;
131 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
133 p = (GC_PTR) c->constants.tags;
134 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
135 p = (GC_PTR) c->constants.data;
136 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
138 // If the class is an array, then the methods field holds a
139 // pointer to the element class. If the class is primitive,
140 // then the methods field holds a pointer to the array class.
141 p = (GC_PTR) c->methods;
142 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
144 p = (GC_PTR) c->fields;
145 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
147 // The vtable might be allocated even for compiled code.
148 p = (GC_PTR) c->vtable;
149 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
151 p = (GC_PTR) c->interfaces;
152 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
153 p = (GC_PTR) c->loader;
154 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
156 // The dispatch tables can be allocated at runtime.
157 p = (GC_PTR) c->ancestors;
158 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
161 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
163 p = (GC_PTR) c->arrayclass;
164 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
165 p = (GC_PTR) c->protectionDomain;
166 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
167 p = (GC_PTR) c->hack_signers;
168 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
169 p = (GC_PTR) c->aux_info;
170 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
174 // NOTE: each class only holds information about the class
175 // itself. So we must do the marking for the entire inheritance
176 // tree in order to mark all fields. FIXME: what about
177 // interfaces? We skip Object here, because Object only has a
178 // sync_info, and we handled that earlier.
179 // Note: occasionally `klass' can be null. For instance, this
180 // can happen if a GC occurs between the point where an object
181 // is allocated and where the vtbl slot is set.
182 while (klass && klass != &java::lang::Object::class$)
184 jfieldID field = JvGetFirstInstanceField (klass);
185 jint max = JvNumInstanceFields (klass);
187 for (int i = 0; i < max; ++i)
189 if (JvFieldIsRef (field))
191 jobject val = JvGetObjectField (obj, field);
193 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
195 field = field->getNextField ();
197 klass = klass->getSuperclass();
201 return mark_stack_ptr;
204 // This is called by the GC during the mark phase. It marks a Java
205 // array (of objects). We use `void *' arguments and return, and not
206 // what the Boehm GC wants, to avoid pollution in our headers.
208 _Jv_MarkArray (void *addr, void *msp, void *msl, void *env)
210 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
211 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
213 if (env == (void *)1) /* Object allocated with debug allocator. */
214 addr = (void *)GC_USR_PTR_FROM_BASE(addr);
215 jobjectArray array = (jobjectArray) addr;
217 _Jv_VTable *dt = *(_Jv_VTable **) addr;
218 // Assumes size >= 3 words. That's currently true since arrays have
219 // a vtable, sync pointer, and size. If the sync pointer goes away,
220 // we may need to round up the size.
221 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
222 return mark_stack_ptr;
226 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
228 # ifndef JV_HASH_SYNCHRONIZATION
229 // Every object has a sync_info pointer.
230 p = (GC_PTR) array->sync_info;
231 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
234 for (int i = 0; i < JvGetArrayLength (array); ++i)
236 jobject obj = elements (array)[i];
238 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
241 return mark_stack_ptr;
244 // Generate a GC marking descriptor for a class.
246 // We assume that the gcj mark proc has index 0. This is a dubious assumption,
247 // since another one could be registered first. But the compiler also
248 // knows this, so in that case everything else will break, too.
249 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
252 _Jv_BuildGCDescr(jclass self)
255 jint bits_per_word = CHAR_BIT * sizeof (void *);
257 // Note: for now we only consider a bitmap mark descriptor. We
258 // could also handle the case where the first N fields of a type are
259 // references. However, this is not very likely to be used by many
260 // classes, and it is easier to compute things this way.
262 // The vtable pointer.
263 desc |= 1ULL << (bits_per_word - 1);
264 #ifndef JV_HASH_SYNCHRONIZATION
265 // The sync_info field.
266 desc |= 1ULL << (bits_per_word - 2);
269 for (jclass klass = self; klass != NULL; klass = klass->getSuperclass())
271 jfieldID field = JvGetFirstInstanceField(klass);
272 int count = JvNumInstanceFields(klass);
274 for (int i = 0; i < count; ++i)
278 unsigned int off = field->getOffset();
279 // If we run into a weird situation, we bail.
280 if (off % sizeof (void *) != 0)
281 return (void *) (GCJ_DEFAULT_DESCR);
282 off /= sizeof (void *);
283 // If we find a field outside the range of our bitmap,
284 // fall back to procedure marker. The bottom 2 bits are
286 if (off >= (unsigned) bits_per_word - 2)
287 return (void *) (GCJ_DEFAULT_DESCR);
288 desc |= 1ULL << (bits_per_word - off - 1);
291 field = field->getNextField();
295 // For bitmap mark type, bottom bits are 01.
297 // Bogus warning avoidance (on many platforms).
298 return (void *) (unsigned long) desc;
301 // Allocate some space that is known to be pointer-free.
303 _Jv_AllocBytes (jsize size)
305 void *r = GC_MALLOC_ATOMIC (size);
306 // We have to explicitly zero memory here, as the GC doesn't
307 // guarantee that PTRFREE allocations are zeroed. Note that we
308 // don't have to do this for other allocation types because we set
309 // the `ok_init' flag in the type descriptor.
314 #ifdef LIBGCJ_GC_DEBUG
317 _Jv_AllocObj (jsize size, jclass klass)
319 return GC_GCJ_MALLOC (size, klass->vtable);
323 _Jv_AllocPtrFreeObj (jsize size, jclass klass)
325 #ifdef JV_HASH_SYNCHRONIZATION
326 void * obj = GC_MALLOC_ATOMIC(size);
327 *((_Jv_VTable **) obj) = klass->vtable;
329 void * obj = GC_GCJ_MALLOC(size, klass->vtable);
334 #endif /* LIBGCJ_GC_DEBUG */
335 // In the non-debug case, the above two functions are defined
336 // as inline functions in boehm-gc.h. In the debug case we
337 // really want to take advantage of the definitions in gc_gcj.h.
339 // Allocate space for a new Java array.
340 // Used only for arrays of objects.
342 _Jv_AllocArray (jsize size, jclass klass)
346 #ifdef LIBGCJ_GC_DEBUG
347 // There isn't much to lose by scanning this conservatively.
348 // If we didn't, the mark proc would have to understand that
349 // it needed to skip the header.
350 obj = GC_MALLOC(size);
352 const jsize min_heap_addr = 16*1024;
353 // A heuristic. If size is less than this value, the size
354 // stored in the array can't possibly be misinterpreted as
355 // a pointer. Thus we lose nothing by scanning the object
356 // completely conservatively, since no misidentification can
359 if (size < min_heap_addr)
360 obj = GC_MALLOC(size);
362 obj = GC_generic_malloc (size, array_kind_x);
364 *((_Jv_VTable **) obj) = klass->vtable;
368 /* Allocate space for a new non-Java object, which does not have the usual
369 Java object header but may contain pointers to other GC'ed objects. */
371 _Jv_AllocRawObj (jsize size)
373 return (void *) GC_MALLOC (size ? size : 1);
377 call_finalizer (GC_PTR obj, GC_PTR client_data)
379 _Jv_FinalizerFunc *fn = (_Jv_FinalizerFunc *) client_data;
380 jobject jobj = (jobject) obj;
386 _Jv_RegisterFinalizer (void *object, _Jv_FinalizerFunc *meth)
388 GC_REGISTER_FINALIZER_NO_ORDER (object, call_finalizer, (GC_PTR) meth,
393 _Jv_RunFinalizers (void)
395 GC_invoke_finalizers ();
399 _Jv_RunAllFinalizers (void)
411 _Jv_GCTotalMemory (void)
413 return GC_get_heap_size ();
417 _Jv_GCFreeMemory (void)
419 return GC_get_free_bytes ();
423 _Jv_GCSetInitialHeapSize (size_t size)
425 size_t current = GC_get_heap_size ();
427 GC_expand_hp (size - current);
431 _Jv_GCSetMaximumHeapSize (size_t size)
433 GC_set_max_heap_size ((GC_word) size);
448 static void * handle_out_of_memory(size_t)
454 gcj_describe_type_fn(void *obj, char *out_buf)
456 _Jv_VTable *dt = *(_Jv_VTable **) obj;
458 if (! dt /* Shouldn't happen */)
460 strcpy(out_buf, "GCJ (bad)");
463 jclass klass = dt->clas;
464 if (!klass /* shouldn't happen */)
466 strcpy(out_buf, "GCJ (bad)");
469 jstring name = klass -> getName();
470 size_t len = name -> length();
471 if (len >= GC_TYPE_DESCR_LEN) len = GC_TYPE_DESCR_LEN - 1;
472 JvGetStringUTFRegion (name, 0, len, out_buf);
480 static bool gc_initialized;
487 // Ignore pointers that do not point to the start of an object.
488 GC_all_interior_pointers = 0;
491 // Tell the collector to ask us before scanning DSOs.
492 GC_register_has_static_roots_callback (_Jv_GC_has_static_roots);
495 // Configure the collector to use the bitmap marking descriptors that we
496 // stash in the class vtable.
497 // We always use mark proc descriptor 0, since the compiler knows
499 GC_init_gcj_malloc (0, (void *) _Jv_MarkObj);
501 // Cause an out of memory error to be thrown from the allocators,
502 // instead of returning 0. This is cheaper than checking on allocation.
503 GC_oom_fn = handle_out_of_memory;
505 GC_java_finalization = 1;
507 // We use a different mark procedure for object arrays. This code
508 // configures a different object `kind' for object array allocation and
510 array_free_list = GC_new_free_list();
511 proc = GC_new_proc((GC_mark_proc)_Jv_MarkArray);
512 array_kind_x = GC_new_kind(array_free_list, GC_MAKE_PROC (proc, 0), 0, 1);
514 // Arrange to have the GC print Java class names in backtraces, etc.
515 GC_register_describe_type_fn(GC_gcj_kind, gcj_describe_type_fn);
516 GC_register_describe_type_fn(GC_gcj_debug_kind, gcj_describe_type_fn);
519 #ifdef JV_HASH_SYNCHRONIZATION
520 // Allocate an object with a fake vtable pointer, which causes only
521 // the first field (beyond the fake vtable pointer) to be traced.
522 // Eventually this should probably be generalized.
524 static _Jv_VTable trace_one_vtable = {
526 (void *)(2 * sizeof(void *)),
527 // descriptor; scan 2 words incl. vtable ptr.
528 // Least significant bits must be zero to
529 // identify this as a length descriptor
534 _Jv_AllocTraceOne (jsize size /* includes vtable slot */)
536 return GC_GCJ_MALLOC (size, &trace_one_vtable);
539 // Ditto for two words.
540 // the first field (beyond the fake vtable pointer) to be traced.
541 // Eventually this should probably be generalized.
543 static _Jv_VTable trace_two_vtable =
546 (void *)(3 * sizeof(void *)),
547 // descriptor; scan 3 words incl. vtable ptr.
552 _Jv_AllocTraceTwo (jsize size /* includes vtable slot */)
554 return GC_GCJ_MALLOC (size, &trace_two_vtable);
557 #endif /* JV_HASH_SYNCHRONIZATION */
560 _Jv_GCInitializeFinalizers (void (*notifier) (void))
562 GC_finalize_on_demand = 1;
563 GC_finalizer_notifier = notifier;
567 _Jv_GCRegisterDisappearingLink (jobject *objp)
569 // This test helps to ensure that we meet a precondition of
570 // GC_general_register_disappearing_link, viz. "Obj must be a
571 // pointer to the first word of an object we allocated."
573 GC_general_register_disappearing_link ((GC_PTR *) objp, (GC_PTR) *objp);
577 _Jv_GCCanReclaimSoftReference (jobject)
579 // For now, always reclaim soft references. FIXME.
587 // We keep a store of the filenames of DSOs that need to be
588 // conservatively scanned by the garbage collector. During collection
589 // the gc calls _Jv_GC_has_static_roots() to see if the data segment
590 // of a DSO should be scanned.
591 typedef struct filename_node
594 struct filename_node *link;
597 #define FILENAME_STORE_SIZE 17
598 static filename_node *filename_store[FILENAME_STORE_SIZE];
600 // Find a filename in filename_store.
601 static filename_node **
602 find_file (const char *filename)
604 int index = strlen (filename) % FILENAME_STORE_SIZE;
605 filename_node **node = &filename_store[index];
609 if (strcmp ((*node)->name, filename) == 0)
611 node = &(*node)->link;
617 // Print the store of filenames of DSOs that need collection.
619 _Jv_print_gc_store (void)
621 for (int i = 0; i < FILENAME_STORE_SIZE; i++)
623 filename_node *node = filename_store[i];
626 fprintf (stderr, "%s\n", node->name);
632 // Create a new node in the store of libraries to collect.
633 static filename_node *
634 new_node (const char *filename)
636 filename_node *node = (filename_node*)_Jv_Malloc (sizeof (filename_node));
637 node->name = (char *)_Jv_Malloc (strlen (filename) + 1);
639 strcpy (node->name, filename);
644 // Nonzero if the gc should scan this lib.
646 _Jv_GC_has_static_roots (const char *filename, void *, size_t)
648 if (filename == NULL || strlen (filename) == 0)
649 // No filename; better safe than sorry.
652 filename_node **node = find_file (filename);
661 // Register the DSO that contains p for collection.
663 _Jv_RegisterLibForGc (const void *p __attribute__ ((__unused__)))
668 if (dladdr (p, &info) != 0)
670 filename_node **node = find_file (info.dli_fname);
672 *node = new_node (info.dli_fname);