OSDN Git Service

2006-05-04 Andrew Haley <aph@redhat.com>
[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, 2006  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/ClassNotFoundException.h>
53 #include <java/lang/InternalError.h>
54 #include <java/lang/NegativeArraySizeException.h>
55 #include <java/lang/NoClassDefFoundError.h>
56 #include <java/lang/NullPointerException.h>
57 #include <java/lang/OutOfMemoryError.h>
58 #include <java/lang/System.h>
59 #include <java/lang/VMThrowable.h>
60 #include <java/lang/VMClassLoader.h>
61 #include <java/lang/reflect/Modifier.h>
62 #include <java/io/PrintStream.h>
63 #include <java/lang/UnsatisfiedLinkError.h>
64 #include <java/lang/VirtualMachineError.h>
65 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
66 #include <gnu/gcj/runtime/FinalizerThread.h>
67 #include <execution.h>
68 #include <gnu/java/lang/MainThread.h>
69
70 #ifdef USE_LTDL
71 #include <ltdl.h>
72 #endif
73
74 // Execution engine for compiled code.
75 _Jv_CompiledEngine _Jv_soleCompiledEngine;
76
77 // We allocate a single OutOfMemoryError exception which we keep
78 // around for use if we run out of memory.
79 static java::lang::OutOfMemoryError *no_memory;
80
81 // Number of bytes in largest array object we create.  This could be
82 // increased to the largest size_t value, so long as the appropriate
83 // functions are changed to take a size_t argument instead of jint.
84 #define MAX_OBJECT_SIZE ((1<<31) - 1)
85
86 // Properties set at compile time.
87 const char **_Jv_Compiler_Properties = NULL;
88 int _Jv_Properties_Count = 0;
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   unblock_signal (SIGSEGV);
151   MAKE_THROW_FRAME (nullp);
152   java::lang::NullPointerException *nullp 
153     = new java::lang::NullPointerException;
154   throw nullp;
155 }
156 #endif
157
158 #ifdef HANDLE_FPE
159 SIGNAL_HANDLER (catch_fpe)
160 {
161   unblock_signal (SIGFPE);
162 #ifdef HANDLE_DIVIDE_OVERFLOW
163   HANDLE_DIVIDE_OVERFLOW;
164 #else
165   MAKE_THROW_FRAME (arithexception);
166 #endif
167   java::lang::ArithmeticException *arithexception 
168     = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
169   throw arithexception;
170 }
171 #endif
172
173
174 jboolean
175 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
176 {
177   int len;
178   const _Jv_ushort *aptr, *bptr;
179   if (a == b)
180     return true;
181   if (a->hash != b->hash)
182     return false;
183   len = a->length;
184   if (b->length != len)
185     return false;
186   aptr = (const _Jv_ushort *)a->data;
187   bptr = (const _Jv_ushort *)b->data;
188   len = (len + 1) >> 1;
189   while (--len >= 0)
190     if (*aptr++ != *bptr++)
191       return false;
192   return true;
193 }
194
195 /* True iff A is equal to STR.
196    HASH is STR->hashCode().  
197 */
198
199 jboolean
200 _Jv_equal (Utf8Const* a, jstring str, jint hash)
201 {
202   if (a->hash != (_Jv_ushort) hash)
203     return false;
204   jint len = str->length();
205   jint i = 0;
206   jchar *sptr = _Jv_GetStringChars (str);
207   unsigned char* ptr = (unsigned char*) a->data;
208   unsigned char* limit = ptr + a->length;
209   for (;; i++, sptr++)
210     {
211       int ch = UTF8_GET (ptr, limit);
212       if (i == len)
213         return ch < 0;
214       if (ch != *sptr)
215         return false;
216     }
217   return true;
218 }
219
220 /* Like _Jv_equal, but stop after N characters.  */
221 jboolean
222 _Jv_equaln (Utf8Const *a, jstring str, jint n)
223 {
224   jint len = str->length();
225   jint i = 0;
226   jchar *sptr = _Jv_GetStringChars (str);
227   unsigned char* ptr = (unsigned char*) a->data;
228   unsigned char* limit = ptr + a->length;
229   for (; n-- > 0; i++, sptr++)
230     {
231       int ch = UTF8_GET (ptr, limit);
232       if (i == len)
233         return ch < 0;
234       if (ch != *sptr)
235         return false;
236     }
237   return true;
238 }
239
240 // Determines whether the given Utf8Const object contains
241 // a type which is primitive or some derived form of it, eg.
242 // an array or multi-dimensional array variant.
243 jboolean
244 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
245 {
246   unsigned char *aptr = (unsigned char *) a->data;
247   unsigned char *alimit = aptr + a->length;
248   int ac = UTF8_GET(aptr, alimit);
249
250   // Skips any leading array marks.
251   while (ac == '[')
252     ac = UTF8_GET(aptr, alimit);
253
254   // There should not be another character. This implies that
255   // the type name is only one character long.
256   if (UTF8_GET(aptr, alimit) == -1)
257     switch ( ac )
258       {
259         case 'Z':
260         case 'B':
261         case 'C':
262         case 'S':
263         case 'I':
264         case 'J':
265         case 'F':
266         case 'D':
267           return true;
268         default:
269           break;
270        }
271
272    return false;
273 }
274
275 // Find out whether two _Jv_Utf8Const candidates contain the same
276 // classname.
277 // The method is written to handle the different formats of classnames.
278 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
279 // "java.lang.Class" will be seen as equal.
280 // Warning: This function is not smart enough to declare "Z" and "boolean"
281 // and similar cases as equal (and is not meant to be used this way)!
282 jboolean
283 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
284 {
285   // If the class name's length differs by two characters
286   // it is possible that we have candidates which are given
287   // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
288   switch (a->length - b->length)
289     {
290       case -2:
291       case 0:
292       case 2:
293         break;
294       default:
295         return false;
296     }
297
298   unsigned char *aptr = (unsigned char *) a->data;
299   unsigned char *alimit = aptr + a->length;
300   unsigned char *bptr = (unsigned char *) b->data;
301   unsigned char *blimit = bptr + b->length;
302
303   if (alimit[-1] == ';')
304     alimit--;
305
306   if (blimit[-1] == ';')
307     blimit--;
308
309   int ac = UTF8_GET(aptr, alimit);
310   int bc = UTF8_GET(bptr, blimit);
311
312   // Checks whether both strings have the same amount of leading [ characters.
313   while (ac == '[')
314     {
315       if (bc == '[')
316         {
317           ac = UTF8_GET(aptr, alimit);
318           bc = UTF8_GET(bptr, blimit);
319           continue;
320         }
321
322       return false;
323     }
324
325   // Skips leading L character.
326   if (ac == 'L')
327     ac = UTF8_GET(aptr, alimit);
328         
329   if (bc == 'L')
330     bc = UTF8_GET(bptr, blimit);
331
332   // Compares the remaining characters.
333   while (ac != -1 && bc != -1)
334     {
335       // Replaces package separating dots with slashes.
336       if (ac == '.')
337         ac = '/';
338
339       if (bc == '.')
340         bc = '/';
341       
342       // Now classnames differ if there is at least one non-matching
343       // character.
344       if (ac != bc)
345         return false;
346
347       ac = UTF8_GET(aptr, alimit);
348       bc = UTF8_GET(bptr, blimit);
349     }
350
351   return (ac == bc);
352 }
353
354 /* Count the number of Unicode chars encoded in a given Ut8 string. */
355 int
356 _Jv_strLengthUtf8(const char* str, int len)
357 {
358   unsigned char* ptr;
359   unsigned char* limit;
360   int str_length;
361
362   ptr = (unsigned char*) str;
363   limit = ptr + len;
364   str_length = 0;
365   for (; ptr < limit; str_length++)
366     {
367       if (UTF8_GET (ptr, limit) < 0)
368         return (-1);
369     }
370   return (str_length);
371 }
372
373 /* Calculate a hash value for a string encoded in Utf8 format.
374  * This returns the same hash value as specified or java.lang.String.hashCode.
375  */
376 jint
377 _Jv_hashUtf8String (const char* str, int len)
378 {
379   unsigned char* ptr = (unsigned char*) str;
380   unsigned char* limit = ptr + len;
381   jint hash = 0;
382
383   for (; ptr < limit;)
384     {
385       int ch = UTF8_GET (ptr, limit);
386       /* Updated specification from
387          http://www.javasoft.com/docs/books/jls/clarify.html. */
388       hash = (31 * hash) + ch;
389     }
390   return hash;
391 }
392
393 void
394 _Jv_Utf8Const::init(const char *s, int len)
395 {
396   ::memcpy (data, s, len);
397   data[len] = 0;
398   length = len;
399   hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
400 }
401
402 _Jv_Utf8Const *
403 _Jv_makeUtf8Const (const char* s, int len)
404 {
405   if (len < 0)
406     len = strlen (s);
407   Utf8Const* m
408     = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
409   m->init(s, len);
410   return m;
411 }
412
413 _Jv_Utf8Const *
414 _Jv_makeUtf8Const (jstring string)
415 {
416   jint hash = string->hashCode ();
417   jint len = _Jv_GetStringUTFLength (string);
418
419   Utf8Const* m = (Utf8Const*)
420     _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
421
422   m->hash = hash;
423   m->length = len;
424
425   _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
426   m->data[len] = 0;
427   
428   return m;
429 }
430
431 \f
432
433 #ifdef DEBUG
434 void
435 _Jv_Abort (const char *function, const char *file, int line,
436            const char *message)
437 #else
438 void
439 _Jv_Abort (const char *, const char *, int, const char *message)
440 #endif
441 {
442 #ifdef DEBUG
443   fprintf (stderr,
444            "libgcj failure: %s\n   in function %s, file %s, line %d\n",
445            message, function, file, line);
446 #else
447   fprintf (stderr, "libgcj failure: %s\n", message);
448 #endif
449   abort ();
450 }
451
452 static void
453 fail_on_finalization (jobject)
454 {
455   JvFail ("object was finalized");
456 }
457
458 void
459 _Jv_GCWatch (jobject obj)
460 {
461   _Jv_RegisterFinalizer (obj, fail_on_finalization);
462 }
463
464 void
465 _Jv_ThrowBadArrayIndex(jint bad_index)
466 {
467   throw new java::lang::ArrayIndexOutOfBoundsException
468     (java::lang::String::valueOf (bad_index));
469 }
470
471 void
472 _Jv_ThrowNullPointerException ()
473 {
474   throw new java::lang::NullPointerException;
475 }
476
477 // Resolve an entry in the constant pool and return the target
478 // address.
479 void *
480 _Jv_ResolvePoolEntry (jclass this_class, jint index)
481 {
482   _Jv_Constants *pool = &this_class->constants;
483
484   if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
485     return pool->data[index].field->u.addr;
486
487   JvSynchronize sync (this_class);
488   return (_Jv_Linker::resolve_pool_entry (this_class, index))
489     .field->u.addr;
490 }
491
492
493 // Explicitly throw a no memory exception.
494 // The collector calls this when it encounters an out-of-memory condition.
495 void _Jv_ThrowNoMemory()
496 {
497   throw no_memory;
498 }
499
500 #ifdef ENABLE_JVMPI
501 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
502     if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
503       jvmpi_notify_alloc(klass,size,obj);
504 static void
505 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
506 {
507   // Service JVMPI allocation request.
508   JVMPI_Event event;
509
510   event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
511   event.env_id = NULL;
512   event.u.obj_alloc.arena_id = 0;
513   event.u.obj_alloc.class_id = (jobjectID) klass;
514   event.u.obj_alloc.is_array = 0;
515   event.u.obj_alloc.size = size;
516   event.u.obj_alloc.obj_id = (jobjectID) obj;
517
518   // FIXME:  This doesn't look right for the Boehm GC.  A GC may
519   // already be in progress.  _Jv_DisableGC () doesn't wait for it.
520   // More importantly, I don't see the need for disabling GC, since we
521   // blatantly have a pointer to obj on our stack, ensuring that the
522   // object can't be collected.  Even for a nonconservative collector,
523   // it appears to me that this must be true, since we are about to
524   // return obj. Isn't this whole approach way too intrusive for
525   // a useful profiling interface?                      - HB
526   _Jv_DisableGC ();
527   (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
528   _Jv_EnableGC ();
529 }
530 #else /* !ENABLE_JVMPI */
531 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
532 #endif
533
534 // Allocate a new object of class KLASS.
535 // First a version that assumes that we have no finalizer, and that
536 // the class is already initialized.
537 // If we know that JVMPI is disabled, this can be replaced by a direct call
538 // to the allocator for the appropriate GC.
539 jobject
540 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
541 {
542   jint size = klass->size ();
543   jobject obj = (jobject) _Jv_AllocObj (size, klass);
544   JVMPI_NOTIFY_ALLOC (klass, size, obj);
545   return obj;
546 }
547
548 // And now a version that initializes if necessary.
549 jobject
550 _Jv_AllocObjectNoFinalizer (jclass klass)
551 {
552   if (_Jv_IsPhantomClass(klass) )
553     throw new java::lang::NoClassDefFoundError(klass->getName());
554
555   _Jv_InitClass (klass);
556   jint size = klass->size ();
557   jobject obj = (jobject) _Jv_AllocObj (size, klass);
558   JVMPI_NOTIFY_ALLOC (klass, size, obj);
559   return obj;
560 }
561
562 // And now the general version that registers a finalizer if necessary.
563 jobject
564 _Jv_AllocObject (jclass klass)
565 {
566   jobject obj = _Jv_AllocObjectNoFinalizer (klass);
567   
568   // We assume that the compiler only generates calls to this routine
569   // if there really is an interesting finalizer.
570   // Unfortunately, we still have to the dynamic test, since there may
571   // be cni calls to this routine.
572   // Note that on IA64 get_finalizer() returns the starting address of the
573   // function, not a function pointer.  Thus this still works.
574   if (klass->vtable->get_finalizer ()
575       != java::lang::Object::class$.vtable->get_finalizer ())
576     _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
577   return obj;
578 }
579
580 // Allocate a String, including variable length storage.
581 jstring
582 _Jv_AllocString(jsize len)
583 {
584   using namespace java::lang;
585
586   jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
587
588   // We assert that for strings allocated this way, the data field
589   // will always point to the object itself.  Thus there is no reason
590   // for the garbage collector to scan any of it.
591   // Furthermore, we're about to overwrite the string data, so
592   // initialization of the object is not an issue.
593
594   // String needs no initialization, and there is no finalizer, so
595   // we can go directly to the collector's allocator interface.
596   jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
597
598   obj->data = obj;
599   obj->boffset = sizeof(java::lang::String);
600   obj->count = len;
601   obj->cachedHashCode = 0;
602
603   JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
604   
605   return obj;
606 }
607
608 // A version of the above that assumes the object contains no pointers,
609 // and requires no finalization.  This can't happen if we need pointers
610 // to locks.
611 #ifdef JV_HASH_SYNCHRONIZATION
612 jobject
613 _Jv_AllocPtrFreeObject (jclass klass)
614 {
615   _Jv_InitClass (klass);
616   jint size = klass->size ();
617
618   jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
619
620   JVMPI_NOTIFY_ALLOC (klass, size, obj);
621
622   return obj;
623 }
624 #endif /* JV_HASH_SYNCHRONIZATION */
625
626
627 // Allocate a new array of Java objects.  Each object is of type
628 // `elementClass'.  `init' is used to initialize each slot in the
629 // array.
630 jobjectArray
631 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
632 {
633   // Creating an array of an unresolved type is impossible. So we throw
634   // the NoClassDefFoundError.
635   if ( _Jv_IsPhantomClass(elementClass) )
636     throw new java::lang::NoClassDefFoundError(elementClass->getName());
637
638   if (__builtin_expect (count < 0, false))
639     throw new java::lang::NegativeArraySizeException;
640
641   JvAssert (! elementClass->isPrimitive ());
642
643   // Ensure that elements pointer is properly aligned.
644   jobjectArray obj = NULL;
645   size_t size = (size_t) elements (obj);
646   // Check for overflow.
647   if (__builtin_expect ((size_t) count > 
648                         (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
649     throw no_memory;
650
651   size += count * sizeof (jobject);
652
653   jclass klass = _Jv_GetArrayClass (elementClass,
654                                     elementClass->getClassLoaderInternal());
655
656   obj = (jobjectArray) _Jv_AllocArray (size, klass);
657   // Cast away const.
658   jsize *lp = const_cast<jsize *> (&obj->length);
659   *lp = count;
660   // We know the allocator returns zeroed memory.  So don't bother
661   // zeroing it again.
662   if (init)
663     {
664       jobject *ptr = elements(obj);
665       while (--count >= 0)
666         *ptr++ = init;
667     }
668   return obj;
669 }
670
671 // Allocate a new array of primitives.  ELTYPE is the type of the
672 // element, COUNT is the size of the array.
673 jobject
674 _Jv_NewPrimArray (jclass eltype, jint count)
675 {
676   int elsize = eltype->size();
677   if (__builtin_expect (count < 0, false))
678     throw new java::lang::NegativeArraySizeException;
679
680   JvAssert (eltype->isPrimitive ());
681   jobject dummy = NULL;
682   size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
683
684   // Check for overflow.
685   if (__builtin_expect ((size_t) count > 
686                         (MAX_OBJECT_SIZE - size) / elsize, false))
687     throw no_memory;
688
689   jclass klass = _Jv_GetArrayClass (eltype, 0);
690
691 # ifdef JV_HASH_SYNCHRONIZATION
692   // Since the vtable is always statically allocated,
693   // these are completely pointerfree!  Make sure the GC doesn't touch them.
694   __JArray *arr =
695     (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
696   memset((char *)arr + size, 0, elsize * count);
697 # else
698   __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
699   // Note that we assume we are given zeroed memory by the allocator.
700 # endif
701   // Cast away const.
702   jsize *lp = const_cast<jsize *> (&arr->length);
703   *lp = count;
704
705   return arr;
706 }
707
708 jobject
709 _Jv_NewArray (jint type, jint size)
710 {
711   switch (type)
712     {
713       case  4:  return JvNewBooleanArray (size);
714       case  5:  return JvNewCharArray (size);
715       case  6:  return JvNewFloatArray (size);
716       case  7:  return JvNewDoubleArray (size);
717       case  8:  return JvNewByteArray (size);
718       case  9:  return JvNewShortArray (size);
719       case 10:  return JvNewIntArray (size);
720       case 11:  return JvNewLongArray (size);
721     }
722   throw new java::lang::InternalError
723     (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
724 }
725
726 // Allocate a possibly multi-dimensional array but don't check that
727 // any array length is <0.
728 static jobject
729 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
730 {
731   JvAssert (type->isArray());
732   jclass element_type = type->getComponentType();
733   jobject result;
734   if (element_type->isPrimitive())
735     result = _Jv_NewPrimArray (element_type, sizes[0]);
736   else
737     result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
738
739   if (dimensions > 1)
740     {
741       JvAssert (! element_type->isPrimitive());
742       JvAssert (element_type->isArray());
743       jobject *contents = elements ((jobjectArray) result);
744       for (int i = 0; i < sizes[0]; ++i)
745         contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
746                                                   sizes + 1);
747     }
748
749   return result;
750 }
751
752 jobject
753 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
754 {
755   for (int i = 0; i < dimensions; ++i)
756     if (sizes[i] < 0)
757       throw new java::lang::NegativeArraySizeException;
758
759   return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
760 }
761
762 jobject
763 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
764 {
765   // Creating an array of an unresolved type is impossible. So we throw
766   // the NoClassDefFoundError.
767   if (_Jv_IsPhantomClass(array_type))
768     throw new java::lang::NoClassDefFoundError(array_type->getName());
769
770   va_list args;
771   jint sizes[dimensions];
772   va_start (args, dimensions);
773   for (int i = 0; i < dimensions; ++i)
774     {
775       jint size = va_arg (args, jint);
776       if (size < 0)
777         throw new java::lang::NegativeArraySizeException;
778       sizes[i] = size;
779     }
780   va_end (args);
781
782   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
783 }
784
785 \f
786
787 // Ensure 8-byte alignment, for hash synchronization.
788 #define DECLARE_PRIM_TYPE(NAME)                 \
789   java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
790
791 DECLARE_PRIM_TYPE(byte)
792 DECLARE_PRIM_TYPE(short)
793 DECLARE_PRIM_TYPE(int)
794 DECLARE_PRIM_TYPE(long)
795 DECLARE_PRIM_TYPE(boolean)
796 DECLARE_PRIM_TYPE(char)
797 DECLARE_PRIM_TYPE(float)
798 DECLARE_PRIM_TYPE(double)
799 DECLARE_PRIM_TYPE(void)
800
801 void
802 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
803 {    
804   using namespace java::lang::reflect;
805
806   // We must set the vtable for the class; the Java constructor
807   // doesn't do this.
808   (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
809
810   // Initialize the fields we care about.  We do this in the same
811   // order they are declared in Class.h.
812   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
813   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
814   cl->method_count = sig;
815   cl->size_in_bytes = len;
816   cl->vtable = JV_PRIMITIVE_VTABLE;
817   cl->state = JV_STATE_DONE;
818   cl->depth = -1;
819 }
820
821 jclass
822 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
823                             char **endp)
824 {
825   // First count arrays.
826   int array_count = 0;
827   while (*sig == '[')
828     {
829       ++sig;
830       ++array_count;
831     }
832
833   jclass result = NULL;
834   switch (*sig)
835     {
836     case 'B':
837       result = JvPrimClass (byte);
838       break;
839     case 'S':
840       result = JvPrimClass (short);
841       break;
842     case 'I':
843       result = JvPrimClass (int);
844       break;
845     case 'J':
846       result = JvPrimClass (long);
847       break;
848     case 'Z':
849       result = JvPrimClass (boolean);
850       break;
851     case 'C':
852       result = JvPrimClass (char);
853       break;
854     case 'F':
855       result = JvPrimClass (float);
856       break;
857     case 'D':
858       result = JvPrimClass (double);
859       break;
860     case 'V':
861       result = JvPrimClass (void);
862       break;
863     case 'L':
864       {
865         char *save = ++sig;
866         while (*sig && *sig != ';')
867           ++sig;
868         // Do nothing if signature appears to be malformed.
869         if (*sig == ';')
870           {
871             _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
872             result = _Jv_FindClass (name, loader);
873           }
874         break;
875       }
876     default:
877       // Do nothing -- bad signature.
878       break;
879     }
880
881   if (endp)
882     {
883       // Not really the "end", but the last valid character that we
884       // looked at.
885       *endp = sig;
886     }
887
888   if (! result)
889     return NULL;
890
891   // Find arrays.
892   while (array_count-- > 0)
893     result = _Jv_GetArrayClass (result, loader);
894   return result;
895 }
896
897
898 jclass
899 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
900                                        char **endp)
901 {
902   jclass klass;
903
904   try
905     {
906       klass = _Jv_FindClassFromSignature(sig, loader, endp);
907     }
908   catch (java::lang::NoClassDefFoundError *ncdfe)
909     {
910       return NULL;
911     }
912   catch (java::lang::ClassNotFoundException *cnfe)
913     {
914       return NULL;
915     }
916
917   return klass;
918 }
919
920 JArray<jstring> *
921 JvConvertArgv (int argc, const char **argv)
922 {
923   if (argc < 0)
924     argc = 0;
925   jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
926   jobject *ptr = elements(ar);
927   jbyteArray bytes = NULL;
928   for (int i = 0;  i < argc;  i++)
929     {
930       const char *arg = argv[i];
931       int len = strlen (arg);
932       if (bytes == NULL || bytes->length < len)
933         bytes = JvNewByteArray (len);
934       jbyte *bytePtr = elements (bytes);
935       // We assume jbyte == char.
936       memcpy (bytePtr, arg, len);
937
938       // Now convert using the default encoding.
939       *ptr++ = new java::lang::String (bytes, 0, len);
940     }
941   return (JArray<jstring>*) ar;
942 }
943
944 // FIXME: These variables are static so that they will be
945 // automatically scanned by the Boehm collector.  This is needed
946 // because with qthreads the collector won't scan the initial stack --
947 // it will only scan the qthreads stacks.
948
949 // Command line arguments.
950 static JArray<jstring> *arg_vec;
951
952 // The primary thread.
953 static java::lang::Thread *main_thread;
954
955 #ifndef DISABLE_GETENV_PROPERTIES
956
957 static char *
958 next_property_key (char *s, size_t *length)
959 {
960   size_t l = 0;
961
962   JvAssert (s);
963
964   // Skip over whitespace
965   while (isspace (*s))
966     s++;
967
968   // If we've reached the end, return NULL.  Also return NULL if for
969   // some reason we've come across a malformed property string.
970   if (*s == 0
971       || *s == ':'
972       || *s == '=')
973     return NULL;
974
975   // Determine the length of the property key.
976   while (s[l] != 0
977          && ! isspace (s[l])
978          && s[l] != ':'
979          && s[l] != '=')
980     {
981       if (s[l] == '\\'
982           && s[l+1] != 0)
983         l++;
984       l++;
985     }
986
987   *length = l;
988
989   return s;
990 }
991
992 static char *
993 next_property_value (char *s, size_t *length)
994 {
995   size_t l = 0;
996
997   JvAssert (s);
998
999   while (isspace (*s))
1000     s++;
1001
1002   if (*s == ':'
1003       || *s == '=')
1004     s++;
1005
1006   while (isspace (*s))
1007     s++;
1008
1009   // Determine the length of the property value.
1010   while (s[l] != 0
1011          && ! isspace (s[l])
1012          && s[l] != ':'
1013          && s[l] != '=')
1014     {
1015       if (s[l] == '\\'
1016           && s[l+1] != 0)
1017         l += 2;
1018       else
1019         l++;
1020     }
1021
1022   *length = l;
1023
1024   return s;
1025 }
1026
1027 static void
1028 process_gcj_properties ()
1029 {
1030   char *props = getenv("GCJ_PROPERTIES");
1031
1032   if (NULL == props)
1033     return;
1034
1035   // Later on we will write \0s into this string.  It is simplest to
1036   // just duplicate it here.
1037   props = strdup (props);
1038
1039   char *p = props;
1040   size_t length;
1041   size_t property_count = 0;
1042
1043   // Whip through props quickly in order to count the number of
1044   // property values.
1045   while (p && (p = next_property_key (p, &length)))
1046     {
1047       // Skip to the end of the key
1048       p += length;
1049
1050       p = next_property_value (p, &length);
1051       if (p)
1052         p += length;
1053       
1054       property_count++;
1055     }
1056
1057   // Allocate an array of property value/key pairs.
1058   _Jv_Environment_Properties = 
1059     (property_pair *) malloc (sizeof(property_pair) 
1060                               * (property_count + 1));
1061
1062   // Go through the properties again, initializing _Jv_Properties
1063   // along the way.
1064   p = props;
1065   property_count = 0;
1066   while (p && (p = next_property_key (p, &length)))
1067     {
1068       _Jv_Environment_Properties[property_count].key = p;
1069       _Jv_Environment_Properties[property_count].key_length = length;
1070
1071       // Skip to the end of the key
1072       p += length;
1073
1074       p = next_property_value (p, &length);
1075       
1076       _Jv_Environment_Properties[property_count].value = p;
1077       _Jv_Environment_Properties[property_count].value_length = length;
1078
1079       if (p)
1080         p += length;
1081
1082       property_count++;
1083     }
1084   memset ((void *) &_Jv_Environment_Properties[property_count], 
1085           0, sizeof (property_pair));
1086
1087   // Null terminate the strings.
1088   for (property_pair *prop = &_Jv_Environment_Properties[0];
1089        prop->key != NULL;
1090        prop++)
1091     {
1092       prop->key[prop->key_length] = 0;
1093       prop->value[prop->value_length] = 0;
1094     }
1095 }
1096 #endif // DISABLE_GETENV_PROPERTIES
1097
1098 namespace gcj
1099 {
1100   _Jv_Utf8Const *void_signature;
1101   _Jv_Utf8Const *clinit_name;
1102   _Jv_Utf8Const *init_name;
1103   _Jv_Utf8Const *finit_name;
1104   
1105   bool runtimeInitialized = false;
1106   
1107   // When true, print debugging information about class loading.
1108   bool verbose_class_flag;
1109   
1110   // When true, enable the bytecode verifier and BC-ABI type verification. 
1111   bool verifyClasses = true;
1112
1113   // Thread stack size specified by the -Xss runtime argument.
1114   size_t stack_size = 0;
1115 }
1116
1117 // We accept all non-standard options accepted by Sun's java command,
1118 // for compatibility with existing application launch scripts.
1119 static jint
1120 parse_x_arg (char* option_string)
1121 {
1122   if (strlen (option_string) <= 0)
1123     return -1;
1124
1125   if (! strcmp (option_string, "int"))
1126     {
1127       // FIXME: this should cause the vm to never load shared objects
1128     }
1129   else if (! strcmp (option_string, "mixed"))
1130     {
1131       // FIXME: allow interpreted and native code
1132     }
1133   else if (! strcmp (option_string, "batch"))
1134     {
1135       // FIXME: disable background JIT'ing
1136     }
1137   else if (! strcmp (option_string, "debug"))
1138     {
1139       // FIXME: add JDWP/JVMDI support
1140     }
1141   else if (! strncmp (option_string, "bootclasspath:", 14))
1142     {
1143       // FIXME: add a parse_bootclasspath_arg function
1144     }
1145   else if (! strncmp (option_string, "bootclasspath/a:", 16))
1146     {
1147     }
1148   else if (! strncmp (option_string, "bootclasspath/p:", 16))
1149     {
1150     }
1151   else if (! strcmp (option_string, "check:jni"))
1152     {
1153       // FIXME: enable strict JNI checking
1154     }
1155   else if (! strcmp (option_string, "future"))
1156     {
1157       // FIXME: enable strict class file format checks
1158     }
1159   else if (! strcmp (option_string, "noclassgc"))
1160     {
1161       // FIXME: disable garbage collection for classes
1162     }
1163   else if (! strcmp (option_string, "incgc"))
1164     {
1165       // FIXME: incremental garbage collection
1166     }
1167   else if (! strncmp (option_string, "loggc:", 6))
1168     {
1169       if (option_string[6] == '\0')
1170         {
1171           fprintf (stderr,
1172                    "libgcj: filename argument expected for loggc option\n");
1173           return -1;
1174         }
1175       // FIXME: set gc logging filename
1176     }
1177   else if (! strncmp (option_string, "ms", 2))
1178     {
1179       // FIXME: ignore this option until PR 20699 is fixed.
1180       // _Jv_SetInitialHeapSize (option_string + 2);
1181     }
1182   else if (! strncmp (option_string, "mx", 2))
1183     _Jv_SetMaximumHeapSize (option_string + 2);
1184   else if (! strcmp (option_string, "prof"))
1185     {
1186       // FIXME: enable profiling of program running in vm
1187     }
1188   else if (! strncmp (option_string, "runhprof:", 9))
1189     {
1190       // FIXME: enable specific type of vm profiling.  add a
1191       // parse_runhprof_arg function
1192     }
1193   else if (! strcmp (option_string, "rs"))
1194     {
1195       // FIXME: reduced system signal usage.  disable thread dumps,
1196       // only terminate in response to user-initiated calls,
1197       // e.g. System.exit()
1198     }
1199   else if (! strncmp (option_string, "ss", 2))
1200     {
1201       _Jv_SetStackSize (option_string + 2);
1202     }
1203   else if (! strcmp (option_string, "X:+UseAltSigs"))
1204     {
1205       // FIXME: use signals other than SIGUSR1 and SIGUSR2
1206     }
1207   else if (! strcmp (option_string, "share:off"))
1208     {
1209       // FIXME: don't share class data
1210     }
1211   else if (! strcmp (option_string, "share:auto"))
1212     {
1213       // FIXME: share class data where possible
1214     }
1215   else if (! strcmp (option_string, "share:on"))
1216     {
1217       // FIXME: fail if impossible to share class data
1218     }
1219
1220   return 0;
1221 }
1222
1223 static jint
1224 parse_verbose_args (char* option_string,
1225                     bool ignore_unrecognized)
1226 {
1227   size_t len = sizeof ("-verbose") - 1;
1228
1229   if (strlen (option_string) < len)
1230     return -1;
1231
1232   if (option_string[len] == ':'
1233       && option_string[len + 1] != '\0')
1234     {
1235       char* verbose_args = option_string + len + 1;
1236
1237       do
1238         {
1239           if (! strncmp (verbose_args,
1240                          "gc", sizeof ("gc") - 1))
1241             {
1242               if (verbose_args[sizeof ("gc") - 1] == '\0'
1243                   || verbose_args[sizeof ("gc") - 1] == ',')
1244                 {
1245                   // FIXME: we should add functions to boehm-gc that
1246                   // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1247                   // GC_print_back_height.
1248                   verbose_args += sizeof ("gc") - 1;
1249                 }
1250               else
1251                 {
1252                 verbose_arg_err:
1253                   fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1254                            option_string);
1255                   return -1;
1256                 }
1257             }
1258           else if (! strncmp (verbose_args,
1259                               "class",
1260                               sizeof ("class") - 1))
1261             {
1262               if (verbose_args[sizeof ("class") - 1] == '\0'
1263                   || verbose_args[sizeof ("class") - 1] == ',')
1264                 {
1265                   gcj::verbose_class_flag = true;
1266                   verbose_args += sizeof ("class") - 1;
1267                 }
1268               else
1269                 goto verbose_arg_err;
1270             }
1271           else if (! strncmp (verbose_args, "jni",
1272                               sizeof ("jni") - 1))
1273             {
1274               if (verbose_args[sizeof ("jni") - 1] == '\0'
1275                   || verbose_args[sizeof ("jni") - 1] == ',')
1276                 {
1277                   // FIXME: enable JNI messages.
1278                   verbose_args += sizeof ("jni") - 1;
1279                 }
1280               else
1281                 goto verbose_arg_err;
1282             }
1283           else if (ignore_unrecognized
1284                    && verbose_args[0] == 'X')
1285             {
1286               // ignore unrecognized non-standard verbose option
1287               while (verbose_args[0] != '\0'
1288                      && verbose_args[0] != ',')
1289                 verbose_args++;
1290             }
1291           else if (verbose_args[0] == ',')
1292             {
1293               verbose_args++;
1294             }
1295           else
1296             goto verbose_arg_err;
1297
1298           if (verbose_args[0] == ',')
1299             verbose_args++;
1300         }
1301       while (verbose_args[0] != '\0');
1302     }
1303   else if (option_string[len] == 'g'
1304            && option_string[len + 1] == 'c'
1305            && option_string[len + 2] == '\0')
1306     {
1307       // FIXME: we should add functions to boehm-gc that
1308       // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1309       // GC_print_back_height.
1310       return 0;
1311     }
1312   else if (option_string[len] == '\0')
1313     {
1314       gcj::verbose_class_flag = true;
1315       return 0;
1316     }
1317   else
1318     {
1319       // unrecognized option beginning with -verbose
1320       return -1;
1321     }
1322   return 0;
1323 }
1324
1325 static jint
1326 parse_init_args (JvVMInitArgs* vm_args)
1327 {
1328   // if _Jv_Compiler_Properties is non-NULL then it needs to be
1329   // re-allocated dynamically.
1330   if (_Jv_Compiler_Properties)
1331     {
1332       const char** props = _Jv_Compiler_Properties;
1333       _Jv_Compiler_Properties = NULL;
1334
1335       for (int i = 0; props[i]; i++)
1336         {
1337           _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1338             (_Jv_Compiler_Properties,
1339              (_Jv_Properties_Count + 1) * sizeof (const char*));
1340           _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1341         }
1342     }
1343
1344   if (vm_args == NULL)
1345     return 0;
1346
1347   for (int i = 0; i < vm_args->nOptions; ++i)
1348     {
1349       char* option_string = vm_args->options[i].optionString;
1350       if (! strcmp (option_string, "vfprintf")
1351           || ! strcmp (option_string, "exit")
1352           || ! strcmp (option_string, "abort"))
1353         {
1354           // FIXME: we are required to recognize these, but for
1355           // now we don't handle them in any way.
1356           continue;
1357         }
1358       else if (! strncmp (option_string,
1359                           "-verbose", sizeof ("-verbose") - 1))
1360         {
1361           jint result = parse_verbose_args (option_string,
1362                                             vm_args->ignoreUnrecognized);
1363           if (result < 0)
1364             return result;
1365         }
1366       else if (! strncmp (option_string, "-D", 2))
1367         {
1368           _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1369             (_Jv_Compiler_Properties,
1370              (_Jv_Properties_Count + 1) * sizeof (char*));
1371
1372           _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1373             strdup (option_string + 2);
1374
1375           continue;
1376         }
1377       else if (vm_args->ignoreUnrecognized)
1378         {
1379           if (option_string[0] == '_')
1380             parse_x_arg (option_string + 1);
1381           else if (! strncmp (option_string, "-X", 2))
1382             parse_x_arg (option_string + 2);
1383           else
1384             {
1385             unknown_option:
1386               fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1387               return -1;
1388             }
1389         }
1390       else
1391         goto unknown_option;
1392     }
1393   return 0;
1394 }
1395
1396 jint
1397 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1398 {
1399   using namespace gcj;
1400
1401   if (runtimeInitialized)
1402     return -1;
1403
1404   runtimeInitialized = true;
1405
1406   jint result = parse_init_args (vm_args);
1407   if (result < 0)
1408     return -1;
1409
1410   PROCESS_GCJ_PROPERTIES;
1411
1412   /* Threads must be initialized before the GC, so that it inherits the
1413      signal mask.  */
1414   _Jv_InitThreads ();
1415   _Jv_InitGC ();
1416   _Jv_InitializeSyncMutex ();
1417   
1418 #ifdef INTERPRETER
1419   _Jv_InitInterpreter ();
1420 #endif  
1421
1422 #ifdef HANDLE_SEGV
1423   INIT_SEGV;
1424 #endif
1425
1426 #ifdef HANDLE_FPE
1427   INIT_FPE;
1428 #endif
1429
1430   /* Initialize Utf8 constants declared in jvm.h. */
1431   void_signature = _Jv_makeUtf8Const ("()V", 3);
1432   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1433   init_name = _Jv_makeUtf8Const ("<init>", 6);
1434   finit_name = _Jv_makeUtf8Const ("finit$", 6);
1435
1436   /* Initialize built-in classes to represent primitive TYPEs. */
1437   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1);
1438   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2);
1439   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4);
1440   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8);
1441   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1442   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2);
1443   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4);
1444   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8);
1445   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0);
1446
1447   // Turn stack trace generation off while creating exception objects.
1448   _Jv_InitClass (&java::lang::VMThrowable::class$);
1449   java::lang::VMThrowable::trace_enabled = 0;
1450   
1451   // We have to initialize this fairly early, to avoid circular class
1452   // initialization.  In particular we want to start the
1453   // initialization of ClassLoader before we start the initialization
1454   // of VMClassLoader.
1455   _Jv_InitClass (&java::lang::ClassLoader::class$);
1456
1457   // Set up the system class loader and the bootstrap class loader.
1458   gnu::gcj::runtime::ExtensionClassLoader::initialize();
1459   java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1460
1461   _Jv_RegisterBootstrapPackages();
1462
1463   no_memory = new java::lang::OutOfMemoryError;
1464
1465   java::lang::VMThrowable::trace_enabled = 1;
1466
1467 #ifdef USE_LTDL
1468   LTDL_SET_PRELOADED_SYMBOLS ();
1469 #endif
1470
1471   _Jv_platform_initialize ();
1472
1473   _Jv_JNI_Init ();
1474
1475   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1476
1477   // Start the GC finalizer thread.  A VirtualMachineError can be
1478   // thrown by the runtime if, say, threads aren't available.
1479   try
1480     {
1481       using namespace gnu::gcj::runtime;
1482       FinalizerThread *ft = new FinalizerThread ();
1483       ft->start ();
1484     }
1485   catch (java::lang::VirtualMachineError *ignore)
1486     {
1487     }
1488
1489   return 0;
1490 }
1491
1492 void
1493 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1494              const char **argv, bool is_jar)
1495 {
1496 #ifndef DISABLE_MAIN_ARGS
1497   _Jv_SetArgs (argc, argv);
1498 #endif
1499
1500   java::lang::Runtime *runtime = NULL;
1501
1502   try
1503     {
1504       if (_Jv_CreateJavaVM (vm_args) < 0)
1505         {
1506           fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1507           exit (1);
1508         }
1509
1510       // Get the Runtime here.  We want to initialize it before searching
1511       // for `main'; that way it will be set up if `main' is a JNI method.
1512       runtime = java::lang::Runtime::getRuntime ();
1513
1514 #ifdef DISABLE_MAIN_ARGS
1515       arg_vec = JvConvertArgv (0, 0);
1516 #else      
1517       arg_vec = JvConvertArgv (argc - 1, argv + 1);
1518 #endif
1519
1520       using namespace gnu::java::lang;
1521       if (klass)
1522         main_thread = new MainThread (klass, arg_vec);
1523       else
1524         main_thread = new MainThread (JvNewStringLatin1 (name),
1525                                       arg_vec, is_jar);
1526     }
1527   catch (java::lang::Throwable *t)
1528     {
1529       java::lang::System::err->println (JvNewStringLatin1 
1530         ("Exception during runtime initialization"));
1531       t->printStackTrace();
1532       if (runtime)
1533         java::lang::Runtime::exitNoChecksAccessor (1);
1534       // In case the runtime creation failed.
1535       ::exit (1);
1536     }
1537
1538   _Jv_AttachCurrentThread (main_thread);
1539   _Jv_ThreadRun (main_thread);
1540
1541   // If we got here then something went wrong, as MainThread is not
1542   // supposed to terminate.
1543   ::exit (1);
1544 }
1545
1546 void
1547 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
1548              bool is_jar)
1549 {
1550   _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1551 }
1552
1553 void
1554 JvRunMain (jclass klass, int argc, const char **argv)
1555 {
1556   _Jv_RunMain (klass, NULL, argc, argv, false);
1557 }
1558
1559 \f
1560
1561 // Parse a string and return a heap size.
1562 static size_t
1563 parse_memory_size (const char *spec)
1564 {
1565   char *end;
1566   unsigned long val = strtoul (spec, &end, 10);
1567   if (*end == 'k' || *end == 'K')
1568     val *= 1024;
1569   else if (*end == 'm' || *end == 'M')
1570     val *= 1048576;
1571   return (size_t) val;
1572 }
1573
1574 // Set the initial heap size.  This might be ignored by the GC layer.
1575 // This must be called before _Jv_RunMain.
1576 void
1577 _Jv_SetInitialHeapSize (const char *arg)
1578 {
1579   size_t size = parse_memory_size (arg);
1580   _Jv_GCSetInitialHeapSize (size);
1581 }
1582
1583 // Set the maximum heap size.  This might be ignored by the GC layer.
1584 // This must be called before _Jv_RunMain.
1585 void
1586 _Jv_SetMaximumHeapSize (const char *arg)
1587 {
1588   size_t size = parse_memory_size (arg);
1589   _Jv_GCSetMaximumHeapSize (size);
1590 }
1591
1592 void
1593 _Jv_SetStackSize (const char *arg)
1594 {
1595   size_t size = parse_memory_size (arg);
1596   gcj::stack_size = size;
1597 }
1598
1599 void *
1600 _Jv_Malloc (jsize size)
1601 {
1602   if (__builtin_expect (size == 0, false))
1603     size = 1;
1604   void *ptr = malloc ((size_t) size);
1605   if (__builtin_expect (ptr == NULL, false))
1606     throw no_memory;
1607   return ptr;
1608 }
1609
1610 void *
1611 _Jv_Realloc (void *ptr, jsize size)
1612 {
1613   if (__builtin_expect (size == 0, false))
1614     size = 1;
1615   ptr = realloc (ptr, (size_t) size);
1616   if (__builtin_expect (ptr == NULL, false))
1617     throw no_memory;
1618   return ptr;
1619 }
1620
1621 void *
1622 _Jv_MallocUnchecked (jsize size)
1623 {
1624   if (__builtin_expect (size == 0, false))
1625     size = 1;
1626   return malloc ((size_t) size);
1627 }
1628
1629 void
1630 _Jv_Free (void* ptr)
1631 {
1632   return free (ptr);
1633 }
1634
1635 \f
1636
1637 // In theory, these routines can be #ifdef'd away on machines which
1638 // support divide overflow signals.  However, we never know if some
1639 // code might have been compiled with "-fuse-divide-subroutine", so we
1640 // always include them in libgcj.
1641
1642 jint
1643 _Jv_divI (jint dividend, jint divisor)
1644 {
1645   if (__builtin_expect (divisor == 0, false))
1646     {
1647       java::lang::ArithmeticException *arithexception 
1648         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1649       throw arithexception;
1650     }
1651   
1652   if (dividend == (jint) 0x80000000L && divisor == -1)
1653     return dividend;
1654
1655   return dividend / divisor;
1656 }
1657
1658 jint
1659 _Jv_remI (jint dividend, jint divisor)
1660 {
1661   if (__builtin_expect (divisor == 0, false))
1662     {
1663       java::lang::ArithmeticException *arithexception 
1664         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1665       throw arithexception;
1666     }
1667   
1668   if (dividend == (jint) 0x80000000L && divisor == -1)
1669     return 0;
1670   
1671   return dividend % divisor;
1672 }
1673
1674 jlong
1675 _Jv_divJ (jlong dividend, jlong divisor)
1676 {
1677   if (__builtin_expect (divisor == 0, false))
1678     {
1679       java::lang::ArithmeticException *arithexception 
1680         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1681       throw arithexception;
1682     }
1683
1684   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1685     return dividend;
1686
1687   return dividend / divisor;
1688 }
1689
1690 jlong
1691 _Jv_remJ (jlong dividend, jlong divisor)
1692 {
1693   if (__builtin_expect (divisor == 0, false))
1694     {
1695       java::lang::ArithmeticException *arithexception 
1696         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1697       throw arithexception;
1698     }
1699
1700   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1701     return 0;
1702
1703   return dividend % divisor;
1704 }
1705
1706 \f
1707
1708 // Return true if SELF_KLASS can access a field or method in
1709 // OTHER_KLASS.  The field or method's access flags are specified in
1710 // FLAGS.
1711 jboolean
1712 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1713 {
1714   using namespace java::lang::reflect;
1715   return ((self_klass == other_klass)
1716           || ((flags & Modifier::PUBLIC) != 0)
1717           || (((flags & Modifier::PROTECTED) != 0)
1718               && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1719           || (((flags & Modifier::PRIVATE) == 0)
1720               && _Jv_ClassNameSamePackage (self_klass->name,
1721                                            other_klass->name)));
1722 }