acx.m4 (ACX_CHECK_INSTALLED_TARGET_TOOL): Fixup logic for cross builds.
[official-gcc.git] / libjava / prims.cc
blob706ab4b7a3e65f7ef54ba6ecc9207c1088349501
1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 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
9 details. */
11 #include <config.h>
12 #include <platform.h>
14 #include <stdlib.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <signal.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
24 #include <gcj/cni.h>
25 #include <jvm.h>
26 #include <java-signal.h>
27 #include <java-threads.h>
28 #include <java-interp.h>
30 #ifdef ENABLE_JVMPI
31 #include <jvmpi.h>
32 #include <java/lang/ThreadGroup.h>
33 #endif
35 #include <jvmti.h>
36 #include "jvmti-int.h"
38 #ifndef DISABLE_GETENV_PROPERTIES
39 #include <ctype.h>
40 #include <java-props.h>
41 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
42 #else
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>
74 #ifdef USE_LTDL
75 #include <ltdl.h>
76 #endif
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;
100 #endif
102 // Stash the argv pointer to benefit native libraries that need it.
103 const char **_Jv_argv;
104 int _Jv_argc;
106 // Debugging options
107 static bool remoteDebug = false;
108 static char defaultJdwpOptions[] = "";
109 static char *jdwpOptions = defaultJdwpOptions;
111 // Typedefs for JVMTI agent functions.
112 typedef jint jvmti_agent_onload_func (JavaVM *vm, char *options,
113 void *reserved);
114 typedef jint jvmti_agent_onunload_func (JavaVM *vm);
116 // JVMTI agent function pointers.
117 static jvmti_agent_onload_func *jvmti_agentonload = NULL;
118 static jvmti_agent_onunload_func *jvmti_agentonunload = NULL;
119 static char *jvmti_agent_opts;
121 // Argument support.
123 _Jv_GetNbArgs (void)
125 // _Jv_argc is 0 if not explicitly initialized.
126 return _Jv_argc;
129 const char *
130 _Jv_GetSafeArg (int index)
132 if (index >=0 && index < _Jv_GetNbArgs ())
133 return _Jv_argv[index];
134 else
135 return "";
138 void
139 _Jv_SetArgs (int argc, const char **argv)
141 _Jv_argc = argc;
142 _Jv_argv = argv;
145 #ifdef ENABLE_JVMPI
146 // Pointer to JVMPI notification functions.
147 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
148 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
149 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
150 #endif
153 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
154 /* Unblock a signal. Unless we do this, the signal may only be sent
155 once. */
156 static void
157 unblock_signal (int signum __attribute__ ((__unused__)))
159 #ifdef _POSIX_VERSION
160 sigset_t sigs;
162 sigemptyset (&sigs);
163 sigaddset (&sigs, signum);
164 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
165 #endif
167 #endif
169 #ifdef HANDLE_SEGV
170 SIGNAL_HANDLER (catch_segv)
172 unblock_signal (SIGSEGV);
173 MAKE_THROW_FRAME (nullp);
174 java::lang::NullPointerException *nullp
175 = new java::lang::NullPointerException;
176 throw nullp;
178 #endif
180 #ifdef HANDLE_FPE
181 SIGNAL_HANDLER (catch_fpe)
183 unblock_signal (SIGFPE);
184 #ifdef HANDLE_DIVIDE_OVERFLOW
185 HANDLE_DIVIDE_OVERFLOW;
186 #else
187 MAKE_THROW_FRAME (arithexception);
188 #endif
189 java::lang::ArithmeticException *arithexception
190 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
191 throw arithexception;
193 #endif
196 jboolean
197 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
199 int len;
200 const _Jv_ushort *aptr, *bptr;
201 if (a == b)
202 return true;
203 if (a->hash != b->hash)
204 return false;
205 len = a->length;
206 if (b->length != len)
207 return false;
208 aptr = (const _Jv_ushort *)a->data;
209 bptr = (const _Jv_ushort *)b->data;
210 len = (len + 1) >> 1;
211 while (--len >= 0)
212 if (*aptr++ != *bptr++)
213 return false;
214 return true;
217 /* True iff A is equal to STR.
218 HASH is STR->hashCode().
221 jboolean
222 _Jv_equal (Utf8Const* a, jstring str, jint hash)
224 if (a->hash != (_Jv_ushort) hash)
225 return false;
226 jint len = str->length();
227 jint i = 0;
228 jchar *sptr = _Jv_GetStringChars (str);
229 unsigned char* ptr = (unsigned char*) a->data;
230 unsigned char* limit = ptr + a->length;
231 for (;; i++, sptr++)
233 int ch = UTF8_GET (ptr, limit);
234 if (i == len)
235 return ch < 0;
236 if (ch != *sptr)
237 return false;
239 return true;
242 /* Like _Jv_equal, but stop after N characters. */
243 jboolean
244 _Jv_equaln (Utf8Const *a, jstring str, jint n)
246 jint len = str->length();
247 jint i = 0;
248 jchar *sptr = _Jv_GetStringChars (str);
249 unsigned char* ptr = (unsigned char*) a->data;
250 unsigned char* limit = ptr + a->length;
251 for (; n-- > 0; i++, sptr++)
253 int ch = UTF8_GET (ptr, limit);
254 if (i == len)
255 return ch < 0;
256 if (ch != *sptr)
257 return false;
259 return true;
262 // Determines whether the given Utf8Const object contains
263 // a type which is primitive or some derived form of it, eg.
264 // an array or multi-dimensional array variant.
265 jboolean
266 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
268 unsigned char *aptr = (unsigned char *) a->data;
269 unsigned char *alimit = aptr + a->length;
270 int ac = UTF8_GET(aptr, alimit);
272 // Skips any leading array marks.
273 while (ac == '[')
274 ac = UTF8_GET(aptr, alimit);
276 // There should not be another character. This implies that
277 // the type name is only one character long.
278 if (UTF8_GET(aptr, alimit) == -1)
279 switch ( ac )
281 case 'Z':
282 case 'B':
283 case 'C':
284 case 'S':
285 case 'I':
286 case 'J':
287 case 'F':
288 case 'D':
289 return true;
290 default:
291 break;
294 return false;
297 // Find out whether two _Jv_Utf8Const candidates contain the same
298 // classname.
299 // The method is written to handle the different formats of classnames.
300 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
301 // "java.lang.Class" will be seen as equal.
302 // Warning: This function is not smart enough to declare "Z" and "boolean"
303 // and similar cases as equal (and is not meant to be used this way)!
304 jboolean
305 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
307 // If the class name's length differs by two characters
308 // it is possible that we have candidates which are given
309 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
310 switch (a->length - b->length)
312 case -2:
313 case 0:
314 case 2:
315 break;
316 default:
317 return false;
320 unsigned char *aptr = (unsigned char *) a->data;
321 unsigned char *alimit = aptr + a->length;
322 unsigned char *bptr = (unsigned char *) b->data;
323 unsigned char *blimit = bptr + b->length;
325 if (alimit[-1] == ';')
326 alimit--;
328 if (blimit[-1] == ';')
329 blimit--;
331 int ac = UTF8_GET(aptr, alimit);
332 int bc = UTF8_GET(bptr, blimit);
334 // Checks whether both strings have the same amount of leading [ characters.
335 while (ac == '[')
337 if (bc == '[')
339 ac = UTF8_GET(aptr, alimit);
340 bc = UTF8_GET(bptr, blimit);
341 continue;
344 return false;
347 // Skips leading L character.
348 if (ac == 'L')
349 ac = UTF8_GET(aptr, alimit);
351 if (bc == 'L')
352 bc = UTF8_GET(bptr, blimit);
354 // Compares the remaining characters.
355 while (ac != -1 && bc != -1)
357 // Replaces package separating dots with slashes.
358 if (ac == '.')
359 ac = '/';
361 if (bc == '.')
362 bc = '/';
364 // Now classnames differ if there is at least one non-matching
365 // character.
366 if (ac != bc)
367 return false;
369 ac = UTF8_GET(aptr, alimit);
370 bc = UTF8_GET(bptr, blimit);
373 return (ac == bc);
376 /* Count the number of Unicode chars encoded in a given Ut8 string. */
378 _Jv_strLengthUtf8(const char* str, int len)
380 unsigned char* ptr;
381 unsigned char* limit;
382 int str_length;
384 ptr = (unsigned char*) str;
385 limit = ptr + len;
386 str_length = 0;
387 for (; ptr < limit; str_length++)
389 if (UTF8_GET (ptr, limit) < 0)
390 return (-1);
392 return (str_length);
395 /* Calculate a hash value for a string encoded in Utf8 format.
396 * This returns the same hash value as specified or java.lang.String.hashCode.
398 jint
399 _Jv_hashUtf8String (const char* str, int len)
401 unsigned char* ptr = (unsigned char*) str;
402 unsigned char* limit = ptr + len;
403 jint hash = 0;
405 for (; ptr < limit;)
407 int ch = UTF8_GET (ptr, limit);
408 /* Updated specification from
409 http://www.javasoft.com/docs/books/jls/clarify.html. */
410 hash = (31 * hash) + ch;
412 return hash;
415 void
416 _Jv_Utf8Const::init(const char *s, int len)
418 ::memcpy (data, s, len);
419 data[len] = 0;
420 length = len;
421 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
424 _Jv_Utf8Const *
425 _Jv_makeUtf8Const (const char* s, int len)
427 if (len < 0)
428 len = strlen (s);
429 Utf8Const* m
430 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
431 m->init(s, len);
432 return m;
435 _Jv_Utf8Const *
436 _Jv_makeUtf8Const (jstring string)
438 jint hash = string->hashCode ();
439 jint len = _Jv_GetStringUTFLength (string);
441 Utf8Const* m = (Utf8Const*)
442 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
444 m->hash = hash;
445 m->length = len;
447 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
448 m->data[len] = 0;
450 return m;
455 #ifdef DEBUG
456 void
457 _Jv_Abort (const char *function, const char *file, int line,
458 const char *message)
459 #else
460 void
461 _Jv_Abort (const char *, const char *, int, const char *message)
462 #endif
464 #ifdef DEBUG
465 fprintf (stderr,
466 "libgcj failure: %s\n in function %s, file %s, line %d\n",
467 message, function, file, line);
468 #else
469 fprintf (stderr, "libgcj failure: %s\n", message);
470 #endif
471 fflush (stderr);
472 abort ();
475 static void
476 fail_on_finalization (jobject)
478 JvFail ("object was finalized");
481 void
482 _Jv_GCWatch (jobject obj)
484 _Jv_RegisterFinalizer (obj, fail_on_finalization);
487 void
488 _Jv_ThrowBadArrayIndex(jint bad_index)
490 throw new java::lang::ArrayIndexOutOfBoundsException
491 (java::lang::String::valueOf (bad_index));
494 void
495 _Jv_ThrowNullPointerException ()
497 throw new java::lang::NullPointerException;
500 // Resolve an entry in the constant pool and return the target
501 // address.
502 void *
503 _Jv_ResolvePoolEntry (jclass this_class, jint index)
505 _Jv_Constants *pool = &this_class->constants;
507 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
508 return pool->data[index].field->u.addr;
510 JvSynchronize sync (this_class);
511 return (_Jv_Linker::resolve_pool_entry (this_class, index))
512 .field->u.addr;
516 // Explicitly throw a no memory exception.
517 // The collector calls this when it encounters an out-of-memory condition.
518 void _Jv_ThrowNoMemory()
520 throw no_memory;
523 #ifdef ENABLE_JVMPI
524 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
525 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
526 jvmpi_notify_alloc(klass,size,obj);
527 static void
528 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
530 // Service JVMPI allocation request.
531 JVMPI_Event event;
533 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
534 event.env_id = NULL;
535 event.u.obj_alloc.arena_id = 0;
536 event.u.obj_alloc.class_id = (jobjectID) klass;
537 event.u.obj_alloc.is_array = 0;
538 event.u.obj_alloc.size = size;
539 event.u.obj_alloc.obj_id = (jobjectID) obj;
541 // FIXME: This doesn't look right for the Boehm GC. A GC may
542 // already be in progress. _Jv_DisableGC () doesn't wait for it.
543 // More importantly, I don't see the need for disabling GC, since we
544 // blatantly have a pointer to obj on our stack, ensuring that the
545 // object can't be collected. Even for a nonconservative collector,
546 // it appears to me that this must be true, since we are about to
547 // return obj. Isn't this whole approach way too intrusive for
548 // a useful profiling interface? - HB
549 _Jv_DisableGC ();
550 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
551 _Jv_EnableGC ();
553 #else /* !ENABLE_JVMPI */
554 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
555 #endif
557 // Allocate a new object of class KLASS.
558 // First a version that assumes that we have no finalizer, and that
559 // the class is already initialized.
560 // If we know that JVMPI is disabled, this can be replaced by a direct call
561 // to the allocator for the appropriate GC.
562 jobject
563 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
565 jint size = klass->size ();
566 jobject obj = (jobject) _Jv_AllocObj (size, klass);
567 JVMPI_NOTIFY_ALLOC (klass, size, obj);
568 return obj;
571 // And now a version that initializes if necessary.
572 jobject
573 _Jv_AllocObjectNoFinalizer (jclass klass)
575 if (_Jv_IsPhantomClass(klass) )
576 throw new java::lang::NoClassDefFoundError(klass->getName());
578 _Jv_InitClass (klass);
579 jint size = klass->size ();
580 jobject obj = (jobject) _Jv_AllocObj (size, klass);
581 JVMPI_NOTIFY_ALLOC (klass, size, obj);
582 return obj;
585 // And now the general version that registers a finalizer if necessary.
586 jobject
587 _Jv_AllocObject (jclass klass)
589 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
591 // We assume that the compiler only generates calls to this routine
592 // if there really is an interesting finalizer.
593 // Unfortunately, we still have to the dynamic test, since there may
594 // be cni calls to this routine.
595 // Note that on IA64 get_finalizer() returns the starting address of the
596 // function, not a function pointer. Thus this still works.
597 if (klass->vtable->get_finalizer ()
598 != java::lang::Object::class$.vtable->get_finalizer ())
599 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
600 return obj;
603 // Allocate a String, including variable length storage.
604 jstring
605 _Jv_AllocString(jsize len)
607 using namespace java::lang;
609 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
611 // We assert that for strings allocated this way, the data field
612 // will always point to the object itself. Thus there is no reason
613 // for the garbage collector to scan any of it.
614 // Furthermore, we're about to overwrite the string data, so
615 // initialization of the object is not an issue.
617 // String needs no initialization, and there is no finalizer, so
618 // we can go directly to the collector's allocator interface.
619 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
621 obj->data = obj;
622 obj->boffset = sizeof(java::lang::String);
623 obj->count = len;
624 obj->cachedHashCode = 0;
626 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
628 return obj;
631 // A version of the above that assumes the object contains no pointers,
632 // and requires no finalization. This can't happen if we need pointers
633 // to locks.
634 #ifdef JV_HASH_SYNCHRONIZATION
635 jobject
636 _Jv_AllocPtrFreeObject (jclass klass)
638 _Jv_InitClass (klass);
639 jint size = klass->size ();
641 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
643 JVMPI_NOTIFY_ALLOC (klass, size, obj);
645 return obj;
647 #endif /* JV_HASH_SYNCHRONIZATION */
650 // Allocate a new array of Java objects. Each object is of type
651 // `elementClass'. `init' is used to initialize each slot in the
652 // array.
653 jobjectArray
654 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
656 // Creating an array of an unresolved type is impossible. So we throw
657 // the NoClassDefFoundError.
658 if ( _Jv_IsPhantomClass(elementClass) )
659 throw new java::lang::NoClassDefFoundError(elementClass->getName());
661 if (__builtin_expect (count < 0, false))
662 throw new java::lang::NegativeArraySizeException;
664 JvAssert (! elementClass->isPrimitive ());
666 // Ensure that elements pointer is properly aligned.
667 jobjectArray obj = NULL;
668 size_t size = (size_t) elements (obj);
669 // Check for overflow.
670 if (__builtin_expect ((size_t) count >
671 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
672 throw no_memory;
674 size += count * sizeof (jobject);
676 jclass klass = _Jv_GetArrayClass (elementClass,
677 elementClass->getClassLoaderInternal());
679 obj = (jobjectArray) _Jv_AllocArray (size, klass);
680 // Cast away const.
681 jsize *lp = const_cast<jsize *> (&obj->length);
682 *lp = count;
683 // We know the allocator returns zeroed memory. So don't bother
684 // zeroing it again.
685 if (init)
687 jobject *ptr = elements(obj);
688 while (--count >= 0)
689 *ptr++ = init;
691 return obj;
694 // Allocate a new array of primitives. ELTYPE is the type of the
695 // element, COUNT is the size of the array.
696 jobject
697 _Jv_NewPrimArray (jclass eltype, jint count)
699 int elsize = eltype->size();
700 if (__builtin_expect (count < 0, false))
701 throw new java::lang::NegativeArraySizeException;
703 JvAssert (eltype->isPrimitive ());
704 jobject dummy = NULL;
705 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
707 // Check for overflow.
708 if (__builtin_expect ((size_t) count >
709 (MAX_OBJECT_SIZE - size) / elsize, false))
710 throw no_memory;
712 jclass klass = _Jv_GetArrayClass (eltype, 0);
714 # ifdef JV_HASH_SYNCHRONIZATION
715 // Since the vtable is always statically allocated,
716 // these are completely pointerfree! Make sure the GC doesn't touch them.
717 __JArray *arr =
718 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
719 memset((char *)arr + size, 0, elsize * count);
720 # else
721 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
722 // Note that we assume we are given zeroed memory by the allocator.
723 # endif
724 // Cast away const.
725 jsize *lp = const_cast<jsize *> (&arr->length);
726 *lp = count;
728 return arr;
731 jobject
732 _Jv_NewArray (jint type, jint size)
734 switch (type)
736 case 4: return JvNewBooleanArray (size);
737 case 5: return JvNewCharArray (size);
738 case 6: return JvNewFloatArray (size);
739 case 7: return JvNewDoubleArray (size);
740 case 8: return JvNewByteArray (size);
741 case 9: return JvNewShortArray (size);
742 case 10: return JvNewIntArray (size);
743 case 11: return JvNewLongArray (size);
745 throw new java::lang::InternalError
746 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
749 // Allocate a possibly multi-dimensional array but don't check that
750 // any array length is <0.
751 static jobject
752 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
754 JvAssert (type->isArray());
755 jclass element_type = type->getComponentType();
756 jobject result;
757 if (element_type->isPrimitive())
758 result = _Jv_NewPrimArray (element_type, sizes[0]);
759 else
760 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
762 if (dimensions > 1)
764 JvAssert (! element_type->isPrimitive());
765 JvAssert (element_type->isArray());
766 jobject *contents = elements ((jobjectArray) result);
767 for (int i = 0; i < sizes[0]; ++i)
768 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
769 sizes + 1);
772 return result;
775 jobject
776 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
778 for (int i = 0; i < dimensions; ++i)
779 if (sizes[i] < 0)
780 throw new java::lang::NegativeArraySizeException;
782 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
785 jobject
786 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
788 // Creating an array of an unresolved type is impossible. So we throw
789 // the NoClassDefFoundError.
790 if (_Jv_IsPhantomClass(array_type))
791 throw new java::lang::NoClassDefFoundError(array_type->getName());
793 va_list args;
794 jint sizes[dimensions];
795 va_start (args, dimensions);
796 for (int i = 0; i < dimensions; ++i)
798 jint size = va_arg (args, jint);
799 if (size < 0)
800 throw new java::lang::NegativeArraySizeException;
801 sizes[i] = size;
803 va_end (args);
805 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
810 // Ensure 8-byte alignment, for hash synchronization.
811 #define DECLARE_PRIM_TYPE(NAME) \
812 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
814 DECLARE_PRIM_TYPE(byte)
815 DECLARE_PRIM_TYPE(short)
816 DECLARE_PRIM_TYPE(int)
817 DECLARE_PRIM_TYPE(long)
818 DECLARE_PRIM_TYPE(boolean)
819 DECLARE_PRIM_TYPE(char)
820 DECLARE_PRIM_TYPE(float)
821 DECLARE_PRIM_TYPE(double)
822 DECLARE_PRIM_TYPE(void)
824 void
825 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
827 using namespace java::lang::reflect;
829 // We must set the vtable for the class; the Java constructor
830 // doesn't do this.
831 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
833 // Initialize the fields we care about. We do this in the same
834 // order they are declared in Class.h.
835 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
836 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
837 cl->method_count = sig;
838 cl->size_in_bytes = len;
839 cl->vtable = JV_PRIMITIVE_VTABLE;
840 cl->state = JV_STATE_DONE;
841 cl->depth = -1;
844 jclass
845 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
846 char **endp)
848 // First count arrays.
849 int array_count = 0;
850 while (*sig == '[')
852 ++sig;
853 ++array_count;
856 jclass result = NULL;
857 switch (*sig)
859 case 'B':
860 result = JvPrimClass (byte);
861 break;
862 case 'S':
863 result = JvPrimClass (short);
864 break;
865 case 'I':
866 result = JvPrimClass (int);
867 break;
868 case 'J':
869 result = JvPrimClass (long);
870 break;
871 case 'Z':
872 result = JvPrimClass (boolean);
873 break;
874 case 'C':
875 result = JvPrimClass (char);
876 break;
877 case 'F':
878 result = JvPrimClass (float);
879 break;
880 case 'D':
881 result = JvPrimClass (double);
882 break;
883 case 'V':
884 result = JvPrimClass (void);
885 break;
886 case 'L':
888 char *save = ++sig;
889 while (*sig && *sig != ';')
890 ++sig;
891 // Do nothing if signature appears to be malformed.
892 if (*sig == ';')
894 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
895 result = _Jv_FindClass (name, loader);
897 break;
899 default:
900 // Do nothing -- bad signature.
901 break;
904 if (endp)
906 // Not really the "end", but the last valid character that we
907 // looked at.
908 *endp = sig;
911 if (! result)
912 return NULL;
914 // Find arrays.
915 while (array_count-- > 0)
916 result = _Jv_GetArrayClass (result, loader);
917 return result;
921 jclass
922 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
923 char **endp)
925 jclass klass;
929 klass = _Jv_FindClassFromSignature(sig, loader, endp);
931 catch (java::lang::NoClassDefFoundError *ncdfe)
933 return NULL;
935 catch (java::lang::ClassNotFoundException *cnfe)
937 return NULL;
940 return klass;
943 JArray<jstring> *
944 JvConvertArgv (int argc, const char **argv)
946 if (argc < 0)
947 argc = 0;
948 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
949 jobject *ptr = elements(ar);
950 jbyteArray bytes = NULL;
951 for (int i = 0; i < argc; i++)
953 const char *arg = argv[i];
954 int len = strlen (arg);
955 if (bytes == NULL || bytes->length < len)
956 bytes = JvNewByteArray (len);
957 jbyte *bytePtr = elements (bytes);
958 // We assume jbyte == char.
959 memcpy (bytePtr, arg, len);
961 // Now convert using the default encoding.
962 *ptr++ = new java::lang::String (bytes, 0, len);
964 return (JArray<jstring>*) ar;
967 // FIXME: These variables are static so that they will be
968 // automatically scanned by the Boehm collector. This is needed
969 // because with qthreads the collector won't scan the initial stack --
970 // it will only scan the qthreads stacks.
972 // Command line arguments.
973 static JArray<jstring> *arg_vec;
975 // The primary thread.
976 static java::lang::Thread *main_thread;
978 #ifndef DISABLE_GETENV_PROPERTIES
980 static char *
981 next_property_key (char *s, size_t *length)
983 size_t l = 0;
985 JvAssert (s);
987 // Skip over whitespace
988 while (isspace (*s))
989 s++;
991 // If we've reached the end, return NULL. Also return NULL if for
992 // some reason we've come across a malformed property string.
993 if (*s == 0
994 || *s == ':'
995 || *s == '=')
996 return NULL;
998 // Determine the length of the property key.
999 while (s[l] != 0
1000 && ! isspace (s[l])
1001 && s[l] != ':'
1002 && s[l] != '=')
1004 if (s[l] == '\\'
1005 && s[l+1] != 0)
1006 l++;
1007 l++;
1010 *length = l;
1012 return s;
1015 static char *
1016 next_property_value (char *s, size_t *length)
1018 size_t l = 0;
1020 JvAssert (s);
1022 while (isspace (*s))
1023 s++;
1025 if (*s == ':'
1026 || *s == '=')
1027 s++;
1029 while (isspace (*s))
1030 s++;
1032 // Determine the length of the property value.
1033 while (s[l] != 0
1034 && ! isspace (s[l])
1035 && s[l] != ':'
1036 && s[l] != '=')
1038 if (s[l] == '\\'
1039 && s[l+1] != 0)
1040 l += 2;
1041 else
1042 l++;
1045 *length = l;
1047 return s;
1050 static void
1051 process_gcj_properties ()
1053 char *props = getenv("GCJ_PROPERTIES");
1055 if (NULL == props)
1056 return;
1058 // Later on we will write \0s into this string. It is simplest to
1059 // just duplicate it here.
1060 props = strdup (props);
1062 char *p = props;
1063 size_t length;
1064 size_t property_count = 0;
1066 // Whip through props quickly in order to count the number of
1067 // property values.
1068 while (p && (p = next_property_key (p, &length)))
1070 // Skip to the end of the key
1071 p += length;
1073 p = next_property_value (p, &length);
1074 if (p)
1075 p += length;
1077 property_count++;
1080 // Allocate an array of property value/key pairs.
1081 _Jv_Environment_Properties =
1082 (property_pair *) malloc (sizeof(property_pair)
1083 * (property_count + 1));
1085 // Go through the properties again, initializing _Jv_Properties
1086 // along the way.
1087 p = props;
1088 property_count = 0;
1089 while (p && (p = next_property_key (p, &length)))
1091 _Jv_Environment_Properties[property_count].key = p;
1092 _Jv_Environment_Properties[property_count].key_length = length;
1094 // Skip to the end of the key
1095 p += length;
1097 p = next_property_value (p, &length);
1099 _Jv_Environment_Properties[property_count].value = p;
1100 _Jv_Environment_Properties[property_count].value_length = length;
1102 if (p)
1103 p += length;
1105 property_count++;
1107 memset ((void *) &_Jv_Environment_Properties[property_count],
1108 0, sizeof (property_pair));
1110 // Null terminate the strings.
1111 for (property_pair *prop = &_Jv_Environment_Properties[0];
1112 prop->key != NULL;
1113 prop++)
1115 prop->key[prop->key_length] = 0;
1116 prop->value[prop->value_length] = 0;
1119 #endif // DISABLE_GETENV_PROPERTIES
1121 namespace gcj
1123 _Jv_Utf8Const *void_signature;
1124 _Jv_Utf8Const *clinit_name;
1125 _Jv_Utf8Const *init_name;
1126 _Jv_Utf8Const *finit_name;
1128 bool runtimeInitialized = false;
1130 // When true, print debugging information about class loading.
1131 bool verbose_class_flag;
1133 // When true, enable the bytecode verifier and BC-ABI type verification.
1134 bool verifyClasses = true;
1136 // Thread stack size specified by the -Xss runtime argument.
1137 size_t stack_size = 0;
1139 // Start time of the VM
1140 jlong startTime = 0;
1142 // Arguments passed to the VM
1143 JArray<jstring>* vmArgs;
1145 // Currently loaded classes
1146 jint loadedClasses = 0;
1148 // Unloaded classes
1149 jlong unloadedClasses = 0;
1152 // We accept all non-standard options accepted by Sun's java command,
1153 // for compatibility with existing application launch scripts.
1154 static jint
1155 parse_x_arg (char* option_string)
1157 if (strlen (option_string) <= 0)
1158 return -1;
1160 if (! strcmp (option_string, "int"))
1162 // FIXME: this should cause the vm to never load shared objects
1164 else if (! strcmp (option_string, "mixed"))
1166 // FIXME: allow interpreted and native code
1168 else if (! strcmp (option_string, "batch"))
1170 // FIXME: disable background JIT'ing
1172 else if (! strcmp (option_string, "debug"))
1174 remoteDebug = true;
1176 else if (! strncmp (option_string, "runjdwp:", 8))
1178 if (strlen (option_string) > 8)
1179 jdwpOptions = &option_string[8];
1180 else
1182 fprintf (stderr,
1183 "libgcj: argument required for JDWP options");
1184 return -1;
1187 else if (! strncmp (option_string, "bootclasspath:", 14))
1189 // FIXME: add a parse_bootclasspath_arg function
1191 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1194 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1197 else if (! strcmp (option_string, "check:jni"))
1199 // FIXME: enable strict JNI checking
1201 else if (! strcmp (option_string, "future"))
1203 // FIXME: enable strict class file format checks
1205 else if (! strcmp (option_string, "noclassgc"))
1207 // FIXME: disable garbage collection for classes
1209 else if (! strcmp (option_string, "incgc"))
1211 // FIXME: incremental garbage collection
1213 else if (! strncmp (option_string, "loggc:", 6))
1215 if (option_string[6] == '\0')
1217 fprintf (stderr,
1218 "libgcj: filename argument expected for loggc option\n");
1219 return -1;
1221 // FIXME: set gc logging filename
1223 else if (! strncmp (option_string, "ms", 2))
1225 // FIXME: ignore this option until PR 20699 is fixed.
1226 // _Jv_SetInitialHeapSize (option_string + 2);
1228 else if (! strncmp (option_string, "mx", 2))
1229 _Jv_SetMaximumHeapSize (option_string + 2);
1230 else if (! strcmp (option_string, "prof"))
1232 // FIXME: enable profiling of program running in vm
1234 else if (! strncmp (option_string, "runhprof:", 9))
1236 // FIXME: enable specific type of vm profiling. add a
1237 // parse_runhprof_arg function
1239 else if (! strcmp (option_string, "rs"))
1241 // FIXME: reduced system signal usage. disable thread dumps,
1242 // only terminate in response to user-initiated calls,
1243 // e.g. System.exit()
1245 else if (! strncmp (option_string, "ss", 2))
1247 _Jv_SetStackSize (option_string + 2);
1249 else if (! strcmp (option_string, "X:+UseAltSigs"))
1251 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1253 else if (! strcmp (option_string, "share:off"))
1255 // FIXME: don't share class data
1257 else if (! strcmp (option_string, "share:auto"))
1259 // FIXME: share class data where possible
1261 else if (! strcmp (option_string, "share:on"))
1263 // FIXME: fail if impossible to share class data
1266 return 0;
1269 static jint
1270 parse_verbose_args (char* option_string,
1271 bool ignore_unrecognized)
1273 size_t len = sizeof ("-verbose") - 1;
1275 if (strlen (option_string) < len)
1276 return -1;
1278 if (option_string[len] == ':'
1279 && option_string[len + 1] != '\0')
1281 char* verbose_args = option_string + len + 1;
1285 if (! strncmp (verbose_args,
1286 "gc", sizeof ("gc") - 1))
1288 if (verbose_args[sizeof ("gc") - 1] == '\0'
1289 || verbose_args[sizeof ("gc") - 1] == ',')
1291 // FIXME: we should add functions to boehm-gc that
1292 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1293 // GC_print_back_height.
1294 verbose_args += sizeof ("gc") - 1;
1296 else
1298 verbose_arg_err:
1299 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1300 option_string);
1301 return -1;
1304 else if (! strncmp (verbose_args,
1305 "class",
1306 sizeof ("class") - 1))
1308 if (verbose_args[sizeof ("class") - 1] == '\0'
1309 || verbose_args[sizeof ("class") - 1] == ',')
1311 gcj::verbose_class_flag = true;
1312 verbose_args += sizeof ("class") - 1;
1314 else
1315 goto verbose_arg_err;
1317 else if (! strncmp (verbose_args, "jni",
1318 sizeof ("jni") - 1))
1320 if (verbose_args[sizeof ("jni") - 1] == '\0'
1321 || verbose_args[sizeof ("jni") - 1] == ',')
1323 // FIXME: enable JNI messages.
1324 verbose_args += sizeof ("jni") - 1;
1326 else
1327 goto verbose_arg_err;
1329 else if (ignore_unrecognized
1330 && verbose_args[0] == 'X')
1332 // ignore unrecognized non-standard verbose option
1333 while (verbose_args[0] != '\0'
1334 && verbose_args[0] != ',')
1335 verbose_args++;
1337 else if (verbose_args[0] == ',')
1339 verbose_args++;
1341 else
1342 goto verbose_arg_err;
1344 if (verbose_args[0] == ',')
1345 verbose_args++;
1347 while (verbose_args[0] != '\0');
1349 else if (option_string[len] == 'g'
1350 && option_string[len + 1] == 'c'
1351 && option_string[len + 2] == '\0')
1353 // FIXME: we should add functions to boehm-gc that
1354 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1355 // GC_print_back_height.
1356 return 0;
1358 else if (option_string[len] == '\0')
1360 gcj::verbose_class_flag = true;
1361 return 0;
1363 else
1365 // unrecognized option beginning with -verbose
1366 return -1;
1368 return 0;
1371 // This function loads the agent functions for JVMTI from the library indicated
1372 // by name. It returns a negative value on failure, the value of which
1373 // indicates where ltdl failed, it also prints an error message.
1374 static jint
1375 load_jvmti_agent (const char *name)
1377 #ifdef USE_LTDL
1378 if (lt_dlinit ())
1380 fprintf (stderr,
1381 "libgcj: Error in ltdl init while loading agent library.\n");
1382 return -1;
1385 lt_dlhandle lib = lt_dlopenext (name);
1386 if (!lib)
1388 fprintf (stderr,
1389 "libgcj: Error opening agent library.\n");
1390 return -2;
1393 if (lib)
1395 jvmti_agentonload
1396 = (jvmti_agent_onload_func *) lt_dlsym (lib, "Agent_OnLoad");
1398 if (!jvmti_agentonload)
1400 fprintf (stderr,
1401 "libgcj: Error finding agent function in library %s.\n",
1402 name);
1403 lt_dlclose (lib);
1404 lib = NULL;
1405 return -4;
1407 else
1409 jvmti_agentonunload
1410 = (jvmti_agent_onunload_func *) lt_dlsym (lib, "Agent_OnUnload");
1412 return 0;
1415 else
1417 fprintf (stderr, "libgcj: Library %s not found in library path.\n", name);
1418 return -3;
1421 #endif /* USE_LTDL */
1423 // If LTDL cannot be used, return an error code indicating this.
1424 return -99;
1427 static jint
1428 parse_init_args (JvVMInitArgs* vm_args)
1430 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1431 // re-allocated dynamically.
1432 if (_Jv_Compiler_Properties)
1434 const char** props = _Jv_Compiler_Properties;
1435 _Jv_Compiler_Properties = NULL;
1437 for (int i = 0; props[i]; i++)
1439 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1440 (_Jv_Compiler_Properties,
1441 (_Jv_Properties_Count + 1) * sizeof (const char*));
1442 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1446 if (vm_args == NULL)
1447 return 0;
1449 for (int i = 0; i < vm_args->nOptions; ++i)
1451 char* option_string = vm_args->options[i].optionString;
1453 if (! strcmp (option_string, "vfprintf")
1454 || ! strcmp (option_string, "exit")
1455 || ! strcmp (option_string, "abort"))
1457 // FIXME: we are required to recognize these, but for
1458 // now we don't handle them in any way.
1459 continue;
1461 else if (! strncmp (option_string,
1462 "-verbose", sizeof ("-verbose") - 1))
1464 jint result = parse_verbose_args (option_string,
1465 vm_args->ignoreUnrecognized);
1466 if (result < 0)
1467 return result;
1469 else if (! strncmp (option_string, "-D", 2))
1471 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1472 (_Jv_Compiler_Properties,
1473 (_Jv_Properties_Count + 1) * sizeof (char*));
1475 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1476 strdup (option_string + 2);
1478 continue;
1480 else if (! strncmp (option_string, "-agentlib", sizeof ("-agentlib") - 1))
1482 char *strPtr;
1484 if (strlen(option_string) > (sizeof ("-agentlib:") - 1))
1485 strPtr = &option_string[sizeof ("-agentlib:") - 1];
1486 else
1488 fprintf (stderr,
1489 "libgcj: Malformed agentlib argument %s: expected lib name\n",
1490 option_string);
1491 return -1;
1494 // These are optional arguments to pass to the agent library.
1495 jvmti_agent_opts = strchr (strPtr, '=');
1497 if (! strncmp (strPtr, "jdwp", 4))
1499 // We want to run JDWP here so set the correct variables.
1500 remoteDebug = true;
1501 jdwpOptions = ++jvmti_agent_opts;
1503 else
1505 jint nameLength;
1507 if (jvmti_agent_opts == NULL)
1508 nameLength = strlen (strPtr);
1509 else
1511 nameLength = jvmti_agent_opts - strPtr;
1512 jvmti_agent_opts++;
1515 char lib_name[nameLength + 3 + 1];
1516 strcpy (lib_name, "lib");
1517 strncat (lib_name, strPtr, nameLength);
1519 jint result = load_jvmti_agent (lib_name);
1521 if (result < 0)
1523 return -1;
1526 // Mark JVMTI active
1527 JVMTI::enabled = true;
1530 continue;
1532 else if (! strncmp (option_string, "-agentpath:",
1533 sizeof ("-agentpath:") - 1))
1535 char *strPtr;
1537 if (strlen(option_string) > 10)
1538 strPtr = &option_string[10];
1539 else
1541 fprintf (stderr,
1542 "libgcj: Malformed agentlib argument %s: expected lib path\n",
1543 option_string);
1544 return -1;
1547 // These are optional arguments to pass to the agent library.
1548 jvmti_agent_opts = strchr (strPtr, '=');
1550 jint nameLength;
1552 if (jvmti_agent_opts == NULL)
1553 nameLength = strlen (strPtr);
1554 else
1556 nameLength = jvmti_agent_opts - strPtr;
1557 jvmti_agent_opts++;
1560 char lib_name[nameLength + 3 + 1];
1561 strcpy (lib_name, "lib");
1562 strncat (lib_name, strPtr, nameLength);
1563 jint result = load_jvmti_agent (strPtr);
1565 if (result < 0)
1567 return -1;
1570 // Mark JVMTI active
1571 JVMTI::enabled = true;
1572 continue;
1574 else if (vm_args->ignoreUnrecognized)
1576 if (option_string[0] == '_')
1577 parse_x_arg (option_string + 1);
1578 else if (! strncmp (option_string, "-X", 2))
1579 parse_x_arg (option_string + 2);
1580 else
1582 unknown_option:
1583 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1584 return -1;
1587 else
1588 goto unknown_option;
1590 return 0;
1593 jint
1594 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1596 using namespace gcj;
1598 if (runtimeInitialized)
1599 return -1;
1601 runtimeInitialized = true;
1602 startTime = _Jv_platform_gettimeofday();
1604 jint result = parse_init_args (vm_args);
1605 if (result < 0)
1606 return -1;
1608 PROCESS_GCJ_PROPERTIES;
1610 /* Threads must be initialized before the GC, so that it inherits the
1611 signal mask. */
1612 _Jv_InitThreads ();
1613 _Jv_InitGC ();
1614 _Jv_InitializeSyncMutex ();
1616 #ifdef INTERPRETER
1617 _Jv_InitInterpreter ();
1618 #endif
1620 #ifdef HANDLE_SEGV
1621 INIT_SEGV;
1622 #endif
1624 #ifdef HANDLE_FPE
1625 INIT_FPE;
1626 #endif
1628 /* Initialize Utf8 constants declared in jvm.h. */
1629 void_signature = _Jv_makeUtf8Const ("()V", 3);
1630 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1631 init_name = _Jv_makeUtf8Const ("<init>", 6);
1632 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1634 /* Initialize built-in classes to represent primitive TYPEs. */
1635 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1636 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1637 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1638 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1639 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1640 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1641 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1642 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1643 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1645 // We have to initialize this fairly early, to avoid circular class
1646 // initialization. In particular we want to start the
1647 // initialization of ClassLoader before we start the initialization
1648 // of VMClassLoader.
1649 _Jv_InitClass (&java::lang::ClassLoader::class$);
1651 // Set up the system class loader and the bootstrap class loader.
1652 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1653 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1655 _Jv_RegisterBootstrapPackages();
1657 no_memory = new java::lang::OutOfMemoryError;
1659 #ifdef USE_LTDL
1660 LTDL_SET_PRELOADED_SYMBOLS ();
1661 #endif
1663 _Jv_platform_initialize ();
1665 _Jv_JNI_Init ();
1666 _Jv_JVMTI_Init ();
1668 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1670 // Start the GC finalizer thread. A VirtualMachineError can be
1671 // thrown by the runtime if, say, threads aren't available.
1674 using namespace gnu::gcj::runtime;
1675 FinalizerThread *ft = new FinalizerThread ();
1676 ft->start ();
1678 catch (java::lang::VirtualMachineError *ignore)
1682 runtimeInitialized = true;
1684 return 0;
1687 void
1688 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1689 const char **argv, bool is_jar)
1691 #ifndef DISABLE_MAIN_ARGS
1692 _Jv_SetArgs (argc, argv);
1693 #endif
1695 java::lang::Runtime *runtime = NULL;
1699 if (_Jv_CreateJavaVM (vm_args) < 0)
1701 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1702 exit (1);
1705 if (vm_args == NULL)
1706 gcj::vmArgs = JvConvertArgv(0, NULL);
1707 else
1709 const char* vmArgs[vm_args->nOptions];
1710 const char** vmPtr = vmArgs;
1711 struct _Jv_VMOption* optionPtr = vm_args->options;
1712 for (int i = 0; i < vm_args->nOptions; ++i)
1713 *vmPtr++ = (*optionPtr++).optionString;
1714 gcj::vmArgs = JvConvertArgv(vm_args->nOptions, vmArgs);
1717 // Get the Runtime here. We want to initialize it before searching
1718 // for `main'; that way it will be set up if `main' is a JNI method.
1719 runtime = java::lang::Runtime::getRuntime ();
1721 #ifdef DISABLE_MAIN_ARGS
1722 arg_vec = JvConvertArgv (0, 0);
1723 #else
1724 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1725 #endif
1727 using namespace gnu::java::lang;
1728 if (klass)
1729 main_thread = new MainThread (klass, arg_vec);
1730 else
1731 main_thread = new MainThread (JvNewStringUTF (name),
1732 arg_vec, is_jar);
1733 _Jv_AttachCurrentThread (main_thread);
1735 // Start JVMTI if an agent function has been found.
1736 if (jvmti_agentonload)
1737 (*jvmti_agentonload) (_Jv_GetJavaVM (), jvmti_agent_opts, NULL);
1739 // Start JDWP
1740 if (remoteDebug)
1742 using namespace gnu::classpath::jdwp;
1743 VMVirtualMachine::initialize ();
1744 Jdwp *jdwp = new Jdwp ();
1745 jdwp->setDaemon (true);
1746 jdwp->configure (JvNewStringLatin1 (jdwpOptions));
1747 jdwp->start ();
1749 // Wait for JDWP to initialize and start
1750 jdwp->join ();
1752 // Send VMInit
1753 if (JVMTI_REQUESTED_EVENT (VMInit))
1754 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_INIT, main_thread);
1756 catch (java::lang::Throwable *t)
1758 java::lang::System::err->println (JvNewStringLatin1
1759 ("Exception during runtime initialization"));
1760 t->printStackTrace();
1761 if (runtime)
1762 java::lang::Runtime::exitNoChecksAccessor (1);
1763 // In case the runtime creation failed.
1764 ::exit (1);
1767 _Jv_ThreadRun (main_thread);
1769 // Send VMDeath
1770 if (JVMTI_REQUESTED_EVENT (VMDeath))
1772 java::lang::Thread *thread = java::lang::Thread::currentThread ();
1773 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
1774 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_DEATH, thread, jni_env);
1777 // Run JVMTI AgentOnUnload if it exists and an agent is loaded.
1778 if (jvmti_agentonunload)
1779 (*jvmti_agentonunload) (_Jv_GetJavaVM ());
1781 // If we got here then something went wrong, as MainThread is not
1782 // supposed to terminate.
1783 ::exit (1);
1786 void
1787 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1788 bool is_jar)
1790 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1793 void
1794 JvRunMain (jclass klass, int argc, const char **argv)
1796 _Jv_RunMain (klass, NULL, argc, argv, false);
1799 void
1800 JvRunMainName (const char *name, int argc, const char **argv)
1802 _Jv_RunMain (NULL, name, argc, argv, false);
1807 // Parse a string and return a heap size.
1808 static size_t
1809 parse_memory_size (const char *spec)
1811 char *end;
1812 unsigned long val = strtoul (spec, &end, 10);
1813 if (*end == 'k' || *end == 'K')
1814 val *= 1024;
1815 else if (*end == 'm' || *end == 'M')
1816 val *= 1048576;
1817 return (size_t) val;
1820 // Set the initial heap size. This might be ignored by the GC layer.
1821 // This must be called before _Jv_RunMain.
1822 void
1823 _Jv_SetInitialHeapSize (const char *arg)
1825 size_t size = parse_memory_size (arg);
1826 _Jv_GCSetInitialHeapSize (size);
1829 // Set the maximum heap size. This might be ignored by the GC layer.
1830 // This must be called before _Jv_RunMain.
1831 void
1832 _Jv_SetMaximumHeapSize (const char *arg)
1834 size_t size = parse_memory_size (arg);
1835 _Jv_GCSetMaximumHeapSize (size);
1838 void
1839 _Jv_SetStackSize (const char *arg)
1841 size_t size = parse_memory_size (arg);
1842 gcj::stack_size = size;
1845 void *
1846 _Jv_Malloc (jsize size)
1848 if (__builtin_expect (size == 0, false))
1849 size = 1;
1850 void *ptr = malloc ((size_t) size);
1851 if (__builtin_expect (ptr == NULL, false))
1852 throw no_memory;
1853 return ptr;
1856 void *
1857 _Jv_Realloc (void *ptr, jsize size)
1859 if (__builtin_expect (size == 0, false))
1860 size = 1;
1861 ptr = realloc (ptr, (size_t) size);
1862 if (__builtin_expect (ptr == NULL, false))
1863 throw no_memory;
1864 return ptr;
1867 void *
1868 _Jv_MallocUnchecked (jsize size)
1870 if (__builtin_expect (size == 0, false))
1871 size = 1;
1872 return malloc ((size_t) size);
1875 void
1876 _Jv_Free (void* ptr)
1878 return free (ptr);
1883 // In theory, these routines can be #ifdef'd away on machines which
1884 // support divide overflow signals. However, we never know if some
1885 // code might have been compiled with "-fuse-divide-subroutine", so we
1886 // always include them in libgcj.
1888 jint
1889 _Jv_divI (jint dividend, jint divisor)
1891 if (__builtin_expect (divisor == 0, false))
1893 java::lang::ArithmeticException *arithexception
1894 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1895 throw arithexception;
1898 if (dividend == (jint) 0x80000000L && divisor == -1)
1899 return dividend;
1901 return dividend / divisor;
1904 jint
1905 _Jv_remI (jint dividend, jint divisor)
1907 if (__builtin_expect (divisor == 0, false))
1909 java::lang::ArithmeticException *arithexception
1910 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1911 throw arithexception;
1914 if (dividend == (jint) 0x80000000L && divisor == -1)
1915 return 0;
1917 return dividend % divisor;
1920 jlong
1921 _Jv_divJ (jlong dividend, jlong divisor)
1923 if (__builtin_expect (divisor == 0, false))
1925 java::lang::ArithmeticException *arithexception
1926 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1927 throw arithexception;
1930 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1931 return dividend;
1933 return dividend / divisor;
1936 jlong
1937 _Jv_remJ (jlong dividend, jlong divisor)
1939 if (__builtin_expect (divisor == 0, false))
1941 java::lang::ArithmeticException *arithexception
1942 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1943 throw arithexception;
1946 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1947 return 0;
1949 return dividend % divisor;
1954 // Return true if SELF_KLASS can access a field or method in
1955 // OTHER_KLASS. The field or method's access flags are specified in
1956 // FLAGS.
1957 jboolean
1958 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1960 using namespace java::lang::reflect;
1961 return ((self_klass == other_klass)
1962 || ((flags & Modifier::PUBLIC) != 0)
1963 || (((flags & Modifier::PROTECTED) != 0)
1964 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1965 || (((flags & Modifier::PRIVATE) == 0)
1966 && _Jv_ClassNameSamePackage (self_klass->name,
1967 other_klass->name)));
1970 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1971 // char array, if the path is not already prefixed by
1972 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1973 // result should be freed using JvFree.
1974 char*
1975 _Jv_PrependVersionedLibdir (char* libpath)
1977 char* retval = 0;
1979 if (libpath && libpath[0] != '\0')
1981 if (! strncmp (libpath,
1982 GCJ_VERSIONED_LIBDIR,
1983 sizeof (GCJ_VERSIONED_LIBDIR) - 1))
1985 // LD_LIBRARY_PATH is already prefixed with
1986 // GCJ_VERSIONED_LIBDIR.
1987 retval = (char*) _Jv_Malloc (strlen (libpath) + 1);
1988 strcpy (retval, libpath);
1990 else
1992 // LD_LIBRARY_PATH is not prefixed with
1993 // GCJ_VERSIONED_LIBDIR.
1994 char path_sep[2];
1995 path_sep[0] = (char) _Jv_platform_path_separator;
1996 path_sep[1] = '\0';
1997 jsize total = ((sizeof (GCJ_VERSIONED_LIBDIR) - 1)
1998 + 1 /* path separator */ + strlen (libpath) + 1);
1999 retval = (char*) _Jv_Malloc (total);
2000 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2001 strcat (retval, path_sep);
2002 strcat (retval, libpath);
2005 else
2007 // LD_LIBRARY_PATH was not specified or is empty.
2008 retval = (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR));
2009 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2012 return retval;