* config/m68k/m68k.md (bungt_rev): New pattern.
[official-gcc.git] / libjava / prims.cc
blob3db82c19fa7fa481cb0966a7c0ab044fcc18a18b
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 // Execution engine for compiled code.
78 _Jv_CompiledEngine _Jv_soleCompiledEngine;
80 // Execution engine for code compiled with -findirect-classes
81 _Jv_IndirectCompiledEngine _Jv_soleIndirectCompiledEngine;
83 // We allocate a single OutOfMemoryError exception which we keep
84 // around for use if we run out of memory.
85 static java::lang::OutOfMemoryError *no_memory;
87 // Number of bytes in largest array object we create. This could be
88 // increased to the largest size_t value, so long as the appropriate
89 // functions are changed to take a size_t argument instead of jint.
90 #define MAX_OBJECT_SIZE ((1<<31) - 1)
92 // Properties set at compile time.
93 const char **_Jv_Compiler_Properties = NULL;
94 int _Jv_Properties_Count = 0;
96 #ifndef DISABLE_GETENV_PROPERTIES
97 // Property key/value pairs.
98 property_pair *_Jv_Environment_Properties;
99 #endif
101 // Stash the argv pointer to benefit native libraries that need it.
102 const char **_Jv_argv;
103 int _Jv_argc;
105 // Debugging options
106 static bool remoteDebug = false;
107 static char *jdwpOptions = "";
109 // Argument support.
111 _Jv_GetNbArgs (void)
113 // _Jv_argc is 0 if not explicitly initialized.
114 return _Jv_argc;
117 const char *
118 _Jv_GetSafeArg (int index)
120 if (index >=0 && index < _Jv_GetNbArgs ())
121 return _Jv_argv[index];
122 else
123 return "";
126 void
127 _Jv_SetArgs (int argc, const char **argv)
129 _Jv_argc = argc;
130 _Jv_argv = argv;
133 #ifdef ENABLE_JVMPI
134 // Pointer to JVMPI notification functions.
135 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
136 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
137 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
138 #endif
141 #if defined (HANDLE_SEGV) || defined(HANDLE_FPE)
142 /* Unblock a signal. Unless we do this, the signal may only be sent
143 once. */
144 static void
145 unblock_signal (int signum __attribute__ ((__unused__)))
147 #ifdef _POSIX_VERSION
148 sigset_t sigs;
150 sigemptyset (&sigs);
151 sigaddset (&sigs, signum);
152 sigprocmask (SIG_UNBLOCK, &sigs, NULL);
153 #endif
155 #endif
157 #ifdef HANDLE_SEGV
158 SIGNAL_HANDLER (catch_segv)
160 unblock_signal (SIGSEGV);
161 MAKE_THROW_FRAME (nullp);
162 java::lang::NullPointerException *nullp
163 = new java::lang::NullPointerException;
164 throw nullp;
166 #endif
168 #ifdef HANDLE_FPE
169 SIGNAL_HANDLER (catch_fpe)
171 unblock_signal (SIGFPE);
172 #ifdef HANDLE_DIVIDE_OVERFLOW
173 HANDLE_DIVIDE_OVERFLOW;
174 #else
175 MAKE_THROW_FRAME (arithexception);
176 #endif
177 java::lang::ArithmeticException *arithexception
178 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
179 throw arithexception;
181 #endif
184 jboolean
185 _Jv_equalUtf8Consts (const Utf8Const* a, const Utf8Const *b)
187 int len;
188 const _Jv_ushort *aptr, *bptr;
189 if (a == b)
190 return true;
191 if (a->hash != b->hash)
192 return false;
193 len = a->length;
194 if (b->length != len)
195 return false;
196 aptr = (const _Jv_ushort *)a->data;
197 bptr = (const _Jv_ushort *)b->data;
198 len = (len + 1) >> 1;
199 while (--len >= 0)
200 if (*aptr++ != *bptr++)
201 return false;
202 return true;
205 /* True iff A is equal to STR.
206 HASH is STR->hashCode().
209 jboolean
210 _Jv_equal (Utf8Const* a, jstring str, jint hash)
212 if (a->hash != (_Jv_ushort) hash)
213 return false;
214 jint len = str->length();
215 jint i = 0;
216 jchar *sptr = _Jv_GetStringChars (str);
217 unsigned char* ptr = (unsigned char*) a->data;
218 unsigned char* limit = ptr + a->length;
219 for (;; i++, sptr++)
221 int ch = UTF8_GET (ptr, limit);
222 if (i == len)
223 return ch < 0;
224 if (ch != *sptr)
225 return false;
227 return true;
230 /* Like _Jv_equal, but stop after N characters. */
231 jboolean
232 _Jv_equaln (Utf8Const *a, jstring str, jint n)
234 jint len = str->length();
235 jint i = 0;
236 jchar *sptr = _Jv_GetStringChars (str);
237 unsigned char* ptr = (unsigned char*) a->data;
238 unsigned char* limit = ptr + a->length;
239 for (; n-- > 0; i++, sptr++)
241 int ch = UTF8_GET (ptr, limit);
242 if (i == len)
243 return ch < 0;
244 if (ch != *sptr)
245 return false;
247 return true;
250 // Determines whether the given Utf8Const object contains
251 // a type which is primitive or some derived form of it, eg.
252 // an array or multi-dimensional array variant.
253 jboolean
254 _Jv_isPrimitiveOrDerived(const Utf8Const *a)
256 unsigned char *aptr = (unsigned char *) a->data;
257 unsigned char *alimit = aptr + a->length;
258 int ac = UTF8_GET(aptr, alimit);
260 // Skips any leading array marks.
261 while (ac == '[')
262 ac = UTF8_GET(aptr, alimit);
264 // There should not be another character. This implies that
265 // the type name is only one character long.
266 if (UTF8_GET(aptr, alimit) == -1)
267 switch ( ac )
269 case 'Z':
270 case 'B':
271 case 'C':
272 case 'S':
273 case 'I':
274 case 'J':
275 case 'F':
276 case 'D':
277 return true;
278 default:
279 break;
282 return false;
285 // Find out whether two _Jv_Utf8Const candidates contain the same
286 // classname.
287 // The method is written to handle the different formats of classnames.
288 // Eg. "Ljava/lang/Class;", "Ljava.lang.Class;", "java/lang/Class" and
289 // "java.lang.Class" will be seen as equal.
290 // Warning: This function is not smart enough to declare "Z" and "boolean"
291 // and similar cases as equal (and is not meant to be used this way)!
292 jboolean
293 _Jv_equalUtf8Classnames (const Utf8Const *a, const Utf8Const *b)
295 // If the class name's length differs by two characters
296 // it is possible that we have candidates which are given
297 // in the two different formats ("Lp1/p2/cn;" vs. "p1/p2/cn")
298 switch (a->length - b->length)
300 case -2:
301 case 0:
302 case 2:
303 break;
304 default:
305 return false;
308 unsigned char *aptr = (unsigned char *) a->data;
309 unsigned char *alimit = aptr + a->length;
310 unsigned char *bptr = (unsigned char *) b->data;
311 unsigned char *blimit = bptr + b->length;
313 if (alimit[-1] == ';')
314 alimit--;
316 if (blimit[-1] == ';')
317 blimit--;
319 int ac = UTF8_GET(aptr, alimit);
320 int bc = UTF8_GET(bptr, blimit);
322 // Checks whether both strings have the same amount of leading [ characters.
323 while (ac == '[')
325 if (bc == '[')
327 ac = UTF8_GET(aptr, alimit);
328 bc = UTF8_GET(bptr, blimit);
329 continue;
332 return false;
335 // Skips leading L character.
336 if (ac == 'L')
337 ac = UTF8_GET(aptr, alimit);
339 if (bc == 'L')
340 bc = UTF8_GET(bptr, blimit);
342 // Compares the remaining characters.
343 while (ac != -1 && bc != -1)
345 // Replaces package separating dots with slashes.
346 if (ac == '.')
347 ac = '/';
349 if (bc == '.')
350 bc = '/';
352 // Now classnames differ if there is at least one non-matching
353 // character.
354 if (ac != bc)
355 return false;
357 ac = UTF8_GET(aptr, alimit);
358 bc = UTF8_GET(bptr, blimit);
361 return (ac == bc);
364 /* Count the number of Unicode chars encoded in a given Ut8 string. */
366 _Jv_strLengthUtf8(const char* str, int len)
368 unsigned char* ptr;
369 unsigned char* limit;
370 int str_length;
372 ptr = (unsigned char*) str;
373 limit = ptr + len;
374 str_length = 0;
375 for (; ptr < limit; str_length++)
377 if (UTF8_GET (ptr, limit) < 0)
378 return (-1);
380 return (str_length);
383 /* Calculate a hash value for a string encoded in Utf8 format.
384 * This returns the same hash value as specified or java.lang.String.hashCode.
386 jint
387 _Jv_hashUtf8String (const char* str, int len)
389 unsigned char* ptr = (unsigned char*) str;
390 unsigned char* limit = ptr + len;
391 jint hash = 0;
393 for (; ptr < limit;)
395 int ch = UTF8_GET (ptr, limit);
396 /* Updated specification from
397 http://www.javasoft.com/docs/books/jls/clarify.html. */
398 hash = (31 * hash) + ch;
400 return hash;
403 void
404 _Jv_Utf8Const::init(const char *s, int len)
406 ::memcpy (data, s, len);
407 data[len] = 0;
408 length = len;
409 hash = _Jv_hashUtf8String (s, len) & 0xFFFF;
412 _Jv_Utf8Const *
413 _Jv_makeUtf8Const (const char* s, int len)
415 if (len < 0)
416 len = strlen (s);
417 Utf8Const* m
418 = (Utf8Const*) _Jv_AllocBytes (_Jv_Utf8Const::space_needed(s, len));
419 m->init(s, len);
420 return m;
423 _Jv_Utf8Const *
424 _Jv_makeUtf8Const (jstring string)
426 jint hash = string->hashCode ();
427 jint len = _Jv_GetStringUTFLength (string);
429 Utf8Const* m = (Utf8Const*)
430 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
432 m->hash = hash;
433 m->length = len;
435 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
436 m->data[len] = 0;
438 return m;
443 #ifdef DEBUG
444 void
445 _Jv_Abort (const char *function, const char *file, int line,
446 const char *message)
447 #else
448 void
449 _Jv_Abort (const char *, const char *, int, const char *message)
450 #endif
452 #ifdef DEBUG
453 fprintf (stderr,
454 "libgcj failure: %s\n in function %s, file %s, line %d\n",
455 message, function, file, line);
456 #else
457 fprintf (stderr, "libgcj failure: %s\n", message);
458 #endif
459 abort ();
462 static void
463 fail_on_finalization (jobject)
465 JvFail ("object was finalized");
468 void
469 _Jv_GCWatch (jobject obj)
471 _Jv_RegisterFinalizer (obj, fail_on_finalization);
474 void
475 _Jv_ThrowBadArrayIndex(jint bad_index)
477 throw new java::lang::ArrayIndexOutOfBoundsException
478 (java::lang::String::valueOf (bad_index));
481 void
482 _Jv_ThrowNullPointerException ()
484 throw new java::lang::NullPointerException;
487 // Resolve an entry in the constant pool and return the target
488 // address.
489 void *
490 _Jv_ResolvePoolEntry (jclass this_class, jint index)
492 _Jv_Constants *pool = &this_class->constants;
494 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
495 return pool->data[index].field->u.addr;
497 JvSynchronize sync (this_class);
498 return (_Jv_Linker::resolve_pool_entry (this_class, index))
499 .field->u.addr;
503 // Explicitly throw a no memory exception.
504 // The collector calls this when it encounters an out-of-memory condition.
505 void _Jv_ThrowNoMemory()
507 throw no_memory;
510 #ifdef ENABLE_JVMPI
511 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) \
512 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false)) \
513 jvmpi_notify_alloc(klass,size,obj);
514 static void
515 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
517 // Service JVMPI allocation request.
518 JVMPI_Event event;
520 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
521 event.env_id = NULL;
522 event.u.obj_alloc.arena_id = 0;
523 event.u.obj_alloc.class_id = (jobjectID) klass;
524 event.u.obj_alloc.is_array = 0;
525 event.u.obj_alloc.size = size;
526 event.u.obj_alloc.obj_id = (jobjectID) obj;
528 // FIXME: This doesn't look right for the Boehm GC. A GC may
529 // already be in progress. _Jv_DisableGC () doesn't wait for it.
530 // More importantly, I don't see the need for disabling GC, since we
531 // blatantly have a pointer to obj on our stack, ensuring that the
532 // object can't be collected. Even for a nonconservative collector,
533 // it appears to me that this must be true, since we are about to
534 // return obj. Isn't this whole approach way too intrusive for
535 // a useful profiling interface? - HB
536 _Jv_DisableGC ();
537 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
538 _Jv_EnableGC ();
540 #else /* !ENABLE_JVMPI */
541 # define JVMPI_NOTIFY_ALLOC(klass,size,obj) /* do nothing */
542 #endif
544 // Allocate a new object of class KLASS.
545 // First a version that assumes that we have no finalizer, and that
546 // the class is already initialized.
547 // If we know that JVMPI is disabled, this can be replaced by a direct call
548 // to the allocator for the appropriate GC.
549 jobject
550 _Jv_AllocObjectNoInitNoFinalizer (jclass klass)
552 jint size = klass->size ();
553 jobject obj = (jobject) _Jv_AllocObj (size, klass);
554 JVMPI_NOTIFY_ALLOC (klass, size, obj);
555 return obj;
558 // And now a version that initializes if necessary.
559 jobject
560 _Jv_AllocObjectNoFinalizer (jclass klass)
562 if (_Jv_IsPhantomClass(klass) )
563 throw new java::lang::NoClassDefFoundError(klass->getName());
565 _Jv_InitClass (klass);
566 jint size = klass->size ();
567 jobject obj = (jobject) _Jv_AllocObj (size, klass);
568 JVMPI_NOTIFY_ALLOC (klass, size, obj);
569 return obj;
572 // And now the general version that registers a finalizer if necessary.
573 jobject
574 _Jv_AllocObject (jclass klass)
576 jobject obj = _Jv_AllocObjectNoFinalizer (klass);
578 // We assume that the compiler only generates calls to this routine
579 // if there really is an interesting finalizer.
580 // Unfortunately, we still have to the dynamic test, since there may
581 // be cni calls to this routine.
582 // Note that on IA64 get_finalizer() returns the starting address of the
583 // function, not a function pointer. Thus this still works.
584 if (klass->vtable->get_finalizer ()
585 != java::lang::Object::class$.vtable->get_finalizer ())
586 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
587 return obj;
590 // Allocate a String, including variable length storage.
591 jstring
592 _Jv_AllocString(jsize len)
594 using namespace java::lang;
596 jsize sz = sizeof(java::lang::String) + len * sizeof(jchar);
598 // We assert that for strings allocated this way, the data field
599 // will always point to the object itself. Thus there is no reason
600 // for the garbage collector to scan any of it.
601 // Furthermore, we're about to overwrite the string data, so
602 // initialization of the object is not an issue.
604 // String needs no initialization, and there is no finalizer, so
605 // we can go directly to the collector's allocator interface.
606 jstring obj = (jstring) _Jv_AllocPtrFreeObj(sz, &String::class$);
608 obj->data = obj;
609 obj->boffset = sizeof(java::lang::String);
610 obj->count = len;
611 obj->cachedHashCode = 0;
613 JVMPI_NOTIFY_ALLOC (&String::class$, sz, obj);
615 return obj;
618 // A version of the above that assumes the object contains no pointers,
619 // and requires no finalization. This can't happen if we need pointers
620 // to locks.
621 #ifdef JV_HASH_SYNCHRONIZATION
622 jobject
623 _Jv_AllocPtrFreeObject (jclass klass)
625 _Jv_InitClass (klass);
626 jint size = klass->size ();
628 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
630 JVMPI_NOTIFY_ALLOC (klass, size, obj);
632 return obj;
634 #endif /* JV_HASH_SYNCHRONIZATION */
637 // Allocate a new array of Java objects. Each object is of type
638 // `elementClass'. `init' is used to initialize each slot in the
639 // array.
640 jobjectArray
641 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
643 // Creating an array of an unresolved type is impossible. So we throw
644 // the NoClassDefFoundError.
645 if ( _Jv_IsPhantomClass(elementClass) )
646 throw new java::lang::NoClassDefFoundError(elementClass->getName());
648 if (__builtin_expect (count < 0, false))
649 throw new java::lang::NegativeArraySizeException;
651 JvAssert (! elementClass->isPrimitive ());
653 // Ensure that elements pointer is properly aligned.
654 jobjectArray obj = NULL;
655 size_t size = (size_t) elements (obj);
656 // Check for overflow.
657 if (__builtin_expect ((size_t) count >
658 (MAX_OBJECT_SIZE - 1 - size) / sizeof (jobject), false))
659 throw no_memory;
661 size += count * sizeof (jobject);
663 jclass klass = _Jv_GetArrayClass (elementClass,
664 elementClass->getClassLoaderInternal());
666 obj = (jobjectArray) _Jv_AllocArray (size, klass);
667 // Cast away const.
668 jsize *lp = const_cast<jsize *> (&obj->length);
669 *lp = count;
670 // We know the allocator returns zeroed memory. So don't bother
671 // zeroing it again.
672 if (init)
674 jobject *ptr = elements(obj);
675 while (--count >= 0)
676 *ptr++ = init;
678 return obj;
681 // Allocate a new array of primitives. ELTYPE is the type of the
682 // element, COUNT is the size of the array.
683 jobject
684 _Jv_NewPrimArray (jclass eltype, jint count)
686 int elsize = eltype->size();
687 if (__builtin_expect (count < 0, false))
688 throw new java::lang::NegativeArraySizeException;
690 JvAssert (eltype->isPrimitive ());
691 jobject dummy = NULL;
692 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
694 // Check for overflow.
695 if (__builtin_expect ((size_t) count >
696 (MAX_OBJECT_SIZE - size) / elsize, false))
697 throw no_memory;
699 jclass klass = _Jv_GetArrayClass (eltype, 0);
701 # ifdef JV_HASH_SYNCHRONIZATION
702 // Since the vtable is always statically allocated,
703 // these are completely pointerfree! Make sure the GC doesn't touch them.
704 __JArray *arr =
705 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
706 memset((char *)arr + size, 0, elsize * count);
707 # else
708 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
709 // Note that we assume we are given zeroed memory by the allocator.
710 # endif
711 // Cast away const.
712 jsize *lp = const_cast<jsize *> (&arr->length);
713 *lp = count;
715 return arr;
718 jobject
719 _Jv_NewArray (jint type, jint size)
721 switch (type)
723 case 4: return JvNewBooleanArray (size);
724 case 5: return JvNewCharArray (size);
725 case 6: return JvNewFloatArray (size);
726 case 7: return JvNewDoubleArray (size);
727 case 8: return JvNewByteArray (size);
728 case 9: return JvNewShortArray (size);
729 case 10: return JvNewIntArray (size);
730 case 11: return JvNewLongArray (size);
732 throw new java::lang::InternalError
733 (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
736 // Allocate a possibly multi-dimensional array but don't check that
737 // any array length is <0.
738 static jobject
739 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
741 JvAssert (type->isArray());
742 jclass element_type = type->getComponentType();
743 jobject result;
744 if (element_type->isPrimitive())
745 result = _Jv_NewPrimArray (element_type, sizes[0]);
746 else
747 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
749 if (dimensions > 1)
751 JvAssert (! element_type->isPrimitive());
752 JvAssert (element_type->isArray());
753 jobject *contents = elements ((jobjectArray) result);
754 for (int i = 0; i < sizes[0]; ++i)
755 contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
756 sizes + 1);
759 return result;
762 jobject
763 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
765 for (int i = 0; i < dimensions; ++i)
766 if (sizes[i] < 0)
767 throw new java::lang::NegativeArraySizeException;
769 return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
772 jobject
773 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
775 // Creating an array of an unresolved type is impossible. So we throw
776 // the NoClassDefFoundError.
777 if (_Jv_IsPhantomClass(array_type))
778 throw new java::lang::NoClassDefFoundError(array_type->getName());
780 va_list args;
781 jint sizes[dimensions];
782 va_start (args, dimensions);
783 for (int i = 0; i < dimensions; ++i)
785 jint size = va_arg (args, jint);
786 if (size < 0)
787 throw new java::lang::NegativeArraySizeException;
788 sizes[i] = size;
790 va_end (args);
792 return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
797 // Ensure 8-byte alignment, for hash synchronization.
798 #define DECLARE_PRIM_TYPE(NAME) \
799 java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
801 DECLARE_PRIM_TYPE(byte)
802 DECLARE_PRIM_TYPE(short)
803 DECLARE_PRIM_TYPE(int)
804 DECLARE_PRIM_TYPE(long)
805 DECLARE_PRIM_TYPE(boolean)
806 DECLARE_PRIM_TYPE(char)
807 DECLARE_PRIM_TYPE(float)
808 DECLARE_PRIM_TYPE(double)
809 DECLARE_PRIM_TYPE(void)
811 void
812 _Jv_InitPrimClass (jclass cl, const char *cname, char sig, int len)
814 using namespace java::lang::reflect;
816 // We must set the vtable for the class; the Java constructor
817 // doesn't do this.
818 (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
820 // Initialize the fields we care about. We do this in the same
821 // order they are declared in Class.h.
822 cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
823 cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
824 cl->method_count = sig;
825 cl->size_in_bytes = len;
826 cl->vtable = JV_PRIMITIVE_VTABLE;
827 cl->state = JV_STATE_DONE;
828 cl->depth = -1;
831 jclass
832 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader,
833 char **endp)
835 // First count arrays.
836 int array_count = 0;
837 while (*sig == '[')
839 ++sig;
840 ++array_count;
843 jclass result = NULL;
844 switch (*sig)
846 case 'B':
847 result = JvPrimClass (byte);
848 break;
849 case 'S':
850 result = JvPrimClass (short);
851 break;
852 case 'I':
853 result = JvPrimClass (int);
854 break;
855 case 'J':
856 result = JvPrimClass (long);
857 break;
858 case 'Z':
859 result = JvPrimClass (boolean);
860 break;
861 case 'C':
862 result = JvPrimClass (char);
863 break;
864 case 'F':
865 result = JvPrimClass (float);
866 break;
867 case 'D':
868 result = JvPrimClass (double);
869 break;
870 case 'V':
871 result = JvPrimClass (void);
872 break;
873 case 'L':
875 char *save = ++sig;
876 while (*sig && *sig != ';')
877 ++sig;
878 // Do nothing if signature appears to be malformed.
879 if (*sig == ';')
881 _Jv_Utf8Const *name = _Jv_makeUtf8Const (save, sig - save);
882 result = _Jv_FindClass (name, loader);
884 break;
886 default:
887 // Do nothing -- bad signature.
888 break;
891 if (endp)
893 // Not really the "end", but the last valid character that we
894 // looked at.
895 *endp = sig;
898 if (! result)
899 return NULL;
901 // Find arrays.
902 while (array_count-- > 0)
903 result = _Jv_GetArrayClass (result, loader);
904 return result;
908 jclass
909 _Jv_FindClassFromSignatureNoException (char *sig, java::lang::ClassLoader *loader,
910 char **endp)
912 jclass klass;
916 klass = _Jv_FindClassFromSignature(sig, loader, endp);
918 catch (java::lang::NoClassDefFoundError *ncdfe)
920 return NULL;
922 catch (java::lang::ClassNotFoundException *cnfe)
924 return NULL;
927 return klass;
930 JArray<jstring> *
931 JvConvertArgv (int argc, const char **argv)
933 if (argc < 0)
934 argc = 0;
935 jobjectArray ar = JvNewObjectArray(argc, &java::lang::String::class$, NULL);
936 jobject *ptr = elements(ar);
937 jbyteArray bytes = NULL;
938 for (int i = 0; i < argc; i++)
940 const char *arg = argv[i];
941 int len = strlen (arg);
942 if (bytes == NULL || bytes->length < len)
943 bytes = JvNewByteArray (len);
944 jbyte *bytePtr = elements (bytes);
945 // We assume jbyte == char.
946 memcpy (bytePtr, arg, len);
948 // Now convert using the default encoding.
949 *ptr++ = new java::lang::String (bytes, 0, len);
951 return (JArray<jstring>*) ar;
954 // FIXME: These variables are static so that they will be
955 // automatically scanned by the Boehm collector. This is needed
956 // because with qthreads the collector won't scan the initial stack --
957 // it will only scan the qthreads stacks.
959 // Command line arguments.
960 static JArray<jstring> *arg_vec;
962 // The primary thread.
963 static java::lang::Thread *main_thread;
965 #ifndef DISABLE_GETENV_PROPERTIES
967 static char *
968 next_property_key (char *s, size_t *length)
970 size_t l = 0;
972 JvAssert (s);
974 // Skip over whitespace
975 while (isspace (*s))
976 s++;
978 // If we've reached the end, return NULL. Also return NULL if for
979 // some reason we've come across a malformed property string.
980 if (*s == 0
981 || *s == ':'
982 || *s == '=')
983 return NULL;
985 // Determine the length of the property key.
986 while (s[l] != 0
987 && ! isspace (s[l])
988 && s[l] != ':'
989 && s[l] != '=')
991 if (s[l] == '\\'
992 && s[l+1] != 0)
993 l++;
994 l++;
997 *length = l;
999 return s;
1002 static char *
1003 next_property_value (char *s, size_t *length)
1005 size_t l = 0;
1007 JvAssert (s);
1009 while (isspace (*s))
1010 s++;
1012 if (*s == ':'
1013 || *s == '=')
1014 s++;
1016 while (isspace (*s))
1017 s++;
1019 // Determine the length of the property value.
1020 while (s[l] != 0
1021 && ! isspace (s[l])
1022 && s[l] != ':'
1023 && s[l] != '=')
1025 if (s[l] == '\\'
1026 && s[l+1] != 0)
1027 l += 2;
1028 else
1029 l++;
1032 *length = l;
1034 return s;
1037 static void
1038 process_gcj_properties ()
1040 char *props = getenv("GCJ_PROPERTIES");
1042 if (NULL == props)
1043 return;
1045 // Later on we will write \0s into this string. It is simplest to
1046 // just duplicate it here.
1047 props = strdup (props);
1049 char *p = props;
1050 size_t length;
1051 size_t property_count = 0;
1053 // Whip through props quickly in order to count the number of
1054 // property values.
1055 while (p && (p = next_property_key (p, &length)))
1057 // Skip to the end of the key
1058 p += length;
1060 p = next_property_value (p, &length);
1061 if (p)
1062 p += length;
1064 property_count++;
1067 // Allocate an array of property value/key pairs.
1068 _Jv_Environment_Properties =
1069 (property_pair *) malloc (sizeof(property_pair)
1070 * (property_count + 1));
1072 // Go through the properties again, initializing _Jv_Properties
1073 // along the way.
1074 p = props;
1075 property_count = 0;
1076 while (p && (p = next_property_key (p, &length)))
1078 _Jv_Environment_Properties[property_count].key = p;
1079 _Jv_Environment_Properties[property_count].key_length = length;
1081 // Skip to the end of the key
1082 p += length;
1084 p = next_property_value (p, &length);
1086 _Jv_Environment_Properties[property_count].value = p;
1087 _Jv_Environment_Properties[property_count].value_length = length;
1089 if (p)
1090 p += length;
1092 property_count++;
1094 memset ((void *) &_Jv_Environment_Properties[property_count],
1095 0, sizeof (property_pair));
1097 // Null terminate the strings.
1098 for (property_pair *prop = &_Jv_Environment_Properties[0];
1099 prop->key != NULL;
1100 prop++)
1102 prop->key[prop->key_length] = 0;
1103 prop->value[prop->value_length] = 0;
1106 #endif // DISABLE_GETENV_PROPERTIES
1108 namespace gcj
1110 _Jv_Utf8Const *void_signature;
1111 _Jv_Utf8Const *clinit_name;
1112 _Jv_Utf8Const *init_name;
1113 _Jv_Utf8Const *finit_name;
1115 bool runtimeInitialized = false;
1117 // When true, print debugging information about class loading.
1118 bool verbose_class_flag;
1120 // When true, enable the bytecode verifier and BC-ABI type verification.
1121 bool verifyClasses = true;
1123 // Thread stack size specified by the -Xss runtime argument.
1124 size_t stack_size = 0;
1127 // We accept all non-standard options accepted by Sun's java command,
1128 // for compatibility with existing application launch scripts.
1129 static jint
1130 parse_x_arg (char* option_string)
1132 if (strlen (option_string) <= 0)
1133 return -1;
1135 if (! strcmp (option_string, "int"))
1137 // FIXME: this should cause the vm to never load shared objects
1139 else if (! strcmp (option_string, "mixed"))
1141 // FIXME: allow interpreted and native code
1143 else if (! strcmp (option_string, "batch"))
1145 // FIXME: disable background JIT'ing
1147 else if (! strcmp (option_string, "debug"))
1149 remoteDebug = true;
1151 else if (! strncmp (option_string, "runjdwp:", 8))
1153 if (strlen (option_string) > 8)
1154 jdwpOptions = &option_string[8];
1155 else
1157 fprintf (stderr,
1158 "libgcj: argument required for JDWP options");
1159 return -1;
1162 else if (! strncmp (option_string, "bootclasspath:", 14))
1164 // FIXME: add a parse_bootclasspath_arg function
1166 else if (! strncmp (option_string, "bootclasspath/a:", 16))
1169 else if (! strncmp (option_string, "bootclasspath/p:", 16))
1172 else if (! strcmp (option_string, "check:jni"))
1174 // FIXME: enable strict JNI checking
1176 else if (! strcmp (option_string, "future"))
1178 // FIXME: enable strict class file format checks
1180 else if (! strcmp (option_string, "noclassgc"))
1182 // FIXME: disable garbage collection for classes
1184 else if (! strcmp (option_string, "incgc"))
1186 // FIXME: incremental garbage collection
1188 else if (! strncmp (option_string, "loggc:", 6))
1190 if (option_string[6] == '\0')
1192 fprintf (stderr,
1193 "libgcj: filename argument expected for loggc option\n");
1194 return -1;
1196 // FIXME: set gc logging filename
1198 else if (! strncmp (option_string, "ms", 2))
1200 // FIXME: ignore this option until PR 20699 is fixed.
1201 // _Jv_SetInitialHeapSize (option_string + 2);
1203 else if (! strncmp (option_string, "mx", 2))
1204 _Jv_SetMaximumHeapSize (option_string + 2);
1205 else if (! strcmp (option_string, "prof"))
1207 // FIXME: enable profiling of program running in vm
1209 else if (! strncmp (option_string, "runhprof:", 9))
1211 // FIXME: enable specific type of vm profiling. add a
1212 // parse_runhprof_arg function
1214 else if (! strcmp (option_string, "rs"))
1216 // FIXME: reduced system signal usage. disable thread dumps,
1217 // only terminate in response to user-initiated calls,
1218 // e.g. System.exit()
1220 else if (! strncmp (option_string, "ss", 2))
1222 _Jv_SetStackSize (option_string + 2);
1224 else if (! strcmp (option_string, "X:+UseAltSigs"))
1226 // FIXME: use signals other than SIGUSR1 and SIGUSR2
1228 else if (! strcmp (option_string, "share:off"))
1230 // FIXME: don't share class data
1232 else if (! strcmp (option_string, "share:auto"))
1234 // FIXME: share class data where possible
1236 else if (! strcmp (option_string, "share:on"))
1238 // FIXME: fail if impossible to share class data
1241 return 0;
1244 static jint
1245 parse_verbose_args (char* option_string,
1246 bool ignore_unrecognized)
1248 size_t len = sizeof ("-verbose") - 1;
1250 if (strlen (option_string) < len)
1251 return -1;
1253 if (option_string[len] == ':'
1254 && option_string[len + 1] != '\0')
1256 char* verbose_args = option_string + len + 1;
1260 if (! strncmp (verbose_args,
1261 "gc", sizeof ("gc") - 1))
1263 if (verbose_args[sizeof ("gc") - 1] == '\0'
1264 || verbose_args[sizeof ("gc") - 1] == ',')
1266 // FIXME: we should add functions to boehm-gc that
1267 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1268 // GC_print_back_height.
1269 verbose_args += sizeof ("gc") - 1;
1271 else
1273 verbose_arg_err:
1274 fprintf (stderr, "libgcj: unknown verbose option: %s\n",
1275 option_string);
1276 return -1;
1279 else if (! strncmp (verbose_args,
1280 "class",
1281 sizeof ("class") - 1))
1283 if (verbose_args[sizeof ("class") - 1] == '\0'
1284 || verbose_args[sizeof ("class") - 1] == ',')
1286 gcj::verbose_class_flag = true;
1287 verbose_args += sizeof ("class") - 1;
1289 else
1290 goto verbose_arg_err;
1292 else if (! strncmp (verbose_args, "jni",
1293 sizeof ("jni") - 1))
1295 if (verbose_args[sizeof ("jni") - 1] == '\0'
1296 || verbose_args[sizeof ("jni") - 1] == ',')
1298 // FIXME: enable JNI messages.
1299 verbose_args += sizeof ("jni") - 1;
1301 else
1302 goto verbose_arg_err;
1304 else if (ignore_unrecognized
1305 && verbose_args[0] == 'X')
1307 // ignore unrecognized non-standard verbose option
1308 while (verbose_args[0] != '\0'
1309 && verbose_args[0] != ',')
1310 verbose_args++;
1312 else if (verbose_args[0] == ',')
1314 verbose_args++;
1316 else
1317 goto verbose_arg_err;
1319 if (verbose_args[0] == ',')
1320 verbose_args++;
1322 while (verbose_args[0] != '\0');
1324 else if (option_string[len] == 'g'
1325 && option_string[len + 1] == 'c'
1326 && option_string[len + 2] == '\0')
1328 // FIXME: we should add functions to boehm-gc that
1329 // toggle GC_print_stats, GC_PRINT_ADDRESS_MAP and
1330 // GC_print_back_height.
1331 return 0;
1333 else if (option_string[len] == '\0')
1335 gcj::verbose_class_flag = true;
1336 return 0;
1338 else
1340 // unrecognized option beginning with -verbose
1341 return -1;
1343 return 0;
1346 static jint
1347 parse_init_args (JvVMInitArgs* vm_args)
1349 // if _Jv_Compiler_Properties is non-NULL then it needs to be
1350 // re-allocated dynamically.
1351 if (_Jv_Compiler_Properties)
1353 const char** props = _Jv_Compiler_Properties;
1354 _Jv_Compiler_Properties = NULL;
1356 for (int i = 0; props[i]; i++)
1358 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1359 (_Jv_Compiler_Properties,
1360 (_Jv_Properties_Count + 1) * sizeof (const char*));
1361 _Jv_Compiler_Properties[_Jv_Properties_Count++] = props[i];
1365 if (vm_args == NULL)
1366 return 0;
1368 for (int i = 0; i < vm_args->nOptions; ++i)
1370 char* option_string = vm_args->options[i].optionString;
1371 if (! strcmp (option_string, "vfprintf")
1372 || ! strcmp (option_string, "exit")
1373 || ! strcmp (option_string, "abort"))
1375 // FIXME: we are required to recognize these, but for
1376 // now we don't handle them in any way.
1377 continue;
1379 else if (! strncmp (option_string,
1380 "-verbose", sizeof ("-verbose") - 1))
1382 jint result = parse_verbose_args (option_string,
1383 vm_args->ignoreUnrecognized);
1384 if (result < 0)
1385 return result;
1387 else if (! strncmp (option_string, "-D", 2))
1389 _Jv_Compiler_Properties = (const char**) _Jv_Realloc
1390 (_Jv_Compiler_Properties,
1391 (_Jv_Properties_Count + 1) * sizeof (char*));
1393 _Jv_Compiler_Properties[_Jv_Properties_Count++] =
1394 strdup (option_string + 2);
1396 continue;
1398 else if (vm_args->ignoreUnrecognized)
1400 if (option_string[0] == '_')
1401 parse_x_arg (option_string + 1);
1402 else if (! strncmp (option_string, "-X", 2))
1403 parse_x_arg (option_string + 2);
1404 else
1406 unknown_option:
1407 fprintf (stderr, "libgcj: unknown option: %s\n", option_string);
1408 return -1;
1411 else
1412 goto unknown_option;
1414 return 0;
1417 jint
1418 _Jv_CreateJavaVM (JvVMInitArgs* vm_args)
1420 using namespace gcj;
1422 if (runtimeInitialized)
1423 return -1;
1425 jint result = parse_init_args (vm_args);
1426 if (result < 0)
1427 return -1;
1429 PROCESS_GCJ_PROPERTIES;
1431 /* Threads must be initialized before the GC, so that it inherits the
1432 signal mask. */
1433 _Jv_InitThreads ();
1434 _Jv_InitGC ();
1435 _Jv_InitializeSyncMutex ();
1437 #ifdef INTERPRETER
1438 _Jv_InitInterpreter ();
1439 #endif
1441 #ifdef HANDLE_SEGV
1442 INIT_SEGV;
1443 #endif
1445 #ifdef HANDLE_FPE
1446 INIT_FPE;
1447 #endif
1449 /* Initialize Utf8 constants declared in jvm.h. */
1450 void_signature = _Jv_makeUtf8Const ("()V", 3);
1451 clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
1452 init_name = _Jv_makeUtf8Const ("<init>", 6);
1453 finit_name = _Jv_makeUtf8Const ("finit$", 6);
1455 /* Initialize built-in classes to represent primitive TYPEs. */
1456 _Jv_InitPrimClass (&_Jv_byteClass, "byte", 'B', 1);
1457 _Jv_InitPrimClass (&_Jv_shortClass, "short", 'S', 2);
1458 _Jv_InitPrimClass (&_Jv_intClass, "int", 'I', 4);
1459 _Jv_InitPrimClass (&_Jv_longClass, "long", 'J', 8);
1460 _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1);
1461 _Jv_InitPrimClass (&_Jv_charClass, "char", 'C', 2);
1462 _Jv_InitPrimClass (&_Jv_floatClass, "float", 'F', 4);
1463 _Jv_InitPrimClass (&_Jv_doubleClass, "double", 'D', 8);
1464 _Jv_InitPrimClass (&_Jv_voidClass, "void", 'V', 0);
1466 // We have to initialize this fairly early, to avoid circular class
1467 // initialization. In particular we want to start the
1468 // initialization of ClassLoader before we start the initialization
1469 // of VMClassLoader.
1470 _Jv_InitClass (&java::lang::ClassLoader::class$);
1472 // Set up the system class loader and the bootstrap class loader.
1473 gnu::gcj::runtime::ExtensionClassLoader::initialize();
1474 java::lang::VMClassLoader::initialize(JvNewStringLatin1(TOOLEXECLIBDIR));
1476 _Jv_RegisterBootstrapPackages();
1478 no_memory = new java::lang::OutOfMemoryError;
1480 #ifdef USE_LTDL
1481 LTDL_SET_PRELOADED_SYMBOLS ();
1482 #endif
1484 _Jv_platform_initialize ();
1486 _Jv_JNI_Init ();
1487 _Jv_JVMTI_Init ();
1489 _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
1491 // Start the GC finalizer thread. A VirtualMachineError can be
1492 // thrown by the runtime if, say, threads aren't available.
1495 using namespace gnu::gcj::runtime;
1496 FinalizerThread *ft = new FinalizerThread ();
1497 ft->start ();
1499 catch (java::lang::VirtualMachineError *ignore)
1503 runtimeInitialized = true;
1505 return 0;
1508 void
1509 _Jv_RunMain (JvVMInitArgs *vm_args, jclass klass, const char *name, int argc,
1510 const char **argv, bool is_jar)
1512 #ifndef DISABLE_MAIN_ARGS
1513 _Jv_SetArgs (argc, argv);
1514 #endif
1516 java::lang::Runtime *runtime = NULL;
1520 if (_Jv_CreateJavaVM (vm_args) < 0)
1522 fprintf (stderr, "libgcj: couldn't create virtual machine\n");
1523 exit (1);
1526 // Get the Runtime here. We want to initialize it before searching
1527 // for `main'; that way it will be set up if `main' is a JNI method.
1528 runtime = java::lang::Runtime::getRuntime ();
1530 #ifdef DISABLE_MAIN_ARGS
1531 arg_vec = JvConvertArgv (0, 0);
1532 #else
1533 arg_vec = JvConvertArgv (argc - 1, argv + 1);
1534 #endif
1536 using namespace gnu::java::lang;
1537 if (klass)
1538 main_thread = new MainThread (klass, arg_vec);
1539 else
1540 main_thread = new MainThread (JvNewStringUTF (name),
1541 arg_vec, is_jar);
1542 _Jv_AttachCurrentThread (main_thread);
1544 // Start JDWP
1545 if (remoteDebug)
1547 using namespace gnu::classpath::jdwp;
1548 VMVirtualMachine::initialize ();
1549 Jdwp *jdwp = new Jdwp ();
1550 jdwp->setDaemon (true);
1551 jdwp->configure (JvNewStringLatin1 (jdwpOptions));
1552 jdwp->start ();
1554 // Wait for JDWP to initialize and start
1555 jdwp->join ();
1558 // Send VmInit
1559 gnu::classpath::jdwp::event::VmInitEvent *event;
1560 event = new gnu::classpath::jdwp::event::VmInitEvent (main_thread);
1561 gnu::classpath::jdwp::Jdwp::notify (event);
1563 catch (java::lang::Throwable *t)
1565 java::lang::System::err->println (JvNewStringLatin1
1566 ("Exception during runtime initialization"));
1567 t->printStackTrace();
1568 if (runtime)
1569 java::lang::Runtime::exitNoChecksAccessor (1);
1570 // In case the runtime creation failed.
1571 ::exit (1);
1574 _Jv_ThreadRun (main_thread);
1576 // Notify debugger of VM's death
1577 if (gnu::classpath::jdwp::Jdwp::isDebugging)
1579 using namespace gnu::classpath::jdwp;
1580 event::VmDeathEvent *event = new event::VmDeathEvent ();
1581 Jdwp::notify (event);
1584 // If we got here then something went wrong, as MainThread is not
1585 // supposed to terminate.
1586 ::exit (1);
1589 void
1590 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
1591 bool is_jar)
1593 _Jv_RunMain (NULL, klass, name, argc, argv, is_jar);
1596 void
1597 JvRunMain (jclass klass, int argc, const char **argv)
1599 _Jv_RunMain (klass, NULL, argc, argv, false);
1604 // Parse a string and return a heap size.
1605 static size_t
1606 parse_memory_size (const char *spec)
1608 char *end;
1609 unsigned long val = strtoul (spec, &end, 10);
1610 if (*end == 'k' || *end == 'K')
1611 val *= 1024;
1612 else if (*end == 'm' || *end == 'M')
1613 val *= 1048576;
1614 return (size_t) val;
1617 // Set the initial heap size. This might be ignored by the GC layer.
1618 // This must be called before _Jv_RunMain.
1619 void
1620 _Jv_SetInitialHeapSize (const char *arg)
1622 size_t size = parse_memory_size (arg);
1623 _Jv_GCSetInitialHeapSize (size);
1626 // Set the maximum heap size. This might be ignored by the GC layer.
1627 // This must be called before _Jv_RunMain.
1628 void
1629 _Jv_SetMaximumHeapSize (const char *arg)
1631 size_t size = parse_memory_size (arg);
1632 _Jv_GCSetMaximumHeapSize (size);
1635 void
1636 _Jv_SetStackSize (const char *arg)
1638 size_t size = parse_memory_size (arg);
1639 gcj::stack_size = size;
1642 void *
1643 _Jv_Malloc (jsize size)
1645 if (__builtin_expect (size == 0, false))
1646 size = 1;
1647 void *ptr = malloc ((size_t) size);
1648 if (__builtin_expect (ptr == NULL, false))
1649 throw no_memory;
1650 return ptr;
1653 void *
1654 _Jv_Realloc (void *ptr, jsize size)
1656 if (__builtin_expect (size == 0, false))
1657 size = 1;
1658 ptr = realloc (ptr, (size_t) size);
1659 if (__builtin_expect (ptr == NULL, false))
1660 throw no_memory;
1661 return ptr;
1664 void *
1665 _Jv_MallocUnchecked (jsize size)
1667 if (__builtin_expect (size == 0, false))
1668 size = 1;
1669 return malloc ((size_t) size);
1672 void
1673 _Jv_Free (void* ptr)
1675 return free (ptr);
1680 // In theory, these routines can be #ifdef'd away on machines which
1681 // support divide overflow signals. However, we never know if some
1682 // code might have been compiled with "-fuse-divide-subroutine", so we
1683 // always include them in libgcj.
1685 jint
1686 _Jv_divI (jint dividend, jint divisor)
1688 if (__builtin_expect (divisor == 0, false))
1690 java::lang::ArithmeticException *arithexception
1691 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1692 throw arithexception;
1695 if (dividend == (jint) 0x80000000L && divisor == -1)
1696 return dividend;
1698 return dividend / divisor;
1701 jint
1702 _Jv_remI (jint dividend, jint divisor)
1704 if (__builtin_expect (divisor == 0, false))
1706 java::lang::ArithmeticException *arithexception
1707 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1708 throw arithexception;
1711 if (dividend == (jint) 0x80000000L && divisor == -1)
1712 return 0;
1714 return dividend % divisor;
1717 jlong
1718 _Jv_divJ (jlong dividend, jlong divisor)
1720 if (__builtin_expect (divisor == 0, false))
1722 java::lang::ArithmeticException *arithexception
1723 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1724 throw arithexception;
1727 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1728 return dividend;
1730 return dividend / divisor;
1733 jlong
1734 _Jv_remJ (jlong dividend, jlong divisor)
1736 if (__builtin_expect (divisor == 0, false))
1738 java::lang::ArithmeticException *arithexception
1739 = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
1740 throw arithexception;
1743 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1744 return 0;
1746 return dividend % divisor;
1751 // Return true if SELF_KLASS can access a field or method in
1752 // OTHER_KLASS. The field or method's access flags are specified in
1753 // FLAGS.
1754 jboolean
1755 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1757 using namespace java::lang::reflect;
1758 return ((self_klass == other_klass)
1759 || ((flags & Modifier::PUBLIC) != 0)
1760 || (((flags & Modifier::PROTECTED) != 0)
1761 && _Jv_IsAssignableFromSlow (self_klass, other_klass))
1762 || (((flags & Modifier::PRIVATE) == 0)
1763 && _Jv_ClassNameSamePackage (self_klass->name,
1764 other_klass->name)));
1767 // Prepend GCJ_VERSIONED_LIBDIR to a module search path stored in a C
1768 // char array, if the path is not already prefixed by
1769 // GCJ_VERSIONED_LIBDIR. Return a newly JvMalloc'd char buffer. The
1770 // result should be freed using JvFree.
1771 char*
1772 _Jv_PrependVersionedLibdir (char* libpath)
1774 char* retval = 0;
1776 if (libpath && libpath[0] != '\0')
1778 if (! strncmp (libpath,
1779 GCJ_VERSIONED_LIBDIR,
1780 sizeof (GCJ_VERSIONED_LIBDIR) - 1))
1782 // LD_LIBRARY_PATH is already prefixed with
1783 // GCJ_VERSIONED_LIBDIR.
1784 retval = (char*) _Jv_Malloc (strlen (libpath) + 1);
1785 strcpy (retval, libpath);
1787 else
1789 // LD_LIBRARY_PATH is not prefixed with
1790 // GCJ_VERSIONED_LIBDIR.
1791 jsize total = (sizeof (GCJ_VERSIONED_LIBDIR) - 1)
1792 + (sizeof (PATH_SEPARATOR) - 1) + strlen (libpath) + 1;
1793 retval = (char*) _Jv_Malloc (total);
1794 strcpy (retval, GCJ_VERSIONED_LIBDIR);
1795 strcat (retval, PATH_SEPARATOR);
1796 strcat (retval, libpath);
1799 else
1801 // LD_LIBRARY_PATH was not specified or is empty.
1802 retval = (char*) _Jv_Malloc (sizeof (GCJ_VERSIONED_LIBDIR));
1803 strcpy (retval, GCJ_VERSIONED_LIBDIR);
1806 return retval;