1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999 Cygnus Solutions
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
19 #pragma implementation "gcj/array.h"
23 #include <java-signal.h>
24 #include <java-threads.h>
26 #ifndef DISABLE_GETENV_PROPERTIES
28 #include <java-props.h>
29 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
31 #define PROCESS_GCJ_PROPERTIES
32 #endif // DISABLE_GETENV_PROPERTIES
34 #include <java/lang/Class.h>
35 #include <java/lang/Runtime.h>
36 #include <java/lang/String.h>
37 #include <java/lang/Thread.h>
38 #include <java/lang/ThreadGroup.h>
39 #include <java/lang/FirstThread.h>
40 #include <java/lang/ArrayIndexOutOfBoundsException.h>
41 #include <java/lang/ArithmeticException.h>
42 #include <java/lang/ClassFormatError.h>
43 #include <java/lang/ClassCastException.h>
44 #include <java/lang/NegativeArraySizeException.h>
45 #include <java/lang/NullPointerException.h>
46 #include <java/lang/OutOfMemoryError.h>
47 #include <java/lang/ArrayStoreException.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
;
76 static java::lang::NullPointerException
*nullp
;
77 SIGNAL_HANDLER (catch_segv
)
84 static java::lang::ArithmeticException
*arithexception
;
87 SIGNAL_HANDLER (catch_fpe
)
89 #ifdef HANDLE_DIVIDE_OVERFLOW
90 HANDLE_DIVIDE_OVERFLOW
;
94 _Jv_Throw (arithexception
);
101 _Jv_equalUtf8Consts (Utf8Const
* a
, Utf8Const
*b
)
104 register _Jv_ushort
*aptr
, *bptr
;
107 if (a
->hash
!= b
->hash
)
110 if (b
->length
!= len
)
112 aptr
= (_Jv_ushort
*)a
->data
;
113 bptr
= (_Jv_ushort
*)b
->data
;
114 len
= (len
+ 1) >> 1;
116 if (*aptr
++ != *bptr
++)
121 /* True iff A is equal to STR.
122 HASH is STR->hashCode().
126 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
128 if (a
->hash
!= (_Jv_ushort
) hash
)
130 jint len
= str
->length();
132 jchar
*sptr
= _Jv_GetStringChars (str
);
133 register unsigned char* ptr
= (unsigned char*) a
->data
;
134 register unsigned char* limit
= ptr
+ a
->length
;
137 int ch
= UTF8_GET (ptr
, limit
);
146 /* Count the number of Unicode chars encoded in a given Ut8 string. */
148 _Jv_strLengthUtf8(char* str
, int len
)
150 register unsigned char* ptr
;
151 register unsigned char* limit
;
154 ptr
= (unsigned char*) str
;
157 for (; ptr
< limit
; str_length
++) {
158 if (UTF8_GET (ptr
, limit
) < 0) {
165 /* Calculate a hash value for a string encoded in Utf8 format.
166 * This returns the same hash value as specified or java.lang.String.hashCode.
169 hashUtf8String (char* str
, int len
)
171 register unsigned char* ptr
= (unsigned char*) str
;
172 register unsigned char* limit
= ptr
+ len
;
177 int ch
= UTF8_GET (ptr
, limit
);
178 /* Updated specification from
179 http://www.javasoft.com/docs/books/jls/clarify.html. */
180 hash
= (31 * hash
) + ch
;
186 _Jv_makeUtf8Const (char* s
, int len
)
190 Utf8Const
* m
= (Utf8Const
*) _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
193 memcpy (m
->data
, s
, len
);
196 m
->hash
= hashUtf8String (s
, len
) & 0xFFFF;
201 _Jv_makeUtf8Const (jstring string
)
203 jint hash
= string
->hashCode ();
204 jint len
= _Jv_GetStringUTFLength (string
);
206 Utf8Const
* m
= (Utf8Const
*)
207 _Jv_AllocBytesChecked (sizeof(Utf8Const
) + len
+ 1);
212 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
222 _Jv_Abort (const char *function
, const char *file
, int line
,
226 _Jv_Abort (const char *, const char *, int, const char *message
)
231 "libgcj failure: %s\n in function %s, file %s, line %d\n",
232 message
, function
, file
, line
);
234 java::io::PrintStream
*err
= java::lang::System::err
;
235 err
->print(JvNewStringLatin1 ("libgcj failure: "));
236 err
->println(JvNewStringLatin1 (message
));
243 fail_on_finalization (jobject
)
245 JvFail ("object was finalized");
249 _Jv_GCWatch (jobject obj
)
251 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
255 _Jv_ThrowBadArrayIndex(jint bad_index
)
257 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
258 (java::lang::String::valueOf(bad_index
)));
262 _Jv_CheckCast (jclass c
, jobject obj
)
264 if (obj
!= NULL
&& ! c
->isAssignableFrom(obj
->getClass()))
265 JvThrow (new java::lang::ClassCastException
);
270 _Jv_CheckArrayStore (jobject arr
, jobject obj
)
274 JvAssert (arr
!= NULL
);
275 jclass arr_class
= arr
->getClass();
276 JvAssert (arr_class
->isArray());
277 jclass elt_class
= arr_class
->getComponentType();
278 jclass obj_class
= obj
->getClass();
279 if (! elt_class
->isAssignableFrom(obj_class
))
280 JvThrow (new java::lang::ArrayStoreException
);
286 // Allocate some unscanned memory and throw an exception if no memory.
288 _Jv_AllocBytesChecked (jsize size
)
290 void *r
= _Jv_AllocBytes (size
);
292 _Jv_Throw (no_memory
);
296 // Allocate a new object of class C. SIZE is the size of the object
297 // to allocate. You might think this is redundant, but it isn't; some
298 // classes, such as String, aren't of fixed size.
300 _Jv_AllocObject (jclass c
, jint size
)
304 jobject obj
= (jobject
) _Jv_AllocObj (size
);
307 *((_Jv_VTable
**) obj
) = c
->vtable
;
309 // If this class has inherited finalize from Object, then don't
310 // bother registering a finalizer. We know that finalize() is the
311 // very first method after the dummy entry. If this turns out to be
312 // unreliable, a more robust implementation can be written. Such an
313 // implementation would look for Object.finalize in Object's method
314 // table at startup, and then use that information to find the
315 // appropriate index in the method vector.
316 if (c
->vtable
->method
[1] != ObjectClass
.vtable
->method
[1])
317 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
322 // Allocate a new array of Java objects. Each object is of type
323 // `elementClass'. `init' is used to initialize each slot in the
326 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
329 JvThrow (new java::lang::NegativeArraySizeException
);
331 // Check for overflow.
332 if ((size_t) count
> (SIZE_T_MAX
- sizeof (__JArray
)) / sizeof (jobject
))
335 size_t size
= count
* sizeof (jobject
) + sizeof (__JArray
);
337 // FIXME: second argument should be "current loader" //
338 jclass clas
= _Jv_FindArrayClass (elementClass
, 0);
340 jobjectArray obj
= (jobjectArray
) _Jv_AllocArray (size
);
344 jobject
* ptr
= elements(obj
);
345 // We know the allocator returns zeroed memory. So don't bother
352 // Set the vtbl last to avoid problems if the GC happens during the
353 // window in this function between the allocation and this
355 *((_Jv_VTable
**) obj
) = clas
->vtable
;
359 // Allocate a new array of primitives. ELTYPE is the type of the
360 // element, COUNT is the size of the array.
362 _Jv_NewPrimArray (jclass eltype
, jint count
)
364 int elsize
= eltype
->size();
366 JvThrow (new java::lang::NegativeArraySizeException ());
368 // Check for overflow.
369 if ((size_t) count
> (SIZE_T_MAX
- sizeof (__JArray
)) / elsize
)
372 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (sizeof (__JArray
)
377 // Note that we assume we are given zeroed memory by the allocator.
379 jclass klass
= _Jv_FindArrayClass (eltype
, 0);
380 // Set the vtbl last to avoid problems if the GC happens during the
381 // window in this function between the allocation and this
383 *((_Jv_VTable
**) arr
) = klass
->vtable
;
388 JvNewCharArray (jint length
)
390 return (jcharArray
) _Jv_NewPrimArray (JvPrimClass (char), length
);
394 JvNewBooleanArray (jint length
)
396 return (jbooleanArray
) _Jv_NewPrimArray (JvPrimClass (boolean
), length
);
400 JvNewByteArray (jint length
)
402 return (jbyteArray
) _Jv_NewPrimArray (JvPrimClass (byte
), length
);
406 JvNewShortArray (jint length
)
408 return (jshortArray
) _Jv_NewPrimArray (JvPrimClass (short), length
);
412 JvNewIntArray (jint length
)
414 return (jintArray
) _Jv_NewPrimArray (JvPrimClass (int), length
);
418 JvNewLongArray (jint length
)
420 return (jlongArray
) _Jv_NewPrimArray (JvPrimClass (long), length
);
424 JvNewFloatArray (jint length
)
426 return (jfloatArray
) _Jv_NewPrimArray (JvPrimClass (float), length
);
430 JvNewDoubleArray (jint length
)
432 return (jdoubleArray
) _Jv_NewPrimArray (JvPrimClass (double), length
);
436 _Jv_NewArray (jint type
, jint size
)
440 case 4: return JvNewBooleanArray (size
);
441 case 5: return JvNewCharArray (size
);
442 case 6: return JvNewFloatArray (size
);
443 case 7: return JvNewDoubleArray (size
);
444 case 8: return JvNewByteArray (size
);
445 case 9: return JvNewShortArray (size
);
446 case 10: return JvNewIntArray (size
);
447 case 11: return JvNewLongArray (size
);
449 JvFail ("newarray - bad type code");
450 return NULL
; // Placate compiler.
454 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
456 JvAssert (type
->isArray());
457 jclass element_type
= type
->getComponentType();
459 if (element_type
->isPrimitive())
460 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
462 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
466 JvAssert (! element_type
->isPrimitive());
467 JvAssert (element_type
->isArray());
468 jobject
*contents
= elements ((jobjectArray
) result
);
469 for (int i
= 0; i
< sizes
[0]; ++i
)
470 contents
[i
] = _Jv_NewMultiArray (element_type
, dimensions
- 1,
478 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
481 jint sizes
[dimensions
];
482 va_start (args
, dimensions
);
483 for (int i
= 0; i
< dimensions
; ++i
)
485 jint size
= va_arg (args
, jint
);
490 return _Jv_NewMultiArray (array_type
, dimensions
, sizes
);
495 class _Jv_PrimClass
: public java::lang::Class
498 // FIXME: calling convention is weird. If we use the natural types
499 // then the compiler will complain because they aren't Java types.
500 _Jv_PrimClass (jobject cname
, jbyte sig
, jint len
)
502 using namespace java::lang::reflect
;
504 // We must initialize every field of the class. We do this in
505 // the same order they are declared in Class.h.
507 name
= _Jv_makeUtf8Const ((char *) cname
, -1);
508 accflags
= Modifier::PUBLIC
| Modifier::FINAL
;
511 constants
.tags
= NULL
;
512 constants
.data
= NULL
;
515 vtable_method_count
= 0;
519 static_field_count
= 0;
520 vtable
= JV_PRIMITIVE_VTABLE
;
529 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
530 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
532 DECLARE_PRIM_TYPE(byte
, 'B', 1);
533 DECLARE_PRIM_TYPE(short, 'S', 2);
534 DECLARE_PRIM_TYPE(int, 'I', 4);
535 DECLARE_PRIM_TYPE(long, 'J', 8);
536 DECLARE_PRIM_TYPE(boolean
, 'Z', 1);
537 DECLARE_PRIM_TYPE(char, 'C', 2);
538 DECLARE_PRIM_TYPE(float, 'F', 4);
539 DECLARE_PRIM_TYPE(double, 'D', 8);
540 DECLARE_PRIM_TYPE(void, 'V', 0);
543 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
)
548 return JvPrimClass (byte
);
550 return JvPrimClass (short);
552 return JvPrimClass (int);
554 return JvPrimClass (long);
556 return JvPrimClass (boolean
);
558 return JvPrimClass (char);
560 return JvPrimClass (float);
562 return JvPrimClass (double);
564 return JvPrimClass (void);
568 for (i
= 1; sig
[i
] && sig
[i
] != ';'; ++i
)
570 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (&sig
[1], i
- 1);
571 return _Jv_FindClass (name
, loader
);
575 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig
[1], loader
),
578 JvFail ("couldn't understand class signature");
579 return NULL
; // Placate compiler.
585 JvConvertArgv (int argc
, const char **argv
)
589 jobjectArray ar
= JvNewObjectArray(argc
, &StringClass
, NULL
);
590 jobject
* ptr
= elements(ar
);
591 for (int i
= 0; i
< argc
; i
++)
593 const char *arg
= argv
[i
];
594 // FIXME - should probably use JvNewStringUTF.
595 *ptr
++ = JvNewStringLatin1(arg
, strlen(arg
));
597 return (JArray
<jstring
>*) ar
;
600 // FIXME: These variables are static so that they will be
601 // automatically scanned by the Boehm collector. This is needed
602 // because with qthreads the collector won't scan the initial stack --
603 // it will only scan the qthreads stacks.
605 // Command line arguments.
606 static jobject arg_vec
;
608 // The primary threadgroup.
609 static java::lang::ThreadGroup
*main_group
;
611 // The primary thread.
612 static java::lang::Thread
*main_thread
;
621 arithexception
= new java::lang::ArithmeticException
622 (JvNewStringLatin1 ("/ by zero"));
625 no_memory
= new java::lang::OutOfMemoryError
;
628 LTDL_SET_PRELOADED_SYMBOLS ();
631 // FIXME: we only want this on POSIX systems.
632 struct sigaction act
;
633 act
.sa_handler
= SIG_IGN
;
634 sigemptyset (&act
.sa_mask
);
636 sigaction (SIGPIPE
, &act
, NULL
);
639 #ifndef DISABLE_GETENV_PROPERTIES
642 next_property_key (char *s
, size_t *length
)
648 // Skip over whitespace
652 // If we've reached the end, return NULL. Also return NULL if for
653 // some reason we've come across a malformed property string.
659 // Determine the length of the property key.
677 next_property_value (char *s
, size_t *length
)
693 // If we've reached the end, return NULL.
697 // Determine the length of the property value.
716 process_gcj_properties ()
718 char *props
= getenv("GCJ_PROPERTIES");
721 size_t property_count
= 0;
726 // Whip through props quickly in order to count the number of
728 while (p
&& (p
= next_property_key (p
, &length
)))
730 // Skip to the end of the key
733 p
= next_property_value (p
, &length
);
740 // Allocate an array of property value/key pairs.
741 _Jv_Environment_Properties
=
742 (property_pair
*) malloc (sizeof(property_pair
)
743 * (property_count
+ 1));
745 // Go through the properties again, initializing _Jv_Properties
749 while (p
&& (p
= next_property_key (p
, &length
)))
751 _Jv_Environment_Properties
[property_count
].key
= p
;
752 _Jv_Environment_Properties
[property_count
].key_length
= length
;
754 // Skip to the end of the key
757 p
= next_property_value (p
, &length
);
759 _Jv_Environment_Properties
[property_count
].value
= p
;
760 _Jv_Environment_Properties
[property_count
].value_length
= length
;
767 memset ((void *) &_Jv_Environment_Properties
[property_count
],
768 0, sizeof (property_pair
));
772 // Null terminate the strings.
773 while (_Jv_Environment_Properties
[i
].key
)
775 _Jv_Environment_Properties
[i
].key
[_Jv_Environment_Properties
[i
].key_length
] = 0;
776 _Jv_Environment_Properties
[i
++].value
[_Jv_Environment_Properties
[i
].value_length
] = 0;
780 #endif // DISABLE_GETENV_PROPERTIES
783 JvRunMain (jclass klass
, int argc
, const char **argv
)
785 PROCESS_GCJ_PROPERTIES
;
789 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
790 main_group
= new java::lang::ThreadGroup (23);
791 main_thread
= new java::lang::FirstThread (main_group
, klass
, arg_vec
);
793 main_thread
->start();
796 java::lang::Runtime::getRuntime ()->exit (0);
800 _Jv_RunMain (const char *class_name
, int argc
, const char **argv
)
802 PROCESS_GCJ_PROPERTIES
;
806 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
807 main_group
= new java::lang::ThreadGroup (23);
808 main_thread
= new java::lang::FirstThread (main_group
,
809 JvNewStringLatin1 (class_name
),
811 main_thread
->start();
814 java::lang::Runtime::getRuntime ()->exit (0);
819 // Parse a string and return a heap size.
821 parse_heap_size (const char *spec
)
824 unsigned long val
= strtoul (spec
, &end
, 10);
825 if (*spec
== 'k' || *spec
== 'K')
827 else if (*spec
== 'm' || *spec
== 'M')
832 // Set the initial heap size. This might be ignored by the GC layer.
833 // This must be called before _Jv_RunMain.
835 _Jv_SetInitialHeapSize (const char *arg
)
837 size_t size
= parse_heap_size (arg
);
838 _Jv_GCSetInitialHeapSize (size
);
841 // Set the maximum heap size. This might be ignored by the GC layer.
842 // This must be called before _Jv_RunMain.
844 _Jv_SetMaximumHeapSize (const char *arg
)
846 size_t size
= parse_heap_size (arg
);
847 _Jv_GCSetMaximumHeapSize (size
);
853 _Jv_Malloc (jsize size
)
857 void *ptr
= malloc ((size_t) size
);
871 // In theory, these routines can be #ifdef'd away on machines which
872 // support divide overflow signals. However, we never know if some
873 // code might have been compiled with "-fuse-divide-subroutine", so we
874 // always include them in libgcj.
877 _Jv_divI (jint dividend
, jint divisor
)
880 _Jv_Throw (arithexception
);
882 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
885 return dividend
/ divisor
;
889 _Jv_remI (jint dividend
, jint divisor
)
892 _Jv_Throw (arithexception
);
894 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
897 return dividend
% divisor
;
901 _Jv_divJ (jlong dividend
, jlong divisor
)
904 _Jv_Throw (arithexception
);
906 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
909 return dividend
/ divisor
;
913 _Jv_remJ (jlong dividend
, jlong divisor
)
916 _Jv_Throw (arithexception
);
918 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
921 return dividend
% divisor
;