PR libgcj/27271:
[official-gcc.git] / libjava / boehm.cc
blob3b013dae3d6bfa8ae3d1b4111c64e2874c7ddc87
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
10 details. */
12 #include <config.h>
14 #include <stdio.h>
15 #include <limits.h>
17 #include <jvm.h>
18 #include <gcj/cni.h>
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.
26 #undef TRUE
27 #undef FALSE
29 // We include two autoconf headers. Avoid multiple definition warnings.
30 #undef PACKAGE_NAME
31 #undef PACKAGE_STRING
32 #undef PACKAGE_TARNAME
33 #undef PACKAGE_VERSION
35 #ifdef HAVE_DLFCN_H
36 #undef _GNU_SOURCE
37 #define _GNU_SOURCE
38 #include <dlfcn.h>
39 #endif
41 extern "C"
43 #include <gc_config.h>
45 // Set GC_DEBUG before including gc.h!
46 #ifdef LIBGCJ_GC_DEBUG
47 # define GC_DEBUG
48 #endif
50 #include <gc_mark.h>
51 #include <gc_gcj.h>
52 #include <javaxfc.h> // GC_finalize_all declaration.
54 #ifdef THREAD_LOCAL_ALLOC
55 # define GC_REDIRECT_TO_LOCAL
56 # include <gc_local_alloc.h>
57 #endif
59 // From boehm's misc.c
60 void GC_enable();
61 void GC_disable();
64 #define MAYBE_MARK(Obj, Top, Limit, Source) \
65 Top=GC_MARK_AND_PUSH((GC_PTR) Obj, Top, Limit, (GC_PTR *) Source)
67 // `kind' index used when allocating Java arrays.
68 static int array_kind_x;
70 // Freelist used for Java arrays.
71 static void **array_free_list;
73 static int _Jv_GC_has_static_roots (const char *filename, void *, size_t);
77 // This is called by the GC during the mark phase. It marks a Java
78 // object. We use `void *' arguments and return, and not what the
79 // Boehm GC wants, to avoid pollution in our headers.
80 void *
81 _Jv_MarkObj (void *addr, void *msp, void *msl, void *env)
83 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
84 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
86 if (env == (void *)1) /* Object allocated with debug allocator. */
87 addr = (GC_PTR)GC_USR_PTR_FROM_BASE(addr);
88 jobject obj = (jobject) addr;
90 _Jv_VTable *dt = *(_Jv_VTable **) addr;
91 // The object might not yet have its vtable set, or it might
92 // really be an object on the freelist. In either case, the vtable slot
93 // will either be 0, or it will point to a cleared object.
94 // This assumes Java objects have size at least 3 words,
95 // including the header. But this should remain true, since this
96 // should only be used with debugging allocation or with large objects.
97 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
98 return mark_stack_ptr;
99 jclass klass = dt->clas;
100 GC_PTR p;
102 p = (GC_PTR) dt;
103 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
105 # ifndef JV_HASH_SYNCHRONIZATION
106 // Every object has a sync_info pointer.
107 p = (GC_PTR) obj->sync_info;
108 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
109 # endif
111 if (__builtin_expect (klass == &java::lang::Class::class$, false))
113 // Currently we allocate some of the memory referenced from class objects
114 // as pointerfree memory, and then mark it more intelligently here.
115 // We ensure that the ClassClass mark descriptor forces invocation of
116 // this procedure.
117 // Correctness of this is subtle, but it looks OK to me for now. For the incremental
118 // collector, we need to make sure that the class object is written whenever
119 // any of the subobjects are altered and may need rescanning. This may be tricky
120 // during construction, and this may not be the right way to do this with
121 // incremental collection.
122 // If we overflow the mark stack, we will rescan the class object, so we should
123 // be OK. The same applies if we redo the mark phase because win32 unmapped part
124 // of our root set. - HB
125 jclass c = (jclass) addr;
127 p = (GC_PTR) c->name;
128 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
129 p = (GC_PTR) c->superclass;
130 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
132 p = (GC_PTR) c->constants.tags;
133 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
134 p = (GC_PTR) c->constants.data;
135 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
137 // If the class is an array, then the methods field holds a
138 // pointer to the element class. If the class is primitive,
139 // then the methods field holds a pointer to the array class.
140 p = (GC_PTR) c->methods;
141 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
143 p = (GC_PTR) c->fields;
144 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
146 // The vtable might be allocated even for compiled code.
147 p = (GC_PTR) c->vtable;
148 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
150 p = (GC_PTR) c->interfaces;
151 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
152 p = (GC_PTR) c->loader;
153 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
155 // The dispatch tables can be allocated at runtime.
156 p = (GC_PTR) c->ancestors;
157 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
159 p = (GC_PTR) c->idt;
160 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
162 p = (GC_PTR) c->arrayclass;
163 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
164 p = (GC_PTR) c->protectionDomain;
165 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
166 p = (GC_PTR) c->hack_signers;
167 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
168 p = (GC_PTR) c->aux_info;
169 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
171 // The class chain must be marked for runtime-allocated Classes
172 // loaded by the bootstrap ClassLoader.
173 p = (GC_PTR) c->next_or_version;
174 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
176 else
178 // NOTE: each class only holds information about the class
179 // itself. So we must do the marking for the entire inheritance
180 // tree in order to mark all fields. FIXME: what about
181 // interfaces? We skip Object here, because Object only has a
182 // sync_info, and we handled that earlier.
183 // Note: occasionally `klass' can be null. For instance, this
184 // can happen if a GC occurs between the point where an object
185 // is allocated and where the vtbl slot is set.
186 while (klass && klass != &java::lang::Object::class$)
188 jfieldID field = JvGetFirstInstanceField (klass);
189 jint max = JvNumInstanceFields (klass);
191 for (int i = 0; i < max; ++i)
193 if (JvFieldIsRef (field))
195 jobject val = JvGetObjectField (obj, field);
196 p = (GC_PTR) val;
197 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
199 field = field->getNextField ();
201 klass = klass->getSuperclass();
205 return mark_stack_ptr;
208 // This is called by the GC during the mark phase. It marks a Java
209 // array (of objects). We use `void *' arguments and return, and not
210 // what the Boehm GC wants, to avoid pollution in our headers.
211 void *
212 _Jv_MarkArray (void *addr, void *msp, void *msl, void *env)
214 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
215 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
217 if (env == (void *)1) /* Object allocated with debug allocator. */
218 addr = (void *)GC_USR_PTR_FROM_BASE(addr);
219 jobjectArray array = (jobjectArray) addr;
221 _Jv_VTable *dt = *(_Jv_VTable **) addr;
222 // Assumes size >= 3 words. That's currently true since arrays have
223 // a vtable, sync pointer, and size. If the sync pointer goes away,
224 // we may need to round up the size.
225 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
226 return mark_stack_ptr;
227 GC_PTR p;
229 p = (GC_PTR) dt;
230 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
232 # ifndef JV_HASH_SYNCHRONIZATION
233 // Every object has a sync_info pointer.
234 p = (GC_PTR) array->sync_info;
235 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
236 # endif
238 for (int i = 0; i < JvGetArrayLength (array); ++i)
240 jobject obj = elements (array)[i];
241 p = (GC_PTR) obj;
242 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
245 return mark_stack_ptr;
248 // Generate a GC marking descriptor for a class.
250 // We assume that the gcj mark proc has index 0. This is a dubious assumption,
251 // since another one could be registered first. But the compiler also
252 // knows this, so in that case everything else will break, too.
253 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
255 void *
256 _Jv_BuildGCDescr(jclass self)
258 jlong desc = 0;
259 jint bits_per_word = CHAR_BIT * sizeof (void *);
261 // Note: for now we only consider a bitmap mark descriptor. We
262 // could also handle the case where the first N fields of a type are
263 // references. However, this is not very likely to be used by many
264 // classes, and it is easier to compute things this way.
266 // The vtable pointer.
267 desc |= 1ULL << (bits_per_word - 1);
268 #ifndef JV_HASH_SYNCHRONIZATION
269 // The sync_info field.
270 desc |= 1ULL << (bits_per_word - 2);
271 #endif
273 for (jclass klass = self; klass != NULL; klass = klass->getSuperclass())
275 jfieldID field = JvGetFirstInstanceField(klass);
276 int count = JvNumInstanceFields(klass);
278 for (int i = 0; i < count; ++i)
280 if (field->isRef())
282 unsigned int off = field->getOffset();
283 // If we run into a weird situation, we bail.
284 if (off % sizeof (void *) != 0)
285 return (void *) (GCJ_DEFAULT_DESCR);
286 off /= sizeof (void *);
287 // If we find a field outside the range of our bitmap,
288 // fall back to procedure marker. The bottom 2 bits are
289 // reserved.
290 if (off >= (unsigned) bits_per_word - 2)
291 return (void *) (GCJ_DEFAULT_DESCR);
292 desc |= 1ULL << (bits_per_word - off - 1);
295 field = field->getNextField();
299 // For bitmap mark type, bottom bits are 01.
300 desc |= 1;
301 // Bogus warning avoidance (on many platforms).
302 return (void *) (unsigned long) desc;
305 // Allocate some space that is known to be pointer-free.
306 void *
307 _Jv_AllocBytes (jsize size)
309 void *r = GC_MALLOC_ATOMIC (size);
310 // We have to explicitly zero memory here, as the GC doesn't
311 // guarantee that PTRFREE allocations are zeroed. Note that we
312 // don't have to do this for other allocation types because we set
313 // the `ok_init' flag in the type descriptor.
314 memset (r, 0, size);
315 return r;
318 #ifdef LIBGCJ_GC_DEBUG
320 void *
321 _Jv_AllocObj (jsize size, jclass klass)
323 return GC_GCJ_MALLOC (size, klass->vtable);
326 void *
327 _Jv_AllocPtrFreeObj (jsize size, jclass klass)
329 #ifdef JV_HASH_SYNCHRONIZATION
330 void * obj = GC_MALLOC_ATOMIC(size);
331 *((_Jv_VTable **) obj) = klass->vtable;
332 #else
333 void * obj = GC_GCJ_MALLOC(size, klass->vtable);
334 #endif
335 return obj;
338 #endif /* LIBGCJ_GC_DEBUG */
339 // In the non-debug case, the above two functions are defined
340 // as inline functions in boehm-gc.h. In the debug case we
341 // really want to take advantage of the definitions in gc_gcj.h.
343 // Allocate space for a new Java array.
344 // Used only for arrays of objects.
345 void *
346 _Jv_AllocArray (jsize size, jclass klass)
348 void *obj;
350 #ifdef LIBGCJ_GC_DEBUG
351 // There isn't much to lose by scanning this conservatively.
352 // If we didn't, the mark proc would have to understand that
353 // it needed to skip the header.
354 obj = GC_MALLOC(size);
355 #else
356 const jsize min_heap_addr = 16*1024;
357 // A heuristic. If size is less than this value, the size
358 // stored in the array can't possibly be misinterpreted as
359 // a pointer. Thus we lose nothing by scanning the object
360 // completely conservatively, since no misidentification can
361 // take place.
363 if (size < min_heap_addr)
364 obj = GC_MALLOC(size);
365 else
366 obj = GC_generic_malloc (size, array_kind_x);
367 #endif
368 *((_Jv_VTable **) obj) = klass->vtable;
369 return obj;
372 /* Allocate space for a new non-Java object, which does not have the usual
373 Java object header but may contain pointers to other GC'ed objects. */
374 void *
375 _Jv_AllocRawObj (jsize size)
377 return (void *) GC_MALLOC (size ? size : 1);
380 static void
381 call_finalizer (GC_PTR obj, GC_PTR client_data)
383 _Jv_FinalizerFunc *fn = (_Jv_FinalizerFunc *) client_data;
384 jobject jobj = (jobject) obj;
386 (*fn) (jobj);
389 void
390 _Jv_RegisterFinalizer (void *object, _Jv_FinalizerFunc *meth)
392 GC_REGISTER_FINALIZER_NO_ORDER (object, call_finalizer, (GC_PTR) meth,
393 NULL, NULL);
396 void
397 _Jv_RunFinalizers (void)
399 GC_invoke_finalizers ();
402 void
403 _Jv_RunAllFinalizers (void)
405 GC_finalize_all ();
408 void
409 _Jv_RunGC (void)
411 GC_gcollect ();
414 long
415 _Jv_GCTotalMemory (void)
417 return GC_get_heap_size ();
420 long
421 _Jv_GCFreeMemory (void)
423 return GC_get_free_bytes ();
426 void
427 _Jv_GCSetInitialHeapSize (size_t size)
429 size_t current = GC_get_heap_size ();
430 if (size > current)
431 GC_expand_hp (size - current);
434 void
435 _Jv_GCSetMaximumHeapSize (size_t size)
437 GC_set_max_heap_size ((GC_word) size);
440 void
441 _Jv_DisableGC (void)
443 GC_disable();
446 void
447 _Jv_EnableGC (void)
449 GC_enable();
452 static void * handle_out_of_memory(size_t)
454 _Jv_ThrowNoMemory();
457 static void
458 gcj_describe_type_fn(void *obj, char *out_buf)
460 _Jv_VTable *dt = *(_Jv_VTable **) obj;
462 if (! dt /* Shouldn't happen */)
464 strcpy(out_buf, "GCJ (bad)");
465 return;
467 jclass klass = dt->clas;
468 if (!klass /* shouldn't happen */)
470 strcpy(out_buf, "GCJ (bad)");
471 return;
473 jstring name = klass -> getName();
474 size_t len = name -> length();
475 if (len >= GC_TYPE_DESCR_LEN) len = GC_TYPE_DESCR_LEN - 1;
476 JvGetStringUTFRegion (name, 0, len, out_buf);
477 out_buf[len] = '\0';
480 void
481 _Jv_InitGC (void)
483 int proc;
484 static bool gc_initialized;
486 if (gc_initialized)
487 return;
489 gc_initialized = 1;
491 // Ignore pointers that do not point to the start of an object.
492 GC_all_interior_pointers = 0;
494 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
495 // Tell the collector to ask us before scanning DSOs.
496 GC_register_has_static_roots_callback (_Jv_GC_has_static_roots);
497 #endif
499 // Configure the collector to use the bitmap marking descriptors that we
500 // stash in the class vtable.
501 // We always use mark proc descriptor 0, since the compiler knows
502 // about it.
503 GC_init_gcj_malloc (0, (void *) _Jv_MarkObj);
505 // Cause an out of memory error to be thrown from the allocators,
506 // instead of returning 0. This is cheaper than checking on allocation.
507 GC_oom_fn = handle_out_of_memory;
509 GC_java_finalization = 1;
511 // We use a different mark procedure for object arrays. This code
512 // configures a different object `kind' for object array allocation and
513 // marking.
514 array_free_list = GC_new_free_list();
515 proc = GC_new_proc((GC_mark_proc)_Jv_MarkArray);
516 array_kind_x = GC_new_kind(array_free_list, GC_MAKE_PROC (proc, 0), 0, 1);
518 // Arrange to have the GC print Java class names in backtraces, etc.
519 GC_register_describe_type_fn(GC_gcj_kind, gcj_describe_type_fn);
520 GC_register_describe_type_fn(GC_gcj_debug_kind, gcj_describe_type_fn);
523 #ifdef JV_HASH_SYNCHRONIZATION
524 // Allocate an object with a fake vtable pointer, which causes only
525 // the first field (beyond the fake vtable pointer) to be traced.
526 // Eventually this should probably be generalized.
528 static _Jv_VTable trace_one_vtable = {
529 0, // class pointer
530 (void *)(2 * sizeof(void *)),
531 // descriptor; scan 2 words incl. vtable ptr.
532 // Least significant bits must be zero to
533 // identify this as a length descriptor
534 {0} // First method
537 void *
538 _Jv_AllocTraceOne (jsize size /* includes vtable slot */)
540 return GC_GCJ_MALLOC (size, &trace_one_vtable);
543 // Ditto for two words.
544 // the first field (beyond the fake vtable pointer) to be traced.
545 // Eventually this should probably be generalized.
547 static _Jv_VTable trace_two_vtable =
549 0, // class pointer
550 (void *)(3 * sizeof(void *)),
551 // descriptor; scan 3 words incl. vtable ptr.
552 {0} // First method
555 void *
556 _Jv_AllocTraceTwo (jsize size /* includes vtable slot */)
558 return GC_GCJ_MALLOC (size, &trace_two_vtable);
561 #endif /* JV_HASH_SYNCHRONIZATION */
563 void
564 _Jv_GCInitializeFinalizers (void (*notifier) (void))
566 GC_finalize_on_demand = 1;
567 GC_finalizer_notifier = notifier;
570 void
571 _Jv_GCRegisterDisappearingLink (jobject *objp)
573 // This test helps to ensure that we meet a precondition of
574 // GC_general_register_disappearing_link, viz. "Obj must be a
575 // pointer to the first word of an object we allocated."
576 if (GC_base(*objp))
577 GC_general_register_disappearing_link ((GC_PTR *) objp, (GC_PTR) *objp);
580 jboolean
581 _Jv_GCCanReclaimSoftReference (jobject)
583 // For now, always reclaim soft references. FIXME.
584 return true;
589 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
591 // We keep a store of the filenames of DSOs that need to be
592 // conservatively scanned by the garbage collector. During collection
593 // the gc calls _Jv_GC_has_static_roots() to see if the data segment
594 // of a DSO should be scanned.
595 typedef struct filename_node
597 char *name;
598 struct filename_node *link;
599 } filename_node;
601 #define FILENAME_STORE_SIZE 17
602 static filename_node *filename_store[FILENAME_STORE_SIZE];
604 // Find a filename in filename_store.
605 static filename_node **
606 find_file (const char *filename)
608 int index = strlen (filename) % FILENAME_STORE_SIZE;
609 filename_node **node = &filename_store[index];
611 while (*node)
613 if (strcmp ((*node)->name, filename) == 0)
614 return node;
615 node = &(*node)->link;
618 return node;
621 // Print the store of filenames of DSOs that need collection.
622 void
623 _Jv_print_gc_store (void)
625 for (int i = 0; i < FILENAME_STORE_SIZE; i++)
627 filename_node *node = filename_store[i];
628 while (node)
630 fprintf (stderr, "%s\n", node->name);
631 node = node->link;
636 // Create a new node in the store of libraries to collect.
637 static filename_node *
638 new_node (const char *filename)
640 filename_node *node = (filename_node*)_Jv_Malloc (sizeof (filename_node));
641 node->name = (char *)_Jv_Malloc (strlen (filename) + 1);
642 node->link = NULL;
643 strcpy (node->name, filename);
645 return node;
648 // Nonzero if the gc should scan this lib.
649 static int
650 _Jv_GC_has_static_roots (const char *filename, void *, size_t)
652 if (filename == NULL || strlen (filename) == 0)
653 // No filename; better safe than sorry.
654 return 1;
656 filename_node **node = find_file (filename);
657 if (*node)
658 return 1;
660 return 0;
663 #endif
665 // Register the DSO that contains p for collection.
666 void
667 _Jv_RegisterLibForGc (const void *p __attribute__ ((__unused__)))
669 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
670 Dl_info info;
672 if (dladdr (const_cast<void *>(p), &info) != 0)
674 filename_node **node = find_file (info.dli_fname);
675 if (! *node)
676 *node = new_node (info.dli_fname);
678 #endif
681 #if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
682 && !defined(GC_WIN32_THREADS) && !defined(GC_DARWIN_THREADS)
684 void
685 _Jv_SuspendThread (_Jv_Thread_t *thread)
687 GC_suspend_thread (_Jv_GetPlatformThreadID (thread));
690 void
691 _Jv_ResumeThread (_Jv_Thread_t *thread)
693 GC_resume_thread (_Jv_GetPlatformThreadID (thread));
696 #endif