OSDN Git Service

* gnu/gcj/util/natDebug.cc (getField): Don't qualify name.
[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  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/InternalError.h>
53 #include <java/lang/NegativeArraySizeException.h>
54 #include <java/lang/NullPointerException.h>
55 #include <java/lang/OutOfMemoryError.h>
56 #include <java/lang/System.h>
57 #include <java/lang/VMThrowable.h>
58 #include <java/lang/reflect/Modifier.h>
59 #include <java/io/PrintStream.h>
60 #include <java/lang/UnsatisfiedLinkError.h>
61 #include <java/lang/VirtualMachineError.h>
62 #include <gnu/gcj/runtime/VMClassLoader.h>
63 #include <gnu/gcj/runtime/FinalizerThread.h>
64 #include <execution.h>
65 #include <gnu/java/lang/MainThread.h>
66
67 #ifdef USE_LTDL
68 #include <ltdl.h>
69 #endif
70
71 // Execution engine for compiled code.
72 _Jv_CompiledEngine _Jv_soleCompiledEngine;
73
74 // We allocate a single OutOfMemoryError exception which we keep
75 // around for use if we run out of memory.
76 static java::lang::OutOfMemoryError *no_memory;
77
78 // Number of bytes in largest array object we create.  This could be
79 // increased to the largest size_t value, so long as the appropriate
80 // functions are changed to take a size_t argument instead of jint.
81 #define MAX_OBJECT_SIZE ((1<<31) - 1)
82
83 static const char *no_properties[] = { NULL };
84
85 // Properties set at compile time.
86 const char **_Jv_Compiler_Properties = no_properties;
87
88 // The JAR file to add to the beginning of java.class.path.
89 const char *_Jv_Jar_Class_Path;
90
91 #ifndef DISABLE_GETENV_PROPERTIES
92 // Property key/value pairs.
93 property_pair *_Jv_Environment_Properties;
94 #endif
95
96 // Stash the argv pointer to benefit native libraries that need it.
97 const char **_Jv_argv;
98 int _Jv_argc;
99
100 // Argument support.
101 int
102 _Jv_GetNbArgs (void)
103 {
104   // _Jv_argc is 0 if not explicitly initialized.
105   return _Jv_argc;
106 }
107
108 const char *
109 _Jv_GetSafeArg (int index)
110 {
111   if (index >=0 && index < _Jv_GetNbArgs ())
112     return _Jv_argv[index];
113   else
114     return "";
115 }
116
117 void
118 _Jv_SetArgs (int argc, const char **argv)
119 {
120   _Jv_argc = argc;
121   _Jv_argv = argv;
122 }
123
124 #ifdef ENABLE_JVMPI
125 // Pointer to JVMPI notification functions.
126 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
127 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
128 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
129 #endif
130 \f
131
132 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
133 /* Unblock a signal.  Unless we do this, the signal may only be sent
134    once.  */
135 static void 
136 unblock_signal (int signum __attribute__ ((__unused__)))
137 {
138 #ifdef _POSIX_VERSION
139   sigset_t sigs;
140
141   sigemptyset (&sigs);
142   sigaddset (&sigs, signum);
143   sigprocmask (SIG_UNBLOCK, &sigs, NULL);
144 #endif
145 }
146 #endif
147
148 #ifdef HANDLE_SEGV
149 SIGNAL_HANDLER (catch_segv)
150 {
151   java::lang::NullPointerException *nullp 
152     = new java::lang::NullPointerException;
153   unblock_signal (SIGSEGV);
154   MAKE_THROW_FRAME (nullp);
155   throw nullp;
156 }
157 #endif
158
159 #ifdef HANDLE_FPE
160 SIGNAL_HANDLER (catch_fpe)
161 {
162   java::lang::ArithmeticException *arithexception 
163     = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
164   unblock_signal (SIGFPE);
165 #ifdef HANDLE_DIVIDE_OVERFLOW
166   HANDLE_DIVIDE_OVERFLOW;
167 #else
168   MAKE_THROW_FRAME (arithexception);
169 #endif
170   throw arithexception;
171 }
172 #endif
173
174 \f
175
176 jboolean
177 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
178 {
179   int len;
180   const _Jv_ushort *aptr, *bptr;
181   if (a == b)
182     return true;
183   if (a->hash != b->hash)
184     return false;
185   len = a->length;
186   if (b->length != len)
187     return false;
188   aptr = (const _Jv_ushort *)a->data;
189   bptr = (const _Jv_ushort *)b->data;
190   len = (len + 1) >> 1;
191   while (--len >= 0)
192     if (*aptr++ != *bptr++)
193       return false;
194   return true;
195 }
196
197 /* True iff A is equal to STR.
198    HASH is STR->hashCode().  
199 */
200
201 jboolean
202 _Jv_equal (Utf8Const* a, jstring str, jint hash)
203 {
204   if (a->hash != (_Jv_ushort) hash)
205     return false;
206   jint len = str->length();
207   jint i = 0;
208   jchar *sptr = _Jv_GetStringChars (str);
209   unsigned char* ptr = (unsigned char*) a->data;
210   unsigned char* limit = ptr + a->length;
211   for (;; i++, sptr++)
212     {
213       int ch = UTF8_GET (ptr, limit);
214       if (i == len)
215         return ch < 0;
216       if (ch != *sptr)
217         return false;
218     }
219   return true;
220 }
221
222 /* Like _Jv_equal, but stop after N characters.  */
223 jboolean
224 _Jv_equaln (Utf8Const *a, jstring str, jint n)
225 {
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 (; n-- > 0; 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 /* Count the number of Unicode chars encoded in a given Ut8 string. */
243 int
244 _Jv_strLengthUtf8(char* str, int len)
245 {
246   unsigned char* ptr;
247   unsigned char* limit;
248   int str_length;
249
250   ptr = (unsigned char*) str;
251   limit = ptr + len;
252   str_length = 0;
253   for (; ptr < limit; str_length++)
254     {
255       if (UTF8_GET (ptr, limit) < 0)
256         return (-1);
257     }
258   return (str_length);
259 }
260
261 /* Calculate a hash value for a string encoded in Utf8 format.
262  * This returns the same hash value as specified or java.lang.String.hashCode.
263  */
264 jint
265 _Jv_hashUtf8String (char* str, int len)
266 {
267   unsigned char* ptr = (unsigned char*) str;
268   unsigned char* limit = ptr + len;
269   jint hash = 0;
270
271   for (; ptr < limit;)
272     {
273       int ch = UTF8_GET (ptr, limit);
274       /* Updated specification from
275          http://www.javasoft.com/docs/books/jls/clarify.html. */
276       hash = (31 * hash) + ch;
277     }
278   return hash;
279 }
280
281 void
282 _Jv_Utf8Const::init(char *s, int len)
283 {
284   ::memcpy (data, s, len);
285   data[len] = 0;
286   length = len;
287   hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
288 }
289
290 _Jv_Utf8Const *
291 _Jv_makeUtf8Const (char* s, int len)
292 {
293   if (len < 0)
294     len = strlen (s);
295   Utf8Const* m
296     = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
297   m->init(s, len);
298   return m;
299 }
300
301 _Jv_Utf8Const *
302 _Jv_makeUtf8Const (jstring string)
303 {
304   jint hash = string->hashCode ();
305   jint len = _Jv_GetStringUTFLength (string);
306
307   Utf8Const* m = (Utf8Const*)
308     _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
309
310   m->hash = hash;
311   m->length = len;
312
313   _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
314   m->data[len] = 0;
315   
316   return m;
317 }
318
319 \f
320
321 #ifdef DEBUG
322 void
323 _Jv_Abort (const char *function, const char *file, int line,
324            const char *message)
325 #else
326 void
327 _Jv_Abort (const char *, const char *, int, const char *message)
328 #endif
329 {
330 #ifdef DEBUG
331   fprintf (stderr,
332            "libgcj failure: %s\n   in function %s, file %s, line %d\n",
333            message, function, file, line);
334 #else
335   fprintf (stderr, "libgcj failure: %s\n", message);
336 #endif
337   abort ();
338 }
339
340 static void
341 fail_on_finalization (jobject)
342 {
343   JvFail ("object was finalized");
344 }
345
346 void
347 _Jv_GCWatch (jobject obj)
348 {
349   _Jv_RegisterFinalizer (obj, fail_on_finalization);
350 }
351
352 void
353 _Jv_ThrowBadArrayIndex(jint bad_index)
354 {
355   throw new java::lang::ArrayIndexOutOfBoundsException
356     (java::lang::String::valueOf (bad_index));
357 }
358
359 void
360 _Jv_ThrowNullPointerException ()
361 {
362   throw new java::lang::NullPointerException;
363 }
364
365 // Explicitly throw a no memory exception.
366 // The collector calls this when it encounters an out-of-memory condition.
367 void _Jv_ThrowNoMemory()
368 {
369   throw no_memory;
370 }
371
372 #ifdef ENABLE_JVMPI
373 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
374     if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
375       jvmpi_notify_alloc(klass,size,obj);
376 static void
377 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
378 {
379   // Service JVMPI allocation request.
380   JVMPI_Event event;
381
382   event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
383   event.env_id = NULL;
384   event.u.obj_alloc.arena_id = 0;
385   event.u.obj_alloc.class_id = (jobjectID) klass;
386   event.u.obj_alloc.is_array = 0;
387   event.u.obj_alloc.size = size;
388   event.u.obj_alloc.obj_id = (jobjectID) obj;
389
390   // FIXME:  This doesn't look right for the Boehm GC.  A GC may
391   // already be in progress.  _Jv_DisableGC () doesn't wait for it.
392   // More importantly, I don't see the need for disabling GC, since we
393   // blatantly have a pointer to obj on our stack, ensuring that the
394   // object can't be collected.  Even for a nonconservative collector,
395   // it appears to me that this must be true, since we are about to
396   // return obj. Isn't this whole approach way too intrusive for
397   // a useful profiling interface?                      - HB
398   _Jv_DisableGC ();
399   (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
400   _Jv_EnableGC ();
401 }
402 #else /* !ENABLE_JVMPI */
403 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
404 #endif
405
406 // Allocate a new object of class KLASS.
407 // First a version that assumes that we have no finalizer, and that
408 // the class is already initialized.
409 // If we know that JVMPI is disabled, this can be replaced by a direct call
410 // to the allocator for the appropriate GC.
411 jobject
412 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
413 {
414   jint size = klass->size ();
415   jobject obj = (jobject) _Jv_AllocObj (size, klass);
416   JVMPI_NOTIFY_ALLOC (klass, size, obj);
417   return obj;
418 }
419
420 // And now a version that initializes if necessary.
421 jobject
422 _Jv_AllocObjectNoFinalizer (jclass klass)
423 {
424   _Jv_InitClass (klass);
425   jint size = klass->size ();
426   jobject obj = (jobject) _Jv_AllocObj (size, klass);
427   JVMPI_NOTIFY_ALLOC (klass, size, obj);
428   return obj;
429 }
430
431 // And now the general version that registers a finalizer if necessary.
432 jobject
433 _Jv_AllocObject (jclass klass)
434 {
435   jobject obj = _Jv_AllocObjectNoFinalizer (klass);
436   
437   // We assume that the compiler only generates calls to this routine
438   // if there really is an interesting finalizer.
439   // Unfortunately, we still have to the dynamic test, since there may
440   // be cni calls to this routine.
441   // Note that on IA64 get_finalizer() returns the starting address of the
442   // function, not a function pointer.  Thus this still works.
443   if (klass->vtable->get_finalizer ()
444       != java::lang::Object::class$.vtable->get_finalizer ())
445     _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
446   return obj;
447 }
448
449 // Allocate a String, including variable length storage.
450 jstring
451 _Jv_AllocString(jsize len)
452 {
453   using namespace java::lang;
454
455   jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
456
457   // We assert that for strings allocated this way, the data field
458   // will always point to the object itself.  Thus there is no reason
459   // for the garbage collector to scan any of it.
460   // Furthermore, we're about to overwrite the string data, so
461   // initialization of the object is not an issue.
462
463   // String needs no initialization, and there is no finalizer, so
464   // we can go directly to the collector's allocator interface.
465   jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
466
467   obj->data = obj;
468   obj->boffset = sizeof(java::lang::String);
469   obj->count = len;
470   obj->cachedHashCode = 0;
471
472   JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
473   
474   return obj;
475 }
476
477 // A version of the above that assumes the object contains no pointers,
478 // and requires no finalization.  This can't happen if we need pointers
479 // to locks.
480 #ifdef JV_HASH_SYNCHRONIZATION
481 jobject
482 _Jv_AllocPtrFreeObject (jclass klass)
483 {
484   _Jv_InitClass (klass);
485   jint size = klass->size ();
486
487   jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
488
489   JVMPI_NOTIFY_ALLOC (klass, size, obj);
490
491   return obj;
492 }
493 #endif /* JV_HASH_SYNCHRONIZATION */
494
495
496 // Allocate a new array of Java objects.  Each object is of type
497 // `elementClass'.  `init' is used to initialize each slot in the
498 // array.
499 jobjectArray
500 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
501 {
502   if (__builtin_expect (count < 0, false))
503     throw new java::lang::NegativeArraySizeException;
504
505   JvAssert (! elementClass->isPrimitive ());
506
507   // Ensure that elements pointer is properly aligned.
508   jobjectArray obj = NULL;
509   size_t size = (size_t) elements (obj);
510   // Check for overflow.
511   if (__builtin_expect ((size_t) count > 
512                         (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
513     throw no_memory;
514
515   size += count * sizeof (jobject);
516
517   jclass klass = _Jv_GetArrayClass (elementClass,
518                                     elementClass->getClassLoaderInternal());
519
520   obj = (jobjectArray) _Jv_AllocArray (size, klass);
521   // Cast away const.
522   jsize *lp = const_cast<jsize *> (&obj->length);
523   *lp = count;
524   // We know the allocator returns zeroed memory.  So don't bother
525   // zeroing it again.
526   if (init)
527     {
528       jobject *ptr = elements(obj);
529       while (--count >= 0)
530         *ptr++ = init;
531     }
532   return obj;
533 }
534
535 // Allocate a new array of primitives.  ELTYPE is the type of the
536 // element, COUNT is the size of the array.
537 jobject
538 _Jv_NewPrimArray (jclass eltype, jint count)
539 {
540   int elsize = eltype->size();
541   if (__builtin_expect (count < 0, false))
542     throw new java::lang::NegativeArraySizeException;
543
544   JvAssert (eltype->isPrimitive ());
545   jobject dummy = NULL;
546   size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
547
548   // Check for overflow.
549   if (__builtin_expect ((size_t) count > 
550                         (MAX_OBJECT_SIZE - size) / elsize, false))
551     throw no_memory;
552
553   jclass klass = _Jv_GetArrayClass (eltype, 0);
554
555 # ifdef JV_HASH_SYNCHRONIZATION
556   // Since the vtable is always statically allocated,
557   // these are completely pointerfree!  Make sure the GC doesn't touch them.
558   __JArray *arr =
559     (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
560   memset((char *)arr + size, 0, elsize * count);
561 # else
562   __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
563   // Note that we assume we are given zeroed memory by the allocator.
564 # endif
565   // Cast away const.
566   jsize *lp = const_cast<jsize *> (&arr->length);
567   *lp = count;
568
569   return arr;
570 }
571
572 jobject
573 _Jv_NewArray (jint type, jint size)
574 {
575   switch (type)
576     {
577       case  4:  return JvNewBooleanArray (size);
578       case  5:  return JvNewCharArray (size);
579       case  6:  return JvNewFloatArray (size);
580       case  7:  return JvNewDoubleArray (size);
581       case  8:  return JvNewByteArray (size);
582       case  9:  return JvNewShortArray (size);
583       case 10:  return JvNewIntArray (size);
584       case 11:  return JvNewLongArray (size);
585     }
586   throw new java::lang::InternalError
587     (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
588 }
589
590 // Allocate a possibly multi-dimensional array but don't check that
591 // any array length is <0.
592 static jobject
593 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
594 {
595   JvAssert (type->isArray());
596   jclass element_type = type->getComponentType();
597   jobject result;
598   if (element_type->isPrimitive())
599     result = _Jv_NewPrimArray (element_type, sizes[0]);
600   else
601     result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
602
603   if (dimensions > 1)
604     {
605       JvAssert (! element_type->isPrimitive());
606       JvAssert (element_type->isArray());
607       jobject *contents = elements ((jobjectArray) result);
608       for (int i = 0; i < sizes[0]; ++i)
609         contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
610                                                   sizes + 1);
611     }
612
613   return result;
614 }
615
616 jobject
617 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
618 {
619   for (int i = 0; i < dimensions; ++i)
620     if (sizes[i] < 0)
621       throw new java::lang::NegativeArraySizeException;
622
623   return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
624 }
625
626 jobject
627 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
628 {
629   va_list args;
630   jint sizes[dimensions];
631   va_start (args, dimensions);
632   for (int i = 0; i < dimensions; ++i)
633     {
634       jint size = va_arg (args, jint);
635       if (size < 0)
636         throw new java::lang::NegativeArraySizeException;
637       sizes[i] = size;
638     }
639   va_end (args);
640
641   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
642 }
643
644 \f
645
646 // Ensure 8-byte alignment, for hash synchronization.
647 #define DECLARE_PRIM_TYPE(NAME)                 \
648   java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
649
650 DECLARE_PRIM_TYPE(byte)
651 DECLARE_PRIM_TYPE(short)
652 DECLARE_PRIM_TYPE(int)
653 DECLARE_PRIM_TYPE(long)
654 DECLARE_PRIM_TYPE(boolean)
655 DECLARE_PRIM_TYPE(char)
656 DECLARE_PRIM_TYPE(float)
657 DECLARE_PRIM_TYPE(double)
658 DECLARE_PRIM_TYPE(void)
659
660 void
661 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len)
662 {    
663   using namespace java::lang::reflect;
664
665   // We must set the vtable for the class; the Java constructor
666   // doesn't do this.
667   (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
668
669   // Initialize the fields we care about.  We do this in the same
670   // order they are declared in Class.h.
671   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
672   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
673   cl->method_count = sig;
674   cl->size_in_bytes = len;
675   cl->vtable = JV_PRIMITIVE_VTABLE;
676   cl->state = JV_STATE_DONE;
677   cl->depth = -1;
678 }
679
680 jclass
681 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
682 {
683   switch (*sig)
684     {
685     case 'B':
686       return JvPrimClass (byte);
687     case 'S':
688       return JvPrimClass (short);
689     case 'I':
690       return JvPrimClass (int);
691     case 'J':
692       return JvPrimClass (long);
693     case 'Z':
694       return JvPrimClass (boolean);
695     case 'C':
696       return JvPrimClass (char);
697     case 'F':
698       return JvPrimClass (float);
699     case 'D':
700       return JvPrimClass (double);
701     case 'V':
702       return JvPrimClass (void);
703     case 'L':
704       {
705         int i;
706         for (i = 1; sig[i] && sig[i] != ';'; ++i)
707           ;
708         _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
709         return _Jv_FindClass (name, loader);
710       }
711     case '[':
712       {
713         jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
714         if (! klass)
715           return NULL;
716         return _Jv_GetArrayClass (klass, loader);
717       }
718     }
719
720   return NULL;                  // Placate compiler.
721 }
722
723 \f
724
725 JArray<jstring> *
726 JvConvertArgv (int argc, const char **argv)
727 {
728   if (argc < 0)
729     argc = 0;
730   jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
731   jobject *ptr = elements(ar);
732   jbyteArray bytes = NULL;
733   for (int i = 0;  i < argc;  i++)
734     {
735       const char *arg = argv[i];
736       int len = strlen (arg);
737       if (bytes == NULL || bytes->length < len)
738         bytes = JvNewByteArray (len);
739       jbyte *bytePtr = elements (bytes);
740       // We assume jbyte == char.
741       memcpy (bytePtr, arg, len);
742
743       // Now convert using the default encoding.
744       *ptr++ = new java::lang::String (bytes, 0, len);
745     }
746   return (JArray<jstring>*) ar;
747 }
748
749 // FIXME: These variables are static so that they will be
750 // automatically scanned by the Boehm collector.  This is needed
751 // because with qthreads the collector won't scan the initial stack --
752 // it will only scan the qthreads stacks.
753
754 // Command line arguments.
755 static JArray<jstring> *arg_vec;
756
757 // The primary thread.
758 static java::lang::Thread *main_thread;
759
760 #ifndef DISABLE_GETENV_PROPERTIES
761
762 static char *
763 next_property_key (char *s, size_t *length)
764 {
765   size_t l = 0;
766
767   JvAssert (s);
768
769   // Skip over whitespace
770   while (isspace (*s))
771     s++;
772
773   // If we've reached the end, return NULL.  Also return NULL if for
774   // some reason we've come across a malformed property string.
775   if (*s == 0
776       || *s == ':'
777       || *s == '=')
778     return NULL;
779
780   // Determine the length of the property key.
781   while (s[l] != 0
782          && ! isspace (s[l])
783          && s[l] != ':'
784          && s[l] != '=')
785     {
786       if (s[l] == '\\'
787           && s[l+1] != 0)
788         l++;
789       l++;
790     }
791
792   *length = l;
793
794   return s;
795 }
796
797 static char *
798 next_property_value (char *s, size_t *length)
799 {
800   size_t l = 0;
801
802   JvAssert (s);
803
804   while (isspace (*s))
805     s++;
806
807   if (*s == ':'
808       || *s == '=')
809     s++;
810
811   while (isspace (*s))
812     s++;
813
814   // If we've reached the end, return NULL.
815   if (*s == 0)
816     return NULL;
817
818   // Determine the length of the property value.
819   while (s[l] != 0
820          && ! isspace (s[l])
821          && s[l] != ':'
822          && s[l] != '=')
823     {
824       if (s[l] == '\\'
825           && s[l+1] != 0)
826         l += 2;
827       else
828         l++;
829     }
830
831   *length = l;
832
833   return s;
834 }
835
836 static void
837 process_gcj_properties ()
838 {
839   char *props = getenv("GCJ_PROPERTIES");
840   char *p = props;
841   size_t length;
842   size_t property_count = 0;
843
844   if (NULL == props)
845     return;
846
847   // Whip through props quickly in order to count the number of
848   // property values.
849   while (p && (p = next_property_key (p, &length)))
850     {
851       // Skip to the end of the key
852       p += length;
853
854       p = next_property_value (p, &length);
855       if (p)
856         p += length;
857       
858       property_count++;
859     }
860
861   // Allocate an array of property value/key pairs.
862   _Jv_Environment_Properties = 
863     (property_pair *) malloc (sizeof(property_pair) 
864                               * (property_count + 1));
865
866   // Go through the properties again, initializing _Jv_Properties
867   // along the way.
868   p = props;
869   property_count = 0;
870   while (p && (p = next_property_key (p, &length)))
871     {
872       _Jv_Environment_Properties[property_count].key = p;
873       _Jv_Environment_Properties[property_count].key_length = length;
874
875       // Skip to the end of the key
876       p += length;
877
878       p = next_property_value (p, &length);
879       
880       _Jv_Environment_Properties[property_count].value = p;
881       _Jv_Environment_Properties[property_count].value_length = length;
882
883       if (p)
884         p += length;
885
886       property_count++;
887     }
888   memset ((void *) &_Jv_Environment_Properties[property_count], 
889           0, sizeof (property_pair));
890
891   // Null terminate the strings.
892   for (property_pair *prop = &_Jv_Environment_Properties[0];
893        prop->key != NULL;
894        prop++)
895     {
896       prop->key[prop->key_length] = 0;
897       prop->value[prop->value_length] = 0;
898     }
899 }
900 #endif // DISABLE_GETENV_PROPERTIES
901
902 namespace gcj
903 {
904   _Jv_Utf8Const *void_signature;
905   _Jv_Utf8Const *clinit_name;
906   _Jv_Utf8Const *init_name;
907   _Jv_Utf8Const *finit_name;
908   
909   bool runtimeInitialized = false;
910 }
911
912 jint
913 _Jv_CreateJavaVM (void* /*vm_args*/)
914 {
915   using namespace gcj;
916   
917   if (runtimeInitialized)
918     return -1;
919
920   runtimeInitialized = true;
921
922   PROCESS_GCJ_PROPERTIES;
923
924   _Jv_InitThreads ();
925   _Jv_InitGC ();
926   _Jv_InitializeSyncMutex ();
927   
928 #ifdef INTERPRETER
929   _Jv_InitInterpreter ();
930 #endif  
931
932 #ifdef HANDLE_SEGV
933   INIT_SEGV;
934 #endif
935
936 #ifdef HANDLE_FPE
937   INIT_FPE;
938 #endif
939
940   /* Initialize Utf8 constants declared in jvm.h. */
941   void_signature = _Jv_makeUtf8Const ("()V", 3);
942   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
943   init_name = _Jv_makeUtf8Const ("<init>", 6);
944   finit_name = _Jv_makeUtf8Const ("finit$", 6);
945
946   /* Initialize built-in classes to represent primitive TYPEs. */
947   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1);
948   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2);
949   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4);
950   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8);
951   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
952   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2);
953   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4);
954   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8);
955   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0);
956
957   // Turn stack trace generation off while creating exception objects.
958   _Jv_InitClass (&java::lang::VMThrowable::class$);
959   java::lang::VMThrowable::trace_enabled = 0;
960   
961   // We have to initialize this fairly early, to avoid circular class
962   // initialization.  In particular we want to start the
963   // initialization of ClassLoader before we start the initialization
964   // of VMClassLoader.
965   _Jv_InitClass (&java::lang::ClassLoader::class$);
966
967   // Once the bootstrap loader is in place, change it into a kind of
968   // system loader, by having it read the class path.
969   gnu::gcj::runtime::VMClassLoader::initialize();
970
971   no_memory = new java::lang::OutOfMemoryError;
972
973   java::lang::VMThrowable::trace_enabled = 1;
974
975 #ifdef USE_LTDL
976   LTDL_SET_PRELOADED_SYMBOLS ();
977 #endif
978
979   _Jv_platform_initialize ();
980
981   _Jv_JNI_Init ();
982
983   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
984
985   // Start the GC finalizer thread.  A VirtualMachineError can be
986   // thrown by the runtime if, say, threads aren't available.
987   try
988     {
989       using namespace gnu::gcj::runtime;
990       FinalizerThread *ft = new FinalizerThread ();
991       ft->start ();
992     }
993   catch (java::lang::VirtualMachineError *ignore)
994     {
995     }
996
997   return 0;
998 }
999
1000 void
1001 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
1002              bool is_jar)
1003 {
1004 #ifndef DISABLE_MAIN_ARGS
1005   _Jv_SetArgs (argc, argv);
1006 #endif
1007
1008   java::lang::Runtime *runtime = NULL;
1009
1010   try
1011     {
1012       // Set this very early so that it is seen when java.lang.System
1013       // is initialized.
1014       if (is_jar)
1015         _Jv_Jar_Class_Path = strdup (name);
1016       _Jv_CreateJavaVM (NULL);
1017
1018       // Get the Runtime here.  We want to initialize it before searching
1019       // for `main'; that way it will be set up if `main' is a JNI method.
1020       runtime = java::lang::Runtime::getRuntime ();
1021
1022 #ifdef DISABLE_MAIN_ARGS
1023       arg_vec = JvConvertArgv (0, 0);
1024 #else      
1025       arg_vec = JvConvertArgv (argc - 1, argv + 1);
1026 #endif
1027
1028       using namespace gnu::java::lang;
1029       if (klass)
1030         main_thread = new MainThread (klass, arg_vec);
1031       else
1032         main_thread = new MainThread (JvNewStringLatin1 (name),
1033                                       arg_vec, is_jar);
1034     }
1035   catch (java::lang::Throwable *t)
1036     {
1037       java::lang::System::err->println (JvNewStringLatin1 
1038         ("Exception during runtime initialization"));
1039       t->printStackTrace();
1040       runtime->exit (1);
1041     }
1042
1043   _Jv_AttachCurrentThread (main_thread);
1044   _Jv_ThreadRun (main_thread);
1045   _Jv_ThreadWait ();
1046
1047   int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1048   runtime->exit (status);
1049 }
1050
1051 void
1052 JvRunMain (jclass klass, int argc, const char **argv)
1053 {
1054   _Jv_RunMain (klass, NULL, argc, argv, false);
1055 }
1056
1057 \f
1058
1059 // Parse a string and return a heap size.
1060 static size_t
1061 parse_heap_size (const char *spec)
1062 {
1063   char *end;
1064   unsigned long val = strtoul (spec, &end, 10);
1065   if (*end == 'k' || *end == 'K')
1066     val *= 1024;
1067   else if (*end == 'm' || *end == 'M')
1068     val *= 1048576;
1069   return (size_t) val;
1070 }
1071
1072 // Set the initial heap size.  This might be ignored by the GC layer.
1073 // This must be called before _Jv_RunMain.
1074 void
1075 _Jv_SetInitialHeapSize (const char *arg)
1076 {
1077   size_t size = parse_heap_size (arg);
1078   _Jv_GCSetInitialHeapSize (size);
1079 }
1080
1081 // Set the maximum heap size.  This might be ignored by the GC layer.
1082 // This must be called before _Jv_RunMain.
1083 void
1084 _Jv_SetMaximumHeapSize (const char *arg)
1085 {
1086   size_t size = parse_heap_size (arg);
1087   _Jv_GCSetMaximumHeapSize (size);
1088 }
1089
1090 \f
1091
1092 void *
1093 _Jv_Malloc (jsize size)
1094 {
1095   if (__builtin_expect (size == 0, false))
1096     size = 1;
1097   void *ptr = malloc ((size_t) size);
1098   if (__builtin_expect (ptr == NULL, false))
1099     throw no_memory;
1100   return ptr;
1101 }
1102
1103 void *
1104 _Jv_Realloc (void *ptr, jsize size)
1105 {
1106   if (__builtin_expect (size == 0, false))
1107     size = 1;
1108   ptr = realloc (ptr, (size_t) size);
1109   if (__builtin_expect (ptr == NULL, false))
1110     throw no_memory;
1111   return ptr;
1112 }
1113
1114 void *
1115 _Jv_MallocUnchecked (jsize size)
1116 {
1117   if (__builtin_expect (size == 0, false))
1118     size = 1;
1119   return malloc ((size_t) size);
1120 }
1121
1122 void
1123 _Jv_Free (void* ptr)
1124 {
1125   return free (ptr);
1126 }
1127
1128 \f
1129
1130 // In theory, these routines can be #ifdef'd away on machines which
1131 // support divide overflow signals.  However, we never know if some
1132 // code might have been compiled with "-fuse-divide-subroutine", so we
1133 // always include them in libgcj.
1134
1135 jint
1136 _Jv_divI (jint dividend, jint divisor)
1137 {
1138   if (__builtin_expect (divisor == 0, false))
1139     {
1140       java::lang::ArithmeticException *arithexception 
1141         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1142       throw arithexception;
1143     }
1144   
1145   if (dividend == (jint) 0x80000000L && divisor == -1)
1146     return dividend;
1147
1148   return dividend / divisor;
1149 }
1150
1151 jint
1152 _Jv_remI (jint dividend, jint divisor)
1153 {
1154   if (__builtin_expect (divisor == 0, false))
1155     {
1156       java::lang::ArithmeticException *arithexception 
1157         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1158       throw arithexception;
1159     }
1160   
1161   if (dividend == (jint) 0x80000000L && divisor == -1)
1162     return 0;
1163   
1164   return dividend % divisor;
1165 }
1166
1167 jlong
1168 _Jv_divJ (jlong dividend, jlong divisor)
1169 {
1170   if (__builtin_expect (divisor == 0, false))
1171     {
1172       java::lang::ArithmeticException *arithexception 
1173         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1174       throw arithexception;
1175     }
1176
1177   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1178     return dividend;
1179
1180   return dividend / divisor;
1181 }
1182
1183 jlong
1184 _Jv_remJ (jlong dividend, jlong divisor)
1185 {
1186   if (__builtin_expect (divisor == 0, false))
1187     {
1188       java::lang::ArithmeticException *arithexception 
1189         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1190       throw arithexception;
1191     }
1192
1193   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1194     return 0;
1195
1196   return dividend % divisor;
1197 }
1198
1199 \f
1200
1201 // Return true if SELF_KLASS can access a field or method in
1202 // OTHER_KLASS.  The field or method's access flags are specified in
1203 // FLAGS.
1204 jboolean
1205 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1206 {
1207   using namespace java::lang::reflect;
1208   return ((self_klass == other_klass)
1209           || ((flags & Modifier::PUBLIC) != 0)
1210           || (((flags & Modifier::PROTECTED) != 0)
1211               && _Jv_IsAssignableFromSlow (other_klass, self_klass))
1212           || (((flags & Modifier::PRIVATE) == 0)
1213               && _Jv_ClassNameSamePackage (self_klass->name,
1214                                            other_klass->name)));
1215 }