OSDN Git Service

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