It appears that we can now successfully all of spec and libgcj, flow-sensitively...
[official-gcc.git] / libjava / prims.cc
blob601f89ffc3d015d68da70c3f55cb19e679928340
1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
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/ClassNotFoundException.h>
53 #include <java/lang/InternalError.h>
54 #include <java/lang/NegativeArraySizeException.h>
55 #include <java/lang/NoClassDefFoundError.h>
56 #include <java/lang/NullPointerException.h>
57 #include <java/lang/OutOfMemoryError.h>
58 #include <java/lang/System.h>
59 #include <java/lang/VMClassLoader.h>
60 #include <java/lang/reflect/Modifier.h>
61 #include <java/io/PrintStream.h>
62 #include <java/lang/UnsatisfiedLinkError.h>
63 #include <java/lang/VirtualMachineError.h>
64 #include <gnu/gcj/runtime/ExtensionClassLoader.h>
65 #include <gnu/gcj/runtime/FinalizerThread.h>
66 #include <execution.h>
67 #include <gnu/classpath/jdwp/Jdwp.h>
68 #include <gnu/classpath/jdwp/VMVirtualMachine.h>
69 #include <gnu/classpath/jdwp/event/VmDeathEvent.h>
70 #include <gnu/classpath/jdwp/event/VmInitEvent.h>
71 #include <gnu/java/lang/MainThread.h>
73 #ifdef USE_LTDL
74 #include <ltdl.h>
75 #endif
77 #include "mem_usage.h"
79 static FILE* output = NULL;
80 void
81 note_memory_usage (const char* note, jsize size)
83 if (!output) output = fopen("mem", "w");
84 fprintf (output, "%s%d\n", note, (int)size);
87 // Execution engine for compiled code.
88 _Jv_CompiledEngine _Jv_soleCompiledEngine;
90 // Execution engine for code compiled with -findirect-classes
91 _Jv_IndirectCompiledEngine _Jv_soleIndirectCompiledEngine;
93 // We allocate a single OutOfMemoryError exception which we keep
94 // around for use if we run out of memory.
95 static java::lang::OutOfMemoryError *no_memory;
97 // Number of bytes in largest array object we create. This could be
98 // increased to the largest size_t value, so long as the appropriate
99 // functions are changed to take a size_t argument instead of jint.
100 #define MAX_OBJECT_SIZE ((1<<31) - 1)
102 // Properties set at compile time.
103 const char **_Jv_Compiler_Properties = NULL;
104 int _Jv_Properties_Count = 0;
106 #ifndef DISABLE_GETENV_PROPERTIES
107 // Property key/value pairs.
108 property_pair *_Jv_Environment_Properties;
109 #endif
111 // Stash the argv pointer to benefit native libraries that need it.
112 const char **_Jv_argv;
113 int _Jv_argc;
115 // Debugging options
116 static bool remoteDebug = false;
117 static char *jdwpOptions = "";
119 // Argument support.
121 _Jv_GetNbArgs (void)
123 // _Jv_argc is 0 if not explicitly initialized.
124 return _Jv_argc;
127 const char *
128 _Jv_GetSafeArg (int index)
130 if (index >=0 && index < _Jv_GetNbArgs ())
131 return _Jv_argv[index];
132 else
133 return "";
136 void
137 _Jv_SetArgs (int argc, const char **argv)
139 _Jv_argc = argc;
140 _Jv_argv = argv;
143 #ifdef ENABLE_JVMPI
144 // Pointer to JVMPI notification functions.
145 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
146 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
147 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
148 #endif
151 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
152 /* Unblock a signal. Unless we do this, the signal may only be sent
153 once. */
154 static void
155 unblock_signal (int signum __attribute__ ((__unused__)))
157 #ifdef _POSIX_VERSION
158 sigset_t sigs;
160 sigemptyset (&sigs);
161 sigaddset (&sigs, signum);
162 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
163 #endif
165 #endif
167 #ifdef HANDLE_SEGV
168 SIGNAL_HANDLER (catch_segv)
170 unblock_signal (SIGSEGV);
171 MAKE_THROW_FRAME (nullp);
172 java::lang::NullPointerException *nullp
173 = new java::lang::NullPointerException;
174 throw nullp;
176 #endif
178 #ifdef HANDLE_FPE
179 SIGNAL_HANDLER (catch_fpe)
181 unblock_signal (SIGFPE);
182 #ifdef HANDLE_DIVIDE_OVERFLOW
183 HANDLE_DIVIDE_OVERFLOW;
184 #else
185 MAKE_THROW_FRAME (arithexception);
186 #endif
187 java::lang::ArithmeticException *arithexception
188 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
189 throw arithexception;
191 #endif
194 jboolean
195 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
197 int len;
198 const _Jv_ushort *aptr, *bptr;
199 if (a == b)
200 return true;
201 if (a->hash != b->hash)
202 return false;
203 len = a->length;
204 if (b->length != len)
205 return false;
206 aptr = (const _Jv_ushort *)a->data;
207 bptr = (const _Jv_ushort *)b->data;
208 len = (len + 1) >> 1;
209 while (--len >= 0)
210 if (*aptr++ != *bptr++)
211 return false;
212 return true;
215 /* True iff A is equal to STR.
216 HASH is STR->hashCode().
219 jboolean
220 _Jv_equal (Utf8Const* a, jstring str, jint hash)
222 if (a->hash != (_Jv_ushort) hash)
223 return false;
224 jint len = str->length();
225 jint i = 0;
226 jchar *sptr = _Jv_GetStringChars (str);
227 unsigned char* ptr = (unsigned char*) a->data;
228 unsigned char* limit = ptr + a->length;
229 for (;; i++, sptr++)
231 int ch = UTF8_GET (ptr, limit);
232 if (i == len)
233 return ch < 0;
234 if (ch != *sptr)
235 return false;
237 return true;
240 /* Like _Jv_equal, but stop after N characters. */
241 jboolean
242 _Jv_equaln (Utf8Const *a, jstring str, jint n)
244 jint len = str->length();
245 jint i = 0;
246 jchar *sptr = _Jv_GetStringChars (str);
247 unsigned char* ptr = (unsigned char*) a->data;
248 unsigned char* limit = ptr + a->length;
249 for (; n-- > 0; i++, sptr++)
251 int ch = UTF8_GET (ptr, limit);
252 if (i == len)
253 return ch < 0;
254 if (ch != *sptr)
255 return false;
257 return true;
260 // Determines whether the given Utf8Const object contains
261 // a type which is primitive or some derived form of it, eg.
262 // an array or multi-dimensional array variant.
263 jboolean
264 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
266 unsigned char *aptr = (unsigned char *) a->data;
267 unsigned char *alimit = aptr + a->length;
268 int ac = UTF8_GET(aptr, alimit);
270 // Skips any leading array marks.
271 while (ac == '[')
272 ac = UTF8_GET(aptr, alimit);
274 // There should not be another character. This implies that
275 // the type name is only one character long.
276 if (UTF8_GET(aptr, alimit) == -1)
277 switch ( ac )
279 case 'Z':
280 case 'B':
281 case 'C':
282 case 'S':
283 case 'I':
284 case 'J':
285 case 'F':
286 case 'D':
287 return true;
288 default:
289 break;
292 return false;
295 // Find out whether two _Jv_Utf8Const candidates contain the same
296 // classname.
297 // The method is written to handle the different formats of classnames.
298 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
299 // "java.lang.Class" will be seen as equal.
300 // Warning: This function is not smart enough to declare "Z" and "boolean"
301 // and similar cases as equal (and is not meant to be used this way)!
302 jboolean
303 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
305 // If the class name's length differs by two characters
306 // it is possible that we have candidates which are given
307 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
308 switch (a->length - b->length)
310 case -2:
311 case 0:
312 case 2:
313 break;
314 default:
315 return false;
318 unsigned char *aptr = (unsigned char *) a->data;
319 unsigned char *alimit = aptr + a->length;
320 unsigned char *bptr = (unsigned char *) b->data;
321 unsigned char *blimit = bptr + b->length;
323 if (alimit[-1] == ';')
324 alimit--;
326 if (blimit[-1] == ';')
327 blimit--;
329 int ac = UTF8_GET(aptr, alimit);
330 int bc = UTF8_GET(bptr, blimit);
332 // Checks whether both strings have the same amount of leading [ characters.
333 while (ac == '[')
335 if (bc == '[')
337 ac = UTF8_GET(aptr, alimit);
338 bc = UTF8_GET(bptr, blimit);
339 continue;
342 return false;
345 // Skips leading L character.
346 if (ac == 'L')
347 ac = UTF8_GET(aptr, alimit);
349 if (bc == 'L')
350 bc = UTF8_GET(bptr, blimit);
352 // Compares the remaining characters.
353 while (ac != -1 && bc != -1)
355 // Replaces package separating dots with slashes.
356 if (ac == '.')
357 ac = '/';
359 if (bc == '.')
360 bc = '/';
362 // Now classnames differ if there is at least one non-matching
363 // character.
364 if (ac != bc)
365 return false;
367 ac = UTF8_GET(aptr, alimit);
368 bc = UTF8_GET(bptr, blimit);
371 return (ac == bc);
374 /* Count the number of Unicode chars encoded in a given Ut8 string. */
376 _Jv_strLengthUtf8(const char* str, int len)
378 unsigned char* ptr;
379 unsigned char* limit;
380 int str_length;
382 ptr = (unsigned char*) str;
383 limit = ptr + len;
384 str_length = 0;
385 for (; ptr < limit; str_length++)
387 if (UTF8_GET (ptr, limit) < 0)
388 return (-1);
390 return (str_length);
393 /* Calculate a hash value for a string encoded in Utf8 format.
394 * This returns the same hash value as specified or java.lang.String.hashCode.
396 jint
397 _Jv_hashUtf8String (const char* str, int len)
399 unsigned char* ptr = (unsigned char*) str;
400 unsigned char* limit = ptr + len;
401 jint hash = 0;
403 for (; ptr < limit;)
405 int ch = UTF8_GET (ptr, limit);
406 /* Updated specification from
407 http://www.javasoft.com/docs/books/jls/clarify.html. */
408 hash = (31 * hash) + ch;
410 return hash;
413 void
414 _Jv_Utf8Const::init(const char *s, int len)
416 ::memcpy (data, s, len);
417 data[len] = 0;
418 length = len;
419 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
422 /* for info only -same as below*/
423 _Jv_Utf8Const *
424 _Jv_InitUtf8Const (const char* s, int len)
426 if (len < 0)
427 len = strlen (s);
428 int size = _Jv_Utf8Const::space_needed(s, len);
429 NOTE_MEMORY_USAGE ("A", size);
430 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (size);
431 m->init(s, len);
432 return m;
435 _Jv_Utf8Const *
436 _Jv_makeUtf8Const (const char* s, int len)
438 if (len < 0)
439 len = strlen (s);
440 int size = _Jv_Utf8Const::space_needed(s, len);
441 NOTE_MEMORY_USAGE ("a", size);
442 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (size);
443 m->init(s, len);
444 return m;
447 /* for info only */
448 _Jv_Utf8Const *
449 _Jv_InitUtf8Const (jstring string)
451 jint hash = string->hashCode ();
452 jint len = _Jv_GetStringUTFLength (string);
454 NOTE_MEMORY_USAGE ("B", sizeof(Utf8Const) + len + 1);
455 Utf8Const* m = (Utf8Const*)
456 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
458 m->hash = hash;
459 m->length = len;
461 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
462 m->data[len] = 0;
464 return m;
467 _Jv_Utf8Const *
468 _Jv_makeUtf8Const (jstring string)
470 jint hash = string->hashCode ();
471 jint len = _Jv_GetStringUTFLength (string);
473 NOTE_MEMORY_USAGE ("b", sizeof(Utf8Const) + len + 1);
474 Utf8Const* m = (Utf8Const*)
475 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
477 m->hash = hash;
478 m->length = len;
480 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
481 m->data[len] = 0;
483 return m;
488 #ifdef DEBUG
489 void
490 _Jv_Abort (const char *function, const char *file, int line,
491 const char *message)
492 #else
493 void
494 _Jv_Abort (const char *, const char *, int, const char *message)
495 #endif
497 #ifdef DEBUG
498 fprintf (stderr,
499 "libgcj failure: %s\n in function %s, file %s, line %d\n",
500 message, function, file, line);
501 #else
502 fprintf (stderr, "libgcj failure: %s\n", message);
503 #endif
504 abort ();
507 static void
508 fail_on_finalization (jobject)
510 JvFail ("object was finalized");
513 void
514 _Jv_GCWatch (jobject obj)
516 _Jv_RegisterFinalizer (obj, fail_on_finalization);
519 void
520 _Jv_ThrowBadArrayIndex(jint bad_index)
522 throw new java::lang::ArrayIndexOutOfBoundsException
523 (java::lang::String::valueOf (bad_index));
526 void
527 _Jv_ThrowNullPointerException ()
529 throw new java::lang::NullPointerException;
532 // Resolve an entry in the constant pool and return the target
533 // address.
534 void *
535 _Jv_ResolvePoolEntry (jclass this_class, jint index)
537 _Jv_Constants *pool = &this_class->constants;
539 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
540 return pool->data[index].field->u.addr;
542 JvSynchronize sync (this_class);
543 return (_Jv_Linker::resolve_pool_entry (this_class, index))
544 .field->u.addr;
548 // Explicitly throw a no memory exception.
549 // The collector calls this when it encounters an out-of-memory condition.
550 void _Jv_ThrowNoMemory()
552 throw no_memory;
555 #ifdef ENABLE_JVMPI
556 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
557 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
558 jvmpi_notify_alloc(klass,size,obj);
559 static void
560 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
562 // Service JVMPI allocation request.
563 JVMPI_Event event;
565 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
566 event.env_id = NULL;
567 event.u.obj_alloc.arena_id = 0;
568 event.u.obj_alloc.class_id = (jobjectID) klass;
569 event.u.obj_alloc.is_array = 0;
570 event.u.obj_alloc.size = size;
571 event.u.obj_alloc.obj_id = (jobjectID) obj;
573 // FIXME: This doesn't look right for the Boehm GC. A GC may
574 // already be in progress. _Jv_DisableGC () doesn't wait for it.
575 // More importantly, I don't see the need for disabling GC, since we
576 // blatantly have a pointer to obj on our stack, ensuring that the
577 // object can't be collected. Even for a nonconservative collector,
578 // it appears to me that this must be true, since we are about to
579 // return obj. Isn't this whole approach way too intrusive for
580 // a useful profiling interface? - HB
581 _Jv_DisableGC ();
582 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
583 _Jv_EnableGC ();
585 #else /* !ENABLE_JVMPI */
586 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
587 #endif
589 // Allocate a new object of class KLASS.
590 // First a version that assumes that we have no finalizer, and that
591 // the class is already initialized.
592 // If we know that JVMPI is disabled, this can be replaced by a direct call
593 // to the allocator for the appropriate GC.
594 jobject
595 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
597 jint size = klass->size ();
598 NOTE_MEMORY_USAGE ("c", size);
599 jobject obj = (jobject) _Jv_AllocObj (size, klass);
600 JVMPI_NOTIFY_ALLOC (klass, size, obj);
601 return obj;
604 jobject
605 _Jv_InitObjectNoInitNoFinalizer (jclass klass)
607 jint size = klass->size ();
608 NOTE_MEMORY_USAGE ("C", size);
609 jobject obj = (jobject) _Jv_AllocObj (size, klass);
610 JVMPI_NOTIFY_ALLOC (klass, size, obj);
611 return obj;
614 // And now a version that initializes if necessary.
615 jobject
616 _Jv_AllocObjectNoFinalizer (jclass klass)
618 if (_Jv_IsPhantomClass(klass) )
619 throw new java::lang::NoClassDefFoundError(klass->getName());
621 _Jv_InitClass (klass);
622 jint size = klass->size ();
623 NOTE_MEMORY_USAGE ("d", size);
624 jobject obj = (jobject) _Jv_AllocObj (size, klass);
625 JVMPI_NOTIFY_ALLOC (klass, size, obj);
626 return obj;
629 // Now a version that takes it's memory as a parameter
630 jobject
631 _Jv_InitObjectNoFinalizer (jclass klass)
633 if (_Jv_IsPhantomClass(klass) )
634 throw new java::lang::NoClassDefFoundError(klass->getName());
636 _Jv_InitClass (klass);
637 jint size = klass->size ();
638 NOTE_MEMORY_USAGE ("D", size);
639 jobject obj = (jobject) _Jv_AllocObj (size, klass);
640 JVMPI_NOTIFY_ALLOC (klass, size, obj);
641 return obj;
643 #if 0
644 void
645 _Jv_InitObjectNoFinalizer (jclass klass, jobject obj)
647 if (_Jv_IsPhantomClass(klass) )
648 throw new java::lang::NoClassDefFoundError(klass->getName());
650 _Jv_InitClass (klass);
652 /* If OBJ is 0, this is as a result of ALLOCA failing (presumably due to
653 * stack overflow, which is undefined. So we'll ignore it. */
655 /* Memory is assumed to be cleared, so we need to clear the allocation
656 * here. */
657 jint size = klass->size ();
658 memset (obj, 0, size);
659 NOTE_MEMORY_USAGE ("D", size);
661 *(void **)obj = klass->vtable;
663 JVMPI_NOTIFY_ALLOC (klass, size, obj);
665 #endif
667 // And now the general version that registers a finalizer if necessary.
668 jobject
669 _Jv_AllocObject (jclass klass)
671 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
673 // We assume that the compiler only generates calls to this routine
674 // if there really is an interesting finalizer.
675 // Unfortunately, we still have to the dynamic test, since there may
676 // be cni calls to this routine.
677 // Note that on IA64 get_finalizer() returns the starting address of the
678 // function, not a function pointer. Thus this still works.
679 NOTE_MEMORY_USAGE ("e", klass->size ());
680 if (klass->vtable->get_finalizer ()
681 != java::lang::Object::class$.vtable->get_finalizer ())
682 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
683 return obj;
686 jobject
687 _Jv_InitObject (jclass klass)
689 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
691 // We assume that the compiler only generates calls to this routine
692 // if there really is an interesting finalizer.
693 // Unfortunately, we still have to the dynamic test, since there may
694 // be cni calls to this routine.
695 // Note that on IA64 get_finalizer() returns the starting address of the
696 // function, not a function pointer. Thus this still works.
697 NOTE_MEMORY_USAGE ("E", klass->size ());
698 if (klass->vtable->get_finalizer ()
699 != java::lang::Object::class$.vtable->get_finalizer ())
700 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
701 return obj;
704 // Allocate a String, including variable length storage.
705 jstring
706 _Jv_AllocString(jsize len)
708 using namespace java::lang;
710 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
712 // We assert that for strings allocated this way, the data field
713 // will always point to the object itself. Thus there is no reason
714 // for the garbage collector to scan any of it.
715 // Furthermore, we're about to overwrite the string data, so
716 // initialization of the object is not an issue.
718 // String needs no initialization, and there is no finalizer, so
719 // we can go directly to the collector's allocator interface.
720 NOTE_MEMORY_USAGE ("i", sz);
721 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
723 obj->data = obj;
724 obj->boffset = sizeof(java::lang::String);
725 obj->count = len;
726 obj->cachedHashCode = 0;
728 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
730 return obj;
733 // A version of the above that assumes the object contains no pointers,
734 // and requires no finalization. This can't happen if we need pointers
735 // to locks.
736 #ifdef JV_HASH_SYNCHRONIZATION
737 jobject
738 _Jv_AllocPtrFreeObject (jclass klass)
740 _Jv_InitClass (klass);
741 jint size = klass->size ();
743 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
744 NOTE_MEMORY_USAGE ("f", size);
746 JVMPI_NOTIFY_ALLOC (klass, size, obj);
748 return obj;
751 jobject
752 _Jv_InitPtrFreeObject (jclass klass)
754 _Jv_InitClass (klass);
755 jint size = klass->size ();
757 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
758 NOTE_MEMORY_USAGE ("F", size);
760 JVMPI_NOTIFY_ALLOC (klass, size, obj);
762 return obj;
764 #endif /* JV_HASH_SYNCHRONIZATION */
767 // Allocate a new array of Java objects. Each object is of type
768 // `elementClass'. `init' is used to initialize each slot in the
769 // array.
770 jobjectArray
771 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
773 // Creating an array of an unresolved type is impossible. So we throw
774 // the NoClassDefFoundError.
775 if ( _Jv_IsPhantomClass(elementClass) )
776 throw new java::lang::NoClassDefFoundError(elementClass->getName());
778 if (__builtin_expect (count < 0, false))
779 throw new java::lang::NegativeArraySizeException;
781 JvAssert (! elementClass->isPrimitive ());
783 // Ensure that elements pointer is properly aligned.
784 jobjectArray obj = NULL;
785 size_t size = (size_t) elements (obj);
786 // Check for overflow.
787 if (__builtin_expect ((size_t) count >
788 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
789 throw no_memory;
791 size += count * sizeof (jobject);
793 jclass klass = _Jv_GetArrayClass (elementClass,
794 elementClass->getClassLoaderInternal());
796 NOTE_MEMORY_USAGE ("g", size);
797 obj = (jobjectArray) _Jv_AllocArray (size, klass);
798 // Cast away const.
799 jsize *lp = const_cast<jsize *> (&obj->length);
800 *lp = count;
801 // We know the allocator returns zeroed memory. So don't bother
802 // zeroing it again.
803 if (init)
805 jobject *ptr = elements(obj);
806 while (--count >= 0)
807 *ptr++ = init;
809 return obj;
812 // Initialize a new array of Java objects from pre-allocated memory.
813 // Each object is of type `elementClass'. `init' is used to initialize
814 // each slot in the array.
815 jobjectArray
816 _Jv_InitObjectArray (jsize count, jclass elementClass, jobject init)
818 // Creating an array of an unresolved type is impossible. So we throw
819 // the NoClassDefFoundError.
820 if ( _Jv_IsPhantomClass(elementClass) )
821 throw new java::lang::NoClassDefFoundError(elementClass->getName());
823 if (__builtin_expect (count < 0, false))
824 throw new java::lang::NegativeArraySizeException;
826 JvAssert (! elementClass->isPrimitive ());
828 // Ensure that elements pointer is properly aligned.
829 jobjectArray obj = NULL;
830 size_t size = (size_t) elements (obj);
831 // Check for overflow.
832 if (__builtin_expect ((size_t) count >
833 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
834 throw no_memory;
836 size += count * sizeof (jobject);
838 jclass klass = _Jv_GetArrayClass (elementClass,
839 elementClass->getClassLoaderInternal());
841 NOTE_MEMORY_USAGE ("G", size);
842 obj = (jobjectArray) _Jv_AllocArray (size, klass);
843 // Cast away const.
844 jsize *lp = const_cast<jsize *> (&obj->length);
845 *lp = count;
846 // We know the allocator returns zeroed memory. So don't bother
847 // zeroing it again.
848 if (init)
850 jobject *ptr = elements(obj);
851 while (--count >= 0)
852 *ptr++ = init;
854 return obj;
857 #if 0
858 void
859 _Jv_InitNewObjectArray (jsize size, jclass elementClass, jobjectArray obj)
861 // Creating an array of an unresolved type is impossible. So we throw
862 // the NoClassDefFoundError.
863 if ( _Jv_IsPhantomClass(elementClass) )
864 throw new java::lang::NoClassDefFoundError(elementClass->getName());
866 // this was meant to be count, but I removed cont, so
867 if (__builtin_expect ((size_t)size < (size_t)elements(obj), false))
868 throw new java::lang::NegativeArraySizeException;
871 JvAssert (! elementClass->isPrimitive ());
873 // memory is already allocated by alloca
874 jclass arrayClass = _Jv_GetArrayClass (elementClass,
875 elementClass->getClassLoaderInternal());
876 NOTE_MEMORY_USAGE ("G", size);
878 // zero the memory (the allocator would otherwise do this)
879 memset (obj, 0, size);
881 // put in the array's vtable (from _JvAllocArray)
882 *((_Jv_VTable **) obj) = arrayClass->vtable;
884 #endif
887 // Allocate a new array of primitives. ELTYPE is the type of the
888 // element, COUNT is the size of the array.
889 jobject
890 _Jv_NewPrimArray (jclass eltype, jint count)
892 int elsize = eltype->size();
893 if (__builtin_expect (count < 0, false))
894 throw new java::lang::NegativeArraySizeException;
896 JvAssert (eltype->isPrimitive ());
897 jobject dummy = NULL;
898 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
900 // Check for overflow.
901 if (__builtin_expect ((size_t) count >
902 (MAX_OBJECT_SIZE - size) / elsize, false))
903 throw no_memory;
905 jclass klass = _Jv_GetArrayClass (eltype, 0);
906 NOTE_MEMORY_USAGE ("h", size + elsize * count);
908 # ifdef JV_HASH_SYNCHRONIZATION
909 // Since the vtable is always statically allocated,
910 // these are completely pointerfree! Make sure the GC doesn't touch them.
911 __JArray *arr =
912 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
913 memset((char *)arr + size, 0, elsize * count);
914 # else
915 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
916 // Note that we assume we are given zeroed memory by the allocator.
917 # endif
918 // Cast away const.
919 jsize *lp = const_cast<jsize *> (&arr->length);
920 *lp = count;
922 return arr;
925 jobject
926 _Jv_InitPrimArray (jclass eltype, jint count)
928 int elsize = eltype->size();
929 if (__builtin_expect (count < 0, false))
930 throw new java::lang::NegativeArraySizeException;
932 JvAssert (eltype->isPrimitive ());
933 jobject dummy = NULL;
934 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
936 // Check for overflow.
937 if (__builtin_expect ((size_t) count >
938 (MAX_OBJECT_SIZE - size) / elsize, false))
939 throw no_memory;
941 jclass klass = _Jv_GetArrayClass (eltype, 0);
942 NOTE_MEMORY_USAGE ("H", size + elsize * count);
944 # ifdef JV_HASH_SYNCHRONIZATION
945 // Since the vtable is always statically allocated,
946 // these are completely pointerfree! Make sure the GC doesn't touch them.
947 __JArray *arr =
948 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
949 memset((char *)arr + size, 0, elsize * count);
950 # else
951 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
952 // Note that we assume we are given zeroed memory by the allocator.
953 # endif
954 // Cast away const.
955 jsize *lp = const_cast<jsize *> (&arr->length);
956 *lp = count;
958 return arr;
961 jobject
962 _Jv_NewArray (jint type, jint size)
964 switch (type)
966 case 4: return JvNewBooleanArray (size);
967 case 5: return JvNewCharArray (size);
968 case 6: return JvNewFloatArray (size);
969 case 7: return JvNewDoubleArray (size);
970 case 8: return JvNewByteArray (size);
971 case 9: return JvNewShortArray (size);
972 case 10: return JvNewIntArray (size);
973 case 11: return JvNewLongArray (size);
975 throw new java::lang::InternalError
976 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
979 // Allocate a possibly multi-dimensional array but don't check that
980 // any array length is <0.
981 static jobject
982 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
984 JvAssert (type->isArray());
985 jclass element_type = type->getComponentType();
986 jobject result;
987 if (element_type->isPrimitive())
988 result = _Jv_NewPrimArray (element_type, sizes[0]);
989 else
990 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
992 if (dimensions > 1)
994 JvAssert (! element_type->isPrimitive());
995 JvAssert (element_type->isArray());
996 jobject *contents = elements ((jobjectArray) result);
997 for (int i = 0; i < sizes[0]; ++i)
998 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
999 sizes + 1);
1002 return result;
1005 jobject
1006 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
1008 for (int i = 0; i < dimensions; ++i)
1009 if (sizes[i] < 0)
1010 throw new java::lang::NegativeArraySizeException;
1012 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
1015 jobject
1016 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
1018 // Creating an array of an unresolved type is impossible. So we throw
1019 // the NoClassDefFoundError.
1020 if (_Jv_IsPhantomClass(array_type))
1021 throw new java::lang::NoClassDefFoundError(array_type->getName());
1023 va_list args;
1024 jint sizes[dimensions];
1025 va_start (args, dimensions);
1026 for (int i = 0; i < dimensions; ++i)
1028 jint size = va_arg (args, jint);
1029 if (size < 0)
1030 throw new java::lang::NegativeArraySizeException;
1031 sizes[i] = size;
1033 va_end (args);
1035 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
1038 static jobject
1039 _Jv_InitMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
1041 JvAssert (type->isArray());
1042 jclass element_type = type->getComponentType();
1043 jobject result;
1044 if (element_type->isPrimitive())
1045 result = _Jv_InitPrimArray (element_type, sizes[0]);
1046 else
1047 result = _Jv_InitObjectArray (sizes[0], element_type, NULL);
1049 if (dimensions > 1)
1051 JvAssert (! element_type->isPrimitive());
1052 JvAssert (element_type->isArray());
1053 jobject *contents = elements ((jobjectArray) result);
1054 for (int i = 0; i < sizes[0]; ++i)
1055 contents[i] = _Jv_InitMultiArrayUnchecked (element_type, dimensions - 1,
1056 sizes + 1);
1059 return result;
1062 jobject
1063 _Jv_InitMultiArray (jclass type, jint dimensions, jint *sizes)
1065 for (int i = 0; i < dimensions; ++i)
1066 if (sizes[i] < 0)
1067 throw new java::lang::NegativeArraySizeException;
1069 return _Jv_InitMultiArrayUnchecked (type, dimensions, sizes);
1072 jobject
1073 _Jv_InitMultiArray (jclass array_type, jint dimensions, ...)
1075 // Creating an array of an unresolved type is impossible. So we throw
1076 // the NoClassDefFoundError.
1077 if (_Jv_IsPhantomClass(array_type))
1078 throw new java::lang::NoClassDefFoundError(array_type->getName());
1080 va_list args;
1081 jint sizes[dimensions];
1082 va_start (args, dimensions);
1083 for (int i = 0; i < dimensions; ++i)
1085 jint size = va_arg (args, jint);
1086 if (size < 0)
1087 throw new java::lang::NegativeArraySizeException;
1088 sizes[i] = size;
1090 va_end (args);
1092 return _Jv_InitMultiArrayUnchecked (array_type, dimensions, sizes);
1098 // Ensure 8-byte alignment, for hash synchronization.
1099 #define DECLARE_PRIM_TYPE(NAME) \
1100 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
1102 DECLARE_PRIM_TYPE(byte)
1103 DECLARE_PRIM_TYPE(short)
1104 DECLARE_PRIM_TYPE(int)
1105 DECLARE_PRIM_TYPE(long)
1106 DECLARE_PRIM_TYPE(boolean)
1107 DECLARE_PRIM_TYPE(char)
1108 DECLARE_PRIM_TYPE(float)
1109 DECLARE_PRIM_TYPE(double)
1110 DECLARE_PRIM_TYPE(void)
1112 void
1113 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
1115 using namespace java::lang::reflect;
1117 // We must set the vtable for the class; the Java constructor
1118 // doesn't do this.
1119 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
1121 // Initialize the fields we care about. We do this in the same
1122 // order they are declared in Class.h.
1123 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
1124 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
1125 cl->method_count = sig;
1126 cl->size_in_bytes = len;
1127 cl->vtable = JV_PRIMITIVE_VTABLE;
1128 cl->state = JV_STATE_DONE;
1129 cl->depth = -1;
1132 jclass
1133 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
1134 char **endp)
1136 // First count arrays.
1137 int array_count = 0;
1138 while (*sig == '[')
1140 ++sig;
1141 ++array_count;
1144 jclass result = NULL;
1145 switch (*sig)
1147 case 'B':
1148 result = JvPrimClass (byte);
1149 break;
1150 case 'S':
1151 result = JvPrimClass (short);
1152 break;
1153 case 'I':
1154 result = JvPrimClass (int);
1155 break;
1156 case 'J':
1157 result = JvPrimClass (long);
1158 break;
1159 case 'Z':
1160 result = JvPrimClass (boolean);
1161 break;
1162 case 'C':
1163 result = JvPrimClass (char);
1164 break;
1165 case 'F':
1166 result = JvPrimClass (float);
1167 break;
1168 case 'D':
1169 result = JvPrimClass (double);
1170 break;
1171 case 'V':
1172 result = JvPrimClass (void);
1173 break;
1174 case 'L':
1176 char *save = ++sig;
1177 while (*sig && *sig != ';')
1178 ++sig;
1179 // Do nothing if signature appears to be malformed.
1180 if (*sig == ';')
1182 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
1183 result = _Jv_FindClass (name, loader);
1185 break;
1187 default:
1188 // Do nothing -- bad signature.
1189 break;
1192 if (endp)
1194 // Not really the "end", but the last valid character that we
1195 // looked at.
1196 *endp = sig;
1199 if (! result)
1200 return NULL;
1202 // Find arrays.
1203 while (array_count-- > 0)
1204 result = _Jv_GetArrayClass (result, loader);
1205 return result;
1209 jclass
1210 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
1211 char **endp)
1213 jclass klass;
1217 klass = _Jv_FindClassFromSignature(sig, loader, endp);
1219 catch (java::lang::NoClassDefFoundError *ncdfe)
1221 return NULL;
1223 catch (java::lang::ClassNotFoundException *cnfe)
1225 return NULL;
1228 return klass;
1231 JArray<jstring> *
1232 JvConvertArgv (int argc, const char **argv)
1234 if (argc < 0)
1235 argc = 0;
1236 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
1237 jobject *ptr = elements(ar);
1238 jbyteArray bytes = NULL;
1239 for (int i = 0; i < argc; i++)
1241 const char *arg = argv[i];
1242 int len = strlen (arg);
1243 if (bytes == NULL || bytes->length < len)
1244 bytes = JvNewByteArray (len);
1245 jbyte *bytePtr = elements (bytes);
1246 // We assume jbyte == char.
1247 memcpy (bytePtr, arg, len);
1249 // Now convert using the default encoding.
1250 *ptr++ = new java::lang::String (bytes, 0, len);
1252 return (JArray<jstring>*) ar;
1255 // FIXME: These variables are static so that they will be
1256 // automatically scanned by the Boehm collector. This is needed
1257 // because with qthreads the collector won't scan the initial stack --
1258 // it will only scan the qthreads stacks.
1260 // Command line arguments.
1261 static JArray<jstring> *arg_vec;
1263 // The primary thread.
1264 static java::lang::Thread *main_thread;
1266 #ifndef DISABLE_GETENV_PROPERTIES
1268 static char *
1269 next_property_key (char *s, size_t *length)
1271 size_t l = 0;
1273 JvAssert (s);
1275 // Skip over whitespace
1276 while (isspace (*s))
1277 s++;
1279 // If we've reached the end, return NULL. Also return NULL if for
1280 // some reason we've come across a malformed property string.
1281 if (*s == 0
1282 || *s == ':'
1283 || *s == '=')
1284 return NULL;
1286 // Determine the length of the property key.
1287 while (s[l] != 0
1288 && ! isspace (s[l])
1289 && s[l] != ':'
1290 && s[l] != '=')
1292 if (s[l] == '\\'
1293 && s[l+1] != 0)
1294 l++;
1295 l++;
1298 *length = l;
1300 return s;
1303 static char *
1304 next_property_value (char *s, size_t *length)
1306 size_t l = 0;
1308 JvAssert (s);
1310 while (isspace (*s))
1311 s++;
1313 if (*s == ':'
1314 || *s == '=')
1315 s++;
1317 while (isspace (*s))
1318 s++;
1320 // Determine the length of the property value.
1321 while (s[l] != 0
1322 && ! isspace (s[l])
1323 && s[l] != ':'
1324 && s[l] != '=')
1326 if (s[l] == '\\'
1327 && s[l+1] != 0)
1328 l += 2;
1329 else
1330 l++;
1333 *length = l;
1335 return s;
1338 static void
1339 process_gcj_properties ()
1341 char *props = getenv("GCJ_PROPERTIES");
1343 if (NULL == props)
1344 return;
1346 // Later on we will write \0s into this string. It is simplest to
1347 // just duplicate it here.
1348 props = strdup (props);
1350 char *p = props;
1351 size_t length;
1352 size_t property_count = 0;
1354 // Whip through props quickly in order to count the number of
1355 // property values.
1356 while (p && (p = next_property_key (p, &length)))
1358 // Skip to the end of the key
1359 p += length;
1361 p = next_property_value (p, &length);
1362 if (p)
1363 p += length;
1365 property_count++;
1368 // Allocate an array of property value/key pairs.
1369 _Jv_Environment_Properties =
1370 (property_pair *) malloc (sizeof(property_pair)
1371 * (property_count + 1));
1373 // Go through the properties again, initializing _Jv_Properties
1374 // along the way.
1375 p = props;
1376 property_count = 0;
1377 while (p && (p = next_property_key (p, &length)))
1379 _Jv_Environment_Properties[property_count].key = p;
1380 _Jv_Environment_Properties[property_count].key_length = length;
1382 // Skip to the end of the key
1383 p += length;
1385 p = next_property_value (p, &length);
1387 _Jv_Environment_Properties[property_count].value = p;
1388 _Jv_Environment_Properties[property_count].value_length = length;
1390 if (p)
1391 p += length;
1393 property_count++;
1395 memset ((void *) &_Jv_Environment_Properties[property_count],
1396 0, sizeof (property_pair));
1398 // Null terminate the strings.
1399 for (property_pair *prop = &_Jv_Environment_Properties[0];
1400 prop->key != NULL;
1401 prop++)
1403 prop->key[prop->key_length] = 0;
1404 prop->value[prop->value_length] = 0;
1407 #endif // DISABLE_GETENV_PROPERTIES
1409 namespace gcj
1411 _Jv_Utf8Const *void_signature;
1412 _Jv_Utf8Const *clinit_name;
1413 _Jv_Utf8Const *init_name;
1414 _Jv_Utf8Const *finit_name;
1416 bool runtimeInitialized = false;
1418 // When true, print debugging information about class loading.
1419 bool verbose_class_flag;
1421 // When true, enable the bytecode verifier and BC-ABI type verification.
1422 bool verifyClasses = true;
1424 // Thread stack size specified by the -Xss runtime argument.
1425 size_t stack_size = 0;
1428 // We accept all non-standard options accepted by Sun's java command,
1429 // for compatibility with existing application launch scripts.
1430 static jint
1431 parse_x_arg (char* option_string)
1433 if (strlen (option_string) <= 0)
1434 return -1;
1436 if (! strcmp (option_string, "int"))
1438 // FIXME: this should cause the vm to never load shared objects
1440 else if (! strcmp (option_string, "mixed"))
1442 // FIXME: allow interpreted and native code
1444 else if (! strcmp (option_string, "batch"))
1446 // FIXME: disable background JIT'ing
1448 else if (! strcmp (option_string, "debug"))
1450 remoteDebug = true;
1452 else if (! strncmp (option_string, "runjdwp:", 8))
1454 if (strlen (option_string) > 8)
1455 jdwpOptions = &option_string[8];
1456 else
1458 fprintf (stderr,
1459 "libgcj: argument required for JDWP options");
1460 return -1;
1463 else if (! strncmp (option_string, "bootclasspath:", 14))
1465 // FIXME: add a parse_bootclasspath_arg function
1467 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1470 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1473 else if (! strcmp (option_string, "check:jni"))
1475 // FIXME: enable strict JNI checking
1477 else if (! strcmp (option_string, "future"))
1479 // FIXME: enable strict class file format checks
1481 else if (! strcmp (option_string, "noclassgc"))
1483 // FIXME: disable garbage collection for classes
1485 else if (! strcmp (option_string, "incgc"))
1487 // FIXME: incremental garbage collection
1489 else if (! strncmp (option_string, "loggc:", 6))
1491 if (option_string[6] == '\0')
1493 fprintf (stderr,
1494 "libgcj: filename argument expected for loggc option\n");
1495 return -1;
1497 // FIXME: set gc logging filename
1499 else if (! strncmp (option_string, "ms", 2))
1501 // FIXME: ignore this option until PR 20699 is fixed.
1502 // _Jv_SetInitialHeapSize (option_string + 2);
1504 else if (! strncmp (option_string, "mx", 2))
1505 _Jv_SetMaximumHeapSize (option_string + 2);
1506 else if (! strcmp (option_string, "prof"))
1508 // FIXME: enable profiling of program running in vm
1510 else if (! strncmp (option_string, "runhprof:", 9))
1512 // FIXME: enable specific type of vm profiling. add a
1513 // parse_runhprof_arg function
1515 else if (! strcmp (option_string, "rs"))
1517 // FIXME: reduced system signal usage. disable thread dumps,
1518 // only terminate in response to user-initiated calls,
1519 // e.g. System.exit()
1521 else if (! strncmp (option_string, "ss", 2))
1523 _Jv_SetStackSize (option_string + 2);
1525 else if (! strcmp (option_string, "X:+UseAltSigs"))
1527 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1529 else if (! strcmp (option_string, "share:off"))
1531 // FIXME: don't share class data
1533 else if (! strcmp (option_string, "share:auto"))
1535 // FIXME: share class data where possible
1537 else if (! strcmp (option_string, "share:on"))
1539 // FIXME: fail if impossible to share class data
1542 return 0;
1545 static jint
1546 parse_verbose_args (char* option_string,
1547 bool ignore_unrecognized)
1549 size_t len = sizeof ("-verbose") - 1;
1551 if (strlen (option_string) < len)
1552 return -1;
1554 if (option_string[len] == ':'
1555 && option_string[len + 1] != '\0')
1557 char* verbose_args = option_string + len + 1;
1561 if (! strncmp (verbose_args,
1562 "gc", sizeof ("gc") - 1))
1564 if (verbose_args[sizeof ("gc") - 1] == '\0'
1565 || verbose_args[sizeof ("gc") - 1] == ',')
1567 // FIXME: we should add functions to boehm-gc that
1568 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1569 // GC_print_back_height.
1570 verbose_args += sizeof ("gc") - 1;
1572 else
1574 verbose_arg_err:
1575 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1576 option_string);
1577 return -1;
1580 else if (! strncmp (verbose_args,
1581 "class",
1582 sizeof ("class") - 1))
1584 if (verbose_args[sizeof ("class") - 1] == '\0'
1585 || verbose_args[sizeof ("class") - 1] == ',')
1587 gcj::verbose_class_flag = true;
1588 verbose_args += sizeof ("class") - 1;
1590 else
1591 goto verbose_arg_err;
1593 else if (! strncmp (verbose_args, "jni",
1594 sizeof ("jni") - 1))
1596 if (verbose_args[sizeof ("jni") - 1] == '\0'
1597 || verbose_args[sizeof ("jni") - 1] == ',')
1599 // FIXME: enable JNI messages.
1600 verbose_args += sizeof ("jni") - 1;
1602 else
1603 goto verbose_arg_err;
1605 else if (ignore_unrecognized
1606 && verbose_args[0] == 'X')
1608 // ignore unrecognized non-standard verbose option
1609 while (verbose_args[0] != '\0'
1610 && verbose_args[0] != ',')
1611 verbose_args++;
1613 else if (verbose_args[0] == ',')
1615 verbose_args++;
1617 else
1618 goto verbose_arg_err;
1620 if (verbose_args[0] == ',')
1621 verbose_args++;
1623 while (verbose_args[0] != '\0');
1625 else if (option_string[len] == 'g'
1626 && option_string[len + 1] == 'c'
1627 && option_string[len + 2] == '\0')
1629 // FIXME: we should add functions to boehm-gc that
1630 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1631 // GC_print_back_height.
1632 return 0;
1634 else if (option_string[len] == '\0')
1636 gcj::verbose_class_flag = true;
1637 return 0;
1639 else
1641 // unrecognized option beginning with -verbose
1642 return -1;
1644 return 0;
1647 static jint
1648 parse_init_args (JvVMInitArgs* vm_args)
1650 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1651 // re-allocated dynamically.
1652 if (_Jv_Compiler_Properties)
1654 const char** props = _Jv_Compiler_Properties;
1655 _Jv_Compiler_Properties = NULL;
1657 for (int i = 0; props[i]; i++)
1659 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1660 (_Jv_Compiler_Properties,
1661 (_Jv_Properties_Count + 1) * sizeof (const char*));
1662 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1666 if (vm_args == NULL)
1667 return 0;
1669 for (int i = 0; i < vm_args->nOptions; ++i)
1671 char* option_string = vm_args->options[i].optionString;
1672 if (! strcmp (option_string, "vfprintf")
1673 || ! strcmp (option_string, "exit")
1674 || ! strcmp (option_string, "abort"))
1676 // FIXME: we are required to recognize these, but for
1677 // now we don't handle them in any way.
1678 continue;
1680 else if (! strncmp (option_string,
1681 "-verbose", sizeof ("-verbose") - 1))
1683 jint result = parse_verbose_args (option_string,
1684 vm_args->ignoreUnrecognized);
1685 if (result < 0)
1686 return result;
1688 else if (! strncmp (option_string, "-D", 2))
1690 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1691 (_Jv_Compiler_Properties,
1692 (_Jv_Properties_Count + 1) * sizeof (char*));
1694 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1695 strdup (option_string + 2);
1697 continue;
1699 else if (vm_args->ignoreUnrecognized)
1701 if (option_string[0] == '_')
1702 parse_x_arg (option_string + 1);
1703 else if (! strncmp (option_string, "-X", 2))
1704 parse_x_arg (option_string + 2);
1705 else
1707 unknown_option:
1708 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1709 return -1;
1712 else
1713 goto unknown_option;
1715 return 0;
1718 jint
1719 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1721 using namespace gcj;
1723 if (runtimeInitialized)
1724 return -1;
1726 jint result = parse_init_args (vm_args);
1727 if (result < 0)
1728 return -1;
1730 PROCESS_GCJ_PROPERTIES;
1732 /* Threads must be initialized before the GC, so that it inherits the
1733 signal mask. */
1734 _Jv_InitThreads ();
1735 _Jv_InitGC ();
1736 _Jv_InitializeSyncMutex ();
1738 #ifdef INTERPRETER
1739 _Jv_InitInterpreter ();
1740 #endif
1742 #ifdef HANDLE_SEGV
1743 INIT_SEGV;
1744 #endif
1746 #ifdef HANDLE_FPE
1747 INIT_FPE;
1748 #endif
1750 /* Initialize Utf8 constants declared in jvm.h. */
1751 void_signature = _Jv_makeUtf8Const ("()V", 3);
1752 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1753 init_name = _Jv_makeUtf8Const ("<init>", 6);
1754 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1756 /* Initialize built-in classes to represent primitive TYPEs. */
1757 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1758 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1759 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1760 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1761 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1762 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1763 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1764 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1765 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1767 // We have to initialize this fairly early, to avoid circular class
1768 // initialization. In particular we want to start the
1769 // initialization of ClassLoader before we start the initialization
1770 // of VMClassLoader.
1771 _Jv_InitClass (&java::lang::ClassLoader::class$);
1773 // Set up the system class loader and the bootstrap class loader.
1774 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1775 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1777 _Jv_RegisterBootstrapPackages();
1779 no_memory = new java::lang::OutOfMemoryError;
1781 #ifdef USE_LTDL
1782 LTDL_SET_PRELOADED_SYMBOLS ();
1783 #endif
1785 _Jv_platform_initialize ();
1787 _Jv_JNI_Init ();
1788 _Jv_JVMTI_Init ();
1790 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1792 // Start the GC finalizer thread. A VirtualMachineError can be
1793 // thrown by the runtime if, say, threads aren't available.
1796 using namespace gnu::gcj::runtime;
1797 FinalizerThread *ft = new FinalizerThread ();
1798 ft->start ();
1800 catch (java::lang::VirtualMachineError *ignore)
1804 runtimeInitialized = true;
1806 return 0;
1809 void
1810 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1811 const char **argv, bool is_jar)
1813 #ifndef DISABLE_MAIN_ARGS
1814 _Jv_SetArgs (argc, argv);
1815 #endif
1817 java::lang::Runtime *runtime = NULL;
1821 if (_Jv_CreateJavaVM (vm_args) < 0)
1823 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1824 exit (1);
1827 // Get the Runtime here. We want to initialize it before searching
1828 // for `main'; that way it will be set up if `main' is a JNI method.
1829 runtime = java::lang::Runtime::getRuntime ();
1831 #ifdef DISABLE_MAIN_ARGS
1832 arg_vec = JvConvertArgv (0, 0);
1833 #else
1834 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1835 #endif
1837 using namespace gnu::java::lang;
1838 if (klass)
1839 main_thread = new MainThread (klass, arg_vec);
1840 else
1841 main_thread = new MainThread (JvNewStringUTF (name),
1842 arg_vec, is_jar);
1843 _Jv_AttachCurrentThread (main_thread);
1845 // Start JDWP
1846 if (remoteDebug)
1848 using namespace gnu::classpath::jdwp;
1849 VMVirtualMachine::initialize ();
1850 Jdwp *jdwp = new Jdwp ();
1851 jdwp->setDaemon (true);
1852 jdwp->configure (JvNewStringLatin1 (jdwpOptions));
1853 jdwp->start ();
1855 // Wait for JDWP to initialize and start
1856 jdwp->join ();
1859 // Send VmInit
1860 gnu::classpath::jdwp::event::VmInitEvent *event;
1861 event = new gnu::classpath::jdwp::event::VmInitEvent (main_thread);
1862 gnu::classpath::jdwp::Jdwp::notify (event);
1864 catch (java::lang::Throwable *t)
1866 java::lang::System::err->println (JvNewStringLatin1
1867 ("Exception during runtime initialization"));
1868 t->printStackTrace();
1869 if (runtime)
1870 java::lang::Runtime::exitNoChecksAccessor (1);
1871 // In case the runtime creation failed.
1872 ::exit (1);
1875 _Jv_ThreadRun (main_thread);
1877 // Notify debugger of VM's death
1878 if (gnu::classpath::jdwp::Jdwp::isDebugging)
1880 using namespace gnu::classpath::jdwp;
1881 event::VmDeathEvent *event = new event::VmDeathEvent ();
1882 Jdwp::notify (event);
1885 // If we got here then something went wrong, as MainThread is not
1886 // supposed to terminate.
1887 ::exit (1);
1890 void
1891 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1892 bool is_jar)
1894 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1897 void
1898 JvRunMain (jclass klass, int argc, const char **argv)
1900 _Jv_RunMain (klass, NULL, argc, argv, false);
1905 // Parse a string and return a heap size.
1906 static size_t
1907 parse_memory_size (const char *spec)
1909 char *end;
1910 unsigned long val = strtoul (spec, &end, 10);
1911 if (*end == 'k' || *end == 'K')
1912 val *= 1024;
1913 else if (*end == 'm' || *end == 'M')
1914 val *= 1048576;
1915 return (size_t) val;
1918 // Set the initial heap size. This might be ignored by the GC layer.
1919 // This must be called before _Jv_RunMain.
1920 void
1921 _Jv_SetInitialHeapSize (const char *arg)
1923 size_t size = parse_memory_size (arg);
1924 _Jv_GCSetInitialHeapSize (size);
1927 // Set the maximum heap size. This might be ignored by the GC layer.
1928 // This must be called before _Jv_RunMain.
1929 void
1930 _Jv_SetMaximumHeapSize (const char *arg)
1932 size_t size = parse_memory_size (arg);
1933 _Jv_GCSetMaximumHeapSize (size);
1936 void
1937 _Jv_SetStackSize (const char *arg)
1939 size_t size = parse_memory_size (arg);
1940 gcj::stack_size = size;
1943 void *
1944 _Jv_Malloc (jsize size)
1946 if (__builtin_expect (size == 0, false))
1947 size = 1;
1948 void *ptr = malloc ((size_t) size);
1949 if (__builtin_expect (ptr == NULL, false))
1950 throw no_memory;
1951 return ptr;
1954 void *
1955 _Jv_Realloc (void *ptr, jsize size)
1957 if (__builtin_expect (size == 0, false))
1958 size = 1;
1959 ptr = realloc (ptr, (size_t) size);
1960 if (__builtin_expect (ptr == NULL, false))
1961 throw no_memory;
1962 return ptr;
1965 void *
1966 _Jv_MallocUnchecked (jsize size)
1968 if (__builtin_expect (size == 0, false))
1969 size = 1;
1970 return malloc ((size_t) size);
1973 void
1974 _Jv_Free (void* ptr)
1976 return free (ptr);
1981 // In theory, these routines can be #ifdef'd away on machines which
1982 // support divide overflow signals. However, we never know if some
1983 // code might have been compiled with "-fuse-divide-subroutine", so we
1984 // always include them in libgcj.
1986 jint
1987 _Jv_divI (jint dividend, jint divisor)
1989 if (__builtin_expect (divisor == 0, false))
1991 java::lang::ArithmeticException *arithexception
1992 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1993 throw arithexception;
1996 if (dividend == (jint) 0x80000000L && divisor == -1)
1997 return dividend;
1999 return dividend / divisor;
2002 jint
2003 _Jv_remI (jint dividend, jint divisor)
2005 if (__builtin_expect (divisor == 0, false))
2007 java::lang::ArithmeticException *arithexception
2008 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
2009 throw arithexception;
2012 if (dividend == (jint) 0x80000000L && divisor == -1)
2013 return 0;
2015 return dividend % divisor;
2018 jlong
2019 _Jv_divJ (jlong dividend, jlong divisor)
2021 if (__builtin_expect (divisor == 0, false))
2023 java::lang::ArithmeticException *arithexception
2024 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
2025 throw arithexception;
2028 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
2029 return dividend;
2031 return dividend / divisor;
2034 jlong
2035 _Jv_remJ (jlong dividend, jlong divisor)
2037 if (__builtin_expect (divisor == 0, false))
2039 java::lang::ArithmeticException *arithexception
2040 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
2041 throw arithexception;
2044 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
2045 return 0;
2047 return dividend % divisor;
2052 // Return true if SELF_KLASS can access a field or method in
2053 // OTHER_KLASS. The field or method's access flags are specified in
2054 // FLAGS.
2055 jboolean
2056 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
2058 using namespace java::lang::reflect;
2059 return ((self_klass == other_klass)
2060 || ((flags & Modifier::PUBLIC) != 0)
2061 || (((flags & Modifier::PROTECTED) != 0)
2062 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
2063 || (((flags & Modifier::PRIVATE) == 0)
2064 && _Jv_ClassNameSamePackage (self_klass->name,
2065 other_klass->name)));
2068 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
2069 // char array, if the path is not already prefixed by
2070 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
2071 // result should be freed using JvFree.
2072 char*
2073 _Jv_PrependVersionedLibdir (char* libpath)
2075 char* retval = 0;
2077 if (libpath && libpath[0] != '\0')
2079 if (! strncmp (libpath,
2080 GCJ_VERSIONED_LIBDIR,
2081 sizeof (GCJ_VERSIONED_LIBDIR) - 1))
2083 // LD_LIBRARY_PATH is already prefixed with
2084 // GCJ_VERSIONED_LIBDIR.
2085 retval = (char*) _Jv_Malloc (strlen (libpath) + 1);
2086 strcpy (retval, libpath);
2088 else
2090 // LD_LIBRARY_PATH is not prefixed with
2091 // GCJ_VERSIONED_LIBDIR.
2092 char path_sep[2];
2093 path_sep[0] = (char) _Jv_platform_path_separator;
2094 path_sep[1] = '\0';
2095 jsize total = ((sizeof (GCJ_VERSIONED_LIBDIR) - 1)
2096 + 1 /* path separator */ + strlen (libpath) + 1);
2097 retval = (char*) _Jv_Malloc (total);
2098 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2099 strcat (retval, path_sep);
2100 strcat (retval, libpath);
2103 else
2105 // LD_LIBRARY_PATH was not specified or is empty.
2106 retval = (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR));
2107 strcpy (retval, GCJ_VERSIONED_LIBDIR);
2110 return retval;