Fix entry.
[official-gcc.git] / libjava / prims.cc
blob9281711ae89ca025f46d044a5b9ecb1ec1b24fdd
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/reflect/Modifier.h>
59 #include <java/io/PrintStream.h>
60 #include <java/lang/UnsatisfiedLinkError.h>
61 #include <java/lang/VirtualMachineError.h>
62 #include <gnu/gcj/runtime/VMClassLoader.h>
63 #include <gnu/gcj/runtime/FinalizerThread.h>
64 #include <execution.h>
65 #include <gnu/java/lang/MainThread.h>
67 #ifdef USE_LTDL
68 #include <ltdl.h>
69 #endif
71 // Execution engine for compiled code.
72 _Jv_CompiledEngine _Jv_soleCompiledEngine;
74 // We allocate a single OutOfMemoryError exception which we keep
75 // around for use if we run out of memory.
76 static java::lang::OutOfMemoryError *no_memory;
78 // Number of bytes in largest array object we create. This could be
79 // increased to the largest size_t value, so long as the appropriate
80 // functions are changed to take a size_t argument instead of jint.
81 #define MAX_OBJECT_SIZE ((1<<31) - 1)
83 // Properties set at compile time.
84 const char **_Jv_Compiler_Properties = NULL;
85 int _Jv_Properties_Count = 0;
87 // The JAR file to add to the beginning of java.class.path.
88 const char *_Jv_Jar_Class_Path;
90 #ifndef DISABLE_GETENV_PROPERTIES
91 // Property key/value pairs.
92 property_pair *_Jv_Environment_Properties;
93 #endif
95 // Stash the argv pointer to benefit native libraries that need it.
96 const char **_Jv_argv;
97 int _Jv_argc;
99 // Argument support.
101 _Jv_GetNbArgs (void)
103 // _Jv_argc is 0 if not explicitly initialized.
104 return _Jv_argc;
107 const char *
108 _Jv_GetSafeArg (int index)
110 if (index >=0 && index < _Jv_GetNbArgs ())
111 return _Jv_argv[index];
112 else
113 return "";
116 void
117 _Jv_SetArgs (int argc, const char **argv)
119 _Jv_argc = argc;
120 _Jv_argv = argv;
123 #ifdef ENABLE_JVMPI
124 // Pointer to JVMPI notification functions.
125 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
126 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
127 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
128 #endif
131 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
132 /* Unblock a signal. Unless we do this, the signal may only be sent
133 once. */
134 static void
135 unblock_signal (int signum __attribute__ ((__unused__)))
137 #ifdef _POSIX_VERSION
138 sigset_t sigs;
140 sigemptyset (&sigs);
141 sigaddset (&sigs, signum);
142 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
143 #endif
145 #endif
147 #ifdef HANDLE_SEGV
148 SIGNAL_HANDLER (catch_segv)
150 unblock_signal (SIGSEGV);
151 MAKE_THROW_FRAME (nullp);
152 java::lang::NullPointerException *nullp
153 = new java::lang::NullPointerException;
154 throw nullp;
156 #endif
158 #ifdef HANDLE_FPE
159 SIGNAL_HANDLER (catch_fpe)
161 unblock_signal (SIGFPE);
162 #ifdef HANDLE_DIVIDE_OVERFLOW
163 HANDLE_DIVIDE_OVERFLOW;
164 #else
165 MAKE_THROW_FRAME (arithexception);
166 #endif
167 java::lang::ArithmeticException *arithexception
168 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
169 throw arithexception;
171 #endif
175 jboolean
176 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
178 int len;
179 const _Jv_ushort *aptr, *bptr;
180 if (a == b)
181 return true;
182 if (a->hash != b->hash)
183 return false;
184 len = a->length;
185 if (b->length != len)
186 return false;
187 aptr = (const _Jv_ushort *)a->data;
188 bptr = (const _Jv_ushort *)b->data;
189 len = (len + 1) >> 1;
190 while (--len >= 0)
191 if (*aptr++ != *bptr++)
192 return false;
193 return true;
196 /* True iff A is equal to STR.
197 HASH is STR->hashCode().
200 jboolean
201 _Jv_equal (Utf8Const* a, jstring str, jint hash)
203 if (a->hash != (_Jv_ushort) hash)
204 return false;
205 jint len = str->length();
206 jint i = 0;
207 jchar *sptr = _Jv_GetStringChars (str);
208 unsigned char* ptr = (unsigned char*) a->data;
209 unsigned char* limit = ptr + a->length;
210 for (;; i++, sptr++)
212 int ch = UTF8_GET (ptr, limit);
213 if (i == len)
214 return ch < 0;
215 if (ch != *sptr)
216 return false;
218 return true;
221 /* Like _Jv_equal, but stop after N characters. */
222 jboolean
223 _Jv_equaln (Utf8Const *a, jstring str, jint n)
225 jint len = str->length();
226 jint i = 0;
227 jchar *sptr = _Jv_GetStringChars (str);
228 unsigned char* ptr = (unsigned char*) a->data;
229 unsigned char* limit = ptr + a->length;
230 for (; n-- > 0; i++, sptr++)
232 int ch = UTF8_GET (ptr, limit);
233 if (i == len)
234 return ch < 0;
235 if (ch != *sptr)
236 return false;
238 return true;
241 /* Count the number of Unicode chars encoded in a given Ut8 string. */
243 _Jv_strLengthUtf8(char* str, int len)
245 unsigned char* ptr;
246 unsigned char* limit;
247 int str_length;
249 ptr = (unsigned char*) str;
250 limit = ptr + len;
251 str_length = 0;
252 for (; ptr < limit; str_length++)
254 if (UTF8_GET (ptr, limit) < 0)
255 return (-1);
257 return (str_length);
260 /* Calculate a hash value for a string encoded in Utf8 format.
261 * This returns the same hash value as specified or java.lang.String.hashCode.
263 jint
264 _Jv_hashUtf8String (char* str, int len)
266 unsigned char* ptr = (unsigned char*) str;
267 unsigned char* limit = ptr + len;
268 jint hash = 0;
270 for (; ptr < limit;)
272 int ch = UTF8_GET (ptr, limit);
273 /* Updated specification from
274 http://www.javasoft.com/docs/books/jls/clarify.html. */
275 hash = (31 * hash) + ch;
277 return hash;
280 void
281 _Jv_Utf8Const::init(char *s, int len)
283 ::memcpy (data, s, len);
284 data[len] = 0;
285 length = len;
286 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
289 _Jv_Utf8Const *
290 _Jv_makeUtf8Const (char* s, int len)
292 if (len < 0)
293 len = strlen (s);
294 Utf8Const* m
295 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
296 m->init(s, len);
297 return m;
300 _Jv_Utf8Const *
301 _Jv_makeUtf8Const (jstring string)
303 jint hash = string->hashCode ();
304 jint len = _Jv_GetStringUTFLength (string);
306 Utf8Const* m = (Utf8Const*)
307 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
309 m->hash = hash;
310 m->length = len;
312 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
313 m->data[len] = 0;
315 return m;
320 #ifdef DEBUG
321 void
322 _Jv_Abort (const char *function, const char *file, int line,
323 const char *message)
324 #else
325 void
326 _Jv_Abort (const char *, const char *, int, const char *message)
327 #endif
329 #ifdef DEBUG
330 fprintf (stderr,
331 "libgcj failure: %s\n in function %s, file %s, line %d\n",
332 message, function, file, line);
333 #else
334 fprintf (stderr, "libgcj failure: %s\n", message);
335 #endif
336 abort ();
339 static void
340 fail_on_finalization (jobject)
342 JvFail ("object was finalized");
345 void
346 _Jv_GCWatch (jobject obj)
348 _Jv_RegisterFinalizer (obj, fail_on_finalization);
351 void
352 _Jv_ThrowBadArrayIndex(jint bad_index)
354 throw new java::lang::ArrayIndexOutOfBoundsException
355 (java::lang::String::valueOf (bad_index));
358 void
359 _Jv_ThrowNullPointerException ()
361 throw new java::lang::NullPointerException;
364 // Explicitly throw a no memory exception.
365 // The collector calls this when it encounters an out-of-memory condition.
366 void _Jv_ThrowNoMemory()
368 throw no_memory;
371 #ifdef ENABLE_JVMPI
372 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
373 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
374 jvmpi_notify_alloc(klass,size,obj);
375 static void
376 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
378 // Service JVMPI allocation request.
379 JVMPI_Event event;
381 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
382 event.env_id = NULL;
383 event.u.obj_alloc.arena_id = 0;
384 event.u.obj_alloc.class_id = (jobjectID) klass;
385 event.u.obj_alloc.is_array = 0;
386 event.u.obj_alloc.size = size;
387 event.u.obj_alloc.obj_id = (jobjectID) obj;
389 // FIXME: This doesn't look right for the Boehm GC. A GC may
390 // already be in progress. _Jv_DisableGC () doesn't wait for it.
391 // More importantly, I don't see the need for disabling GC, since we
392 // blatantly have a pointer to obj on our stack, ensuring that the
393 // object can't be collected. Even for a nonconservative collector,
394 // it appears to me that this must be true, since we are about to
395 // return obj. Isn't this whole approach way too intrusive for
396 // a useful profiling interface? - HB
397 _Jv_DisableGC ();
398 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
399 _Jv_EnableGC ();
401 #else /* !ENABLE_JVMPI */
402 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
403 #endif
405 // Allocate a new object of class KLASS.
406 // First a version that assumes that we have no finalizer, and that
407 // the class is already initialized.
408 // If we know that JVMPI is disabled, this can be replaced by a direct call
409 // to the allocator for the appropriate GC.
410 jobject
411 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
413 jint size = klass->size ();
414 jobject obj = (jobject) _Jv_AllocObj (size, klass);
415 JVMPI_NOTIFY_ALLOC (klass, size, obj);
416 return obj;
419 // And now a version that initializes if necessary.
420 jobject
421 _Jv_AllocObjectNoFinalizer (jclass klass)
423 _Jv_InitClass (klass);
424 jint size = klass->size ();
425 jobject obj = (jobject) _Jv_AllocObj (size, klass);
426 JVMPI_NOTIFY_ALLOC (klass, size, obj);
427 return obj;
430 // And now the general version that registers a finalizer if necessary.
431 jobject
432 _Jv_AllocObject (jclass klass)
434 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
436 // We assume that the compiler only generates calls to this routine
437 // if there really is an interesting finalizer.
438 // Unfortunately, we still have to the dynamic test, since there may
439 // be cni calls to this routine.
440 // Note that on IA64 get_finalizer() returns the starting address of the
441 // function, not a function pointer. Thus this still works.
442 if (klass->vtable->get_finalizer ()
443 != java::lang::Object::class$.vtable->get_finalizer ())
444 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
445 return obj;
448 // Allocate a String, including variable length storage.
449 jstring
450 _Jv_AllocString(jsize len)
452 using namespace java::lang;
454 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
456 // We assert that for strings allocated this way, the data field
457 // will always point to the object itself. Thus there is no reason
458 // for the garbage collector to scan any of it.
459 // Furthermore, we're about to overwrite the string data, so
460 // initialization of the object is not an issue.
462 // String needs no initialization, and there is no finalizer, so
463 // we can go directly to the collector's allocator interface.
464 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
466 obj->data = obj;
467 obj->boffset = sizeof(java::lang::String);
468 obj->count = len;
469 obj->cachedHashCode = 0;
471 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
473 return obj;
476 // A version of the above that assumes the object contains no pointers,
477 // and requires no finalization. This can't happen if we need pointers
478 // to locks.
479 #ifdef JV_HASH_SYNCHRONIZATION
480 jobject
481 _Jv_AllocPtrFreeObject (jclass klass)
483 _Jv_InitClass (klass);
484 jint size = klass->size ();
486 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
488 JVMPI_NOTIFY_ALLOC (klass, size, obj);
490 return obj;
492 #endif /* JV_HASH_SYNCHRONIZATION */
495 // Allocate a new array of Java objects. Each object is of type
496 // `elementClass'. `init' is used to initialize each slot in the
497 // array.
498 jobjectArray
499 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
501 if (__builtin_expect (count < 0, false))
502 throw new java::lang::NegativeArraySizeException;
504 JvAssert (! elementClass->isPrimitive ());
506 // Ensure that elements pointer is properly aligned.
507 jobjectArray obj = NULL;
508 size_t size = (size_t) elements (obj);
509 // Check for overflow.
510 if (__builtin_expect ((size_t) count >
511 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
512 throw no_memory;
514 size += count * sizeof (jobject);
516 jclass klass = _Jv_GetArrayClass (elementClass,
517 elementClass->getClassLoaderInternal());
519 obj = (jobjectArray) _Jv_AllocArray (size, klass);
520 // Cast away const.
521 jsize *lp = const_cast<jsize *> (&obj->length);
522 *lp = count;
523 // We know the allocator returns zeroed memory. So don't bother
524 // zeroing it again.
525 if (init)
527 jobject *ptr = elements(obj);
528 while (--count >= 0)
529 *ptr++ = init;
531 return obj;
534 // Allocate a new array of primitives. ELTYPE is the type of the
535 // element, COUNT is the size of the array.
536 jobject
537 _Jv_NewPrimArray (jclass eltype, jint count)
539 int elsize = eltype->size();
540 if (__builtin_expect (count < 0, false))
541 throw new java::lang::NegativeArraySizeException;
543 JvAssert (eltype->isPrimitive ());
544 jobject dummy = NULL;
545 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
547 // Check for overflow.
548 if (__builtin_expect ((size_t) count >
549 (MAX_OBJECT_SIZE - size) / elsize, false))
550 throw no_memory;
552 jclass klass = _Jv_GetArrayClass (eltype, 0);
554 # ifdef JV_HASH_SYNCHRONIZATION
555 // Since the vtable is always statically allocated,
556 // these are completely pointerfree! Make sure the GC doesn't touch them.
557 __JArray *arr =
558 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
559 memset((char *)arr + size, 0, elsize * count);
560 # else
561 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
562 // Note that we assume we are given zeroed memory by the allocator.
563 # endif
564 // Cast away const.
565 jsize *lp = const_cast<jsize *> (&arr->length);
566 *lp = count;
568 return arr;
571 jobject
572 _Jv_NewArray (jint type, jint size)
574 switch (type)
576 case 4: return JvNewBooleanArray (size);
577 case 5: return JvNewCharArray (size);
578 case 6: return JvNewFloatArray (size);
579 case 7: return JvNewDoubleArray (size);
580 case 8: return JvNewByteArray (size);
581 case 9: return JvNewShortArray (size);
582 case 10: return JvNewIntArray (size);
583 case 11: return JvNewLongArray (size);
585 throw new java::lang::InternalError
586 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
589 // Allocate a possibly multi-dimensional array but don't check that
590 // any array length is <0.
591 static jobject
592 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
594 JvAssert (type->isArray());
595 jclass element_type = type->getComponentType();
596 jobject result;
597 if (element_type->isPrimitive())
598 result = _Jv_NewPrimArray (element_type, sizes[0]);
599 else
600 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
602 if (dimensions > 1)
604 JvAssert (! element_type->isPrimitive());
605 JvAssert (element_type->isArray());
606 jobject *contents = elements ((jobjectArray) result);
607 for (int i = 0; i < sizes[0]; ++i)
608 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
609 sizes + 1);
612 return result;
615 jobject
616 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
618 for (int i = 0; i < dimensions; ++i)
619 if (sizes[i] < 0)
620 throw new java::lang::NegativeArraySizeException;
622 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
625 jobject
626 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
628 va_list args;
629 jint sizes[dimensions];
630 va_start (args, dimensions);
631 for (int i = 0; i < dimensions; ++i)
633 jint size = va_arg (args, jint);
634 if (size < 0)
635 throw new java::lang::NegativeArraySizeException;
636 sizes[i] = size;
638 va_end (args);
640 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
645 // Ensure 8-byte alignment, for hash synchronization.
646 #define DECLARE_PRIM_TYPE(NAME) \
647 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
649 DECLARE_PRIM_TYPE(byte)
650 DECLARE_PRIM_TYPE(short)
651 DECLARE_PRIM_TYPE(int)
652 DECLARE_PRIM_TYPE(long)
653 DECLARE_PRIM_TYPE(boolean)
654 DECLARE_PRIM_TYPE(char)
655 DECLARE_PRIM_TYPE(float)
656 DECLARE_PRIM_TYPE(double)
657 DECLARE_PRIM_TYPE(void)
659 void
660 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len)
662 using namespace java::lang::reflect;
664 // We must set the vtable for the class; the Java constructor
665 // doesn't do this.
666 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
668 // Initialize the fields we care about. We do this in the same
669 // order they are declared in Class.h.
670 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
671 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
672 cl->method_count = sig;
673 cl->size_in_bytes = len;
674 cl->vtable = JV_PRIMITIVE_VTABLE;
675 cl->state = JV_STATE_DONE;
676 cl->depth = -1;
679 jclass
680 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
682 switch (*sig)
684 case 'B':
685 return JvPrimClass (byte);
686 case 'S':
687 return JvPrimClass (short);
688 case 'I':
689 return JvPrimClass (int);
690 case 'J':
691 return JvPrimClass (long);
692 case 'Z':
693 return JvPrimClass (boolean);
694 case 'C':
695 return JvPrimClass (char);
696 case 'F':
697 return JvPrimClass (float);
698 case 'D':
699 return JvPrimClass (double);
700 case 'V':
701 return JvPrimClass (void);
702 case 'L':
704 int i;
705 for (i = 1; sig[i] && sig[i] != ';'; ++i)
707 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
708 return _Jv_FindClass (name, loader);
710 case '[':
712 jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
713 if (! klass)
714 return NULL;
715 return _Jv_GetArrayClass (klass, loader);
719 return NULL; // Placate compiler.
724 JArray<jstring> *
725 JvConvertArgv (int argc, const char **argv)
727 if (argc < 0)
728 argc = 0;
729 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
730 jobject *ptr = elements(ar);
731 jbyteArray bytes = NULL;
732 for (int i = 0; i < argc; i++)
734 const char *arg = argv[i];
735 int len = strlen (arg);
736 if (bytes == NULL || bytes->length < len)
737 bytes = JvNewByteArray (len);
738 jbyte *bytePtr = elements (bytes);
739 // We assume jbyte == char.
740 memcpy (bytePtr, arg, len);
742 // Now convert using the default encoding.
743 *ptr++ = new java::lang::String (bytes, 0, len);
745 return (JArray<jstring>*) ar;
748 // FIXME: These variables are static so that they will be
749 // automatically scanned by the Boehm collector. This is needed
750 // because with qthreads the collector won't scan the initial stack --
751 // it will only scan the qthreads stacks.
753 // Command line arguments.
754 static JArray<jstring> *arg_vec;
756 // The primary thread.
757 static java::lang::Thread *main_thread;
759 #ifndef DISABLE_GETENV_PROPERTIES
761 static char *
762 next_property_key (char *s, size_t *length)
764 size_t l = 0;
766 JvAssert (s);
768 // Skip over whitespace
769 while (isspace (*s))
770 s++;
772 // If we've reached the end, return NULL. Also return NULL if for
773 // some reason we've come across a malformed property string.
774 if (*s == 0
775 || *s == ':'
776 || *s == '=')
777 return NULL;
779 // Determine the length of the property key.
780 while (s[l] != 0
781 && ! isspace (s[l])
782 && s[l] != ':'
783 && s[l] != '=')
785 if (s[l] == '\\'
786 && s[l+1] != 0)
787 l++;
788 l++;
791 *length = l;
793 return s;
796 static char *
797 next_property_value (char *s, size_t *length)
799 size_t l = 0;
801 JvAssert (s);
803 while (isspace (*s))
804 s++;
806 if (*s == ':'
807 || *s == '=')
808 s++;
810 while (isspace (*s))
811 s++;
813 // If we've reached the end, return NULL.
814 if (*s == 0)
815 return NULL;
817 // Determine the length of the property value.
818 while (s[l] != 0
819 && ! isspace (s[l])
820 && s[l] != ':'
821 && s[l] != '=')
823 if (s[l] == '\\'
824 && s[l+1] != 0)
825 l += 2;
826 else
827 l++;
830 *length = l;
832 return s;
835 static void
836 process_gcj_properties ()
838 char *props = getenv("GCJ_PROPERTIES");
839 char *p = props;
840 size_t length;
841 size_t property_count = 0;
843 if (NULL == props)
844 return;
846 // Whip through props quickly in order to count the number of
847 // property values.
848 while (p && (p = next_property_key (p, &length)))
850 // Skip to the end of the key
851 p += length;
853 p = next_property_value (p, &length);
854 if (p)
855 p += length;
857 property_count++;
860 // Allocate an array of property value/key pairs.
861 _Jv_Environment_Properties =
862 (property_pair *) malloc (sizeof(property_pair)
863 * (property_count + 1));
865 // Go through the properties again, initializing _Jv_Properties
866 // along the way.
867 p = props;
868 property_count = 0;
869 while (p && (p = next_property_key (p, &length)))
871 _Jv_Environment_Properties[property_count].key = p;
872 _Jv_Environment_Properties[property_count].key_length = length;
874 // Skip to the end of the key
875 p += length;
877 p = next_property_value (p, &length);
879 _Jv_Environment_Properties[property_count].value = p;
880 _Jv_Environment_Properties[property_count].value_length = length;
882 if (p)
883 p += length;
885 property_count++;
887 memset ((void *) &_Jv_Environment_Properties[property_count],
888 0, sizeof (property_pair));
890 // Null terminate the strings.
891 for (property_pair *prop = &_Jv_Environment_Properties[0];
892 prop->key != NULL;
893 prop++)
895 prop->key[prop->key_length] = 0;
896 prop->value[prop->value_length] = 0;
899 #endif // DISABLE_GETENV_PROPERTIES
901 namespace gcj
903 _Jv_Utf8Const *void_signature;
904 _Jv_Utf8Const *clinit_name;
905 _Jv_Utf8Const *init_name;
906 _Jv_Utf8Const *finit_name;
908 bool runtimeInitialized = false;
911 static jint
912 parse_verbose_args (char* option_string,
913 bool ignore_unrecognized)
915 size_t len = sizeof ("-verbose");
917 if (strlen (option_string) < len)
918 return -1;
920 if (option_string[len] == ':'
921 && option_string[len + 1] != '\0')
923 char* verbose_args = option_string + len + 1;
924 size_t last = 0;
928 if (! strncmp (verbose_args,
929 "gc", (last = sizeof ("gc")) - 1)
930 && (verbose_args[last] == '\0'
931 || verbose_args[last] == ','))
933 // FIXME: we should add functions to boehm-gc that
934 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
935 // GC_print_back_height.
938 else if (! strncmp (verbose_args,
939 "class",
940 (last = sizeof ("class")) - 1)
941 && (verbose_args[last] == '\0'
942 || verbose_args[last] == ','))
944 gcj::verbose_class_flag = true;
946 else if (! strncmp (verbose_args, "jni",
947 (last = sizeof ("jni")) - 1)
948 && (verbose_args[last] == '\0'
949 || verbose_args[last] == ','))
951 // FIXME: enable JNI messages.
953 else if (ignore_unrecognized
954 && verbose_args[0] == 'X')
956 // ignore unrecognized non-standard verbose option
957 last = 0;
958 while (verbose_args[last] != '\0'
959 && verbose_args[last++] != ',');
962 if (strlen (verbose_args) >= last)
964 if (verbose_args[last] == ',')
966 if (verbose_args[last + 1] == '\0')
967 // trailing comma
968 return -1;
969 else
971 verbose_args = verbose_args + last + 1;
972 last = 0;
975 // here verbose_args[last] is either '\0' or
976 // the first character in the next verbose
977 // argument.
979 else
980 // partial option
981 return -1;
983 // verbose_args[last] will be '\0' here if we're
984 // done.
986 while (verbose_args[last] != '\0');
988 else if (option_string[len] == 'g'
989 && option_string[len + 1] == 'c'
990 && option_string[len + 2] == '\0')
992 // FIXME: we should add functions to boehm-gc that
993 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
994 // GC_print_back_height.
995 return 0;
997 else if (option_string[len] == '\0')
999 gcj::verbose_class_flag = true;
1000 return 0;
1002 else
1004 // unrecognized option beginning with -verbose
1005 return -1;
1007 return 0;
1010 static jint
1011 parse_init_args (JvVMInitArgs* vm_args)
1013 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1014 // re-allocated dynamically.
1015 if (_Jv_Compiler_Properties)
1017 const char** props = _Jv_Compiler_Properties;
1018 _Jv_Compiler_Properties = NULL;
1020 for (int i = 0; props[i]; i++)
1022 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1023 (_Jv_Compiler_Properties,
1024 (_Jv_Properties_Count + 1) * sizeof (const char*));
1025 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1029 if (vm_args == NULL)
1030 return 0;
1032 for (int i = 0; i < vm_args->nOptions; ++i)
1034 char* option_string = vm_args->options[i].optionString;
1035 if (! strcmp (option_string, "vfprintf")
1036 || ! strcmp (option_string, "exit")
1037 || ! strcmp (option_string, "abort"))
1039 // FIXME: we are required to recognize these, but for
1040 // now we don't handle them in any way.
1041 continue;
1043 else if (! strncmp (option_string,
1044 "-verbose", sizeof ("-verbose") - 1))
1046 jint result = parse_verbose_args (option_string,
1047 vm_args->ignoreUnrecognized);
1048 if (result < 0)
1049 return result;
1051 else if (! strncmp (option_string, "-D", 2))
1053 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1054 (_Jv_Compiler_Properties,
1055 (_Jv_Properties_Count + 1) * sizeof (char*));
1057 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1058 strdup (option_string + 2);
1060 continue;
1062 else if (vm_args->ignoreUnrecognized)
1064 if (option_string[0] == '_'
1065 || ! strncmp (option_string, "-X", 2))
1066 continue;
1069 return 0;
1072 jint
1073 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1075 using namespace gcj;
1077 if (runtimeInitialized)
1078 return -1;
1080 runtimeInitialized = true;
1082 jint result = parse_init_args (vm_args);
1083 if (result < 0)
1084 return -1;
1086 PROCESS_GCJ_PROPERTIES;
1088 /* Threads must be initialized before the GC, so that it inherits the
1089 signal mask. */
1090 _Jv_InitThreads ();
1091 _Jv_InitGC ();
1092 _Jv_InitializeSyncMutex ();
1094 #ifdef INTERPRETER
1095 _Jv_InitInterpreter ();
1096 #endif
1098 #ifdef HANDLE_SEGV
1099 INIT_SEGV;
1100 #endif
1102 #ifdef HANDLE_FPE
1103 INIT_FPE;
1104 #endif
1106 /* Initialize Utf8 constants declared in jvm.h. */
1107 void_signature = _Jv_makeUtf8Const ("()V", 3);
1108 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1109 init_name = _Jv_makeUtf8Const ("<init>", 6);
1110 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1112 /* Initialize built-in classes to represent primitive TYPEs. */
1113 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1114 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1115 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1116 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1117 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1118 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1119 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1120 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1121 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1123 // Turn stack trace generation off while creating exception objects.
1124 _Jv_InitClass (&java::lang::VMThrowable::class$);
1125 java::lang::VMThrowable::trace_enabled = 0;
1127 // We have to initialize this fairly early, to avoid circular class
1128 // initialization. In particular we want to start the
1129 // initialization of ClassLoader before we start the initialization
1130 // of VMClassLoader.
1131 _Jv_InitClass (&java::lang::ClassLoader::class$);
1133 // Set up the system class loader.
1134 gnu::gcj::runtime::VMClassLoader::initialize();
1136 _Jv_RegisterBootstrapPackages();
1138 no_memory = new java::lang::OutOfMemoryError;
1140 java::lang::VMThrowable::trace_enabled = 1;
1142 #ifdef USE_LTDL
1143 LTDL_SET_PRELOADED_SYMBOLS ();
1144 #endif
1146 _Jv_platform_initialize ();
1148 _Jv_JNI_Init ();
1150 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1152 // Start the GC finalizer thread. A VirtualMachineError can be
1153 // thrown by the runtime if, say, threads aren't available.
1156 using namespace gnu::gcj::runtime;
1157 FinalizerThread *ft = new FinalizerThread ();
1158 ft->start ();
1160 catch (java::lang::VirtualMachineError *ignore)
1164 return 0;
1167 void
1168 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1169 bool is_jar)
1171 #ifndef DISABLE_MAIN_ARGS
1172 _Jv_SetArgs (argc, argv);
1173 #endif
1175 java::lang::Runtime *runtime = NULL;
1179 // Set this very early so that it is seen when java.lang.System
1180 // is initialized.
1181 if (is_jar)
1182 _Jv_Jar_Class_Path = strdup (name);
1184 if (_Jv_CreateJavaVM (NULL) < 0)
1186 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1187 exit (1);
1190 // Get the Runtime here. We want to initialize it before searching
1191 // for `main'; that way it will be set up if `main' is a JNI method.
1192 runtime = java::lang::Runtime::getRuntime ();
1194 #ifdef DISABLE_MAIN_ARGS
1195 arg_vec = JvConvertArgv (0, 0);
1196 #else
1197 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1198 #endif
1200 using namespace gnu::java::lang;
1201 if (klass)
1202 main_thread = new MainThread (klass, arg_vec);
1203 else
1204 main_thread = new MainThread (JvNewStringLatin1 (name),
1205 arg_vec, is_jar);
1207 catch (java::lang::Throwable *t)
1209 java::lang::System::err->println (JvNewStringLatin1
1210 ("Exception during runtime initialization"));
1211 t->printStackTrace();
1212 runtime->exit (1);
1215 _Jv_AttachCurrentThread (main_thread);
1216 _Jv_ThreadRun (main_thread);
1217 _Jv_ThreadWait ();
1219 int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1220 runtime->exit (status);
1223 void
1224 JvRunMain (jclass klass, int argc, const char **argv)
1226 _Jv_RunMain (klass, NULL, argc, argv, false);
1231 // Parse a string and return a heap size.
1232 static size_t
1233 parse_heap_size (const char *spec)
1235 char *end;
1236 unsigned long val = strtoul (spec, &end, 10);
1237 if (*end == 'k' || *end == 'K')
1238 val *= 1024;
1239 else if (*end == 'm' || *end == 'M')
1240 val *= 1048576;
1241 return (size_t) val;
1244 // Set the initial heap size. This might be ignored by the GC layer.
1245 // This must be called before _Jv_RunMain.
1246 void
1247 _Jv_SetInitialHeapSize (const char *arg)
1249 size_t size = parse_heap_size (arg);
1250 _Jv_GCSetInitialHeapSize (size);
1253 // Set the maximum heap size. This might be ignored by the GC layer.
1254 // This must be called before _Jv_RunMain.
1255 void
1256 _Jv_SetMaximumHeapSize (const char *arg)
1258 size_t size = parse_heap_size (arg);
1259 _Jv_GCSetMaximumHeapSize (size);
1264 void *
1265 _Jv_Malloc (jsize size)
1267 if (__builtin_expect (size == 0, false))
1268 size = 1;
1269 void *ptr = malloc ((size_t) size);
1270 if (__builtin_expect (ptr == NULL, false))
1271 throw no_memory;
1272 return ptr;
1275 void *
1276 _Jv_Realloc (void *ptr, jsize size)
1278 if (__builtin_expect (size == 0, false))
1279 size = 1;
1280 ptr = realloc (ptr, (size_t) size);
1281 if (__builtin_expect (ptr == NULL, false))
1282 throw no_memory;
1283 return ptr;
1286 void *
1287 _Jv_MallocUnchecked (jsize size)
1289 if (__builtin_expect (size == 0, false))
1290 size = 1;
1291 return malloc ((size_t) size);
1294 void
1295 _Jv_Free (void* ptr)
1297 return free (ptr);
1302 // In theory, these routines can be #ifdef'd away on machines which
1303 // support divide overflow signals. However, we never know if some
1304 // code might have been compiled with "-fuse-divide-subroutine", so we
1305 // always include them in libgcj.
1307 jint
1308 _Jv_divI (jint dividend, jint divisor)
1310 if (__builtin_expect (divisor == 0, false))
1312 java::lang::ArithmeticException *arithexception
1313 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1314 throw arithexception;
1317 if (dividend == (jint) 0x80000000L && divisor == -1)
1318 return dividend;
1320 return dividend / divisor;
1323 jint
1324 _Jv_remI (jint dividend, jint divisor)
1326 if (__builtin_expect (divisor == 0, false))
1328 java::lang::ArithmeticException *arithexception
1329 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1330 throw arithexception;
1333 if (dividend == (jint) 0x80000000L && divisor == -1)
1334 return 0;
1336 return dividend % divisor;
1339 jlong
1340 _Jv_divJ (jlong dividend, jlong divisor)
1342 if (__builtin_expect (divisor == 0, false))
1344 java::lang::ArithmeticException *arithexception
1345 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1346 throw arithexception;
1349 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1350 return dividend;
1352 return dividend / divisor;
1355 jlong
1356 _Jv_remJ (jlong dividend, jlong divisor)
1358 if (__builtin_expect (divisor == 0, false))
1360 java::lang::ArithmeticException *arithexception
1361 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1362 throw arithexception;
1365 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1366 return 0;
1368 return dividend % divisor;
1373 // Return true if SELF_KLASS can access a field or method in
1374 // OTHER_KLASS. The field or method's access flags are specified in
1375 // FLAGS.
1376 jboolean
1377 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1379 using namespace java::lang::reflect;
1380 return ((self_klass == other_klass)
1381 || ((flags & Modifier::PUBLIC) != 0)
1382 || (((flags & Modifier::PROTECTED) != 0)
1383 && _Jv_IsAssignableFromSlow (other_klass, self_klass))
1384 || (((flags & Modifier::PRIVATE) == 0)
1385 && _Jv_ClassNameSamePackage (self_klass->name,
1386 other_klass->name)));