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/java/lang/MainThread.h>
73 // Execution engine for compiled code.
74 _Jv_CompiledEngine _Jv_soleCompiledEngine
;
76 // Execution engine for code compiled with -findirect-classes
77 _Jv_IndirectCompiledEngine _Jv_soleIndirectCompiledEngine
;
79 // We allocate a single OutOfMemoryError exception which we keep
80 // around for use if we run out of memory.
81 static java::lang::OutOfMemoryError
*no_memory
;
83 // Number of bytes in largest array object we create. This could be
84 // increased to the largest size_t value, so long as the appropriate
85 // functions are changed to take a size_t argument instead of jint.
86 #define MAX_OBJECT_SIZE ((1<<31) - 1)
88 // Properties set at compile time.
89 const char **_Jv_Compiler_Properties
= NULL
;
90 int _Jv_Properties_Count
= 0;
92 #ifndef DISABLE_GETENV_PROPERTIES
93 // Property key/value pairs.
94 property_pair
*_Jv_Environment_Properties
;
97 // Stash the argv pointer to benefit native libraries that need it.
98 const char **_Jv_argv
;
105 // _Jv_argc is 0 if not explicitly initialized.
110 _Jv_GetSafeArg (int index
)
112 if (index
>=0 && index
< _Jv_GetNbArgs ())
113 return _Jv_argv
[index
];
119 _Jv_SetArgs (int argc
, const char **argv
)
126 // Pointer to JVMPI notification functions.
127 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (JVMPI_Event
*event
);
128 void (*_Jv_JVMPI_Notify_THREAD_START
) (JVMPI_Event
*event
);
129 void (*_Jv_JVMPI_Notify_THREAD_END
) (JVMPI_Event
*event
);
133 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
134 /* Unblock a signal. Unless we do this, the signal may only be sent
137 unblock_signal (int signum
__attribute__ ((__unused__
)))
139 #ifdef _POSIX_VERSION
143 sigaddset (&sigs
, signum
);
144 sigprocmask (SIG_UNBLOCK
, &sigs
, NULL
);
150 SIGNAL_HANDLER (catch_segv
)
152 unblock_signal (SIGSEGV
);
153 MAKE_THROW_FRAME (nullp
);
154 java::lang::NullPointerException
*nullp
155 = new java::lang::NullPointerException
;
161 SIGNAL_HANDLER (catch_fpe
)
163 unblock_signal (SIGFPE
);
164 #ifdef HANDLE_DIVIDE_OVERFLOW
165 HANDLE_DIVIDE_OVERFLOW
;
167 MAKE_THROW_FRAME (arithexception
);
169 java::lang::ArithmeticException
*arithexception
170 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
171 throw arithexception
;
177 _Jv_equalUtf8Consts (const Utf8Const
* a
, const Utf8Const
*b
)
180 const _Jv_ushort
*aptr
, *bptr
;
183 if (a
->hash
!= b
->hash
)
186 if (b
->length
!= len
)
188 aptr
= (const _Jv_ushort
*)a
->data
;
189 bptr
= (const _Jv_ushort
*)b
->data
;
190 len
= (len
+ 1) >> 1;
192 if (*aptr
++ != *bptr
++)
197 /* True iff A is equal to STR.
198 HASH is STR->hashCode().
202 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
204 if (a
->hash
!= (_Jv_ushort
) hash
)
206 jint len
= str
->length();
208 jchar
*sptr
= _Jv_GetStringChars (str
);
209 unsigned char* ptr
= (unsigned char*) a
->data
;
210 unsigned char* limit
= ptr
+ a
->length
;
213 int ch
= UTF8_GET (ptr
, limit
);
222 /* Like _Jv_equal, but stop after N characters. */
224 _Jv_equaln (Utf8Const
*a
, jstring str
, jint n
)
226 jint len
= str
->length();
228 jchar
*sptr
= _Jv_GetStringChars (str
);
229 unsigned char* ptr
= (unsigned char*) a
->data
;
230 unsigned char* limit
= ptr
+ a
->length
;
231 for (; n
-- > 0; i
++, sptr
++)
233 int ch
= UTF8_GET (ptr
, limit
);
242 // Determines whether the given Utf8Const object contains
243 // a type which is primitive or some derived form of it, eg.
244 // an array or multi-dimensional array variant.
246 _Jv_isPrimitiveOrDerived(const Utf8Const
*a
)
248 unsigned char *aptr
= (unsigned char *) a
->data
;
249 unsigned char *alimit
= aptr
+ a
->length
;
250 int ac
= UTF8_GET(aptr
, alimit
);
252 // Skips any leading array marks.
254 ac
= UTF8_GET(aptr
, alimit
);
256 // There should not be another character. This implies that
257 // the type name is only one character long.
258 if (UTF8_GET(aptr
, alimit
) == -1)
277 // Find out whether two _Jv_Utf8Const candidates contain the same
279 // The method is written to handle the different formats of classnames.
280 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
281 // "java.lang.Class" will be seen as equal.
282 // Warning: This function is not smart enough to declare "Z" and "boolean"
283 // and similar cases as equal (and is not meant to be used this way)!
285 _Jv_equalUtf8Classnames (const Utf8Const
*a
, const Utf8Const
*b
)
287 // If the class name's length differs by two characters
288 // it is possible that we have candidates which are given
289 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
290 switch (a
->length
- b
->length
)
300 unsigned char *aptr
= (unsigned char *) a
->data
;
301 unsigned char *alimit
= aptr
+ a
->length
;
302 unsigned char *bptr
= (unsigned char *) b
->data
;
303 unsigned char *blimit
= bptr
+ b
->length
;
305 if (alimit
[-1] == ';')
308 if (blimit
[-1] == ';')
311 int ac
= UTF8_GET(aptr
, alimit
);
312 int bc
= UTF8_GET(bptr
, blimit
);
314 // Checks whether both strings have the same amount of leading [ characters.
319 ac
= UTF8_GET(aptr
, alimit
);
320 bc
= UTF8_GET(bptr
, blimit
);
327 // Skips leading L character.
329 ac
= UTF8_GET(aptr
, alimit
);
332 bc
= UTF8_GET(bptr
, blimit
);
334 // Compares the remaining characters.
335 while (ac
!= -1 && bc
!= -1)
337 // Replaces package separating dots with slashes.
344 // Now classnames differ if there is at least one non-matching
349 ac
= UTF8_GET(aptr
, alimit
);
350 bc
= UTF8_GET(bptr
, blimit
);
356 /* Count the number of Unicode chars encoded in a given Ut8 string. */
358 _Jv_strLengthUtf8(const char* str
, int len
)
361 unsigned char* limit
;
364 ptr
= (unsigned char*) str
;
367 for (; ptr
< limit
; str_length
++)
369 if (UTF8_GET (ptr
, limit
) < 0)
375 /* Calculate a hash value for a string encoded in Utf8 format.
376 * This returns the same hash value as specified or java.lang.String.hashCode.
379 _Jv_hashUtf8String (const char* str
, int len
)
381 unsigned char* ptr
= (unsigned char*) str
;
382 unsigned char* limit
= ptr
+ len
;
387 int ch
= UTF8_GET (ptr
, limit
);
388 /* Updated specification from
389 http://www.javasoft.com/docs/books/jls/clarify.html. */
390 hash
= (31 * hash
) + ch
;
396 _Jv_Utf8Const::init(const char *s
, int len
)
398 ::memcpy (data
, s
, len
);
401 hash
= _Jv_hashUtf8String (s
, len
) & 0xFFFF;
405 _Jv_makeUtf8Const (const char* s
, int len
)
410 = (Utf8Const
*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s
, len
));
416 _Jv_makeUtf8Const (jstring string
)
418 jint hash
= string
->hashCode ();
419 jint len
= _Jv_GetStringUTFLength (string
);
421 Utf8Const
* m
= (Utf8Const
*)
422 _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
427 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
437 _Jv_Abort (const char *function
, const char *file
, int line
,
441 _Jv_Abort (const char *, const char *, int, const char *message
)
446 "libgcj failure: %s\n in function %s, file %s, line %d\n",
447 message
, function
, file
, line
);
449 fprintf (stderr
, "libgcj failure: %s\n", message
);
455 fail_on_finalization (jobject
)
457 JvFail ("object was finalized");
461 _Jv_GCWatch (jobject obj
)
463 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
467 _Jv_ThrowBadArrayIndex(jint bad_index
)
469 throw new java::lang::ArrayIndexOutOfBoundsException
470 (java::lang::String::valueOf (bad_index
));
474 _Jv_ThrowNullPointerException ()
476 throw new java::lang::NullPointerException
;
479 // Resolve an entry in the constant pool and return the target
482 _Jv_ResolvePoolEntry (jclass this_class
, jint index
)
484 _Jv_Constants
*pool
= &this_class
->constants
;
486 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
487 return pool
->data
[index
].field
->u
.addr
;
489 JvSynchronize
sync (this_class
);
490 return (_Jv_Linker::resolve_pool_entry (this_class
, index
))
495 // Explicitly throw a no memory exception.
496 // The collector calls this when it encounters an out-of-memory condition.
497 void _Jv_ThrowNoMemory()
503 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
504 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
505 jvmpi_notify_alloc(klass,size,obj);
507 jvmpi_notify_alloc(jclass klass
, jint size
, jobject obj
)
509 // Service JVMPI allocation request.
512 event
.event_type
= JVMPI_EVENT_OBJECT_ALLOC
;
514 event
.u
.obj_alloc
.arena_id
= 0;
515 event
.u
.obj_alloc
.class_id
= (jobjectID
) klass
;
516 event
.u
.obj_alloc
.is_array
= 0;
517 event
.u
.obj_alloc
.size
= size
;
518 event
.u
.obj_alloc
.obj_id
= (jobjectID
) obj
;
520 // FIXME: This doesn't look right for the Boehm GC. A GC may
521 // already be in progress. _Jv_DisableGC () doesn't wait for it.
522 // More importantly, I don't see the need for disabling GC, since we
523 // blatantly have a pointer to obj on our stack, ensuring that the
524 // object can't be collected. Even for a nonconservative collector,
525 // it appears to me that this must be true, since we are about to
526 // return obj. Isn't this whole approach way too intrusive for
527 // a useful profiling interface? - HB
529 (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (&event
);
532 #else /* !ENABLE_JVMPI */
533 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
536 // Allocate a new object of class KLASS.
537 // First a version that assumes that we have no finalizer, and that
538 // the class is already initialized.
539 // If we know that JVMPI is disabled, this can be replaced by a direct call
540 // to the allocator for the appropriate GC.
542 _Jv_AllocObjectNoInitNoFinalizer (jclass klass
)
544 jint size
= klass
->size ();
545 jobject obj
= (jobject
) _Jv_AllocObj (size
, klass
);
546 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
550 // And now a version that initializes if necessary.
552 _Jv_AllocObjectNoFinalizer (jclass klass
)
554 if (_Jv_IsPhantomClass(klass
) )
555 throw new java::lang::NoClassDefFoundError(klass
->getName());
557 _Jv_InitClass (klass
);
558 jint size
= klass
->size ();
559 jobject obj
= (jobject
) _Jv_AllocObj (size
, klass
);
560 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
564 // And now the general version that registers a finalizer if necessary.
566 _Jv_AllocObject (jclass klass
)
568 jobject obj
= _Jv_AllocObjectNoFinalizer (klass
);
570 // We assume that the compiler only generates calls to this routine
571 // if there really is an interesting finalizer.
572 // Unfortunately, we still have to the dynamic test, since there may
573 // be cni calls to this routine.
574 // Note that on IA64 get_finalizer() returns the starting address of the
575 // function, not a function pointer. Thus this still works.
576 if (klass
->vtable
->get_finalizer ()
577 != java::lang::Object::class$
.vtable
->get_finalizer ())
578 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
582 // Allocate a String, including variable length storage.
584 _Jv_AllocString(jsize len
)
586 using namespace java::lang
;
588 jsize sz
= sizeof(java::lang::String
) + len
* sizeof(jchar
);
590 // We assert that for strings allocated this way, the data field
591 // will always point to the object itself. Thus there is no reason
592 // for the garbage collector to scan any of it.
593 // Furthermore, we're about to overwrite the string data, so
594 // initialization of the object is not an issue.
596 // String needs no initialization, and there is no finalizer, so
597 // we can go directly to the collector's allocator interface.
598 jstring obj
= (jstring
) _Jv_AllocPtrFreeObj(sz
, &String::class$
);
601 obj
->boffset
= sizeof(java::lang::String
);
603 obj
->cachedHashCode
= 0;
605 JVMPI_NOTIFY_ALLOC (&String::class$
, sz
, obj
);
610 // A version of the above that assumes the object contains no pointers,
611 // and requires no finalization. This can't happen if we need pointers
613 #ifdef JV_HASH_SYNCHRONIZATION
615 _Jv_AllocPtrFreeObject (jclass klass
)
617 _Jv_InitClass (klass
);
618 jint size
= klass
->size ();
620 jobject obj
= (jobject
) _Jv_AllocPtrFreeObj (size
, klass
);
622 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
626 #endif /* JV_HASH_SYNCHRONIZATION */
629 // Allocate a new array of Java objects. Each object is of type
630 // `elementClass'. `init' is used to initialize each slot in the
633 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
635 // Creating an array of an unresolved type is impossible. So we throw
636 // the NoClassDefFoundError.
637 if ( _Jv_IsPhantomClass(elementClass
) )
638 throw new java::lang::NoClassDefFoundError(elementClass
->getName());
640 if (__builtin_expect (count
< 0, false))
641 throw new java::lang::NegativeArraySizeException
;
643 JvAssert (! elementClass
->isPrimitive ());
645 // Ensure that elements pointer is properly aligned.
646 jobjectArray obj
= NULL
;
647 size_t size
= (size_t) elements (obj
);
648 // Check for overflow.
649 if (__builtin_expect ((size_t) count
>
650 (MAX_OBJECT_SIZE
- 1 - size
) / sizeof (jobject
), false))
653 size
+= count
* sizeof (jobject
);
655 jclass klass
= _Jv_GetArrayClass (elementClass
,
656 elementClass
->getClassLoaderInternal());
658 obj
= (jobjectArray
) _Jv_AllocArray (size
, klass
);
660 jsize
*lp
= const_cast<jsize
*> (&obj
->length
);
662 // We know the allocator returns zeroed memory. So don't bother
666 jobject
*ptr
= elements(obj
);
673 // Allocate a new array of primitives. ELTYPE is the type of the
674 // element, COUNT is the size of the array.
676 _Jv_NewPrimArray (jclass eltype
, jint count
)
678 int elsize
= eltype
->size();
679 if (__builtin_expect (count
< 0, false))
680 throw new java::lang::NegativeArraySizeException
;
682 JvAssert (eltype
->isPrimitive ());
683 jobject dummy
= NULL
;
684 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
686 // Check for overflow.
687 if (__builtin_expect ((size_t) count
>
688 (MAX_OBJECT_SIZE
- size
) / elsize
, false))
691 jclass klass
= _Jv_GetArrayClass (eltype
, 0);
693 # ifdef JV_HASH_SYNCHRONIZATION
694 // Since the vtable is always statically allocated,
695 // these are completely pointerfree! Make sure the GC doesn't touch them.
697 (__JArray
*) _Jv_AllocPtrFreeObj (size
+ elsize
* count
, klass
);
698 memset((char *)arr
+ size
, 0, elsize
* count
);
700 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
, klass
);
701 // Note that we assume we are given zeroed memory by the allocator.
704 jsize
*lp
= const_cast<jsize
*> (&arr
->length
);
711 _Jv_NewArray (jint type
, jint size
)
715 case 4: return JvNewBooleanArray (size
);
716 case 5: return JvNewCharArray (size
);
717 case 6: return JvNewFloatArray (size
);
718 case 7: return JvNewDoubleArray (size
);
719 case 8: return JvNewByteArray (size
);
720 case 9: return JvNewShortArray (size
);
721 case 10: return JvNewIntArray (size
);
722 case 11: return JvNewLongArray (size
);
724 throw new java::lang::InternalError
725 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
728 // Allocate a possibly multi-dimensional array but don't check that
729 // any array length is <0.
731 _Jv_NewMultiArrayUnchecked (jclass type
, jint dimensions
, jint
*sizes
)
733 JvAssert (type
->isArray());
734 jclass element_type
= type
->getComponentType();
736 if (element_type
->isPrimitive())
737 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
739 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
743 JvAssert (! element_type
->isPrimitive());
744 JvAssert (element_type
->isArray());
745 jobject
*contents
= elements ((jobjectArray
) result
);
746 for (int i
= 0; i
< sizes
[0]; ++i
)
747 contents
[i
] = _Jv_NewMultiArrayUnchecked (element_type
, dimensions
- 1,
755 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
757 for (int i
= 0; i
< dimensions
; ++i
)
759 throw new java::lang::NegativeArraySizeException
;
761 return _Jv_NewMultiArrayUnchecked (type
, dimensions
, sizes
);
765 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
767 // Creating an array of an unresolved type is impossible. So we throw
768 // the NoClassDefFoundError.
769 if (_Jv_IsPhantomClass(array_type
))
770 throw new java::lang::NoClassDefFoundError(array_type
->getName());
773 jint sizes
[dimensions
];
774 va_start (args
, dimensions
);
775 for (int i
= 0; i
< dimensions
; ++i
)
777 jint size
= va_arg (args
, jint
);
779 throw new java::lang::NegativeArraySizeException
;
784 return _Jv_NewMultiArrayUnchecked (array_type
, dimensions
, sizes
);
789 // Ensure 8-byte alignment, for hash synchronization.
790 #define DECLARE_PRIM_TYPE(NAME) \
791 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
793 DECLARE_PRIM_TYPE(byte
)
794 DECLARE_PRIM_TYPE(short)
795 DECLARE_PRIM_TYPE(int)
796 DECLARE_PRIM_TYPE(long)
797 DECLARE_PRIM_TYPE(boolean
)
798 DECLARE_PRIM_TYPE(char)
799 DECLARE_PRIM_TYPE(float)
800 DECLARE_PRIM_TYPE(double)
801 DECLARE_PRIM_TYPE(void)
804 _Jv_InitPrimClass (jclass cl
, const char *cname
, char sig
, int len
)
806 using namespace java::lang::reflect
;
808 // We must set the vtable for the class; the Java constructor
810 (*(_Jv_VTable
**) cl
) = java::lang::Class::class$
.vtable
;
812 // Initialize the fields we care about. We do this in the same
813 // order they are declared in Class.h.
814 cl
->name
= _Jv_makeUtf8Const ((char *) cname
, -1);
815 cl
->accflags
= Modifier::PUBLIC
| Modifier::FINAL
| Modifier::ABSTRACT
;
816 cl
->method_count
= sig
;
817 cl
->size_in_bytes
= len
;
818 cl
->vtable
= JV_PRIMITIVE_VTABLE
;
819 cl
->state
= JV_STATE_DONE
;
824 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
,
827 // First count arrays.
835 jclass result
= NULL
;
839 result
= JvPrimClass (byte
);
842 result
= JvPrimClass (short);
845 result
= JvPrimClass (int);
848 result
= JvPrimClass (long);
851 result
= JvPrimClass (boolean
);
854 result
= JvPrimClass (char);
857 result
= JvPrimClass (float);
860 result
= JvPrimClass (double);
863 result
= JvPrimClass (void);
868 while (*sig
&& *sig
!= ';')
870 // Do nothing if signature appears to be malformed.
873 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (save
, sig
- save
);
874 result
= _Jv_FindClass (name
, loader
);
879 // Do nothing -- bad signature.
885 // Not really the "end", but the last valid character that we
894 while (array_count
-- > 0)
895 result
= _Jv_GetArrayClass (result
, loader
);
901 _Jv_FindClassFromSignatureNoException (char *sig
, java::lang::ClassLoader
*loader
,
908 klass
= _Jv_FindClassFromSignature(sig
, loader
, endp
);
910 catch (java::lang::NoClassDefFoundError
*ncdfe
)
914 catch (java::lang::ClassNotFoundException
*cnfe
)
923 JvConvertArgv (int argc
, const char **argv
)
927 jobjectArray ar
= JvNewObjectArray(argc
, &java::lang::String::class$
, NULL
);
928 jobject
*ptr
= elements(ar
);
929 jbyteArray bytes
= NULL
;
930 for (int i
= 0; i
< argc
; i
++)
932 const char *arg
= argv
[i
];
933 int len
= strlen (arg
);
934 if (bytes
== NULL
|| bytes
->length
< len
)
935 bytes
= JvNewByteArray (len
);
936 jbyte
*bytePtr
= elements (bytes
);
937 // We assume jbyte == char.
938 memcpy (bytePtr
, arg
, len
);
940 // Now convert using the default encoding.
941 *ptr
++ = new java::lang::String (bytes
, 0, len
);
943 return (JArray
<jstring
>*) ar
;
946 // FIXME: These variables are static so that they will be
947 // automatically scanned by the Boehm collector. This is needed
948 // because with qthreads the collector won't scan the initial stack --
949 // it will only scan the qthreads stacks.
951 // Command line arguments.
952 static JArray
<jstring
> *arg_vec
;
954 // The primary thread.
955 static java::lang::Thread
*main_thread
;
957 #ifndef DISABLE_GETENV_PROPERTIES
960 next_property_key (char *s
, size_t *length
)
966 // Skip over whitespace
970 // If we've reached the end, return NULL. Also return NULL if for
971 // some reason we've come across a malformed property string.
977 // Determine the length of the property key.
995 next_property_value (char *s
, size_t *length
)
1001 while (isspace (*s
))
1008 while (isspace (*s
))
1011 // Determine the length of the property value.
1030 process_gcj_properties ()
1032 char *props
= getenv("GCJ_PROPERTIES");
1037 // Later on we will write \0s into this string. It is simplest to
1038 // just duplicate it here.
1039 props
= strdup (props
);
1043 size_t property_count
= 0;
1045 // Whip through props quickly in order to count the number of
1047 while (p
&& (p
= next_property_key (p
, &length
)))
1049 // Skip to the end of the key
1052 p
= next_property_value (p
, &length
);
1059 // Allocate an array of property value/key pairs.
1060 _Jv_Environment_Properties
=
1061 (property_pair
*) malloc (sizeof(property_pair
)
1062 * (property_count
+ 1));
1064 // Go through the properties again, initializing _Jv_Properties
1068 while (p
&& (p
= next_property_key (p
, &length
)))
1070 _Jv_Environment_Properties
[property_count
].key
= p
;
1071 _Jv_Environment_Properties
[property_count
].key_length
= length
;
1073 // Skip to the end of the key
1076 p
= next_property_value (p
, &length
);
1078 _Jv_Environment_Properties
[property_count
].value
= p
;
1079 _Jv_Environment_Properties
[property_count
].value_length
= length
;
1086 memset ((void *) &_Jv_Environment_Properties
[property_count
],
1087 0, sizeof (property_pair
));
1089 // Null terminate the strings.
1090 for (property_pair
*prop
= &_Jv_Environment_Properties
[0];
1094 prop
->key
[prop
->key_length
] = 0;
1095 prop
->value
[prop
->value_length
] = 0;
1098 #endif // DISABLE_GETENV_PROPERTIES
1102 _Jv_Utf8Const
*void_signature
;
1103 _Jv_Utf8Const
*clinit_name
;
1104 _Jv_Utf8Const
*init_name
;
1105 _Jv_Utf8Const
*finit_name
;
1107 bool runtimeInitialized
= false;
1109 // When true, print debugging information about class loading.
1110 bool verbose_class_flag
;
1112 // When true, enable the bytecode verifier and BC-ABI type verification.
1113 bool verifyClasses
= true;
1115 // Thread stack size specified by the -Xss runtime argument.
1116 size_t stack_size
= 0;
1119 // We accept all non-standard options accepted by Sun's java command,
1120 // for compatibility with existing application launch scripts.
1122 parse_x_arg (char* option_string
)
1124 if (strlen (option_string
) <= 0)
1127 if (! strcmp (option_string
, "int"))
1129 // FIXME: this should cause the vm to never load shared objects
1131 else if (! strcmp (option_string
, "mixed"))
1133 // FIXME: allow interpreted and native code
1135 else if (! strcmp (option_string
, "batch"))
1137 // FIXME: disable background JIT'ing
1139 else if (! strcmp (option_string
, "debug"))
1141 // FIXME: add JDWP/JVMDI support
1143 else if (! strncmp (option_string
, "bootclasspath:", 14))
1145 // FIXME: add a parse_bootclasspath_arg function
1147 else if (! strncmp (option_string
, "bootclasspath/a:", 16))
1150 else if (! strncmp (option_string
, "bootclasspath/p:", 16))
1153 else if (! strcmp (option_string
, "check:jni"))
1155 // FIXME: enable strict JNI checking
1157 else if (! strcmp (option_string
, "future"))
1159 // FIXME: enable strict class file format checks
1161 else if (! strcmp (option_string
, "noclassgc"))
1163 // FIXME: disable garbage collection for classes
1165 else if (! strcmp (option_string
, "incgc"))
1167 // FIXME: incremental garbage collection
1169 else if (! strncmp (option_string
, "loggc:", 6))
1171 if (option_string
[6] == '\0')
1174 "libgcj: filename argument expected for loggc option\n");
1177 // FIXME: set gc logging filename
1179 else if (! strncmp (option_string
, "ms", 2))
1181 // FIXME: ignore this option until PR 20699 is fixed.
1182 // _Jv_SetInitialHeapSize (option_string + 2);
1184 else if (! strncmp (option_string
, "mx", 2))
1185 _Jv_SetMaximumHeapSize (option_string
+ 2);
1186 else if (! strcmp (option_string
, "prof"))
1188 // FIXME: enable profiling of program running in vm
1190 else if (! strncmp (option_string
, "runhprof:", 9))
1192 // FIXME: enable specific type of vm profiling. add a
1193 // parse_runhprof_arg function
1195 else if (! strcmp (option_string
, "rs"))
1197 // FIXME: reduced system signal usage. disable thread dumps,
1198 // only terminate in response to user-initiated calls,
1199 // e.g. System.exit()
1201 else if (! strncmp (option_string
, "ss", 2))
1203 _Jv_SetStackSize (option_string
+ 2);
1205 else if (! strcmp (option_string
, "X:+UseAltSigs"))
1207 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1209 else if (! strcmp (option_string
, "share:off"))
1211 // FIXME: don't share class data
1213 else if (! strcmp (option_string
, "share:auto"))
1215 // FIXME: share class data where possible
1217 else if (! strcmp (option_string
, "share:on"))
1219 // FIXME: fail if impossible to share class data
1226 parse_verbose_args (char* option_string
,
1227 bool ignore_unrecognized
)
1229 size_t len
= sizeof ("-verbose") - 1;
1231 if (strlen (option_string
) < len
)
1234 if (option_string
[len
] == ':'
1235 && option_string
[len
+ 1] != '\0')
1237 char* verbose_args
= option_string
+ len
+ 1;
1241 if (! strncmp (verbose_args
,
1242 "gc", sizeof ("gc") - 1))
1244 if (verbose_args
[sizeof ("gc") - 1] == '\0'
1245 || verbose_args
[sizeof ("gc") - 1] == ',')
1247 // FIXME: we should add functions to boehm-gc that
1248 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1249 // GC_print_back_height.
1250 verbose_args
+= sizeof ("gc") - 1;
1255 fprintf (stderr
, "libgcj: unknown verbose option: %s\n",
1260 else if (! strncmp (verbose_args
,
1262 sizeof ("class") - 1))
1264 if (verbose_args
[sizeof ("class") - 1] == '\0'
1265 || verbose_args
[sizeof ("class") - 1] == ',')
1267 gcj::verbose_class_flag
= true;
1268 verbose_args
+= sizeof ("class") - 1;
1271 goto verbose_arg_err
;
1273 else if (! strncmp (verbose_args
, "jni",
1274 sizeof ("jni") - 1))
1276 if (verbose_args
[sizeof ("jni") - 1] == '\0'
1277 || verbose_args
[sizeof ("jni") - 1] == ',')
1279 // FIXME: enable JNI messages.
1280 verbose_args
+= sizeof ("jni") - 1;
1283 goto verbose_arg_err
;
1285 else if (ignore_unrecognized
1286 && verbose_args
[0] == 'X')
1288 // ignore unrecognized non-standard verbose option
1289 while (verbose_args
[0] != '\0'
1290 && verbose_args
[0] != ',')
1293 else if (verbose_args
[0] == ',')
1298 goto verbose_arg_err
;
1300 if (verbose_args
[0] == ',')
1303 while (verbose_args
[0] != '\0');
1305 else if (option_string
[len
] == 'g'
1306 && option_string
[len
+ 1] == 'c'
1307 && option_string
[len
+ 2] == '\0')
1309 // FIXME: we should add functions to boehm-gc that
1310 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1311 // GC_print_back_height.
1314 else if (option_string
[len
] == '\0')
1316 gcj::verbose_class_flag
= true;
1321 // unrecognized option beginning with -verbose
1328 parse_init_args (JvVMInitArgs
* vm_args
)
1330 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1331 // re-allocated dynamically.
1332 if (_Jv_Compiler_Properties
)
1334 const char** props
= _Jv_Compiler_Properties
;
1335 _Jv_Compiler_Properties
= NULL
;
1337 for (int i
= 0; props
[i
]; i
++)
1339 _Jv_Compiler_Properties
= (const char**) _Jv_Realloc
1340 (_Jv_Compiler_Properties
,
1341 (_Jv_Properties_Count
+ 1) * sizeof (const char*));
1342 _Jv_Compiler_Properties
[_Jv_Properties_Count
++] = props
[i
];
1346 if (vm_args
== NULL
)
1349 for (int i
= 0; i
< vm_args
->nOptions
; ++i
)
1351 char* option_string
= vm_args
->options
[i
].optionString
;
1352 if (! strcmp (option_string
, "vfprintf")
1353 || ! strcmp (option_string
, "exit")
1354 || ! strcmp (option_string
, "abort"))
1356 // FIXME: we are required to recognize these, but for
1357 // now we don't handle them in any way.
1360 else if (! strncmp (option_string
,
1361 "-verbose", sizeof ("-verbose") - 1))
1363 jint result
= parse_verbose_args (option_string
,
1364 vm_args
->ignoreUnrecognized
);
1368 else if (! strncmp (option_string
, "-D", 2))
1370 _Jv_Compiler_Properties
= (const char**) _Jv_Realloc
1371 (_Jv_Compiler_Properties
,
1372 (_Jv_Properties_Count
+ 1) * sizeof (char*));
1374 _Jv_Compiler_Properties
[_Jv_Properties_Count
++] =
1375 strdup (option_string
+ 2);
1379 else if (vm_args
->ignoreUnrecognized
)
1381 if (option_string
[0] == '_')
1382 parse_x_arg (option_string
+ 1);
1383 else if (! strncmp (option_string
, "-X", 2))
1384 parse_x_arg (option_string
+ 2);
1388 fprintf (stderr
, "libgcj: unknown option: %s\n", option_string
);
1393 goto unknown_option
;
1399 _Jv_CreateJavaVM (JvVMInitArgs
* vm_args
)
1401 using namespace gcj
;
1403 if (runtimeInitialized
)
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 // We have to initialize this fairly early, to avoid circular class
1448 // initialization. In particular we want to start the
1449 // initialization of ClassLoader before we start the initialization
1450 // of VMClassLoader.
1451 _Jv_InitClass (&java::lang::ClassLoader::class$
);
1453 // Set up the system class loader and the bootstrap class loader.
1454 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1455 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR
));
1457 _Jv_RegisterBootstrapPackages();
1459 no_memory
= new java::lang::OutOfMemoryError
;
1462 LTDL_SET_PRELOADED_SYMBOLS ();
1465 _Jv_platform_initialize ();
1469 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady
);
1471 // Start the GC finalizer thread. A VirtualMachineError can be
1472 // thrown by the runtime if, say, threads aren't available.
1475 using namespace gnu::gcj::runtime
;
1476 FinalizerThread
*ft
= new FinalizerThread ();
1479 catch (java::lang::VirtualMachineError
*ignore
)
1483 runtimeInitialized
= true;
1489 _Jv_RunMain (JvVMInitArgs
*vm_args
, jclass klass
, const char *name
, int argc
,
1490 const char **argv
, bool is_jar
)
1492 #ifndef DISABLE_MAIN_ARGS
1493 _Jv_SetArgs (argc
, argv
);
1496 java::lang::Runtime
*runtime
= NULL
;
1500 if (_Jv_CreateJavaVM (vm_args
) < 0)
1502 fprintf (stderr
, "libgcj: couldn't create virtual machine\n");
1506 // Get the Runtime here. We want to initialize it before searching
1507 // for `main'; that way it will be set up if `main' is a JNI method.
1508 runtime
= java::lang::Runtime::getRuntime ();
1510 #ifdef DISABLE_MAIN_ARGS
1511 arg_vec
= JvConvertArgv (0, 0);
1513 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
1516 using namespace gnu::java::lang
;
1518 main_thread
= new MainThread (klass
, arg_vec
);
1520 main_thread
= new MainThread (JvNewStringUTF (name
),
1523 catch (java::lang::Throwable
*t
)
1525 java::lang::System::err
->println (JvNewStringLatin1
1526 ("Exception during runtime initialization"));
1527 t
->printStackTrace();
1529 java::lang::Runtime::exitNoChecksAccessor (1);
1530 // In case the runtime creation failed.
1534 _Jv_AttachCurrentThread (main_thread
);
1535 _Jv_ThreadRun (main_thread
);
1537 // If we got here then something went wrong, as MainThread is not
1538 // supposed to terminate.
1543 _Jv_RunMain (jclass klass
, const char *name
, int argc
, const char **argv
,
1546 _Jv_RunMain (NULL
, klass
, name
, argc
, argv
, is_jar
);
1550 JvRunMain (jclass klass
, int argc
, const char **argv
)
1552 _Jv_RunMain (klass
, NULL
, argc
, argv
, false);
1557 // Parse a string and return a heap size.
1559 parse_memory_size (const char *spec
)
1562 unsigned long val
= strtoul (spec
, &end
, 10);
1563 if (*end
== 'k' || *end
== 'K')
1565 else if (*end
== 'm' || *end
== 'M')
1567 return (size_t) val
;
1570 // Set the initial heap size. This might be ignored by the GC layer.
1571 // This must be called before _Jv_RunMain.
1573 _Jv_SetInitialHeapSize (const char *arg
)
1575 size_t size
= parse_memory_size (arg
);
1576 _Jv_GCSetInitialHeapSize (size
);
1579 // Set the maximum heap size. This might be ignored by the GC layer.
1580 // This must be called before _Jv_RunMain.
1582 _Jv_SetMaximumHeapSize (const char *arg
)
1584 size_t size
= parse_memory_size (arg
);
1585 _Jv_GCSetMaximumHeapSize (size
);
1589 _Jv_SetStackSize (const char *arg
)
1591 size_t size
= parse_memory_size (arg
);
1592 gcj::stack_size
= size
;
1596 _Jv_Malloc (jsize size
)
1598 if (__builtin_expect (size
== 0, false))
1600 void *ptr
= malloc ((size_t) size
);
1601 if (__builtin_expect (ptr
== NULL
, false))
1607 _Jv_Realloc (void *ptr
, jsize size
)
1609 if (__builtin_expect (size
== 0, false))
1611 ptr
= realloc (ptr
, (size_t) size
);
1612 if (__builtin_expect (ptr
== NULL
, false))
1618 _Jv_MallocUnchecked (jsize size
)
1620 if (__builtin_expect (size
== 0, false))
1622 return malloc ((size_t) size
);
1626 _Jv_Free (void* ptr
)
1633 // In theory, these routines can be #ifdef'd away on machines which
1634 // support divide overflow signals. However, we never know if some
1635 // code might have been compiled with "-fuse-divide-subroutine", so we
1636 // always include them in libgcj.
1639 _Jv_divI (jint dividend
, jint divisor
)
1641 if (__builtin_expect (divisor
== 0, false))
1643 java::lang::ArithmeticException
*arithexception
1644 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1645 throw arithexception
;
1648 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
1651 return dividend
/ divisor
;
1655 _Jv_remI (jint dividend
, jint divisor
)
1657 if (__builtin_expect (divisor
== 0, false))
1659 java::lang::ArithmeticException
*arithexception
1660 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1661 throw arithexception
;
1664 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
1667 return dividend
% divisor
;
1671 _Jv_divJ (jlong dividend
, jlong divisor
)
1673 if (__builtin_expect (divisor
== 0, false))
1675 java::lang::ArithmeticException
*arithexception
1676 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1677 throw arithexception
;
1680 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1683 return dividend
/ divisor
;
1687 _Jv_remJ (jlong dividend
, jlong divisor
)
1689 if (__builtin_expect (divisor
== 0, false))
1691 java::lang::ArithmeticException
*arithexception
1692 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1693 throw arithexception
;
1696 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1699 return dividend
% divisor
;
1704 // Return true if SELF_KLASS can access a field or method in
1705 // OTHER_KLASS. The field or method's access flags are specified in
1708 _Jv_CheckAccess (jclass self_klass
, jclass other_klass
, jint flags
)
1710 using namespace java::lang::reflect
;
1711 return ((self_klass
== other_klass
)
1712 || ((flags
& Modifier::PUBLIC
) != 0)
1713 || (((flags
& Modifier::PROTECTED
) != 0)
1714 && _Jv_IsAssignableFromSlow (self_klass
, other_klass
))
1715 || (((flags
& Modifier::PRIVATE
) == 0)
1716 && _Jv_ClassNameSamePackage (self_klass
->name
,
1717 other_klass
->name
)));
1720 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1721 // char array, if the path is not already prefixed by
1722 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1723 // result should be freed using JvFree.
1725 _Jv_PrependVersionedLibdir (char* libpath
)
1729 if (libpath
&& libpath
[0] != '\0')
1731 if (! strncmp (libpath
,
1732 GCJ_VERSIONED_LIBDIR
,
1733 sizeof (GCJ_VERSIONED_LIBDIR
) - 1))
1735 // LD_LIBRARY_PATH is already prefixed with
1736 // GCJ_VERSIONED_LIBDIR.
1737 retval
= (char*) _Jv_Malloc (strlen (libpath
) + 1);
1738 strcpy (retval
, libpath
);
1742 // LD_LIBRARY_PATH is not prefixed with
1743 // GCJ_VERSIONED_LIBDIR.
1744 jsize total
= (sizeof (GCJ_VERSIONED_LIBDIR
) - 1)
1745 + (sizeof (PATH_SEPARATOR
) - 1) + strlen (libpath
) + 1;
1746 retval
= (char*) _Jv_Malloc (total
);
1747 strcpy (retval
, GCJ_VERSIONED_LIBDIR
);
1748 strcat (retval
, PATH_SEPARATOR
);
1749 strcat (retval
, libpath
);
1754 // LD_LIBRARY_PATH was not specified or is empty.
1755 retval
= (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR
));
1756 strcpy (retval
, GCJ_VERSIONED_LIBDIR
);