OSDN Git Service

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