OSDN Git Service

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