OSDN Git Service

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