OSDN Git Service

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