OSDN Git Service

PR libgcj/26063, PR libgcj/17978, PR libgcj/10598:
[pf3gnuchains/gcc-fork.git] / libjava / boehm.cc
1 // boehm.cc - interface between libjava and Boehm GC.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4    Free Software Foundation
5
6    This file is part of libgcj.
7
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
10 details.  */
11
12 #include <config.h>
13
14 #include <stdio.h>
15 #include <limits.h>
16
17 #include <jvm.h>
18 #include <gcj/cni.h>
19
20 #include <java/lang/Class.h>
21 #include <java/lang/reflect/Modifier.h>
22 #include <java-interp.h>
23
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
28
29 extern "C"
30 {
31 #include <gc_config.h>
32
33 // Set GC_DEBUG before including gc.h!
34 #ifdef LIBGCJ_GC_DEBUG
35 # define GC_DEBUG
36 #endif
37
38 #include <gc_mark.h>
39 #include <gc_gcj.h>
40 #include <javaxfc.h>  // GC_finalize_all declaration.  
41
42 #ifdef THREAD_LOCAL_ALLOC
43 # define GC_REDIRECT_TO_LOCAL
44 # include <gc_local_alloc.h>
45 #endif
46
47   // From boehm's misc.c 
48   void GC_enable();
49   void GC_disable();
50 };
51
52 #define MAYBE_MARK(Obj, Top, Limit, Source)  \
53         Top=GC_MARK_AND_PUSH((GC_PTR) Obj, Top, Limit, (GC_PTR *) Source)
54
55 // `kind' index used when allocating Java arrays.
56 static int array_kind_x;
57
58 // Freelist used for Java arrays.
59 static void **array_free_list;
60
61 \f
62
63 // This is called by the GC during the mark phase.  It marks a Java
64 // object.  We use `void *' arguments and return, and not what the
65 // Boehm GC wants, to avoid pollution in our headers.
66 void *
67 _Jv_MarkObj (void *addr, void *msp, void *msl, void *env)
68 {
69   struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
70   struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
71
72   if (env == (void *)1) /* Object allocated with debug allocator.       */
73     addr = (GC_PTR)GC_USR_PTR_FROM_BASE(addr);
74   jobject obj = (jobject) addr;
75
76   _Jv_VTable *dt = *(_Jv_VTable **) addr;
77   // The object might not yet have its vtable set, or it might
78   // really be an object on the freelist.  In either case, the vtable slot
79   // will either be 0, or it will point to a cleared object.
80   // This assumes Java objects have size at least 3 words,
81   // including the header.   But this should remain true, since this
82   // should only be used with debugging allocation or with large objects.
83   if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
84     return mark_stack_ptr;
85   jclass klass = dt->clas;
86   GC_PTR p;
87
88   p = (GC_PTR) dt;
89   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
90
91 # ifndef JV_HASH_SYNCHRONIZATION
92     // Every object has a sync_info pointer.
93     p = (GC_PTR) obj->sync_info;
94     MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
95 # endif
96   // Mark the object's class.
97   p = (GC_PTR) klass;
98   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
99
100   if (__builtin_expect (klass == &java::lang::Class::class$, false))
101     {
102       // Currently we allocate some of the memory referenced from class objects
103       // as pointerfree memory, and then mark it more intelligently here.
104       // We ensure that the ClassClass mark descriptor forces invocation of
105       // this procedure.
106       // Correctness of this is subtle, but it looks OK to me for now.  For the incremental
107       // collector, we need to make sure that the class object is written whenever
108       // any of the subobjects are altered and may need rescanning.  This may be tricky
109       // during construction, and this may not be the right way to do this with
110       // incremental collection.
111       // If we overflow the mark stack, we will rescan the class object, so we should
112       // be OK.  The same applies if we redo the mark phase because win32 unmapped part
113       // of our root set.               - HB
114       jclass c = (jclass) addr;
115
116       p = (GC_PTR) c->name;
117       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
118       p = (GC_PTR) c->superclass;
119       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
120
121       p = (GC_PTR) c->constants.tags;
122       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
123       p = (GC_PTR) c->constants.data;
124       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
125
126       // If the class is an array, then the methods field holds a
127       // pointer to the element class.  If the class is primitive,
128       // then the methods field holds a pointer to the array class.
129       p = (GC_PTR) c->methods;
130       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
131
132       p = (GC_PTR) c->fields;
133       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
134
135       // The vtable might be allocated even for compiled code.
136       p = (GC_PTR) c->vtable;
137       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
138
139       p = (GC_PTR) c->interfaces;
140       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
141       p = (GC_PTR) c->loader;
142       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
143
144       // The dispatch tables can be allocated at runtime.
145       p = (GC_PTR) c->ancestors;
146       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
147
148       p = (GC_PTR) c->idt;
149       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
150
151       p = (GC_PTR) c->arrayclass;
152       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
153       p = (GC_PTR) c->protectionDomain;
154       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
155       p = (GC_PTR) c->hack_signers;
156       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
157       p = (GC_PTR) c->aux_info;
158       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
159     }
160   else
161     {
162       // NOTE: each class only holds information about the class
163       // itself.  So we must do the marking for the entire inheritance
164       // tree in order to mark all fields.  FIXME: what about
165       // interfaces?  We skip Object here, because Object only has a
166       // sync_info, and we handled that earlier.
167       // Note: occasionally `klass' can be null.  For instance, this
168       // can happen if a GC occurs between the point where an object
169       // is allocated and where the vtbl slot is set.
170       while (klass && klass != &java::lang::Object::class$)
171         {
172           jfieldID field = JvGetFirstInstanceField (klass);
173           jint max = JvNumInstanceFields (klass);
174
175           for (int i = 0; i < max; ++i)
176             {
177               if (JvFieldIsRef (field))
178                 {
179                   jobject val = JvGetObjectField (obj, field);
180                   p = (GC_PTR) val;
181                   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
182                 }
183               field = field->getNextField ();
184             }
185           klass = klass->getSuperclass();
186         }
187     }
188
189   return mark_stack_ptr;
190 }
191
192 // This is called by the GC during the mark phase.  It marks a Java
193 // array (of objects).  We use `void *' arguments and return, and not
194 // what the Boehm GC wants, to avoid pollution in our headers.
195 void *
196 _Jv_MarkArray (void *addr, void *msp, void *msl, void *env)
197 {
198   struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
199   struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
200
201   if (env == (void *)1) /* Object allocated with debug allocator.       */
202     addr = (void *)GC_USR_PTR_FROM_BASE(addr);
203   jobjectArray array = (jobjectArray) addr;
204
205   _Jv_VTable *dt = *(_Jv_VTable **) addr;
206   // Assumes size >= 3 words.  That's currently true since arrays have
207   // a vtable, sync pointer, and size.  If the sync pointer goes away,
208   // we may need to round up the size.
209   if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
210     return mark_stack_ptr;
211   jclass klass = dt->clas;
212   GC_PTR p;
213
214   p = (GC_PTR) dt;
215   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
216
217 # ifndef JV_HASH_SYNCHRONIZATION
218     // Every object has a sync_info pointer.
219     p = (GC_PTR) array->sync_info;
220     MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
221 # endif
222   // Mark the object's class.
223   p = (GC_PTR) klass;
224   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, &(dt -> clas));
225
226   for (int i = 0; i < JvGetArrayLength (array); ++i)
227     {
228       jobject obj = elements (array)[i];
229       p = (GC_PTR) obj;
230       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
231     }
232
233   return mark_stack_ptr;
234 }
235
236 // Generate a GC marking descriptor for a class.
237 //
238 // We assume that the gcj mark proc has index 0.  This is a dubious assumption,
239 // since another one could be registered first.  But the compiler also
240 // knows this, so in that case everything else will break, too.
241 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
242
243 void *
244 _Jv_BuildGCDescr(jclass self)
245 {
246   jlong desc = 0;
247   jint bits_per_word = CHAR_BIT * sizeof (void *);
248
249   // Note: for now we only consider a bitmap mark descriptor.  We
250   // could also handle the case where the first N fields of a type are
251   // references.  However, this is not very likely to be used by many
252   // classes, and it is easier to compute things this way.
253
254   // The vtable pointer.
255   desc |= 1ULL << (bits_per_word - 1);
256 #ifndef JV_HASH_SYNCHRONIZATION
257   // The sync_info field.
258   desc |= 1ULL << (bits_per_word - 2);
259 #endif
260
261   for (jclass klass = self; klass != NULL; klass = klass->getSuperclass())
262     {
263       jfieldID field = JvGetFirstInstanceField(klass);
264       int count = JvNumInstanceFields(klass);
265
266       for (int i = 0; i < count; ++i)
267         {
268           if (field->isRef())
269             {
270               unsigned int off = field->getOffset();
271               // If we run into a weird situation, we bail.
272               if (off % sizeof (void *) != 0)
273                 return (void *) (GCJ_DEFAULT_DESCR);
274               off /= sizeof (void *);
275               // If we find a field outside the range of our bitmap,
276               // fall back to procedure marker. The bottom 2 bits are
277               // reserved.
278               if (off >= (unsigned) bits_per_word - 2)
279                 return (void *) (GCJ_DEFAULT_DESCR);
280               desc |= 1ULL << (bits_per_word - off - 1);
281             }
282
283           field = field->getNextField();
284         }
285     }
286
287   // For bitmap mark type, bottom bits are 01.
288   desc |= 1;
289   // Bogus warning avoidance (on many platforms).
290   return (void *) (unsigned long) desc;
291 }
292
293 // Allocate some space that is known to be pointer-free.
294 void *
295 _Jv_AllocBytes (jsize size)
296 {
297   void *r = GC_MALLOC_ATOMIC (size);
298   // We have to explicitly zero memory here, as the GC doesn't
299   // guarantee that PTRFREE allocations are zeroed.  Note that we
300   // don't have to do this for other allocation types because we set
301   // the `ok_init' flag in the type descriptor.
302   memset (r, 0, size);
303   return r;
304 }
305
306 #ifdef LIBGCJ_GC_DEBUG
307
308 void *
309 _Jv_AllocObj (jsize size, jclass klass)
310 {
311   return GC_GCJ_MALLOC (size, klass->vtable);
312 }
313
314 void *
315 _Jv_AllocPtrFreeObj (jsize size, jclass klass)
316 {
317 #ifdef JV_HASH_SYNCHRONIZATION
318   void * obj = GC_MALLOC_ATOMIC(size);
319   *((_Jv_VTable **) obj) = klass->vtable;
320 #else
321   void * obj = GC_GCJ_MALLOC(size, klass->vtable);
322 #endif
323   return obj;
324 }
325
326 #endif /* LIBGCJ_GC_DEBUG */
327 // In the non-debug case, the above two functions are defined
328 // as inline functions in boehm-gc.h.  In the debug case we
329 // really want to take advantage of the definitions in gc_gcj.h.
330
331 // Allocate space for a new Java array.
332 // Used only for arrays of objects.
333 void *
334 _Jv_AllocArray (jsize size, jclass klass)
335 {
336   void *obj;
337
338 #ifdef LIBGCJ_GC_DEBUG
339   // There isn't much to lose by scanning this conservatively.
340   // If we didn't, the mark proc would have to understand that
341   // it needed to skip the header.
342   obj = GC_MALLOC(size);
343 #else
344   const jsize min_heap_addr = 16*1024;
345   // A heuristic.  If size is less than this value, the size
346   // stored in the array can't possibly be misinterpreted as
347   // a pointer.   Thus we lose nothing by scanning the object
348   // completely conservatively, since no misidentification can
349   // take place.
350   
351   if (size < min_heap_addr) 
352     obj = GC_MALLOC(size);
353   else 
354     obj = GC_generic_malloc (size, array_kind_x);
355 #endif
356   *((_Jv_VTable **) obj) = klass->vtable;
357   return obj;
358 }
359
360 /* Allocate space for a new non-Java object, which does not have the usual 
361    Java object header but may contain pointers to other GC'ed objects. */
362 void *
363 _Jv_AllocRawObj (jsize size)
364 {
365   return (void *) GC_MALLOC (size ? size : 1);
366 }
367
368 static void
369 call_finalizer (GC_PTR obj, GC_PTR client_data)
370 {
371   _Jv_FinalizerFunc *fn = (_Jv_FinalizerFunc *) client_data;
372   jobject jobj = (jobject) obj;
373
374   (*fn) (jobj);
375 }
376
377 void
378 _Jv_RegisterFinalizer (void *object, _Jv_FinalizerFunc *meth)
379 {
380   GC_REGISTER_FINALIZER_NO_ORDER (object, call_finalizer, (GC_PTR) meth,
381                                   NULL, NULL);
382 }
383
384 void
385 _Jv_RunFinalizers (void)
386 {
387   GC_invoke_finalizers ();
388 }
389
390 void
391 _Jv_RunAllFinalizers (void)
392 {
393   GC_finalize_all ();
394 }
395
396 void
397 _Jv_RunGC (void)
398 {
399   GC_gcollect ();
400 }
401
402 long
403 _Jv_GCTotalMemory (void)
404 {
405   return GC_get_heap_size ();
406 }
407
408 long
409 _Jv_GCFreeMemory (void)
410 {
411   return GC_get_free_bytes ();
412 }
413
414 void
415 _Jv_GCSetInitialHeapSize (size_t size)
416 {
417   size_t current = GC_get_heap_size ();
418   if (size > current)
419     GC_expand_hp (size - current);
420 }
421
422 void
423 _Jv_GCSetMaximumHeapSize (size_t size)
424 {
425   GC_set_max_heap_size ((GC_word) size);
426 }
427
428 void
429 _Jv_DisableGC (void)
430 {
431   GC_disable();
432 }
433
434 void
435 _Jv_EnableGC (void)
436 {
437   GC_enable();
438 }
439
440 static void * handle_out_of_memory(size_t)
441 {
442   _Jv_ThrowNoMemory();
443 }
444
445 static void
446 gcj_describe_type_fn(void *obj, char *out_buf)
447 {
448   _Jv_VTable *dt = *(_Jv_VTable **) obj;
449
450   if (! dt /* Shouldn't happen */)
451     {
452       strcpy(out_buf, "GCJ (bad)");
453       return;
454     }
455   jclass klass = dt->clas;
456   if (!klass /* shouldn't happen */)
457     {
458       strcpy(out_buf, "GCJ (bad)");
459       return;
460     }
461   jstring name = klass -> getName();
462   size_t len = name -> length();
463   if (len >= GC_TYPE_DESCR_LEN) len = GC_TYPE_DESCR_LEN - 1;
464   JvGetStringUTFRegion (name, 0, len, out_buf);
465   out_buf[len] = '\0';
466 }
467
468 void
469 _Jv_InitGC (void)
470 {
471   int proc;
472
473   // Ignore pointers that do not point to the start of an object.
474   GC_all_interior_pointers = 0;
475
476   // Configure the collector to use the bitmap marking descriptors that we
477   // stash in the class vtable.
478   // We always use mark proc descriptor 0, since the compiler knows
479   // about it.
480   GC_init_gcj_malloc (0, (void *) _Jv_MarkObj);  
481
482   // Cause an out of memory error to be thrown from the allocators,
483   // instead of returning 0.  This is cheaper than checking on allocation.
484   GC_oom_fn = handle_out_of_memory;
485
486   GC_java_finalization = 1;
487
488   // We use a different mark procedure for object arrays. This code 
489   // configures a different object `kind' for object array allocation and
490   // marking.
491   array_free_list = GC_new_free_list();
492   proc = GC_new_proc((GC_mark_proc)_Jv_MarkArray);
493   array_kind_x = GC_new_kind(array_free_list, GC_MAKE_PROC (proc, 0), 0, 1);
494
495   // Arrange to have the GC print Java class names in backtraces, etc.
496   GC_register_describe_type_fn(GC_gcj_kind, gcj_describe_type_fn);
497   GC_register_describe_type_fn(GC_gcj_debug_kind, gcj_describe_type_fn);
498 }
499
500 #ifdef JV_HASH_SYNCHRONIZATION
501 // Allocate an object with a fake vtable pointer, which causes only
502 // the first field (beyond the fake vtable pointer) to be traced.
503 // Eventually this should probably be generalized.
504
505 static _Jv_VTable trace_one_vtable = {
506     0,                  // class pointer
507     (void *)(2 * sizeof(void *)),
508                         // descriptor; scan 2 words incl. vtable ptr.
509                         // Least significant bits must be zero to
510                         // identify this as a length descriptor
511     {0}                 // First method
512 };
513
514 void *
515 _Jv_AllocTraceOne (jsize size /* includes vtable slot */) 
516 {
517   return GC_GCJ_MALLOC (size, &trace_one_vtable);
518 }
519
520 // Ditto for two words.
521 // the first field (beyond the fake vtable pointer) to be traced.
522 // Eventually this should probably be generalized.
523
524 static _Jv_VTable trace_two_vtable =
525 {
526   0,                    // class pointer
527   (void *)(3 * sizeof(void *)),
528                         // descriptor; scan 3 words incl. vtable ptr.
529   {0}                   // First method
530 };
531
532 void *
533 _Jv_AllocTraceTwo (jsize size /* includes vtable slot */) 
534 {
535   return GC_GCJ_MALLOC (size, &trace_two_vtable);
536 }
537
538 #endif /* JV_HASH_SYNCHRONIZATION */
539
540 void
541 _Jv_GCInitializeFinalizers (void (*notifier) (void))
542 {
543   GC_finalize_on_demand = 1;
544   GC_finalizer_notifier = notifier;
545 }
546
547 void
548 _Jv_GCRegisterDisappearingLink (jobject *objp)
549 {
550   // This test helps to ensure that we meet a precondition of
551   // GC_general_register_disappearing_link, viz. "Obj must be a
552   // pointer to the first word of an object we allocated."
553   if (GC_base(*objp))
554     GC_general_register_disappearing_link ((GC_PTR *) objp, (GC_PTR) *objp);
555 }
556
557 jboolean
558 _Jv_GCCanReclaimSoftReference (jobject)
559 {
560   // For now, always reclaim soft references.  FIXME.
561   return true;
562 }