OSDN Git Service

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