OSDN Git Service

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