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>
36 #include "jvmti-int.h"
38 #ifndef DISABLE_GETENV_PROPERTIES
40 #include <java-props.h>
41 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
43 #define PROCESS_GCJ_PROPERTIES
44 #endif // DISABLE_GETENV_PROPERTIES
46 #include <java/lang/Class.h>
47 #include <java/lang/ClassLoader.h>
48 #include <java/lang/Runtime.h>
49 #include <java/lang/String.h>
50 #include <java/lang/Thread.h>
51 #include <java/lang/ThreadGroup.h>
52 #include <java/lang/ArrayIndexOutOfBoundsException.h>
53 #include <java/lang/ArithmeticException.h>
54 #include <java/lang/ClassFormatError.h>
55 #include <java/lang/ClassNotFoundException.h>
56 #include <java/lang/InternalError.h>
57 #include <java/lang/NegativeArraySizeException.h>
58 #include <java/lang/NoClassDefFoundError.h>
59 #include <java/lang/NullPointerException.h>
60 #include <java/lang/OutOfMemoryError.h>
61 #include <java/lang/System.h>
62 #include <java/lang/VMClassLoader.h>
63 #include <java/lang/reflect/Modifier.h>
64 #include <java/io/PrintStream.h>
65 #include <java/lang/UnsatisfiedLinkError.h>
66 #include <java/lang/VirtualMachineError.h>
67 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
68 #include <gnu/gcj/runtime/FinalizerThread.h>
69 #include <execution.h>
70 #include <gnu/classpath/jdwp/Jdwp.h>
71 #include <gnu/classpath/jdwp/VMVirtualMachine.h>
72 #include <gnu/java/lang/MainThread.h>
78 // Execution engine for compiled code.
79 _Jv_CompiledEngine _Jv_soleCompiledEngine
;
81 // Execution engine for code compiled with -findirect-classes
82 _Jv_IndirectCompiledEngine _Jv_soleIndirectCompiledEngine
;
84 // We allocate a single OutOfMemoryError exception which we keep
85 // around for use if we run out of memory.
86 static java::lang::OutOfMemoryError
*no_memory
;
88 // Number of bytes in largest array object we create. This could be
89 // increased to the largest size_t value, so long as the appropriate
90 // functions are changed to take a size_t argument instead of jint.
91 #define MAX_OBJECT_SIZE (((size_t)1<<31) - 1)
93 // Properties set at compile time.
94 const char **_Jv_Compiler_Properties
= NULL
;
95 int _Jv_Properties_Count
= 0;
97 #ifndef DISABLE_GETENV_PROPERTIES
98 // Property key/value pairs.
99 property_pair
*_Jv_Environment_Properties
;
102 // Stash the argv pointer to benefit native libraries that need it.
103 const char **_Jv_argv
;
107 static bool remoteDebug
= false;
108 static char defaultJdwpOptions
[] = "";
109 static char *jdwpOptions
= defaultJdwpOptions
;
115 // _Jv_argc is 0 if not explicitly initialized.
120 _Jv_GetSafeArg (int index
)
122 if (index
>=0 && index
< _Jv_GetNbArgs ())
123 return _Jv_argv
[index
];
129 _Jv_SetArgs (int argc
, const char **argv
)
136 // Pointer to JVMPI notification functions.
137 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (JVMPI_Event
*event
);
138 void (*_Jv_JVMPI_Notify_THREAD_START
) (JVMPI_Event
*event
);
139 void (*_Jv_JVMPI_Notify_THREAD_END
) (JVMPI_Event
*event
);
143 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
144 /* Unblock a signal. Unless we do this, the signal may only be sent
147 unblock_signal (int signum
__attribute__ ((__unused__
)))
149 #ifdef _POSIX_VERSION
153 sigaddset (&sigs
, signum
);
154 sigprocmask (SIG_UNBLOCK
, &sigs
, NULL
);
160 SIGNAL_HANDLER (catch_segv
)
162 unblock_signal (SIGSEGV
);
163 MAKE_THROW_FRAME (nullp
);
164 java::lang::NullPointerException
*nullp
165 = new java::lang::NullPointerException
;
171 SIGNAL_HANDLER (catch_fpe
)
173 unblock_signal (SIGFPE
);
174 #ifdef HANDLE_DIVIDE_OVERFLOW
175 HANDLE_DIVIDE_OVERFLOW
;
177 MAKE_THROW_FRAME (arithexception
);
179 java::lang::ArithmeticException
*arithexception
180 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
181 throw arithexception
;
187 _Jv_equalUtf8Consts (const Utf8Const
* a
, const Utf8Const
*b
)
190 const _Jv_ushort
*aptr
, *bptr
;
193 if (a
->hash
!= b
->hash
)
196 if (b
->length
!= len
)
198 aptr
= (const _Jv_ushort
*)a
->data
;
199 bptr
= (const _Jv_ushort
*)b
->data
;
200 len
= (len
+ 1) >> 1;
202 if (*aptr
++ != *bptr
++)
207 /* True iff A is equal to STR.
208 HASH is STR->hashCode().
212 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
214 if (a
->hash
!= (_Jv_ushort
) hash
)
216 jint len
= str
->length();
218 jchar
*sptr
= _Jv_GetStringChars (str
);
219 unsigned char* ptr
= (unsigned char*) a
->data
;
220 unsigned char* limit
= ptr
+ a
->length
;
223 int ch
= UTF8_GET (ptr
, limit
);
232 /* Like _Jv_equal, but stop after N characters. */
234 _Jv_equaln (Utf8Const
*a
, jstring str
, jint n
)
236 jint len
= str
->length();
238 jchar
*sptr
= _Jv_GetStringChars (str
);
239 unsigned char* ptr
= (unsigned char*) a
->data
;
240 unsigned char* limit
= ptr
+ a
->length
;
241 for (; n
-- > 0; i
++, sptr
++)
243 int ch
= UTF8_GET (ptr
, limit
);
252 // Determines whether the given Utf8Const object contains
253 // a type which is primitive or some derived form of it, eg.
254 // an array or multi-dimensional array variant.
256 _Jv_isPrimitiveOrDerived(const Utf8Const
*a
)
258 unsigned char *aptr
= (unsigned char *) a
->data
;
259 unsigned char *alimit
= aptr
+ a
->length
;
260 int ac
= UTF8_GET(aptr
, alimit
);
262 // Skips any leading array marks.
264 ac
= UTF8_GET(aptr
, alimit
);
266 // There should not be another character. This implies that
267 // the type name is only one character long.
268 if (UTF8_GET(aptr
, alimit
) == -1)
287 // Find out whether two _Jv_Utf8Const candidates contain the same
289 // The method is written to handle the different formats of classnames.
290 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
291 // "java.lang.Class" will be seen as equal.
292 // Warning: This function is not smart enough to declare "Z" and "boolean"
293 // and similar cases as equal (and is not meant to be used this way)!
295 _Jv_equalUtf8Classnames (const Utf8Const
*a
, const Utf8Const
*b
)
297 // If the class name's length differs by two characters
298 // it is possible that we have candidates which are given
299 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
300 switch (a
->length
- b
->length
)
310 unsigned char *aptr
= (unsigned char *) a
->data
;
311 unsigned char *alimit
= aptr
+ a
->length
;
312 unsigned char *bptr
= (unsigned char *) b
->data
;
313 unsigned char *blimit
= bptr
+ b
->length
;
315 if (alimit
[-1] == ';')
318 if (blimit
[-1] == ';')
321 int ac
= UTF8_GET(aptr
, alimit
);
322 int bc
= UTF8_GET(bptr
, blimit
);
324 // Checks whether both strings have the same amount of leading [ characters.
329 ac
= UTF8_GET(aptr
, alimit
);
330 bc
= UTF8_GET(bptr
, blimit
);
337 // Skips leading L character.
339 ac
= UTF8_GET(aptr
, alimit
);
342 bc
= UTF8_GET(bptr
, blimit
);
344 // Compares the remaining characters.
345 while (ac
!= -1 && bc
!= -1)
347 // Replaces package separating dots with slashes.
354 // Now classnames differ if there is at least one non-matching
359 ac
= UTF8_GET(aptr
, alimit
);
360 bc
= UTF8_GET(bptr
, blimit
);
366 /* Count the number of Unicode chars encoded in a given Ut8 string. */
368 _Jv_strLengthUtf8(const char* str
, int len
)
371 unsigned char* limit
;
374 ptr
= (unsigned char*) str
;
377 for (; ptr
< limit
; str_length
++)
379 if (UTF8_GET (ptr
, limit
) < 0)
385 /* Calculate a hash value for a string encoded in Utf8 format.
386 * This returns the same hash value as specified or java.lang.String.hashCode.
389 _Jv_hashUtf8String (const char* str
, int len
)
391 unsigned char* ptr
= (unsigned char*) str
;
392 unsigned char* limit
= ptr
+ len
;
397 int ch
= UTF8_GET (ptr
, limit
);
398 /* Updated specification from
399 http://www.javasoft.com/docs/books/jls/clarify.html. */
400 hash
= (31 * hash
) + ch
;
406 _Jv_Utf8Const::init(const char *s
, int len
)
408 ::memcpy (data
, s
, len
);
411 hash
= _Jv_hashUtf8String (s
, len
) & 0xFFFF;
415 _Jv_makeUtf8Const (const char* s
, int len
)
420 = (Utf8Const
*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s
, len
));
426 _Jv_makeUtf8Const (jstring string
)
428 jint hash
= string
->hashCode ();
429 jint len
= _Jv_GetStringUTFLength (string
);
431 Utf8Const
* m
= (Utf8Const
*)
432 _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
437 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
447 _Jv_Abort (const char *function
, const char *file
, int line
,
451 _Jv_Abort (const char *, const char *, int, const char *message
)
456 "libgcj failure: %s\n in function %s, file %s, line %d\n",
457 message
, function
, file
, line
);
459 fprintf (stderr
, "libgcj failure: %s\n", message
);
465 fail_on_finalization (jobject
)
467 JvFail ("object was finalized");
471 _Jv_GCWatch (jobject obj
)
473 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
477 _Jv_ThrowBadArrayIndex(jint bad_index
)
479 throw new java::lang::ArrayIndexOutOfBoundsException
480 (java::lang::String::valueOf (bad_index
));
484 _Jv_ThrowNullPointerException ()
486 throw new java::lang::NullPointerException
;
489 // Resolve an entry in the constant pool and return the target
492 _Jv_ResolvePoolEntry (jclass this_class
, jint index
)
494 _Jv_Constants
*pool
= &this_class
->constants
;
496 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
497 return pool
->data
[index
].field
->u
.addr
;
499 JvSynchronize
sync (this_class
);
500 return (_Jv_Linker::resolve_pool_entry (this_class
, index
))
505 // Explicitly throw a no memory exception.
506 // The collector calls this when it encounters an out-of-memory condition.
507 void _Jv_ThrowNoMemory()
513 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
514 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
515 jvmpi_notify_alloc(klass,size,obj);
517 jvmpi_notify_alloc(jclass klass
, jint size
, jobject obj
)
519 // Service JVMPI allocation request.
522 event
.event_type
= JVMPI_EVENT_OBJECT_ALLOC
;
524 event
.u
.obj_alloc
.arena_id
= 0;
525 event
.u
.obj_alloc
.class_id
= (jobjectID
) klass
;
526 event
.u
.obj_alloc
.is_array
= 0;
527 event
.u
.obj_alloc
.size
= size
;
528 event
.u
.obj_alloc
.obj_id
= (jobjectID
) obj
;
530 // FIXME: This doesn't look right for the Boehm GC. A GC may
531 // already be in progress. _Jv_DisableGC () doesn't wait for it.
532 // More importantly, I don't see the need for disabling GC, since we
533 // blatantly have a pointer to obj on our stack, ensuring that the
534 // object can't be collected. Even for a nonconservative collector,
535 // it appears to me that this must be true, since we are about to
536 // return obj. Isn't this whole approach way too intrusive for
537 // a useful profiling interface? - HB
539 (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (&event
);
542 #else /* !ENABLE_JVMPI */
543 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
546 // Allocate a new object of class KLASS.
547 // First a version that assumes that we have no finalizer, and that
548 // the class is already initialized.
549 // If we know that JVMPI is disabled, this can be replaced by a direct call
550 // to the allocator for the appropriate GC.
552 _Jv_AllocObjectNoInitNoFinalizer (jclass klass
)
554 jint size
= klass
->size ();
555 jobject obj
= (jobject
) _Jv_AllocObj (size
, klass
);
556 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
560 // And now a version that initializes if necessary.
562 _Jv_AllocObjectNoFinalizer (jclass klass
)
564 if (_Jv_IsPhantomClass(klass
) )
565 throw new java::lang::NoClassDefFoundError(klass
->getName());
567 _Jv_InitClass (klass
);
568 jint size
= klass
->size ();
569 jobject obj
= (jobject
) _Jv_AllocObj (size
, klass
);
570 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
574 // And now the general version that registers a finalizer if necessary.
576 _Jv_AllocObject (jclass klass
)
578 jobject obj
= _Jv_AllocObjectNoFinalizer (klass
);
580 // We assume that the compiler only generates calls to this routine
581 // if there really is an interesting finalizer.
582 // Unfortunately, we still have to the dynamic test, since there may
583 // be cni calls to this routine.
584 // Note that on IA64 get_finalizer() returns the starting address of the
585 // function, not a function pointer. Thus this still works.
586 if (klass
->vtable
->get_finalizer ()
587 != java::lang::Object::class$
.vtable
->get_finalizer ())
588 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
592 // Allocate a String, including variable length storage.
594 _Jv_AllocString(jsize len
)
596 using namespace java::lang
;
598 jsize sz
= sizeof(java::lang::String
) + len
* sizeof(jchar
);
600 // We assert that for strings allocated this way, the data field
601 // will always point to the object itself. Thus there is no reason
602 // for the garbage collector to scan any of it.
603 // Furthermore, we're about to overwrite the string data, so
604 // initialization of the object is not an issue.
606 // String needs no initialization, and there is no finalizer, so
607 // we can go directly to the collector's allocator interface.
608 jstring obj
= (jstring
) _Jv_AllocPtrFreeObj(sz
, &String::class$
);
611 obj
->boffset
= sizeof(java::lang::String
);
613 obj
->cachedHashCode
= 0;
615 JVMPI_NOTIFY_ALLOC (&String::class$
, sz
, obj
);
620 // A version of the above that assumes the object contains no pointers,
621 // and requires no finalization. This can't happen if we need pointers
623 #ifdef JV_HASH_SYNCHRONIZATION
625 _Jv_AllocPtrFreeObject (jclass klass
)
627 _Jv_InitClass (klass
);
628 jint size
= klass
->size ();
630 jobject obj
= (jobject
) _Jv_AllocPtrFreeObj (size
, klass
);
632 JVMPI_NOTIFY_ALLOC (klass
, size
, obj
);
636 #endif /* JV_HASH_SYNCHRONIZATION */
639 // Allocate a new array of Java objects. Each object is of type
640 // `elementClass'. `init' is used to initialize each slot in the
643 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
645 // Creating an array of an unresolved type is impossible. So we throw
646 // the NoClassDefFoundError.
647 if ( _Jv_IsPhantomClass(elementClass
) )
648 throw new java::lang::NoClassDefFoundError(elementClass
->getName());
650 if (__builtin_expect (count
< 0, false))
651 throw new java::lang::NegativeArraySizeException
;
653 JvAssert (! elementClass
->isPrimitive ());
655 // Ensure that elements pointer is properly aligned.
656 jobjectArray obj
= NULL
;
657 size_t size
= (size_t) elements (obj
);
658 // Check for overflow.
659 if (__builtin_expect ((size_t) count
>
660 (MAX_OBJECT_SIZE
- 1 - size
) / sizeof (jobject
), false))
663 size
+= count
* sizeof (jobject
);
665 jclass klass
= _Jv_GetArrayClass (elementClass
,
666 elementClass
->getClassLoaderInternal());
668 obj
= (jobjectArray
) _Jv_AllocArray (size
, klass
);
670 jsize
*lp
= const_cast<jsize
*> (&obj
->length
);
672 // We know the allocator returns zeroed memory. So don't bother
676 jobject
*ptr
= elements(obj
);
683 // Allocate a new array of primitives. ELTYPE is the type of the
684 // element, COUNT is the size of the array.
686 _Jv_NewPrimArray (jclass eltype
, jint count
)
688 int elsize
= eltype
->size();
689 if (__builtin_expect (count
< 0, false))
690 throw new java::lang::NegativeArraySizeException
;
692 JvAssert (eltype
->isPrimitive ());
693 jobject dummy
= NULL
;
694 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
696 // Check for overflow.
697 if (__builtin_expect ((size_t) count
>
698 (MAX_OBJECT_SIZE
- size
) / elsize
, false))
701 jclass klass
= _Jv_GetArrayClass (eltype
, 0);
703 # ifdef JV_HASH_SYNCHRONIZATION
704 // Since the vtable is always statically allocated,
705 // these are completely pointerfree! Make sure the GC doesn't touch them.
707 (__JArray
*) _Jv_AllocPtrFreeObj (size
+ elsize
* count
, klass
);
708 memset((char *)arr
+ size
, 0, elsize
* count
);
710 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
, klass
);
711 // Note that we assume we are given zeroed memory by the allocator.
714 jsize
*lp
= const_cast<jsize
*> (&arr
->length
);
721 _Jv_NewArray (jint type
, jint size
)
725 case 4: return JvNewBooleanArray (size
);
726 case 5: return JvNewCharArray (size
);
727 case 6: return JvNewFloatArray (size
);
728 case 7: return JvNewDoubleArray (size
);
729 case 8: return JvNewByteArray (size
);
730 case 9: return JvNewShortArray (size
);
731 case 10: return JvNewIntArray (size
);
732 case 11: return JvNewLongArray (size
);
734 throw new java::lang::InternalError
735 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
738 // Allocate a possibly multi-dimensional array but don't check that
739 // any array length is <0.
741 _Jv_NewMultiArrayUnchecked (jclass type
, jint dimensions
, jint
*sizes
)
743 JvAssert (type
->isArray());
744 jclass element_type
= type
->getComponentType();
746 if (element_type
->isPrimitive())
747 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
749 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
753 JvAssert (! element_type
->isPrimitive());
754 JvAssert (element_type
->isArray());
755 jobject
*contents
= elements ((jobjectArray
) result
);
756 for (int i
= 0; i
< sizes
[0]; ++i
)
757 contents
[i
] = _Jv_NewMultiArrayUnchecked (element_type
, dimensions
- 1,
765 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
767 for (int i
= 0; i
< dimensions
; ++i
)
769 throw new java::lang::NegativeArraySizeException
;
771 return _Jv_NewMultiArrayUnchecked (type
, dimensions
, sizes
);
775 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
777 // Creating an array of an unresolved type is impossible. So we throw
778 // the NoClassDefFoundError.
779 if (_Jv_IsPhantomClass(array_type
))
780 throw new java::lang::NoClassDefFoundError(array_type
->getName());
783 jint sizes
[dimensions
];
784 va_start (args
, dimensions
);
785 for (int i
= 0; i
< dimensions
; ++i
)
787 jint size
= va_arg (args
, jint
);
789 throw new java::lang::NegativeArraySizeException
;
794 return _Jv_NewMultiArrayUnchecked (array_type
, dimensions
, sizes
);
799 // Ensure 8-byte alignment, for hash synchronization.
800 #define DECLARE_PRIM_TYPE(NAME) \
801 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
803 DECLARE_PRIM_TYPE(byte
)
804 DECLARE_PRIM_TYPE(short)
805 DECLARE_PRIM_TYPE(int)
806 DECLARE_PRIM_TYPE(long)
807 DECLARE_PRIM_TYPE(boolean
)
808 DECLARE_PRIM_TYPE(char)
809 DECLARE_PRIM_TYPE(float)
810 DECLARE_PRIM_TYPE(double)
811 DECLARE_PRIM_TYPE(void)
814 _Jv_InitPrimClass (jclass cl
, const char *cname
, char sig
, int len
)
816 using namespace java::lang::reflect
;
818 // We must set the vtable for the class; the Java constructor
820 (*(_Jv_VTable
**) cl
) = java::lang::Class::class$
.vtable
;
822 // Initialize the fields we care about. We do this in the same
823 // order they are declared in Class.h.
824 cl
->name
= _Jv_makeUtf8Const ((char *) cname
, -1);
825 cl
->accflags
= Modifier::PUBLIC
| Modifier::FINAL
| Modifier::ABSTRACT
;
826 cl
->method_count
= sig
;
827 cl
->size_in_bytes
= len
;
828 cl
->vtable
= JV_PRIMITIVE_VTABLE
;
829 cl
->state
= JV_STATE_DONE
;
834 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
,
837 // First count arrays.
845 jclass result
= NULL
;
849 result
= JvPrimClass (byte
);
852 result
= JvPrimClass (short);
855 result
= JvPrimClass (int);
858 result
= JvPrimClass (long);
861 result
= JvPrimClass (boolean
);
864 result
= JvPrimClass (char);
867 result
= JvPrimClass (float);
870 result
= JvPrimClass (double);
873 result
= JvPrimClass (void);
878 while (*sig
&& *sig
!= ';')
880 // Do nothing if signature appears to be malformed.
883 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (save
, sig
- save
);
884 result
= _Jv_FindClass (name
, loader
);
889 // Do nothing -- bad signature.
895 // Not really the "end", but the last valid character that we
904 while (array_count
-- > 0)
905 result
= _Jv_GetArrayClass (result
, loader
);
911 _Jv_FindClassFromSignatureNoException (char *sig
, java::lang::ClassLoader
*loader
,
918 klass
= _Jv_FindClassFromSignature(sig
, loader
, endp
);
920 catch (java::lang::NoClassDefFoundError
*ncdfe
)
924 catch (java::lang::ClassNotFoundException
*cnfe
)
933 JvConvertArgv (int argc
, const char **argv
)
937 jobjectArray ar
= JvNewObjectArray(argc
, &java::lang::String::class$
, NULL
);
938 jobject
*ptr
= elements(ar
);
939 jbyteArray bytes
= NULL
;
940 for (int i
= 0; i
< argc
; i
++)
942 const char *arg
= argv
[i
];
943 int len
= strlen (arg
);
944 if (bytes
== NULL
|| bytes
->length
< len
)
945 bytes
= JvNewByteArray (len
);
946 jbyte
*bytePtr
= elements (bytes
);
947 // We assume jbyte == char.
948 memcpy (bytePtr
, arg
, len
);
950 // Now convert using the default encoding.
951 *ptr
++ = new java::lang::String (bytes
, 0, len
);
953 return (JArray
<jstring
>*) ar
;
956 // FIXME: These variables are static so that they will be
957 // automatically scanned by the Boehm collector. This is needed
958 // because with qthreads the collector won't scan the initial stack --
959 // it will only scan the qthreads stacks.
961 // Command line arguments.
962 static JArray
<jstring
> *arg_vec
;
964 // The primary thread.
965 static java::lang::Thread
*main_thread
;
967 #ifndef DISABLE_GETENV_PROPERTIES
970 next_property_key (char *s
, size_t *length
)
976 // Skip over whitespace
980 // If we've reached the end, return NULL. Also return NULL if for
981 // some reason we've come across a malformed property string.
987 // Determine the length of the property key.
1005 next_property_value (char *s
, size_t *length
)
1011 while (isspace (*s
))
1018 while (isspace (*s
))
1021 // Determine the length of the property value.
1040 process_gcj_properties ()
1042 char *props
= getenv("GCJ_PROPERTIES");
1047 // Later on we will write \0s into this string. It is simplest to
1048 // just duplicate it here.
1049 props
= strdup (props
);
1053 size_t property_count
= 0;
1055 // Whip through props quickly in order to count the number of
1057 while (p
&& (p
= next_property_key (p
, &length
)))
1059 // Skip to the end of the key
1062 p
= next_property_value (p
, &length
);
1069 // Allocate an array of property value/key pairs.
1070 _Jv_Environment_Properties
=
1071 (property_pair
*) malloc (sizeof(property_pair
)
1072 * (property_count
+ 1));
1074 // Go through the properties again, initializing _Jv_Properties
1078 while (p
&& (p
= next_property_key (p
, &length
)))
1080 _Jv_Environment_Properties
[property_count
].key
= p
;
1081 _Jv_Environment_Properties
[property_count
].key_length
= length
;
1083 // Skip to the end of the key
1086 p
= next_property_value (p
, &length
);
1088 _Jv_Environment_Properties
[property_count
].value
= p
;
1089 _Jv_Environment_Properties
[property_count
].value_length
= length
;
1096 memset ((void *) &_Jv_Environment_Properties
[property_count
],
1097 0, sizeof (property_pair
));
1099 // Null terminate the strings.
1100 for (property_pair
*prop
= &_Jv_Environment_Properties
[0];
1104 prop
->key
[prop
->key_length
] = 0;
1105 prop
->value
[prop
->value_length
] = 0;
1108 #endif // DISABLE_GETENV_PROPERTIES
1112 _Jv_Utf8Const
*void_signature
;
1113 _Jv_Utf8Const
*clinit_name
;
1114 _Jv_Utf8Const
*init_name
;
1115 _Jv_Utf8Const
*finit_name
;
1117 bool runtimeInitialized
= false;
1119 // When true, print debugging information about class loading.
1120 bool verbose_class_flag
;
1122 // When true, enable the bytecode verifier and BC-ABI type verification.
1123 bool verifyClasses
= true;
1125 // Thread stack size specified by the -Xss runtime argument.
1126 size_t stack_size
= 0;
1128 // Start time of the VM
1129 jlong startTime
= 0;
1131 // Arguments passed to the VM
1132 JArray
<jstring
>* vmArgs
;
1134 // Currently loaded classes
1135 jint loadedClasses
= 0;
1138 jlong unloadedClasses
= 0;
1141 // We accept all non-standard options accepted by Sun's java command,
1142 // for compatibility with existing application launch scripts.
1144 parse_x_arg (char* option_string
)
1146 if (strlen (option_string
) <= 0)
1149 if (! strcmp (option_string
, "int"))
1151 // FIXME: this should cause the vm to never load shared objects
1153 else if (! strcmp (option_string
, "mixed"))
1155 // FIXME: allow interpreted and native code
1157 else if (! strcmp (option_string
, "batch"))
1159 // FIXME: disable background JIT'ing
1161 else if (! strcmp (option_string
, "debug"))
1165 else if (! strncmp (option_string
, "runjdwp:", 8))
1167 if (strlen (option_string
) > 8)
1168 jdwpOptions
= &option_string
[8];
1172 "libgcj: argument required for JDWP options");
1176 else if (! strncmp (option_string
, "bootclasspath:", 14))
1178 // FIXME: add a parse_bootclasspath_arg function
1180 else if (! strncmp (option_string
, "bootclasspath/a:", 16))
1183 else if (! strncmp (option_string
, "bootclasspath/p:", 16))
1186 else if (! strcmp (option_string
, "check:jni"))
1188 // FIXME: enable strict JNI checking
1190 else if (! strcmp (option_string
, "future"))
1192 // FIXME: enable strict class file format checks
1194 else if (! strcmp (option_string
, "noclassgc"))
1196 // FIXME: disable garbage collection for classes
1198 else if (! strcmp (option_string
, "incgc"))
1200 // FIXME: incremental garbage collection
1202 else if (! strncmp (option_string
, "loggc:", 6))
1204 if (option_string
[6] == '\0')
1207 "libgcj: filename argument expected for loggc option\n");
1210 // FIXME: set gc logging filename
1212 else if (! strncmp (option_string
, "ms", 2))
1214 // FIXME: ignore this option until PR 20699 is fixed.
1215 // _Jv_SetInitialHeapSize (option_string + 2);
1217 else if (! strncmp (option_string
, "mx", 2))
1218 _Jv_SetMaximumHeapSize (option_string
+ 2);
1219 else if (! strcmp (option_string
, "prof"))
1221 // FIXME: enable profiling of program running in vm
1223 else if (! strncmp (option_string
, "runhprof:", 9))
1225 // FIXME: enable specific type of vm profiling. add a
1226 // parse_runhprof_arg function
1228 else if (! strcmp (option_string
, "rs"))
1230 // FIXME: reduced system signal usage. disable thread dumps,
1231 // only terminate in response to user-initiated calls,
1232 // e.g. System.exit()
1234 else if (! strncmp (option_string
, "ss", 2))
1236 _Jv_SetStackSize (option_string
+ 2);
1238 else if (! strcmp (option_string
, "X:+UseAltSigs"))
1240 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1242 else if (! strcmp (option_string
, "share:off"))
1244 // FIXME: don't share class data
1246 else if (! strcmp (option_string
, "share:auto"))
1248 // FIXME: share class data where possible
1250 else if (! strcmp (option_string
, "share:on"))
1252 // FIXME: fail if impossible to share class data
1259 parse_verbose_args (char* option_string
,
1260 bool ignore_unrecognized
)
1262 size_t len
= sizeof ("-verbose") - 1;
1264 if (strlen (option_string
) < len
)
1267 if (option_string
[len
] == ':'
1268 && option_string
[len
+ 1] != '\0')
1270 char* verbose_args
= option_string
+ len
+ 1;
1274 if (! strncmp (verbose_args
,
1275 "gc", sizeof ("gc") - 1))
1277 if (verbose_args
[sizeof ("gc") - 1] == '\0'
1278 || verbose_args
[sizeof ("gc") - 1] == ',')
1280 // FIXME: we should add functions to boehm-gc that
1281 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1282 // GC_print_back_height.
1283 verbose_args
+= sizeof ("gc") - 1;
1288 fprintf (stderr
, "libgcj: unknown verbose option: %s\n",
1293 else if (! strncmp (verbose_args
,
1295 sizeof ("class") - 1))
1297 if (verbose_args
[sizeof ("class") - 1] == '\0'
1298 || verbose_args
[sizeof ("class") - 1] == ',')
1300 gcj::verbose_class_flag
= true;
1301 verbose_args
+= sizeof ("class") - 1;
1304 goto verbose_arg_err
;
1306 else if (! strncmp (verbose_args
, "jni",
1307 sizeof ("jni") - 1))
1309 if (verbose_args
[sizeof ("jni") - 1] == '\0'
1310 || verbose_args
[sizeof ("jni") - 1] == ',')
1312 // FIXME: enable JNI messages.
1313 verbose_args
+= sizeof ("jni") - 1;
1316 goto verbose_arg_err
;
1318 else if (ignore_unrecognized
1319 && verbose_args
[0] == 'X')
1321 // ignore unrecognized non-standard verbose option
1322 while (verbose_args
[0] != '\0'
1323 && verbose_args
[0] != ',')
1326 else if (verbose_args
[0] == ',')
1331 goto verbose_arg_err
;
1333 if (verbose_args
[0] == ',')
1336 while (verbose_args
[0] != '\0');
1338 else if (option_string
[len
] == 'g'
1339 && option_string
[len
+ 1] == 'c'
1340 && option_string
[len
+ 2] == '\0')
1342 // FIXME: we should add functions to boehm-gc that
1343 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1344 // GC_print_back_height.
1347 else if (option_string
[len
] == '\0')
1349 gcj::verbose_class_flag
= true;
1354 // unrecognized option beginning with -verbose
1361 parse_init_args (JvVMInitArgs
* vm_args
)
1363 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1364 // re-allocated dynamically.
1365 if (_Jv_Compiler_Properties
)
1367 const char** props
= _Jv_Compiler_Properties
;
1368 _Jv_Compiler_Properties
= NULL
;
1370 for (int i
= 0; props
[i
]; i
++)
1372 _Jv_Compiler_Properties
= (const char**) _Jv_Realloc
1373 (_Jv_Compiler_Properties
,
1374 (_Jv_Properties_Count
+ 1) * sizeof (const char*));
1375 _Jv_Compiler_Properties
[_Jv_Properties_Count
++] = props
[i
];
1379 if (vm_args
== NULL
)
1382 for (int i
= 0; i
< vm_args
->nOptions
; ++i
)
1384 char* option_string
= vm_args
->options
[i
].optionString
;
1385 if (! strcmp (option_string
, "vfprintf")
1386 || ! strcmp (option_string
, "exit")
1387 || ! strcmp (option_string
, "abort"))
1389 // FIXME: we are required to recognize these, but for
1390 // now we don't handle them in any way.
1393 else if (! strncmp (option_string
,
1394 "-verbose", sizeof ("-verbose") - 1))
1396 jint result
= parse_verbose_args (option_string
,
1397 vm_args
->ignoreUnrecognized
);
1401 else if (! strncmp (option_string
, "-D", 2))
1403 _Jv_Compiler_Properties
= (const char**) _Jv_Realloc
1404 (_Jv_Compiler_Properties
,
1405 (_Jv_Properties_Count
+ 1) * sizeof (char*));
1407 _Jv_Compiler_Properties
[_Jv_Properties_Count
++] =
1408 strdup (option_string
+ 2);
1412 else if (vm_args
->ignoreUnrecognized
)
1414 if (option_string
[0] == '_')
1415 parse_x_arg (option_string
+ 1);
1416 else if (! strncmp (option_string
, "-X", 2))
1417 parse_x_arg (option_string
+ 2);
1421 fprintf (stderr
, "libgcj: unknown option: %s\n", option_string
);
1426 goto unknown_option
;
1432 _Jv_CreateJavaVM (JvVMInitArgs
* vm_args
)
1434 using namespace gcj
;
1436 if (runtimeInitialized
)
1439 runtimeInitialized
= true;
1440 startTime
= _Jv_platform_gettimeofday();
1442 jint result
= parse_init_args (vm_args
);
1446 PROCESS_GCJ_PROPERTIES
;
1448 /* Threads must be initialized before the GC, so that it inherits the
1452 _Jv_InitializeSyncMutex ();
1455 _Jv_InitInterpreter ();
1466 /* Initialize Utf8 constants declared in jvm.h. */
1467 void_signature
= _Jv_makeUtf8Const ("()V", 3);
1468 clinit_name
= _Jv_makeUtf8Const ("<clinit>", 8);
1469 init_name
= _Jv_makeUtf8Const ("<init>", 6);
1470 finit_name
= _Jv_makeUtf8Const ("finit$", 6);
1472 /* Initialize built-in classes to represent primitive TYPEs. */
1473 _Jv_InitPrimClass (&_Jv_byteClass
, "byte", 'B', 1);
1474 _Jv_InitPrimClass (&_Jv_shortClass
, "short", 'S', 2);
1475 _Jv_InitPrimClass (&_Jv_intClass
, "int", 'I', 4);
1476 _Jv_InitPrimClass (&_Jv_longClass
, "long", 'J', 8);
1477 _Jv_InitPrimClass (&_Jv_booleanClass
, "boolean", 'Z', 1);
1478 _Jv_InitPrimClass (&_Jv_charClass
, "char", 'C', 2);
1479 _Jv_InitPrimClass (&_Jv_floatClass
, "float", 'F', 4);
1480 _Jv_InitPrimClass (&_Jv_doubleClass
, "double", 'D', 8);
1481 _Jv_InitPrimClass (&_Jv_voidClass
, "void", 'V', 0);
1483 // We have to initialize this fairly early, to avoid circular class
1484 // initialization. In particular we want to start the
1485 // initialization of ClassLoader before we start the initialization
1486 // of VMClassLoader.
1487 _Jv_InitClass (&java::lang::ClassLoader::class$
);
1489 // Set up the system class loader and the bootstrap class loader.
1490 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1491 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR
));
1493 _Jv_RegisterBootstrapPackages();
1495 no_memory
= new java::lang::OutOfMemoryError
;
1498 LTDL_SET_PRELOADED_SYMBOLS ();
1501 _Jv_platform_initialize ();
1506 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady
);
1508 // Start the GC finalizer thread. A VirtualMachineError can be
1509 // thrown by the runtime if, say, threads aren't available.
1512 using namespace gnu::gcj::runtime
;
1513 FinalizerThread
*ft
= new FinalizerThread ();
1516 catch (java::lang::VirtualMachineError
*ignore
)
1520 runtimeInitialized
= true;
1526 _Jv_RunMain (JvVMInitArgs
*vm_args
, jclass klass
, const char *name
, int argc
,
1527 const char **argv
, bool is_jar
)
1529 #ifndef DISABLE_MAIN_ARGS
1530 _Jv_SetArgs (argc
, argv
);
1533 java::lang::Runtime
*runtime
= NULL
;
1537 if (_Jv_CreateJavaVM (vm_args
) < 0)
1539 fprintf (stderr
, "libgcj: couldn't create virtual machine\n");
1543 if (vm_args
== NULL
)
1544 gcj::vmArgs
= JvConvertArgv(0, NULL
);
1547 const char* vmArgs
[vm_args
->nOptions
];
1548 const char** vmPtr
= vmArgs
;
1549 struct _Jv_VMOption
* optionPtr
= vm_args
->options
;
1550 for (int i
= 0; i
< vm_args
->nOptions
; ++i
)
1551 *vmPtr
++ = (*optionPtr
++).optionString
;
1552 gcj::vmArgs
= JvConvertArgv(vm_args
->nOptions
, vmArgs
);
1555 // Get the Runtime here. We want to initialize it before searching
1556 // for `main'; that way it will be set up if `main' is a JNI method.
1557 runtime
= java::lang::Runtime::getRuntime ();
1559 #ifdef DISABLE_MAIN_ARGS
1560 arg_vec
= JvConvertArgv (0, 0);
1562 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
1565 using namespace gnu::java::lang
;
1567 main_thread
= new MainThread (klass
, arg_vec
);
1569 main_thread
= new MainThread (JvNewStringUTF (name
),
1571 _Jv_AttachCurrentThread (main_thread
);
1576 using namespace gnu::classpath::jdwp
;
1577 VMVirtualMachine::initialize ();
1578 Jdwp
*jdwp
= new Jdwp ();
1579 jdwp
->setDaemon (true);
1580 jdwp
->configure (JvNewStringLatin1 (jdwpOptions
));
1583 // Wait for JDWP to initialize and start
1588 if (JVMTI_REQUESTED_EVENT (VMInit
))
1589 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_INIT
, main_thread
);
1591 catch (java::lang::Throwable
*t
)
1593 java::lang::System::err
->println (JvNewStringLatin1
1594 ("Exception during runtime initialization"));
1595 t
->printStackTrace();
1597 java::lang::Runtime::exitNoChecksAccessor (1);
1598 // In case the runtime creation failed.
1602 _Jv_ThreadRun (main_thread
);
1605 if (JVMTI_REQUESTED_EVENT (VMDeath
))
1607 java::lang::Thread
*thread
= java::lang::Thread::currentThread ();
1608 JNIEnv
*jni_env
= _Jv_GetCurrentJNIEnv ();
1609 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_DEATH
, thread
, jni_env
);
1612 // If we got here then something went wrong, as MainThread is not
1613 // supposed to terminate.
1618 _Jv_RunMain (jclass klass
, const char *name
, int argc
, const char **argv
,
1621 _Jv_RunMain (NULL
, klass
, name
, argc
, argv
, is_jar
);
1625 JvRunMain (jclass klass
, int argc
, const char **argv
)
1627 _Jv_RunMain (klass
, NULL
, argc
, argv
, false);
1631 JvRunMainName (const char *name
, int argc
, const char **argv
)
1633 _Jv_RunMain (NULL
, name
, argc
, argv
, false);
1638 // Parse a string and return a heap size.
1640 parse_memory_size (const char *spec
)
1643 unsigned long val
= strtoul (spec
, &end
, 10);
1644 if (*end
== 'k' || *end
== 'K')
1646 else if (*end
== 'm' || *end
== 'M')
1648 return (size_t) val
;
1651 // Set the initial heap size. This might be ignored by the GC layer.
1652 // This must be called before _Jv_RunMain.
1654 _Jv_SetInitialHeapSize (const char *arg
)
1656 size_t size
= parse_memory_size (arg
);
1657 _Jv_GCSetInitialHeapSize (size
);
1660 // Set the maximum heap size. This might be ignored by the GC layer.
1661 // This must be called before _Jv_RunMain.
1663 _Jv_SetMaximumHeapSize (const char *arg
)
1665 size_t size
= parse_memory_size (arg
);
1666 _Jv_GCSetMaximumHeapSize (size
);
1670 _Jv_SetStackSize (const char *arg
)
1672 size_t size
= parse_memory_size (arg
);
1673 gcj::stack_size
= size
;
1677 _Jv_Malloc (jsize size
)
1679 if (__builtin_expect (size
== 0, false))
1681 void *ptr
= malloc ((size_t) size
);
1682 if (__builtin_expect (ptr
== NULL
, false))
1688 _Jv_Realloc (void *ptr
, jsize size
)
1690 if (__builtin_expect (size
== 0, false))
1692 ptr
= realloc (ptr
, (size_t) size
);
1693 if (__builtin_expect (ptr
== NULL
, false))
1699 _Jv_MallocUnchecked (jsize size
)
1701 if (__builtin_expect (size
== 0, false))
1703 return malloc ((size_t) size
);
1707 _Jv_Free (void* ptr
)
1714 // In theory, these routines can be #ifdef'd away on machines which
1715 // support divide overflow signals. However, we never know if some
1716 // code might have been compiled with "-fuse-divide-subroutine", so we
1717 // always include them in libgcj.
1720 _Jv_divI (jint dividend
, jint divisor
)
1722 if (__builtin_expect (divisor
== 0, false))
1724 java::lang::ArithmeticException
*arithexception
1725 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1726 throw arithexception
;
1729 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
1732 return dividend
/ divisor
;
1736 _Jv_remI (jint dividend
, jint divisor
)
1738 if (__builtin_expect (divisor
== 0, false))
1740 java::lang::ArithmeticException
*arithexception
1741 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1742 throw arithexception
;
1745 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
1748 return dividend
% divisor
;
1752 _Jv_divJ (jlong dividend
, jlong divisor
)
1754 if (__builtin_expect (divisor
== 0, false))
1756 java::lang::ArithmeticException
*arithexception
1757 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1758 throw arithexception
;
1761 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1764 return dividend
/ divisor
;
1768 _Jv_remJ (jlong dividend
, jlong divisor
)
1770 if (__builtin_expect (divisor
== 0, false))
1772 java::lang::ArithmeticException
*arithexception
1773 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1774 throw arithexception
;
1777 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1780 return dividend
% divisor
;
1785 // Return true if SELF_KLASS can access a field or method in
1786 // OTHER_KLASS. The field or method's access flags are specified in
1789 _Jv_CheckAccess (jclass self_klass
, jclass other_klass
, jint flags
)
1791 using namespace java::lang::reflect
;
1792 return ((self_klass
== other_klass
)
1793 || ((flags
& Modifier::PUBLIC
) != 0)
1794 || (((flags
& Modifier::PROTECTED
) != 0)
1795 && _Jv_IsAssignableFromSlow (self_klass
, other_klass
))
1796 || (((flags
& Modifier::PRIVATE
) == 0)
1797 && _Jv_ClassNameSamePackage (self_klass
->name
,
1798 other_klass
->name
)));
1801 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1802 // char array, if the path is not already prefixed by
1803 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1804 // result should be freed using JvFree.
1806 _Jv_PrependVersionedLibdir (char* libpath
)
1810 if (libpath
&& libpath
[0] != '\0')
1812 if (! strncmp (libpath
,
1813 GCJ_VERSIONED_LIBDIR
,
1814 sizeof (GCJ_VERSIONED_LIBDIR
) - 1))
1816 // LD_LIBRARY_PATH is already prefixed with
1817 // GCJ_VERSIONED_LIBDIR.
1818 retval
= (char*) _Jv_Malloc (strlen (libpath
) + 1);
1819 strcpy (retval
, libpath
);
1823 // LD_LIBRARY_PATH is not prefixed with
1824 // GCJ_VERSIONED_LIBDIR.
1826 path_sep
[0] = (char) _Jv_platform_path_separator
;
1828 jsize total
= ((sizeof (GCJ_VERSIONED_LIBDIR
) - 1)
1829 + 1 /* path separator */ + strlen (libpath
) + 1);
1830 retval
= (char*) _Jv_Malloc (total
);
1831 strcpy (retval
, GCJ_VERSIONED_LIBDIR
);
1832 strcat (retval
, path_sep
);
1833 strcat (retval
, libpath
);
1838 // LD_LIBRARY_PATH was not specified or is empty.
1839 retval
= (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR
));
1840 strcpy (retval
, GCJ_VERSIONED_LIBDIR
);