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/VMClassLoader.h>
60 #include <java/lang/reflect/Modifier.h>
61 #include <java/io/PrintStream.h>
62 #include <java/lang/UnsatisfiedLinkError.h>
63 #include <java/lang/VirtualMachineError.h>
64 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
65 #include <gnu/gcj/runtime/FinalizerThread.h>
66 #include <execution.h>
67 #include <gnu/classpath/jdwp/Jdwp.h>
68 #include <gnu/classpath/jdwp/VMVirtualMachine.h>
69 #include <gnu/classpath/jdwp/event/VmDeathEvent.h>
70 #include <gnu/classpath/jdwp/event/VmInitEvent.h>
71 #include <gnu/java/lang/MainThread.h>
77 // Execution engine for compiled code.
78 _Jv_CompiledEngine _Jv_soleCompiledEngine;
80 // Execution engine for code compiled with -findirect-classes
81 _Jv_IndirectCompiledEngine _Jv_soleIndirectCompiledEngine;
83 // We allocate a single OutOfMemoryError exception which we keep
84 // around for use if we run out of memory.
85 static java::lang::OutOfMemoryError *no_memory;
87 // Number of bytes in largest array object we create. This could be
88 // increased to the largest size_t value, so long as the appropriate
89 // functions are changed to take a size_t argument instead of jint.
90 #define MAX_OBJECT_SIZE ((1<<31) - 1)
92 // Properties set at compile time.
93 const char **_Jv_Compiler_Properties = NULL;
94 int _Jv_Properties_Count = 0;
96 #ifndef DISABLE_GETENV_PROPERTIES
97 // Property key/value pairs.
98 property_pair *_Jv_Environment_Properties;
101 // Stash the argv pointer to benefit native libraries that need it.
102 const char **_Jv_argv;
106 static bool remoteDebug = false;
107 static char *jdwpOptions = "";
113 // _Jv_argc is 0 if not explicitly initialized.
118 _Jv_GetSafeArg (int index)
120 if (index >=0 && index < _Jv_GetNbArgs ())
121 return _Jv_argv[index];
127 _Jv_SetArgs (int argc, const char **argv)
134 // Pointer to JVMPI notification functions.
135 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
136 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
137 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
141 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
142 /* Unblock a signal. Unless we do this, the signal may only be sent
145 unblock_signal (int signum __attribute__ ((__unused__)))
147 #ifdef _POSIX_VERSION
151 sigaddset (&sigs, signum);
152 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
158 SIGNAL_HANDLER (catch_segv)
160 unblock_signal (SIGSEGV);
161 MAKE_THROW_FRAME (nullp);
162 java::lang::NullPointerException *nullp
163 = new java::lang::NullPointerException;
169 SIGNAL_HANDLER (catch_fpe)
171 unblock_signal (SIGFPE);
172 #ifdef HANDLE_DIVIDE_OVERFLOW
173 HANDLE_DIVIDE_OVERFLOW;
175 MAKE_THROW_FRAME (arithexception);
177 java::lang::ArithmeticException *arithexception
178 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
179 throw arithexception;
185 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
188 const _Jv_ushort *aptr, *bptr;
191 if (a->hash != b->hash)
194 if (b->length != len)
196 aptr = (const _Jv_ushort *)a->data;
197 bptr = (const _Jv_ushort *)b->data;
198 len = (len + 1) >> 1;
200 if (*aptr++ != *bptr++)
205 /* True iff A is equal to STR.
206 HASH is STR->hashCode().
210 _Jv_equal (Utf8Const* a, jstring str, jint hash)
212 if (a->hash != (_Jv_ushort) hash)
214 jint len = str->length();
216 jchar *sptr = _Jv_GetStringChars (str);
217 unsigned char* ptr = (unsigned char*) a->data;
218 unsigned char* limit = ptr + a->length;
221 int ch = UTF8_GET (ptr, limit);
230 /* Like _Jv_equal, but stop after N characters. */
232 _Jv_equaln (Utf8Const *a, jstring str, jint n)
234 jint len = str->length();
236 jchar *sptr = _Jv_GetStringChars (str);
237 unsigned char* ptr = (unsigned char*) a->data;
238 unsigned char* limit = ptr + a->length;
239 for (; n-- > 0; i++, sptr++)
241 int ch = UTF8_GET (ptr, limit);
250 // Determines whether the given Utf8Const object contains
251 // a type which is primitive or some derived form of it, eg.
252 // an array or multi-dimensional array variant.
254 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
256 unsigned char *aptr = (unsigned char *) a->data;
257 unsigned char *alimit = aptr + a->length;
258 int ac = UTF8_GET(aptr, alimit);
260 // Skips any leading array marks.
262 ac = UTF8_GET(aptr, alimit);
264 // There should not be another character. This implies that
265 // the type name is only one character long.
266 if (UTF8_GET(aptr, alimit) == -1)
285 // Find out whether two _Jv_Utf8Const candidates contain the same
287 // The method is written to handle the different formats of classnames.
288 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
289 // "java.lang.Class" will be seen as equal.
290 // Warning: This function is not smart enough to declare "Z" and "boolean"
291 // and similar cases as equal (and is not meant to be used this way)!
293 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
295 // If the class name's length differs by two characters
296 // it is possible that we have candidates which are given
297 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
298 switch (a->length - b->length)
308 unsigned char *aptr = (unsigned char *) a->data;
309 unsigned char *alimit = aptr + a->length;
310 unsigned char *bptr = (unsigned char *) b->data;
311 unsigned char *blimit = bptr + b->length;
313 if (alimit[-1] == ';')
316 if (blimit[-1] == ';')
319 int ac = UTF8_GET(aptr, alimit);
320 int bc = UTF8_GET(bptr, blimit);
322 // Checks whether both strings have the same amount of leading [ characters.
327 ac = UTF8_GET(aptr, alimit);
328 bc = UTF8_GET(bptr, blimit);
335 // Skips leading L character.
337 ac = UTF8_GET(aptr, alimit);
340 bc = UTF8_GET(bptr, blimit);
342 // Compares the remaining characters.
343 while (ac != -1 && bc != -1)
345 // Replaces package separating dots with slashes.
352 // Now classnames differ if there is at least one non-matching
357 ac = UTF8_GET(aptr, alimit);
358 bc = UTF8_GET(bptr, blimit);
364 /* Count the number of Unicode chars encoded in a given Ut8 string. */
366 _Jv_strLengthUtf8(const char* str, int len)
369 unsigned char* limit;
372 ptr = (unsigned char*) str;
375 for (; ptr < limit; str_length++)
377 if (UTF8_GET (ptr, limit) < 0)
383 /* Calculate a hash value for a string encoded in Utf8 format.
384 * This returns the same hash value as specified or java.lang.String.hashCode.
387 _Jv_hashUtf8String (const char* str, int len)
389 unsigned char* ptr = (unsigned char*) str;
390 unsigned char* limit = ptr + len;
395 int ch = UTF8_GET (ptr, limit);
396 /* Updated specification from
397 http://www.javasoft.com/docs/books/jls/clarify.html. */
398 hash = (31 * hash) + ch;
404 _Jv_Utf8Const::init(const char *s, int len)
406 ::memcpy (data, s, len);
409 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
413 _Jv_makeUtf8Const (const char* s, int len)
418 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
424 _Jv_makeUtf8Const (jstring string)
426 jint hash = string->hashCode ();
427 jint len = _Jv_GetStringUTFLength (string);
429 Utf8Const* m = (Utf8Const*)
430 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
435 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
445 _Jv_Abort (const char *function, const char *file, int line,
449 _Jv_Abort (const char *, const char *, int, const char *message)
454 "libgcj failure: %s\n in function %s, file %s, line %d\n",
455 message, function, file, line);
457 fprintf (stderr, "libgcj failure: %s\n", message);
463 fail_on_finalization (jobject)
465 JvFail ("object was finalized");
469 _Jv_GCWatch (jobject obj)
471 _Jv_RegisterFinalizer (obj, fail_on_finalization);
475 _Jv_ThrowBadArrayIndex(jint bad_index)
477 throw new java::lang::ArrayIndexOutOfBoundsException
478 (java::lang::String::valueOf (bad_index));
482 _Jv_ThrowNullPointerException ()
484 throw new java::lang::NullPointerException;
487 // Resolve an entry in the constant pool and return the target
490 _Jv_ResolvePoolEntry (jclass this_class, jint index)
492 _Jv_Constants *pool = &this_class->constants;
494 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
495 return pool->data[index].field->u.addr;
497 JvSynchronize sync (this_class);
498 return (_Jv_Linker::resolve_pool_entry (this_class, index))
503 // Explicitly throw a no memory exception.
504 // The collector calls this when it encounters an out-of-memory condition.
505 void _Jv_ThrowNoMemory()
511 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
512 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
513 jvmpi_notify_alloc(klass,size,obj);
515 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
517 // Service JVMPI allocation request.
520 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
522 event.u.obj_alloc.arena_id = 0;
523 event.u.obj_alloc.class_id = (jobjectID) klass;
524 event.u.obj_alloc.is_array = 0;
525 event.u.obj_alloc.size = size;
526 event.u.obj_alloc.obj_id = (jobjectID) obj;
528 // FIXME: This doesn't look right for the Boehm GC. A GC may
529 // already be in progress. _Jv_DisableGC () doesn't wait for it.
530 // More importantly, I don't see the need for disabling GC, since we
531 // blatantly have a pointer to obj on our stack, ensuring that the
532 // object can't be collected. Even for a nonconservative collector,
533 // it appears to me that this must be true, since we are about to
534 // return obj. Isn't this whole approach way too intrusive for
535 // a useful profiling interface? - HB
537 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
540 #else /* !ENABLE_JVMPI */
541 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
544 // Allocate a new object of class KLASS.
545 // First a version that assumes that we have no finalizer, and that
546 // the class is already initialized.
547 // If we know that JVMPI is disabled, this can be replaced by a direct call
548 // to the allocator for the appropriate GC.
550 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
552 jint size = klass->size ();
553 jobject obj = (jobject) _Jv_AllocObj (size, klass);
554 JVMPI_NOTIFY_ALLOC (klass, size, obj);
558 // And now a version that initializes if necessary.
560 _Jv_AllocObjectNoFinalizer (jclass klass)
562 if (_Jv_IsPhantomClass(klass) )
563 throw new java::lang::NoClassDefFoundError(klass->getName());
565 _Jv_InitClass (klass);
566 jint size = klass->size ();
567 jobject obj = (jobject) _Jv_AllocObj (size, klass);
568 JVMPI_NOTIFY_ALLOC (klass, size, obj);
572 // And now the general version that registers a finalizer if necessary.
574 _Jv_AllocObject (jclass klass)
576 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
578 // We assume that the compiler only generates calls to this routine
579 // if there really is an interesting finalizer.
580 // Unfortunately, we still have to the dynamic test, since there may
581 // be cni calls to this routine.
582 // Note that on IA64 get_finalizer() returns the starting address of the
583 // function, not a function pointer. Thus this still works.
584 if (klass->vtable->get_finalizer ()
585 != java::lang::Object::class$.vtable->get_finalizer ())
586 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
590 // Allocate a String, including variable length storage.
592 _Jv_AllocString(jsize len)
594 using namespace java::lang;
596 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
598 // We assert that for strings allocated this way, the data field
599 // will always point to the object itself. Thus there is no reason
600 // for the garbage collector to scan any of it.
601 // Furthermore, we're about to overwrite the string data, so
602 // initialization of the object is not an issue.
604 // String needs no initialization, and there is no finalizer, so
605 // we can go directly to the collector's allocator interface.
606 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
609 obj->boffset = sizeof(java::lang::String);
611 obj->cachedHashCode = 0;
613 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
618 // A version of the above that assumes the object contains no pointers,
619 // and requires no finalization. This can't happen if we need pointers
621 #ifdef JV_HASH_SYNCHRONIZATION
623 _Jv_AllocPtrFreeObject (jclass klass)
625 _Jv_InitClass (klass);
626 jint size = klass->size ();
628 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
630 JVMPI_NOTIFY_ALLOC (klass, size, obj);
634 #endif /* JV_HASH_SYNCHRONIZATION */
637 // Allocate a new array of Java objects. Each object is of type
638 // `elementClass'. `init' is used to initialize each slot in the
641 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
643 // Creating an array of an unresolved type is impossible. So we throw
644 // the NoClassDefFoundError.
645 if ( _Jv_IsPhantomClass(elementClass) )
646 throw new java::lang::NoClassDefFoundError(elementClass->getName());
648 if (__builtin_expect (count < 0, false))
649 throw new java::lang::NegativeArraySizeException;
651 JvAssert (! elementClass->isPrimitive ());
653 // Ensure that elements pointer is properly aligned.
654 jobjectArray obj = NULL;
655 size_t size = (size_t) elements (obj);
656 // Check for overflow.
657 if (__builtin_expect ((size_t) count >
658 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
661 size += count * sizeof (jobject);
663 jclass klass = _Jv_GetArrayClass (elementClass,
664 elementClass->getClassLoaderInternal());
666 obj = (jobjectArray) _Jv_AllocArray (size, klass);
668 jsize *lp = const_cast<jsize *> (&obj->length);
670 // We know the allocator returns zeroed memory. So don't bother
674 jobject *ptr = elements(obj);
681 // Allocate a new array of primitives. ELTYPE is the type of the
682 // element, COUNT is the size of the array.
684 _Jv_NewPrimArray (jclass eltype, jint count)
686 int elsize = eltype->size();
687 if (__builtin_expect (count < 0, false))
688 throw new java::lang::NegativeArraySizeException;
690 JvAssert (eltype->isPrimitive ());
691 jobject dummy = NULL;
692 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
694 // Check for overflow.
695 if (__builtin_expect ((size_t) count >
696 (MAX_OBJECT_SIZE - size) / elsize, false))
699 jclass klass = _Jv_GetArrayClass (eltype, 0);
701 # ifdef JV_HASH_SYNCHRONIZATION
702 // Since the vtable is always statically allocated,
703 // these are completely pointerfree! Make sure the GC doesn't touch them.
705 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
706 memset((char *)arr + size, 0, elsize * count);
708 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
709 // Note that we assume we are given zeroed memory by the allocator.
712 jsize *lp = const_cast<jsize *> (&arr->length);
719 _Jv_NewArray (jint type, jint size)
723 case 4: return JvNewBooleanArray (size);
724 case 5: return JvNewCharArray (size);
725 case 6: return JvNewFloatArray (size);
726 case 7: return JvNewDoubleArray (size);
727 case 8: return JvNewByteArray (size);
728 case 9: return JvNewShortArray (size);
729 case 10: return JvNewIntArray (size);
730 case 11: return JvNewLongArray (size);
732 throw new java::lang::InternalError
733 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
736 // Allocate a possibly multi-dimensional array but don't check that
737 // any array length is <0.
739 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
741 JvAssert (type->isArray());
742 jclass element_type = type->getComponentType();
744 if (element_type->isPrimitive())
745 result = _Jv_NewPrimArray (element_type, sizes[0]);
747 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
751 JvAssert (! element_type->isPrimitive());
752 JvAssert (element_type->isArray());
753 jobject *contents = elements ((jobjectArray) result);
754 for (int i = 0; i < sizes[0]; ++i)
755 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
763 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
765 for (int i = 0; i < dimensions; ++i)
767 throw new java::lang::NegativeArraySizeException;
769 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
773 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
775 // Creating an array of an unresolved type is impossible. So we throw
776 // the NoClassDefFoundError.
777 if (_Jv_IsPhantomClass(array_type))
778 throw new java::lang::NoClassDefFoundError(array_type->getName());
781 jint sizes[dimensions];
782 va_start (args, dimensions);
783 for (int i = 0; i < dimensions; ++i)
785 jint size = va_arg (args, jint);
787 throw new java::lang::NegativeArraySizeException;
792 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
797 // Ensure 8-byte alignment, for hash synchronization.
798 #define DECLARE_PRIM_TYPE(NAME) \
799 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
801 DECLARE_PRIM_TYPE(byte)
802 DECLARE_PRIM_TYPE(short)
803 DECLARE_PRIM_TYPE(int)
804 DECLARE_PRIM_TYPE(long)
805 DECLARE_PRIM_TYPE(boolean)
806 DECLARE_PRIM_TYPE(char)
807 DECLARE_PRIM_TYPE(float)
808 DECLARE_PRIM_TYPE(double)
809 DECLARE_PRIM_TYPE(void)
812 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
814 using namespace java::lang::reflect;
816 // We must set the vtable for the class; the Java constructor
818 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
820 // Initialize the fields we care about. We do this in the same
821 // order they are declared in Class.h.
822 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
823 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
824 cl->method_count = sig;
825 cl->size_in_bytes = len;
826 cl->vtable = JV_PRIMITIVE_VTABLE;
827 cl->state = JV_STATE_DONE;
832 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
835 // First count arrays.
843 jclass result = NULL;
847 result = JvPrimClass (byte);
850 result = JvPrimClass (short);
853 result = JvPrimClass (int);
856 result = JvPrimClass (long);
859 result = JvPrimClass (boolean);
862 result = JvPrimClass (char);
865 result = JvPrimClass (float);
868 result = JvPrimClass (double);
871 result = JvPrimClass (void);
876 while (*sig && *sig != ';')
878 // Do nothing if signature appears to be malformed.
881 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
882 result = _Jv_FindClass (name, loader);
887 // Do nothing -- bad signature.
893 // Not really the "end", but the last valid character that we
902 while (array_count-- > 0)
903 result = _Jv_GetArrayClass (result, loader);
909 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
916 klass = _Jv_FindClassFromSignature(sig, loader, endp);
918 catch (java::lang::NoClassDefFoundError *ncdfe)
922 catch (java::lang::ClassNotFoundException *cnfe)
931 JvConvertArgv (int argc, const char **argv)
935 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
936 jobject *ptr = elements(ar);
937 jbyteArray bytes = NULL;
938 for (int i = 0; i < argc; i++)
940 const char *arg = argv[i];
941 int len = strlen (arg);
942 if (bytes == NULL || bytes->length < len)
943 bytes = JvNewByteArray (len);
944 jbyte *bytePtr = elements (bytes);
945 // We assume jbyte == char.
946 memcpy (bytePtr, arg, len);
948 // Now convert using the default encoding.
949 *ptr++ = new java::lang::String (bytes, 0, len);
951 return (JArray<jstring>*) ar;
954 // FIXME: These variables are static so that they will be
955 // automatically scanned by the Boehm collector. This is needed
956 // because with qthreads the collector won't scan the initial stack --
957 // it will only scan the qthreads stacks.
959 // Command line arguments.
960 static JArray<jstring> *arg_vec;
962 // The primary thread.
963 static java::lang::Thread *main_thread;
965 #ifndef DISABLE_GETENV_PROPERTIES
968 next_property_key (char *s, size_t *length)
974 // Skip over whitespace
978 // If we've reached the end, return NULL. Also return NULL if for
979 // some reason we've come across a malformed property string.
985 // Determine the length of the property key.
1003 next_property_value (char *s, size_t *length)
1009 while (isspace (*s))
1016 while (isspace (*s))
1019 // Determine the length of the property value.
1038 process_gcj_properties ()
1040 char *props = getenv("GCJ_PROPERTIES");
1045 // Later on we will write \0s into this string. It is simplest to
1046 // just duplicate it here.
1047 props = strdup (props);
1051 size_t property_count = 0;
1053 // Whip through props quickly in order to count the number of
1055 while (p && (p = next_property_key (p, &length)))
1057 // Skip to the end of the key
1060 p = next_property_value (p, &length);
1067 // Allocate an array of property value/key pairs.
1068 _Jv_Environment_Properties =
1069 (property_pair *) malloc (sizeof(property_pair)
1070 * (property_count + 1));
1072 // Go through the properties again, initializing _Jv_Properties
1076 while (p && (p = next_property_key (p, &length)))
1078 _Jv_Environment_Properties[property_count].key = p;
1079 _Jv_Environment_Properties[property_count].key_length = length;
1081 // Skip to the end of the key
1084 p = next_property_value (p, &length);
1086 _Jv_Environment_Properties[property_count].value = p;
1087 _Jv_Environment_Properties[property_count].value_length = length;
1094 memset ((void *) &_Jv_Environment_Properties[property_count],
1095 0, sizeof (property_pair));
1097 // Null terminate the strings.
1098 for (property_pair *prop = &_Jv_Environment_Properties[0];
1102 prop->key[prop->key_length] = 0;
1103 prop->value[prop->value_length] = 0;
1106 #endif // DISABLE_GETENV_PROPERTIES
1110 _Jv_Utf8Const *void_signature;
1111 _Jv_Utf8Const *clinit_name;
1112 _Jv_Utf8Const *init_name;
1113 _Jv_Utf8Const *finit_name;
1115 bool runtimeInitialized = false;
1117 // When true, print debugging information about class loading.
1118 bool verbose_class_flag;
1120 // When true, enable the bytecode verifier and BC-ABI type verification.
1121 bool verifyClasses = true;
1123 // Thread stack size specified by the -Xss runtime argument.
1124 size_t stack_size = 0;
1127 // We accept all non-standard options accepted by Sun's java command,
1128 // for compatibility with existing application launch scripts.
1130 parse_x_arg (char* option_string)
1132 if (strlen (option_string) <= 0)
1135 if (! strcmp (option_string, "int"))
1137 // FIXME: this should cause the vm to never load shared objects
1139 else if (! strcmp (option_string, "mixed"))
1141 // FIXME: allow interpreted and native code
1143 else if (! strcmp (option_string, "batch"))
1145 // FIXME: disable background JIT'ing
1147 else if (! strcmp (option_string, "debug"))
1151 else if (! strncmp (option_string, "runjdwp:", 8))
1153 if (strlen (option_string) > 8)
1154 jdwpOptions = &option_string[8];
1158 "libgcj: argument required for JDWP options");
1162 else if (! strncmp (option_string, "bootclasspath:", 14))
1164 // FIXME: add a parse_bootclasspath_arg function
1166 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1169 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1172 else if (! strcmp (option_string, "check:jni"))
1174 // FIXME: enable strict JNI checking
1176 else if (! strcmp (option_string, "future"))
1178 // FIXME: enable strict class file format checks
1180 else if (! strcmp (option_string, "noclassgc"))
1182 // FIXME: disable garbage collection for classes
1184 else if (! strcmp (option_string, "incgc"))
1186 // FIXME: incremental garbage collection
1188 else if (! strncmp (option_string, "loggc:", 6))
1190 if (option_string[6] == '\0')
1193 "libgcj: filename argument expected for loggc option\n");
1196 // FIXME: set gc logging filename
1198 else if (! strncmp (option_string, "ms", 2))
1200 // FIXME: ignore this option until PR 20699 is fixed.
1201 // _Jv_SetInitialHeapSize (option_string + 2);
1203 else if (! strncmp (option_string, "mx", 2))
1204 _Jv_SetMaximumHeapSize (option_string + 2);
1205 else if (! strcmp (option_string, "prof"))
1207 // FIXME: enable profiling of program running in vm
1209 else if (! strncmp (option_string, "runhprof:", 9))
1211 // FIXME: enable specific type of vm profiling. add a
1212 // parse_runhprof_arg function
1214 else if (! strcmp (option_string, "rs"))
1216 // FIXME: reduced system signal usage. disable thread dumps,
1217 // only terminate in response to user-initiated calls,
1218 // e.g. System.exit()
1220 else if (! strncmp (option_string, "ss", 2))
1222 _Jv_SetStackSize (option_string + 2);
1224 else if (! strcmp (option_string, "X:+UseAltSigs"))
1226 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1228 else if (! strcmp (option_string, "share:off"))
1230 // FIXME: don't share class data
1232 else if (! strcmp (option_string, "share:auto"))
1234 // FIXME: share class data where possible
1236 else if (! strcmp (option_string, "share:on"))
1238 // FIXME: fail if impossible to share class data
1245 parse_verbose_args (char* option_string,
1246 bool ignore_unrecognized)
1248 size_t len = sizeof ("-verbose") - 1;
1250 if (strlen (option_string) < len)
1253 if (option_string[len] == ':'
1254 && option_string[len + 1] != '\0')
1256 char* verbose_args = option_string + len + 1;
1260 if (! strncmp (verbose_args,
1261 "gc", sizeof ("gc") - 1))
1263 if (verbose_args[sizeof ("gc") - 1] == '\0'
1264 || verbose_args[sizeof ("gc") - 1] == ',')
1266 // FIXME: we should add functions to boehm-gc that
1267 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1268 // GC_print_back_height.
1269 verbose_args += sizeof ("gc") - 1;
1274 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1279 else if (! strncmp (verbose_args,
1281 sizeof ("class") - 1))
1283 if (verbose_args[sizeof ("class") - 1] == '\0'
1284 || verbose_args[sizeof ("class") - 1] == ',')
1286 gcj::verbose_class_flag = true;
1287 verbose_args += sizeof ("class") - 1;
1290 goto verbose_arg_err;
1292 else if (! strncmp (verbose_args, "jni",
1293 sizeof ("jni") - 1))
1295 if (verbose_args[sizeof ("jni") - 1] == '\0'
1296 || verbose_args[sizeof ("jni") - 1] == ',')
1298 // FIXME: enable JNI messages.
1299 verbose_args += sizeof ("jni") - 1;
1302 goto verbose_arg_err;
1304 else if (ignore_unrecognized
1305 && verbose_args[0] == 'X')
1307 // ignore unrecognized non-standard verbose option
1308 while (verbose_args[0] != '\0'
1309 && verbose_args[0] != ',')
1312 else if (verbose_args[0] == ',')
1317 goto verbose_arg_err;
1319 if (verbose_args[0] == ',')
1322 while (verbose_args[0] != '\0');
1324 else if (option_string[len] == 'g'
1325 && option_string[len + 1] == 'c'
1326 && option_string[len + 2] == '\0')
1328 // FIXME: we should add functions to boehm-gc that
1329 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1330 // GC_print_back_height.
1333 else if (option_string[len] == '\0')
1335 gcj::verbose_class_flag = true;
1340 // unrecognized option beginning with -verbose
1347 parse_init_args (JvVMInitArgs* vm_args)
1349 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1350 // re-allocated dynamically.
1351 if (_Jv_Compiler_Properties)
1353 const char** props = _Jv_Compiler_Properties;
1354 _Jv_Compiler_Properties = NULL;
1356 for (int i = 0; props[i]; i++)
1358 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1359 (_Jv_Compiler_Properties,
1360 (_Jv_Properties_Count + 1) * sizeof (const char*));
1361 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1365 if (vm_args == NULL)
1368 for (int i = 0; i < vm_args->nOptions; ++i)
1370 char* option_string = vm_args->options[i].optionString;
1371 if (! strcmp (option_string, "vfprintf")
1372 || ! strcmp (option_string, "exit")
1373 || ! strcmp (option_string, "abort"))
1375 // FIXME: we are required to recognize these, but for
1376 // now we don't handle them in any way.
1379 else if (! strncmp (option_string,
1380 "-verbose", sizeof ("-verbose") - 1))
1382 jint result = parse_verbose_args (option_string,
1383 vm_args->ignoreUnrecognized);
1387 else if (! strncmp (option_string, "-D", 2))
1389 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1390 (_Jv_Compiler_Properties,
1391 (_Jv_Properties_Count + 1) * sizeof (char*));
1393 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1394 strdup (option_string + 2);
1398 else if (vm_args->ignoreUnrecognized)
1400 if (option_string[0] == '_')
1401 parse_x_arg (option_string + 1);
1402 else if (! strncmp (option_string, "-X", 2))
1403 parse_x_arg (option_string + 2);
1407 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1412 goto unknown_option;
1418 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1420 using namespace gcj;
1422 if (runtimeInitialized)
1425 jint result = parse_init_args (vm_args);
1429 PROCESS_GCJ_PROPERTIES;
1431 /* Threads must be initialized before the GC, so that it inherits the
1435 _Jv_InitializeSyncMutex ();
1438 _Jv_InitInterpreter ();
1449 /* Initialize Utf8 constants declared in jvm.h. */
1450 void_signature = _Jv_makeUtf8Const ("()V", 3);
1451 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1452 init_name = _Jv_makeUtf8Const ("<init>", 6);
1453 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1455 /* Initialize built-in classes to represent primitive TYPEs. */
1456 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1457 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1458 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1459 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1460 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1461 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1462 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1463 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1464 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1466 // We have to initialize this fairly early, to avoid circular class
1467 // initialization. In particular we want to start the
1468 // initialization of ClassLoader before we start the initialization
1469 // of VMClassLoader.
1470 _Jv_InitClass (&java::lang::ClassLoader::class$);
1472 // Set up the system class loader and the bootstrap class loader.
1473 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1474 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1476 _Jv_RegisterBootstrapPackages();
1478 no_memory = new java::lang::OutOfMemoryError;
1481 LTDL_SET_PRELOADED_SYMBOLS ();
1484 _Jv_platform_initialize ();
1489 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1491 // Start the GC finalizer thread. A VirtualMachineError can be
1492 // thrown by the runtime if, say, threads aren't available.
1495 using namespace gnu::gcj::runtime;
1496 FinalizerThread *ft = new FinalizerThread ();
1499 catch (java::lang::VirtualMachineError *ignore)
1503 runtimeInitialized = true;
1509 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1510 const char **argv, bool is_jar)
1512 #ifndef DISABLE_MAIN_ARGS
1513 _Jv_SetArgs (argc, argv);
1516 java::lang::Runtime *runtime = NULL;
1520 if (_Jv_CreateJavaVM (vm_args) < 0)
1522 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1526 // Get the Runtime here. We want to initialize it before searching
1527 // for `main'; that way it will be set up if `main' is a JNI method.
1528 runtime = java::lang::Runtime::getRuntime ();
1530 #ifdef DISABLE_MAIN_ARGS
1531 arg_vec = JvConvertArgv (0, 0);
1533 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1536 using namespace gnu::java::lang;
1538 main_thread = new MainThread (klass, arg_vec);
1540 main_thread = new MainThread (JvNewStringUTF (name),
1542 _Jv_AttachCurrentThread (main_thread);
1547 using namespace gnu::classpath::jdwp;
1548 VMVirtualMachine::initialize ();
1549 Jdwp *jdwp = new Jdwp ();
1550 jdwp->setDaemon (true);
1551 jdwp->configure (JvNewStringLatin1 (jdwpOptions));
1554 // Wait for JDWP to initialize and start
1559 gnu::classpath::jdwp::event::VmInitEvent *event;
1560 event = new gnu::classpath::jdwp::event::VmInitEvent (main_thread);
1561 gnu::classpath::jdwp::Jdwp::notify (event);
1563 catch (java::lang::Throwable *t)
1565 java::lang::System::err->println (JvNewStringLatin1
1566 ("Exception during runtime initialization"));
1567 t->printStackTrace();
1569 java::lang::Runtime::exitNoChecksAccessor (1);
1570 // In case the runtime creation failed.
1574 _Jv_ThreadRun (main_thread);
1576 // Notify debugger of VM's death
1577 if (gnu::classpath::jdwp::Jdwp::isDebugging)
1579 using namespace gnu::classpath::jdwp;
1580 event::VmDeathEvent *event = new event::VmDeathEvent ();
1581 Jdwp::notify (event);
1584 // If we got here then something went wrong, as MainThread is not
1585 // supposed to terminate.
1590 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1593 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1597 JvRunMain (jclass klass, int argc, const char **argv)
1599 _Jv_RunMain (klass, NULL, argc, argv, false);
1604 // Parse a string and return a heap size.
1606 parse_memory_size (const char *spec)
1609 unsigned long val = strtoul (spec, &end, 10);
1610 if (*end == 'k' || *end == 'K')
1612 else if (*end == 'm' || *end == 'M')
1614 return (size_t) val;
1617 // Set the initial heap size. This might be ignored by the GC layer.
1618 // This must be called before _Jv_RunMain.
1620 _Jv_SetInitialHeapSize (const char *arg)
1622 size_t size = parse_memory_size (arg);
1623 _Jv_GCSetInitialHeapSize (size);
1626 // Set the maximum heap size. This might be ignored by the GC layer.
1627 // This must be called before _Jv_RunMain.
1629 _Jv_SetMaximumHeapSize (const char *arg)
1631 size_t size = parse_memory_size (arg);
1632 _Jv_GCSetMaximumHeapSize (size);
1636 _Jv_SetStackSize (const char *arg)
1638 size_t size = parse_memory_size (arg);
1639 gcj::stack_size = size;
1643 _Jv_Malloc (jsize size)
1645 if (__builtin_expect (size == 0, false))
1647 void *ptr = malloc ((size_t) size);
1648 if (__builtin_expect (ptr == NULL, false))
1654 _Jv_Realloc (void *ptr, jsize size)
1656 if (__builtin_expect (size == 0, false))
1658 ptr = realloc (ptr, (size_t) size);
1659 if (__builtin_expect (ptr == NULL, false))
1665 _Jv_MallocUnchecked (jsize size)
1667 if (__builtin_expect (size == 0, false))
1669 return malloc ((size_t) size);
1673 _Jv_Free (void* ptr)
1680 // In theory, these routines can be #ifdef'd away on machines which
1681 // support divide overflow signals. However, we never know if some
1682 // code might have been compiled with "-fuse-divide-subroutine", so we
1683 // always include them in libgcj.
1686 _Jv_divI (jint dividend, jint 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 == (jint) 0x80000000L && divisor == -1)
1698 return dividend / divisor;
1702 _Jv_remI (jint dividend, jint divisor)
1704 if (__builtin_expect (divisor == 0, false))
1706 java::lang::ArithmeticException *arithexception
1707 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1708 throw arithexception;
1711 if (dividend == (jint) 0x80000000L && divisor == -1)
1714 return dividend % divisor;
1718 _Jv_divJ (jlong dividend, jlong divisor)
1720 if (__builtin_expect (divisor == 0, false))
1722 java::lang::ArithmeticException *arithexception
1723 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1724 throw arithexception;
1727 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1730 return dividend / divisor;
1734 _Jv_remJ (jlong dividend, jlong divisor)
1736 if (__builtin_expect (divisor == 0, false))
1738 java::lang::ArithmeticException *arithexception
1739 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1740 throw arithexception;
1743 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1746 return dividend % divisor;
1751 // Return true if SELF_KLASS can access a field or method in
1752 // OTHER_KLASS. The field or method's access flags are specified in
1755 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1757 using namespace java::lang::reflect;
1758 return ((self_klass == other_klass)
1759 || ((flags & Modifier::PUBLIC) != 0)
1760 || (((flags & Modifier::PROTECTED) != 0)
1761 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1762 || (((flags & Modifier::PRIVATE) == 0)
1763 && _Jv_ClassNameSamePackage (self_klass->name,
1764 other_klass->name)));
1767 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1768 // char array, if the path is not already prefixed by
1769 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1770 // result should be freed using JvFree.
1772 _Jv_PrependVersionedLibdir (char* libpath)
1776 if (libpath && libpath[0] != '\0')
1778 if (! strncmp (libpath,
1779 GCJ_VERSIONED_LIBDIR,
1780 sizeof (GCJ_VERSIONED_LIBDIR) - 1))
1782 // LD_LIBRARY_PATH is already prefixed with
1783 // GCJ_VERSIONED_LIBDIR.
1784 retval = (char*) _Jv_Malloc (strlen (libpath) + 1);
1785 strcpy (retval, libpath);
1789 // LD_LIBRARY_PATH is not prefixed with
1790 // GCJ_VERSIONED_LIBDIR.
1792 path_sep[0] = (char) _Jv_platform_path_separator;
1794 jsize total = ((sizeof (GCJ_VERSIONED_LIBDIR) - 1)
1795 + 1 /* path separator */ + strlen (libpath) + 1);
1796 retval = (char*) _Jv_Malloc (total);
1797 strcpy (retval, GCJ_VERSIONED_LIBDIR);
1798 strcat (retval, path_sep);
1799 strcat (retval, libpath);
1804 // LD_LIBRARY_PATH was not specified or is empty.
1805 retval = (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR));
1806 strcpy (retval, GCJ_VERSIONED_LIBDIR);