OSDN Git Service

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