1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999 Cygnus Solutions
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
18 #pragma implementation "java-array.h"
22 #include <java-signal.h>
24 #include <java/lang/Class.h>
25 #include <java/lang/Runtime.h>
26 #include <java/lang/String.h>
27 #include <java/lang/Thread.h>
28 #include <java/lang/ThreadGroup.h>
29 #include <java/lang/FirstThread.h>
30 #include <java/lang/ArrayIndexOutOfBoundsException.h>
31 #include <java/lang/ArithmeticException.h>
32 #include <java/lang/ClassFormatError.h>
33 #include <java/lang/ClassCastException.h>
34 #include <java/lang/NegativeArraySizeException.h>
35 #include <java/lang/NullPointerException.h>
36 #include <java/lang/OutOfMemoryError.h>
37 #include <java/lang/ArrayStoreException.h>
38 #include <java/lang/System.h>
39 #include <java/lang/reflect/Modifier.h>
40 #include <java/io/PrintStream.h>
46 #define ObjectClass _CL_Q34java4lang6Object
47 extern java::lang::Class ObjectClass;
49 // We allocate a single OutOfMemoryError exception which we keep
50 // around for use if we run out of memory.
51 static java::lang::OutOfMemoryError *no_memory;
53 // Largest representable size_t.
54 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
59 static java::lang::NullPointerException *nullp;
60 SIGNAL_HANDLER (catch_segv)
67 static java::lang::ArithmeticException *arithexception;
70 SIGNAL_HANDLER (catch_fpe)
72 #ifdef HANDLE_DIVIDE_OVERFLOW
73 HANDLE_DIVIDE_OVERFLOW;
77 _Jv_Throw (arithexception);
84 _Jv_equalUtf8Consts (Utf8Const* a, Utf8Const *b)
87 register _Jv_ushort *aptr, *bptr;
90 if (a->hash != b->hash)
95 aptr = (_Jv_ushort *)a->data;
96 bptr = (_Jv_ushort *)b->data;
99 if (*aptr++ != *bptr++)
104 /* True iff A is equal to STR.
105 HASH is STR->hashCode().
109 _Jv_equal (Utf8Const* a, jstring str, jint hash)
111 if (a->hash != (_Jv_ushort) hash)
113 jint len = str->length();
115 jchar *sptr = _Jv_GetStringChars (str);
116 register unsigned char* ptr = (unsigned char*) a->data;
117 register unsigned char* limit = ptr + a->length;
120 int ch = UTF8_GET (ptr, limit);
129 /* Count the number of Unicode chars encoded in a given Ut8 string. */
131 _Jv_strLengthUtf8(char* str, int len)
133 register unsigned char* ptr;
134 register unsigned char* limit;
137 ptr = (unsigned char*) str;
140 for (; ptr < limit; str_length++) {
141 if (UTF8_GET (ptr, limit) < 0) {
148 /* Calculate a hash value for a string encoded in Utf8 format.
149 * This returns the same hash value as specified or java.lang.String.hashCode.
152 hashUtf8String (char* str, int len)
154 register unsigned char* ptr = (unsigned char*) str;
155 register unsigned char* limit = ptr + len;
160 int ch = UTF8_GET (ptr, limit);
161 /* Updated specification from
162 http://www.javasoft.com/docs/books/jls/clarify.html. */
163 hash = (31 * hash) + ch;
169 _Jv_makeUtf8Const (char* s, int len)
173 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
176 memcpy (m->data, s, len);
179 m->hash = hashUtf8String (s, len) & 0xFFFF;
184 _Jv_makeUtf8Const (jstring string)
186 jint hash = string->hashCode ();
187 jint len = _Jv_GetStringUTFLength (string);
189 Utf8Const* m = (Utf8Const*)
190 _Jv_AllocBytesChecked (sizeof(Utf8Const) + len + 1);
195 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
205 _Jv_Abort (const char *function, const char *file, int line,
209 _Jv_Abort (const char *, const char *, int, const char *message)
214 "libgcj failure: %s\n in function %s, file %s, line %d\n",
215 message, function, file, line);
217 java::io::PrintStream *err = java::lang::System::err;
218 err->print(JvNewStringLatin1 ("libgcj failure: "));
219 err->println(JvNewStringLatin1 (message));
226 fail_on_finalization (jobject)
228 JvFail ("object was finalized");
232 _Jv_GCWatch (jobject obj)
234 _Jv_RegisterFinalizer (obj, fail_on_finalization);
238 _Jv_ThrowBadArrayIndex(jint bad_index)
240 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
241 (java::lang::String::valueOf(bad_index)));
245 _Jv_CheckCast (jclass c, jobject obj)
247 if (obj != NULL && ! c->isAssignableFrom(obj->getClass()))
248 JvThrow (new java::lang::ClassCastException);
253 _Jv_CheckArrayStore (jobject arr, jobject obj)
257 JvAssert (arr != NULL);
258 jclass arr_class = arr->getClass();
259 JvAssert (arr_class->isArray());
260 jclass elt_class = arr_class->getComponentType();
261 jclass obj_class = obj->getClass();
262 if (! elt_class->isAssignableFrom(obj_class))
263 JvThrow (new java::lang::ArrayStoreException);
269 // Allocate some unscanned memory and throw an exception if no memory.
271 _Jv_AllocBytesChecked (jsize size)
273 void *r = _Jv_AllocBytes (size);
275 _Jv_Throw (no_memory);
279 // Allocate a new object of class C. SIZE is the size of the object
280 // to allocate. You might think this is redundant, but it isn't; some
281 // classes, such as String, aren't of fixed size.
283 _Jv_AllocObject (jclass c, jint size)
287 jobject obj = (jobject) _Jv_AllocObj (size);
290 *((_Jv_VTable **) obj) = c->vtable;
292 // If this class has inherited finalize from Object, then don't
293 // bother registering a finalizer. We know that finalize() is the
294 // very first method after the dummy entry. If this turns out to be
295 // unreliable, a more robust implementation can be written. Such an
296 // implementation would look for Object.finalize in Object's method
297 // table at startup, and then use that information to find the
298 // appropriate index in the method vector.
299 if (c->vtable->method[1] != ObjectClass.vtable->method[1])
300 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
305 // Allocate a new array of Java objects. Each object is of type
306 // `elementClass'. `init' is used to initialize each slot in the
309 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
312 JvThrow (new java::lang::NegativeArraySizeException);
314 // Check for overflow.
315 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / sizeof (jobject))
318 size_t size = count * sizeof (jobject) + sizeof (__JArray);
320 // FIXME: second argument should be "current loader" //
321 jclass clas = _Jv_FindArrayClass (elementClass, 0);
323 jobjectArray obj = (jobjectArray) _Jv_AllocArray (size);
327 jobject* ptr = elements(obj);
328 // We know the allocator returns zeroed memory. So don't bother
335 // Set the vtbl last to avoid problems if the GC happens during the
336 // window in this function between the allocation and this
338 *((_Jv_VTable **) obj) = clas->vtable;
342 // Allocate a new array of primitives. ELTYPE is the type of the
343 // element, COUNT is the size of the array.
345 _Jv_NewPrimArray (jclass eltype, jint count)
347 int elsize = eltype->size();
349 JvThrow (new java::lang::NegativeArraySizeException ());
351 // Check for overflow.
352 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / elsize)
355 __JArray *arr = (__JArray*) _Jv_AllocObj (sizeof (__JArray)
360 // Note that we assume we are given zeroed memory by the allocator.
362 jclass klass = _Jv_FindArrayClass (eltype, 0);
363 // Set the vtbl last to avoid problems if the GC happens during the
364 // window in this function between the allocation and this
366 *((_Jv_VTable **) arr) = klass->vtable;
371 JvNewCharArray (jint length)
373 return (jcharArray) _Jv_NewPrimArray (JvPrimClass (char), length);
377 JvNewBooleanArray (jint length)
379 return (jbooleanArray) _Jv_NewPrimArray (JvPrimClass (boolean), length);
383 JvNewByteArray (jint length)
385 return (jbyteArray) _Jv_NewPrimArray (JvPrimClass (byte), length);
389 JvNewShortArray (jint length)
391 return (jshortArray) _Jv_NewPrimArray (JvPrimClass (short), length);
395 JvNewIntArray (jint length)
397 return (jintArray) _Jv_NewPrimArray (JvPrimClass (int), length);
401 JvNewLongArray (jint length)
403 return (jlongArray) _Jv_NewPrimArray (JvPrimClass (long), length);
407 JvNewFloatArray (jint length)
409 return (jfloatArray) _Jv_NewPrimArray (JvPrimClass (float), length);
413 JvNewDoubleArray (jint length)
415 return (jdoubleArray) _Jv_NewPrimArray (JvPrimClass (double), length);
419 _Jv_NewArray (jint type, jint size)
423 case 4: return JvNewBooleanArray (size);
424 case 5: return JvNewCharArray (size);
425 case 6: return JvNewFloatArray (size);
426 case 7: return JvNewDoubleArray (size);
427 case 8: return JvNewByteArray (size);
428 case 9: return JvNewShortArray (size);
429 case 10: return JvNewIntArray (size);
430 case 11: return JvNewLongArray (size);
432 JvFail ("newarray - bad type code");
433 return NULL; // Placate compiler.
437 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
439 JvAssert (type->isArray());
440 jclass element_type = type->getComponentType();
442 if (element_type->isPrimitive())
443 result = _Jv_NewPrimArray (element_type, sizes[0]);
445 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
449 JvAssert (! element_type->isPrimitive());
450 JvAssert (element_type->isArray());
451 jobject *contents = elements ((jobjectArray) result);
452 for (int i = 0; i < sizes[0]; ++i)
453 contents[i] = _Jv_NewMultiArray (element_type, dimensions - 1,
461 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
464 jint sizes[dimensions];
465 va_start (args, dimensions);
466 for (int i = 0; i < dimensions; ++i)
468 jint size = va_arg (args, jint);
473 return _Jv_NewMultiArray (array_type, dimensions, sizes);
478 class _Jv_PrimClass : public java::lang::Class
481 // FIXME: calling convention is weird. If we use the natural types
482 // then the compiler will complain because they aren't Java types.
483 _Jv_PrimClass (jobject cname, jbyte sig, jint len)
485 using namespace java::lang::reflect;
487 // We must initialize every field of the class. We do this in
488 // the same order they are declared in Class.h.
490 name = _Jv_makeUtf8Const ((char *) cname, -1);
491 accflags = Modifier::PUBLIC | Modifier::FINAL;
494 constants.tags = NULL;
495 constants.data = NULL;
498 vtable_method_count = 0;
502 static_field_count = 0;
503 vtable = JV_PRIMITIVE_VTABLE;
512 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
513 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
515 DECLARE_PRIM_TYPE(byte, 'B', 1);
516 DECLARE_PRIM_TYPE(short, 'S', 2);
517 DECLARE_PRIM_TYPE(int, 'I', 4);
518 DECLARE_PRIM_TYPE(long, 'J', 8);
519 DECLARE_PRIM_TYPE(boolean, 'Z', 1);
520 DECLARE_PRIM_TYPE(char, 'C', 2);
521 DECLARE_PRIM_TYPE(float, 'F', 4);
522 DECLARE_PRIM_TYPE(double, 'D', 8);
523 DECLARE_PRIM_TYPE(void, 'V', 0);
526 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
531 return JvPrimClass (byte);
533 return JvPrimClass (short);
535 return JvPrimClass (int);
537 return JvPrimClass (long);
539 return JvPrimClass (boolean);
541 return JvPrimClass (char);
543 return JvPrimClass (float);
545 return JvPrimClass (double);
547 return JvPrimClass (void);
551 for (i = 1; sig[i] && sig[i] != ';'; ++i)
553 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
554 return _Jv_FindClass (name, loader);
558 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig[1], loader),
561 JvFail ("couldn't understand class signature");
562 return NULL; // Placate compiler.
568 JvConvertArgv (int argc, const char **argv)
572 jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
573 jobject* ptr = elements(ar);
574 for (int i = 0; i < argc; i++)
576 const char *arg = argv[i];
577 // FIXME - should probably use JvNewStringUTF.
578 *ptr++ = JvNewStringLatin1(arg, strlen(arg));
580 return (JArray<jstring>*) ar;
583 // FIXME: These variables are static so that they will be
584 // automatically scanned by the Boehm collector. This is needed
585 // because with qthreads the collector won't scan the initial stack --
586 // it will only scan the qthreads stacks.
588 // Command line arguments.
589 static jobject arg_vec;
591 // The primary threadgroup.
592 static java::lang::ThreadGroup *main_group;
594 // The primary thread.
595 static java::lang::Thread *main_thread;
598 JvRunMain (jclass klass, int argc, const char **argv)
604 arithexception = new java::lang::ArithmeticException
605 (JvNewStringLatin1 ("/ by zero"));
608 no_memory = new java::lang::OutOfMemoryError;
611 LTDL_SET_PRELOADED_SYMBOLS ();
614 arg_vec = JvConvertArgv (argc - 1, argv + 1);
615 main_group = new java::lang::ThreadGroup (23);
616 main_thread = new java::lang::FirstThread (main_group, klass, arg_vec);
618 main_thread->start();
621 java::lang::Runtime::getRuntime ()->exit (0);
625 _Jv_RunMain (const char *class_name, int argc, const char **argv)
631 arithexception = new java::lang::ArithmeticException
632 (JvNewStringLatin1 ("/ by zero"));
635 no_memory = new java::lang::OutOfMemoryError;
638 LTDL_SET_PRELOADED_SYMBOLS ();
641 arg_vec = JvConvertArgv (argc - 1, argv + 1);
642 main_group = new java::lang::ThreadGroup (23);
643 main_thread = new java::lang::FirstThread (main_group,
644 JvNewStringLatin1 (class_name),
646 main_thread->start();
649 java::lang::Runtime::getRuntime ()->exit (0);
656 _Jv_Malloc (jsize size)
660 void *ptr = malloc ((size_t) size);
674 // In theory, these routines can be #ifdef'd away on machines which
675 // support divide overflow signals. However, we never know if some
676 // code might have been compiled with "-fuse-divide-subroutine", so we
677 // always include them in libgcj.
680 _Jv_divI (jint dividend, jint divisor)
683 _Jv_Throw (arithexception);
685 if (dividend == (jint) 0x80000000L && divisor == -1)
688 return dividend / divisor;
692 _Jv_remI (jint dividend, jint divisor)
695 _Jv_Throw (arithexception);
697 if (dividend == (jint) 0x80000000L && divisor == -1)
700 return dividend % divisor;
704 _Jv_divJ (jlong dividend, jlong divisor)
707 _Jv_Throw (arithexception);
709 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
712 return dividend / divisor;
716 _Jv_remJ (jlong dividend, jlong divisor)
719 _Jv_Throw (arithexception);
721 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
724 return dividend % divisor;