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, ...)
766 jint sizes[dimensions];
767 va_start (args, dimensions);
768 for (int i = 0; i < dimensions; ++i)
770 jint size = va_arg (args, jint);
772 throw new java::lang::NegativeArraySizeException;
777 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
782 // Ensure 8-byte alignment, for hash synchronization.
783 #define DECLARE_PRIM_TYPE(NAME) \
784 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
786 DECLARE_PRIM_TYPE(byte)
787 DECLARE_PRIM_TYPE(short)
788 DECLARE_PRIM_TYPE(int)
789 DECLARE_PRIM_TYPE(long)
790 DECLARE_PRIM_TYPE(boolean)
791 DECLARE_PRIM_TYPE(char)
792 DECLARE_PRIM_TYPE(float)
793 DECLARE_PRIM_TYPE(double)
794 DECLARE_PRIM_TYPE(void)
797 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
799 using namespace java::lang::reflect;
801 // We must set the vtable for the class; the Java constructor
803 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
805 // Initialize the fields we care about. We do this in the same
806 // order they are declared in Class.h.
807 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
808 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
809 cl->method_count = sig;
810 cl->size_in_bytes = len;
811 cl->vtable = JV_PRIMITIVE_VTABLE;
812 cl->state = JV_STATE_DONE;
817 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
820 // First count arrays.
828 jclass result = NULL;
832 result = JvPrimClass (byte);
835 result = JvPrimClass (short);
838 result = JvPrimClass (int);
841 result = JvPrimClass (long);
844 result = JvPrimClass (boolean);
847 result = JvPrimClass (char);
850 result = JvPrimClass (float);
853 result = JvPrimClass (double);
856 result = JvPrimClass (void);
861 while (*sig && *sig != ';')
863 // Do nothing if signature appears to be malformed.
866 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
867 result = _Jv_FindClass (name, loader);
872 // Do nothing -- bad signature.
878 // Not really the "end", but the last valid character that we
887 while (array_count-- > 0)
888 result = _Jv_GetArrayClass (result, loader);
894 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
901 klass = _Jv_FindClassFromSignature(sig, loader, endp);
903 catch (java::lang::NoClassDefFoundError *ncdfe)
907 catch (java::lang::ClassNotFoundException *cnfe)
916 JvConvertArgv (int argc, const char **argv)
920 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
921 jobject *ptr = elements(ar);
922 jbyteArray bytes = NULL;
923 for (int i = 0; i < argc; i++)
925 const char *arg = argv[i];
926 int len = strlen (arg);
927 if (bytes == NULL || bytes->length < len)
928 bytes = JvNewByteArray (len);
929 jbyte *bytePtr = elements (bytes);
930 // We assume jbyte == char.
931 memcpy (bytePtr, arg, len);
933 // Now convert using the default encoding.
934 *ptr++ = new java::lang::String (bytes, 0, len);
936 return (JArray<jstring>*) ar;
939 // FIXME: These variables are static so that they will be
940 // automatically scanned by the Boehm collector. This is needed
941 // because with qthreads the collector won't scan the initial stack --
942 // it will only scan the qthreads stacks.
944 // Command line arguments.
945 static JArray<jstring> *arg_vec;
947 // The primary thread.
948 static java::lang::Thread *main_thread;
950 #ifndef DISABLE_GETENV_PROPERTIES
953 next_property_key (char *s, size_t *length)
959 // Skip over whitespace
963 // If we've reached the end, return NULL. Also return NULL if for
964 // some reason we've come across a malformed property string.
970 // Determine the length of the property key.
988 next_property_value (char *s, size_t *length)
1001 while (isspace (*s))
1004 // Determine the length of the property value.
1023 process_gcj_properties ()
1025 char *props = getenv("GCJ_PROPERTIES");
1030 // Later on we will write \0s into this string. It is simplest to
1031 // just duplicate it here.
1032 props = strdup (props);
1036 size_t property_count = 0;
1038 // Whip through props quickly in order to count the number of
1040 while (p && (p = next_property_key (p, &length)))
1042 // Skip to the end of the key
1045 p = next_property_value (p, &length);
1052 // Allocate an array of property value/key pairs.
1053 _Jv_Environment_Properties =
1054 (property_pair *) malloc (sizeof(property_pair)
1055 * (property_count + 1));
1057 // Go through the properties again, initializing _Jv_Properties
1061 while (p && (p = next_property_key (p, &length)))
1063 _Jv_Environment_Properties[property_count].key = p;
1064 _Jv_Environment_Properties[property_count].key_length = length;
1066 // Skip to the end of the key
1069 p = next_property_value (p, &length);
1071 _Jv_Environment_Properties[property_count].value = p;
1072 _Jv_Environment_Properties[property_count].value_length = length;
1079 memset ((void *) &_Jv_Environment_Properties[property_count],
1080 0, sizeof (property_pair));
1082 // Null terminate the strings.
1083 for (property_pair *prop = &_Jv_Environment_Properties[0];
1087 prop->key[prop->key_length] = 0;
1088 prop->value[prop->value_length] = 0;
1091 #endif // DISABLE_GETENV_PROPERTIES
1095 _Jv_Utf8Const *void_signature;
1096 _Jv_Utf8Const *clinit_name;
1097 _Jv_Utf8Const *init_name;
1098 _Jv_Utf8Const *finit_name;
1100 bool runtimeInitialized = false;
1102 // When true, print debugging information about class loading.
1103 bool verbose_class_flag;
1105 // When true, enable the bytecode verifier and BC-ABI type verification.
1106 bool verifyClasses = true;
1108 // Thread stack size specified by the -Xss runtime argument.
1109 size_t stack_size = 0;
1112 // We accept all non-standard options accepted by Sun's java command,
1113 // for compatibility with existing application launch scripts.
1115 parse_x_arg (char* option_string)
1117 if (strlen (option_string) <= 0)
1120 if (! strcmp (option_string, "int"))
1122 // FIXME: this should cause the vm to never load shared objects
1124 else if (! strcmp (option_string, "mixed"))
1126 // FIXME: allow interpreted and native code
1128 else if (! strcmp (option_string, "batch"))
1130 // FIXME: disable background JIT'ing
1132 else if (! strcmp (option_string, "debug"))
1134 // FIXME: add JDWP/JVMDI support
1136 else if (! strncmp (option_string, "bootclasspath:", 14))
1138 // FIXME: add a parse_bootclasspath_arg function
1140 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1143 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1146 else if (! strcmp (option_string, "check:jni"))
1148 // FIXME: enable strict JNI checking
1150 else if (! strcmp (option_string, "future"))
1152 // FIXME: enable strict class file format checks
1154 else if (! strcmp (option_string, "noclassgc"))
1156 // FIXME: disable garbage collection for classes
1158 else if (! strcmp (option_string, "incgc"))
1160 // FIXME: incremental garbage collection
1162 else if (! strncmp (option_string, "loggc:", 6))
1164 if (option_string[6] == '\0')
1167 "libgcj: filename argument expected for loggc option\n");
1170 // FIXME: set gc logging filename
1172 else if (! strncmp (option_string, "ms", 2))
1174 // FIXME: ignore this option until PR 20699 is fixed.
1175 // _Jv_SetInitialHeapSize (option_string + 2);
1177 else if (! strncmp (option_string, "mx", 2))
1178 _Jv_SetMaximumHeapSize (option_string + 2);
1179 else if (! strcmp (option_string, "prof"))
1181 // FIXME: enable profiling of program running in vm
1183 else if (! strncmp (option_string, "runhprof:", 9))
1185 // FIXME: enable specific type of vm profiling. add a
1186 // parse_runhprof_arg function
1188 else if (! strcmp (option_string, "rs"))
1190 // FIXME: reduced system signal usage. disable thread dumps,
1191 // only terminate in response to user-initiated calls,
1192 // e.g. System.exit()
1194 else if (! strncmp (option_string, "ss", 2))
1196 _Jv_SetStackSize (option_string + 2);
1198 else if (! strcmp (option_string, "X:+UseAltSigs"))
1200 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1202 else if (! strcmp (option_string, "share:off"))
1204 // FIXME: don't share class data
1206 else if (! strcmp (option_string, "share:auto"))
1208 // FIXME: share class data where possible
1210 else if (! strcmp (option_string, "share:on"))
1212 // FIXME: fail if impossible to share class data
1219 parse_verbose_args (char* option_string,
1220 bool ignore_unrecognized)
1222 size_t len = sizeof ("-verbose") - 1;
1224 if (strlen (option_string) < len)
1227 if (option_string[len] == ':'
1228 && option_string[len + 1] != '\0')
1230 char* verbose_args = option_string + len + 1;
1234 if (! strncmp (verbose_args,
1235 "gc", sizeof ("gc") - 1))
1237 if (verbose_args[sizeof ("gc") - 1] == '\0'
1238 || verbose_args[sizeof ("gc") - 1] == ',')
1240 // FIXME: we should add functions to boehm-gc that
1241 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1242 // GC_print_back_height.
1243 verbose_args += sizeof ("gc") - 1;
1248 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1253 else if (! strncmp (verbose_args,
1255 sizeof ("class") - 1))
1257 if (verbose_args[sizeof ("class") - 1] == '\0'
1258 || verbose_args[sizeof ("class") - 1] == ',')
1260 gcj::verbose_class_flag = true;
1261 verbose_args += sizeof ("class") - 1;
1264 goto verbose_arg_err;
1266 else if (! strncmp (verbose_args, "jni",
1267 sizeof ("jni") - 1))
1269 if (verbose_args[sizeof ("jni") - 1] == '\0'
1270 || verbose_args[sizeof ("jni") - 1] == ',')
1272 // FIXME: enable JNI messages.
1273 verbose_args += sizeof ("jni") - 1;
1276 goto verbose_arg_err;
1278 else if (ignore_unrecognized
1279 && verbose_args[0] == 'X')
1281 // ignore unrecognized non-standard verbose option
1282 while (verbose_args[0] != '\0'
1283 && verbose_args[0] != ',')
1286 else if (verbose_args[0] == ',')
1291 goto verbose_arg_err;
1293 if (verbose_args[0] == ',')
1296 while (verbose_args[0] != '\0');
1298 else if (option_string[len] == 'g'
1299 && option_string[len + 1] == 'c'
1300 && option_string[len + 2] == '\0')
1302 // FIXME: we should add functions to boehm-gc that
1303 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1304 // GC_print_back_height.
1307 else if (option_string[len] == '\0')
1309 gcj::verbose_class_flag = true;
1314 // unrecognized option beginning with -verbose
1321 parse_init_args (JvVMInitArgs* vm_args)
1323 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1324 // re-allocated dynamically.
1325 if (_Jv_Compiler_Properties)
1327 const char** props = _Jv_Compiler_Properties;
1328 _Jv_Compiler_Properties = NULL;
1330 for (int i = 0; props[i]; i++)
1332 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1333 (_Jv_Compiler_Properties,
1334 (_Jv_Properties_Count + 1) * sizeof (const char*));
1335 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1339 if (vm_args == NULL)
1342 for (int i = 0; i < vm_args->nOptions; ++i)
1344 char* option_string = vm_args->options[i].optionString;
1345 if (! strcmp (option_string, "vfprintf")
1346 || ! strcmp (option_string, "exit")
1347 || ! strcmp (option_string, "abort"))
1349 // FIXME: we are required to recognize these, but for
1350 // now we don't handle them in any way.
1353 else if (! strncmp (option_string,
1354 "-verbose", sizeof ("-verbose") - 1))
1356 jint result = parse_verbose_args (option_string,
1357 vm_args->ignoreUnrecognized);
1361 else if (! strncmp (option_string, "-D", 2))
1363 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1364 (_Jv_Compiler_Properties,
1365 (_Jv_Properties_Count + 1) * sizeof (char*));
1367 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1368 strdup (option_string + 2);
1372 else if (vm_args->ignoreUnrecognized)
1374 if (option_string[0] == '_')
1375 parse_x_arg (option_string + 1);
1376 else if (! strncmp (option_string, "-X", 2))
1377 parse_x_arg (option_string + 2);
1381 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1386 goto unknown_option;
1392 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1394 using namespace gcj;
1396 if (runtimeInitialized)
1399 runtimeInitialized = true;
1401 jint result = parse_init_args (vm_args);
1405 PROCESS_GCJ_PROPERTIES;
1407 /* Threads must be initialized before the GC, so that it inherits the
1411 _Jv_InitializeSyncMutex ();
1414 _Jv_InitInterpreter ();
1425 /* Initialize Utf8 constants declared in jvm.h. */
1426 void_signature = _Jv_makeUtf8Const ("()V", 3);
1427 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1428 init_name = _Jv_makeUtf8Const ("<init>", 6);
1429 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1431 /* Initialize built-in classes to represent primitive TYPEs. */
1432 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1433 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1434 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1435 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1436 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1437 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1438 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1439 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1440 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1442 // Turn stack trace generation off while creating exception objects.
1443 _Jv_InitClass (&java::lang::VMThrowable::class$);
1444 java::lang::VMThrowable::trace_enabled = 0;
1446 // We have to initialize this fairly early, to avoid circular class
1447 // initialization. In particular we want to start the
1448 // initialization of ClassLoader before we start the initialization
1449 // of VMClassLoader.
1450 _Jv_InitClass (&java::lang::ClassLoader::class$);
1452 // Set up the system class loader and the bootstrap class loader.
1453 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1454 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1456 _Jv_RegisterBootstrapPackages();
1458 no_memory = new java::lang::OutOfMemoryError;
1460 java::lang::VMThrowable::trace_enabled = 1;
1463 LTDL_SET_PRELOADED_SYMBOLS ();
1466 _Jv_platform_initialize ();
1470 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1472 // Start the GC finalizer thread. A VirtualMachineError can be
1473 // thrown by the runtime if, say, threads aren't available.
1476 using namespace gnu::gcj::runtime;
1477 FinalizerThread *ft = new FinalizerThread ();
1480 catch (java::lang::VirtualMachineError *ignore)
1488 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1489 const char **argv, bool is_jar)
1491 #ifndef DISABLE_MAIN_ARGS
1492 _Jv_SetArgs (argc, argv);
1495 java::lang::Runtime *runtime = NULL;
1499 if (_Jv_CreateJavaVM (vm_args) < 0)
1501 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1505 // Get the Runtime here. We want to initialize it before searching
1506 // for `main'; that way it will be set up if `main' is a JNI method.
1507 runtime = java::lang::Runtime::getRuntime ();
1509 #ifdef DISABLE_MAIN_ARGS
1510 arg_vec = JvConvertArgv (0, 0);
1512 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1515 using namespace gnu::java::lang;
1517 main_thread = new MainThread (klass, arg_vec);
1519 main_thread = new MainThread (JvNewStringLatin1 (name),
1522 catch (java::lang::Throwable *t)
1524 java::lang::System::err->println (JvNewStringLatin1
1525 ("Exception during runtime initialization"));
1526 t->printStackTrace();
1529 // In case the runtime creation failed.
1533 _Jv_AttachCurrentThread (main_thread);
1534 _Jv_ThreadRun (main_thread);
1536 // If we got here then something went wrong, as MainThread is not
1537 // supposed to terminate.
1542 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1545 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1549 JvRunMain (jclass klass, int argc, const char **argv)
1551 _Jv_RunMain (klass, NULL, argc, argv, false);
1556 // Parse a string and return a heap size.
1558 parse_memory_size (const char *spec)
1561 unsigned long val = strtoul (spec, &end, 10);
1562 if (*end == 'k' || *end == 'K')
1564 else if (*end == 'm' || *end == 'M')
1566 return (size_t) val;
1569 // Set the initial heap size. This might be ignored by the GC layer.
1570 // This must be called before _Jv_RunMain.
1572 _Jv_SetInitialHeapSize (const char *arg)
1574 size_t size = parse_memory_size (arg);
1575 _Jv_GCSetInitialHeapSize (size);
1578 // Set the maximum heap size. This might be ignored by the GC layer.
1579 // This must be called before _Jv_RunMain.
1581 _Jv_SetMaximumHeapSize (const char *arg)
1583 size_t size = parse_memory_size (arg);
1584 _Jv_GCSetMaximumHeapSize (size);
1588 _Jv_SetStackSize (const char *arg)
1590 size_t size = parse_memory_size (arg);
1591 gcj::stack_size = size;
1595 _Jv_Malloc (jsize size)
1597 if (__builtin_expect (size == 0, false))
1599 void *ptr = malloc ((size_t) size);
1600 if (__builtin_expect (ptr == NULL, false))
1606 _Jv_Realloc (void *ptr, jsize size)
1608 if (__builtin_expect (size == 0, false))
1610 ptr = realloc (ptr, (size_t) size);
1611 if (__builtin_expect (ptr == NULL, false))
1617 _Jv_MallocUnchecked (jsize size)
1619 if (__builtin_expect (size == 0, false))
1621 return malloc ((size_t) size);
1625 _Jv_Free (void* ptr)
1632 // In theory, these routines can be #ifdef'd away on machines which
1633 // support divide overflow signals. However, we never know if some
1634 // code might have been compiled with "-fuse-divide-subroutine", so we
1635 // always include them in libgcj.
1638 _Jv_divI (jint dividend, jint divisor)
1640 if (__builtin_expect (divisor == 0, false))
1642 java::lang::ArithmeticException *arithexception
1643 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1644 throw arithexception;
1647 if (dividend == (jint) 0x80000000L && divisor == -1)
1650 return dividend / divisor;
1654 _Jv_remI (jint dividend, jint divisor)
1656 if (__builtin_expect (divisor == 0, false))
1658 java::lang::ArithmeticException *arithexception
1659 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1660 throw arithexception;
1663 if (dividend == (jint) 0x80000000L && divisor == -1)
1666 return dividend % divisor;
1670 _Jv_divJ (jlong dividend, jlong divisor)
1672 if (__builtin_expect (divisor == 0, false))
1674 java::lang::ArithmeticException *arithexception
1675 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1676 throw arithexception;
1679 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1682 return dividend / divisor;
1686 _Jv_remJ (jlong dividend, jlong divisor)
1688 if (__builtin_expect (divisor == 0, false))
1690 java::lang::ArithmeticException *arithexception
1691 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1692 throw arithexception;
1695 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1698 return dividend % divisor;
1703 // Return true if SELF_KLASS can access a field or method in
1704 // OTHER_KLASS. The field or method's access flags are specified in
1707 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1709 using namespace java::lang::reflect;
1710 return ((self_klass == other_klass)
1711 || ((flags & Modifier::PUBLIC) != 0)
1712 || (((flags & Modifier::PROTECTED) != 0)
1713 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1714 || (((flags & Modifier::PRIVATE) == 0)
1715 && _Jv_ClassNameSamePackage (self_klass->name,
1716 other_klass->name)));