prims.cc: Some old cleanups.
[platform/upstream/gcc.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   memcpy (m->data, s, len);
260   m->data[len] = 0;
261   m->length = len;
262   m->hash = hashUtf8String (s, len) & 0xFFFF;
263   return (m);
264 }
265
266 _Jv_Utf8Const *
267 _Jv_makeUtf8Const (jstring string)
268 {
269   jint hash = string->hashCode ();
270   jint len = _Jv_GetStringUTFLength (string);
271
272   Utf8Const* m = (Utf8Const*)
273     _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
274
275   m->hash = hash;
276   m->length = len;
277
278   _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
279   m->data[len] = 0;
280   
281   return m;
282 }
283
284 \f
285
286 #ifdef DEBUG
287 void
288 _Jv_Abort (const char *function, const char *file, int line,
289            const char *message)
290 #else
291 void
292 _Jv_Abort (const char *, const char *, int, const char *message)
293 #endif
294 {
295 #ifdef DEBUG
296   fprintf (stderr,
297            "libgcj failure: %s\n   in function %s, file %s, line %d\n",
298            message, function, file, line);
299 #else
300   fprintf (stderr, "libgcj failure: %s\n", message);
301 #endif
302   abort ();
303 }
304
305 static void
306 fail_on_finalization (jobject)
307 {
308   JvFail ("object was finalized");
309 }
310
311 void
312 _Jv_GCWatch (jobject obj)
313 {
314   _Jv_RegisterFinalizer (obj, fail_on_finalization);
315 }
316
317 void
318 _Jv_ThrowBadArrayIndex(jint bad_index)
319 {
320   throw new java::lang::ArrayIndexOutOfBoundsException
321     (java::lang::String::valueOf (bad_index));
322 }
323
324 void
325 _Jv_ThrowNullPointerException ()
326 {
327   throw new java::lang::NullPointerException;
328 }
329
330 // Explicitly throw a no memory exception.
331 // The collector calls this when it encounters an out-of-memory condition.
332 void _Jv_ThrowNoMemory()
333 {
334   throw no_memory;
335 }
336
337 #ifdef ENABLE_JVMPI
338 static void
339 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
340 {
341   // Service JVMPI allocation request.
342   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
343     {
344       JVMPI_Event event;
345
346       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
347       event.env_id = NULL;
348       event.u.obj_alloc.arena_id = 0;
349       event.u.obj_alloc.class_id = (jobjectID) klass;
350       event.u.obj_alloc.is_array = 0;
351       event.u.obj_alloc.size = size;
352       event.u.obj_alloc.obj_id = (jobjectID) obj;
353
354       // FIXME:  This doesn't look right for the Boehm GC.  A GC may
355       // already be in progress.  _Jv_DisableGC () doesn't wait for it.
356       // More importantly, I don't see the need for disabling GC, since we
357       // blatantly have a pointer to obj on our stack, ensuring that the
358       // object can't be collected.  Even for a nonconservative collector,
359       // it appears to me that this must be true, since we are about to
360       // return obj. Isn't this whole approach way too intrusive for
361       // a useful profiling interface?                  - HB
362       _Jv_DisableGC ();
363       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
364       _Jv_EnableGC ();
365     }
366 }
367 #else /* !ENABLE_JVMPI */
368 # define jvmpi_notify_alloc(klass,size,obj) /* do nothing */
369 #endif
370
371 // Allocate a new object of class KLASS.  SIZE is the size of the object
372 // to allocate.  You might think this is redundant, but it isn't; some
373 // classes, such as String, aren't of fixed size.
374 // First a version that assumes that we have no finalizer, and that
375 // the class is already initialized.
376 // If we know that JVMPI is disabled, this can be replaced by a direct call
377 // to the allocator for the appropriate GC.
378 jobject
379 _Jv_AllocObjectNoInitNoFinalizer (jclass klass, jint size)
380 {
381   jobject obj = (jobject) _Jv_AllocObj (size, klass);
382   jvmpi_notify_alloc (klass, size, obj);
383   return obj;
384 }
385
386 // And now a version that initializes if necessary.
387 jobject
388 _Jv_AllocObjectNoFinalizer (jclass klass, jint size)
389 {
390   _Jv_InitClass (klass);
391   jobject obj = (jobject) _Jv_AllocObj (size, klass);
392   jvmpi_notify_alloc (klass, size, obj);
393   return obj;
394 }
395
396 // And now the general version that registers a finalizer if necessary.
397 jobject
398 _Jv_AllocObject (jclass klass, jint size)
399 {
400   jobject obj = _Jv_AllocObjectNoFinalizer (klass, size);
401
402   // We assume that the compiler only generates calls to this routine
403   // if there really is an interesting finalizer.
404   // Unfortunately, we still have to the dynamic test, since there may
405   // be cni calls to this routine.
406   // Nore that on IA64 get_finalizer() returns the starting address of the
407   // function, not a function pointer.  Thus this still works.
408   if (klass->vtable->get_finalizer ()
409       != java::lang::Object::class$.vtable->get_finalizer ())
410     _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
411   return obj;
412 }
413
414 // A version of the above that assumes the object contains no pointers,
415 // and requires no finalization.  This can't happen if we need pointers
416 // to locks.
417 #ifdef JV_HASH_SYNCHRONIZATION
418 jobject
419 _Jv_AllocPtrFreeObject (jclass klass, jint size)
420 {
421   _Jv_InitClass (klass);
422
423   jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
424
425 #ifdef ENABLE_JVMPI
426   // Service JVMPI request.
427
428   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
429     {
430       JVMPI_Event event;
431
432       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
433       event.env_id = NULL;
434       event.u.obj_alloc.arena_id = 0;
435       event.u.obj_alloc.class_id = (jobjectID) klass;
436       event.u.obj_alloc.is_array = 0;
437       event.u.obj_alloc.size = size;
438       event.u.obj_alloc.obj_id = (jobjectID) obj;
439
440       _Jv_DisableGC ();
441       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
442       _Jv_EnableGC ();
443     }
444 #endif
445
446   return obj;
447 }
448 #endif /* JV_HASH_SYNCHRONIZATION */
449
450
451 // Allocate a new array of Java objects.  Each object is of type
452 // `elementClass'.  `init' is used to initialize each slot in the
453 // array.
454 jobjectArray
455 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
456 {
457   if (__builtin_expect (count < 0, false))
458     throw new java::lang::NegativeArraySizeException;
459
460   JvAssert (! elementClass->isPrimitive ());
461
462   // Ensure that elements pointer is properly aligned.
463   jobjectArray obj = NULL;
464   size_t size = (size_t) elements (obj);
465   size += count * sizeof (jobject);
466
467   // FIXME: second argument should be "current loader"
468   jclass klass = _Jv_GetArrayClass (elementClass, 0);
469
470   obj = (jobjectArray) _Jv_AllocArray (size, klass);
471   // Cast away const.
472   jsize *lp = const_cast<jsize *> (&obj->length);
473   *lp = count;
474   // We know the allocator returns zeroed memory.  So don't bother
475   // zeroing it again.
476   if (init)
477     {
478       jobject *ptr = elements(obj);
479       while (--count >= 0)
480         *ptr++ = init;
481     }
482   return obj;
483 }
484
485 // Allocate a new array of primitives.  ELTYPE is the type of the
486 // element, COUNT is the size of the array.
487 jobject
488 _Jv_NewPrimArray (jclass eltype, jint count)
489 {
490   int elsize = eltype->size();
491   if (__builtin_expect (count < 0, false))
492     throw new java::lang::NegativeArraySizeException;
493
494   JvAssert (eltype->isPrimitive ());
495   jobject dummy = NULL;
496   size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
497
498   // Check for overflow.
499   if (__builtin_expect ((size_t) count > 
500                         (SIZE_T_MAX - size) / elsize, false))
501     throw no_memory;
502
503   jclass klass = _Jv_GetArrayClass (eltype, 0);
504
505 # ifdef JV_HASH_SYNCHRONIZATION
506   // Since the vtable is always statically allocated,
507   // these are completely pointerfree!  Make sure the GC doesn't touch them.
508   __JArray *arr =
509     (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
510   memset((char *)arr + size, 0, elsize * count);
511 # else
512   __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
513   // Note that we assume we are given zeroed memory by the allocator.
514 # endif
515   // Cast away const.
516   jsize *lp = const_cast<jsize *> (&arr->length);
517   *lp = count;
518
519   return arr;
520 }
521
522 jobject
523 _Jv_NewArray (jint type, jint size)
524 {
525   switch (type)
526     {
527       case  4:  return JvNewBooleanArray (size);
528       case  5:  return JvNewCharArray (size);
529       case  6:  return JvNewFloatArray (size);
530       case  7:  return JvNewDoubleArray (size);
531       case  8:  return JvNewByteArray (size);
532       case  9:  return JvNewShortArray (size);
533       case 10:  return JvNewIntArray (size);
534       case 11:  return JvNewLongArray (size);
535     }
536   JvFail ("newarray - bad type code");
537   return NULL;                  // Placate compiler.
538 }
539
540 // Allocate a possibly multi-dimensional array but don't check that
541 // any array length is <0.
542 static jobject
543 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
544 {
545   JvAssert (type->isArray());
546   jclass element_type = type->getComponentType();
547   jobject result;
548   if (element_type->isPrimitive())
549     result = _Jv_NewPrimArray (element_type, sizes[0]);
550   else
551     result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
552
553   if (dimensions > 1)
554     {
555       JvAssert (! element_type->isPrimitive());
556       JvAssert (element_type->isArray());
557       jobject *contents = elements ((jobjectArray) result);
558       for (int i = 0; i < sizes[0]; ++i)
559         contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
560                                                   sizes + 1);
561     }
562
563   return result;
564 }
565
566 jobject
567 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
568 {
569   for (int i = 0; i < dimensions; ++i)
570     if (sizes[i] < 0)
571       throw new java::lang::NegativeArraySizeException;
572
573   return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
574 }
575
576 jobject
577 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
578 {
579   va_list args;
580   jint sizes[dimensions];
581   va_start (args, dimensions);
582   for (int i = 0; i < dimensions; ++i)
583     {
584       jint size = va_arg (args, jint);
585       if (size < 0)
586         throw new java::lang::NegativeArraySizeException;
587       sizes[i] = size;
588     }
589   va_end (args);
590
591   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
592 }
593
594 \f
595
596 #define DECLARE_PRIM_TYPE(NAME)                 \
597   _Jv_ArrayVTable _Jv_##NAME##VTable;           \
598   java::lang::Class _Jv_##NAME##Class;
599
600 DECLARE_PRIM_TYPE(byte);
601 DECLARE_PRIM_TYPE(short);
602 DECLARE_PRIM_TYPE(int);
603 DECLARE_PRIM_TYPE(long);
604 DECLARE_PRIM_TYPE(boolean);
605 DECLARE_PRIM_TYPE(char);
606 DECLARE_PRIM_TYPE(float);
607 DECLARE_PRIM_TYPE(double);
608 DECLARE_PRIM_TYPE(void);
609
610 void
611 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len, 
612                    _Jv_ArrayVTable *array_vtable)
613 {    
614   using namespace java::lang::reflect;
615
616   // We must initialize every field of the class.  We do this in the
617   // same order they are declared in Class.h, except for fields that
618   // are initialized to NULL.
619   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
620   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
621   cl->method_count = sig;
622   cl->size_in_bytes = len;
623   cl->vtable = JV_PRIMITIVE_VTABLE;
624   cl->state = JV_STATE_DONE;
625   cl->depth = -1;
626   if (sig != 'V')
627     _Jv_NewArrayClass (cl, NULL, (_Jv_VTable *) array_vtable);
628 }
629
630 jclass
631 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
632 {
633   switch (*sig)
634     {
635     case 'B':
636       return JvPrimClass (byte);
637     case 'S':
638       return JvPrimClass (short);
639     case 'I':
640       return JvPrimClass (int);
641     case 'J':
642       return JvPrimClass (long);
643     case 'Z':
644       return JvPrimClass (boolean);
645     case 'C':
646       return JvPrimClass (char);
647     case 'F':
648       return JvPrimClass (float);
649     case 'D':
650       return JvPrimClass (double);
651     case 'V':
652       return JvPrimClass (void);
653     case 'L':
654       {
655         int i;
656         for (i = 1; sig[i] && sig[i] != ';'; ++i)
657           ;
658         _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
659         return _Jv_FindClass (name, loader);
660
661       }
662     case '[':
663       {
664         jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
665         if (! klass)
666           return NULL;
667         return _Jv_GetArrayClass (klass, loader);
668       }
669     }
670
671   return NULL;                  // Placate compiler.
672 }
673
674 \f
675
676 JArray<jstring> *
677 JvConvertArgv (int argc, const char **argv)
678 {
679   if (argc < 0)
680     argc = 0;
681   jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
682   jobject *ptr = elements(ar);
683   jbyteArray bytes = NULL;
684   for (int i = 0;  i < argc;  i++)
685     {
686       const char *arg = argv[i];
687       int len = strlen (arg);
688       if (bytes == NULL || bytes->length < len)
689         bytes = JvNewByteArray (len);
690       jbyte *bytePtr = elements (bytes);
691       // We assume jbyte == char.
692       memcpy (bytePtr, arg, len);
693
694       // Now convert using the default encoding.
695       *ptr++ = new java::lang::String (bytes, 0, len);
696     }
697   return (JArray<jstring>*) ar;
698 }
699
700 // FIXME: These variables are static so that they will be
701 // automatically scanned by the Boehm collector.  This is needed
702 // because with qthreads the collector won't scan the initial stack --
703 // it will only scan the qthreads stacks.
704
705 // Command line arguments.
706 static JArray<jstring> *arg_vec;
707
708 // The primary thread.
709 static java::lang::Thread *main_thread;
710
711 char *
712 _Jv_ThisExecutable (void)
713 {
714   return _Jv_execName;
715 }
716
717 void
718 _Jv_ThisExecutable (const char *name)
719 {
720   if (name)
721     {
722       _Jv_execName = (char *) _Jv_Malloc (strlen (name) + 1);
723       strcpy (_Jv_execName, name);
724     }
725 }
726
727 #ifdef USE_WIN32_SIGNALLING
728
729 extern "C" int* win32_get_restart_frame (void *);
730
731 LONG CALLBACK
732 win32_exception_handler (LPEXCEPTION_POINTERS e)
733 {
734   int* setjmp_buf;
735   if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)   
736     setjmp_buf = win32_get_restart_frame (nullp);
737   else if (e->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO)
738     setjmp_buf = win32_get_restart_frame (arithexception);
739   else
740     return EXCEPTION_CONTINUE_SEARCH;
741
742   e->ContextRecord->Ebp = setjmp_buf[0];
743   // FIXME: Why does i386-signal.h increment the PC here, do we need to do it?
744   e->ContextRecord->Eip = setjmp_buf[1];
745   // FIXME: Is this the stack pointer? Do we need it?
746   e->ContextRecord->Esp = setjmp_buf[2];
747
748   return EXCEPTION_CONTINUE_EXECUTION;
749 }
750
751 #endif
752
753 #ifndef DISABLE_GETENV_PROPERTIES
754
755 static char *
756 next_property_key (char *s, size_t *length)
757 {
758   size_t l = 0;
759
760   JvAssert (s);
761
762   // Skip over whitespace
763   while (isspace (*s))
764     s++;
765
766   // If we've reached the end, return NULL.  Also return NULL if for
767   // some reason we've come across a malformed property string.
768   if (*s == 0
769       || *s == ':'
770       || *s == '=')
771     return NULL;
772
773   // Determine the length of the property key.
774   while (s[l] != 0
775          && ! isspace (s[l])
776          && s[l] != ':'
777          && s[l] != '=')
778     {
779       if (s[l] == '\\'
780           && s[l+1] != 0)
781         l++;
782       l++;
783     }
784
785   *length = l;
786
787   return s;
788 }
789
790 static char *
791 next_property_value (char *s, size_t *length)
792 {
793   size_t l = 0;
794
795   JvAssert (s);
796
797   while (isspace (*s))
798     s++;
799
800   if (*s == ':'
801       || *s == '=')
802     s++;
803
804   while (isspace (*s))
805     s++;
806
807   // If we've reached the end, return NULL.
808   if (*s == 0)
809     return NULL;
810
811   // Determine the length of the property value.
812   while (s[l] != 0
813          && ! isspace (s[l])
814          && s[l] != ':'
815          && s[l] != '=')
816     {
817       if (s[l] == '\\'
818           && s[l+1] != 0)
819         l += 2;
820       else
821         l++;
822     }
823
824   *length = l;
825
826   return s;
827 }
828
829 static void
830 process_gcj_properties ()
831 {
832   char *props = getenv("GCJ_PROPERTIES");
833   char *p = props;
834   size_t length;
835   size_t property_count = 0;
836
837   if (NULL == props)
838     return;
839
840   // Whip through props quickly in order to count the number of
841   // property values.
842   while (p && (p = next_property_key (p, &length)))
843     {
844       // Skip to the end of the key
845       p += length;
846
847       p = next_property_value (p, &length);
848       if (p)
849         p += length;
850       
851       property_count++;
852     }
853
854   // Allocate an array of property value/key pairs.
855   _Jv_Environment_Properties = 
856     (property_pair *) malloc (sizeof(property_pair) 
857                               * (property_count + 1));
858
859   // Go through the properties again, initializing _Jv_Properties
860   // along the way.
861   p = props;
862   property_count = 0;
863   while (p && (p = next_property_key (p, &length)))
864     {
865       _Jv_Environment_Properties[property_count].key = p;
866       _Jv_Environment_Properties[property_count].key_length = length;
867
868       // Skip to the end of the key
869       p += length;
870
871       p = next_property_value (p, &length);
872       
873       _Jv_Environment_Properties[property_count].value = p;
874       _Jv_Environment_Properties[property_count].value_length = length;
875
876       if (p)
877         p += length;
878
879       property_count++;
880     }
881   memset ((void *) &_Jv_Environment_Properties[property_count], 
882           0, sizeof (property_pair));
883   {
884     size_t i = 0;
885
886     // Null terminate the strings.
887     while (_Jv_Environment_Properties[i].key)
888       {
889         _Jv_Environment_Properties[i].key[_Jv_Environment_Properties[i].key_length] = 0;
890         _Jv_Environment_Properties[i++].value[_Jv_Environment_Properties[i].value_length] = 0;
891       }
892   }
893 }
894 #endif // DISABLE_GETENV_PROPERTIES
895
896 namespace gcj
897 {
898   _Jv_Utf8Const *void_signature;
899   _Jv_Utf8Const *clinit_name;
900   _Jv_Utf8Const *init_name;
901   _Jv_Utf8Const *finit_name;
902   
903   bool runtimeInitialized = false;
904 }
905
906 jint
907 _Jv_CreateJavaVM (void* /*vm_args*/)
908 {
909   using namespace gcj;
910   
911   if (runtimeInitialized)
912     return -1;
913
914   runtimeInitialized = true;
915
916   PROCESS_GCJ_PROPERTIES;
917
918   _Jv_InitThreads ();
919   _Jv_InitGC ();
920   _Jv_InitializeSyncMutex ();
921
922   /* Initialize Utf8 constants declared in jvm.h. */
923   void_signature = _Jv_makeUtf8Const ("()V", 3);
924   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
925   init_name = _Jv_makeUtf8Const ("<init>", 6);
926   finit_name = _Jv_makeUtf8Const ("finit$", 6);
927
928   /* Initialize built-in classes to represent primitive TYPEs. */
929   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1, &_Jv_byteVTable);
930   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2, &_Jv_shortVTable);
931   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4, &_Jv_intVTable);
932   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8, &_Jv_longVTable);
933   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1, &_Jv_booleanVTable);
934   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2, &_Jv_charVTable);
935   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4, &_Jv_floatVTable);
936   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8, &_Jv_doubleVTable);
937   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0, &_Jv_voidVTable);
938
939   // Turn stack trace generation off while creating exception objects.
940   _Jv_InitClass (&java::lang::Throwable::class$);
941   java::lang::Throwable::trace_enabled = 0;
942   
943   INIT_SEGV;
944 #ifdef HANDLE_FPE
945   INIT_FPE;
946 #else
947   arithexception = new java::lang::ArithmeticException
948     (JvNewStringLatin1 ("/ by zero"));
949 #endif
950
951   no_memory = new java::lang::OutOfMemoryError;
952
953   java::lang::Throwable::trace_enabled = 1;
954
955 #ifdef USE_LTDL
956   LTDL_SET_PRELOADED_SYMBOLS ();
957 #endif
958
959 #ifdef USE_WINSOCK
960   // Initialise winsock for networking
961   WSADATA data;
962   if (WSAStartup (MAKEWORD (1, 1), &data))
963       MessageBox (NULL, "Error initialising winsock library.", "Error", MB_OK | MB_ICONEXCLAMATION);
964 #endif /* USE_WINSOCK */
965
966 #ifdef USE_WIN32_SIGNALLING
967   // Install exception handler
968   SetUnhandledExceptionFilter (win32_exception_handler);
969 #elif defined(HAVE_SIGACTION)
970   // We only want this on POSIX systems.
971   struct sigaction act;
972   act.sa_handler = SIG_IGN;
973   sigemptyset (&act.sa_mask);
974   act.sa_flags = 0;
975   sigaction (SIGPIPE, &act, NULL);
976 #else
977   signal (SIGPIPE, SIG_IGN);
978 #endif
979
980   _Jv_JNI_Init ();
981
982   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
983
984   // Start the GC finalizer thread.  A VirtualMachineError can be
985   // thrown by the runtime if, say, threads aren't available.  In this
986   // case finalizers simply won't run.
987   try
988     {
989       using namespace gnu::gcj::runtime;
990       FinalizerThread *ft = new FinalizerThread ();
991       ft->start ();
992     }
993   catch (java::lang::VirtualMachineError *ignore)
994     {
995     }
996
997   return 0;
998 }
999
1000 void
1001 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
1002              bool is_jar)
1003 {
1004   _Jv_argv = argv;
1005   _Jv_argc = argc;
1006
1007   java::lang::Runtime *runtime = NULL;
1008
1009 #ifdef HAVE_PROC_SELF_EXE
1010   char exec_name[20];
1011   sprintf (exec_name, "/proc/%d/exe", getpid ());
1012   _Jv_ThisExecutable (exec_name);
1013 #else
1014   _Jv_ThisExecutable (argv[0]);
1015 #endif
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       arg_vec = JvConvertArgv (argc - 1, argv + 1);
1030
1031       using namespace gnu::gcj::runtime;
1032       if (klass)
1033         main_thread = new FirstThread (klass, arg_vec);
1034       else
1035         main_thread = new FirstThread (JvNewStringLatin1 (name),
1036                                        arg_vec, is_jar);
1037     }
1038   catch (java::lang::Throwable *t)
1039     {
1040       java::lang::System::err->println (JvNewStringLatin1 
1041         ("Exception during runtime initialization"));
1042       t->printStackTrace();
1043       runtime->exit (1);
1044     }
1045
1046   _Jv_AttachCurrentThread (main_thread);
1047   _Jv_ThreadRun (main_thread);
1048   _Jv_ThreadWait ();
1049
1050   int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1051   runtime->exit (status);
1052 }
1053
1054 void
1055 JvRunMain (jclass klass, int argc, const char **argv)
1056 {
1057   _Jv_RunMain (klass, NULL, argc, argv, false);
1058 }
1059
1060 \f
1061
1062 // Parse a string and return a heap size.
1063 static size_t
1064 parse_heap_size (const char *spec)
1065 {
1066   char *end;
1067   unsigned long val = strtoul (spec, &end, 10);
1068   if (*end == 'k' || *end == 'K')
1069     val *= 1024;
1070   else if (*end == 'm' || *end == 'M')
1071     val *= 1048576;
1072   return (size_t) val;
1073 }
1074
1075 // Set the initial heap size.  This might be ignored by the GC layer.
1076 // This must be called before _Jv_RunMain.
1077 void
1078 _Jv_SetInitialHeapSize (const char *arg)
1079 {
1080   size_t size = parse_heap_size (arg);
1081   _Jv_GCSetInitialHeapSize (size);
1082 }
1083
1084 // Set the maximum heap size.  This might be ignored by the GC layer.
1085 // This must be called before _Jv_RunMain.
1086 void
1087 _Jv_SetMaximumHeapSize (const char *arg)
1088 {
1089   size_t size = parse_heap_size (arg);
1090   _Jv_GCSetMaximumHeapSize (size);
1091 }
1092
1093 \f
1094
1095 void *
1096 _Jv_Malloc (jsize size)
1097 {
1098   if (__builtin_expect (size == 0, false))
1099     size = 1;
1100   void *ptr = malloc ((size_t) size);
1101   if (__builtin_expect (ptr == NULL, false))
1102     throw no_memory;
1103   return ptr;
1104 }
1105
1106 void *
1107 _Jv_Realloc (void *ptr, jsize size)
1108 {
1109   if (__builtin_expect (size == 0, false))
1110     size = 1;
1111   ptr = realloc (ptr, (size_t) size);
1112   if (__builtin_expect (ptr == NULL, false))
1113     throw no_memory;
1114   return ptr;
1115 }
1116
1117 void *
1118 _Jv_MallocUnchecked (jsize size)
1119 {
1120   if (__builtin_expect (size == 0, false))
1121     size = 1;
1122   return malloc ((size_t) size);
1123 }
1124
1125 void
1126 _Jv_Free (void* ptr)
1127 {
1128   return free (ptr);
1129 }
1130
1131 \f
1132
1133 // In theory, these routines can be #ifdef'd away on machines which
1134 // support divide overflow signals.  However, we never know if some
1135 // code might have been compiled with "-fuse-divide-subroutine", so we
1136 // always include them in libgcj.
1137
1138 jint
1139 _Jv_divI (jint dividend, jint divisor)
1140 {
1141   if (__builtin_expect (divisor == 0, false))
1142     _Jv_ThrowSignal (arithexception);
1143   
1144   if (dividend == (jint) 0x80000000L && divisor == -1)
1145     return dividend;
1146
1147   return dividend / divisor;
1148 }
1149
1150 jint
1151 _Jv_remI (jint dividend, jint divisor)
1152 {
1153   if (__builtin_expect (divisor == 0, false))
1154     _Jv_ThrowSignal (arithexception);
1155   
1156   if (dividend == (jint) 0x80000000L && divisor == -1)
1157     return 0;
1158
1159   return dividend % divisor;
1160 }
1161
1162 jlong
1163 _Jv_divJ (jlong dividend, jlong divisor)
1164 {
1165   if (__builtin_expect (divisor == 0, false))
1166     _Jv_ThrowSignal (arithexception);
1167   
1168   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1169     return dividend;
1170
1171   return dividend / divisor;
1172 }
1173
1174 jlong
1175 _Jv_remJ (jlong dividend, jlong divisor)
1176 {
1177   if (__builtin_expect (divisor == 0, false))
1178     _Jv_ThrowSignal (arithexception);
1179   
1180   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1181     return 0;
1182
1183   return dividend % divisor;
1184 }