OSDN Git Service

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