OSDN Git Service

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