OSDN Git Service

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