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