natClassLoader.cc (_Jv_PrepareCompiledClass): Renamed from _Jv_InternClassStrings.
[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 _Jv_Utf8Const *
184 _Jv_makeUtf8Const (jstring string)
185 {
186 jint hash = string->hashCode ();
187 jint len = _Jv_GetStringUTFLength (string);
188
189 Utf8Const* m = (Utf8Const*)
190 _Jv_AllocBytesChecked (sizeof(Utf8Const) + len + 1);
191
192 m->hash = hash;
193 m->length = len;
194
195 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
196 m->data[len] = 0;
197
198 return m;
199 }
200
201 \f
202
203 #ifdef DEBUG
204 void
205 _Jv_Abort (const char *function, const char *file, int line,
206 const char *message)
207 #else
208 void
209 _Jv_Abort (const char *, const char *, int, const char *message)
210 #endif
211 {
212 #ifdef DEBUG
213 fprintf (stderr,
214 "libgcj failure: %s\n in function %s, file %s, line %d\n",
215 message, function, file, line);
216 #else
217 java::io::PrintStream *err = java::lang::System::err;
218 err->print(JvNewStringLatin1 ("libgcj failure: "));
219 err->println(JvNewStringLatin1 (message));
220 err->flush();
221 #endif
222 abort ();
223 }
224
225 static void
226 fail_on_finalization (jobject)
227 {
228 JvFail ("object was finalized");
229 }
230
231 void
232 _Jv_GCWatch (jobject obj)
233 {
234 _Jv_RegisterFinalizer (obj, fail_on_finalization);
235 }
236
237 void
238 _Jv_ThrowBadArrayIndex(jint bad_index)
239 {
240 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
241 (java::lang::String::valueOf(bad_index)));
242 }
243
244 void*
245 _Jv_CheckCast (jclass c, jobject obj)
246 {
247 if (obj != NULL && ! c->isAssignableFrom(obj->getClass()))
248 JvThrow (new java::lang::ClassCastException);
249 return obj;
250 }
251
252 void
253 _Jv_CheckArrayStore (jobject arr, jobject obj)
254 {
255 if (obj)
256 {
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);
264 }
265 }
266
267 \f
268
269 // Allocate some unscanned memory and throw an exception if no memory.
270 void *
271 _Jv_AllocBytesChecked (jsize size)
272 {
273 void *r = _Jv_AllocBytes (size);
274 if (! r)
275 _Jv_Throw (no_memory);
276 return r;
277 }
278
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.
282 jobject
283 _Jv_AllocObject (jclass c, jint size)
284 {
285 _Jv_InitClass (c);
286
287 jobject obj = (jobject) _Jv_AllocObj (size);
288 if (! obj)
289 JvThrow (no_memory);
290 *((_Jv_VTable **) obj) = c->vtable;
291
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);
301
302 return obj;
303 }
304
305 // Allocate a new array of Java objects. Each object is of type
306 // `elementClass'. `init' is used to initialize each slot in the
307 // array.
308 jobjectArray
309 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
310 {
311 if (count < 0)
312 JvThrow (new java::lang::NegativeArraySizeException);
313
314 // Check for overflow.
315 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / sizeof (jobject))
316 JvThrow (no_memory);
317
318 size_t size = count * sizeof (jobject) + sizeof (__JArray);
319
320 // FIXME: second argument should be "current loader" //
321 jclass clas = _Jv_FindArrayClass (elementClass, 0);
322
323 jobjectArray obj = (jobjectArray) _Jv_AllocArray (size);
324 if (! obj)
325 JvThrow (no_memory);
326 obj->length = count;
327 jobject* ptr = elements(obj);
328 // We know the allocator returns zeroed memory. So don't bother
329 // zeroing it again.
330 if (init)
331 {
332 while (--count >= 0)
333 *ptr++ = init;
334 }
335 // Set the vtbl last to avoid problems if the GC happens during the
336 // window in this function between the allocation and this
337 // assignment.
338 *((_Jv_VTable **) obj) = clas->vtable;
339 return obj;
340 }
341
342 // Allocate a new array of primitives. ELTYPE is the type of the
343 // element, COUNT is the size of the array.
344 jobject
345 _Jv_NewPrimArray (jclass eltype, jint count)
346 {
347 int elsize = eltype->size();
348 if (count < 0)
349 JvThrow (new java::lang::NegativeArraySizeException ());
350
351 // Check for overflow.
352 if ((size_t) count > (SIZE_T_MAX - sizeof (__JArray)) / elsize)
353 JvThrow (no_memory);
354
355 __JArray *arr = (__JArray*) _Jv_AllocObj (sizeof (__JArray)
356 + elsize * count);
357 if (! arr)
358 JvThrow (no_memory);
359 arr->length = count;
360 // Note that we assume we are given zeroed memory by the allocator.
361
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
365 // assignment.
366 *((_Jv_VTable **) arr) = klass->vtable;
367 return arr;
368 }
369
370 jcharArray
371 JvNewCharArray (jint length)
372 {
373 return (jcharArray) _Jv_NewPrimArray (JvPrimClass (char), length);
374 }
375
376 jbooleanArray
377 JvNewBooleanArray (jint length)
378 {
379 return (jbooleanArray) _Jv_NewPrimArray (JvPrimClass (boolean), length);
380 }
381
382 jbyteArray
383 JvNewByteArray (jint length)
384 {
385 return (jbyteArray) _Jv_NewPrimArray (JvPrimClass (byte), length);
386 }
387
388 jshortArray
389 JvNewShortArray (jint length)
390 {
391 return (jshortArray) _Jv_NewPrimArray (JvPrimClass (short), length);
392 }
393
394 jintArray
395 JvNewIntArray (jint length)
396 {
397 return (jintArray) _Jv_NewPrimArray (JvPrimClass (int), length);
398 }
399
400 jlongArray
401 JvNewLongArray (jint length)
402 {
403 return (jlongArray) _Jv_NewPrimArray (JvPrimClass (long), length);
404 }
405
406 jfloatArray
407 JvNewFloatArray (jint length)
408 {
409 return (jfloatArray) _Jv_NewPrimArray (JvPrimClass (float), length);
410 }
411
412 jdoubleArray
413 JvNewDoubleArray (jint length)
414 {
415 return (jdoubleArray) _Jv_NewPrimArray (JvPrimClass (double), length);
416 }
417
418 jobject
419 _Jv_NewArray (jint type, jint size)
420 {
421 switch (type)
422 {
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);
431 }
432 JvFail ("newarray - bad type code");
433 return NULL; // Placate compiler.
434 }
435
436 jobject
437 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
438 {
439 JvAssert (type->isArray());
440 jclass element_type = type->getComponentType();
441 jobject result;
442 if (element_type->isPrimitive())
443 result = _Jv_NewPrimArray (element_type, sizes[0]);
444 else
445 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
446
447 if (dimensions > 1)
448 {
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,
454 sizes + 1);
455 }
456
457 return result;
458 }
459
460 jobject
461 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
462 {
463 va_list args;
464 jint sizes[dimensions];
465 va_start (args, dimensions);
466 for (int i = 0; i < dimensions; ++i)
467 {
468 jint size = va_arg (args, jint);
469 sizes[i] = size;
470 }
471 va_end (args);
472
473 return _Jv_NewMultiArray (array_type, dimensions, sizes);
474 }
475
476 \f
477
478 class _Jv_PrimClass : public java::lang::Class
479 {
480 public:
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)
484 {
485 using namespace java::lang::reflect;
486
487 // We must initialize every field of the class. We do this in
488 // the same order they are declared in Class.h.
489 next = NULL;
490 name = _Jv_makeUtf8Const ((char *) cname, -1);
491 accflags = Modifier::PUBLIC | Modifier::FINAL;
492 superclass = NULL;
493 constants.size = 0;
494 constants.tags = NULL;
495 constants.data = NULL;
496 methods = NULL;
497 method_count = sig;
498 vtable_method_count = 0;
499 fields = NULL;
500 size_in_bytes = len;
501 field_count = 0;
502 static_field_count = 0;
503 vtable = JV_PRIMITIVE_VTABLE;
504 interfaces = NULL;
505 loader = NULL;
506 interface_count = 0;
507 state = 0; // FIXME.
508 thread = NULL;
509 }
510 };
511
512 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
513 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
514
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);
524
525 jclass
526 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
527 {
528 switch (*sig)
529 {
530 case 'B':
531 return JvPrimClass (byte);
532 case 'S':
533 return JvPrimClass (short);
534 case 'I':
535 return JvPrimClass (int);
536 case 'J':
537 return JvPrimClass (long);
538 case 'Z':
539 return JvPrimClass (boolean);
540 case 'C':
541 return JvPrimClass (char);
542 case 'F':
543 return JvPrimClass (float);
544 case 'D':
545 return JvPrimClass (double);
546 case 'V':
547 return JvPrimClass (void);
548 case 'L':
549 {
550 int i;
551 for (i = 1; sig[i] && sig[i] != ';'; ++i)
552 ;
553 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
554 return _Jv_FindClass (name, loader);
555
556 }
557 case '[':
558 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig[1], loader),
559 loader);
560 }
561 JvFail ("couldn't understand class signature");
562 return NULL; // Placate compiler.
563 }
564
565 \f
566
567 JArray<jstring> *
568 JvConvertArgv (int argc, const char **argv)
569 {
570 if (argc < 0)
571 argc = 0;
572 jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
573 jobject* ptr = elements(ar);
574 for (int i = 0; i < argc; i++)
575 {
576 const char *arg = argv[i];
577 // FIXME - should probably use JvNewStringUTF.
578 *ptr++ = JvNewStringLatin1(arg, strlen(arg));
579 }
580 return (JArray<jstring>*) ar;
581 }
582
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.
587
588 // Command line arguments.
589 static jobject arg_vec;
590
591 // The primary threadgroup.
592 static java::lang::ThreadGroup *main_group;
593
594 // The primary thread.
595 static java::lang::Thread *main_thread;
596
597 void
598 JvRunMain (jclass klass, int argc, const char **argv)
599 {
600 INIT_SEGV;
601 #ifdef HANDLE_FPE
602 INIT_FPE;
603 #else
604 arithexception = new java::lang::ArithmeticException
605 (JvNewStringLatin1 ("/ by zero"));
606 #endif
607
608 no_memory = new java::lang::OutOfMemoryError;
609
610 #ifdef USE_LTDL
611 LTDL_SET_PRELOADED_SYMBOLS ();
612 #endif
613
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);
617
618 main_thread->start();
619 _Jv_ThreadWait ();
620
621 java::lang::Runtime::getRuntime ()->exit (0);
622 }
623
624 void
625 _Jv_RunMain (const char *class_name, int argc, const char **argv)
626 {
627 INIT_SEGV;
628 #ifdef HANDLE_FPE
629 INIT_FPE;
630 #else
631 arithexception = new java::lang::ArithmeticException
632 (JvNewStringLatin1 ("/ by zero"));
633 #endif
634
635 no_memory = new java::lang::OutOfMemoryError;
636
637 #ifdef USE_LTDL
638 LTDL_SET_PRELOADED_SYMBOLS ();
639 #endif
640
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),
645 arg_vec);
646 main_thread->start();
647 _Jv_ThreadWait ();
648
649 java::lang::Runtime::getRuntime ()->exit (0);
650 }
651
652
653 \f
654
655 void *
656 _Jv_Malloc (jsize size)
657 {
658 if (size == 0)
659 size = 1;
660 void *ptr = malloc ((size_t) size);
661 if (ptr == NULL)
662 JvThrow (no_memory);
663 return ptr;
664 }
665
666 void
667 _Jv_Free (void* ptr)
668 {
669 return free (ptr);
670 }
671
672 \f
673
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.
678
679 jint
680 _Jv_divI (jint dividend, jint divisor)
681 {
682 if (divisor == 0)
683 _Jv_Throw (arithexception);
684
685 if (dividend == (jint) 0x80000000L && divisor == -1)
686 return dividend;
687
688 return dividend / divisor;
689 }
690
691 jint
692 _Jv_remI (jint dividend, jint divisor)
693 {
694 if (divisor == 0)
695 _Jv_Throw (arithexception);
696
697 if (dividend == (jint) 0x80000000L && divisor == -1)
698 return 0;
699
700 return dividend % divisor;
701 }
702
703 jlong
704 _Jv_divJ (jlong dividend, jlong divisor)
705 {
706 if (divisor == 0)
707 _Jv_Throw (arithexception);
708
709 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
710 return dividend;
711
712 return dividend / divisor;
713 }
714
715 jlong
716 _Jv_remJ (jlong dividend, jlong divisor)
717 {
718 if (divisor == 0)
719 _Jv_Throw (arithexception);
720
721 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
722 return 0;
723
724 return dividend % divisor;
725 }
726
727
728
729
730
731
732