OSDN Git Service

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