1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000 Red Hat, Inc.
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
25 #include <java-signal.h>
26 #include <java-threads.h>
28 #ifndef DISABLE_GETENV_PROPERTIES
30 #include <java-props.h>
31 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
33 #define PROCESS_GCJ_PROPERTIES
34 #endif // DISABLE_GETENV_PROPERTIES
36 #include <java/lang/Class.h>
37 #include <java/lang/Runtime.h>
38 #include <java/lang/String.h>
39 #include <java/lang/Thread.h>
40 #include <java/lang/ThreadGroup.h>
41 #include <java/lang/FirstThread.h>
42 #include <java/lang/ArrayIndexOutOfBoundsException.h>
43 #include <java/lang/ArithmeticException.h>
44 #include <java/lang/ClassFormatError.h>
45 #include <java/lang/ClassCastException.h>
46 #include <java/lang/NegativeArraySizeException.h>
47 #include <java/lang/NullPointerException.h>
48 #include <java/lang/OutOfMemoryError.h>
49 #include <java/lang/ArrayStoreException.h>
50 #include <java/lang/System.h>
51 #include <java/lang/reflect/Modifier.h>
52 #include <java/io/PrintStream.h>
58 #define ObjectClass _CL_Q34java4lang6Object
59 extern java::lang::Class ObjectClass
;
61 // We allocate a single OutOfMemoryError exception which we keep
62 // around for use if we run out of memory.
63 static java::lang::OutOfMemoryError
*no_memory
;
65 // Largest representable size_t.
66 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
68 // Properties set at compile time.
69 const char **_Jv_Compiler_Properties
;
71 #ifndef DISABLE_GETENV_PROPERTIES
72 // Property key/value pairs.
73 property_pair
*_Jv_Environment_Properties
;
76 // The name of this executable.
77 static char * _Jv_execName
;
82 static java::lang::NullPointerException
*nullp
;
83 SIGNAL_HANDLER (catch_segv
)
86 nullp
->fillInStackTrace ();
91 static java::lang::ArithmeticException
*arithexception
;
94 SIGNAL_HANDLER (catch_fpe
)
96 #ifdef HANDLE_DIVIDE_OVERFLOW
97 HANDLE_DIVIDE_OVERFLOW
;
101 arithexception
->fillInStackTrace ();
102 _Jv_Throw (arithexception
);
109 _Jv_equalUtf8Consts (Utf8Const
* a
, Utf8Const
*b
)
112 register _Jv_ushort
*aptr
, *bptr
;
115 if (a
->hash
!= b
->hash
)
118 if (b
->length
!= len
)
120 aptr
= (_Jv_ushort
*)a
->data
;
121 bptr
= (_Jv_ushort
*)b
->data
;
122 len
= (len
+ 1) >> 1;
124 if (*aptr
++ != *bptr
++)
129 /* True iff A is equal to STR.
130 HASH is STR->hashCode().
134 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
136 if (a
->hash
!= (_Jv_ushort
) hash
)
138 jint len
= str
->length();
140 jchar
*sptr
= _Jv_GetStringChars (str
);
141 register unsigned char* ptr
= (unsigned char*) a
->data
;
142 register unsigned char* limit
= ptr
+ a
->length
;
145 int ch
= UTF8_GET (ptr
, limit
);
154 /* Like _Jv_equal, but stop after N characters. */
156 _Jv_equaln (Utf8Const
*a
, jstring str
, jint n
)
158 jint len
= str
->length();
160 jchar
*sptr
= _Jv_GetStringChars (str
);
161 register unsigned char* ptr
= (unsigned char*) a
->data
;
162 register unsigned char* limit
= ptr
+ a
->length
;
163 for (; n
-- > 0; i
++, sptr
++)
165 int ch
= UTF8_GET (ptr
, limit
);
174 /* Count the number of Unicode chars encoded in a given Ut8 string. */
176 _Jv_strLengthUtf8(char* str
, int len
)
178 register unsigned char* ptr
;
179 register unsigned char* limit
;
182 ptr
= (unsigned char*) str
;
185 for (; ptr
< limit
; str_length
++) {
186 if (UTF8_GET (ptr
, limit
) < 0) {
193 /* Calculate a hash value for a string encoded in Utf8 format.
194 * This returns the same hash value as specified or java.lang.String.hashCode.
197 hashUtf8String (char* str
, int len
)
199 register unsigned char* ptr
= (unsigned char*) str
;
200 register unsigned char* limit
= ptr
+ len
;
205 int ch
= UTF8_GET (ptr
, limit
);
206 /* Updated specification from
207 http://www.javasoft.com/docs/books/jls/clarify.html. */
208 hash
= (31 * hash
) + ch
;
214 _Jv_makeUtf8Const (char* s
, int len
)
218 Utf8Const
* m
= (Utf8Const
*) _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
221 memcpy (m
->data
, s
, len
);
224 m
->hash
= hashUtf8String (s
, len
) & 0xFFFF;
229 _Jv_makeUtf8Const (jstring string
)
231 jint hash
= string
->hashCode ();
232 jint len
= _Jv_GetStringUTFLength (string
);
234 Utf8Const
* m
= (Utf8Const
*)
235 _Jv_AllocBytesChecked (sizeof(Utf8Const
) + len
+ 1);
240 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
250 _Jv_Abort (const char *function
, const char *file
, int line
,
254 _Jv_Abort (const char *, const char *, int, const char *message
)
259 "libgcj failure: %s\n in function %s, file %s, line %d\n",
260 message
, function
, file
, line
);
262 java::io::PrintStream
*err
= java::lang::System::err
;
263 err
->print(JvNewStringLatin1 ("libgcj failure: "));
264 err
->println(JvNewStringLatin1 (message
));
271 fail_on_finalization (jobject
)
273 JvFail ("object was finalized");
277 _Jv_GCWatch (jobject obj
)
279 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
283 _Jv_ThrowBadArrayIndex(jint bad_index
)
285 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
286 (java::lang::String::valueOf(bad_index
)));
290 _Jv_CheckCast (jclass c
, jobject obj
)
292 if (obj
!= NULL
&& ! c
->isAssignableFrom(obj
->getClass()))
293 JvThrow (new java::lang::ClassCastException
);
298 _Jv_CheckArrayStore (jobject arr
, jobject obj
)
302 JvAssert (arr
!= NULL
);
303 jclass arr_class
= arr
->getClass();
304 JvAssert (arr_class
->isArray());
305 jclass elt_class
= arr_class
->getComponentType();
306 jclass obj_class
= obj
->getClass();
307 if (! elt_class
->isAssignableFrom(obj_class
))
308 JvThrow (new java::lang::ArrayStoreException
);
314 // Allocate some unscanned memory and throw an exception if no memory.
316 _Jv_AllocBytesChecked (jsize size
)
318 void *r
= _Jv_AllocBytes (size
);
320 _Jv_Throw (no_memory
);
324 // Allocate a new object of class C. SIZE is the size of the object
325 // to allocate. You might think this is redundant, but it isn't; some
326 // classes, such as String, aren't of fixed size.
328 _Jv_AllocObject (jclass c
, jint size
)
332 jobject obj
= (jobject
) _Jv_AllocObj (size
);
335 *((_Jv_VTable
**) obj
) = c
->vtable
;
337 // If this class has inherited finalize from Object, then don't
338 // bother registering a finalizer. We know that finalize() is the
339 // very first method after the dummy entry. If this turns out to be
340 // unreliable, a more robust implementation can be written. Such an
341 // implementation would look for Object.finalize in Object's method
342 // table at startup, and then use that information to find the
343 // appropriate index in the method vector.
344 if (c
->vtable
->method
[1] != ObjectClass
.vtable
->method
[1])
345 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
350 // Allocate a new array of Java objects. Each object is of type
351 // `elementClass'. `init' is used to initialize each slot in the
354 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
357 JvThrow (new java::lang::NegativeArraySizeException
);
359 JvAssert (! elementClass
->isPrimitive ());
361 jobjectArray obj
= NULL
;
362 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (obj
,
365 // Check for overflow.
366 if ((size_t) count
> (SIZE_T_MAX
- size
) / sizeof (jobject
))
369 size
+= count
* sizeof (jobject
);
371 // FIXME: second argument should be "current loader" //
372 jclass clas
= _Jv_FindArrayClass (elementClass
, 0);
374 obj
= (jobjectArray
) _Jv_AllocArray (size
);
378 jobject
* ptr
= elements(obj
);
379 // We know the allocator returns zeroed memory. So don't bother
386 // Set the vtbl last to avoid problems if the GC happens during the
387 // window in this function between the allocation and this
389 *((_Jv_VTable
**) obj
) = clas
->vtable
;
393 // Allocate a new array of primitives. ELTYPE is the type of the
394 // element, COUNT is the size of the array.
396 _Jv_NewPrimArray (jclass eltype
, jint count
)
398 int elsize
= eltype
->size();
400 JvThrow (new java::lang::NegativeArraySizeException ());
402 JvAssert (eltype
->isPrimitive ());
403 jobject dummy
= NULL
;
404 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
406 // Check for overflow.
407 if ((size_t) count
> (SIZE_T_MAX
- size
) / elsize
)
410 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
);
414 // Note that we assume we are given zeroed memory by the allocator.
416 jclass klass
= _Jv_FindArrayClass (eltype
, 0);
417 // Set the vtbl last to avoid problems if the GC happens during the
418 // window in this function between the allocation and this
420 *((_Jv_VTable
**) arr
) = klass
->vtable
;
425 JvNewCharArray (jint length
)
427 return (jcharArray
) _Jv_NewPrimArray (JvPrimClass (char), length
);
431 JvNewBooleanArray (jint length
)
433 return (jbooleanArray
) _Jv_NewPrimArray (JvPrimClass (boolean
), length
);
437 JvNewByteArray (jint length
)
439 return (jbyteArray
) _Jv_NewPrimArray (JvPrimClass (byte
), length
);
443 JvNewShortArray (jint length
)
445 return (jshortArray
) _Jv_NewPrimArray (JvPrimClass (short), length
);
449 JvNewIntArray (jint length
)
451 return (jintArray
) _Jv_NewPrimArray (JvPrimClass (int), length
);
455 JvNewLongArray (jint length
)
457 return (jlongArray
) _Jv_NewPrimArray (JvPrimClass (long), length
);
461 JvNewFloatArray (jint length
)
463 return (jfloatArray
) _Jv_NewPrimArray (JvPrimClass (float), length
);
467 JvNewDoubleArray (jint length
)
469 return (jdoubleArray
) _Jv_NewPrimArray (JvPrimClass (double), length
);
473 _Jv_NewArray (jint type
, jint size
)
477 case 4: return JvNewBooleanArray (size
);
478 case 5: return JvNewCharArray (size
);
479 case 6: return JvNewFloatArray (size
);
480 case 7: return JvNewDoubleArray (size
);
481 case 8: return JvNewByteArray (size
);
482 case 9: return JvNewShortArray (size
);
483 case 10: return JvNewIntArray (size
);
484 case 11: return JvNewLongArray (size
);
486 JvFail ("newarray - bad type code");
487 return NULL
; // Placate compiler.
491 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
493 JvAssert (type
->isArray());
494 jclass element_type
= type
->getComponentType();
496 if (element_type
->isPrimitive())
497 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
499 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
503 JvAssert (! element_type
->isPrimitive());
504 JvAssert (element_type
->isArray());
505 jobject
*contents
= elements ((jobjectArray
) result
);
506 for (int i
= 0; i
< sizes
[0]; ++i
)
507 contents
[i
] = _Jv_NewMultiArray (element_type
, dimensions
- 1,
515 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
518 jint sizes
[dimensions
];
519 va_start (args
, dimensions
);
520 for (int i
= 0; i
< dimensions
; ++i
)
522 jint size
= va_arg (args
, jint
);
527 return _Jv_NewMultiArray (array_type
, dimensions
, sizes
);
532 class _Jv_PrimClass
: public java::lang::Class
535 // FIXME: calling convention is weird. If we use the natural types
536 // then the compiler will complain because they aren't Java types.
537 _Jv_PrimClass (jobject cname
, jbyte sig
, jint len
)
539 using namespace java::lang::reflect
;
541 // We must initialize every field of the class. We do this in
542 // the same order they are declared in Class.h.
544 name
= _Jv_makeUtf8Const ((char *) cname
, -1);
545 accflags
= Modifier::PUBLIC
| Modifier::FINAL
;
548 constants
.tags
= NULL
;
549 constants
.data
= NULL
;
552 vtable_method_count
= 0;
556 static_field_count
= 0;
557 vtable
= JV_PRIMITIVE_VTABLE
;
561 state
= JV_STATE_NOTHING
;
566 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
567 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
569 DECLARE_PRIM_TYPE(byte
, 'B', 1);
570 DECLARE_PRIM_TYPE(short, 'S', 2);
571 DECLARE_PRIM_TYPE(int, 'I', 4);
572 DECLARE_PRIM_TYPE(long, 'J', 8);
573 DECLARE_PRIM_TYPE(boolean
, 'Z', 1);
574 DECLARE_PRIM_TYPE(char, 'C', 2);
575 DECLARE_PRIM_TYPE(float, 'F', 4);
576 DECLARE_PRIM_TYPE(double, 'D', 8);
577 DECLARE_PRIM_TYPE(void, 'V', 0);
580 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
)
585 return JvPrimClass (byte
);
587 return JvPrimClass (short);
589 return JvPrimClass (int);
591 return JvPrimClass (long);
593 return JvPrimClass (boolean
);
595 return JvPrimClass (char);
597 return JvPrimClass (float);
599 return JvPrimClass (double);
601 return JvPrimClass (void);
605 for (i
= 1; sig
[i
] && sig
[i
] != ';'; ++i
)
607 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (&sig
[1], i
- 1);
608 return _Jv_FindClass (name
, loader
);
612 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig
[1], loader
),
615 JvFail ("couldn't understand class signature");
616 return NULL
; // Placate compiler.
622 JvConvertArgv (int argc
, const char **argv
)
626 jobjectArray ar
= JvNewObjectArray(argc
, &StringClass
, NULL
);
627 jobject
* ptr
= elements(ar
);
628 for (int i
= 0; i
< argc
; i
++)
630 const char *arg
= argv
[i
];
631 // FIXME - should probably use JvNewStringUTF.
632 *ptr
++ = JvNewStringLatin1(arg
, strlen(arg
));
634 return (JArray
<jstring
>*) ar
;
637 // FIXME: These variables are static so that they will be
638 // automatically scanned by the Boehm collector. This is needed
639 // because with qthreads the collector won't scan the initial stack --
640 // it will only scan the qthreads stacks.
642 // Command line arguments.
643 static jobject arg_vec
;
645 // The primary threadgroup.
646 static java::lang::ThreadGroup
*main_group
;
648 // The primary thread.
649 static java::lang::Thread
*main_thread
;
652 _Jv_ThisExecutable (void)
658 _Jv_ThisExecutable (const char *name
)
662 _Jv_execName
= new char[strlen (name
) + 1];
663 strcpy (_Jv_execName
, name
);
674 arithexception
= new java::lang::ArithmeticException
675 (JvNewStringLatin1 ("/ by zero"));
678 no_memory
= new java::lang::OutOfMemoryError
;
681 LTDL_SET_PRELOADED_SYMBOLS ();
684 // FIXME: we only want this on POSIX systems.
685 struct sigaction act
;
686 act
.sa_handler
= SIG_IGN
;
687 sigemptyset (&act
.sa_mask
);
689 sigaction (SIGPIPE
, &act
, NULL
);
694 #ifndef DISABLE_GETENV_PROPERTIES
697 next_property_key (char *s
, size_t *length
)
703 // Skip over whitespace
707 // If we've reached the end, return NULL. Also return NULL if for
708 // some reason we've come across a malformed property string.
714 // Determine the length of the property key.
732 next_property_value (char *s
, size_t *length
)
748 // If we've reached the end, return NULL.
752 // Determine the length of the property value.
771 process_gcj_properties ()
773 char *props
= getenv("GCJ_PROPERTIES");
776 size_t property_count
= 0;
781 // Whip through props quickly in order to count the number of
783 while (p
&& (p
= next_property_key (p
, &length
)))
785 // Skip to the end of the key
788 p
= next_property_value (p
, &length
);
795 // Allocate an array of property value/key pairs.
796 _Jv_Environment_Properties
=
797 (property_pair
*) malloc (sizeof(property_pair
)
798 * (property_count
+ 1));
800 // Go through the properties again, initializing _Jv_Properties
804 while (p
&& (p
= next_property_key (p
, &length
)))
806 _Jv_Environment_Properties
[property_count
].key
= p
;
807 _Jv_Environment_Properties
[property_count
].key_length
= length
;
809 // Skip to the end of the key
812 p
= next_property_value (p
, &length
);
814 _Jv_Environment_Properties
[property_count
].value
= p
;
815 _Jv_Environment_Properties
[property_count
].value_length
= length
;
822 memset ((void *) &_Jv_Environment_Properties
[property_count
],
823 0, sizeof (property_pair
));
827 // Null terminate the strings.
828 while (_Jv_Environment_Properties
[i
].key
)
830 _Jv_Environment_Properties
[i
].key
[_Jv_Environment_Properties
[i
].key_length
] = 0;
831 _Jv_Environment_Properties
[i
++].value
[_Jv_Environment_Properties
[i
].value_length
] = 0;
835 #endif // DISABLE_GETENV_PROPERTIES
838 JvRunMain (jclass klass
, int argc
, const char **argv
)
840 PROCESS_GCJ_PROPERTIES
;
843 #ifdef HAVE_PROC_SELF_EXE
845 sprintf (exec_name
, "/proc/%d/exe", getpid ());
846 _Jv_ThisExecutable (exec_name
);
848 _Jv_ThisExecutable (argv
[0]);
851 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
852 main_group
= new java::lang::ThreadGroup (23);
853 main_thread
= new java::lang::FirstThread (main_group
, klass
, arg_vec
);
855 main_thread
->start();
858 java::lang::Runtime::getRuntime ()->exit (0);
862 _Jv_RunMain (const char *class_name
, int argc
, const char **argv
)
864 PROCESS_GCJ_PROPERTIES
;
868 #ifdef HAVE_PROC_SELF_EXE
870 sprintf (exec_name
, "/proc/%d/exe", getpid ());
871 _Jv_ThisExecutable (exec_name
);
874 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
875 main_group
= new java::lang::ThreadGroup (23);
876 main_thread
= new java::lang::FirstThread (main_group
,
877 JvNewStringLatin1 (class_name
),
879 main_thread
->start();
882 java::lang::Runtime::getRuntime ()->exit (0);
887 // Parse a string and return a heap size.
889 parse_heap_size (const char *spec
)
892 unsigned long val
= strtoul (spec
, &end
, 10);
893 if (*end
== 'k' || *end
== 'K')
895 else if (*end
== 'm' || *end
== 'M')
900 // Set the initial heap size. This might be ignored by the GC layer.
901 // This must be called before _Jv_RunMain.
903 _Jv_SetInitialHeapSize (const char *arg
)
905 size_t size
= parse_heap_size (arg
);
906 _Jv_GCSetInitialHeapSize (size
);
909 // Set the maximum heap size. This might be ignored by the GC layer.
910 // This must be called before _Jv_RunMain.
912 _Jv_SetMaximumHeapSize (const char *arg
)
914 size_t size
= parse_heap_size (arg
);
915 _Jv_GCSetMaximumHeapSize (size
);
921 _Jv_MallocUnchecked (jsize size
)
925 return malloc ((size_t) size
);
929 _Jv_Malloc (jsize size
)
933 void *ptr
= malloc ((size_t) size
);
947 // In theory, these routines can be #ifdef'd away on machines which
948 // support divide overflow signals. However, we never know if some
949 // code might have been compiled with "-fuse-divide-subroutine", so we
950 // always include them in libgcj.
953 _Jv_divI (jint dividend
, jint divisor
)
956 _Jv_Throw (arithexception
);
958 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
961 return dividend
/ divisor
;
965 _Jv_remI (jint dividend
, jint divisor
)
968 _Jv_Throw (arithexception
);
970 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
973 return dividend
% divisor
;
977 _Jv_divJ (jlong dividend
, jlong divisor
)
980 _Jv_Throw (arithexception
);
982 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
985 return dividend
/ divisor
;
989 _Jv_remJ (jlong dividend
, jlong divisor
)
992 _Jv_Throw (arithexception
);
994 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
997 return dividend
% divisor
;