* snapshot-README: Mention how the snapshot was generated.
[official-gcc.git] / libjava / prims.cc
blob06791d388f393e00eebe07b005ecc4aa61ddc58e
1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 #include <config.h>
12 #include <platform.h>
14 #include <stdlib.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <signal.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
24 #include <gcj/cni.h>
25 #include <jvm.h>
26 #include <java-signal.h>
27 #include <java-threads.h>
29 #ifdef ENABLE_JVMPI
30 #include <jvmpi.h>
31 #include <java/lang/ThreadGroup.h>
32 #endif
34 #ifndef DISABLE_GETENV_PROPERTIES
35 #include <ctype.h>
36 #include <java-props.h>
37 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
38 #else
39 #define PROCESS_GCJ_PROPERTIES
40 #endif // DISABLE_GETENV_PROPERTIES
42 #include <java/lang/Class.h>
43 #include <java/lang/ClassLoader.h>
44 #include <java/lang/Runtime.h>
45 #include <java/lang/String.h>
46 #include <java/lang/Thread.h>
47 #include <java/lang/ThreadGroup.h>
48 #include <java/lang/ArrayIndexOutOfBoundsException.h>
49 #include <java/lang/ArithmeticException.h>
50 #include <java/lang/ClassFormatError.h>
51 #include <java/lang/InternalError.h>
52 #include <java/lang/NegativeArraySizeException.h>
53 #include <java/lang/NullPointerException.h>
54 #include <java/lang/OutOfMemoryError.h>
55 #include <java/lang/System.h>
56 #include <java/lang/VMThrowable.h>
57 #include <java/lang/reflect/Modifier.h>
58 #include <java/io/PrintStream.h>
59 #include <java/lang/UnsatisfiedLinkError.h>
60 #include <java/lang/VirtualMachineError.h>
61 #include <gnu/gcj/runtime/VMClassLoader.h>
62 #include <gnu/gcj/runtime/FinalizerThread.h>
63 #include <gnu/gcj/runtime/FirstThread.h>
65 #ifdef USE_LTDL
66 #include <ltdl.h>
67 #endif
69 // We allocate a single OutOfMemoryError exception which we keep
70 // around for use if we run out of memory.
71 static java::lang::OutOfMemoryError *no_memory;
73 // Number of bytes in largest array object we create. This could be
74 // increased to the largest size_t value, so long as the appropriate
75 // functions are changed to take a size_t argument instead of jint.
76 #define MAX_OBJECT_SIZE ((1<<31) - 1)
78 static const char *no_properties[] = { NULL };
80 // Properties set at compile time.
81 const char **_Jv_Compiler_Properties = no_properties;
83 // The JAR file to add to the beginning of java.class.path.
84 const char *_Jv_Jar_Class_Path;
86 #ifndef DISABLE_GETENV_PROPERTIES
87 // Property key/value pairs.
88 property_pair *_Jv_Environment_Properties;
89 #endif
91 // Stash the argv pointer to benefit native libraries that need it.
92 const char **_Jv_argv;
93 int _Jv_argc;
95 // Argument support.
96 int
97 _Jv_GetNbArgs (void)
99 // _Jv_argc is 0 if not explicitly initialized.
100 return _Jv_argc;
103 const char *
104 _Jv_GetSafeArg (int index)
106 if (index >=0 && index < _Jv_GetNbArgs ())
107 return _Jv_argv[index];
108 else
109 return "";
112 void
113 _Jv_SetArgs (int argc, const char **argv)
115 _Jv_argc = argc;
116 _Jv_argv = argv;
119 #ifdef ENABLE_JVMPI
120 // Pointer to JVMPI notification functions.
121 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
122 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
123 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
124 #endif
127 /* Unblock a signal. Unless we do this, the signal may only be sent
128 once. */
129 static void
130 unblock_signal (int signum)
132 #ifdef _POSIX_VERSION
133 sigset_t sigs;
135 sigemptyset (&sigs);
136 sigaddset (&sigs, signum);
137 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
138 #endif
141 #ifdef HANDLE_SEGV
142 SIGNAL_HANDLER (catch_segv)
144 java::lang::NullPointerException *nullp
145 = new java::lang::NullPointerException;
146 unblock_signal (SIGSEGV);
147 MAKE_THROW_FRAME (nullp);
148 throw nullp;
150 #endif
152 #ifdef HANDLE_FPE
153 SIGNAL_HANDLER (catch_fpe)
155 java::lang::ArithmeticException *arithexception
156 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
157 unblock_signal (SIGFPE);
158 #ifdef HANDLE_DIVIDE_OVERFLOW
159 HANDLE_DIVIDE_OVERFLOW;
160 #else
161 MAKE_THROW_FRAME (arithexception);
162 #endif
163 throw arithexception;
165 #endif
169 jboolean
170 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
172 int len;
173 const _Jv_ushort *aptr, *bptr;
174 if (a == b)
175 return true;
176 if (a->hash != b->hash)
177 return false;
178 len = a->length;
179 if (b->length != len)
180 return false;
181 aptr = (const _Jv_ushort *)a->data;
182 bptr = (const _Jv_ushort *)b->data;
183 len = (len + 1) >> 1;
184 while (--len >= 0)
185 if (*aptr++ != *bptr++)
186 return false;
187 return true;
190 /* True iff A is equal to STR.
191 HASH is STR->hashCode().
194 jboolean
195 _Jv_equal (Utf8Const* a, jstring str, jint hash)
197 if (a->hash != (_Jv_ushort) hash)
198 return false;
199 jint len = str->length();
200 jint i = 0;
201 jchar *sptr = _Jv_GetStringChars (str);
202 unsigned char* ptr = (unsigned char*) a->data;
203 unsigned char* limit = ptr + a->length;
204 for (;; i++, sptr++)
206 int ch = UTF8_GET (ptr, limit);
207 if (i == len)
208 return ch < 0;
209 if (ch != *sptr)
210 return false;
212 return true;
215 /* Like _Jv_equal, but stop after N characters. */
216 jboolean
217 _Jv_equaln (Utf8Const *a, jstring str, jint n)
219 jint len = str->length();
220 jint i = 0;
221 jchar *sptr = _Jv_GetStringChars (str);
222 unsigned char* ptr = (unsigned char*) a->data;
223 unsigned char* limit = ptr + a->length;
224 for (; n-- > 0; i++, sptr++)
226 int ch = UTF8_GET (ptr, limit);
227 if (i == len)
228 return ch < 0;
229 if (ch != *sptr)
230 return false;
232 return true;
235 /* Count the number of Unicode chars encoded in a given Ut8 string. */
237 _Jv_strLengthUtf8(char* str, int len)
239 unsigned char* ptr;
240 unsigned char* limit;
241 int str_length;
243 ptr = (unsigned char*) str;
244 limit = ptr + len;
245 str_length = 0;
246 for (; ptr < limit; str_length++)
248 if (UTF8_GET (ptr, limit) < 0)
249 return (-1);
251 return (str_length);
254 /* Calculate a hash value for a string encoded in Utf8 format.
255 * This returns the same hash value as specified or java.lang.String.hashCode.
257 static jint
258 hashUtf8String (char* str, int len)
260 unsigned char* ptr = (unsigned char*) str;
261 unsigned char* limit = ptr + len;
262 jint hash = 0;
264 for (; ptr < limit;)
266 int ch = UTF8_GET (ptr, limit);
267 /* Updated specification from
268 http://www.javasoft.com/docs/books/jls/clarify.html. */
269 hash = (31 * hash) + ch;
271 return hash;
274 _Jv_Utf8Const *
275 _Jv_makeUtf8Const (char* s, int len)
277 if (len < 0)
278 len = strlen (s);
279 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
280 memcpy (m->data, s, len);
281 m->data[len] = 0;
282 m->length = len;
283 m->hash = hashUtf8String (s, len) & 0xFFFF;
284 return (m);
287 _Jv_Utf8Const *
288 _Jv_makeUtf8Const (jstring string)
290 jint hash = string->hashCode ();
291 jint len = _Jv_GetStringUTFLength (string);
293 Utf8Const* m = (Utf8Const*)
294 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
296 m->hash = hash;
297 m->length = len;
299 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
300 m->data[len] = 0;
302 return m;
307 #ifdef DEBUG
308 void
309 _Jv_Abort (const char *function, const char *file, int line,
310 const char *message)
311 #else
312 void
313 _Jv_Abort (const char *, const char *, int, const char *message)
314 #endif
316 #ifdef DEBUG
317 fprintf (stderr,
318 "libgcj failure: %s\n in function %s, file %s, line %d\n",
319 message, function, file, line);
320 #else
321 fprintf (stderr, "libgcj failure: %s\n", message);
322 #endif
323 abort ();
326 static void
327 fail_on_finalization (jobject)
329 JvFail ("object was finalized");
332 void
333 _Jv_GCWatch (jobject obj)
335 _Jv_RegisterFinalizer (obj, fail_on_finalization);
338 void
339 _Jv_ThrowBadArrayIndex(jint bad_index)
341 throw new java::lang::ArrayIndexOutOfBoundsException
342 (java::lang::String::valueOf (bad_index));
345 void
346 _Jv_ThrowNullPointerException ()
348 throw new java::lang::NullPointerException;
351 // Explicitly throw a no memory exception.
352 // The collector calls this when it encounters an out-of-memory condition.
353 void _Jv_ThrowNoMemory()
355 throw no_memory;
358 #ifdef ENABLE_JVMPI
359 static void
360 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
362 // Service JVMPI allocation request.
363 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
365 JVMPI_Event event;
367 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
368 event.env_id = NULL;
369 event.u.obj_alloc.arena_id = 0;
370 event.u.obj_alloc.class_id = (jobjectID) klass;
371 event.u.obj_alloc.is_array = 0;
372 event.u.obj_alloc.size = size;
373 event.u.obj_alloc.obj_id = (jobjectID) obj;
375 // FIXME: This doesn't look right for the Boehm GC. A GC may
376 // already be in progress. _Jv_DisableGC () doesn't wait for it.
377 // More importantly, I don't see the need for disabling GC, since we
378 // blatantly have a pointer to obj on our stack, ensuring that the
379 // object can't be collected. Even for a nonconservative collector,
380 // it appears to me that this must be true, since we are about to
381 // return obj. Isn't this whole approach way too intrusive for
382 // a useful profiling interface? - HB
383 _Jv_DisableGC ();
384 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
385 _Jv_EnableGC ();
388 #else /* !ENABLE_JVMPI */
389 # define jvmpi_notify_alloc(klass,size,obj) /* do nothing */
390 #endif
392 // Allocate a new object of class KLASS. SIZE is the size of the object
393 // to allocate. You might think this is redundant, but it isn't; some
394 // classes, such as String, aren't of fixed size.
395 // First a version that assumes that we have no finalizer, and that
396 // the class is already initialized.
397 // If we know that JVMPI is disabled, this can be replaced by a direct call
398 // to the allocator for the appropriate GC.
399 jobject
400 _Jv_AllocObjectNoInitNoFinalizer (jclass klass, jint size)
402 jobject obj = (jobject) _Jv_AllocObj (size, klass);
403 jvmpi_notify_alloc (klass, size, obj);
404 return obj;
407 // And now a version that initializes if necessary.
408 jobject
409 _Jv_AllocObjectNoFinalizer (jclass klass, jint size)
411 _Jv_InitClass (klass);
412 jobject obj = (jobject) _Jv_AllocObj (size, klass);
413 jvmpi_notify_alloc (klass, size, obj);
414 return obj;
417 // And now the general version that registers a finalizer if necessary.
418 jobject
419 _Jv_AllocObject (jclass klass, jint size)
421 jobject obj = _Jv_AllocObjectNoFinalizer (klass, size);
423 // We assume that the compiler only generates calls to this routine
424 // if there really is an interesting finalizer.
425 // Unfortunately, we still have to the dynamic test, since there may
426 // be cni calls to this routine.
427 // Note that on IA64 get_finalizer() returns the starting address of the
428 // function, not a function pointer. Thus this still works.
429 if (klass->vtable->get_finalizer ()
430 != java::lang::Object::class$.vtable->get_finalizer ())
431 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
432 return obj;
435 // A version of the above that assumes the object contains no pointers,
436 // and requires no finalization. This can't happen if we need pointers
437 // to locks.
438 #ifdef JV_HASH_SYNCHRONIZATION
439 jobject
440 _Jv_AllocPtrFreeObject (jclass klass, jint size)
442 _Jv_InitClass (klass);
444 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
446 #ifdef ENABLE_JVMPI
447 // Service JVMPI request.
449 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
451 JVMPI_Event event;
453 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
454 event.env_id = NULL;
455 event.u.obj_alloc.arena_id = 0;
456 event.u.obj_alloc.class_id = (jobjectID) klass;
457 event.u.obj_alloc.is_array = 0;
458 event.u.obj_alloc.size = size;
459 event.u.obj_alloc.obj_id = (jobjectID) obj;
461 _Jv_DisableGC ();
462 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
463 _Jv_EnableGC ();
465 #endif
467 return obj;
469 #endif /* JV_HASH_SYNCHRONIZATION */
472 // Allocate a new array of Java objects. Each object is of type
473 // `elementClass'. `init' is used to initialize each slot in the
474 // array.
475 jobjectArray
476 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
478 if (__builtin_expect (count < 0, false))
479 throw new java::lang::NegativeArraySizeException;
481 JvAssert (! elementClass->isPrimitive ());
483 // Ensure that elements pointer is properly aligned.
484 jobjectArray obj = NULL;
485 size_t size = (size_t) elements (obj);
486 // Check for overflow.
487 if (__builtin_expect ((size_t) count >
488 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
489 throw no_memory;
491 size += count * sizeof (jobject);
493 jclass klass = _Jv_GetArrayClass (elementClass,
494 elementClass->getClassLoaderInternal());
496 obj = (jobjectArray) _Jv_AllocArray (size, klass);
497 // Cast away const.
498 jsize *lp = const_cast<jsize *> (&obj->length);
499 *lp = count;
500 // We know the allocator returns zeroed memory. So don't bother
501 // zeroing it again.
502 if (init)
504 jobject *ptr = elements(obj);
505 while (--count >= 0)
506 *ptr++ = init;
508 return obj;
511 // Allocate a new array of primitives. ELTYPE is the type of the
512 // element, COUNT is the size of the array.
513 jobject
514 _Jv_NewPrimArray (jclass eltype, jint count)
516 int elsize = eltype->size();
517 if (__builtin_expect (count < 0, false))
518 throw new java::lang::NegativeArraySizeException;
520 JvAssert (eltype->isPrimitive ());
521 jobject dummy = NULL;
522 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
524 // Check for overflow.
525 if (__builtin_expect ((size_t) count >
526 (MAX_OBJECT_SIZE - size) / elsize, false))
527 throw no_memory;
529 jclass klass = _Jv_GetArrayClass (eltype, 0);
531 # ifdef JV_HASH_SYNCHRONIZATION
532 // Since the vtable is always statically allocated,
533 // these are completely pointerfree! Make sure the GC doesn't touch them.
534 __JArray *arr =
535 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
536 memset((char *)arr + size, 0, elsize * count);
537 # else
538 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
539 // Note that we assume we are given zeroed memory by the allocator.
540 # endif
541 // Cast away const.
542 jsize *lp = const_cast<jsize *> (&arr->length);
543 *lp = count;
545 return arr;
548 jobject
549 _Jv_NewArray (jint type, jint size)
551 switch (type)
553 case 4: return JvNewBooleanArray (size);
554 case 5: return JvNewCharArray (size);
555 case 6: return JvNewFloatArray (size);
556 case 7: return JvNewDoubleArray (size);
557 case 8: return JvNewByteArray (size);
558 case 9: return JvNewShortArray (size);
559 case 10: return JvNewIntArray (size);
560 case 11: return JvNewLongArray (size);
562 throw new java::lang::InternalError
563 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
566 // Allocate a possibly multi-dimensional array but don't check that
567 // any array length is <0.
568 static jobject
569 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
571 JvAssert (type->isArray());
572 jclass element_type = type->getComponentType();
573 jobject result;
574 if (element_type->isPrimitive())
575 result = _Jv_NewPrimArray (element_type, sizes[0]);
576 else
577 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
579 if (dimensions > 1)
581 JvAssert (! element_type->isPrimitive());
582 JvAssert (element_type->isArray());
583 jobject *contents = elements ((jobjectArray) result);
584 for (int i = 0; i < sizes[0]; ++i)
585 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
586 sizes + 1);
589 return result;
592 jobject
593 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
595 for (int i = 0; i < dimensions; ++i)
596 if (sizes[i] < 0)
597 throw new java::lang::NegativeArraySizeException;
599 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
602 jobject
603 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
605 va_list args;
606 jint sizes[dimensions];
607 va_start (args, dimensions);
608 for (int i = 0; i < dimensions; ++i)
610 jint size = va_arg (args, jint);
611 if (size < 0)
612 throw new java::lang::NegativeArraySizeException;
613 sizes[i] = size;
615 va_end (args);
617 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
622 // Ensure 8-byte alignment, for hash synchronization.
623 #define DECLARE_PRIM_TYPE(NAME) \
624 _Jv_ArrayVTable _Jv_##NAME##VTable; \
625 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
627 DECLARE_PRIM_TYPE(byte)
628 DECLARE_PRIM_TYPE(short)
629 DECLARE_PRIM_TYPE(int)
630 DECLARE_PRIM_TYPE(long)
631 DECLARE_PRIM_TYPE(boolean)
632 DECLARE_PRIM_TYPE(char)
633 DECLARE_PRIM_TYPE(float)
634 DECLARE_PRIM_TYPE(double)
635 DECLARE_PRIM_TYPE(void)
637 void
638 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len,
639 _Jv_ArrayVTable *array_vtable)
641 using namespace java::lang::reflect;
643 // We must set the vtable for the class; the Java constructor
644 // doesn't do this.
645 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
647 // Initialize the fields we care about. We do this in the same
648 // order they are declared in Class.h.
649 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
650 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
651 cl->method_count = sig;
652 cl->size_in_bytes = len;
653 cl->vtable = JV_PRIMITIVE_VTABLE;
654 cl->state = JV_STATE_DONE;
655 cl->depth = -1;
656 if (sig != 'V')
657 _Jv_NewArrayClass (cl, NULL, (_Jv_VTable *) array_vtable);
660 jclass
661 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
663 switch (*sig)
665 case 'B':
666 return JvPrimClass (byte);
667 case 'S':
668 return JvPrimClass (short);
669 case 'I':
670 return JvPrimClass (int);
671 case 'J':
672 return JvPrimClass (long);
673 case 'Z':
674 return JvPrimClass (boolean);
675 case 'C':
676 return JvPrimClass (char);
677 case 'F':
678 return JvPrimClass (float);
679 case 'D':
680 return JvPrimClass (double);
681 case 'V':
682 return JvPrimClass (void);
683 case 'L':
685 int i;
686 for (i = 1; sig[i] && sig[i] != ';'; ++i)
688 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
689 return _Jv_FindClass (name, loader);
691 case '[':
693 jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
694 if (! klass)
695 return NULL;
696 return _Jv_GetArrayClass (klass, loader);
700 return NULL; // Placate compiler.
705 JArray<jstring> *
706 JvConvertArgv (int argc, const char **argv)
708 if (argc < 0)
709 argc = 0;
710 jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
711 jobject *ptr = elements(ar);
712 jbyteArray bytes = NULL;
713 for (int i = 0; i < argc; i++)
715 const char *arg = argv[i];
716 int len = strlen (arg);
717 if (bytes == NULL || bytes->length < len)
718 bytes = JvNewByteArray (len);
719 jbyte *bytePtr = elements (bytes);
720 // We assume jbyte == char.
721 memcpy (bytePtr, arg, len);
723 // Now convert using the default encoding.
724 *ptr++ = new java::lang::String (bytes, 0, len);
726 return (JArray<jstring>*) ar;
729 // FIXME: These variables are static so that they will be
730 // automatically scanned by the Boehm collector. This is needed
731 // because with qthreads the collector won't scan the initial stack --
732 // it will only scan the qthreads stacks.
734 // Command line arguments.
735 static JArray<jstring> *arg_vec;
737 // The primary thread.
738 static java::lang::Thread *main_thread;
740 #ifndef DISABLE_GETENV_PROPERTIES
742 static char *
743 next_property_key (char *s, size_t *length)
745 size_t l = 0;
747 JvAssert (s);
749 // Skip over whitespace
750 while (isspace (*s))
751 s++;
753 // If we've reached the end, return NULL. Also return NULL if for
754 // some reason we've come across a malformed property string.
755 if (*s == 0
756 || *s == ':'
757 || *s == '=')
758 return NULL;
760 // Determine the length of the property key.
761 while (s[l] != 0
762 && ! isspace (s[l])
763 && s[l] != ':'
764 && s[l] != '=')
766 if (s[l] == '\\'
767 && s[l+1] != 0)
768 l++;
769 l++;
772 *length = l;
774 return s;
777 static char *
778 next_property_value (char *s, size_t *length)
780 size_t l = 0;
782 JvAssert (s);
784 while (isspace (*s))
785 s++;
787 if (*s == ':'
788 || *s == '=')
789 s++;
791 while (isspace (*s))
792 s++;
794 // If we've reached the end, return NULL.
795 if (*s == 0)
796 return NULL;
798 // Determine the length of the property value.
799 while (s[l] != 0
800 && ! isspace (s[l])
801 && s[l] != ':'
802 && s[l] != '=')
804 if (s[l] == '\\'
805 && s[l+1] != 0)
806 l += 2;
807 else
808 l++;
811 *length = l;
813 return s;
816 static void
817 process_gcj_properties ()
819 char *props = getenv("GCJ_PROPERTIES");
820 char *p = props;
821 size_t length;
822 size_t property_count = 0;
824 if (NULL == props)
825 return;
827 // Whip through props quickly in order to count the number of
828 // property values.
829 while (p && (p = next_property_key (p, &length)))
831 // Skip to the end of the key
832 p += length;
834 p = next_property_value (p, &length);
835 if (p)
836 p += length;
838 property_count++;
841 // Allocate an array of property value/key pairs.
842 _Jv_Environment_Properties =
843 (property_pair *) malloc (sizeof(property_pair)
844 * (property_count + 1));
846 // Go through the properties again, initializing _Jv_Properties
847 // along the way.
848 p = props;
849 property_count = 0;
850 while (p && (p = next_property_key (p, &length)))
852 _Jv_Environment_Properties[property_count].key = p;
853 _Jv_Environment_Properties[property_count].key_length = length;
855 // Skip to the end of the key
856 p += length;
858 p = next_property_value (p, &length);
860 _Jv_Environment_Properties[property_count].value = p;
861 _Jv_Environment_Properties[property_count].value_length = length;
863 if (p)
864 p += length;
866 property_count++;
868 memset ((void *) &_Jv_Environment_Properties[property_count],
869 0, sizeof (property_pair));
871 size_t i = 0;
873 // Null terminate the strings.
874 while (_Jv_Environment_Properties[i].key)
876 _Jv_Environment_Properties[i].key[_Jv_Environment_Properties[i].key_length] = 0;
877 _Jv_Environment_Properties[i++].value[_Jv_Environment_Properties[i].value_length] = 0;
881 #endif // DISABLE_GETENV_PROPERTIES
883 namespace gcj
885 _Jv_Utf8Const *void_signature;
886 _Jv_Utf8Const *clinit_name;
887 _Jv_Utf8Const *init_name;
888 _Jv_Utf8Const *finit_name;
890 bool runtimeInitialized = false;
893 jint
894 _Jv_CreateJavaVM (void* /*vm_args*/)
896 using namespace gcj;
898 if (runtimeInitialized)
899 return -1;
901 runtimeInitialized = true;
903 PROCESS_GCJ_PROPERTIES;
905 _Jv_InitThreads ();
906 _Jv_InitGC ();
907 _Jv_InitializeSyncMutex ();
909 /* Initialize Utf8 constants declared in jvm.h. */
910 void_signature = _Jv_makeUtf8Const ("()V", 3);
911 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
912 init_name = _Jv_makeUtf8Const ("<init>", 6);
913 finit_name = _Jv_makeUtf8Const ("finit$", 6);
915 /* Initialize built-in classes to represent primitive TYPEs. */
916 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1, &_Jv_byteVTable);
917 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2, &_Jv_shortVTable);
918 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4, &_Jv_intVTable);
919 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8, &_Jv_longVTable);
920 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1, &_Jv_booleanVTable);
921 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2, &_Jv_charVTable);
922 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4, &_Jv_floatVTable);
923 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8, &_Jv_doubleVTable);
924 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0, &_Jv_voidVTable);
926 // Turn stack trace generation off while creating exception objects.
927 _Jv_InitClass (&java::lang::VMThrowable::class$);
928 java::lang::VMThrowable::trace_enabled = 0;
930 // We have to initialize this fairly early, to avoid circular class
931 // initialization. In particular we want to start the
932 // initialization of ClassLoader before we start the initialization
933 // of VMClassLoader.
934 _Jv_InitClass (&java::lang::ClassLoader::class$);
935 // Once the bootstrap loader is in place, change it into a kind of
936 // system loader, by having it read the class path.
937 gnu::gcj::runtime::VMClassLoader::initialize();
939 INIT_SEGV;
940 #ifdef HANDLE_FPE
941 INIT_FPE;
942 #endif
944 no_memory = new java::lang::OutOfMemoryError;
946 java::lang::VMThrowable::trace_enabled = 1;
948 #ifdef USE_LTDL
949 LTDL_SET_PRELOADED_SYMBOLS ();
950 #endif
952 _Jv_platform_initialize ();
954 _Jv_JNI_Init ();
956 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
958 // Start the GC finalizer thread. A VirtualMachineError can be
959 // thrown by the runtime if, say, threads aren't available. In this
960 // case finalizers simply won't run.
963 using namespace gnu::gcj::runtime;
964 FinalizerThread *ft = new FinalizerThread ();
965 ft->start ();
967 catch (java::lang::VirtualMachineError *ignore)
971 return 0;
974 void
975 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
976 bool is_jar)
978 _Jv_SetArgs (argc, argv);
980 java::lang::Runtime *runtime = NULL;
984 // Set this very early so that it is seen when java.lang.System
985 // is initialized.
986 if (is_jar)
987 _Jv_Jar_Class_Path = strdup (name);
988 _Jv_CreateJavaVM (NULL);
990 // Get the Runtime here. We want to initialize it before searching
991 // for `main'; that way it will be set up if `main' is a JNI method.
992 runtime = java::lang::Runtime::getRuntime ();
994 #ifdef DISABLE_MAIN_ARGS
995 arg_vec = JvConvertArgv (0, 0);
996 #else
997 arg_vec = JvConvertArgv (argc - 1, argv + 1);
998 #endif
1000 using namespace gnu::gcj::runtime;
1001 if (klass)
1002 main_thread = new FirstThread (klass, arg_vec);
1003 else
1004 main_thread = new FirstThread (JvNewStringLatin1 (name),
1005 arg_vec, is_jar);
1007 catch (java::lang::Throwable *t)
1009 java::lang::System::err->println (JvNewStringLatin1
1010 ("Exception during runtime initialization"));
1011 t->printStackTrace();
1012 runtime->exit (1);
1015 _Jv_AttachCurrentThread (main_thread);
1016 _Jv_ThreadRun (main_thread);
1017 _Jv_ThreadWait ();
1019 int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1020 runtime->exit (status);
1023 void
1024 JvRunMain (jclass klass, int argc, const char **argv)
1026 _Jv_RunMain (klass, NULL, argc, argv, false);
1031 // Parse a string and return a heap size.
1032 static size_t
1033 parse_heap_size (const char *spec)
1035 char *end;
1036 unsigned long val = strtoul (spec, &end, 10);
1037 if (*end == 'k' || *end == 'K')
1038 val *= 1024;
1039 else if (*end == 'm' || *end == 'M')
1040 val *= 1048576;
1041 return (size_t) val;
1044 // Set the initial heap size. This might be ignored by the GC layer.
1045 // This must be called before _Jv_RunMain.
1046 void
1047 _Jv_SetInitialHeapSize (const char *arg)
1049 size_t size = parse_heap_size (arg);
1050 _Jv_GCSetInitialHeapSize (size);
1053 // Set the maximum heap size. This might be ignored by the GC layer.
1054 // This must be called before _Jv_RunMain.
1055 void
1056 _Jv_SetMaximumHeapSize (const char *arg)
1058 size_t size = parse_heap_size (arg);
1059 _Jv_GCSetMaximumHeapSize (size);
1064 void *
1065 _Jv_Malloc (jsize size)
1067 if (__builtin_expect (size == 0, false))
1068 size = 1;
1069 void *ptr = malloc ((size_t) size);
1070 if (__builtin_expect (ptr == NULL, false))
1071 throw no_memory;
1072 return ptr;
1075 void *
1076 _Jv_Realloc (void *ptr, jsize size)
1078 if (__builtin_expect (size == 0, false))
1079 size = 1;
1080 ptr = realloc (ptr, (size_t) size);
1081 if (__builtin_expect (ptr == NULL, false))
1082 throw no_memory;
1083 return ptr;
1086 void *
1087 _Jv_MallocUnchecked (jsize size)
1089 if (__builtin_expect (size == 0, false))
1090 size = 1;
1091 return malloc ((size_t) size);
1094 void
1095 _Jv_Free (void* ptr)
1097 return free (ptr);
1102 // In theory, these routines can be #ifdef'd away on machines which
1103 // support divide overflow signals. However, we never know if some
1104 // code might have been compiled with "-fuse-divide-subroutine", so we
1105 // always include them in libgcj.
1107 jint
1108 _Jv_divI (jint dividend, jint divisor)
1110 if (__builtin_expect (divisor == 0, false))
1112 java::lang::ArithmeticException *arithexception
1113 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1114 throw arithexception;
1117 if (dividend == (jint) 0x80000000L && divisor == -1)
1118 return dividend;
1120 return dividend / divisor;
1123 jint
1124 _Jv_remI (jint dividend, jint divisor)
1126 if (__builtin_expect (divisor == 0, false))
1128 java::lang::ArithmeticException *arithexception
1129 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1130 throw arithexception;
1133 if (dividend == (jint) 0x80000000L && divisor == -1)
1134 return 0;
1136 return dividend % divisor;
1139 jlong
1140 _Jv_divJ (jlong dividend, jlong divisor)
1142 if (__builtin_expect (divisor == 0, false))
1144 java::lang::ArithmeticException *arithexception
1145 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1146 throw arithexception;
1149 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1150 return dividend;
1152 return dividend / divisor;
1155 jlong
1156 _Jv_remJ (jlong dividend, jlong divisor)
1158 if (__builtin_expect (divisor == 0, false))
1160 java::lang::ArithmeticException *arithexception
1161 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1162 throw arithexception;
1165 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1166 return 0;
1168 return dividend % divisor;
1173 // Return true if SELF_KLASS can access a field or method in
1174 // OTHER_KLASS. The field or method's access flags are specified in
1175 // FLAGS.
1176 jboolean
1177 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1179 using namespace java::lang::reflect;
1180 return ((self_klass == other_klass)
1181 || ((flags & Modifier::PUBLIC) != 0)
1182 || (((flags & Modifier::PROTECTED) != 0)
1183 && other_klass->isAssignableFrom (self_klass))
1184 || (((flags & Modifier::PRIVATE) == 0)
1185 && _Jv_ClassNameSamePackage (self_klass->name,
1186 other_klass->name)));