1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 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
26 #include <java-signal.h>
27 #include <java-threads.h>
28 #include <java-interp.h>
32 #include <java/lang/ThreadGroup.h>
35 #ifndef DISABLE_GETENV_PROPERTIES
37 #include <java-props.h>
38 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
40 #define PROCESS_GCJ_PROPERTIES
41 #endif // DISABLE_GETENV_PROPERTIES
43 #include <java/lang/Class.h>
44 #include <java/lang/ClassLoader.h>
45 #include <java/lang/Runtime.h>
46 #include <java/lang/String.h>
47 #include <java/lang/Thread.h>
48 #include <java/lang/ThreadGroup.h>
49 #include <java/lang/ArrayIndexOutOfBoundsException.h>
50 #include <java/lang/ArithmeticException.h>
51 #include <java/lang/ClassFormatError.h>
52 #include <java/lang/ClassNotFoundException.h>
53 #include <java/lang/InternalError.h>
54 #include <java/lang/NegativeArraySizeException.h>
55 #include <java/lang/NoClassDefFoundError.h>
56 #include <java/lang/NullPointerException.h>
57 #include <java/lang/OutOfMemoryError.h>
58 #include <java/lang/System.h>
59 #include <java/lang/VMThrowable.h>
60 #include <java/lang/VMClassLoader.h>
61 #include <java/lang/reflect/Modifier.h>
62 #include <java/io/PrintStream.h>
63 #include <java/lang/UnsatisfiedLinkError.h>
64 #include <java/lang/VirtualMachineError.h>
65 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
66 #include <gnu/gcj/runtime/FinalizerThread.h>
67 #include <execution.h>
68 #include <gnu/java/lang/MainThread.h>
74 // Execution engine for compiled code.
75 _Jv_CompiledEngine _Jv_soleCompiledEngine;
77 // We allocate a single OutOfMemoryError exception which we keep
78 // around for use if we run out of memory.
79 static java::lang::OutOfMemoryError *no_memory;
81 // Number of bytes in largest array object we create. This could be
82 // increased to the largest size_t value, so long as the appropriate
83 // functions are changed to take a size_t argument instead of jint.
84 #define MAX_OBJECT_SIZE ((1<<31) - 1)
86 // Properties set at compile time.
87 const char **_Jv_Compiler_Properties = NULL;
88 int _Jv_Properties_Count = 0;
90 #ifndef DISABLE_GETENV_PROPERTIES
91 // Property key/value pairs.
92 property_pair *_Jv_Environment_Properties;
95 // Stash the argv pointer to benefit native libraries that need it.
96 const char **_Jv_argv;
103 // _Jv_argc is 0 if not explicitly initialized.
108 _Jv_GetSafeArg (int index)
110 if (index >=0 && index < _Jv_GetNbArgs ())
111 return _Jv_argv[index];
117 _Jv_SetArgs (int argc, const char **argv)
124 // Pointer to JVMPI notification functions.
125 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
126 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
127 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
131 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
132 /* Unblock a signal. Unless we do this, the signal may only be sent
135 unblock_signal (int signum __attribute__ ((__unused__)))
137 #ifdef _POSIX_VERSION
141 sigaddset (&sigs, signum);
142 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
148 SIGNAL_HANDLER (catch_segv)
150 unblock_signal (SIGSEGV);
151 MAKE_THROW_FRAME (nullp);
152 java::lang::NullPointerException *nullp
153 = new java::lang::NullPointerException;
159 SIGNAL_HANDLER (catch_fpe)
161 unblock_signal (SIGFPE);
162 #ifdef HANDLE_DIVIDE_OVERFLOW
163 HANDLE_DIVIDE_OVERFLOW;
165 MAKE_THROW_FRAME (arithexception);
167 java::lang::ArithmeticException *arithexception
168 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
169 throw arithexception;
175 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
178 const _Jv_ushort *aptr, *bptr;
181 if (a->hash != b->hash)
184 if (b->length != len)
186 aptr = (const _Jv_ushort *)a->data;
187 bptr = (const _Jv_ushort *)b->data;
188 len = (len + 1) >> 1;
190 if (*aptr++ != *bptr++)
195 /* True iff A is equal to STR.
196 HASH is STR->hashCode().
200 _Jv_equal (Utf8Const* a, jstring str, jint hash)
202 if (a->hash != (_Jv_ushort) hash)
204 jint len = str->length();
206 jchar *sptr = _Jv_GetStringChars (str);
207 unsigned char* ptr = (unsigned char*) a->data;
208 unsigned char* limit = ptr + a->length;
211 int ch = UTF8_GET (ptr, limit);
220 /* Like _Jv_equal, but stop after N characters. */
222 _Jv_equaln (Utf8Const *a, jstring str, jint n)
224 jint len = str->length();
226 jchar *sptr = _Jv_GetStringChars (str);
227 unsigned char* ptr = (unsigned char*) a->data;
228 unsigned char* limit = ptr + a->length;
229 for (; n-- > 0; i++, sptr++)
231 int ch = UTF8_GET (ptr, limit);
240 // Determines whether the given Utf8Const object contains
241 // a type which is primitive or some derived form of it, eg.
242 // an array or multi-dimensional array variant.
244 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
246 unsigned char *aptr = (unsigned char *) a->data;
247 unsigned char *alimit = aptr + a->length;
248 int ac = UTF8_GET(aptr, alimit);
250 // Skips any leading array marks.
252 ac = UTF8_GET(aptr, alimit);
254 // There should not be another character. This implies that
255 // the type name is only one character long.
256 if (UTF8_GET(aptr, alimit) == -1)
275 // Find out whether two _Jv_Utf8Const candidates contain the same
277 // The method is written to handle the different formats of classnames.
278 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
279 // "java.lang.Class" will be seen as equal.
280 // Warning: This function is not smart enough to declare "Z" and "boolean"
281 // and similar cases as equal (and is not meant to be used this way)!
283 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
285 // If the class name's length differs by two characters
286 // it is possible that we have candidates which are given
287 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
288 switch (a->length - b->length)
298 unsigned char *aptr = (unsigned char *) a->data;
299 unsigned char *alimit = aptr + a->length;
300 unsigned char *bptr = (unsigned char *) b->data;
301 unsigned char *blimit = bptr + b->length;
303 if (alimit[-1] == ';')
306 if (blimit[-1] == ';')
309 int ac = UTF8_GET(aptr, alimit);
310 int bc = UTF8_GET(bptr, blimit);
312 // Checks whether both strings have the same amount of leading [ characters.
317 ac = UTF8_GET(aptr, alimit);
318 bc = UTF8_GET(bptr, blimit);
325 // Skips leading L character.
327 ac = UTF8_GET(aptr, alimit);
330 bc = UTF8_GET(bptr, blimit);
332 // Compares the remaining characters.
333 while (ac != -1 && bc != -1)
335 // Replaces package separating dots with slashes.
342 // Now classnames differ if there is at least one non-matching
347 ac = UTF8_GET(aptr, alimit);
348 bc = UTF8_GET(bptr, blimit);
354 /* Count the number of Unicode chars encoded in a given Ut8 string. */
356 _Jv_strLengthUtf8(const char* str, int len)
359 unsigned char* limit;
362 ptr = (unsigned char*) str;
365 for (; ptr < limit; str_length++)
367 if (UTF8_GET (ptr, limit) < 0)
373 /* Calculate a hash value for a string encoded in Utf8 format.
374 * This returns the same hash value as specified or java.lang.String.hashCode.
377 _Jv_hashUtf8String (const char* str, int len)
379 unsigned char* ptr = (unsigned char*) str;
380 unsigned char* limit = ptr + len;
385 int ch = UTF8_GET (ptr, limit);
386 /* Updated specification from
387 http://www.javasoft.com/docs/books/jls/clarify.html. */
388 hash = (31 * hash) + ch;
394 _Jv_Utf8Const::init(const char *s, int len)
396 ::memcpy (data, s, len);
399 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
403 _Jv_makeUtf8Const (const char* s, int len)
408 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
414 _Jv_makeUtf8Const (jstring string)
416 jint hash = string->hashCode ();
417 jint len = _Jv_GetStringUTFLength (string);
419 Utf8Const* m = (Utf8Const*)
420 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
425 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
435 _Jv_Abort (const char *function, const char *file, int line,
439 _Jv_Abort (const char *, const char *, int, const char *message)
444 "libgcj failure: %s\n in function %s, file %s, line %d\n",
445 message, function, file, line);
447 fprintf (stderr, "libgcj failure: %s\n", message);
453 fail_on_finalization (jobject)
455 JvFail ("object was finalized");
459 _Jv_GCWatch (jobject obj)
461 _Jv_RegisterFinalizer (obj, fail_on_finalization);
465 _Jv_ThrowBadArrayIndex(jint bad_index)
467 throw new java::lang::ArrayIndexOutOfBoundsException
468 (java::lang::String::valueOf (bad_index));
472 _Jv_ThrowNullPointerException ()
474 throw new java::lang::NullPointerException;
477 // Resolve an entry in the constant pool and return the target
480 _Jv_ResolvePoolEntry (jclass this_class, jint index)
482 _Jv_Constants *pool = &this_class->constants;
484 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
485 return pool->data[index].field->u.addr;
487 JvSynchronize sync (this_class);
488 return (_Jv_Linker::resolve_pool_entry (this_class, index))
493 // Explicitly throw a no memory exception.
494 // The collector calls this when it encounters an out-of-memory condition.
495 void _Jv_ThrowNoMemory()
501 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
502 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
503 jvmpi_notify_alloc(klass,size,obj);
505 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
507 // Service JVMPI allocation request.
510 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
512 event.u.obj_alloc.arena_id = 0;
513 event.u.obj_alloc.class_id = (jobjectID) klass;
514 event.u.obj_alloc.is_array = 0;
515 event.u.obj_alloc.size = size;
516 event.u.obj_alloc.obj_id = (jobjectID) obj;
518 // FIXME: This doesn't look right for the Boehm GC. A GC may
519 // already be in progress. _Jv_DisableGC () doesn't wait for it.
520 // More importantly, I don't see the need for disabling GC, since we
521 // blatantly have a pointer to obj on our stack, ensuring that the
522 // object can't be collected. Even for a nonconservative collector,
523 // it appears to me that this must be true, since we are about to
524 // return obj. Isn't this whole approach way too intrusive for
525 // a useful profiling interface? - HB
527 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
530 #else /* !ENABLE_JVMPI */
531 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
534 // Allocate a new object of class KLASS.
535 // First a version that assumes that we have no finalizer, and that
536 // the class is already initialized.
537 // If we know that JVMPI is disabled, this can be replaced by a direct call
538 // to the allocator for the appropriate GC.
540 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
542 jint size = klass->size ();
543 jobject obj = (jobject) _Jv_AllocObj (size, klass);
544 JVMPI_NOTIFY_ALLOC (klass, size, obj);
548 // And now a version that initializes if necessary.
550 _Jv_AllocObjectNoFinalizer (jclass klass)
552 if (_Jv_IsPhantomClass(klass) )
553 throw new java::lang::NoClassDefFoundError(klass->getName());
555 _Jv_InitClass (klass);
556 jint size = klass->size ();
557 jobject obj = (jobject) _Jv_AllocObj (size, klass);
558 JVMPI_NOTIFY_ALLOC (klass, size, obj);
562 // And now the general version that registers a finalizer if necessary.
564 _Jv_AllocObject (jclass klass)
566 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
568 // We assume that the compiler only generates calls to this routine
569 // if there really is an interesting finalizer.
570 // Unfortunately, we still have to the dynamic test, since there may
571 // be cni calls to this routine.
572 // Note that on IA64 get_finalizer() returns the starting address of the
573 // function, not a function pointer. Thus this still works.
574 if (klass->vtable->get_finalizer ()
575 != java::lang::Object::class$.vtable->get_finalizer ())
576 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
580 // Allocate a String, including variable length storage.
582 _Jv_AllocString(jsize len)
584 using namespace java::lang;
586 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
588 // We assert that for strings allocated this way, the data field
589 // will always point to the object itself. Thus there is no reason
590 // for the garbage collector to scan any of it.
591 // Furthermore, we're about to overwrite the string data, so
592 // initialization of the object is not an issue.
594 // String needs no initialization, and there is no finalizer, so
595 // we can go directly to the collector's allocator interface.
596 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
599 obj->boffset = sizeof(java::lang::String);
601 obj->cachedHashCode = 0;
603 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
608 // A version of the above that assumes the object contains no pointers,
609 // and requires no finalization. This can't happen if we need pointers
611 #ifdef JV_HASH_SYNCHRONIZATION
613 _Jv_AllocPtrFreeObject (jclass klass)
615 _Jv_InitClass (klass);
616 jint size = klass->size ();
618 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
620 JVMPI_NOTIFY_ALLOC (klass, size, obj);
624 #endif /* JV_HASH_SYNCHRONIZATION */
627 // Allocate a new array of Java objects. Each object is of type
628 // `elementClass'. `init' is used to initialize each slot in the
631 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
633 // Creating an array of an unresolved type is impossible. So we throw
634 // the NoClassDefFoundError.
635 if ( _Jv_IsPhantomClass(elementClass) )
636 throw new java::lang::NoClassDefFoundError(elementClass->getName());
638 if (__builtin_expect (count < 0, false))
639 throw new java::lang::NegativeArraySizeException;
641 JvAssert (! elementClass->isPrimitive ());
643 // Ensure that elements pointer is properly aligned.
644 jobjectArray obj = NULL;
645 size_t size = (size_t) elements (obj);
646 // Check for overflow.
647 if (__builtin_expect ((size_t) count >
648 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
651 size += count * sizeof (jobject);
653 jclass klass = _Jv_GetArrayClass (elementClass,
654 elementClass->getClassLoaderInternal());
656 obj = (jobjectArray) _Jv_AllocArray (size, klass);
658 jsize *lp = const_cast<jsize *> (&obj->length);
660 // We know the allocator returns zeroed memory. So don't bother
664 jobject *ptr = elements(obj);
671 // Allocate a new array of primitives. ELTYPE is the type of the
672 // element, COUNT is the size of the array.
674 _Jv_NewPrimArray (jclass eltype, jint count)
676 int elsize = eltype->size();
677 if (__builtin_expect (count < 0, false))
678 throw new java::lang::NegativeArraySizeException;
680 JvAssert (eltype->isPrimitive ());
681 jobject dummy = NULL;
682 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
684 // Check for overflow.
685 if (__builtin_expect ((size_t) count >
686 (MAX_OBJECT_SIZE - size) / elsize, false))
689 jclass klass = _Jv_GetArrayClass (eltype, 0);
691 # ifdef JV_HASH_SYNCHRONIZATION
692 // Since the vtable is always statically allocated,
693 // these are completely pointerfree! Make sure the GC doesn't touch them.
695 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
696 memset((char *)arr + size, 0, elsize * count);
698 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
699 // Note that we assume we are given zeroed memory by the allocator.
702 jsize *lp = const_cast<jsize *> (&arr->length);
709 _Jv_NewArray (jint type, jint size)
713 case 4: return JvNewBooleanArray (size);
714 case 5: return JvNewCharArray (size);
715 case 6: return JvNewFloatArray (size);
716 case 7: return JvNewDoubleArray (size);
717 case 8: return JvNewByteArray (size);
718 case 9: return JvNewShortArray (size);
719 case 10: return JvNewIntArray (size);
720 case 11: return JvNewLongArray (size);
722 throw new java::lang::InternalError
723 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
726 // Allocate a possibly multi-dimensional array but don't check that
727 // any array length is <0.
729 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
731 JvAssert (type->isArray());
732 jclass element_type = type->getComponentType();
734 if (element_type->isPrimitive())
735 result = _Jv_NewPrimArray (element_type, sizes[0]);
737 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
741 JvAssert (! element_type->isPrimitive());
742 JvAssert (element_type->isArray());
743 jobject *contents = elements ((jobjectArray) result);
744 for (int i = 0; i < sizes[0]; ++i)
745 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
753 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
755 for (int i = 0; i < dimensions; ++i)
757 throw new java::lang::NegativeArraySizeException;
759 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
763 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
765 // Creating an array of an unresolved type is impossible. So we throw
766 // the NoClassDefFoundError.
767 if (_Jv_IsPhantomClass(array_type))
768 throw new java::lang::NoClassDefFoundError(array_type->getName());
771 jint sizes[dimensions];
772 va_start (args, dimensions);
773 for (int i = 0; i < dimensions; ++i)
775 jint size = va_arg (args, jint);
777 throw new java::lang::NegativeArraySizeException;
782 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
787 // Ensure 8-byte alignment, for hash synchronization.
788 #define DECLARE_PRIM_TYPE(NAME) \
789 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
791 DECLARE_PRIM_TYPE(byte)
792 DECLARE_PRIM_TYPE(short)
793 DECLARE_PRIM_TYPE(int)
794 DECLARE_PRIM_TYPE(long)
795 DECLARE_PRIM_TYPE(boolean)
796 DECLARE_PRIM_TYPE(char)
797 DECLARE_PRIM_TYPE(float)
798 DECLARE_PRIM_TYPE(double)
799 DECLARE_PRIM_TYPE(void)
802 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
804 using namespace java::lang::reflect;
806 // We must set the vtable for the class; the Java constructor
808 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
810 // Initialize the fields we care about. We do this in the same
811 // order they are declared in Class.h.
812 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
813 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
814 cl->method_count = sig;
815 cl->size_in_bytes = len;
816 cl->vtable = JV_PRIMITIVE_VTABLE;
817 cl->state = JV_STATE_DONE;
822 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
825 // First count arrays.
833 jclass result = NULL;
837 result = JvPrimClass (byte);
840 result = JvPrimClass (short);
843 result = JvPrimClass (int);
846 result = JvPrimClass (long);
849 result = JvPrimClass (boolean);
852 result = JvPrimClass (char);
855 result = JvPrimClass (float);
858 result = JvPrimClass (double);
861 result = JvPrimClass (void);
866 while (*sig && *sig != ';')
868 // Do nothing if signature appears to be malformed.
871 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
872 result = _Jv_FindClass (name, loader);
877 // Do nothing -- bad signature.
883 // Not really the "end", but the last valid character that we
892 while (array_count-- > 0)
893 result = _Jv_GetArrayClass (result, loader);
899 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
906 klass = _Jv_FindClassFromSignature(sig, loader, endp);
908 catch (java::lang::NoClassDefFoundError *ncdfe)
912 catch (java::lang::ClassNotFoundException *cnfe)
921 JvConvertArgv (int argc, const char **argv)
925 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
926 jobject *ptr = elements(ar);
927 jbyteArray bytes = NULL;
928 for (int i = 0; i < argc; i++)
930 const char *arg = argv[i];
931 int len = strlen (arg);
932 if (bytes == NULL || bytes->length < len)
933 bytes = JvNewByteArray (len);
934 jbyte *bytePtr = elements (bytes);
935 // We assume jbyte == char.
936 memcpy (bytePtr, arg, len);
938 // Now convert using the default encoding.
939 *ptr++ = new java::lang::String (bytes, 0, len);
941 return (JArray<jstring>*) ar;
944 // FIXME: These variables are static so that they will be
945 // automatically scanned by the Boehm collector. This is needed
946 // because with qthreads the collector won't scan the initial stack --
947 // it will only scan the qthreads stacks.
949 // Command line arguments.
950 static JArray<jstring> *arg_vec;
952 // The primary thread.
953 static java::lang::Thread *main_thread;
955 #ifndef DISABLE_GETENV_PROPERTIES
958 next_property_key (char *s, size_t *length)
964 // Skip over whitespace
968 // If we've reached the end, return NULL. Also return NULL if for
969 // some reason we've come across a malformed property string.
975 // Determine the length of the property key.
993 next_property_value (char *s, size_t *length)
1006 while (isspace (*s))
1009 // Determine the length of the property value.
1028 process_gcj_properties ()
1030 char *props = getenv("GCJ_PROPERTIES");
1035 // Later on we will write \0s into this string. It is simplest to
1036 // just duplicate it here.
1037 props = strdup (props);
1041 size_t property_count = 0;
1043 // Whip through props quickly in order to count the number of
1045 while (p && (p = next_property_key (p, &length)))
1047 // Skip to the end of the key
1050 p = next_property_value (p, &length);
1057 // Allocate an array of property value/key pairs.
1058 _Jv_Environment_Properties =
1059 (property_pair *) malloc (sizeof(property_pair)
1060 * (property_count + 1));
1062 // Go through the properties again, initializing _Jv_Properties
1066 while (p && (p = next_property_key (p, &length)))
1068 _Jv_Environment_Properties[property_count].key = p;
1069 _Jv_Environment_Properties[property_count].key_length = length;
1071 // Skip to the end of the key
1074 p = next_property_value (p, &length);
1076 _Jv_Environment_Properties[property_count].value = p;
1077 _Jv_Environment_Properties[property_count].value_length = length;
1084 memset ((void *) &_Jv_Environment_Properties[property_count],
1085 0, sizeof (property_pair));
1087 // Null terminate the strings.
1088 for (property_pair *prop = &_Jv_Environment_Properties[0];
1092 prop->key[prop->key_length] = 0;
1093 prop->value[prop->value_length] = 0;
1096 #endif // DISABLE_GETENV_PROPERTIES
1100 _Jv_Utf8Const *void_signature;
1101 _Jv_Utf8Const *clinit_name;
1102 _Jv_Utf8Const *init_name;
1103 _Jv_Utf8Const *finit_name;
1105 bool runtimeInitialized = false;
1107 // When true, print debugging information about class loading.
1108 bool verbose_class_flag;
1110 // When true, enable the bytecode verifier and BC-ABI type verification.
1111 bool verifyClasses = true;
1113 // Thread stack size specified by the -Xss runtime argument.
1114 size_t stack_size = 0;
1117 // We accept all non-standard options accepted by Sun's java command,
1118 // for compatibility with existing application launch scripts.
1120 parse_x_arg (char* option_string)
1122 if (strlen (option_string) <= 0)
1125 if (! strcmp (option_string, "int"))
1127 // FIXME: this should cause the vm to never load shared objects
1129 else if (! strcmp (option_string, "mixed"))
1131 // FIXME: allow interpreted and native code
1133 else if (! strcmp (option_string, "batch"))
1135 // FIXME: disable background JIT'ing
1137 else if (! strcmp (option_string, "debug"))
1139 // FIXME: add JDWP/JVMDI support
1141 else if (! strncmp (option_string, "bootclasspath:", 14))
1143 // FIXME: add a parse_bootclasspath_arg function
1145 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1148 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1151 else if (! strcmp (option_string, "check:jni"))
1153 // FIXME: enable strict JNI checking
1155 else if (! strcmp (option_string, "future"))
1157 // FIXME: enable strict class file format checks
1159 else if (! strcmp (option_string, "noclassgc"))
1161 // FIXME: disable garbage collection for classes
1163 else if (! strcmp (option_string, "incgc"))
1165 // FIXME: incremental garbage collection
1167 else if (! strncmp (option_string, "loggc:", 6))
1169 if (option_string[6] == '\0')
1172 "libgcj: filename argument expected for loggc option\n");
1175 // FIXME: set gc logging filename
1177 else if (! strncmp (option_string, "ms", 2))
1179 // FIXME: ignore this option until PR 20699 is fixed.
1180 // _Jv_SetInitialHeapSize (option_string + 2);
1182 else if (! strncmp (option_string, "mx", 2))
1183 _Jv_SetMaximumHeapSize (option_string + 2);
1184 else if (! strcmp (option_string, "prof"))
1186 // FIXME: enable profiling of program running in vm
1188 else if (! strncmp (option_string, "runhprof:", 9))
1190 // FIXME: enable specific type of vm profiling. add a
1191 // parse_runhprof_arg function
1193 else if (! strcmp (option_string, "rs"))
1195 // FIXME: reduced system signal usage. disable thread dumps,
1196 // only terminate in response to user-initiated calls,
1197 // e.g. System.exit()
1199 else if (! strncmp (option_string, "ss", 2))
1201 _Jv_SetStackSize (option_string + 2);
1203 else if (! strcmp (option_string, "X:+UseAltSigs"))
1205 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1207 else if (! strcmp (option_string, "share:off"))
1209 // FIXME: don't share class data
1211 else if (! strcmp (option_string, "share:auto"))
1213 // FIXME: share class data where possible
1215 else if (! strcmp (option_string, "share:on"))
1217 // FIXME: fail if impossible to share class data
1224 parse_verbose_args (char* option_string,
1225 bool ignore_unrecognized)
1227 size_t len = sizeof ("-verbose") - 1;
1229 if (strlen (option_string) < len)
1232 if (option_string[len] == ':'
1233 && option_string[len + 1] != '\0')
1235 char* verbose_args = option_string + len + 1;
1239 if (! strncmp (verbose_args,
1240 "gc", sizeof ("gc") - 1))
1242 if (verbose_args[sizeof ("gc") - 1] == '\0'
1243 || verbose_args[sizeof ("gc") - 1] == ',')
1245 // FIXME: we should add functions to boehm-gc that
1246 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1247 // GC_print_back_height.
1248 verbose_args += sizeof ("gc") - 1;
1253 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1258 else if (! strncmp (verbose_args,
1260 sizeof ("class") - 1))
1262 if (verbose_args[sizeof ("class") - 1] == '\0'
1263 || verbose_args[sizeof ("class") - 1] == ',')
1265 gcj::verbose_class_flag = true;
1266 verbose_args += sizeof ("class") - 1;
1269 goto verbose_arg_err;
1271 else if (! strncmp (verbose_args, "jni",
1272 sizeof ("jni") - 1))
1274 if (verbose_args[sizeof ("jni") - 1] == '\0'
1275 || verbose_args[sizeof ("jni") - 1] == ',')
1277 // FIXME: enable JNI messages.
1278 verbose_args += sizeof ("jni") - 1;
1281 goto verbose_arg_err;
1283 else if (ignore_unrecognized
1284 && verbose_args[0] == 'X')
1286 // ignore unrecognized non-standard verbose option
1287 while (verbose_args[0] != '\0'
1288 && verbose_args[0] != ',')
1291 else if (verbose_args[0] == ',')
1296 goto verbose_arg_err;
1298 if (verbose_args[0] == ',')
1301 while (verbose_args[0] != '\0');
1303 else if (option_string[len] == 'g'
1304 && option_string[len + 1] == 'c'
1305 && option_string[len + 2] == '\0')
1307 // FIXME: we should add functions to boehm-gc that
1308 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1309 // GC_print_back_height.
1312 else if (option_string[len] == '\0')
1314 gcj::verbose_class_flag = true;
1319 // unrecognized option beginning with -verbose
1326 parse_init_args (JvVMInitArgs* vm_args)
1328 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1329 // re-allocated dynamically.
1330 if (_Jv_Compiler_Properties)
1332 const char** props = _Jv_Compiler_Properties;
1333 _Jv_Compiler_Properties = NULL;
1335 for (int i = 0; props[i]; i++)
1337 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1338 (_Jv_Compiler_Properties,
1339 (_Jv_Properties_Count + 1) * sizeof (const char*));
1340 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1344 if (vm_args == NULL)
1347 for (int i = 0; i < vm_args->nOptions; ++i)
1349 char* option_string = vm_args->options[i].optionString;
1350 if (! strcmp (option_string, "vfprintf")
1351 || ! strcmp (option_string, "exit")
1352 || ! strcmp (option_string, "abort"))
1354 // FIXME: we are required to recognize these, but for
1355 // now we don't handle them in any way.
1358 else if (! strncmp (option_string,
1359 "-verbose", sizeof ("-verbose") - 1))
1361 jint result = parse_verbose_args (option_string,
1362 vm_args->ignoreUnrecognized);
1366 else if (! strncmp (option_string, "-D", 2))
1368 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1369 (_Jv_Compiler_Properties,
1370 (_Jv_Properties_Count + 1) * sizeof (char*));
1372 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1373 strdup (option_string + 2);
1377 else if (vm_args->ignoreUnrecognized)
1379 if (option_string[0] == '_')
1380 parse_x_arg (option_string + 1);
1381 else if (! strncmp (option_string, "-X", 2))
1382 parse_x_arg (option_string + 2);
1386 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1391 goto unknown_option;
1397 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1399 using namespace gcj;
1401 if (runtimeInitialized)
1404 runtimeInitialized = true;
1406 jint result = parse_init_args (vm_args);
1410 PROCESS_GCJ_PROPERTIES;
1412 /* Threads must be initialized before the GC, so that it inherits the
1416 _Jv_InitializeSyncMutex ();
1419 _Jv_InitInterpreter ();
1430 /* Initialize Utf8 constants declared in jvm.h. */
1431 void_signature = _Jv_makeUtf8Const ("()V", 3);
1432 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1433 init_name = _Jv_makeUtf8Const ("<init>", 6);
1434 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1436 /* Initialize built-in classes to represent primitive TYPEs. */
1437 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1438 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1439 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1440 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1441 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1442 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1443 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1444 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1445 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1447 // Turn stack trace generation off while creating exception objects.
1448 _Jv_InitClass (&java::lang::VMThrowable::class$);
1449 java::lang::VMThrowable::trace_enabled = 0;
1451 // We have to initialize this fairly early, to avoid circular class
1452 // initialization. In particular we want to start the
1453 // initialization of ClassLoader before we start the initialization
1454 // of VMClassLoader.
1455 _Jv_InitClass (&java::lang::ClassLoader::class$);
1457 // Set up the system class loader and the bootstrap class loader.
1458 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1459 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1461 _Jv_RegisterBootstrapPackages();
1463 no_memory = new java::lang::OutOfMemoryError;
1465 java::lang::VMThrowable::trace_enabled = 1;
1468 LTDL_SET_PRELOADED_SYMBOLS ();
1471 _Jv_platform_initialize ();
1475 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1477 // Start the GC finalizer thread. A VirtualMachineError can be
1478 // thrown by the runtime if, say, threads aren't available.
1481 using namespace gnu::gcj::runtime;
1482 FinalizerThread *ft = new FinalizerThread ();
1485 catch (java::lang::VirtualMachineError *ignore)
1493 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1494 const char **argv, bool is_jar)
1496 #ifndef DISABLE_MAIN_ARGS
1497 _Jv_SetArgs (argc, argv);
1500 java::lang::Runtime *runtime = NULL;
1504 if (_Jv_CreateJavaVM (vm_args) < 0)
1506 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1510 // Get the Runtime here. We want to initialize it before searching
1511 // for `main'; that way it will be set up if `main' is a JNI method.
1512 runtime = java::lang::Runtime::getRuntime ();
1514 #ifdef DISABLE_MAIN_ARGS
1515 arg_vec = JvConvertArgv (0, 0);
1517 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1520 using namespace gnu::java::lang;
1522 main_thread = new MainThread (klass, arg_vec);
1524 main_thread = new MainThread (JvNewStringLatin1 (name),
1527 catch (java::lang::Throwable *t)
1529 java::lang::System::err->println (JvNewStringLatin1
1530 ("Exception during runtime initialization"));
1531 t->printStackTrace();
1533 java::lang::Runtime::exitNoChecksAccessor (1);
1534 // In case the runtime creation failed.
1538 _Jv_AttachCurrentThread (main_thread);
1539 _Jv_ThreadRun (main_thread);
1541 // If we got here then something went wrong, as MainThread is not
1542 // supposed to terminate.
1547 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1550 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1554 JvRunMain (jclass klass, int argc, const char **argv)
1556 _Jv_RunMain (klass, NULL, argc, argv, false);
1561 // Parse a string and return a heap size.
1563 parse_memory_size (const char *spec)
1566 unsigned long val = strtoul (spec, &end, 10);
1567 if (*end == 'k' || *end == 'K')
1569 else if (*end == 'm' || *end == 'M')
1571 return (size_t) val;
1574 // Set the initial heap size. This might be ignored by the GC layer.
1575 // This must be called before _Jv_RunMain.
1577 _Jv_SetInitialHeapSize (const char *arg)
1579 size_t size = parse_memory_size (arg);
1580 _Jv_GCSetInitialHeapSize (size);
1583 // Set the maximum heap size. This might be ignored by the GC layer.
1584 // This must be called before _Jv_RunMain.
1586 _Jv_SetMaximumHeapSize (const char *arg)
1588 size_t size = parse_memory_size (arg);
1589 _Jv_GCSetMaximumHeapSize (size);
1593 _Jv_SetStackSize (const char *arg)
1595 size_t size = parse_memory_size (arg);
1596 gcj::stack_size = size;
1600 _Jv_Malloc (jsize size)
1602 if (__builtin_expect (size == 0, false))
1604 void *ptr = malloc ((size_t) size);
1605 if (__builtin_expect (ptr == NULL, false))
1611 _Jv_Realloc (void *ptr, jsize size)
1613 if (__builtin_expect (size == 0, false))
1615 ptr = realloc (ptr, (size_t) size);
1616 if (__builtin_expect (ptr == NULL, false))
1622 _Jv_MallocUnchecked (jsize size)
1624 if (__builtin_expect (size == 0, false))
1626 return malloc ((size_t) size);
1630 _Jv_Free (void* ptr)
1637 // In theory, these routines can be #ifdef'd away on machines which
1638 // support divide overflow signals. However, we never know if some
1639 // code might have been compiled with "-fuse-divide-subroutine", so we
1640 // always include them in libgcj.
1643 _Jv_divI (jint dividend, jint divisor)
1645 if (__builtin_expect (divisor == 0, false))
1647 java::lang::ArithmeticException *arithexception
1648 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1649 throw arithexception;
1652 if (dividend == (jint) 0x80000000L && divisor == -1)
1655 return dividend / divisor;
1659 _Jv_remI (jint dividend, jint divisor)
1661 if (__builtin_expect (divisor == 0, false))
1663 java::lang::ArithmeticException *arithexception
1664 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1665 throw arithexception;
1668 if (dividend == (jint) 0x80000000L && divisor == -1)
1671 return dividend % divisor;
1675 _Jv_divJ (jlong dividend, jlong divisor)
1677 if (__builtin_expect (divisor == 0, false))
1679 java::lang::ArithmeticException *arithexception
1680 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1681 throw arithexception;
1684 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1687 return dividend / divisor;
1691 _Jv_remJ (jlong dividend, jlong divisor)
1693 if (__builtin_expect (divisor == 0, false))
1695 java::lang::ArithmeticException *arithexception
1696 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1697 throw arithexception;
1700 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1703 return dividend % divisor;
1708 // Return true if SELF_KLASS can access a field or method in
1709 // OTHER_KLASS. The field or method's access flags are specified in
1712 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1714 using namespace java::lang::reflect;
1715 return ((self_klass == other_klass)
1716 || ((flags & Modifier::PUBLIC) != 0)
1717 || (((flags & Modifier::PROTECTED) != 0)
1718 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1719 || (((flags & Modifier::PRIVATE) == 0)
1720 && _Jv_ClassNameSamePackage (self_klass->name,
1721 other_klass->name)));