OSDN Git Service

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