OSDN Git Service

2003-09-09 Andreas Tobler <a.tobler@schweiz.ch>
[pf3gnuchains/gcc-fork.git] / libjava / prims.cc
1 // prims.cc - Code for core of runtime environment.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003  Free Software Foundation
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 #include <platform.h>
13
14 #include <stdlib.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <signal.h>
19
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include <gcj/cni.h>
25 #include <jvm.h>
26 #include <java-signal.h>
27 #include <java-threads.h>
28
29 #ifdef ENABLE_JVMPI
30 #include <jvmpi.h>
31 #include <java/lang/ThreadGroup.h>
32 #endif
33
34 #ifndef DISABLE_GETENV_PROPERTIES
35 #include <ctype.h>
36 #include <java-props.h>
37 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
38 #else
39 #define PROCESS_GCJ_PROPERTIES
40 #endif // DISABLE_GETENV_PROPERTIES
41
42 #include <java/lang/Class.h>
43 #include <java/lang/ClassLoader.h>
44 #include <java/lang/Runtime.h>
45 #include <java/lang/String.h>
46 #include <java/lang/Thread.h>
47 #include <java/lang/ThreadGroup.h>
48 #include <java/lang/ArrayIndexOutOfBoundsException.h>
49 #include <java/lang/ArithmeticException.h>
50 #include <java/lang/ClassFormatError.h>
51 #include <java/lang/InternalError.h>
52 #include <java/lang/NegativeArraySizeException.h>
53 #include <java/lang/NullPointerException.h>
54 #include <java/lang/OutOfMemoryError.h>
55 #include <java/lang/System.h>
56 #include <java/lang/VMThrowable.h>
57 #include <java/lang/reflect/Modifier.h>
58 #include <java/io/PrintStream.h>
59 #include <java/lang/UnsatisfiedLinkError.h>
60 #include <java/lang/VirtualMachineError.h>
61 #include <gnu/gcj/runtime/VMClassLoader.h>
62 #include <gnu/gcj/runtime/FinalizerThread.h>
63 #include <gnu/gcj/runtime/FirstThread.h>
64
65 #ifdef USE_LTDL
66 #include <ltdl.h>
67 #endif
68
69 // We allocate a single OutOfMemoryError exception which we keep
70 // around for use if we run out of memory.
71 static java::lang::OutOfMemoryError *no_memory;
72
73 // Largest representable size_t.
74 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
75
76 static const char *no_properties[] = { NULL };
77
78 // Properties set at compile time.
79 const char **_Jv_Compiler_Properties = no_properties;
80
81 // The JAR file to add to the beginning of java.class.path.
82 const char *_Jv_Jar_Class_Path;
83
84 #ifndef DISABLE_GETENV_PROPERTIES
85 // Property key/value pairs.
86 property_pair *_Jv_Environment_Properties;
87 #endif
88
89 // Stash the argv pointer to benefit native libraries that need it.
90 const char **_Jv_argv;
91 int _Jv_argc;
92
93 // Argument support.
94 int
95 _Jv_GetNbArgs (void)
96 {
97   // _Jv_argc is 0 if not explicitly initialized.
98   return _Jv_argc;
99 }
100
101 const char *
102 _Jv_GetSafeArg (int index)
103 {
104   if (index >=0 && index < _Jv_GetNbArgs ())
105     return _Jv_argv[index];
106   else
107     return "";
108 }
109
110 void
111 _Jv_SetArgs (int argc, const char **argv)
112 {
113   _Jv_argc = argc;
114   _Jv_argv = argv;
115 }
116
117 #ifdef ENABLE_JVMPI
118 // Pointer to JVMPI notification functions.
119 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
120 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
121 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
122 #endif
123 \f
124
125 /* Unblock a signal.  Unless we do this, the signal may only be sent
126    once.  */
127 static void 
128 unblock_signal (int signum)
129 {
130 #ifdef _POSIX_VERSION
131   sigset_t sigs;
132
133   sigemptyset (&sigs);
134   sigaddset (&sigs, signum);
135   sigprocmask (SIG_UNBLOCK, &sigs, NULL);
136 #endif
137 }
138
139 #ifdef HANDLE_SEGV
140 SIGNAL_HANDLER (catch_segv)
141 {
142   java::lang::NullPointerException *nullp 
143     = new java::lang::NullPointerException;
144   unblock_signal (SIGSEGV);
145   MAKE_THROW_FRAME (nullp);
146   throw nullp;
147 }
148 #endif
149
150 #ifdef HANDLE_FPE
151 SIGNAL_HANDLER (catch_fpe)
152 {
153   java::lang::ArithmeticException *arithexception 
154     = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));
155   unblock_signal (SIGFPE);
156 #ifdef HANDLE_DIVIDE_OVERFLOW
157   HANDLE_DIVIDE_OVERFLOW;
158 #else
159   MAKE_THROW_FRAME (arithexception);
160 #endif
161   throw arithexception;
162 }
163 #endif
164
165 \f
166
167 jboolean
168 _Jv_equalUtf8Consts (Utf8Const* a, Utf8Const *b)
169 {
170   int len;
171   _Jv_ushort *aptr, *bptr;
172   if (a == b)
173     return true;
174   if (a->hash != b->hash)
175     return false;
176   len = a->length;
177   if (b->length != len)
178     return false;
179   aptr = (_Jv_ushort *)a->data;
180   bptr = (_Jv_ushort *)b->data;
181   len = (len + 1) >> 1;
182   while (--len >= 0)
183     if (*aptr++ != *bptr++)
184       return false;
185   return true;
186 }
187
188 /* True iff A is equal to STR.
189    HASH is STR->hashCode().  
190 */
191
192 jboolean
193 _Jv_equal (Utf8Const* a, jstring str, jint hash)
194 {
195   if (a->hash != (_Jv_ushort) hash)
196     return false;
197   jint len = str->length();
198   jint i = 0;
199   jchar *sptr = _Jv_GetStringChars (str);
200   unsigned char* ptr = (unsigned char*) a->data;
201   unsigned char* limit = ptr + a->length;
202   for (;; i++, sptr++)
203     {
204       int ch = UTF8_GET (ptr, limit);
205       if (i == len)
206         return ch < 0;
207       if (ch != *sptr)
208         return false;
209     }
210   return true;
211 }
212
213 /* Like _Jv_equal, but stop after N characters.  */
214 jboolean
215 _Jv_equaln (Utf8Const *a, jstring str, jint n)
216 {
217   jint len = str->length();
218   jint i = 0;
219   jchar *sptr = _Jv_GetStringChars (str);
220   unsigned char* ptr = (unsigned char*) a->data;
221   unsigned char* limit = ptr + a->length;
222   for (; n-- > 0; i++, sptr++)
223     {
224       int ch = UTF8_GET (ptr, limit);
225       if (i == len)
226         return ch < 0;
227       if (ch != *sptr)
228         return false;
229     }
230   return true;
231 }
232
233 /* Count the number of Unicode chars encoded in a given Ut8 string. */
234 int
235 _Jv_strLengthUtf8(char* str, int len)
236 {
237   unsigned char* ptr;
238   unsigned char* limit;
239   int str_length;
240
241   ptr = (unsigned char*) str;
242   limit = ptr + len;
243   str_length = 0;
244   for (; ptr < limit; str_length++)
245     {
246       if (UTF8_GET (ptr, limit) < 0)
247         return (-1);
248     }
249   return (str_length);
250 }
251
252 /* Calculate a hash value for a string encoded in Utf8 format.
253  * This returns the same hash value as specified or java.lang.String.hashCode.
254  */
255 static jint
256 hashUtf8String (char* str, int len)
257 {
258   unsigned char* ptr = (unsigned char*) str;
259   unsigned char* limit = ptr + len;
260   jint hash = 0;
261
262   for (; ptr < limit;)
263     {
264       int ch = UTF8_GET (ptr, limit);
265       /* Updated specification from
266          http://www.javasoft.com/docs/books/jls/clarify.html. */
267       hash = (31 * hash) + ch;
268     }
269   return hash;
270 }
271
272 _Jv_Utf8Const *
273 _Jv_makeUtf8Const (char* s, int len)
274 {
275   if (len < 0)
276     len = strlen (s);
277   Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
278   memcpy (m->data, s, len);
279   m->data[len] = 0;
280   m->length = len;
281   m->hash = hashUtf8String (s, len) & 0xFFFF;
282   return (m);
283 }
284
285 _Jv_Utf8Const *
286 _Jv_makeUtf8Const (jstring string)
287 {
288   jint hash = string->hashCode ();
289   jint len = _Jv_GetStringUTFLength (string);
290
291   Utf8Const* m = (Utf8Const*)
292     _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
293
294   m->hash = hash;
295   m->length = len;
296
297   _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
298   m->data[len] = 0;
299   
300   return m;
301 }
302
303 \f
304
305 #ifdef DEBUG
306 void
307 _Jv_Abort (const char *function, const char *file, int line,
308            const char *message)
309 #else
310 void
311 _Jv_Abort (const char *, const char *, int, const char *message)
312 #endif
313 {
314 #ifdef DEBUG
315   fprintf (stderr,
316            "libgcj failure: %s\n   in function %s, file %s, line %d\n",
317            message, function, file, line);
318 #else
319   fprintf (stderr, "libgcj failure: %s\n", message);
320 #endif
321   abort ();
322 }
323
324 static void
325 fail_on_finalization (jobject)
326 {
327   JvFail ("object was finalized");
328 }
329
330 void
331 _Jv_GCWatch (jobject obj)
332 {
333   _Jv_RegisterFinalizer (obj, fail_on_finalization);
334 }
335
336 void
337 _Jv_ThrowBadArrayIndex(jint bad_index)
338 {
339   throw new java::lang::ArrayIndexOutOfBoundsException
340     (java::lang::String::valueOf (bad_index));
341 }
342
343 void
344 _Jv_ThrowNullPointerException ()
345 {
346   throw new java::lang::NullPointerException;
347 }
348
349 // Explicitly throw a no memory exception.
350 // The collector calls this when it encounters an out-of-memory condition.
351 void _Jv_ThrowNoMemory()
352 {
353   throw no_memory;
354 }
355
356 #ifdef ENABLE_JVMPI
357 static void
358 jvmpi_notify_alloc(jclass klass, jint size, jobject obj)
359 {
360   // Service JVMPI allocation request.
361   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
362     {
363       JVMPI_Event event;
364
365       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
366       event.env_id = NULL;
367       event.u.obj_alloc.arena_id = 0;
368       event.u.obj_alloc.class_id = (jobjectID) klass;
369       event.u.obj_alloc.is_array = 0;
370       event.u.obj_alloc.size = size;
371       event.u.obj_alloc.obj_id = (jobjectID) obj;
372
373       // FIXME:  This doesn't look right for the Boehm GC.  A GC may
374       // already be in progress.  _Jv_DisableGC () doesn't wait for it.
375       // More importantly, I don't see the need for disabling GC, since we
376       // blatantly have a pointer to obj on our stack, ensuring that the
377       // object can't be collected.  Even for a nonconservative collector,
378       // it appears to me that this must be true, since we are about to
379       // return obj. Isn't this whole approach way too intrusive for
380       // a useful profiling interface?                  - HB
381       _Jv_DisableGC ();
382       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
383       _Jv_EnableGC ();
384     }
385 }
386 #else /* !ENABLE_JVMPI */
387 # define jvmpi_notify_alloc(klass,size,obj) /* do nothing */
388 #endif
389
390 // Allocate a new object of class KLASS.  SIZE is the size of the object
391 // to allocate.  You might think this is redundant, but it isn't; some
392 // classes, such as String, aren't of fixed size.
393 // First a version that assumes that we have no finalizer, and that
394 // the class is already initialized.
395 // If we know that JVMPI is disabled, this can be replaced by a direct call
396 // to the allocator for the appropriate GC.
397 jobject
398 _Jv_AllocObjectNoInitNoFinalizer (jclass klass, jint size)
399 {
400   jobject obj = (jobject) _Jv_AllocObj (size, klass);
401   jvmpi_notify_alloc (klass, size, obj);
402   return obj;
403 }
404
405 // And now a version that initializes if necessary.
406 jobject
407 _Jv_AllocObjectNoFinalizer (jclass klass, jint size)
408 {
409   _Jv_InitClass (klass);
410   jobject obj = (jobject) _Jv_AllocObj (size, klass);
411   jvmpi_notify_alloc (klass, size, obj);
412   return obj;
413 }
414
415 // And now the general version that registers a finalizer if necessary.
416 jobject
417 _Jv_AllocObject (jclass klass, jint size)
418 {
419   jobject obj = _Jv_AllocObjectNoFinalizer (klass, size);
420
421   // We assume that the compiler only generates calls to this routine
422   // if there really is an interesting finalizer.
423   // Unfortunately, we still have to the dynamic test, since there may
424   // be cni calls to this routine.
425   // Note that on IA64 get_finalizer() returns the starting address of the
426   // function, not a function pointer.  Thus this still works.
427   if (klass->vtable->get_finalizer ()
428       != java::lang::Object::class$.vtable->get_finalizer ())
429     _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
430   return obj;
431 }
432
433 // A version of the above that assumes the object contains no pointers,
434 // and requires no finalization.  This can't happen if we need pointers
435 // to locks.
436 #ifdef JV_HASH_SYNCHRONIZATION
437 jobject
438 _Jv_AllocPtrFreeObject (jclass klass, jint size)
439 {
440   _Jv_InitClass (klass);
441
442   jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
443
444 #ifdef ENABLE_JVMPI
445   // Service JVMPI request.
446
447   if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
448     {
449       JVMPI_Event event;
450
451       event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
452       event.env_id = NULL;
453       event.u.obj_alloc.arena_id = 0;
454       event.u.obj_alloc.class_id = (jobjectID) klass;
455       event.u.obj_alloc.is_array = 0;
456       event.u.obj_alloc.size = size;
457       event.u.obj_alloc.obj_id = (jobjectID) obj;
458
459       _Jv_DisableGC ();
460       (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
461       _Jv_EnableGC ();
462     }
463 #endif
464
465   return obj;
466 }
467 #endif /* JV_HASH_SYNCHRONIZATION */
468
469
470 // Allocate a new array of Java objects.  Each object is of type
471 // `elementClass'.  `init' is used to initialize each slot in the
472 // array.
473 jobjectArray
474 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
475 {
476   if (__builtin_expect (count < 0, false))
477     throw new java::lang::NegativeArraySizeException;
478
479   JvAssert (! elementClass->isPrimitive ());
480
481   // Ensure that elements pointer is properly aligned.
482   jobjectArray obj = NULL;
483   size_t size = (size_t) elements (obj);
484   size += count * sizeof (jobject);
485
486   jclass klass = _Jv_GetArrayClass (elementClass,
487                                     elementClass->getClassLoaderInternal());
488
489   obj = (jobjectArray) _Jv_AllocArray (size, klass);
490   // Cast away const.
491   jsize *lp = const_cast<jsize *> (&obj->length);
492   *lp = count;
493   // We know the allocator returns zeroed memory.  So don't bother
494   // zeroing it again.
495   if (init)
496     {
497       jobject *ptr = elements(obj);
498       while (--count >= 0)
499         *ptr++ = init;
500     }
501   return obj;
502 }
503
504 // Allocate a new array of primitives.  ELTYPE is the type of the
505 // element, COUNT is the size of the array.
506 jobject
507 _Jv_NewPrimArray (jclass eltype, jint count)
508 {
509   int elsize = eltype->size();
510   if (__builtin_expect (count < 0, false))
511     throw new java::lang::NegativeArraySizeException;
512
513   JvAssert (eltype->isPrimitive ());
514   jobject dummy = NULL;
515   size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
516
517   // Check for overflow.
518   if (__builtin_expect ((size_t) count > 
519                         (SIZE_T_MAX - size) / elsize, false))
520     throw no_memory;
521
522   jclass klass = _Jv_GetArrayClass (eltype, 0);
523
524 # ifdef JV_HASH_SYNCHRONIZATION
525   // Since the vtable is always statically allocated,
526   // these are completely pointerfree!  Make sure the GC doesn't touch them.
527   __JArray *arr =
528     (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
529   memset((char *)arr + size, 0, elsize * count);
530 # else
531   __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
532   // Note that we assume we are given zeroed memory by the allocator.
533 # endif
534   // Cast away const.
535   jsize *lp = const_cast<jsize *> (&arr->length);
536   *lp = count;
537
538   return arr;
539 }
540
541 jobject
542 _Jv_NewArray (jint type, jint size)
543 {
544   switch (type)
545     {
546       case  4:  return JvNewBooleanArray (size);
547       case  5:  return JvNewCharArray (size);
548       case  6:  return JvNewFloatArray (size);
549       case  7:  return JvNewDoubleArray (size);
550       case  8:  return JvNewByteArray (size);
551       case  9:  return JvNewShortArray (size);
552       case 10:  return JvNewIntArray (size);
553       case 11:  return JvNewLongArray (size);
554     }
555   throw new java::lang::InternalError
556     (JvNewStringLatin1 ("invalid type code in _Jv_NewArray"));
557 }
558
559 // Allocate a possibly multi-dimensional array but don't check that
560 // any array length is <0.
561 static jobject
562 _Jv_NewMultiArrayUnchecked (jclass type, jint dimensions, jint *sizes)
563 {
564   JvAssert (type->isArray());
565   jclass element_type = type->getComponentType();
566   jobject result;
567   if (element_type->isPrimitive())
568     result = _Jv_NewPrimArray (element_type, sizes[0]);
569   else
570     result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
571
572   if (dimensions > 1)
573     {
574       JvAssert (! element_type->isPrimitive());
575       JvAssert (element_type->isArray());
576       jobject *contents = elements ((jobjectArray) result);
577       for (int i = 0; i < sizes[0]; ++i)
578         contents[i] = _Jv_NewMultiArrayUnchecked (element_type, dimensions - 1,
579                                                   sizes + 1);
580     }
581
582   return result;
583 }
584
585 jobject
586 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
587 {
588   for (int i = 0; i < dimensions; ++i)
589     if (sizes[i] < 0)
590       throw new java::lang::NegativeArraySizeException;
591
592   return _Jv_NewMultiArrayUnchecked (type, dimensions, sizes);
593 }
594
595 jobject
596 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
597 {
598   va_list args;
599   jint sizes[dimensions];
600   va_start (args, dimensions);
601   for (int i = 0; i < dimensions; ++i)
602     {
603       jint size = va_arg (args, jint);
604       if (size < 0)
605         throw new java::lang::NegativeArraySizeException;
606       sizes[i] = size;
607     }
608   va_end (args);
609
610   return _Jv_NewMultiArrayUnchecked (array_type, dimensions, sizes);
611 }
612
613 \f
614
615 // Ensure 8-byte alignment, for hash synchronization.
616 #define DECLARE_PRIM_TYPE(NAME)                 \
617   _Jv_ArrayVTable _Jv_##NAME##VTable;           \
618   java::lang::Class _Jv_##NAME##Class __attribute__ ((aligned (8)));
619
620 DECLARE_PRIM_TYPE(byte)
621 DECLARE_PRIM_TYPE(short)
622 DECLARE_PRIM_TYPE(int)
623 DECLARE_PRIM_TYPE(long)
624 DECLARE_PRIM_TYPE(boolean)
625 DECLARE_PRIM_TYPE(char)
626 DECLARE_PRIM_TYPE(float)
627 DECLARE_PRIM_TYPE(double)
628 DECLARE_PRIM_TYPE(void)
629
630 void
631 _Jv_InitPrimClass (jclass cl, char *cname, char sig, int len, 
632                    _Jv_ArrayVTable *array_vtable)
633 {    
634   using namespace java::lang::reflect;
635
636   _Jv_InitNewClassFields (cl);
637
638   // We must set the vtable for the class; the Java constructor
639   // doesn't do this.
640   (*(_Jv_VTable **) cl) = java::lang::Class::class$.vtable;
641
642   // Initialize the fields we care about.  We do this in the same
643   // order they are declared in Class.h.
644   cl->name = _Jv_makeUtf8Const ((char *) cname, -1);
645   cl->accflags = Modifier::PUBLIC | Modifier::FINAL | Modifier::ABSTRACT;
646   cl->method_count = sig;
647   cl->size_in_bytes = len;
648   cl->vtable = JV_PRIMITIVE_VTABLE;
649   cl->state = JV_STATE_DONE;
650   cl->depth = -1;
651   if (sig != 'V')
652     _Jv_NewArrayClass (cl, NULL, (_Jv_VTable *) array_vtable);
653 }
654
655 jclass
656 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
657 {
658   switch (*sig)
659     {
660     case 'B':
661       return JvPrimClass (byte);
662     case 'S':
663       return JvPrimClass (short);
664     case 'I':
665       return JvPrimClass (int);
666     case 'J':
667       return JvPrimClass (long);
668     case 'Z':
669       return JvPrimClass (boolean);
670     case 'C':
671       return JvPrimClass (char);
672     case 'F':
673       return JvPrimClass (float);
674     case 'D':
675       return JvPrimClass (double);
676     case 'V':
677       return JvPrimClass (void);
678     case 'L':
679       {
680         int i;
681         for (i = 1; sig[i] && sig[i] != ';'; ++i)
682           ;
683         _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
684         return _Jv_FindClass (name, loader);
685       }
686     case '[':
687       {
688         jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
689         if (! klass)
690           return NULL;
691         return _Jv_GetArrayClass (klass, loader);
692       }
693     }
694
695   return NULL;                  // Placate compiler.
696 }
697
698 \f
699
700 JArray<jstring> *
701 JvConvertArgv (int argc, const char **argv)
702 {
703   if (argc < 0)
704     argc = 0;
705   jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
706   jobject *ptr = elements(ar);
707   jbyteArray bytes = NULL;
708   for (int i = 0;  i < argc;  i++)
709     {
710       const char *arg = argv[i];
711       int len = strlen (arg);
712       if (bytes == NULL || bytes->length < len)
713         bytes = JvNewByteArray (len);
714       jbyte *bytePtr = elements (bytes);
715       // We assume jbyte == char.
716       memcpy (bytePtr, arg, len);
717
718       // Now convert using the default encoding.
719       *ptr++ = new java::lang::String (bytes, 0, len);
720     }
721   return (JArray<jstring>*) ar;
722 }
723
724 // FIXME: These variables are static so that they will be
725 // automatically scanned by the Boehm collector.  This is needed
726 // because with qthreads the collector won't scan the initial stack --
727 // it will only scan the qthreads stacks.
728
729 // Command line arguments.
730 static JArray<jstring> *arg_vec;
731
732 // The primary thread.
733 static java::lang::Thread *main_thread;
734
735 #ifndef DISABLE_GETENV_PROPERTIES
736
737 static char *
738 next_property_key (char *s, size_t *length)
739 {
740   size_t l = 0;
741
742   JvAssert (s);
743
744   // Skip over whitespace
745   while (isspace (*s))
746     s++;
747
748   // If we've reached the end, return NULL.  Also return NULL if for
749   // some reason we've come across a malformed property string.
750   if (*s == 0
751       || *s == ':'
752       || *s == '=')
753     return NULL;
754
755   // Determine the length of the property key.
756   while (s[l] != 0
757          && ! isspace (s[l])
758          && s[l] != ':'
759          && s[l] != '=')
760     {
761       if (s[l] == '\\'
762           && s[l+1] != 0)
763         l++;
764       l++;
765     }
766
767   *length = l;
768
769   return s;
770 }
771
772 static char *
773 next_property_value (char *s, size_t *length)
774 {
775   size_t l = 0;
776
777   JvAssert (s);
778
779   while (isspace (*s))
780     s++;
781
782   if (*s == ':'
783       || *s == '=')
784     s++;
785
786   while (isspace (*s))
787     s++;
788
789   // If we've reached the end, return NULL.
790   if (*s == 0)
791     return NULL;
792
793   // Determine the length of the property value.
794   while (s[l] != 0
795          && ! isspace (s[l])
796          && s[l] != ':'
797          && s[l] != '=')
798     {
799       if (s[l] == '\\'
800           && s[l+1] != 0)
801         l += 2;
802       else
803         l++;
804     }
805
806   *length = l;
807
808   return s;
809 }
810
811 static void
812 process_gcj_properties ()
813 {
814   char *props = getenv("GCJ_PROPERTIES");
815   char *p = props;
816   size_t length;
817   size_t property_count = 0;
818
819   if (NULL == props)
820     return;
821
822   // Whip through props quickly in order to count the number of
823   // property values.
824   while (p && (p = next_property_key (p, &length)))
825     {
826       // Skip to the end of the key
827       p += length;
828
829       p = next_property_value (p, &length);
830       if (p)
831         p += length;
832       
833       property_count++;
834     }
835
836   // Allocate an array of property value/key pairs.
837   _Jv_Environment_Properties = 
838     (property_pair *) malloc (sizeof(property_pair) 
839                               * (property_count + 1));
840
841   // Go through the properties again, initializing _Jv_Properties
842   // along the way.
843   p = props;
844   property_count = 0;
845   while (p && (p = next_property_key (p, &length)))
846     {
847       _Jv_Environment_Properties[property_count].key = p;
848       _Jv_Environment_Properties[property_count].key_length = length;
849
850       // Skip to the end of the key
851       p += length;
852
853       p = next_property_value (p, &length);
854       
855       _Jv_Environment_Properties[property_count].value = p;
856       _Jv_Environment_Properties[property_count].value_length = length;
857
858       if (p)
859         p += length;
860
861       property_count++;
862     }
863   memset ((void *) &_Jv_Environment_Properties[property_count], 
864           0, sizeof (property_pair));
865   {
866     size_t i = 0;
867
868     // Null terminate the strings.
869     while (_Jv_Environment_Properties[i].key)
870       {
871         _Jv_Environment_Properties[i].key[_Jv_Environment_Properties[i].key_length] = 0;
872         _Jv_Environment_Properties[i++].value[_Jv_Environment_Properties[i].value_length] = 0;
873       }
874   }
875 }
876 #endif // DISABLE_GETENV_PROPERTIES
877
878 namespace gcj
879 {
880   _Jv_Utf8Const *void_signature;
881   _Jv_Utf8Const *clinit_name;
882   _Jv_Utf8Const *init_name;
883   _Jv_Utf8Const *finit_name;
884   
885   bool runtimeInitialized = false;
886 }
887
888 jint
889 _Jv_CreateJavaVM (void* /*vm_args*/)
890 {
891   using namespace gcj;
892   
893   if (runtimeInitialized)
894     return -1;
895
896   runtimeInitialized = true;
897
898   PROCESS_GCJ_PROPERTIES;
899
900   _Jv_InitThreads ();
901   _Jv_InitGC ();
902   _Jv_InitializeSyncMutex ();
903
904   /* Initialize Utf8 constants declared in jvm.h. */
905   void_signature = _Jv_makeUtf8Const ("()V", 3);
906   clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
907   init_name = _Jv_makeUtf8Const ("<init>", 6);
908   finit_name = _Jv_makeUtf8Const ("finit$", 6);
909
910   /* Initialize built-in classes to represent primitive TYPEs. */
911   _Jv_InitPrimClass (&_Jv_byteClass,    "byte",    'B', 1, &_Jv_byteVTable);
912   _Jv_InitPrimClass (&_Jv_shortClass,   "short",   'S', 2, &_Jv_shortVTable);
913   _Jv_InitPrimClass (&_Jv_intClass,     "int",     'I', 4, &_Jv_intVTable);
914   _Jv_InitPrimClass (&_Jv_longClass,    "long",    'J', 8, &_Jv_longVTable);
915   _Jv_InitPrimClass (&_Jv_booleanClass, "boolean", 'Z', 1, &_Jv_booleanVTable);
916   _Jv_InitPrimClass (&_Jv_charClass,    "char",    'C', 2, &_Jv_charVTable);
917   _Jv_InitPrimClass (&_Jv_floatClass,   "float",   'F', 4, &_Jv_floatVTable);
918   _Jv_InitPrimClass (&_Jv_doubleClass,  "double",  'D', 8, &_Jv_doubleVTable);
919   _Jv_InitPrimClass (&_Jv_voidClass,    "void",    'V', 0, &_Jv_voidVTable);
920
921   // Turn stack trace generation off while creating exception objects.
922   _Jv_InitClass (&java::lang::VMThrowable::class$);
923   java::lang::VMThrowable::trace_enabled = 0;
924   
925   INIT_SEGV;
926 #ifdef HANDLE_FPE
927   INIT_FPE;
928 #endif
929   
930   no_memory = new java::lang::OutOfMemoryError;
931   
932   java::lang::VMThrowable::trace_enabled = 1;
933   
934 #ifdef USE_LTDL
935   LTDL_SET_PRELOADED_SYMBOLS ();
936 #endif
937
938   _Jv_platform_initialize ();
939
940   _Jv_JNI_Init ();
941
942   _Jv_GCInitializeFinalizers (&::gnu::gcj::runtime::FinalizerThread::finalizerReady);
943
944   // Start the GC finalizer thread.  A VirtualMachineError can be
945   // thrown by the runtime if, say, threads aren't available.  In this
946   // case finalizers simply won't run.
947   try
948     {
949       using namespace gnu::gcj::runtime;
950       FinalizerThread *ft = new FinalizerThread ();
951       ft->start ();
952     }
953   catch (java::lang::VirtualMachineError *ignore)
954     {
955     }
956
957   return 0;
958 }
959
960 void
961 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv, 
962              bool is_jar)
963 {
964   _Jv_SetArgs (argc, argv);
965
966   java::lang::Runtime *runtime = NULL;
967
968   try
969     {
970       // Set this very early so that it is seen when java.lang.System
971       // is initialized.
972       if (is_jar)
973         _Jv_Jar_Class_Path = strdup (name);
974       _Jv_CreateJavaVM (NULL);
975
976       // Get the Runtime here.  We want to initialize it before searching
977       // for `main'; that way it will be set up if `main' is a JNI method.
978       runtime = java::lang::Runtime::getRuntime ();
979
980 #ifdef DISABLE_MAIN_ARGS
981       arg_vec = JvConvertArgv (0, 0);
982 #else      
983       arg_vec = JvConvertArgv (argc - 1, argv + 1);
984 #endif
985
986       using namespace gnu::gcj::runtime;
987       if (klass)
988         main_thread = new FirstThread (klass, arg_vec);
989       else
990         main_thread = new FirstThread (JvNewStringLatin1 (name),
991                                        arg_vec, is_jar);
992     }
993   catch (java::lang::Throwable *t)
994     {
995       java::lang::System::err->println (JvNewStringLatin1 
996         ("Exception during runtime initialization"));
997       t->printStackTrace();
998       runtime->exit (1);
999     }
1000
1001   _Jv_AttachCurrentThread (main_thread);
1002   _Jv_ThreadRun (main_thread);
1003   _Jv_ThreadWait ();
1004
1005   int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
1006   runtime->exit (status);
1007 }
1008
1009 void
1010 JvRunMain (jclass klass, int argc, const char **argv)
1011 {
1012   _Jv_RunMain (klass, NULL, argc, argv, false);
1013 }
1014
1015 \f
1016
1017 // Parse a string and return a heap size.
1018 static size_t
1019 parse_heap_size (const char *spec)
1020 {
1021   char *end;
1022   unsigned long val = strtoul (spec, &end, 10);
1023   if (*end == 'k' || *end == 'K')
1024     val *= 1024;
1025   else if (*end == 'm' || *end == 'M')
1026     val *= 1048576;
1027   return (size_t) val;
1028 }
1029
1030 // Set the initial heap size.  This might be ignored by the GC layer.
1031 // This must be called before _Jv_RunMain.
1032 void
1033 _Jv_SetInitialHeapSize (const char *arg)
1034 {
1035   size_t size = parse_heap_size (arg);
1036   _Jv_GCSetInitialHeapSize (size);
1037 }
1038
1039 // Set the maximum heap size.  This might be ignored by the GC layer.
1040 // This must be called before _Jv_RunMain.
1041 void
1042 _Jv_SetMaximumHeapSize (const char *arg)
1043 {
1044   size_t size = parse_heap_size (arg);
1045   _Jv_GCSetMaximumHeapSize (size);
1046 }
1047
1048 \f
1049
1050 void *
1051 _Jv_Malloc (jsize size)
1052 {
1053   if (__builtin_expect (size == 0, false))
1054     size = 1;
1055   void *ptr = malloc ((size_t) size);
1056   if (__builtin_expect (ptr == NULL, false))
1057     throw no_memory;
1058   return ptr;
1059 }
1060
1061 void *
1062 _Jv_Realloc (void *ptr, jsize size)
1063 {
1064   if (__builtin_expect (size == 0, false))
1065     size = 1;
1066   ptr = realloc (ptr, (size_t) size);
1067   if (__builtin_expect (ptr == NULL, false))
1068     throw no_memory;
1069   return ptr;
1070 }
1071
1072 void *
1073 _Jv_MallocUnchecked (jsize size)
1074 {
1075   if (__builtin_expect (size == 0, false))
1076     size = 1;
1077   return malloc ((size_t) size);
1078 }
1079
1080 void
1081 _Jv_Free (void* ptr)
1082 {
1083   return free (ptr);
1084 }
1085
1086 \f
1087
1088 // In theory, these routines can be #ifdef'd away on machines which
1089 // support divide overflow signals.  However, we never know if some
1090 // code might have been compiled with "-fuse-divide-subroutine", so we
1091 // always include them in libgcj.
1092
1093 jint
1094 _Jv_divI (jint dividend, jint divisor)
1095 {
1096   if (__builtin_expect (divisor == 0, false))
1097     {
1098       java::lang::ArithmeticException *arithexception 
1099         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1100       throw arithexception;
1101     }
1102   
1103   if (dividend == (jint) 0x80000000L && divisor == -1)
1104     return dividend;
1105
1106   return dividend / divisor;
1107 }
1108
1109 jint
1110 _Jv_remI (jint dividend, jint divisor)
1111 {
1112   if (__builtin_expect (divisor == 0, false))
1113     {
1114       java::lang::ArithmeticException *arithexception 
1115         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1116       throw arithexception;
1117     }
1118   
1119   if (dividend == (jint) 0x80000000L && divisor == -1)
1120     return 0;
1121   
1122   return dividend % divisor;
1123 }
1124
1125 jlong
1126 _Jv_divJ (jlong dividend, jlong divisor)
1127 {
1128   if (__builtin_expect (divisor == 0, false))
1129     {
1130       java::lang::ArithmeticException *arithexception 
1131         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1132       throw arithexception;
1133     }
1134
1135   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1136     return dividend;
1137
1138   return dividend / divisor;
1139 }
1140
1141 jlong
1142 _Jv_remJ (jlong dividend, jlong divisor)
1143 {
1144   if (__builtin_expect (divisor == 0, false))
1145     {
1146       java::lang::ArithmeticException *arithexception 
1147         = new java::lang::ArithmeticException (JvNewStringLatin1 ("/ by zero"));      
1148       throw arithexception;
1149     }
1150
1151   if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1152     return 0;
1153
1154   return dividend % divisor;
1155 }
1156
1157 \f
1158
1159 // Return true if SELF_KLASS can access a field or method in
1160 // OTHER_KLASS.  The field or method's access flags are specified in
1161 // FLAGS.
1162 jboolean
1163 _Jv_CheckAccess (jclass self_klass, jclass other_klass, jint flags)
1164 {
1165   using namespace java::lang::reflect;
1166   return ((self_klass == other_klass)
1167           || ((flags & Modifier::PUBLIC) != 0)
1168           || (((flags & Modifier::PROTECTED) != 0)
1169               && other_klass->isAssignableFrom (self_klass))
1170           || (((flags & Modifier::PRIVATE) == 0)
1171               && _Jv_ClassNameSamePackage (self_klass->name,
1172                                            other_klass->name)));
1173 }