OSDN Git Service

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