OSDN Git Service

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