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 <gnu/gcj/runtime/FirstThread.h>
42 #include <java/lang/ArrayIndexOutOfBoundsException.h>
43 #include <java/lang/ArithmeticException.h>
44 #include <java/lang/ClassFormatError.h>
45 #include <java/lang/NegativeArraySizeException.h>
46 #include <java/lang/NullPointerException.h>
47 #include <java/lang/OutOfMemoryError.h>
48 #include <java/lang/System.h>
49 #include <java/lang/reflect/Modifier.h>
50 #include <java/io/PrintStream.h>
56 #define ObjectClass _CL_Q34java4lang6Object
57 extern java::lang::Class ObjectClass
;
59 // We allocate a single OutOfMemoryError exception which we keep
60 // around for use if we run out of memory.
61 static java::lang::OutOfMemoryError
*no_memory
;
63 // Largest representable size_t.
64 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
66 // Properties set at compile time.
67 const char **_Jv_Compiler_Properties
;
69 #ifndef DISABLE_GETENV_PROPERTIES
70 // Property key/value pairs.
71 property_pair
*_Jv_Environment_Properties
;
74 // The name of this executable.
75 static char * _Jv_execName
;
80 static java::lang::NullPointerException
*nullp
;
81 SIGNAL_HANDLER (catch_segv
)
84 nullp
->fillInStackTrace ();
89 static java::lang::ArithmeticException
*arithexception
;
92 SIGNAL_HANDLER (catch_fpe
)
94 #ifdef HANDLE_DIVIDE_OVERFLOW
95 HANDLE_DIVIDE_OVERFLOW
;
99 arithexception
->fillInStackTrace ();
100 _Jv_Throw (arithexception
);
107 _Jv_equalUtf8Consts (Utf8Const
* a
, Utf8Const
*b
)
110 register _Jv_ushort
*aptr
, *bptr
;
113 if (a
->hash
!= b
->hash
)
116 if (b
->length
!= len
)
118 aptr
= (_Jv_ushort
*)a
->data
;
119 bptr
= (_Jv_ushort
*)b
->data
;
120 len
= (len
+ 1) >> 1;
122 if (*aptr
++ != *bptr
++)
127 /* True iff A is equal to STR.
128 HASH is STR->hashCode().
132 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
134 if (a
->hash
!= (_Jv_ushort
) hash
)
136 jint len
= str
->length();
138 jchar
*sptr
= _Jv_GetStringChars (str
);
139 register unsigned char* ptr
= (unsigned char*) a
->data
;
140 register unsigned char* limit
= ptr
+ a
->length
;
143 int ch
= UTF8_GET (ptr
, limit
);
152 /* Like _Jv_equal, but stop after N characters. */
154 _Jv_equaln (Utf8Const
*a
, jstring str
, jint n
)
156 jint len
= str
->length();
158 jchar
*sptr
= _Jv_GetStringChars (str
);
159 register unsigned char* ptr
= (unsigned char*) a
->data
;
160 register unsigned char* limit
= ptr
+ a
->length
;
161 for (; n
-- > 0; i
++, sptr
++)
163 int ch
= UTF8_GET (ptr
, limit
);
172 /* Count the number of Unicode chars encoded in a given Ut8 string. */
174 _Jv_strLengthUtf8(char* str
, int len
)
176 register unsigned char* ptr
;
177 register unsigned char* limit
;
180 ptr
= (unsigned char*) str
;
183 for (; ptr
< limit
; str_length
++) {
184 if (UTF8_GET (ptr
, limit
) < 0) {
191 /* Calculate a hash value for a string encoded in Utf8 format.
192 * This returns the same hash value as specified or java.lang.String.hashCode.
195 hashUtf8String (char* str
, int len
)
197 register unsigned char* ptr
= (unsigned char*) str
;
198 register unsigned char* limit
= ptr
+ len
;
203 int ch
= UTF8_GET (ptr
, limit
);
204 /* Updated specification from
205 http://www.javasoft.com/docs/books/jls/clarify.html. */
206 hash
= (31 * hash
) + ch
;
212 _Jv_makeUtf8Const (char* s
, int len
)
216 Utf8Const
* m
= (Utf8Const
*) _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
219 memcpy (m
->data
, s
, len
);
222 m
->hash
= hashUtf8String (s
, len
) & 0xFFFF;
227 _Jv_makeUtf8Const (jstring string
)
229 jint hash
= string
->hashCode ();
230 jint len
= _Jv_GetStringUTFLength (string
);
232 Utf8Const
* m
= (Utf8Const
*)
233 _Jv_AllocBytesChecked (sizeof(Utf8Const
) + len
+ 1);
238 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
248 _Jv_Abort (const char *function
, const char *file
, int line
,
252 _Jv_Abort (const char *, const char *, int, const char *message
)
257 "libgcj failure: %s\n in function %s, file %s, line %d\n",
258 message
, function
, file
, line
);
260 java::io::PrintStream
*err
= java::lang::System::err
;
261 err
->print(JvNewStringLatin1 ("libgcj failure: "));
262 err
->println(JvNewStringLatin1 (message
));
269 fail_on_finalization (jobject
)
271 JvFail ("object was finalized");
275 _Jv_GCWatch (jobject obj
)
277 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
281 _Jv_ThrowBadArrayIndex(jint bad_index
)
283 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
284 (java::lang::String::valueOf(bad_index
)));
287 // Allocate some unscanned memory and throw an exception if no memory.
289 _Jv_AllocBytesChecked (jsize size
)
291 void *r
= _Jv_AllocBytes (size
);
293 _Jv_Throw (no_memory
);
297 // Allocate a new object of class C. SIZE is the size of the object
298 // to allocate. You might think this is redundant, but it isn't; some
299 // classes, such as String, aren't of fixed size.
301 _Jv_AllocObject (jclass c
, jint size
)
305 jobject obj
= (jobject
) _Jv_AllocObj (size
);
308 *((_Jv_VTable
**) obj
) = c
->vtable
;
310 // If this class has inherited finalize from Object, then don't
311 // bother registering a finalizer. We know that finalize() is the
312 // very first method after the dummy entry. If this turns out to be
313 // unreliable, a more robust implementation can be written. Such an
314 // implementation would look for Object.finalize in Object's method
315 // table at startup, and then use that information to find the
316 // appropriate index in the method vector.
317 if (c
->vtable
->method
[1] != ObjectClass
.vtable
->method
[1])
318 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
323 // Allocate a new array of Java objects. Each object is of type
324 // `elementClass'. `init' is used to initialize each slot in the
327 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
330 JvThrow (new java::lang::NegativeArraySizeException
);
332 JvAssert (! elementClass
->isPrimitive ());
334 jobjectArray obj
= NULL
;
335 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (obj
,
338 // Check for overflow.
339 if ((size_t) count
> (SIZE_T_MAX
- size
) / sizeof (jobject
))
342 size
+= count
* sizeof (jobject
);
344 // FIXME: second argument should be "current loader" //
345 jclass clas
= _Jv_FindArrayClass (elementClass
, 0);
347 obj
= (jobjectArray
) _Jv_AllocArray (size
);
351 jobject
* ptr
= elements(obj
);
352 // We know the allocator returns zeroed memory. So don't bother
359 // Set the vtbl last to avoid problems if the GC happens during the
360 // window in this function between the allocation and this
362 *((_Jv_VTable
**) obj
) = clas
->vtable
;
366 // Allocate a new array of primitives. ELTYPE is the type of the
367 // element, COUNT is the size of the array.
369 _Jv_NewPrimArray (jclass eltype
, jint count
)
371 int elsize
= eltype
->size();
373 JvThrow (new java::lang::NegativeArraySizeException ());
375 JvAssert (eltype
->isPrimitive ());
376 jobject dummy
= NULL
;
377 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
379 // Check for overflow.
380 if ((size_t) count
> (SIZE_T_MAX
- size
) / elsize
)
383 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
);
387 // Note that we assume we are given zeroed memory by the allocator.
389 jclass klass
= _Jv_FindArrayClass (eltype
, 0);
390 // Set the vtbl last to avoid problems if the GC happens during the
391 // window in this function between the allocation and this
393 *((_Jv_VTable
**) arr
) = klass
->vtable
;
398 _Jv_NewArray (jint type
, jint size
)
402 case 4: return JvNewBooleanArray (size
);
403 case 5: return JvNewCharArray (size
);
404 case 6: return JvNewFloatArray (size
);
405 case 7: return JvNewDoubleArray (size
);
406 case 8: return JvNewByteArray (size
);
407 case 9: return JvNewShortArray (size
);
408 case 10: return JvNewIntArray (size
);
409 case 11: return JvNewLongArray (size
);
411 JvFail ("newarray - bad type code");
412 return NULL
; // Placate compiler.
416 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
418 JvAssert (type
->isArray());
419 jclass element_type
= type
->getComponentType();
421 if (element_type
->isPrimitive())
422 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
424 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
428 JvAssert (! element_type
->isPrimitive());
429 JvAssert (element_type
->isArray());
430 jobject
*contents
= elements ((jobjectArray
) result
);
431 for (int i
= 0; i
< sizes
[0]; ++i
)
432 contents
[i
] = _Jv_NewMultiArray (element_type
, dimensions
- 1,
440 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
443 jint sizes
[dimensions
];
444 va_start (args
, dimensions
);
445 for (int i
= 0; i
< dimensions
; ++i
)
447 jint size
= va_arg (args
, jint
);
452 return _Jv_NewMultiArray (array_type
, dimensions
, sizes
);
457 class _Jv_PrimClass
: public java::lang::Class
460 // FIXME: calling convention is weird. If we use the natural types
461 // then the compiler will complain because they aren't Java types.
462 _Jv_PrimClass (jobject cname
, jbyte sig
, jint len
)
464 using namespace java::lang::reflect
;
466 // We must initialize every field of the class. We do this in
467 // the same order they are declared in Class.h.
469 name
= _Jv_makeUtf8Const ((char *) cname
, -1);
470 accflags
= Modifier::PUBLIC
| Modifier::FINAL
;
473 constants
.tags
= NULL
;
474 constants
.data
= NULL
;
477 vtable_method_count
= 0;
481 static_field_count
= 0;
482 vtable
= JV_PRIMITIVE_VTABLE
;
486 state
= JV_STATE_NOTHING
;
491 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
492 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
494 DECLARE_PRIM_TYPE(byte
, 'B', 1);
495 DECLARE_PRIM_TYPE(short, 'S', 2);
496 DECLARE_PRIM_TYPE(int, 'I', 4);
497 DECLARE_PRIM_TYPE(long, 'J', 8);
498 DECLARE_PRIM_TYPE(boolean
, 'Z', 1);
499 DECLARE_PRIM_TYPE(char, 'C', 2);
500 DECLARE_PRIM_TYPE(float, 'F', 4);
501 DECLARE_PRIM_TYPE(double, 'D', 8);
502 DECLARE_PRIM_TYPE(void, 'V', 0);
505 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
)
510 return JvPrimClass (byte
);
512 return JvPrimClass (short);
514 return JvPrimClass (int);
516 return JvPrimClass (long);
518 return JvPrimClass (boolean
);
520 return JvPrimClass (char);
522 return JvPrimClass (float);
524 return JvPrimClass (double);
526 return JvPrimClass (void);
530 for (i
= 1; sig
[i
] && sig
[i
] != ';'; ++i
)
532 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (&sig
[1], i
- 1);
533 return _Jv_FindClass (name
, loader
);
537 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig
[1], loader
),
540 JvFail ("couldn't understand class signature");
541 return NULL
; // Placate compiler.
547 JvConvertArgv (int argc
, const char **argv
)
551 jobjectArray ar
= JvNewObjectArray(argc
, &StringClass
, NULL
);
552 jobject
* ptr
= elements(ar
);
553 for (int i
= 0; i
< argc
; i
++)
555 const char *arg
= argv
[i
];
556 // FIXME - should probably use JvNewStringUTF.
557 *ptr
++ = JvNewStringLatin1(arg
, strlen(arg
));
559 return (JArray
<jstring
>*) ar
;
562 // FIXME: These variables are static so that they will be
563 // automatically scanned by the Boehm collector. This is needed
564 // because with qthreads the collector won't scan the initial stack --
565 // it will only scan the qthreads stacks.
567 // Command line arguments.
568 static jobject arg_vec
;
570 // The primary threadgroup.
571 static java::lang::ThreadGroup
*main_group
;
573 // The primary thread.
574 static java::lang::Thread
*main_thread
;
577 _Jv_ThisExecutable (void)
583 _Jv_ThisExecutable (const char *name
)
587 _Jv_execName
= new char[strlen (name
) + 1];
588 strcpy (_Jv_execName
, name
);
599 arithexception
= new java::lang::ArithmeticException
600 (JvNewStringLatin1 ("/ by zero"));
603 no_memory
= new java::lang::OutOfMemoryError
;
606 LTDL_SET_PRELOADED_SYMBOLS ();
609 // FIXME: we only want this on POSIX systems.
610 struct sigaction act
;
611 act
.sa_handler
= SIG_IGN
;
612 sigemptyset (&act
.sa_mask
);
614 sigaction (SIGPIPE
, &act
, NULL
);
619 #ifndef DISABLE_GETENV_PROPERTIES
622 next_property_key (char *s
, size_t *length
)
628 // Skip over whitespace
632 // If we've reached the end, return NULL. Also return NULL if for
633 // some reason we've come across a malformed property string.
639 // Determine the length of the property key.
657 next_property_value (char *s
, size_t *length
)
673 // If we've reached the end, return NULL.
677 // Determine the length of the property value.
696 process_gcj_properties ()
698 char *props
= getenv("GCJ_PROPERTIES");
701 size_t property_count
= 0;
706 // Whip through props quickly in order to count the number of
708 while (p
&& (p
= next_property_key (p
, &length
)))
710 // Skip to the end of the key
713 p
= next_property_value (p
, &length
);
720 // Allocate an array of property value/key pairs.
721 _Jv_Environment_Properties
=
722 (property_pair
*) malloc (sizeof(property_pair
)
723 * (property_count
+ 1));
725 // Go through the properties again, initializing _Jv_Properties
729 while (p
&& (p
= next_property_key (p
, &length
)))
731 _Jv_Environment_Properties
[property_count
].key
= p
;
732 _Jv_Environment_Properties
[property_count
].key_length
= length
;
734 // Skip to the end of the key
737 p
= next_property_value (p
, &length
);
739 _Jv_Environment_Properties
[property_count
].value
= p
;
740 _Jv_Environment_Properties
[property_count
].value_length
= length
;
747 memset ((void *) &_Jv_Environment_Properties
[property_count
],
748 0, sizeof (property_pair
));
752 // Null terminate the strings.
753 while (_Jv_Environment_Properties
[i
].key
)
755 _Jv_Environment_Properties
[i
].key
[_Jv_Environment_Properties
[i
].key_length
] = 0;
756 _Jv_Environment_Properties
[i
++].value
[_Jv_Environment_Properties
[i
].value_length
] = 0;
760 #endif // DISABLE_GETENV_PROPERTIES
763 JvRunMain (jclass klass
, int argc
, const char **argv
)
765 PROCESS_GCJ_PROPERTIES
;
768 #ifdef HAVE_PROC_SELF_EXE
770 sprintf (exec_name
, "/proc/%d/exe", getpid ());
771 _Jv_ThisExecutable (exec_name
);
773 _Jv_ThisExecutable (argv
[0]);
776 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
777 main_group
= new java::lang::ThreadGroup (23);
778 main_thread
= new gnu::gcj::runtime::FirstThread (main_group
,
781 main_thread
->start();
784 java::lang::Runtime::getRuntime ()->exit (0);
788 _Jv_RunMain (const char *class_name
, int argc
, const char **argv
)
790 PROCESS_GCJ_PROPERTIES
;
794 #ifdef HAVE_PROC_SELF_EXE
796 sprintf (exec_name
, "/proc/%d/exe", getpid ());
797 _Jv_ThisExecutable (exec_name
);
800 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
801 main_group
= new java::lang::ThreadGroup (23);
802 main_thread
= new gnu::gcj::runtime::FirstThread (main_group
,
803 JvNewStringLatin1 (class_name
),
805 main_thread
->start();
808 java::lang::Runtime::getRuntime ()->exit (0);
813 // Parse a string and return a heap size.
815 parse_heap_size (const char *spec
)
818 unsigned long val
= strtoul (spec
, &end
, 10);
819 if (*end
== 'k' || *end
== 'K')
821 else if (*end
== 'm' || *end
== 'M')
826 // Set the initial heap size. This might be ignored by the GC layer.
827 // This must be called before _Jv_RunMain.
829 _Jv_SetInitialHeapSize (const char *arg
)
831 size_t size
= parse_heap_size (arg
);
832 _Jv_GCSetInitialHeapSize (size
);
835 // Set the maximum heap size. This might be ignored by the GC layer.
836 // This must be called before _Jv_RunMain.
838 _Jv_SetMaximumHeapSize (const char *arg
)
840 size_t size
= parse_heap_size (arg
);
841 _Jv_GCSetMaximumHeapSize (size
);
847 _Jv_Malloc (jsize size
)
851 void *ptr
= malloc ((size_t) size
);
858 _Jv_Realloc (void *ptr
, jsize size
)
862 ptr
= realloc (ptr
, (size_t) size
);
869 _Jv_MallocUnchecked (jsize size
)
873 return malloc ((size_t) size
);
884 // In theory, these routines can be #ifdef'd away on machines which
885 // support divide overflow signals. However, we never know if some
886 // code might have been compiled with "-fuse-divide-subroutine", so we
887 // always include them in libgcj.
890 _Jv_divI (jint dividend
, jint divisor
)
893 _Jv_Throw (arithexception
);
895 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
898 return dividend
/ divisor
;
902 _Jv_remI (jint dividend
, jint divisor
)
905 _Jv_Throw (arithexception
);
907 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
910 return dividend
% divisor
;
914 _Jv_divJ (jlong dividend
, jlong divisor
)
917 _Jv_Throw (arithexception
);
919 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
922 return dividend
/ divisor
;
926 _Jv_remJ (jlong dividend
, jlong divisor
)
929 _Jv_Throw (arithexception
);
931 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
934 return dividend
% divisor
;