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