OSDN Git Service

* lib/gcc-dg.exp (gcc-dg-debug-runtest): New method.
[pf3gnuchains/gcc-fork.git] / libjava / prims.cc
1 // prims.cc - Code for core of runtime environment.
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 #include <platform.h>
13
14 #include <stdlib.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <signal.h>
19
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include <gcj/cni.h>
25 #include <jvm.h>
26 #include <java-signal.h>
27 #include <java-threads.h>
28
29 #ifdef ENABLE_JVMPI
30 #include <jvmpi.h>
31 #include <java/lang/ThreadGroup.h>
32 #endif
33
34 #ifndef DISABLE_GETENV_PROPERTIES
35 #include <ctype.h>
36 #include <java-props.h>
37 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
38 #else
39 #define PROCESS_GCJ_PROPERTIES
40 #endif // DISABLE_GETENV_PROPERTIES
41
42 #include <java/lang/Class.h>
43 #include <java/lang/ClassLoader.h>
44 #include <java/lang/Runtime.h>
45 #include <java/lang/String.h>
46 #include <java/lang/Thread.h>
47 #include <java/lang/ThreadGroup.h>
48 #include <java/lang/ArrayIndexOutOfBoundsException.h>
49 #include <java/lang/ArithmeticException.h>
50 #include <java/lang/ClassFormatError.h>
51 #include <java/lang/InternalError.h>
52 #include <java/lang/NegativeArraySizeException.h>
53 #include <java/lang/NullPointerException.h>
54 #include <java/lang/OutOfMemoryError.h>
55 #include <java/lang/System.h>
56 #include <java/lang/VMThrowable.h>
57 #include <java/lang/reflect/Modifier.h>
58 #include <java/io/PrintStream.h>
59 #include <java/lang/UnsatisfiedLinkError.h>
60 #include <java/lang/VirtualMachineError.h>
61 #include <gnu/gcj/runtime/VMClassLoader.h>
62 #include <gnu/gcj/runtime/FinalizerThread.h>
63 #include <gnu/gcj/runtime/FirstThread.h>
64
65 #ifdef USE_LTDL
66 #include <ltdl.h>
67 #endif
68
69 // We allocate a single OutOfMemoryError exception which we keep
70 // around for use if we run out of memory.
71 static java::lang::OutOfMemoryError *no_memory;
72
73 // Largest representable size_t.
74 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
75
76 static const char *no_properties[] = { NULL };
77
78 // Properties set at compile time.
79 const char **_Jv_Compiler_Properties = no_properties;
80
81 // The JAR file to add to the beginning of java.class.path.
82 const char *_Jv_Jar_Class_Path;
83
84 #ifndef DISABLE_GETENV_PROPERTIES
85 // Property key/value pairs.
86 property_pair *_Jv_Environment_Properties;
87 #endif
88
89 // Stash the argv pointer to benefit native libraries that need it.
90 const char **_Jv_argv;
91 int _Jv_argc;
92
93 // Argument support.
94 int
95 _Jv_GetNbArgs (void)
96 {
97   // _Jv_argc is 0 if not explicitly initialized.
98   return _Jv_argc;
99 }
100
101 const char *
102 _Jv_GetSafeArg (int index)
103 {
104   if (index >=0 && index < _Jv_GetNbArgs ())
105     return _Jv_argv[index];
106   else
107     return "";
108 }
109
110 void
111 _Jv_SetArgs (int argc, const char **argv)
112 {
113   _Jv_argc = argc;
114   _Jv_argv = argv;
115 }
116
117 #ifdef ENABLE_JVMPI
118 // Pointer to JVMPI notification functions.
119 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
120 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
121 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
122 #endif
123 \f
124
125 extern "C" void _Jv_ThrowSignal (jthrowable) __attribute ((noreturn));
126
127 // Just like _Jv_Throw, but fill in the stack trace first.  Although
128 // this is declared extern in order that its name not be mangled, it
129 // is not intended to be used outside this file.
130 void 
131 _Jv_ThrowSignal (jthrowable throwable)
132 {
133   throwable->fillInStackTrace ();
134   throw throwable;
135 }
136  
137 #ifdef HANDLE_SEGV
138 static java::lang::NullPointerException *nullp;
139
140 SIGNAL_HANDLER (catch_segv)
141 {
142   MAKE_THROW_FRAME (nullp);
143   _Jv_ThrowSignal (nullp);
144 }
145 #endif
146
147 static java::lang::ArithmeticException *arithexception;
148
149 #ifdef HANDLE_FPE
150 SIGNAL_HANDLER (catch_fpe)
151 {
152 #ifdef HANDLE_DIVIDE_OVERFLOW
153   HANDLE_DIVIDE_OVERFLOW;
154 #else
155   MAKE_THROW_FRAME (arithexception);
156 #endif
157   _Jv_ThrowSignal (arithexception);
158 }
159 #endif
160
161 \f
162
163 jboolean
164 _Jv_equalUtf8Consts (Utf8Const* a, Utf8Const *b)
165 {
166   int len;
167   _Jv_ushort *aptr, *bptr;
168   if (a == b)
169     return true;
170   if (a->hash != b->hash)
171     return false;
172   len = a->length;
173   if (b->length != len)
174     return false;
175   aptr = (_Jv_ushort *)a->data;
176   bptr = (_Jv_ushort *)b->data;
177   len = (len + 1) >> 1;
178   while (--len >= 0)
179     if (*aptr++ != *bptr++)
180       return false;
181   return true;
182 }
183
184 /* True iff A is equal to STR.
185    HASH is STR->hashCode().  
186 */
187
188 jboolean
189 _Jv_equal (Utf8Const* a, jstring str, jint hash)
190 {
191   if (a->hash != (_Jv_ushort) hash)
192     return false;
193   jint len = str->length();
194   jint i = 0;
195   jchar *sptr = _Jv_GetStringChars (str);
196   unsigned char* ptr = (unsigned char*) a->data;
197   unsigned char* limit = ptr + a->length;
198   for (;; i++, sptr++)
199     {
200       int ch = UTF8_GET (ptr, limit);
201       if (i == len)
202         return ch < 0;
203       if (ch != *sptr)
204         return false;
205     }
206   return true;
207 }
208
209 /* Like _Jv_equal, but stop after N characters.  */
210 jboolean
211 _Jv_equaln (Utf8Const *a, jstring str, jint n)
212 {
213   jint len = str->length();
214   jint i = 0;
215   jchar *sptr = _Jv_GetStringChars (str);
216   unsigned char* ptr = (unsigned char*) a->data;
217   unsigned char* limit = ptr + a->length;
218   for (; n-- > 0; i++, sptr++)
219     {
220       int ch = UTF8_GET (ptr, limit);
221       if (i == len)
222         return ch < 0;
223       if (ch != *sptr)
224         return false;
225     }
226   return true;
227 }
228
229 /* Count the number of Unicode chars encoded in a given Ut8 string. */
230 int
231 _Jv_strLengthUtf8(char* str, int len)
232 {
233   unsigned char* ptr;
234   unsigned char* limit;
235   int str_length;
236
237   ptr = (unsigned char*) str;
238   limit = ptr + len;
239   str_length = 0;
240   for (; ptr < limit; str_length++)
241     {
242       if (UTF8_GET (ptr, limit) < 0)
243         return (-1);
244     }
245   return (str_length);
246 }
247
248 /* Calculate a hash value for a string encoded in Utf8 format.
249  * This returns the same hash value as specified or java.lang.String.hashCode.
250  */
251 static jint
252 hashUtf8String (char* str, int len)
253 {
254   unsigned char* ptr = (unsigned char*) str;
255   unsigned char* limit = ptr + len;
256   jint hash = 0;
257
258   for (; ptr < limit;)
259     {
260       int ch = UTF8_GET (ptr, limit);
261       /* Updated specification from
262          http://www.javasoft.com/docs/books/jls/clarify.html. */
263       hash = (31 * hash) + ch;
264     }
265   return hash;
266 }
267
268 _Jv_Utf8Const *
269 _Jv_makeUtf8Const (char* s, int len)
270 {
271   if (len < 0)
272     len = strlen (s);
273   Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
274   memcpy (m->data, s, len);
275   m->data[len] = 0;
276   m->length = len;
277   m->hash = hashUtf8String (s, len) & 0xFFFF;
278   return (m);
279 }
280
281 _Jv_Utf8Const *
282 _Jv_makeUtf8Const (jstring string)
283 {
284   jint hash = string->hashCode ();
285   jint len = _Jv_GetStringUTFLength (string);
286
287   Utf8Const* m = (Utf8Const*)
288     _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
289
290   m->hash = hash;
291   m->length = len;
292
293   _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
294   m->data[len] = 0;
295   
296   return m;
297 }
298
299 \f
300
301 #ifdef DEBUG
302 void
303 _Jv_Abort (const char *function, const char *file, int line,
304            const char *message)
305 #else
306 void
307 _Jv_Abort (const char *, const char *, int, const char *message)
308 #endif
309 {
310 #ifdef DEBUG
311   fprintf (stderr,
312            "libgcj failure: %s\n   in function %s, file %s, line %d\n",
313            message, function, file, line);
314 #else
315   fprintf (stderr, "libgcj failure: %s\n", message);
316 #endif
317   abort ();
318 }
319
320 static void
321 fail_on_finalization (jobject)
322 {
323   JvFail ("object was finalized");
324 }
325
326 void
327 _Jv_GCWatch (jobject obj)
328 {
329   _Jv_RegisterFinalizer (obj, fail_on_finalization);
330 }
331
332 void
333 _Jv_ThrowBadArrayIndex(jint bad_index)
334 {
335   throw new java::lang::ArrayIndexOutOfBoundsException
336     (java::lang::String::valueOf (bad_index));
337 }
338
339 void
340 _Jv_ThrowNullPointerException ()
341 {
342   throw new java::lang::NullPointerException;
343 }
344
345 // Explicitly throw a no memory exception.
346 // The collector calls this when it encounters an out-of-memory condition.
347 void _Jv_ThrowNoMemory()
348 {
349   throw no_memory;
350 }
351
352 #ifdef ENABLE_JVMPI
353 static void
354 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
355 {
356   // Service JVMPI allocation request.
357   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
358     {
359       JVMPI_Event event;
360
361       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
362       event.env_id = NULL;
363       event.u.obj_alloc.arena_id = 0;
364       event.u.obj_alloc.class_id = (jobjectID) klass;
365       event.u.obj_alloc.is_array = 0;
366       event.u.obj_alloc.size = size;
367       event.u.obj_alloc.obj_id = (jobjectID) obj;
368
369       // FIXME:  This doesn't look right for the Boehm GC.  A GC may
370       // already be in progress.  _Jv_DisableGC () doesn't wait for it.
371       // More importantly, I don't see the need for disabling GC, since we
372       // blatantly have a pointer to obj on our stack, ensuring that the
373       // object can't be collected.  Even for a nonconservative collector,
374       // it appears to me that this must be true, since we are about to
375       // return obj. Isn't this whole approach way too intrusive for
376       // a useful profiling interface?                  - HB
377       _Jv_DisableGC ();
378       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
379       _Jv_EnableGC ();
380     }
381 }
382 #else /* !ENABLE_JVMPI */
383 # define jvmpi_notify_alloc(klass,size,obj) /* do nothing */
384 #endif
385
386 // Allocate a new object of class KLASS.  SIZE is the size of the object
387 // to allocate.  You might think this is redundant, but it isn't; some
388 // classes, such as String, aren't of fixed size.
389 // First a version that assumes that we have no finalizer, and that
390 // the class is already initialized.
391 // If we know that JVMPI is disabled, this can be replaced by a direct call
392 // to the allocator for the appropriate GC.
393 jobject
394 _Jv_AllocObjectNoInitNoFinalizer (jclass klass, jint size)
395 {
396   jobject obj = (jobject) _Jv_AllocObj (size, klass);
397   jvmpi_notify_alloc (klass, size, obj);
398   return obj;
399 }
400
401 // And now a version that initializes if necessary.
402 jobject
403 _Jv_AllocObjectNoFinalizer (jclass klass, jint size)
404 {
405   _Jv_InitClass (klass);
406   jobject obj = (jobject) _Jv_AllocObj (size, klass);
407   jvmpi_notify_alloc (klass, size, obj);
408   return obj;
409 }
410
411 // And now the general version that registers a finalizer if necessary.
412 jobject
413 _Jv_AllocObject (jclass klass, jint size)
414 {
415   jobject obj = _Jv_AllocObjectNoFinalizer (klass, size);
416
417   // We assume that the compiler only generates calls to this routine
418   // if there really is an interesting finalizer.
419   // Unfortunately, we still have to the dynamic test, since there may
420   // be cni calls to this routine.
421   // Note that on IA64 get_finalizer() returns the starting address of the
422   // function, not a function pointer.  Thus this still works.
423   if (klass->vtable->get_finalizer ()
424       != java::lang::Object::class$.vtable->get_finalizer ())
425     _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
426   return obj;
427 }
428
429 // A version of the above that assumes the object contains no pointers,
430 // and requires no finalization.  This can't happen if we need pointers
431 // to locks.
432 #ifdef JV_HASH_SYNCHRONIZATION
433 jobject
434 _Jv_AllocPtrFreeObject (jclass klass, jint size)
435 {
436   _Jv_InitClass (klass);
437
438   jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
439
440 #ifdef ENABLE_JVMPI
441   // Service JVMPI request.
442
443   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
444     {
445       JVMPI_Event event;
446
447       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
448       event.env_id = NULL;
449       event.u.obj_alloc.arena_id = 0;
450       event.u.obj_alloc.class_id = (jobjectID) klass;
451       event.u.obj_alloc.is_array = 0;
452       event.u.obj_alloc.size = size;
453       event.u.obj_alloc.obj_id = (jobjectID) obj;
454
455       _Jv_DisableGC ();
456       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
457       _Jv_EnableGC ();
458     }
459 #endif
460
461   return obj;
462 }
463 #endif /* JV_HASH_SYNCHRONIZATION */
464
465
466 // Allocate a new array of Java objects.  Each object is of type
467 // `elementClass'.  `init' is used to initialize each slot in the
468 // array.
469 jobjectArray
470 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
471 {
472   if (__builtin_expect (count < 0, false))
473     throw new java::lang::NegativeArraySizeException;
474
475   JvAssert (! elementClass->isPrimitive ());
476
477   // Ensure that elements pointer is properly aligned.
478   jobjectArray obj = NULL;
479   size_t size = (size_t) elements (obj);
480   size += count * sizeof (jobject);
481
482   jclass klass = _Jv_GetArrayClass (elementClass,
483                                     elementClass->getClassLoaderInternal());
484
485   obj = (jobjectArray) _Jv_AllocArray (size, klass);
486   // Cast away const.
487   jsize *lp = const_cast<jsize *> (&obj->length);
488   *lp = count;
489   // We know the allocator returns zeroed memory.  So don't bother
490   // zeroing it again.
491   if (init)
492     {
493       jobject *ptr = elements(obj);
494       while (--count >= 0)
495         *ptr++ = init;
496     }
497   return obj;
498 }
499
500 // Allocate a new array of primitives.  ELTYPE is the type of the
501 // element, COUNT is the size of the array.
502 jobject
503 _Jv_NewPrimArray (jclass eltype, jint count)
504 {
505   int elsize = eltype->size();
506   if (__builtin_expect (count < 0, false))
507     throw new java::lang::NegativeArraySizeException;
508
509   JvAssert (eltype->isPrimitive ());
510   jobject dummy = NULL;
511   size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
512
513   // Check for overflow.
514   if (__builtin_expect ((size_t) count > 
515                         (SIZE_T_MAX - size) / elsize, false))
516     throw no_memory;
517
518   jclass klass = _Jv_GetArrayClass (eltype, 0);
519
520 # ifdef JV_HASH_SYNCHRONIZATION
521   // Since the vtable is always statically allocated,
522   // these are completely pointerfree!  Make sure the GC doesn't touch them.
523   __JArray *arr =
524     (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
525   memset((char *)arr + size, 0, elsize * count);
526 # else
527   __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
528   // Note that we assume we are given zeroed memory by the allocator.
529 # endif
530   // Cast away const.
531   jsize *lp = const_cast<jsize *> (&arr->length);
532   *lp = count;
533
534   return arr;
535 }
536
537 jobject
538 _Jv_NewArray (jint type, jint size)
539 {
540   switch (type)
541     {
542       case  4:  return JvNewBooleanArray (size);
543       case  5:  return JvNewCharArray (size);
544       case  6:  return JvNewFloatArray (size);
545       case  7:  return JvNewDoubleArray (size);
546       case  8:  return JvNewByteArray (size);
547       case  9:  return JvNewShortArray (size);
548       case 10:  return JvNewIntArray (size);
549       case 11:  return JvNewLongArray (size);
550     }
551   throw new java::lang::InternalError
552     (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
553 }
554
555 // Allocate a possibly multi-dimensional array but don't check that
556 // any array length is <0.
557 static jobject
558 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
559 {
560   JvAssert (type->isArray());
561   jclass element_type = type->getComponentType();
562   jobject result;
563   if (element_type->isPrimitive())
564     result = _Jv_NewPrimArray (element_type, sizes[0]);
565   else
566     result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
567
568   if (dimensions > 1)
569     {
570       JvAssert (! element_type->isPrimitive());
571       JvAssert (element_type->isArray());
572       jobject *contents = elements ((jobjectArray) result);
573       for (int i = 0; i < sizes[0]; ++i)
574         contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
575                                                   sizes + 1);
576     }
577
578   return result;
579 }
580
581 jobject
582 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
583 {
584   for (int i = 0; i < dimensions; ++i)
585     if (sizes[i] < 0)
586       throw new java::lang::NegativeArraySizeException;
587
588   return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
589 }
590
591 jobject
592 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
593 {
594   va_list args;
595   jint sizes[dimensions];
596   va_start (args, dimensions);
597   for (int i = 0; i < dimensions; ++i)
598     {
599       jint size = va_arg (args, jint);
600       if (size < 0)
601         throw new java::lang::NegativeArraySizeException;
602       sizes[i] = size;
603     }
604   va_end (args);
605
606   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
607 }
608
609 \f
610
611 // Ensure 8-byte alignment, for hash synchronization.
612 #define DECLARE_PRIM_TYPE(NAME)                 \
613   _Jv_ArrayVTable _Jv_##NAME##VTable;           \
614   java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
615
616 DECLARE_PRIM_TYPE(byte)
617 DECLARE_PRIM_TYPE(short)
618 DECLARE_PRIM_TYPE(int)
619 DECLARE_PRIM_TYPE(long)
620 DECLARE_PRIM_TYPE(boolean)
621 DECLARE_PRIM_TYPE(char)
622 DECLARE_PRIM_TYPE(float)
623 DECLARE_PRIM_TYPE(double)
624 DECLARE_PRIM_TYPE(void)
625
626 void
627 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len, 
628                    _Jv_ArrayVTable *array_vtable)
629 {    
630   using namespace java::lang::reflect;
631
632   _Jv_InitNewClassFields (cl);
633
634   // We must set the vtable for the class; the Java constructor
635   // doesn't do this.
636   (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
637
638   // Initialize the fields we care about.  We do this in the same
639   // order they are declared in Class.h.
640   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
641   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
642   cl->method_count = sig;
643   cl->size_in_bytes = len;
644   cl->vtable = JV_PRIMITIVE_VTABLE;
645   cl->state = JV_STATE_DONE;
646   cl->depth = -1;
647   if (sig != 'V')
648     _Jv_NewArrayClass (cl, NULL, (_Jv_VTable *) array_vtable);
649 }
650
651 jclass
652 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
653 {
654   switch (*sig)
655     {
656     case 'B':
657       return JvPrimClass (byte);
658     case 'S':
659       return JvPrimClass (short);
660     case 'I':
661       return JvPrimClass (int);
662     case 'J':
663       return JvPrimClass (long);
664     case 'Z':
665       return JvPrimClass (boolean);
666     case 'C':
667       return JvPrimClass (char);
668     case 'F':
669       return JvPrimClass (float);
670     case 'D':
671       return JvPrimClass (double);
672     case 'V':
673       return JvPrimClass (void);
674     case 'L':
675       {
676         int i;
677         for (i = 1; sig[i] && sig[i] != ';'; ++i)
678           ;
679         _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
680         return _Jv_FindClass (name, loader);
681       }
682     case '[':
683       {
684         jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
685         if (! klass)
686           return NULL;
687         return _Jv_GetArrayClass (klass, loader);
688       }
689     }
690
691   return NULL;                  // Placate compiler.
692 }
693
694 \f
695
696 JArray<jstring> *
697 JvConvertArgv (int argc, const char **argv)
698 {
699   if (argc < 0)
700     argc = 0;
701   jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
702   jobject *ptr = elements(ar);
703   jbyteArray bytes = NULL;
704   for (int i = 0;  i < argc;  i++)
705     {
706       const char *arg = argv[i];
707       int len = strlen (arg);
708       if (bytes == NULL || bytes->length < len)
709         bytes = JvNewByteArray (len);
710       jbyte *bytePtr = elements (bytes);
711       // We assume jbyte == char.
712       memcpy (bytePtr, arg, len);
713
714       // Now convert using the default encoding.
715       *ptr++ = new java::lang::String (bytes, 0, len);
716     }
717   return (JArray<jstring>*) ar;
718 }
719
720 // FIXME: These variables are static so that they will be
721 // automatically scanned by the Boehm collector.  This is needed
722 // because with qthreads the collector won't scan the initial stack --
723 // it will only scan the qthreads stacks.
724
725 // Command line arguments.
726 static JArray<jstring> *arg_vec;
727
728 // The primary thread.
729 static java::lang::Thread *main_thread;
730
731 #ifndef DISABLE_GETENV_PROPERTIES
732
733 static char *
734 next_property_key (char *s, size_t *length)
735 {
736   size_t l = 0;
737
738   JvAssert (s);
739
740   // Skip over whitespace
741   while (isspace (*s))
742     s++;
743
744   // If we've reached the end, return NULL.  Also return NULL if for
745   // some reason we've come across a malformed property string.
746   if (*s == 0
747       || *s == ':'
748       || *s == '=')
749     return NULL;
750
751   // Determine the length of the property key.
752   while (s[l] != 0
753          && ! isspace (s[l])
754          && s[l] != ':'
755          && s[l] != '=')
756     {
757       if (s[l] == '\\'
758           && s[l+1] != 0)
759         l++;
760       l++;
761     }
762
763   *length = l;
764
765   return s;
766 }
767
768 static char *
769 next_property_value (char *s, size_t *length)
770 {
771   size_t l = 0;
772
773   JvAssert (s);
774
775   while (isspace (*s))
776     s++;
777
778   if (*s == ':'
779       || *s == '=')
780     s++;
781
782   while (isspace (*s))
783     s++;
784
785   // If we've reached the end, return NULL.
786   if (*s == 0)
787     return NULL;
788
789   // Determine the length of the property value.
790   while (s[l] != 0
791          && ! isspace (s[l])
792          && s[l] != ':'
793          && s[l] != '=')
794     {
795       if (s[l] == '\\'
796           && s[l+1] != 0)
797         l += 2;
798       else
799         l++;
800     }
801
802   *length = l;
803
804   return s;
805 }
806
807 static void
808 process_gcj_properties ()
809 {
810   char *props = getenv("GCJ_PROPERTIES");
811   char *p = props;
812   size_t length;
813   size_t property_count = 0;
814
815   if (NULL == props)
816     return;
817
818   // Whip through props quickly in order to count the number of
819   // property values.
820   while (p && (p = next_property_key (p, &length)))
821     {
822       // Skip to the end of the key
823       p += length;
824
825       p = next_property_value (p, &length);
826       if (p)
827         p += length;
828       
829       property_count++;
830     }
831
832   // Allocate an array of property value/key pairs.
833   _Jv_Environment_Properties = 
834     (property_pair *) malloc (sizeof(property_pair) 
835                               * (property_count + 1));
836
837   // Go through the properties again, initializing _Jv_Properties
838   // along the way.
839   p = props;
840   property_count = 0;
841   while (p && (p = next_property_key (p, &length)))
842     {
843       _Jv_Environment_Properties[property_count].key = p;
844       _Jv_Environment_Properties[property_count].key_length = length;
845
846       // Skip to the end of the key
847       p += length;
848
849       p = next_property_value (p, &length);
850       
851       _Jv_Environment_Properties[property_count].value = p;
852       _Jv_Environment_Properties[property_count].value_length = length;
853
854       if (p)
855         p += length;
856
857       property_count++;
858     }
859   memset ((void *) &_Jv_Environment_Properties[property_count], 
860           0, sizeof (property_pair));
861   {
862     size_t i = 0;
863
864     // Null terminate the strings.
865     while (_Jv_Environment_Properties[i].key)
866       {
867         _Jv_Environment_Properties[i].key[_Jv_Environment_Properties[i].key_length] = 0;
868         _Jv_Environment_Properties[i++].value[_Jv_Environment_Properties[i].value_length] = 0;
869       }
870   }
871 }
872 #endif // DISABLE_GETENV_PROPERTIES
873
874 namespace gcj
875 {
876   _Jv_Utf8Const *void_signature;
877   _Jv_Utf8Const *clinit_name;
878   _Jv_Utf8Const *init_name;
879   _Jv_Utf8Const *finit_name;
880   
881   bool runtimeInitialized = false;
882 }
883
884 jint
885 _Jv_CreateJavaVM (void* /*vm_args*/)
886 {
887   using namespace gcj;
888   
889   if (runtimeInitialized)
890     return -1;
891
892   runtimeInitialized = true;
893
894   PROCESS_GCJ_PROPERTIES;
895
896   _Jv_InitThreads ();
897   _Jv_InitGC ();
898   _Jv_InitializeSyncMutex ();
899
900   /* Initialize Utf8 constants declared in jvm.h. */
901   void_signature = _Jv_makeUtf8Const ("()V", 3);
902   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
903   init_name = _Jv_makeUtf8Const ("<init>", 6);
904   finit_name = _Jv_makeUtf8Const ("finit$", 6);
905
906   /* Initialize built-in classes to represent primitive TYPEs. */
907   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1, &_Jv_byteVTable);
908   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2, &_Jv_shortVTable);
909   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4, &_Jv_intVTable);
910   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8, &_Jv_longVTable);
911   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1, &_Jv_booleanVTable);
912   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2, &_Jv_charVTable);
913   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4, &_Jv_floatVTable);
914   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8, &_Jv_doubleVTable);
915   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0, &_Jv_voidVTable);
916
917   // Turn stack trace generation off while creating exception objects.
918   _Jv_InitClass (&java::lang::VMThrowable::class$);
919   java::lang::VMThrowable::trace_enabled = 0;
920   
921   INIT_SEGV;
922 #ifdef HANDLE_FPE
923   INIT_FPE;
924 #else
925   arithexception = new java::lang::ArithmeticException
926     (JvNewStringLatin1 ("/ by zero"));
927 #endif
928   
929   no_memory = new java::lang::OutOfMemoryError;
930   
931   java::lang::VMThrowable::trace_enabled = 1;
932   
933 #ifdef USE_LTDL
934   LTDL_SET_PRELOADED_SYMBOLS ();
935 #endif
936
937   _Jv_platform_initialize ();
938
939   _Jv_JNI_Init ();
940
941   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
942
943   // Start the GC finalizer thread.  A VirtualMachineError can be
944   // thrown by the runtime if, say, threads aren't available.  In this
945   // case finalizers simply won't run.
946   try
947     {
948       using namespace gnu::gcj::runtime;
949       FinalizerThread *ft = new FinalizerThread ();
950       ft->start ();
951     }
952   catch (java::lang::VirtualMachineError *ignore)
953     {
954     }
955
956   return 0;
957 }
958
959 void
960 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
961              bool is_jar)
962 {
963   _Jv_SetArgs (argc, argv);
964
965   java::lang::Runtime *runtime = NULL;
966
967   try
968     {
969       // Set this very early so that it is seen when java.lang.System
970       // is initialized.
971       if (is_jar)
972         _Jv_Jar_Class_Path = strdup (name);
973       _Jv_CreateJavaVM (NULL);
974
975       // Get the Runtime here.  We want to initialize it before searching
976       // for `main'; that way it will be set up if `main' is a JNI method.
977       runtime = java::lang::Runtime::getRuntime ();
978
979 #ifdef DISABLE_MAIN_ARGS
980       arg_vec = JvConvertArgv (0, 0);
981 #else      
982       arg_vec = JvConvertArgv (argc - 1, argv + 1);
983 #endif
984
985       using namespace gnu::gcj::runtime;
986       if (klass)
987         main_thread = new FirstThread (klass, arg_vec);
988       else
989         main_thread = new FirstThread (JvNewStringLatin1 (name),
990                                        arg_vec, is_jar);
991     }
992   catch (java::lang::Throwable *t)
993     {
994       java::lang::System::err->println (JvNewStringLatin1 
995         ("Exception during runtime initialization"));
996       t->printStackTrace();
997       runtime->exit (1);
998     }
999
1000   _Jv_AttachCurrentThread (main_thread);
1001   _Jv_ThreadRun (main_thread);
1002   _Jv_ThreadWait ();
1003
1004   int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1005   runtime->exit (status);
1006 }
1007
1008 void
1009 JvRunMain (jclass klass, int argc, const char **argv)
1010 {
1011   _Jv_RunMain (klass, NULL, argc, argv, false);
1012 }
1013
1014 \f
1015
1016 // Parse a string and return a heap size.
1017 static size_t
1018 parse_heap_size (const char *spec)
1019 {
1020   char *end;
1021   unsigned long val = strtoul (spec, &end, 10);
1022   if (*end == 'k' || *end == 'K')
1023     val *= 1024;
1024   else if (*end == 'm' || *end == 'M')
1025     val *= 1048576;
1026   return (size_t) val;
1027 }
1028
1029 // Set the initial heap size.  This might be ignored by the GC layer.
1030 // This must be called before _Jv_RunMain.
1031 void
1032 _Jv_SetInitialHeapSize (const char *arg)
1033 {
1034   size_t size = parse_heap_size (arg);
1035   _Jv_GCSetInitialHeapSize (size);
1036 }
1037
1038 // Set the maximum heap size.  This might be ignored by the GC layer.
1039 // This must be called before _Jv_RunMain.
1040 void
1041 _Jv_SetMaximumHeapSize (const char *arg)
1042 {
1043   size_t size = parse_heap_size (arg);
1044   _Jv_GCSetMaximumHeapSize (size);
1045 }
1046
1047 \f
1048
1049 void *
1050 _Jv_Malloc (jsize size)
1051 {
1052   if (__builtin_expect (size == 0, false))
1053     size = 1;
1054   void *ptr = malloc ((size_t) size);
1055   if (__builtin_expect (ptr == NULL, false))
1056     throw no_memory;
1057   return ptr;
1058 }
1059
1060 void *
1061 _Jv_Realloc (void *ptr, jsize size)
1062 {
1063   if (__builtin_expect (size == 0, false))
1064     size = 1;
1065   ptr = realloc (ptr, (size_t) size);
1066   if (__builtin_expect (ptr == NULL, false))
1067     throw no_memory;
1068   return ptr;
1069 }
1070
1071 void *
1072 _Jv_MallocUnchecked (jsize size)
1073 {
1074   if (__builtin_expect (size == 0, false))
1075     size = 1;
1076   return malloc ((size_t) size);
1077 }
1078
1079 void
1080 _Jv_Free (void* ptr)
1081 {
1082   return free (ptr);
1083 }
1084
1085 \f
1086
1087 // In theory, these routines can be #ifdef'd away on machines which
1088 // support divide overflow signals.  However, we never know if some
1089 // code might have been compiled with "-fuse-divide-subroutine", so we
1090 // always include them in libgcj.
1091
1092 jint
1093 _Jv_divI (jint dividend, jint divisor)
1094 {
1095   if (__builtin_expect (divisor == 0, false))
1096     _Jv_ThrowSignal (arithexception);
1097   
1098   if (dividend == (jint) 0x80000000L && divisor == -1)
1099     return dividend;
1100
1101   return dividend / divisor;
1102 }
1103
1104 jint
1105 _Jv_remI (jint dividend, jint divisor)
1106 {
1107   if (__builtin_expect (divisor == 0, false))
1108     _Jv_ThrowSignal (arithexception);
1109   
1110   if (dividend == (jint) 0x80000000L && divisor == -1)
1111     return 0;
1112
1113   return dividend % divisor;
1114 }
1115
1116 jlong
1117 _Jv_divJ (jlong dividend, jlong divisor)
1118 {
1119   if (__builtin_expect (divisor == 0, false))
1120     _Jv_ThrowSignal (arithexception);
1121   
1122   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1123     return dividend;
1124
1125   return dividend / divisor;
1126 }
1127
1128 jlong
1129 _Jv_remJ (jlong dividend, jlong divisor)
1130 {
1131   if (__builtin_expect (divisor == 0, false))
1132     _Jv_ThrowSignal (arithexception);
1133   
1134   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1135     return 0;
1136
1137   return dividend % divisor;
1138 }