OSDN Git Service

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