OSDN Git Service

2002-12-19 Anthony Green <green@redhat.com>
[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  Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 #include <config.h>
12
13 #include <stdio.h>
14
15 #include <jvm.h>
16 #include <gcj/cni.h>
17
18 #include <java/lang/Class.h>
19 #include <java/lang/reflect/Modifier.h>
20 #include <java-interp.h>
21
22 // More nastiness: the GC wants to define TRUE and FALSE.  We don't
23 // need the Java definitions (themselves a hack), so we undefine them.
24 #undef TRUE
25 #undef FALSE
26
27 extern "C"
28 {
29 #include <private/gc_pmark.h>
30 #include <gc_gcj.h>
31
32 #ifdef THREAD_LOCAL_ALLOC
33 # define GC_REDIRECT_TO_LOCAL
34 # include <gc_local_alloc.h>
35 #endif
36
37   // These aren't declared in any Boehm GC header.
38   void GC_finalize_all (void);
39   ptr_t GC_debug_generic_malloc (size_t size, int k, GC_EXTRA_PARAMS);
40 };
41
42 #define MAYBE_MARK(Obj, Top, Limit, Source, Exit)  \
43         Top=GC_MARK_AND_PUSH((GC_PTR)Obj, Top, Limit, (GC_PTR *)Source)
44
45 // `kind' index used when allocating Java arrays.
46 static int array_kind_x;
47
48 // Freelist used for Java arrays.
49 static ptr_t *array_free_list;
50
51 // Lock used to protect access to Boehm's GC_enable/GC_disable functions.
52 static _Jv_Mutex_t disable_gc_mutex;
53
54 \f
55
56 // This is called by the GC during the mark phase.  It marks a Java
57 // object.  We use `void *' arguments and return, and not what the
58 // Boehm GC wants, to avoid pollution in our headers.
59 void *
60 _Jv_MarkObj (void *addr, void *msp, void *msl, void * /* env */)
61 {
62   mse *mark_stack_ptr = (mse *) msp;
63   mse *mark_stack_limit = (mse *) msl;
64   jobject obj = (jobject) addr;
65
66   // FIXME: if env is 1, this object was allocated through the debug
67   // interface, and addr points to the beginning of the debug header.
68   // In that case, we should really add the size of the header to addr.
69
70   _Jv_VTable *dt = *(_Jv_VTable **) addr;
71   // The object might not yet have its vtable set, or it might
72   // really be an object on the freelist.  In either case, the vtable slot
73   // will either be 0, or it will point to a cleared object.
74   // This assumes Java objects have size at least 3 words,
75   // including the header.   But this should remain true, since this
76   // should only be used with debugging allocation or with large objects.
77   if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
78     return mark_stack_ptr;
79   jclass klass = dt->clas;
80   ptr_t p;
81
82 # ifndef JV_HASH_SYNCHRONIZATION
83     // Every object has a sync_info pointer.
84     p = (ptr_t) obj->sync_info;
85     MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj, o1label);
86 # endif
87   // Mark the object's class.
88   p = (ptr_t) klass;
89   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj, o2label);
90
91   if (__builtin_expect (klass == &java::lang::Class::class$, false))
92     {
93       // Currently we allocate some of the memory referenced from class objects
94       // as pointerfree memory, and then mark it more intelligently here.
95       // We ensure that the ClassClass mark descriptor forces invocation of
96       // this procedure.
97       // Correctness of this is subtle, but it looks OK to me for now.  For the incremental
98       // collector, we need to make sure that the class object is written whenever
99       // any of the subobjects are altered and may need rescanning.  This may be tricky
100       // during construction, and this may not be the right way to do this with
101       // incremental collection.
102       // If we overflow the mark stack, we will rescan the class object, so we should
103       // be OK.  The same applies if we redo the mark phase because win32 unmapped part
104       // of our root set.               - HB
105       jclass c = (jclass) addr;
106
107       p = (ptr_t) c->name;
108       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c3label);
109       p = (ptr_t) c->superclass;
110       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c4label);
111       for (int i = 0; i < c->constants.size; ++i)
112         {
113           /* FIXME: We could make this more precise by using the tags -KKT */
114           p = (ptr_t) c->constants.data[i].p;
115           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c5label);
116         }
117
118 #ifdef INTERPRETER
119       if (_Jv_IsInterpretedClass (c))
120         {
121           p = (ptr_t) c->constants.tags;
122           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c5alabel);
123           p = (ptr_t) c->constants.data;
124           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c5blabel);
125           p = (ptr_t) c->vtable;
126           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c5clabel);
127         }
128 #endif
129
130       // If the class is an array, then the methods field holds a
131       // pointer to the element class.  If the class is primitive,
132       // then the methods field holds a pointer to the array class.
133       p = (ptr_t) c->methods;
134       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c6label);
135
136       // The vtable might have been set, but the rest of the class
137       // could still be uninitialized.  If this is the case, then
138       // c.isArray will SEGV.  We check for this, and if it is the
139       // case we just return.
140       if (__builtin_expect (c->name == NULL, false))
141         return mark_stack_ptr;
142
143       if (! c->isArray() && ! c->isPrimitive())
144         {
145           // Scan each method in the cases where `methods' really
146           // points to a methods structure.
147           for (int i = 0; i < c->method_count; ++i)
148             {
149               p = (ptr_t) c->methods[i].name;
150               MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c,
151                              cm1label);
152               p = (ptr_t) c->methods[i].signature;
153               MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c,
154                              cm2label);
155             }
156         }
157
158       // Mark all the fields.
159       p = (ptr_t) c->fields;
160       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c8label);
161       for (int i = 0; i < c->field_count; ++i)
162         {
163           _Jv_Field* field = &c->fields[i];
164
165 #ifndef COMPACT_FIELDS
166           p = (ptr_t) field->name;
167           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c8alabel);
168 #endif
169           p = (ptr_t) field->type;
170           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c8blabel);
171
172           // For the interpreter, we also need to mark the memory
173           // containing static members
174           if ((field->flags & java::lang::reflect::Modifier::STATIC))
175             {
176               p = (ptr_t) field->u.addr;
177               MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c8clabel);
178
179               // also, if the static member is a reference,
180               // mark also the value pointed to.  We check for isResolved
181               // since marking can happen before memory is allocated for
182               // static members.
183               if (JvFieldIsRef (field) && field->isResolved()) 
184                 {
185                   jobject val = *(jobject*) field->u.addr;
186                   p = (ptr_t) val;
187                   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit,
188                               c, c8elabel);
189                 }
190             }
191         }
192
193       p = (ptr_t) c->vtable;
194       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, c9label);
195       p = (ptr_t) c->interfaces;
196       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, cAlabel);
197       for (int i = 0; i < c->interface_count; ++i)
198         {
199           p = (ptr_t) c->interfaces[i];
200           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, cClabel);
201         }
202       p = (ptr_t) c->loader;
203       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, cBlabel);
204       p = (ptr_t) c->arrayclass;
205       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c, cDlabel);
206
207 #ifdef INTERPRETER
208       if (_Jv_IsInterpretedClass (c))
209         {
210           _Jv_InterpClass* ic = (_Jv_InterpClass*) c;
211
212           p = (ptr_t) ic->interpreted_methods;
213           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, ic, cElabel);
214
215           for (int i = 0; i < c->method_count; i++)
216             {
217               p = (ptr_t) ic->interpreted_methods[i];
218               MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, ic, \
219                           cFlabel);
220
221               // Mark the direct-threaded code.
222               if ((c->methods[i].accflags
223                    & java::lang::reflect::Modifier::NATIVE) == 0)
224                 {
225                   _Jv_InterpMethod *im
226                     = (_Jv_InterpMethod *) ic->interpreted_methods[i];
227                   if (im)
228                     {
229                       p = (ptr_t) im->prepared;
230                       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, ic, \
231                                   cFlabel);
232                     }
233                 }
234
235               // The interpreter installs a heap-allocated trampoline
236               // here, so we'll mark it.
237               p = (ptr_t) c->methods[i].ncode;
238               MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c,
239                           cm3label);
240             }
241
242           p = (ptr_t) ic->field_initializers;
243           MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, ic, cGlabel);
244           
245         }
246 #endif
247
248     }
249   else
250     {
251       // NOTE: each class only holds information about the class
252       // itself.  So we must do the marking for the entire inheritance
253       // tree in order to mark all fields.  FIXME: what about
254       // interfaces?  We skip Object here, because Object only has a
255       // sync_info, and we handled that earlier.
256       // Note: occasionally `klass' can be null.  For instance, this
257       // can happen if a GC occurs between the point where an object
258       // is allocated and where the vtbl slot is set.
259       while (klass && klass != &java::lang::Object::class$)
260         {
261           jfieldID field = JvGetFirstInstanceField (klass);
262           jint max = JvNumInstanceFields (klass);
263
264           for (int i = 0; i < max; ++i)
265             {
266               if (JvFieldIsRef (field))
267                 {
268                   jobject val = JvGetObjectField (obj, field);
269                   p = (ptr_t) val;
270                   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit,
271                               obj, elabel);
272                 }
273               field = field->getNextField ();
274             }
275           klass = klass->getSuperclass();
276         }
277     }
278
279   return mark_stack_ptr;
280 }
281
282 // This is called by the GC during the mark phase.  It marks a Java
283 // array (of objects).  We use `void *' arguments and return, and not
284 // what the Boehm GC wants, to avoid pollution in our headers.
285 void *
286 _Jv_MarkArray (void *addr, void *msp, void *msl, void * /*env*/)
287 {
288   mse *mark_stack_ptr = (mse *) msp;
289   mse *mark_stack_limit = (mse *) msl;
290   jobjectArray array = (jobjectArray) addr;
291
292   _Jv_VTable *dt = *(_Jv_VTable **) addr;
293   // Assumes size >= 3 words.  That's currently true since arrays have
294   // a vtable, sync pointer, and size.  If the sync pointer goes away,
295   // we may need to round up the size.
296   if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
297     return mark_stack_ptr;
298   jclass klass = dt->clas;
299   ptr_t p;
300
301 # ifndef JV_HASH_SYNCHRONIZATION
302     // Every object has a sync_info pointer.
303     p = (ptr_t) array->sync_info;
304     MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array, e1label);
305 # endif
306   // Mark the object's class.
307   p = (ptr_t) klass;
308   MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, &(dt -> clas), o2label);
309
310   for (int i = 0; i < JvGetArrayLength (array); ++i)
311     {
312       jobject obj = elements (array)[i];
313       p = (ptr_t) obj;
314       MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array, e2label);
315     }
316
317   return mark_stack_ptr;
318 }
319
320 // Generate a GC marking descriptor for a class.
321 //
322 // We assume that the gcj mark proc has index 0.  This is a dubious assumption,
323 // since another one could be registered first.  But the compiler also
324 // knows this, so in that case everything else will break, too.
325 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
326 void *
327 _Jv_BuildGCDescr(jclass)
328 {
329   /* FIXME: We should really look at the class and build the descriptor. */
330   return (void *)(GCJ_DEFAULT_DESCR);
331 }
332
333 // Allocate some space that is known to be pointer-free.
334 void *
335 _Jv_AllocBytes (jsize size)
336 {
337   void *r = GC_MALLOC_ATOMIC (size);
338   // We have to explicitly zero memory here, as the GC doesn't
339   // guarantee that PTRFREE allocations are zeroed.  Note that we
340   // don't have to do this for other allocation types because we set
341   // the `ok_init' flag in the type descriptor.
342   memset (r, 0, size);
343   return r;
344 }
345
346 // Allocate space for a new Java array.
347 // Used only for arrays of objects.
348 void *
349 _Jv_AllocArray (jsize size, jclass klass)
350 {
351   void *obj;
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
357   // take place.
358   
359 #ifdef GC_DEBUG
360   // There isn't much to lose by scanning this conservatively.
361   // If we didn't, the mark proc would have to understand that
362   // it needed to skip the header.
363   obj = GC_MALLOC(size);
364 #else
365   if (size < min_heap_addr) 
366     obj = GC_MALLOC(size);
367   else 
368     obj = GC_generic_malloc (size, array_kind_x);
369 #endif
370   *((_Jv_VTable **) obj) = klass->vtable;
371   return obj;
372 }
373
374 /* Allocate space for a new non-Java object, which does not have the usual 
375    Java object header but may contain pointers to other GC'ed objects. */
376 void *
377 _Jv_AllocRawObj (jsize size)
378 {
379   return (void *) GC_MALLOC (size);
380 }
381
382 static void
383 call_finalizer (GC_PTR obj, GC_PTR client_data)
384 {
385   _Jv_FinalizerFunc *fn = (_Jv_FinalizerFunc *) client_data;
386   jobject jobj = (jobject) obj;
387
388   (*fn) (jobj);
389 }
390
391 void
392 _Jv_RegisterFinalizer (void *object, _Jv_FinalizerFunc *meth)
393 {
394   GC_REGISTER_FINALIZER_NO_ORDER (object, call_finalizer, (GC_PTR) meth,
395                                   NULL, NULL);
396 }
397
398 void
399 _Jv_RunFinalizers (void)
400 {
401   GC_invoke_finalizers ();
402 }
403
404 void
405 _Jv_RunAllFinalizers (void)
406 {
407   GC_finalize_all ();
408 }
409
410 void
411 _Jv_RunGC (void)
412 {
413   GC_gcollect ();
414 }
415
416 long
417 _Jv_GCTotalMemory (void)
418 {
419   return GC_get_heap_size ();
420 }
421
422 long
423 _Jv_GCFreeMemory (void)
424 {
425   return GC_get_free_bytes ();
426 }
427
428 void
429 _Jv_GCSetInitialHeapSize (size_t size)
430 {
431   size_t current = GC_get_heap_size ();
432   if (size > current)
433     GC_expand_hp (size - current);
434 }
435
436 void
437 _Jv_GCSetMaximumHeapSize (size_t size)
438 {
439   GC_set_max_heap_size ((GC_word) size);
440 }
441
442 // From boehm's misc.c 
443 extern "C" void GC_enable();
444 extern "C" void GC_disable();
445
446 void
447 _Jv_DisableGC (void)
448 {
449   _Jv_MutexLock (&disable_gc_mutex); 
450   GC_disable();
451   _Jv_MutexUnlock (&disable_gc_mutex); 
452 }
453
454 void
455 _Jv_EnableGC (void)
456 {
457   _Jv_MutexLock (&disable_gc_mutex); 
458   GC_enable();
459   _Jv_MutexUnlock (&disable_gc_mutex); 
460 }
461
462 static void * handle_out_of_memory(size_t)
463 {
464   _Jv_ThrowNoMemory();
465 }
466
467 void
468 _Jv_InitGC (void)
469 {
470   int proc;
471
472   // Ignore pointers that do not point to the start of an object.
473   GC_all_interior_pointers = 0;
474
475   // Configure the collector to use the bitmap marking descriptors that we
476   // stash in the class vtable.
477   GC_init_gcj_malloc (0, (void *) _Jv_MarkObj);  
478
479   // Cause an out of memory error to be thrown from the allocators,
480   // instead of returning 0.  This is cheaper than checking on allocation.
481   GC_oom_fn = handle_out_of_memory;
482
483   GC_java_finalization = 1;
484
485   // We use a different mark procedure for object arrays. This code 
486   // configures a different object `kind' for object array allocation and
487   // marking. FIXME: see above.
488   array_free_list = (ptr_t *) GC_generic_malloc_inner ((MAXOBJSZ + 1)
489                                                        * sizeof (ptr_t),
490                                                        PTRFREE);
491   memset (array_free_list, 0, (MAXOBJSZ + 1) * sizeof (ptr_t));
492
493   proc = GC_n_mark_procs++;
494   GC_mark_procs[proc] = (GC_mark_proc) _Jv_MarkArray;
495
496   array_kind_x = GC_n_kinds++;
497   GC_obj_kinds[array_kind_x].ok_freelist = array_free_list;
498   GC_obj_kinds[array_kind_x].ok_reclaim_list = 0;
499   GC_obj_kinds[array_kind_x].ok_descriptor = GC_MAKE_PROC (proc, 0);
500   GC_obj_kinds[array_kind_x].ok_relocate_descr = FALSE;
501   GC_obj_kinds[array_kind_x].ok_init = TRUE;
502
503   _Jv_MutexInit (&disable_gc_mutex);
504 }
505
506 #ifdef JV_HASH_SYNCHRONIZATION
507 // Allocate an object with a fake vtable pointer, which causes only
508 // the first field (beyond the fake vtable pointer) to be traced.
509 // Eventually this should probably be generalized.
510
511 static _Jv_VTable trace_one_vtable = {
512     0,                  // class pointer
513     (void *)(2 * sizeof(void *)),
514                         // descriptor; scan 2 words incl. vtable ptr.
515                         // Least significant bits must be zero to
516                         // identify this as a length descriptor
517     {0}                 // First method
518 };
519
520 void *
521 _Jv_AllocTraceOne (jsize size /* includes vtable slot */) 
522 {
523   return GC_GCJ_MALLOC (size, &trace_one_vtable);
524 }
525
526 // Ditto for two words.
527 // the first field (beyond the fake vtable pointer) to be traced.
528 // Eventually this should probably be generalized.
529
530 static _Jv_VTable trace_two_vtable =
531 {
532   0,                    // class pointer
533   (void *)(3 * sizeof(void *)),
534                         // descriptor; scan 3 words incl. vtable ptr.
535   {0}                   // First method
536 };
537
538 void *
539 _Jv_AllocTraceTwo (jsize size /* includes vtable slot */) 
540 {
541   return GC_GCJ_MALLOC (size, &trace_two_vtable);
542 }
543
544 #endif /* JV_HASH_SYNCHRONIZATION */
545
546 void
547 _Jv_GCInitializeFinalizers (void (*notifier) (void))
548 {
549   GC_finalize_on_demand = 1;
550   GC_finalizer_notifier = notifier;
551 }
552
553 void
554 _Jv_GCRegisterDisappearingLink (jobject *objp)
555 {
556   GC_general_register_disappearing_link ((GC_PTR *) objp, (GC_PTR) *objp);
557 }
558
559 jboolean
560 _Jv_GCCanReclaimSoftReference (jobject)
561 {
562   // For now, always reclaim soft references.  FIXME.
563   return true;
564 }