OSDN Git Service

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