OSDN Git Service

* gcc/objc/Make-lang.in (OBJC): Remove
[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   va_list args;
766   jint sizes[dimensions];
767   va_start (args, dimensions);
768   for (int i = 0; i < dimensions; ++i)
769     {
770       jint size = va_arg (args, jint);
771       if (size < 0)
772         throw new java::lang::NegativeArraySizeException;
773       sizes[i] = size;
774     }
775   va_end (args);
776
777   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
778 }
779
780 \f
781
782 // Ensure 8-byte alignment, for hash synchronization.
783 #define DECLARE_PRIM_TYPE(NAME)                 \
784   java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
785
786 DECLARE_PRIM_TYPE(byte)
787 DECLARE_PRIM_TYPE(short)
788 DECLARE_PRIM_TYPE(int)
789 DECLARE_PRIM_TYPE(long)
790 DECLARE_PRIM_TYPE(boolean)
791 DECLARE_PRIM_TYPE(char)
792 DECLARE_PRIM_TYPE(float)
793 DECLARE_PRIM_TYPE(double)
794 DECLARE_PRIM_TYPE(void)
795
796 void
797 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
798 {    
799   using namespace java::lang::reflect;
800
801   // We must set the vtable for the class; the Java constructor
802   // doesn't do this.
803   (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
804
805   // Initialize the fields we care about.  We do this in the same
806   // order they are declared in Class.h.
807   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
808   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
809   cl->method_count = sig;
810   cl->size_in_bytes = len;
811   cl->vtable = JV_PRIMITIVE_VTABLE;
812   cl->state = JV_STATE_DONE;
813   cl->depth = -1;
814 }
815
816 jclass
817 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
818                             char **endp)
819 {
820   // First count arrays.
821   int array_count = 0;
822   while (*sig == '[')
823     {
824       ++sig;
825       ++array_count;
826     }
827
828   jclass result = NULL;
829   switch (*sig)
830     {
831     case 'B':
832       result = JvPrimClass (byte);
833       break;
834     case 'S':
835       result = JvPrimClass (short);
836       break;
837     case 'I':
838       result = JvPrimClass (int);
839       break;
840     case 'J':
841       result = JvPrimClass (long);
842       break;
843     case 'Z':
844       result = JvPrimClass (boolean);
845       break;
846     case 'C':
847       result = JvPrimClass (char);
848       break;
849     case 'F':
850       result = JvPrimClass (float);
851       break;
852     case 'D':
853       result = JvPrimClass (double);
854       break;
855     case 'V':
856       result = JvPrimClass (void);
857       break;
858     case 'L':
859       {
860         char *save = ++sig;
861         while (*sig && *sig != ';')
862           ++sig;
863         // Do nothing if signature appears to be malformed.
864         if (*sig == ';')
865           {
866             _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
867             result = _Jv_FindClass (name, loader);
868           }
869         break;
870       }
871     default:
872       // Do nothing -- bad signature.
873       break;
874     }
875
876   if (endp)
877     {
878       // Not really the "end", but the last valid character that we
879       // looked at.
880       *endp = sig;
881     }
882
883   if (! result)
884     return NULL;
885
886   // Find arrays.
887   while (array_count-- > 0)
888     result = _Jv_GetArrayClass (result, loader);
889   return result;
890 }
891
892
893 jclass
894 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
895                                        char **endp)
896 {
897   jclass klass;
898
899   try
900     {
901       klass = _Jv_FindClassFromSignature(sig, loader, endp);
902     }
903   catch (java::lang::NoClassDefFoundError *ncdfe)
904     {
905       return NULL;
906     }
907   catch (java::lang::ClassNotFoundException *cnfe)
908     {
909       return NULL;
910     }
911
912   return klass;
913 }
914
915 JArray<jstring> *
916 JvConvertArgv (int argc, const char **argv)
917 {
918   if (argc < 0)
919     argc = 0;
920   jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
921   jobject *ptr = elements(ar);
922   jbyteArray bytes = NULL;
923   for (int i = 0;  i < argc;  i++)
924     {
925       const char *arg = argv[i];
926       int len = strlen (arg);
927       if (bytes == NULL || bytes->length < len)
928         bytes = JvNewByteArray (len);
929       jbyte *bytePtr = elements (bytes);
930       // We assume jbyte == char.
931       memcpy (bytePtr, arg, len);
932
933       // Now convert using the default encoding.
934       *ptr++ = new java::lang::String (bytes, 0, len);
935     }
936   return (JArray<jstring>*) ar;
937 }
938
939 // FIXME: These variables are static so that they will be
940 // automatically scanned by the Boehm collector.  This is needed
941 // because with qthreads the collector won't scan the initial stack --
942 // it will only scan the qthreads stacks.
943
944 // Command line arguments.
945 static JArray<jstring> *arg_vec;
946
947 // The primary thread.
948 static java::lang::Thread *main_thread;
949
950 #ifndef DISABLE_GETENV_PROPERTIES
951
952 static char *
953 next_property_key (char *s, size_t *length)
954 {
955   size_t l = 0;
956
957   JvAssert (s);
958
959   // Skip over whitespace
960   while (isspace (*s))
961     s++;
962
963   // If we've reached the end, return NULL.  Also return NULL if for
964   // some reason we've come across a malformed property string.
965   if (*s == 0
966       || *s == ':'
967       || *s == '=')
968     return NULL;
969
970   // Determine the length of the property key.
971   while (s[l] != 0
972          && ! isspace (s[l])
973          && s[l] != ':'
974          && s[l] != '=')
975     {
976       if (s[l] == '\\'
977           && s[l+1] != 0)
978         l++;
979       l++;
980     }
981
982   *length = l;
983
984   return s;
985 }
986
987 static char *
988 next_property_value (char *s, size_t *length)
989 {
990   size_t l = 0;
991
992   JvAssert (s);
993
994   while (isspace (*s))
995     s++;
996
997   if (*s == ':'
998       || *s == '=')
999     s++;
1000
1001   while (isspace (*s))
1002     s++;
1003
1004   // Determine the length of the property value.
1005   while (s[l] != 0
1006          && ! isspace (s[l])
1007          && s[l] != ':'
1008          && s[l] != '=')
1009     {
1010       if (s[l] == '\\'
1011           && s[l+1] != 0)
1012         l += 2;
1013       else
1014         l++;
1015     }
1016
1017   *length = l;
1018
1019   return s;
1020 }
1021
1022 static void
1023 process_gcj_properties ()
1024 {
1025   char *props = getenv("GCJ_PROPERTIES");
1026
1027   if (NULL == props)
1028     return;
1029
1030   // Later on we will write \0s into this string.  It is simplest to
1031   // just duplicate it here.
1032   props = strdup (props);
1033
1034   char *p = props;
1035   size_t length;
1036   size_t property_count = 0;
1037
1038   // Whip through props quickly in order to count the number of
1039   // property values.
1040   while (p && (p = next_property_key (p, &length)))
1041     {
1042       // Skip to the end of the key
1043       p += length;
1044
1045       p = next_property_value (p, &length);
1046       if (p)
1047         p += length;
1048       
1049       property_count++;
1050     }
1051
1052   // Allocate an array of property value/key pairs.
1053   _Jv_Environment_Properties = 
1054     (property_pair *) malloc (sizeof(property_pair) 
1055                               * (property_count + 1));
1056
1057   // Go through the properties again, initializing _Jv_Properties
1058   // along the way.
1059   p = props;
1060   property_count = 0;
1061   while (p && (p = next_property_key (p, &length)))
1062     {
1063       _Jv_Environment_Properties[property_count].key = p;
1064       _Jv_Environment_Properties[property_count].key_length = length;
1065
1066       // Skip to the end of the key
1067       p += length;
1068
1069       p = next_property_value (p, &length);
1070       
1071       _Jv_Environment_Properties[property_count].value = p;
1072       _Jv_Environment_Properties[property_count].value_length = length;
1073
1074       if (p)
1075         p += length;
1076
1077       property_count++;
1078     }
1079   memset ((void *) &_Jv_Environment_Properties[property_count], 
1080           0, sizeof (property_pair));
1081
1082   // Null terminate the strings.
1083   for (property_pair *prop = &_Jv_Environment_Properties[0];
1084        prop->key != NULL;
1085        prop++)
1086     {
1087       prop->key[prop->key_length] = 0;
1088       prop->value[prop->value_length] = 0;
1089     }
1090 }
1091 #endif // DISABLE_GETENV_PROPERTIES
1092
1093 namespace gcj
1094 {
1095   _Jv_Utf8Const *void_signature;
1096   _Jv_Utf8Const *clinit_name;
1097   _Jv_Utf8Const *init_name;
1098   _Jv_Utf8Const *finit_name;
1099   
1100   bool runtimeInitialized = false;
1101   
1102   // When true, print debugging information about class loading.
1103   bool verbose_class_flag;
1104   
1105   // When true, enable the bytecode verifier and BC-ABI type verification. 
1106   bool verifyClasses = true;
1107
1108   // Thread stack size specified by the -Xss runtime argument.
1109   size_t stack_size = 0;
1110 }
1111
1112 // We accept all non-standard options accepted by Sun's java command,
1113 // for compatibility with existing application launch scripts.
1114 static jint
1115 parse_x_arg (char* option_string)
1116 {
1117   if (strlen (option_string) <= 0)
1118     return -1;
1119
1120   if (! strcmp (option_string, "int"))
1121     {
1122       // FIXME: this should cause the vm to never load shared objects
1123     }
1124   else if (! strcmp (option_string, "mixed"))
1125     {
1126       // FIXME: allow interpreted and native code
1127     }
1128   else if (! strcmp (option_string, "batch"))
1129     {
1130       // FIXME: disable background JIT'ing
1131     }
1132   else if (! strcmp (option_string, "debug"))
1133     {
1134       // FIXME: add JDWP/JVMDI support
1135     }
1136   else if (! strncmp (option_string, "bootclasspath:", 14))
1137     {
1138       // FIXME: add a parse_bootclasspath_arg function
1139     }
1140   else if (! strncmp (option_string, "bootclasspath/a:", 16))
1141     {
1142     }
1143   else if (! strncmp (option_string, "bootclasspath/p:", 16))
1144     {
1145     }
1146   else if (! strcmp (option_string, "check:jni"))
1147     {
1148       // FIXME: enable strict JNI checking
1149     }
1150   else if (! strcmp (option_string, "future"))
1151     {
1152       // FIXME: enable strict class file format checks
1153     }
1154   else if (! strcmp (option_string, "noclassgc"))
1155     {
1156       // FIXME: disable garbage collection for classes
1157     }
1158   else if (! strcmp (option_string, "incgc"))
1159     {
1160       // FIXME: incremental garbage collection
1161     }
1162   else if (! strncmp (option_string, "loggc:", 6))
1163     {
1164       if (option_string[6] == '\0')
1165         {
1166           fprintf (stderr,
1167                    "libgcj: filename argument expected for loggc option\n");
1168           return -1;
1169         }
1170       // FIXME: set gc logging filename
1171     }
1172   else if (! strncmp (option_string, "ms", 2))
1173     {
1174       // FIXME: ignore this option until PR 20699 is fixed.
1175       // _Jv_SetInitialHeapSize (option_string + 2);
1176     }
1177   else if (! strncmp (option_string, "mx", 2))
1178     _Jv_SetMaximumHeapSize (option_string + 2);
1179   else if (! strcmp (option_string, "prof"))
1180     {
1181       // FIXME: enable profiling of program running in vm
1182     }
1183   else if (! strncmp (option_string, "runhprof:", 9))
1184     {
1185       // FIXME: enable specific type of vm profiling.  add a
1186       // parse_runhprof_arg function
1187     }
1188   else if (! strcmp (option_string, "rs"))
1189     {
1190       // FIXME: reduced system signal usage.  disable thread dumps,
1191       // only terminate in response to user-initiated calls,
1192       // e.g. System.exit()
1193     }
1194   else if (! strncmp (option_string, "ss", 2))
1195     {
1196       _Jv_SetStackSize (option_string + 2);
1197     }
1198   else if (! strcmp (option_string, "X:+UseAltSigs"))
1199     {
1200       // FIXME: use signals other than SIGUSR1 and SIGUSR2
1201     }
1202   else if (! strcmp (option_string, "share:off"))
1203     {
1204       // FIXME: don't share class data
1205     }
1206   else if (! strcmp (option_string, "share:auto"))
1207     {
1208       // FIXME: share class data where possible
1209     }
1210   else if (! strcmp (option_string, "share:on"))
1211     {
1212       // FIXME: fail if impossible to share class data
1213     }
1214
1215   return 0;
1216 }
1217
1218 static jint
1219 parse_verbose_args (char* option_string,
1220                     bool ignore_unrecognized)
1221 {
1222   size_t len = sizeof ("-verbose") - 1;
1223
1224   if (strlen (option_string) < len)
1225     return -1;
1226
1227   if (option_string[len] == ':'
1228       && option_string[len + 1] != '\0')
1229     {
1230       char* verbose_args = option_string + len + 1;
1231
1232       do
1233         {
1234           if (! strncmp (verbose_args,
1235                          "gc", sizeof ("gc") - 1))
1236             {
1237               if (verbose_args[sizeof ("gc") - 1] == '\0'
1238                   || verbose_args[sizeof ("gc") - 1] == ',')
1239                 {
1240                   // FIXME: we should add functions to boehm-gc that
1241                   // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1242                   // GC_print_back_height.
1243                   verbose_args += sizeof ("gc") - 1;
1244                 }
1245               else
1246                 {
1247                 verbose_arg_err:
1248                   fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1249                            option_string);
1250                   return -1;
1251                 }
1252             }
1253           else if (! strncmp (verbose_args,
1254                               "class",
1255                               sizeof ("class") - 1))
1256             {
1257               if (verbose_args[sizeof ("class") - 1] == '\0'
1258                   || verbose_args[sizeof ("class") - 1] == ',')
1259                 {
1260                   gcj::verbose_class_flag = true;
1261                   verbose_args += sizeof ("class") - 1;
1262                 }
1263               else
1264                 goto verbose_arg_err;
1265             }
1266           else if (! strncmp (verbose_args, "jni",
1267                               sizeof ("jni") - 1))
1268             {
1269               if (verbose_args[sizeof ("jni") - 1] == '\0'
1270                   || verbose_args[sizeof ("jni") - 1] == ',')
1271                 {
1272                   // FIXME: enable JNI messages.
1273                   verbose_args += sizeof ("jni") - 1;
1274                 }
1275               else
1276                 goto verbose_arg_err;
1277             }
1278           else if (ignore_unrecognized
1279                    && verbose_args[0] == 'X')
1280             {
1281               // ignore unrecognized non-standard verbose option
1282               while (verbose_args[0] != '\0'
1283                      && verbose_args[0] != ',')
1284                 verbose_args++;
1285             }
1286           else if (verbose_args[0] == ',')
1287             {
1288               verbose_args++;
1289             }
1290           else
1291             goto verbose_arg_err;
1292
1293           if (verbose_args[0] == ',')
1294             verbose_args++;
1295         }
1296       while (verbose_args[0] != '\0');
1297     }
1298   else if (option_string[len] == 'g'
1299            && option_string[len + 1] == 'c'
1300            && option_string[len + 2] == '\0')
1301     {
1302       // FIXME: we should add functions to boehm-gc that
1303       // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1304       // GC_print_back_height.
1305       return 0;
1306     }
1307   else if (option_string[len] == '\0')
1308     {
1309       gcj::verbose_class_flag = true;
1310       return 0;
1311     }
1312   else
1313     {
1314       // unrecognized option beginning with -verbose
1315       return -1;
1316     }
1317   return 0;
1318 }
1319
1320 static jint
1321 parse_init_args (JvVMInitArgs* vm_args)
1322 {
1323   // if _Jv_Compiler_Properties is non-NULL then it needs to be
1324   // re-allocated dynamically.
1325   if (_Jv_Compiler_Properties)
1326     {
1327       const char** props = _Jv_Compiler_Properties;
1328       _Jv_Compiler_Properties = NULL;
1329
1330       for (int i = 0; props[i]; i++)
1331         {
1332           _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1333             (_Jv_Compiler_Properties,
1334              (_Jv_Properties_Count + 1) * sizeof (const char*));
1335           _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1336         }
1337     }
1338
1339   if (vm_args == NULL)
1340     return 0;
1341
1342   for (int i = 0; i < vm_args->nOptions; ++i)
1343     {
1344       char* option_string = vm_args->options[i].optionString;
1345       if (! strcmp (option_string, "vfprintf")
1346           || ! strcmp (option_string, "exit")
1347           || ! strcmp (option_string, "abort"))
1348         {
1349           // FIXME: we are required to recognize these, but for
1350           // now we don't handle them in any way.
1351           continue;
1352         }
1353       else if (! strncmp (option_string,
1354                           "-verbose", sizeof ("-verbose") - 1))
1355         {
1356           jint result = parse_verbose_args (option_string,
1357                                             vm_args->ignoreUnrecognized);
1358           if (result < 0)
1359             return result;
1360         }
1361       else if (! strncmp (option_string, "-D", 2))
1362         {
1363           _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1364             (_Jv_Compiler_Properties,
1365              (_Jv_Properties_Count + 1) * sizeof (char*));
1366
1367           _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1368             strdup (option_string + 2);
1369
1370           continue;
1371         }
1372       else if (vm_args->ignoreUnrecognized)
1373         {
1374           if (option_string[0] == '_')
1375             parse_x_arg (option_string + 1);
1376           else if (! strncmp (option_string, "-X", 2))
1377             parse_x_arg (option_string + 2);
1378           else
1379             {
1380             unknown_option:
1381               fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1382               return -1;
1383             }
1384         }
1385       else
1386         goto unknown_option;
1387     }
1388   return 0;
1389 }
1390
1391 jint
1392 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1393 {
1394   using namespace gcj;
1395
1396   if (runtimeInitialized)
1397     return -1;
1398
1399   runtimeInitialized = true;
1400
1401   jint result = parse_init_args (vm_args);
1402   if (result < 0)
1403     return -1;
1404
1405   PROCESS_GCJ_PROPERTIES;
1406
1407   /* Threads must be initialized before the GC, so that it inherits the
1408      signal mask.  */
1409   _Jv_InitThreads ();
1410   _Jv_InitGC ();
1411   _Jv_InitializeSyncMutex ();
1412   
1413 #ifdef INTERPRETER
1414   _Jv_InitInterpreter ();
1415 #endif  
1416
1417 #ifdef HANDLE_SEGV
1418   INIT_SEGV;
1419 #endif
1420
1421 #ifdef HANDLE_FPE
1422   INIT_FPE;
1423 #endif
1424
1425   /* Initialize Utf8 constants declared in jvm.h. */
1426   void_signature = _Jv_makeUtf8Const ("()V", 3);
1427   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1428   init_name = _Jv_makeUtf8Const ("<init>", 6);
1429   finit_name = _Jv_makeUtf8Const ("finit$", 6);
1430
1431   /* Initialize built-in classes to represent primitive TYPEs. */
1432   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1);
1433   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2);
1434   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4);
1435   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8);
1436   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1437   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2);
1438   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4);
1439   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8);
1440   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0);
1441
1442   // Turn stack trace generation off while creating exception objects.
1443   _Jv_InitClass (&java::lang::VMThrowable::class$);
1444   java::lang::VMThrowable::trace_enabled = 0;
1445   
1446   // We have to initialize this fairly early, to avoid circular class
1447   // initialization.  In particular we want to start the
1448   // initialization of ClassLoader before we start the initialization
1449   // of VMClassLoader.
1450   _Jv_InitClass (&java::lang::ClassLoader::class$);
1451
1452   // Set up the system class loader and the bootstrap class loader.
1453   gnu::gcj::runtime::ExtensionClassLoader::initialize();
1454   java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1455
1456   _Jv_RegisterBootstrapPackages();
1457
1458   no_memory = new java::lang::OutOfMemoryError;
1459
1460   java::lang::VMThrowable::trace_enabled = 1;
1461
1462 #ifdef USE_LTDL
1463   LTDL_SET_PRELOADED_SYMBOLS ();
1464 #endif
1465
1466   _Jv_platform_initialize ();
1467
1468   _Jv_JNI_Init ();
1469
1470   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1471
1472   // Start the GC finalizer thread.  A VirtualMachineError can be
1473   // thrown by the runtime if, say, threads aren't available.
1474   try
1475     {
1476       using namespace gnu::gcj::runtime;
1477       FinalizerThread *ft = new FinalizerThread ();
1478       ft->start ();
1479     }
1480   catch (java::lang::VirtualMachineError *ignore)
1481     {
1482     }
1483
1484   return 0;
1485 }
1486
1487 void
1488 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1489              const char **argv, bool is_jar)
1490 {
1491 #ifndef DISABLE_MAIN_ARGS
1492   _Jv_SetArgs (argc, argv);
1493 #endif
1494
1495   java::lang::Runtime *runtime = NULL;
1496
1497   try
1498     {
1499       if (_Jv_CreateJavaVM (vm_args) < 0)
1500         {
1501           fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1502           exit (1);
1503         }
1504
1505       // Get the Runtime here.  We want to initialize it before searching
1506       // for `main'; that way it will be set up if `main' is a JNI method.
1507       runtime = java::lang::Runtime::getRuntime ();
1508
1509 #ifdef DISABLE_MAIN_ARGS
1510       arg_vec = JvConvertArgv (0, 0);
1511 #else      
1512       arg_vec = JvConvertArgv (argc - 1, argv + 1);
1513 #endif
1514
1515       using namespace gnu::java::lang;
1516       if (klass)
1517         main_thread = new MainThread (klass, arg_vec);
1518       else
1519         main_thread = new MainThread (JvNewStringLatin1 (name),
1520                                       arg_vec, is_jar);
1521     }
1522   catch (java::lang::Throwable *t)
1523     {
1524       java::lang::System::err->println (JvNewStringLatin1 
1525         ("Exception during runtime initialization"));
1526       t->printStackTrace();
1527       if (runtime)
1528         runtime->exit (1);
1529       // In case the runtime creation failed.
1530       ::exit (1);
1531     }
1532
1533   _Jv_AttachCurrentThread (main_thread);
1534   _Jv_ThreadRun (main_thread);
1535
1536   // If we got here then something went wrong, as MainThread is not
1537   // supposed to terminate.
1538   ::exit (1);
1539 }
1540
1541 void
1542 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
1543              bool is_jar)
1544 {
1545   _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1546 }
1547
1548 void
1549 JvRunMain (jclass klass, int argc, const char **argv)
1550 {
1551   _Jv_RunMain (klass, NULL, argc, argv, false);
1552 }
1553
1554 \f
1555
1556 // Parse a string and return a heap size.
1557 static size_t
1558 parse_memory_size (const char *spec)
1559 {
1560   char *end;
1561   unsigned long val = strtoul (spec, &end, 10);
1562   if (*end == 'k' || *end == 'K')
1563     val *= 1024;
1564   else if (*end == 'm' || *end == 'M')
1565     val *= 1048576;
1566   return (size_t) val;
1567 }
1568
1569 // Set the initial heap size.  This might be ignored by the GC layer.
1570 // This must be called before _Jv_RunMain.
1571 void
1572 _Jv_SetInitialHeapSize (const char *arg)
1573 {
1574   size_t size = parse_memory_size (arg);
1575   _Jv_GCSetInitialHeapSize (size);
1576 }
1577
1578 // Set the maximum heap size.  This might be ignored by the GC layer.
1579 // This must be called before _Jv_RunMain.
1580 void
1581 _Jv_SetMaximumHeapSize (const char *arg)
1582 {
1583   size_t size = parse_memory_size (arg);
1584   _Jv_GCSetMaximumHeapSize (size);
1585 }
1586
1587 void
1588 _Jv_SetStackSize (const char *arg)
1589 {
1590   size_t size = parse_memory_size (arg);
1591   gcj::stack_size = size;
1592 }
1593
1594 void *
1595 _Jv_Malloc (jsize size)
1596 {
1597   if (__builtin_expect (size == 0, false))
1598     size = 1;
1599   void *ptr = malloc ((size_t) size);
1600   if (__builtin_expect (ptr == NULL, false))
1601     throw no_memory;
1602   return ptr;
1603 }
1604
1605 void *
1606 _Jv_Realloc (void *ptr, jsize size)
1607 {
1608   if (__builtin_expect (size == 0, false))
1609     size = 1;
1610   ptr = realloc (ptr, (size_t) size);
1611   if (__builtin_expect (ptr == NULL, false))
1612     throw no_memory;
1613   return ptr;
1614 }
1615
1616 void *
1617 _Jv_MallocUnchecked (jsize size)
1618 {
1619   if (__builtin_expect (size == 0, false))
1620     size = 1;
1621   return malloc ((size_t) size);
1622 }
1623
1624 void
1625 _Jv_Free (void* ptr)
1626 {
1627   return free (ptr);
1628 }
1629
1630 \f
1631
1632 // In theory, these routines can be #ifdef'd away on machines which
1633 // support divide overflow signals.  However, we never know if some
1634 // code might have been compiled with "-fuse-divide-subroutine", so we
1635 // always include them in libgcj.
1636
1637 jint
1638 _Jv_divI (jint dividend, jint divisor)
1639 {
1640   if (__builtin_expect (divisor == 0, false))
1641     {
1642       java::lang::ArithmeticException *arithexception 
1643         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1644       throw arithexception;
1645     }
1646   
1647   if (dividend == (jint) 0x80000000L && divisor == -1)
1648     return dividend;
1649
1650   return dividend / divisor;
1651 }
1652
1653 jint
1654 _Jv_remI (jint dividend, jint divisor)
1655 {
1656   if (__builtin_expect (divisor == 0, false))
1657     {
1658       java::lang::ArithmeticException *arithexception 
1659         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1660       throw arithexception;
1661     }
1662   
1663   if (dividend == (jint) 0x80000000L && divisor == -1)
1664     return 0;
1665   
1666   return dividend % divisor;
1667 }
1668
1669 jlong
1670 _Jv_divJ (jlong dividend, jlong divisor)
1671 {
1672   if (__builtin_expect (divisor == 0, false))
1673     {
1674       java::lang::ArithmeticException *arithexception 
1675         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1676       throw arithexception;
1677     }
1678
1679   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1680     return dividend;
1681
1682   return dividend / divisor;
1683 }
1684
1685 jlong
1686 _Jv_remJ (jlong dividend, jlong divisor)
1687 {
1688   if (__builtin_expect (divisor == 0, false))
1689     {
1690       java::lang::ArithmeticException *arithexception 
1691         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1692       throw arithexception;
1693     }
1694
1695   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1696     return 0;
1697
1698   return dividend % divisor;
1699 }
1700
1701 \f
1702
1703 // Return true if SELF_KLASS can access a field or method in
1704 // OTHER_KLASS.  The field or method's access flags are specified in
1705 // FLAGS.
1706 jboolean
1707 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1708 {
1709   using namespace java::lang::reflect;
1710   return ((self_klass == other_klass)
1711           || ((flags & Modifier::PUBLIC) != 0)
1712           || (((flags & Modifier::PROTECTED) != 0)
1713               && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1714           || (((flags & Modifier::PRIVATE) == 0)
1715               && _Jv_ClassNameSamePackage (self_klass->name,
1716                                            other_klass->name)));
1717 }