prims.cc (JvRunMain): Always initialize arithexception.
[gcc.git] / libjava / prims.cc
1 // prims.cc - Code for core of runtime environment.
2
3 /* Copyright (C) 1998, 1999 Cygnus Solutions
4
5 This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
10
11 #include <config.h>
12
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <stdio.h>
16 #include <string.h>
17
18 #pragma implementation "java-array.h"
19
20 #include <cni.h>
21 #include <jvm.h>
22 #include <java-signal.h>
23
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>
41
42 #ifdef USE_LTDL
43 #include <ltdl.h>
44 #endif
45
46 #define ObjectClass _CL_Q34java4lang6Object
47 extern java::lang::Class ObjectClass;
48
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;
52
53 // Largest representable size_t.
54 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
55
56 \f
57
58 #ifdef HANDLE_SEGV
59 static java::lang::NullPointerException *nullp;
60 SIGNAL_HANDLER (catch_segv)
61 {
62 MAKE_THROW_FRAME;
63 _Jv_Throw (nullp);
64 }
65 #endif
66
67 static java::lang::ArithmeticException *arithexception;
68
69 #ifdef HANDLE_FPE
70 SIGNAL_HANDLER (catch_fpe)
71 {
72 #ifdef HANDLE_DIVIDE_OVERFLOW
73 HANDLE_DIVIDE_OVERFLOW;
74 #else
75 MAKE_THROW_FRAME;
76 #endif
77 _Jv_Throw (arithexception);
78 }
79 #endif
80
81 \f
82
83 jboolean
84 _Jv_equalUtf8Consts (Utf8Const* a, Utf8Const *b)
85 {
86 register int len;
87 register _Jv_ushort *aptr, *bptr;
88 if (a == b)
89 return true;
90 if (a->hash != b->hash)
91 return false;
92 len = a->length;
93 if (b->length != len)
94 return false;
95 aptr = (_Jv_ushort *)a->data;
96 bptr = (_Jv_ushort *)b->data;
97 len = (len + 1) >> 1;
98 while (--len >= 0)
99 if (*aptr++ != *bptr++)
100 return false;
101 return true;
102 }
103
104 /* True iff A is equal to STR.
105 HASH is STR->hashCode().
106 */
107
108 jboolean
109 _Jv_equal (Utf8Const* a, jstring str, jint hash)
110 {
111 if (a->hash != (_Jv_ushort) hash)
112 return false;
113 jint len = str->length();
114 jint i = 0;
115 jchar *sptr = _Jv_GetStringChars (str);
116 register unsigned char* ptr = (unsigned char*) a->data;
117 register unsigned char* limit = ptr + a->length;
118 for (;; i++, sptr++)
119 {
120 int ch = UTF8_GET (ptr, limit);
121 if (i == len)
122 return ch < 0;
123 if (ch != *sptr)
124 return false;
125 }
126 return true;
127 }
128
129 /* Count the number of Unicode chars encoded in a given Ut8 string. */
130 int
131 _Jv_strLengthUtf8(char* str, int len)
132 {
133 register unsigned char* ptr;
134 register unsigned char* limit;
135 int str_length;
136
137 ptr = (unsigned char*) str;
138 limit = ptr + len;
139 str_length = 0;
140 for (; ptr < limit; str_length++) {
141 if (UTF8_GET (ptr, limit) < 0) {
142 return (-1);
143 }
144 }
145 return (str_length);
146 }
147
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.
150 */
151 static jint
152 hashUtf8String (char* str, int len)
153 {
154 register unsigned char* ptr = (unsigned char*) str;
155 register unsigned char* limit = ptr + len;
156 jint hash = 0;
157
158 for (; ptr < limit;)
159 {
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;
164 }
165 return hash;
166 }
167
168 _Jv_Utf8Const *
169 _Jv_makeUtf8Const (char* s, int len)
170 {
171 if (len < 0)
172 len = strlen (s);
173 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
174 if (! m)
175 JvThrow (no_memory);
176 memcpy (m->data, s, len);
177 m->data[len] = 0;
178 m->length = len;
179 m->hash = hashUtf8String (s, len) & 0xFFFF;
180 return (m);
181 }
182
183 \f
184
185 #ifdef DEBUG
186 void
187 _Jv_Abort (const char *function, const char *file, int line,
188 const char *message)
189 #else
190 void
191 _Jv_Abort (const char *, const char *, int, const char *message)
192 #endif
193 {
194 #ifdef DEBUG
195 fprintf (stderr,
196 "libgcj failure: %s\n in function %s, file %s, line %d\n",
197 message, function, file, line);
198 #else
199 java::io::PrintStream *err = java::lang::System::err;
200 err->print(JvNewStringLatin1 ("libgcj failure: "));
201 err->println(JvNewStringLatin1 (message));
202 err->flush();
203 #endif
204 abort ();
205 }
206
207 static void
208 fail_on_finalization (jobject)
209 {
210 JvFail ("object was finalized");
211 }
212
213 void
214 _Jv_GCWatch (jobject obj)
215 {
216 _Jv_RegisterFinalizer (obj, fail_on_finalization);
217 }
218
219 void
220 _Jv_ThrowBadArrayIndex(jint bad_index)
221 {
222 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
223 (java::lang::String::valueOf(bad_index)));
224 }
225
226 void*
227 _Jv_CheckCast (jclass c, jobject obj)
228 {
229 if (obj != NULL && ! c->isAssignableFrom(obj->getClass()))
230 JvThrow (new java::lang::ClassCastException);
231 return obj;
232 }
233
234 void
235 _Jv_CheckArrayStore (jobject arr, jobject obj)
236 {
237 if (obj)
238 {
239 JvAssert (arr != NULL);
240 jclass arr_class = arr->getClass();
241 JvAssert (arr_class->isArray());
242 jclass elt_class = arr_class->getComponentType();
243 jclass obj_class = obj->getClass();
244 if (! elt_class->isAssignableFrom(obj_class))
245 JvThrow (new java::lang::ArrayStoreException);
246 }
247 }
248
249 \f
250
251 // Allocate some unscanned memory and throw an exception if no memory.
252 void *
253 _Jv_AllocBytesChecked (jsize size)
254 {
255 void *r = _Jv_AllocBytes (size);
256 if (! r)
257 _Jv_Throw (no_memory);
258 return r;
259 }
260
261 // Allocate a new object of class C. SIZE is the size of the object
262 // to allocate. You might think this is redundant, but it isn't; some
263 // classes, such as String, aren't of fixed size.
264 jobject
265 _Jv_AllocObject (jclass c, jint size)
266 {
267 _Jv_InitClass (c);
268
269 jobject obj = (jobject) _Jv_AllocObj (size);
270 if (! obj)
271 JvThrow (no_memory);
272 *((_Jv_VTable **) obj) = c->vtable;
273
274 // If this class has inherited finalize from Object, then don't
275 // bother registering a finalizer. We know that finalize() is the
276 // very first method after the dummy entry. If this turns out to be
277 // unreliable, a more robust implementation can be written. Such an
278 // implementation would look for Object.finalize in Object's method
279 // table at startup, and then use that information to find the
280 // appropriate index in the method vector.
281 if (c->vtable->method[1] != ObjectClass.vtable->method[1])
282 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
283
284 return obj;
285 }
286
287 // Allocate a new array of Java objects. Each object is of type
288 // `elementClass'. `init' is used to initialize each slot in the
289 // array.
290 jobjectArray
291 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
292 {
293 if (count < 0)
294 JvThrow (new java::lang::NegativeArraySizeException);
295
296 // Check for overflow.
297 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / sizeof (jobject))
298 JvThrow (no_memory);
299
300 size_t size = count * sizeof (jobject) + sizeof (__JArray);
301 jclass clas = _Jv_FindArrayClass (elementClass);
302 jobjectArray obj = (jobjectArray) _Jv_AllocArray (size);
303 if (! obj)
304 JvThrow (no_memory);
305 obj->length = count;
306 jobject* ptr = elements(obj);
307 // We know the allocator returns zeroed memory. So don't bother
308 // zeroing it again.
309 if (init)
310 {
311 while (--count >= 0)
312 *ptr++ = init;
313 }
314 // Set the vtbl last to avoid problems if the GC happens during the
315 // window in this function between the allocation and this
316 // assignment.
317 *((_Jv_VTable **) obj) = clas->vtable;
318 return obj;
319 }
320
321 // Allocate a new array of primitives. ELTYPE is the type of the
322 // element, COUNT is the size of the array.
323 jobject
324 _Jv_NewPrimArray (jclass eltype, jint count)
325 {
326 int elsize = eltype->size();
327 if (count < 0)
328 JvThrow (new java::lang::NegativeArraySizeException ());
329
330 // Check for overflow.
331 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / elsize)
332 JvThrow (no_memory);
333
334 __JArray *arr = (__JArray*) _Jv_AllocObj (sizeof (__JArray)
335 + elsize * count);
336 if (! arr)
337 JvThrow (no_memory);
338 arr->length = count;
339 // Note that we assume we are given zeroed memory by the allocator.
340
341 jclass klass = _Jv_FindArrayClass (eltype);
342 // Set the vtbl last to avoid problems if the GC happens during the
343 // window in this function between the allocation and this
344 // assignment.
345 *((_Jv_VTable **) arr) = klass->vtable;
346 return arr;
347 }
348
349 jcharArray
350 JvNewCharArray (jint length)
351 {
352 return (jcharArray) _Jv_NewPrimArray (JvPrimClass (char), length);
353 }
354
355 jbooleanArray
356 JvNewBooleanArray (jint length)
357 {
358 return (jbooleanArray) _Jv_NewPrimArray (JvPrimClass (boolean), length);
359 }
360
361 jbyteArray
362 JvNewByteArray (jint length)
363 {
364 return (jbyteArray) _Jv_NewPrimArray (JvPrimClass (byte), length);
365 }
366
367 jshortArray
368 JvNewShortArray (jint length)
369 {
370 return (jshortArray) _Jv_NewPrimArray (JvPrimClass (short), length);
371 }
372
373 jintArray
374 JvNewIntArray (jint length)
375 {
376 return (jintArray) _Jv_NewPrimArray (JvPrimClass (int), length);
377 }
378
379 jlongArray
380 JvNewLongArray (jint length)
381 {
382 return (jlongArray) _Jv_NewPrimArray (JvPrimClass (long), length);
383 }
384
385 jfloatArray
386 JvNewFloatArray (jint length)
387 {
388 return (jfloatArray) _Jv_NewPrimArray (JvPrimClass (float), length);
389 }
390
391 jdoubleArray
392 JvNewDoubleArray (jint length)
393 {
394 return (jdoubleArray) _Jv_NewPrimArray (JvPrimClass (double), length);
395 }
396
397 jobject
398 _Jv_NewArray (jint type, jint size)
399 {
400 switch (type)
401 {
402 case 4: return JvNewBooleanArray (size);
403 case 5: return JvNewCharArray (size);
404 case 6: return JvNewFloatArray (size);
405 case 7: return JvNewDoubleArray (size);
406 case 8: return JvNewByteArray (size);
407 case 9: return JvNewShortArray (size);
408 case 10: return JvNewIntArray (size);
409 case 11: return JvNewLongArray (size);
410 }
411 JvFail ("newarray - bad type code");
412 return NULL; // Placate compiler.
413 }
414
415 jobject
416 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
417 {
418 JvAssert (type->isArray());
419 jclass element_type = type->getComponentType();
420 jobject result;
421 if (element_type->isPrimitive())
422 result = _Jv_NewPrimArray (element_type, sizes[0]);
423 else
424 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
425
426 if (dimensions > 1)
427 {
428 JvAssert (! element_type->isPrimitive());
429 JvAssert (element_type->isArray());
430 jobject *contents = elements ((jobjectArray) result);
431 for (int i = 0; i < sizes[0]; ++i)
432 contents[i] = _Jv_NewMultiArray (element_type, dimensions - 1,
433 sizes + 1);
434 }
435
436 return result;
437 }
438
439 jobject
440 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
441 {
442 va_list args;
443 jint sizes[dimensions];
444 va_start (args, dimensions);
445 for (int i = 0; i < dimensions; ++i)
446 {
447 jint size = va_arg (args, jint);
448 sizes[i] = size;
449 }
450 va_end (args);
451
452 return _Jv_NewMultiArray (array_type, dimensions, sizes);
453 }
454
455 \f
456
457 class _Jv_PrimClass : public java::lang::Class
458 {
459 public:
460 // FIXME: calling convention is weird. If we use the natural types
461 // then the compiler will complain because they aren't Java types.
462 _Jv_PrimClass (jobject cname, jbyte sig, jint len)
463 {
464 using namespace java::lang::reflect;
465
466 // We must initialize every field of the class. We do this in
467 // the same order they are declared in Class.h.
468 next = NULL;
469 name = _Jv_makeUtf8Const ((char *) cname, -1);
470 accflags = Modifier::PUBLIC | Modifier::FINAL;
471 superclass = NULL;
472 constants.size = 0;
473 constants.tags = NULL;
474 constants.data = NULL;
475 methods = NULL;
476 method_count = sig;
477 vtable_method_count = 0;
478 fields = NULL;
479 size_in_bytes = len;
480 field_count = 0;
481 static_field_count = 0;
482 vtable = JV_PRIMITIVE_VTABLE;
483 interfaces = NULL;
484 loader = NULL;
485 interface_count = 0;
486 state = 0; // FIXME.
487 thread = NULL;
488 }
489 };
490
491 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
492 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
493
494 DECLARE_PRIM_TYPE(byte, 'B', 1);
495 DECLARE_PRIM_TYPE(short, 'S', 2);
496 DECLARE_PRIM_TYPE(int, 'I', 4);
497 DECLARE_PRIM_TYPE(long, 'J', 8);
498 DECLARE_PRIM_TYPE(boolean, 'Z', 1);
499 DECLARE_PRIM_TYPE(char, 'C', 2);
500 DECLARE_PRIM_TYPE(float, 'F', 4);
501 DECLARE_PRIM_TYPE(double, 'D', 8);
502 DECLARE_PRIM_TYPE(void, 'V', 0);
503
504 jclass
505 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
506 {
507 switch (*sig)
508 {
509 case 'B':
510 return JvPrimClass (byte);
511 case 'S':
512 return JvPrimClass (short);
513 case 'I':
514 return JvPrimClass (int);
515 case 'J':
516 return JvPrimClass (long);
517 case 'Z':
518 return JvPrimClass (boolean);
519 case 'C':
520 return JvPrimClass (char);
521 case 'F':
522 return JvPrimClass (float);
523 case 'D':
524 return JvPrimClass (double);
525 case 'V':
526 return JvPrimClass (void);
527 case 'L':
528 {
529 int i;
530 for (i = 1; sig[i] && sig[i] != ';'; ++i)
531 ;
532 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
533 return _Jv_FindClass (name, loader);
534 }
535 case '[':
536 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig[1], loader));
537 }
538 JvFail ("couldn't understand class signature");
539 return NULL; // Placate compiler.
540 }
541
542 \f
543
544 JArray<jstring> *
545 JvConvertArgv (int argc, const char **argv)
546 {
547 if (argc < 0)
548 argc = 0;
549 jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
550 jobject* ptr = elements(ar);
551 for (int i = 0; i < argc; i++)
552 {
553 const char *arg = argv[i];
554 // FIXME - should probably use JvNewStringUTF.
555 *ptr++ = JvNewStringLatin1(arg, strlen(arg));
556 }
557 return (JArray<jstring>*) ar;
558 }
559
560 // FIXME: These variables are static so that they will be
561 // automatically scanned by the Boehm collector. This is needed
562 // because with qthreads the collector won't scan the initial stack --
563 // it will only scan the qthreads stacks.
564
565 // Command line arguments.
566 static jobject arg_vec;
567
568 // The primary threadgroup.
569 static java::lang::ThreadGroup *main_group;
570
571 // The primary thread.
572 static java::lang::Thread *main_thread;
573
574 void
575 JvRunMain (jclass klass, int argc, const char **argv)
576 {
577 INIT_SEGV;
578 #ifdef HANDLE_FPE
579 INIT_FPE;
580 #else
581 arithexception = new java::lang::ArithmeticException
582 (JvNewStringLatin1 ("/ by zero"));
583 #endif
584
585 no_memory = new java::lang::OutOfMemoryError;
586
587 #ifdef USE_LTDL
588 LTDL_SET_PRELOADED_SYMBOLS ();
589 #endif
590
591 arg_vec = JvConvertArgv (argc - 1, argv + 1);
592 main_group = new java::lang::ThreadGroup (23);
593 main_thread = new java::lang::FirstThread (main_group, klass, arg_vec);
594
595 main_thread->start();
596 _Jv_ThreadWait ();
597
598 java::lang::Runtime::getRuntime ()->exit (0);
599 }
600
601 \f
602
603 void *
604 _Jv_Malloc (jsize size)
605 {
606 if (size == 0)
607 size = 1;
608 void *ptr = malloc ((size_t) size);
609 if (ptr == NULL)
610 JvThrow (no_memory);
611 return ptr;
612 }
613
614 void
615 _Jv_Free (void* ptr)
616 {
617 return free (ptr);
618 }
619
620 \f
621
622 // In theory, these routines can be #ifdef'd away on machines which
623 // support divide overflow signals. However, we never know if some
624 // code might have been compiled with "-fuse-divide-subroutine", so we
625 // always include them in libgcj.
626
627 jint
628 _Jv_divI (jint dividend, jint divisor)
629 {
630 if (divisor == 0)
631 _Jv_Throw (arithexception);
632
633 if (dividend == 0x80000000L && divisor == -1)
634 return dividend;
635
636 return dividend / divisor;
637 }
638
639 jint
640 _Jv_remI (jint dividend, jint divisor)
641 {
642 if (divisor == 0)
643 _Jv_Throw (arithexception);
644
645 if (dividend == 0x80000000L && divisor == -1)
646 return 0;
647
648 return dividend % divisor;
649 }
650
651 jlong
652 _Jv_divJ (jlong dividend, jlong divisor)
653 {
654 if (divisor == 0)
655 _Jv_Throw (arithexception);
656
657 if (dividend == 0x8000000000000000LL && divisor == -1)
658 return dividend;
659
660 return dividend / divisor;
661 }
662
663 jlong
664 _Jv_remJ (jlong dividend, jlong divisor)
665 {
666 if (divisor == 0)
667 _Jv_Throw (arithexception);
668
669 if (dividend == 0x8000000000000000LL && divisor == -1)
670 return 0;
671
672 return dividend % divisor;
673 }
674