OSDN Git Service

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