PR target/4198
[official-gcc.git] / libjava / prims.cc
blob7060171223819cdfdf14d1e62e595681d77996ab
1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 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 #ifndef DISABLE_GETENV_PROPERTIES
36 #include <ctype.h>
37 #include <java-props.h>
38 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
39 #else
40 #define PROCESS_GCJ_PROPERTIES
41 #endif // DISABLE_GETENV_PROPERTIES
43 #include <java/lang/Class.h>
44 #include <java/lang/ClassLoader.h>
45 #include <java/lang/Runtime.h>
46 #include <java/lang/String.h>
47 #include <java/lang/Thread.h>
48 #include <java/lang/ThreadGroup.h>
49 #include <java/lang/ArrayIndexOutOfBoundsException.h>
50 #include <java/lang/ArithmeticException.h>
51 #include <java/lang/ClassFormatError.h>
52 #include <java/lang/InternalError.h>
53 #include <java/lang/NegativeArraySizeException.h>
54 #include <java/lang/NullPointerException.h>
55 #include <java/lang/OutOfMemoryError.h>
56 #include <java/lang/System.h>
57 #include <java/lang/VMThrowable.h>
58 #include <java/lang/VMClassLoader.h>
59 #include <java/lang/reflect/Modifier.h>
60 #include <java/io/PrintStream.h>
61 #include <java/lang/UnsatisfiedLinkError.h>
62 #include <java/lang/VirtualMachineError.h>
63 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
64 #include <gnu/gcj/runtime/FinalizerThread.h>
65 #include <execution.h>
66 #include <gnu/java/lang/MainThread.h>
68 #ifdef USE_LTDL
69 #include <ltdl.h>
70 #endif
72 // Execution engine for compiled code.
73 _Jv_CompiledEngine _Jv_soleCompiledEngine;
75 // We allocate a single OutOfMemoryError exception which we keep
76 // around for use if we run out of memory.
77 static java::lang::OutOfMemoryError *no_memory;
79 // Number of bytes in largest array object we create. This could be
80 // increased to the largest size_t value, so long as the appropriate
81 // functions are changed to take a size_t argument instead of jint.
82 #define MAX_OBJECT_SIZE ((1<<31) - 1)
84 // Properties set at compile time.
85 const char **_Jv_Compiler_Properties = NULL;
86 int _Jv_Properties_Count = 0;
88 #ifndef DISABLE_GETENV_PROPERTIES
89 // Property key/value pairs.
90 property_pair *_Jv_Environment_Properties;
91 #endif
93 // Stash the argv pointer to benefit native libraries that need it.
94 const char **_Jv_argv;
95 int _Jv_argc;
97 // Argument support.
98 int
99 _Jv_GetNbArgs (void)
101 // _Jv_argc is 0 if not explicitly initialized.
102 return _Jv_argc;
105 const char *
106 _Jv_GetSafeArg (int index)
108 if (index >=0 && index < _Jv_GetNbArgs ())
109 return _Jv_argv[index];
110 else
111 return "";
114 void
115 _Jv_SetArgs (int argc, const char **argv)
117 _Jv_argc = argc;
118 _Jv_argv = argv;
121 #ifdef ENABLE_JVMPI
122 // Pointer to JVMPI notification functions.
123 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
124 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
125 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
126 #endif
129 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
130 /* Unblock a signal. Unless we do this, the signal may only be sent
131 once. */
132 static void
133 unblock_signal (int signum __attribute__ ((__unused__)))
135 #ifdef _POSIX_VERSION
136 sigset_t sigs;
138 sigemptyset (&sigs);
139 sigaddset (&sigs, signum);
140 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
141 #endif
143 #endif
145 #ifdef HANDLE_SEGV
146 SIGNAL_HANDLER (catch_segv)
148 unblock_signal (SIGSEGV);
149 MAKE_THROW_FRAME (nullp);
150 java::lang::NullPointerException *nullp
151 = new java::lang::NullPointerException;
152 throw nullp;
154 #endif
156 #ifdef HANDLE_FPE
157 SIGNAL_HANDLER (catch_fpe)
159 unblock_signal (SIGFPE);
160 #ifdef HANDLE_DIVIDE_OVERFLOW
161 HANDLE_DIVIDE_OVERFLOW;
162 #else
163 MAKE_THROW_FRAME (arithexception);
164 #endif
165 java::lang::ArithmeticException *arithexception
166 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
167 throw arithexception;
169 #endif
173 jboolean
174 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
176 int len;
177 const _Jv_ushort *aptr, *bptr;
178 if (a == b)
179 return true;
180 if (a->hash != b->hash)
181 return false;
182 len = a->length;
183 if (b->length != len)
184 return false;
185 aptr = (const _Jv_ushort *)a->data;
186 bptr = (const _Jv_ushort *)b->data;
187 len = (len + 1) >> 1;
188 while (--len >= 0)
189 if (*aptr++ != *bptr++)
190 return false;
191 return true;
194 /* True iff A is equal to STR.
195 HASH is STR->hashCode().
198 jboolean
199 _Jv_equal (Utf8Const* a, jstring str, jint hash)
201 if (a->hash != (_Jv_ushort) hash)
202 return false;
203 jint len = str->length();
204 jint i = 0;
205 jchar *sptr = _Jv_GetStringChars (str);
206 unsigned char* ptr = (unsigned char*) a->data;
207 unsigned char* limit = ptr + a->length;
208 for (;; i++, sptr++)
210 int ch = UTF8_GET (ptr, limit);
211 if (i == len)
212 return ch < 0;
213 if (ch != *sptr)
214 return false;
216 return true;
219 /* Like _Jv_equal, but stop after N characters. */
220 jboolean
221 _Jv_equaln (Utf8Const *a, jstring str, jint n)
223 jint len = str->length();
224 jint i = 0;
225 jchar *sptr = _Jv_GetStringChars (str);
226 unsigned char* ptr = (unsigned char*) a->data;
227 unsigned char* limit = ptr + a->length;
228 for (; n-- > 0; i++, sptr++)
230 int ch = UTF8_GET (ptr, limit);
231 if (i == len)
232 return ch < 0;
233 if (ch != *sptr)
234 return false;
236 return true;
239 /* Count the number of Unicode chars encoded in a given Ut8 string. */
241 _Jv_strLengthUtf8(char* str, int len)
243 unsigned char* ptr;
244 unsigned char* limit;
245 int str_length;
247 ptr = (unsigned char*) str;
248 limit = ptr + len;
249 str_length = 0;
250 for (; ptr < limit; str_length++)
252 if (UTF8_GET (ptr, limit) < 0)
253 return (-1);
255 return (str_length);
258 /* Calculate a hash value for a string encoded in Utf8 format.
259 * This returns the same hash value as specified or java.lang.String.hashCode.
261 jint
262 _Jv_hashUtf8String (char* str, int len)
264 unsigned char* ptr = (unsigned char*) str;
265 unsigned char* limit = ptr + len;
266 jint hash = 0;
268 for (; ptr < limit;)
270 int ch = UTF8_GET (ptr, limit);
271 /* Updated specification from
272 http://www.javasoft.com/docs/books/jls/clarify.html. */
273 hash = (31 * hash) + ch;
275 return hash;
278 void
279 _Jv_Utf8Const::init(char *s, int len)
281 ::memcpy (data, s, len);
282 data[len] = 0;
283 length = len;
284 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
287 _Jv_Utf8Const *
288 _Jv_makeUtf8Const (char* s, int len)
290 if (len < 0)
291 len = strlen (s);
292 Utf8Const* m
293 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
294 m->init(s, len);
295 return m;
298 _Jv_Utf8Const *
299 _Jv_makeUtf8Const (jstring string)
301 jint hash = string->hashCode ();
302 jint len = _Jv_GetStringUTFLength (string);
304 Utf8Const* m = (Utf8Const*)
305 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
307 m->hash = hash;
308 m->length = len;
310 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
311 m->data[len] = 0;
313 return m;
318 #ifdef DEBUG
319 void
320 _Jv_Abort (const char *function, const char *file, int line,
321 const char *message)
322 #else
323 void
324 _Jv_Abort (const char *, const char *, int, const char *message)
325 #endif
327 #ifdef DEBUG
328 fprintf (stderr,
329 "libgcj failure: %s\n in function %s, file %s, line %d\n",
330 message, function, file, line);
331 #else
332 fprintf (stderr, "libgcj failure: %s\n", message);
333 #endif
334 abort ();
337 static void
338 fail_on_finalization (jobject)
340 JvFail ("object was finalized");
343 void
344 _Jv_GCWatch (jobject obj)
346 _Jv_RegisterFinalizer (obj, fail_on_finalization);
349 void
350 _Jv_ThrowBadArrayIndex(jint bad_index)
352 throw new java::lang::ArrayIndexOutOfBoundsException
353 (java::lang::String::valueOf (bad_index));
356 void
357 _Jv_ThrowNullPointerException ()
359 throw new java::lang::NullPointerException;
362 // Explicitly throw a no memory exception.
363 // The collector calls this when it encounters an out-of-memory condition.
364 void _Jv_ThrowNoMemory()
366 throw no_memory;
369 #ifdef ENABLE_JVMPI
370 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
371 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
372 jvmpi_notify_alloc(klass,size,obj);
373 static void
374 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
376 // Service JVMPI allocation request.
377 JVMPI_Event event;
379 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
380 event.env_id = NULL;
381 event.u.obj_alloc.arena_id = 0;
382 event.u.obj_alloc.class_id = (jobjectID) klass;
383 event.u.obj_alloc.is_array = 0;
384 event.u.obj_alloc.size = size;
385 event.u.obj_alloc.obj_id = (jobjectID) obj;
387 // FIXME: This doesn't look right for the Boehm GC. A GC may
388 // already be in progress. _Jv_DisableGC () doesn't wait for it.
389 // More importantly, I don't see the need for disabling GC, since we
390 // blatantly have a pointer to obj on our stack, ensuring that the
391 // object can't be collected. Even for a nonconservative collector,
392 // it appears to me that this must be true, since we are about to
393 // return obj. Isn't this whole approach way too intrusive for
394 // a useful profiling interface? - HB
395 _Jv_DisableGC ();
396 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
397 _Jv_EnableGC ();
399 #else /* !ENABLE_JVMPI */
400 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
401 #endif
403 // Allocate a new object of class KLASS.
404 // First a version that assumes that we have no finalizer, and that
405 // the class is already initialized.
406 // If we know that JVMPI is disabled, this can be replaced by a direct call
407 // to the allocator for the appropriate GC.
408 jobject
409 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
411 jint size = klass->size ();
412 jobject obj = (jobject) _Jv_AllocObj (size, klass);
413 JVMPI_NOTIFY_ALLOC (klass, size, obj);
414 return obj;
417 // And now a version that initializes if necessary.
418 jobject
419 _Jv_AllocObjectNoFinalizer (jclass klass)
421 _Jv_InitClass (klass);
422 jint size = klass->size ();
423 jobject obj = (jobject) _Jv_AllocObj (size, klass);
424 JVMPI_NOTIFY_ALLOC (klass, size, obj);
425 return obj;
428 // And now the general version that registers a finalizer if necessary.
429 jobject
430 _Jv_AllocObject (jclass klass)
432 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
434 // We assume that the compiler only generates calls to this routine
435 // if there really is an interesting finalizer.
436 // Unfortunately, we still have to the dynamic test, since there may
437 // be cni calls to this routine.
438 // Note that on IA64 get_finalizer() returns the starting address of the
439 // function, not a function pointer. Thus this still works.
440 if (klass->vtable->get_finalizer ()
441 != java::lang::Object::class$.vtable->get_finalizer ())
442 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
443 return obj;
446 // Allocate a String, including variable length storage.
447 jstring
448 _Jv_AllocString(jsize len)
450 using namespace java::lang;
452 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
454 // We assert that for strings allocated this way, the data field
455 // will always point to the object itself. Thus there is no reason
456 // for the garbage collector to scan any of it.
457 // Furthermore, we're about to overwrite the string data, so
458 // initialization of the object is not an issue.
460 // String needs no initialization, and there is no finalizer, so
461 // we can go directly to the collector's allocator interface.
462 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
464 obj->data = obj;
465 obj->boffset = sizeof(java::lang::String);
466 obj->count = len;
467 obj->cachedHashCode = 0;
469 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
471 return obj;
474 // A version of the above that assumes the object contains no pointers,
475 // and requires no finalization. This can't happen if we need pointers
476 // to locks.
477 #ifdef JV_HASH_SYNCHRONIZATION
478 jobject
479 _Jv_AllocPtrFreeObject (jclass klass)
481 _Jv_InitClass (klass);
482 jint size = klass->size ();
484 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
486 JVMPI_NOTIFY_ALLOC (klass, size, obj);
488 return obj;
490 #endif /* JV_HASH_SYNCHRONIZATION */
493 // Allocate a new array of Java objects. Each object is of type
494 // `elementClass'. `init' is used to initialize each slot in the
495 // array.
496 jobjectArray
497 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
499 if (__builtin_expect (count < 0, false))
500 throw new java::lang::NegativeArraySizeException;
502 JvAssert (! elementClass->isPrimitive ());
504 // Ensure that elements pointer is properly aligned.
505 jobjectArray obj = NULL;
506 size_t size = (size_t) elements (obj);
507 // Check for overflow.
508 if (__builtin_expect ((size_t) count >
509 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
510 throw no_memory;
512 size += count * sizeof (jobject);
514 jclass klass = _Jv_GetArrayClass (elementClass,
515 elementClass->getClassLoaderInternal());
517 obj = (jobjectArray) _Jv_AllocArray (size, klass);
518 // Cast away const.
519 jsize *lp = const_cast<jsize *> (&obj->length);
520 *lp = count;
521 // We know the allocator returns zeroed memory. So don't bother
522 // zeroing it again.
523 if (init)
525 jobject *ptr = elements(obj);
526 while (--count >= 0)
527 *ptr++ = init;
529 return obj;
532 // Allocate a new array of primitives. ELTYPE is the type of the
533 // element, COUNT is the size of the array.
534 jobject
535 _Jv_NewPrimArray (jclass eltype, jint count)
537 int elsize = eltype->size();
538 if (__builtin_expect (count < 0, false))
539 throw new java::lang::NegativeArraySizeException;
541 JvAssert (eltype->isPrimitive ());
542 jobject dummy = NULL;
543 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
545 // Check for overflow.
546 if (__builtin_expect ((size_t) count >
547 (MAX_OBJECT_SIZE - size) / elsize, false))
548 throw no_memory;
550 jclass klass = _Jv_GetArrayClass (eltype, 0);
552 # ifdef JV_HASH_SYNCHRONIZATION
553 // Since the vtable is always statically allocated,
554 // these are completely pointerfree! Make sure the GC doesn't touch them.
555 __JArray *arr =
556 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
557 memset((char *)arr + size, 0, elsize * count);
558 # else
559 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
560 // Note that we assume we are given zeroed memory by the allocator.
561 # endif
562 // Cast away const.
563 jsize *lp = const_cast<jsize *> (&arr->length);
564 *lp = count;
566 return arr;
569 jobject
570 _Jv_NewArray (jint type, jint size)
572 switch (type)
574 case 4: return JvNewBooleanArray (size);
575 case 5: return JvNewCharArray (size);
576 case 6: return JvNewFloatArray (size);
577 case 7: return JvNewDoubleArray (size);
578 case 8: return JvNewByteArray (size);
579 case 9: return JvNewShortArray (size);
580 case 10: return JvNewIntArray (size);
581 case 11: return JvNewLongArray (size);
583 throw new java::lang::InternalError
584 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
587 // Allocate a possibly multi-dimensional array but don't check that
588 // any array length is <0.
589 static jobject
590 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
592 JvAssert (type->isArray());
593 jclass element_type = type->getComponentType();
594 jobject result;
595 if (element_type->isPrimitive())
596 result = _Jv_NewPrimArray (element_type, sizes[0]);
597 else
598 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
600 if (dimensions > 1)
602 JvAssert (! element_type->isPrimitive());
603 JvAssert (element_type->isArray());
604 jobject *contents = elements ((jobjectArray) result);
605 for (int i = 0; i < sizes[0]; ++i)
606 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
607 sizes + 1);
610 return result;
613 jobject
614 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
616 for (int i = 0; i < dimensions; ++i)
617 if (sizes[i] < 0)
618 throw new java::lang::NegativeArraySizeException;
620 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
623 jobject
624 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
626 va_list args;
627 jint sizes[dimensions];
628 va_start (args, dimensions);
629 for (int i = 0; i < dimensions; ++i)
631 jint size = va_arg (args, jint);
632 if (size < 0)
633 throw new java::lang::NegativeArraySizeException;
634 sizes[i] = size;
636 va_end (args);
638 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
643 // Ensure 8-byte alignment, for hash synchronization.
644 #define DECLARE_PRIM_TYPE(NAME) \
645 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
647 DECLARE_PRIM_TYPE(byte)
648 DECLARE_PRIM_TYPE(short)
649 DECLARE_PRIM_TYPE(int)
650 DECLARE_PRIM_TYPE(long)
651 DECLARE_PRIM_TYPE(boolean)
652 DECLARE_PRIM_TYPE(char)
653 DECLARE_PRIM_TYPE(float)
654 DECLARE_PRIM_TYPE(double)
655 DECLARE_PRIM_TYPE(void)
657 void
658 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len)
660 using namespace java::lang::reflect;
662 // We must set the vtable for the class; the Java constructor
663 // doesn't do this.
664 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
666 // Initialize the fields we care about. We do this in the same
667 // order they are declared in Class.h.
668 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
669 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
670 cl->method_count = sig;
671 cl->size_in_bytes = len;
672 cl->vtable = JV_PRIMITIVE_VTABLE;
673 cl->state = JV_STATE_DONE;
674 cl->depth = -1;
677 jclass
678 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
680 switch (*sig)
682 case 'B':
683 return JvPrimClass (byte);
684 case 'S':
685 return JvPrimClass (short);
686 case 'I':
687 return JvPrimClass (int);
688 case 'J':
689 return JvPrimClass (long);
690 case 'Z':
691 return JvPrimClass (boolean);
692 case 'C':
693 return JvPrimClass (char);
694 case 'F':
695 return JvPrimClass (float);
696 case 'D':
697 return JvPrimClass (double);
698 case 'V':
699 return JvPrimClass (void);
700 case 'L':
702 int i;
703 for (i = 1; sig[i] && sig[i] != ';'; ++i)
705 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
706 return _Jv_FindClass (name, loader);
708 case '[':
710 jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
711 if (! klass)
712 return NULL;
713 return _Jv_GetArrayClass (klass, loader);
717 return NULL; // Placate compiler.
722 JArray<jstring> *
723 JvConvertArgv (int argc, const char **argv)
725 if (argc < 0)
726 argc = 0;
727 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
728 jobject *ptr = elements(ar);
729 jbyteArray bytes = NULL;
730 for (int i = 0; i < argc; i++)
732 const char *arg = argv[i];
733 int len = strlen (arg);
734 if (bytes == NULL || bytes->length < len)
735 bytes = JvNewByteArray (len);
736 jbyte *bytePtr = elements (bytes);
737 // We assume jbyte == char.
738 memcpy (bytePtr, arg, len);
740 // Now convert using the default encoding.
741 *ptr++ = new java::lang::String (bytes, 0, len);
743 return (JArray<jstring>*) ar;
746 // FIXME: These variables are static so that they will be
747 // automatically scanned by the Boehm collector. This is needed
748 // because with qthreads the collector won't scan the initial stack --
749 // it will only scan the qthreads stacks.
751 // Command line arguments.
752 static JArray<jstring> *arg_vec;
754 // The primary thread.
755 static java::lang::Thread *main_thread;
757 #ifndef DISABLE_GETENV_PROPERTIES
759 static char *
760 next_property_key (char *s, size_t *length)
762 size_t l = 0;
764 JvAssert (s);
766 // Skip over whitespace
767 while (isspace (*s))
768 s++;
770 // If we've reached the end, return NULL. Also return NULL if for
771 // some reason we've come across a malformed property string.
772 if (*s == 0
773 || *s == ':'
774 || *s == '=')
775 return NULL;
777 // Determine the length of the property key.
778 while (s[l] != 0
779 && ! isspace (s[l])
780 && s[l] != ':'
781 && s[l] != '=')
783 if (s[l] == '\\'
784 && s[l+1] != 0)
785 l++;
786 l++;
789 *length = l;
791 return s;
794 static char *
795 next_property_value (char *s, size_t *length)
797 size_t l = 0;
799 JvAssert (s);
801 while (isspace (*s))
802 s++;
804 if (*s == ':'
805 || *s == '=')
806 s++;
808 while (isspace (*s))
809 s++;
811 // If we've reached the end, return NULL.
812 if (*s == 0)
813 return NULL;
815 // Determine the length of the property value.
816 while (s[l] != 0
817 && ! isspace (s[l])
818 && s[l] != ':'
819 && s[l] != '=')
821 if (s[l] == '\\'
822 && s[l+1] != 0)
823 l += 2;
824 else
825 l++;
828 *length = l;
830 return s;
833 static void
834 process_gcj_properties ()
836 char *props = getenv("GCJ_PROPERTIES");
837 char *p = props;
838 size_t length;
839 size_t property_count = 0;
841 if (NULL == props)
842 return;
844 // Whip through props quickly in order to count the number of
845 // property values.
846 while (p && (p = next_property_key (p, &length)))
848 // Skip to the end of the key
849 p += length;
851 p = next_property_value (p, &length);
852 if (p)
853 p += length;
855 property_count++;
858 // Allocate an array of property value/key pairs.
859 _Jv_Environment_Properties =
860 (property_pair *) malloc (sizeof(property_pair)
861 * (property_count + 1));
863 // Go through the properties again, initializing _Jv_Properties
864 // along the way.
865 p = props;
866 property_count = 0;
867 while (p && (p = next_property_key (p, &length)))
869 _Jv_Environment_Properties[property_count].key = p;
870 _Jv_Environment_Properties[property_count].key_length = length;
872 // Skip to the end of the key
873 p += length;
875 p = next_property_value (p, &length);
877 _Jv_Environment_Properties[property_count].value = p;
878 _Jv_Environment_Properties[property_count].value_length = length;
880 if (p)
881 p += length;
883 property_count++;
885 memset ((void *) &_Jv_Environment_Properties[property_count],
886 0, sizeof (property_pair));
888 // Null terminate the strings.
889 for (property_pair *prop = &_Jv_Environment_Properties[0];
890 prop->key != NULL;
891 prop++)
893 prop->key[prop->key_length] = 0;
894 prop->value[prop->value_length] = 0;
897 #endif // DISABLE_GETENV_PROPERTIES
899 namespace gcj
901 _Jv_Utf8Const *void_signature;
902 _Jv_Utf8Const *clinit_name;
903 _Jv_Utf8Const *init_name;
904 _Jv_Utf8Const *finit_name;
906 bool runtimeInitialized = false;
909 // We accept all non-standard options accepted by Sun's java command,
910 // for compatibility with existing application launch scripts.
911 static jint
912 parse_x_arg (char* option_string)
914 if (strlen (option_string) <= 0)
915 return -1;
917 if (! strcmp (option_string, "int"))
919 // FIXME: this should cause the vm to never load shared objects
921 else if (! strcmp (option_string, "mixed"))
923 // FIXME: allow interpreted and native code
925 else if (! strcmp (option_string, "batch"))
927 // FIXME: disable background JIT'ing
929 else if (! strcmp (option_string, "debug"))
931 // FIXME: add JDWP/JVMDI support
933 else if (! strncmp (option_string, "bootclasspath:", 14))
935 // FIXME: add a parse_bootclasspath_arg function
937 else if (! strncmp (option_string, "bootclasspath/a:", 16))
940 else if (! strncmp (option_string, "bootclasspath/p:", 16))
943 else if (! strcmp (option_string, "check:jni"))
945 // FIXME: enable strict JNI checking
947 else if (! strcmp (option_string, "future"))
949 // FIXME: enable strict class file format checks
951 else if (! strcmp (option_string, "noclassgc"))
953 // FIXME: disable garbage collection for classes
955 else if (! strcmp (option_string, "incgc"))
957 // FIXME: incremental garbage collection
959 else if (! strncmp (option_string, "loggc:", 6))
961 if (option_string[6] == '\0')
963 fprintf (stderr,
964 "libgcj: filename argument expected for loggc option\n");
965 return -1;
967 // FIXME: set gc logging filename
969 else if (! strncmp (option_string, "ms", 2))
971 // FIXME: ignore this option until PR 20699 is fixed.
972 // _Jv_SetInitialHeapSize (option_string + 2);
974 else if (! strncmp (option_string, "mx", 2))
975 _Jv_SetMaximumHeapSize (option_string + 2);
976 else if (! strcmp (option_string, "prof"))
978 // FIXME: enable profiling of program running in vm
980 else if (! strncmp (option_string, "runhprof:", 9))
982 // FIXME: enable specific type of vm profiling. add a
983 // parse_runhprof_arg function
985 else if (! strcmp (option_string, "rs"))
987 // FIXME: reduced system signal usage. disable thread dumps,
988 // only terminate in response to user-initiated calls,
989 // e.g. System.exit()
991 else if (! strncmp (option_string, "ss", 2))
993 // FIXME: set thread stack size
995 else if (! strcmp (option_string, "X:+UseAltSigs"))
997 // FIXME: use signals other than SIGUSR1 and SIGUSR2
999 else if (! strcmp (option_string, "share:off"))
1001 // FIXME: don't share class data
1003 else if (! strcmp (option_string, "share:auto"))
1005 // FIXME: share class data where possible
1007 else if (! strcmp (option_string, "share:on"))
1009 // FIXME: fail if impossible to share class data
1012 return 0;
1015 static jint
1016 parse_verbose_args (char* option_string,
1017 bool ignore_unrecognized)
1019 size_t len = sizeof ("-verbose");
1021 if (strlen (option_string) < len)
1022 return -1;
1024 if (option_string[len] == ':'
1025 && option_string[len + 1] != '\0')
1027 char* verbose_args = option_string + len + 1;
1028 size_t last = 0;
1032 if (! strncmp (verbose_args,
1033 "gc", (last = sizeof ("gc")) - 1)
1034 && (verbose_args[last] == '\0'
1035 || verbose_args[last] == ','))
1037 // FIXME: we should add functions to boehm-gc that
1038 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1039 // GC_print_back_height.
1042 else if (! strncmp (verbose_args,
1043 "class",
1044 (last = sizeof ("class")) - 1)
1045 && (verbose_args[last] == '\0'
1046 || verbose_args[last] == ','))
1048 gcj::verbose_class_flag = true;
1050 else if (! strncmp (verbose_args, "jni",
1051 (last = sizeof ("jni")) - 1)
1052 && (verbose_args[last] == '\0'
1053 || verbose_args[last] == ','))
1055 // FIXME: enable JNI messages.
1057 else if (ignore_unrecognized
1058 && verbose_args[0] == 'X')
1060 // ignore unrecognized non-standard verbose option
1061 last = 0;
1062 while (verbose_args[last] != '\0'
1063 && verbose_args[last++] != ',');
1066 if (strlen (verbose_args) >= last)
1068 if (verbose_args[last] == ',')
1070 if (verbose_args[last + 1] == '\0')
1071 // trailing comma
1072 return -1;
1073 else
1075 verbose_args = verbose_args + last + 1;
1076 last = 0;
1079 // here verbose_args[last] is either '\0' or
1080 // the first character in the next verbose
1081 // argument.
1083 else
1084 // partial option
1085 return -1;
1087 // verbose_args[last] will be '\0' here if we're
1088 // done.
1090 while (verbose_args[last] != '\0');
1092 else if (option_string[len] == 'g'
1093 && option_string[len + 1] == 'c'
1094 && option_string[len + 2] == '\0')
1096 // FIXME: we should add functions to boehm-gc that
1097 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1098 // GC_print_back_height.
1099 return 0;
1101 else if (option_string[len] == '\0')
1103 gcj::verbose_class_flag = true;
1104 return 0;
1106 else
1108 // unrecognized option beginning with -verbose
1109 return -1;
1111 return 0;
1114 static jint
1115 parse_init_args (JvVMInitArgs* vm_args)
1117 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1118 // re-allocated dynamically.
1119 if (_Jv_Compiler_Properties)
1121 const char** props = _Jv_Compiler_Properties;
1122 _Jv_Compiler_Properties = NULL;
1124 for (int i = 0; props[i]; i++)
1126 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1127 (_Jv_Compiler_Properties,
1128 (_Jv_Properties_Count + 1) * sizeof (const char*));
1129 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1133 if (vm_args == NULL)
1134 return 0;
1136 for (int i = 0; i < vm_args->nOptions; ++i)
1138 char* option_string = vm_args->options[i].optionString;
1139 if (! strcmp (option_string, "vfprintf")
1140 || ! strcmp (option_string, "exit")
1141 || ! strcmp (option_string, "abort"))
1143 // FIXME: we are required to recognize these, but for
1144 // now we don't handle them in any way.
1145 continue;
1147 else if (! strncmp (option_string,
1148 "-verbose", sizeof ("-verbose") - 1))
1150 jint result = parse_verbose_args (option_string,
1151 vm_args->ignoreUnrecognized);
1152 if (result < 0)
1153 return result;
1155 else if (! strncmp (option_string, "-D", 2))
1157 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1158 (_Jv_Compiler_Properties,
1159 (_Jv_Properties_Count + 1) * sizeof (char*));
1161 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1162 strdup (option_string + 2);
1164 continue;
1166 else if (vm_args->ignoreUnrecognized)
1168 if (option_string[0] == '_')
1169 parse_x_arg (option_string + 1);
1170 else if (! strncmp (option_string, "-X", 2))
1171 parse_x_arg (option_string + 2);
1172 else
1174 unknown_option:
1175 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1176 return -1;
1179 else
1180 goto unknown_option;
1182 return 0;
1185 jint
1186 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1188 using namespace gcj;
1190 if (runtimeInitialized)
1191 return -1;
1193 runtimeInitialized = true;
1195 jint result = parse_init_args (vm_args);
1196 if (result < 0)
1197 return -1;
1199 PROCESS_GCJ_PROPERTIES;
1201 /* Threads must be initialized before the GC, so that it inherits the
1202 signal mask. */
1203 _Jv_InitThreads ();
1204 _Jv_InitGC ();
1205 _Jv_InitializeSyncMutex ();
1207 #ifdef INTERPRETER
1208 _Jv_InitInterpreter ();
1209 #endif
1211 #ifdef HANDLE_SEGV
1212 INIT_SEGV;
1213 #endif
1215 #ifdef HANDLE_FPE
1216 INIT_FPE;
1217 #endif
1219 /* Initialize Utf8 constants declared in jvm.h. */
1220 void_signature = _Jv_makeUtf8Const ("()V", 3);
1221 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1222 init_name = _Jv_makeUtf8Const ("<init>", 6);
1223 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1225 /* Initialize built-in classes to represent primitive TYPEs. */
1226 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1227 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1228 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1229 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1230 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1231 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1232 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1233 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1234 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1236 // Turn stack trace generation off while creating exception objects.
1237 _Jv_InitClass (&java::lang::VMThrowable::class$);
1238 java::lang::VMThrowable::trace_enabled = 0;
1240 // We have to initialize this fairly early, to avoid circular class
1241 // initialization. In particular we want to start the
1242 // initialization of ClassLoader before we start the initialization
1243 // of VMClassLoader.
1244 _Jv_InitClass (&java::lang::ClassLoader::class$);
1246 // Set up the system class loader and the bootstrap class loader.
1247 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1248 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1250 _Jv_RegisterBootstrapPackages();
1252 no_memory = new java::lang::OutOfMemoryError;
1254 java::lang::VMThrowable::trace_enabled = 1;
1256 #ifdef USE_LTDL
1257 LTDL_SET_PRELOADED_SYMBOLS ();
1258 #endif
1260 _Jv_platform_initialize ();
1262 _Jv_JNI_Init ();
1264 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1266 // Start the GC finalizer thread. A VirtualMachineError can be
1267 // thrown by the runtime if, say, threads aren't available.
1270 using namespace gnu::gcj::runtime;
1271 FinalizerThread *ft = new FinalizerThread ();
1272 ft->start ();
1274 catch (java::lang::VirtualMachineError *ignore)
1278 return 0;
1281 void
1282 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1283 const char **argv, bool is_jar)
1285 #ifndef DISABLE_MAIN_ARGS
1286 _Jv_SetArgs (argc, argv);
1287 #endif
1289 java::lang::Runtime *runtime = NULL;
1293 if (_Jv_CreateJavaVM (vm_args) < 0)
1295 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1296 exit (1);
1299 // Get the Runtime here. We want to initialize it before searching
1300 // for `main'; that way it will be set up if `main' is a JNI method.
1301 runtime = java::lang::Runtime::getRuntime ();
1303 #ifdef DISABLE_MAIN_ARGS
1304 arg_vec = JvConvertArgv (0, 0);
1305 #else
1306 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1307 #endif
1309 using namespace gnu::java::lang;
1310 if (klass)
1311 main_thread = new MainThread (klass, arg_vec);
1312 else
1313 main_thread = new MainThread (JvNewStringLatin1 (name),
1314 arg_vec, is_jar);
1316 catch (java::lang::Throwable *t)
1318 java::lang::System::err->println (JvNewStringLatin1
1319 ("Exception during runtime initialization"));
1320 t->printStackTrace();
1321 if (runtime)
1322 runtime->exit (1);
1323 // In case the runtime creation failed.
1324 ::exit (1);
1327 _Jv_AttachCurrentThread (main_thread);
1328 _Jv_ThreadRun (main_thread);
1329 _Jv_ThreadWait ();
1331 int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1332 runtime->exit (status);
1335 void
1336 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1337 bool is_jar)
1339 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1342 void
1343 JvRunMain (jclass klass, int argc, const char **argv)
1345 _Jv_RunMain (klass, NULL, argc, argv, false);
1350 // Parse a string and return a heap size.
1351 static size_t
1352 parse_heap_size (const char *spec)
1354 char *end;
1355 unsigned long val = strtoul (spec, &end, 10);
1356 if (*end == 'k' || *end == 'K')
1357 val *= 1024;
1358 else if (*end == 'm' || *end == 'M')
1359 val *= 1048576;
1360 return (size_t) val;
1363 // Set the initial heap size. This might be ignored by the GC layer.
1364 // This must be called before _Jv_RunMain.
1365 void
1366 _Jv_SetInitialHeapSize (const char *arg)
1368 size_t size = parse_heap_size (arg);
1369 _Jv_GCSetInitialHeapSize (size);
1372 // Set the maximum heap size. This might be ignored by the GC layer.
1373 // This must be called before _Jv_RunMain.
1374 void
1375 _Jv_SetMaximumHeapSize (const char *arg)
1377 size_t size = parse_heap_size (arg);
1378 _Jv_GCSetMaximumHeapSize (size);
1383 void *
1384 _Jv_Malloc (jsize size)
1386 if (__builtin_expect (size == 0, false))
1387 size = 1;
1388 void *ptr = malloc ((size_t) size);
1389 if (__builtin_expect (ptr == NULL, false))
1390 throw no_memory;
1391 return ptr;
1394 void *
1395 _Jv_Realloc (void *ptr, jsize size)
1397 if (__builtin_expect (size == 0, false))
1398 size = 1;
1399 ptr = realloc (ptr, (size_t) size);
1400 if (__builtin_expect (ptr == NULL, false))
1401 throw no_memory;
1402 return ptr;
1405 void *
1406 _Jv_MallocUnchecked (jsize size)
1408 if (__builtin_expect (size == 0, false))
1409 size = 1;
1410 return malloc ((size_t) size);
1413 void
1414 _Jv_Free (void* ptr)
1416 return free (ptr);
1421 // In theory, these routines can be #ifdef'd away on machines which
1422 // support divide overflow signals. However, we never know if some
1423 // code might have been compiled with "-fuse-divide-subroutine", so we
1424 // always include them in libgcj.
1426 jint
1427 _Jv_divI (jint dividend, jint divisor)
1429 if (__builtin_expect (divisor == 0, false))
1431 java::lang::ArithmeticException *arithexception
1432 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1433 throw arithexception;
1436 if (dividend == (jint) 0x80000000L && divisor == -1)
1437 return dividend;
1439 return dividend / divisor;
1442 jint
1443 _Jv_remI (jint dividend, jint divisor)
1445 if (__builtin_expect (divisor == 0, false))
1447 java::lang::ArithmeticException *arithexception
1448 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1449 throw arithexception;
1452 if (dividend == (jint) 0x80000000L && divisor == -1)
1453 return 0;
1455 return dividend % divisor;
1458 jlong
1459 _Jv_divJ (jlong dividend, jlong divisor)
1461 if (__builtin_expect (divisor == 0, false))
1463 java::lang::ArithmeticException *arithexception
1464 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1465 throw arithexception;
1468 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1469 return dividend;
1471 return dividend / divisor;
1474 jlong
1475 _Jv_remJ (jlong dividend, jlong divisor)
1477 if (__builtin_expect (divisor == 0, false))
1479 java::lang::ArithmeticException *arithexception
1480 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1481 throw arithexception;
1484 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1485 return 0;
1487 return dividend % divisor;
1492 // Return true if SELF_KLASS can access a field or method in
1493 // OTHER_KLASS. The field or method's access flags are specified in
1494 // FLAGS.
1495 jboolean
1496 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1498 using namespace java::lang::reflect;
1499 return ((self_klass == other_klass)
1500 || ((flags & Modifier::PUBLIC) != 0)
1501 || (((flags & Modifier::PROTECTED) != 0)
1502 && _Jv_IsAssignableFromSlow (other_klass, self_klass))
1503 || (((flags & Modifier::PRIVATE) == 0)
1504 && _Jv_ClassNameSamePackage (self_klass->name,
1505 other_klass->name)));