PR middle-end/PR28690
[official-gcc.git] / libjava / prims.cc
blob5d3a260e9d0681e82cbd4ee62aaa584da9bb6da3
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
1265 else
1267 // Unrecognized.
1268 return -1;
1270 return 0;
1273 static jint
1274 parse_verbose_args (char* option_string,
1275 bool ignore_unrecognized)
1277 size_t len = sizeof ("-verbose") - 1;
1279 if (strlen (option_string) < len)
1280 return -1;
1282 if (option_string[len] == ':'
1283 && option_string[len + 1] != '\0')
1285 char* verbose_args = option_string + len + 1;
1289 if (! strncmp (verbose_args,
1290 "gc", sizeof ("gc") - 1))
1292 if (verbose_args[sizeof ("gc") - 1] == '\0'
1293 || verbose_args[sizeof ("gc") - 1] == ',')
1295 // FIXME: we should add functions to boehm-gc that
1296 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1297 // GC_print_back_height.
1298 verbose_args += sizeof ("gc") - 1;
1300 else
1302 verbose_arg_err:
1303 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1304 option_string);
1305 return -1;
1308 else if (! strncmp (verbose_args,
1309 "class",
1310 sizeof ("class") - 1))
1312 if (verbose_args[sizeof ("class") - 1] == '\0'
1313 || verbose_args[sizeof ("class") - 1] == ',')
1315 gcj::verbose_class_flag = true;
1316 verbose_args += sizeof ("class") - 1;
1318 else
1319 goto verbose_arg_err;
1321 else if (! strncmp (verbose_args, "jni",
1322 sizeof ("jni") - 1))
1324 if (verbose_args[sizeof ("jni") - 1] == '\0'
1325 || verbose_args[sizeof ("jni") - 1] == ',')
1327 // FIXME: enable JNI messages.
1328 verbose_args += sizeof ("jni") - 1;
1330 else
1331 goto verbose_arg_err;
1333 else if (ignore_unrecognized
1334 && verbose_args[0] == 'X')
1336 // ignore unrecognized non-standard verbose option
1337 while (verbose_args[0] != '\0'
1338 && verbose_args[0] != ',')
1339 verbose_args++;
1341 else if (verbose_args[0] == ',')
1343 verbose_args++;
1345 else
1346 goto verbose_arg_err;
1348 if (verbose_args[0] == ',')
1349 verbose_args++;
1351 while (verbose_args[0] != '\0');
1353 else if (option_string[len] == 'g'
1354 && option_string[len + 1] == 'c'
1355 && option_string[len + 2] == '\0')
1357 // FIXME: we should add functions to boehm-gc that
1358 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1359 // GC_print_back_height.
1360 return 0;
1362 else if (option_string[len] == '\0')
1364 gcj::verbose_class_flag = true;
1365 return 0;
1367 else
1369 // unrecognized option beginning with -verbose
1370 return -1;
1372 return 0;
1375 // This function loads the agent functions for JVMTI from the library indicated
1376 // by name. It returns a negative value on failure, the value of which
1377 // indicates where ltdl failed, it also prints an error message.
1378 static jint
1379 load_jvmti_agent (const char *name)
1381 #ifdef USE_LTDL
1382 if (lt_dlinit ())
1384 fprintf (stderr,
1385 "libgcj: Error in ltdl init while loading agent library.\n");
1386 return -1;
1389 lt_dlhandle lib = lt_dlopenext (name);
1390 if (!lib)
1392 fprintf (stderr,
1393 "libgcj: Error opening agent library.\n");
1394 return -2;
1397 if (lib)
1399 jvmti_agentonload
1400 = (jvmti_agent_onload_func *) lt_dlsym (lib, "Agent_OnLoad");
1402 if (!jvmti_agentonload)
1404 fprintf (stderr,
1405 "libgcj: Error finding agent function in library %s.\n",
1406 name);
1407 lt_dlclose (lib);
1408 lib = NULL;
1409 return -4;
1411 else
1413 jvmti_agentonunload
1414 = (jvmti_agent_onunload_func *) lt_dlsym (lib, "Agent_OnUnload");
1416 return 0;
1419 else
1421 fprintf (stderr, "libgcj: Library %s not found in library path.\n", name);
1422 return -3;
1425 #endif /* USE_LTDL */
1427 // If LTDL cannot be used, return an error code indicating this.
1428 return -99;
1431 static jint
1432 parse_init_args (JvVMInitArgs* vm_args)
1434 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1435 // re-allocated dynamically.
1436 if (_Jv_Compiler_Properties)
1438 const char** props = _Jv_Compiler_Properties;
1439 _Jv_Compiler_Properties = NULL;
1441 for (int i = 0; props[i]; i++)
1443 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1444 (_Jv_Compiler_Properties,
1445 (_Jv_Properties_Count + 1) * sizeof (const char*));
1446 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1450 if (vm_args == NULL)
1451 return 0;
1453 for (int i = 0; i < vm_args->nOptions; ++i)
1455 char* option_string = vm_args->options[i].optionString;
1457 if (! strcmp (option_string, "vfprintf")
1458 || ! strcmp (option_string, "exit")
1459 || ! strcmp (option_string, "abort"))
1461 // FIXME: we are required to recognize these, but for
1462 // now we don't handle them in any way.
1463 continue;
1465 else if (! strncmp (option_string,
1466 "-verbose", sizeof ("-verbose") - 1))
1468 jint result = parse_verbose_args (option_string,
1469 vm_args->ignoreUnrecognized);
1470 if (result < 0)
1471 return result;
1473 else if (! strncmp (option_string, "-D", 2))
1475 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1476 (_Jv_Compiler_Properties,
1477 (_Jv_Properties_Count + 1) * sizeof (char*));
1479 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1480 strdup (option_string + 2);
1482 continue;
1484 else if (! strncmp (option_string, "-agentlib", sizeof ("-agentlib") - 1))
1486 char *strPtr;
1488 if (strlen(option_string) > (sizeof ("-agentlib:") - 1))
1489 strPtr = &option_string[sizeof ("-agentlib:") - 1];
1490 else
1492 fprintf (stderr,
1493 "libgcj: Malformed agentlib argument %s: expected lib name\n",
1494 option_string);
1495 return -1;
1498 // These are optional arguments to pass to the agent library.
1499 jvmti_agent_opts = strchr (strPtr, '=');
1501 if (! strncmp (strPtr, "jdwp", 4))
1503 // We want to run JDWP here so set the correct variables.
1504 remoteDebug = true;
1505 jdwpOptions = ++jvmti_agent_opts;
1507 else
1509 jint nameLength;
1511 if (jvmti_agent_opts == NULL)
1512 nameLength = strlen (strPtr);
1513 else
1515 nameLength = jvmti_agent_opts - strPtr;
1516 jvmti_agent_opts++;
1519 char lib_name[nameLength + 3 + 1];
1520 strcpy (lib_name, "lib");
1521 strncat (lib_name, strPtr, nameLength);
1523 jint result = load_jvmti_agent (lib_name);
1525 if (result < 0)
1527 return -1;
1530 // Mark JVMTI active
1531 JVMTI::enabled = true;
1534 continue;
1536 else if (! strncmp (option_string, "-agentpath:",
1537 sizeof ("-agentpath:") - 1))
1539 char *strPtr;
1541 if (strlen(option_string) > 10)
1542 strPtr = &option_string[10];
1543 else
1545 fprintf (stderr,
1546 "libgcj: Malformed agentlib argument %s: expected lib path\n",
1547 option_string);
1548 return -1;
1551 // These are optional arguments to pass to the agent library.
1552 jvmti_agent_opts = strchr (strPtr, '=');
1554 jint nameLength;
1556 if (jvmti_agent_opts == NULL)
1557 nameLength = strlen (strPtr);
1558 else
1560 nameLength = jvmti_agent_opts - strPtr;
1561 jvmti_agent_opts++;
1564 char lib_name[nameLength + 3 + 1];
1565 strcpy (lib_name, "lib");
1566 strncat (lib_name, strPtr, nameLength);
1567 jint result = load_jvmti_agent (strPtr);
1569 if (result < 0)
1571 return -1;
1574 // Mark JVMTI active
1575 JVMTI::enabled = true;
1576 continue;
1578 else
1580 int r = -1;
1581 if (option_string[0] == '_')
1582 r = parse_x_arg (option_string + 1);
1583 else if (! strncmp (option_string, "-X", 2))
1584 r = parse_x_arg (option_string + 2);
1586 if (r == -1 && ! vm_args->ignoreUnrecognized)
1588 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1589 return -1;
1593 return 0;
1596 jint
1597 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1599 using namespace gcj;
1601 if (runtimeInitialized)
1602 return -1;
1604 runtimeInitialized = true;
1605 startTime = _Jv_platform_gettimeofday();
1607 jint result = parse_init_args (vm_args);
1608 if (result < 0)
1609 return -1;
1611 PROCESS_GCJ_PROPERTIES;
1613 /* Threads must be initialized before the GC, so that it inherits the
1614 signal mask. */
1615 _Jv_InitThreads ();
1616 _Jv_InitGC ();
1617 _Jv_InitializeSyncMutex ();
1619 #ifdef INTERPRETER
1620 _Jv_InitInterpreter ();
1621 #endif
1623 #ifdef HANDLE_SEGV
1624 INIT_SEGV;
1625 #endif
1627 #ifdef HANDLE_FPE
1628 INIT_FPE;
1629 #endif
1631 /* Initialize Utf8 constants declared in jvm.h. */
1632 void_signature = _Jv_makeUtf8Const ("()V", 3);
1633 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1634 init_name = _Jv_makeUtf8Const ("<init>", 6);
1635 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1637 /* Initialize built-in classes to represent primitive TYPEs. */
1638 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1639 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1640 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1641 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1642 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1643 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1644 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1645 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1646 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1648 // We have to initialize this fairly early, to avoid circular class
1649 // initialization. In particular we want to start the
1650 // initialization of ClassLoader before we start the initialization
1651 // of VMClassLoader.
1652 _Jv_InitClass (&java::lang::ClassLoader::class$);
1654 // Set up the system class loader and the bootstrap class loader.
1655 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1656 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1658 _Jv_RegisterBootstrapPackages();
1660 no_memory = new java::lang::OutOfMemoryError;
1662 #ifdef USE_LTDL
1663 LTDL_SET_PRELOADED_SYMBOLS ();
1664 #endif
1666 _Jv_platform_initialize ();
1668 _Jv_JNI_Init ();
1669 _Jv_JVMTI_Init ();
1671 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1673 // Start the GC finalizer thread. A VirtualMachineError can be
1674 // thrown by the runtime if, say, threads aren't available.
1677 using namespace gnu::gcj::runtime;
1678 FinalizerThread *ft = new FinalizerThread ();
1679 ft->start ();
1681 catch (java::lang::VirtualMachineError *ignore)
1685 runtimeInitialized = true;
1687 return 0;
1690 void
1691 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1692 const char **argv, bool is_jar)
1694 #ifndef DISABLE_MAIN_ARGS
1695 _Jv_SetArgs (argc, argv);
1696 #endif
1698 java::lang::Runtime *runtime = NULL;
1702 if (_Jv_CreateJavaVM (vm_args) < 0)
1704 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1705 exit (1);
1708 if (vm_args == NULL)
1709 gcj::vmArgs = JvConvertArgv(0, NULL);
1710 else
1712 const char* vmArgs[vm_args->nOptions];
1713 const char** vmPtr = vmArgs;
1714 struct _Jv_VMOption* optionPtr = vm_args->options;
1715 for (int i = 0; i < vm_args->nOptions; ++i)
1716 *vmPtr++ = (*optionPtr++).optionString;
1717 gcj::vmArgs = JvConvertArgv(vm_args->nOptions, vmArgs);
1720 // Get the Runtime here. We want to initialize it before searching
1721 // for `main'; that way it will be set up if `main' is a JNI method.
1722 runtime = java::lang::Runtime::getRuntime ();
1724 #ifdef DISABLE_MAIN_ARGS
1725 arg_vec = JvConvertArgv (0, 0);
1726 #else
1727 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1728 #endif
1730 using namespace gnu::java::lang;
1731 if (klass)
1732 main_thread = new MainThread (klass, arg_vec);
1733 else
1734 main_thread = new MainThread (JvNewStringUTF (name),
1735 arg_vec, is_jar);
1736 _Jv_AttachCurrentThread (main_thread);
1738 // Start JVMTI if an agent function has been found.
1739 if (jvmti_agentonload)
1740 (*jvmti_agentonload) (_Jv_GetJavaVM (), jvmti_agent_opts, NULL);
1742 // Start JDWP
1743 if (remoteDebug)
1745 using namespace gnu::classpath::jdwp;
1746 VMVirtualMachine::initialize ();
1747 Jdwp *jdwp = new Jdwp ();
1748 jdwp->setDaemon (true);
1749 jdwp->configure (JvNewStringLatin1 (jdwpOptions));
1750 jdwp->start ();
1752 // Wait for JDWP to initialize and start
1753 jdwp->join ();
1755 // Send VMInit
1756 if (JVMTI_REQUESTED_EVENT (VMInit))
1757 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_INIT, main_thread);
1759 catch (java::lang::Throwable *t)
1761 java::lang::System::err->println (JvNewStringLatin1
1762 ("Exception during runtime initialization"));
1763 t->printStackTrace();
1764 if (runtime)
1765 java::lang::Runtime::exitNoChecksAccessor (1);
1766 // In case the runtime creation failed.
1767 ::exit (1);
1770 _Jv_ThreadRun (main_thread);
1772 // Send VMDeath
1773 if (JVMTI_REQUESTED_EVENT (VMDeath))
1775 java::lang::Thread *thread = java::lang::Thread::currentThread ();
1776 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
1777 _Jv_JVMTI_PostEvent (JVMTI_EVENT_VM_DEATH, thread, jni_env);
1780 // Run JVMTI AgentOnUnload if it exists and an agent is loaded.
1781 if (jvmti_agentonunload)
1782 (*jvmti_agentonunload) (_Jv_GetJavaVM ());
1784 // If we got here then something went wrong, as MainThread is not
1785 // supposed to terminate.
1786 ::exit (1);
1789 void
1790 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1791 bool is_jar)
1793 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1796 void
1797 JvRunMain (jclass klass, int argc, const char **argv)
1799 _Jv_RunMain (klass, NULL, argc, argv, false);
1802 void
1803 JvRunMainName (const char *name, int argc, const char **argv)
1805 _Jv_RunMain (NULL, name, argc, argv, false);
1810 // Parse a string and return a heap size.
1811 static size_t
1812 parse_memory_size (const char *spec)
1814 char *end;
1815 unsigned long val = strtoul (spec, &end, 10);
1816 if (*end == 'k' || *end == 'K')
1817 val *= 1024;
1818 else if (*end == 'm' || *end == 'M')
1819 val *= 1048576;
1820 return (size_t) val;
1823 // Set the initial heap size. This might be ignored by the GC layer.
1824 // This must be called before _Jv_RunMain.
1825 void
1826 _Jv_SetInitialHeapSize (const char *arg)
1828 size_t size = parse_memory_size (arg);
1829 _Jv_GCSetInitialHeapSize (size);
1832 // Set the maximum heap size. This might be ignored by the GC layer.
1833 // This must be called before _Jv_RunMain.
1834 void
1835 _Jv_SetMaximumHeapSize (const char *arg)
1837 size_t size = parse_memory_size (arg);
1838 _Jv_GCSetMaximumHeapSize (size);
1841 void
1842 _Jv_SetStackSize (const char *arg)
1844 size_t size = parse_memory_size (arg);
1845 gcj::stack_size = size;
1848 void *
1849 _Jv_Malloc (jsize size)
1851 if (__builtin_expect (size == 0, false))
1852 size = 1;
1853 void *ptr = malloc ((size_t) size);
1854 if (__builtin_expect (ptr == NULL, false))
1855 throw no_memory;
1856 return ptr;
1859 void *
1860 _Jv_Realloc (void *ptr, jsize size)
1862 if (__builtin_expect (size == 0, false))
1863 size = 1;
1864 ptr = realloc (ptr, (size_t) size);
1865 if (__builtin_expect (ptr == NULL, false))
1866 throw no_memory;
1867 return ptr;
1870 void *
1871 _Jv_MallocUnchecked (jsize size)
1873 if (__builtin_expect (size == 0, false))
1874 size = 1;
1875 return malloc ((size_t) size);
1878 void
1879 _Jv_Free (void* ptr)
1881 return free (ptr);
1886 // In theory, these routines can be #ifdef'd away on machines which
1887 // support divide overflow signals. However, we never know if some
1888 // code might have been compiled with "-fuse-divide-subroutine", so we
1889 // always include them in libgcj.
1891 jint
1892 _Jv_divI (jint dividend, jint divisor)
1894 if (__builtin_expect (divisor == 0, false))
1896 java::lang::ArithmeticException *arithexception
1897 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1898 throw arithexception;
1901 if (dividend == (jint) 0x80000000L && divisor == -1)
1902 return dividend;
1904 return dividend / divisor;
1907 jint
1908 _Jv_remI (jint dividend, jint divisor)
1910 if (__builtin_expect (divisor == 0, false))
1912 java::lang::ArithmeticException *arithexception
1913 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1914 throw arithexception;
1917 if (dividend == (jint) 0x80000000L && divisor == -1)
1918 return 0;
1920 return dividend % divisor;
1923 jlong
1924 _Jv_divJ (jlong dividend, jlong divisor)
1926 if (__builtin_expect (divisor == 0, false))
1928 java::lang::ArithmeticException *arithexception
1929 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1930 throw arithexception;
1933 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1934 return dividend;
1936 return dividend / divisor;
1939 jlong
1940 _Jv_remJ (jlong dividend, jlong divisor)
1942 if (__builtin_expect (divisor == 0, false))
1944 java::lang::ArithmeticException *arithexception
1945 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1946 throw arithexception;
1949 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1950 return 0;
1952 return dividend % divisor;
1957 // Return true if SELF_KLASS can access a field or method in
1958 // OTHER_KLASS. The field or method's access flags are specified in
1959 // FLAGS.
1960 jboolean
1961 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1963 using namespace java::lang::reflect;
1964 return ((self_klass == other_klass)
1965 || ((flags & Modifier::PUBLIC) != 0)
1966 || (((flags & Modifier::PROTECTED) != 0)
1967 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1968 || (((flags & Modifier::PRIVATE) == 0)
1969 && _Jv_ClassNameSamePackage (self_klass->name,
1970 other_klass->name)));
1973 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1974 // char array, if the path is not already prefixed by
1975 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1976 // result should be freed using JvFree.
1977 char*
1978 _Jv_PrependVersionedLibdir (char* libpath)
1980 char* retval = 0;
1982 if (libpath && libpath[0] != '\0')
1984 if (! strncmp (libpath,
1985 GCJ_VERSIONED_LIBDIR,
1986 sizeof (GCJ_VERSIONED_LIBDIR) - 1))
1988 // LD_LIBRARY_PATH is already prefixed with
1989 // GCJ_VERSIONED_LIBDIR.
1990 retval = (char*) _Jv_Malloc (strlen (libpath) + 1);
1991 strcpy (retval, libpath);
1993 else
1995 // LD_LIBRARY_PATH is not prefixed with
1996 // GCJ_VERSIONED_LIBDIR.
1997 char path_sep[2];
1998 path_sep[0] = (char) _Jv_platform_path_separator;
1999 path_sep[1] = '\0';
2000 jsize total = ((sizeof (GCJ_VERSIONED_LIBDIR) - 1)
2001 + 1 /* path separator */ + strlen (libpath) + 1);
2002 retval = (char*) _Jv_Malloc (total);
2003 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2004 strcat (retval, path_sep);
2005 strcat (retval, libpath);
2008 else
2010 // LD_LIBRARY_PATH was not specified or is empty.
2011 retval = (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR));
2012 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2015 return retval;