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 JvAssert (! elementClass
->isPrimitive ());
333 jobjectArray obj
= NULL
;
334 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (obj
,
337 // Check for overflow.
338 if ((size_t) count
> (SIZE_T_MAX
- size
) / sizeof (jobject
))
341 size
+= count
* sizeof (jobject
);
343 // FIXME: second argument should be "current loader" //
344 jclass clas
= _Jv_FindArrayClass (elementClass
, 0);
346 obj
= (jobjectArray
) _Jv_AllocArray (size
);
350 jobject
* ptr
= elements(obj
);
351 // We know the allocator returns zeroed memory. So don't bother
358 // Set the vtbl last to avoid problems if the GC happens during the
359 // window in this function between the allocation and this
361 *((_Jv_VTable
**) obj
) = clas
->vtable
;
365 // Allocate a new array of primitives. ELTYPE is the type of the
366 // element, COUNT is the size of the array.
368 _Jv_NewPrimArray (jclass eltype
, jint count
)
370 int elsize
= eltype
->size();
372 JvThrow (new java::lang::NegativeArraySizeException ());
374 JvAssert (eltype
->isPrimitive ());
375 jobject dummy
= NULL
;
376 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
378 // Check for overflow.
379 if ((size_t) count
> (SIZE_T_MAX
- size
) / elsize
)
382 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
);
386 // Note that we assume we are given zeroed memory by the allocator.
388 jclass klass
= _Jv_FindArrayClass (eltype
, 0);
389 // Set the vtbl last to avoid problems if the GC happens during the
390 // window in this function between the allocation and this
392 *((_Jv_VTable
**) arr
) = klass
->vtable
;
397 JvNewCharArray (jint length
)
399 return (jcharArray
) _Jv_NewPrimArray (JvPrimClass (char), length
);
403 JvNewBooleanArray (jint length
)
405 return (jbooleanArray
) _Jv_NewPrimArray (JvPrimClass (boolean
), length
);
409 JvNewByteArray (jint length
)
411 return (jbyteArray
) _Jv_NewPrimArray (JvPrimClass (byte
), length
);
415 JvNewShortArray (jint length
)
417 return (jshortArray
) _Jv_NewPrimArray (JvPrimClass (short), length
);
421 JvNewIntArray (jint length
)
423 return (jintArray
) _Jv_NewPrimArray (JvPrimClass (int), length
);
427 JvNewLongArray (jint length
)
429 return (jlongArray
) _Jv_NewPrimArray (JvPrimClass (long), length
);
433 JvNewFloatArray (jint length
)
435 return (jfloatArray
) _Jv_NewPrimArray (JvPrimClass (float), length
);
439 JvNewDoubleArray (jint length
)
441 return (jdoubleArray
) _Jv_NewPrimArray (JvPrimClass (double), length
);
445 _Jv_NewArray (jint type
, jint size
)
449 case 4: return JvNewBooleanArray (size
);
450 case 5: return JvNewCharArray (size
);
451 case 6: return JvNewFloatArray (size
);
452 case 7: return JvNewDoubleArray (size
);
453 case 8: return JvNewByteArray (size
);
454 case 9: return JvNewShortArray (size
);
455 case 10: return JvNewIntArray (size
);
456 case 11: return JvNewLongArray (size
);
458 JvFail ("newarray - bad type code");
459 return NULL
; // Placate compiler.
463 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
465 JvAssert (type
->isArray());
466 jclass element_type
= type
->getComponentType();
468 if (element_type
->isPrimitive())
469 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
471 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
475 JvAssert (! element_type
->isPrimitive());
476 JvAssert (element_type
->isArray());
477 jobject
*contents
= elements ((jobjectArray
) result
);
478 for (int i
= 0; i
< sizes
[0]; ++i
)
479 contents
[i
] = _Jv_NewMultiArray (element_type
, dimensions
- 1,
487 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
490 jint sizes
[dimensions
];
491 va_start (args
, dimensions
);
492 for (int i
= 0; i
< dimensions
; ++i
)
494 jint size
= va_arg (args
, jint
);
499 return _Jv_NewMultiArray (array_type
, dimensions
, sizes
);
504 class _Jv_PrimClass
: public java::lang::Class
507 // FIXME: calling convention is weird. If we use the natural types
508 // then the compiler will complain because they aren't Java types.
509 _Jv_PrimClass (jobject cname
, jbyte sig
, jint len
)
511 using namespace java::lang::reflect
;
513 // We must initialize every field of the class. We do this in
514 // the same order they are declared in Class.h.
516 name
= _Jv_makeUtf8Const ((char *) cname
, -1);
517 accflags
= Modifier::PUBLIC
| Modifier::FINAL
;
520 constants
.tags
= NULL
;
521 constants
.data
= NULL
;
524 vtable_method_count
= 0;
528 static_field_count
= 0;
529 vtable
= JV_PRIMITIVE_VTABLE
;
538 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
539 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
541 DECLARE_PRIM_TYPE(byte
, 'B', 1);
542 DECLARE_PRIM_TYPE(short, 'S', 2);
543 DECLARE_PRIM_TYPE(int, 'I', 4);
544 DECLARE_PRIM_TYPE(long, 'J', 8);
545 DECLARE_PRIM_TYPE(boolean
, 'Z', 1);
546 DECLARE_PRIM_TYPE(char, 'C', 2);
547 DECLARE_PRIM_TYPE(float, 'F', 4);
548 DECLARE_PRIM_TYPE(double, 'D', 8);
549 DECLARE_PRIM_TYPE(void, 'V', 0);
552 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
)
557 return JvPrimClass (byte
);
559 return JvPrimClass (short);
561 return JvPrimClass (int);
563 return JvPrimClass (long);
565 return JvPrimClass (boolean
);
567 return JvPrimClass (char);
569 return JvPrimClass (float);
571 return JvPrimClass (double);
573 return JvPrimClass (void);
577 for (i
= 1; sig
[i
] && sig
[i
] != ';'; ++i
)
579 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (&sig
[1], i
- 1);
580 return _Jv_FindClass (name
, loader
);
584 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig
[1], loader
),
587 JvFail ("couldn't understand class signature");
588 return NULL
; // Placate compiler.
594 JvConvertArgv (int argc
, const char **argv
)
598 jobjectArray ar
= JvNewObjectArray(argc
, &StringClass
, NULL
);
599 jobject
* ptr
= elements(ar
);
600 for (int i
= 0; i
< argc
; i
++)
602 const char *arg
= argv
[i
];
603 // FIXME - should probably use JvNewStringUTF.
604 *ptr
++ = JvNewStringLatin1(arg
, strlen(arg
));
606 return (JArray
<jstring
>*) ar
;
609 // FIXME: These variables are static so that they will be
610 // automatically scanned by the Boehm collector. This is needed
611 // because with qthreads the collector won't scan the initial stack --
612 // it will only scan the qthreads stacks.
614 // Command line arguments.
615 static jobject arg_vec
;
617 // The primary threadgroup.
618 static java::lang::ThreadGroup
*main_group
;
620 // The primary thread.
621 static java::lang::Thread
*main_thread
;
630 arithexception
= new java::lang::ArithmeticException
631 (JvNewStringLatin1 ("/ by zero"));
634 no_memory
= new java::lang::OutOfMemoryError
;
637 LTDL_SET_PRELOADED_SYMBOLS ();
640 // FIXME: we only want this on POSIX systems.
641 struct sigaction act
;
642 act
.sa_handler
= SIG_IGN
;
643 sigemptyset (&act
.sa_mask
);
645 sigaction (SIGPIPE
, &act
, NULL
);
648 #ifndef DISABLE_GETENV_PROPERTIES
651 next_property_key (char *s
, size_t *length
)
657 // Skip over whitespace
661 // If we've reached the end, return NULL. Also return NULL if for
662 // some reason we've come across a malformed property string.
668 // Determine the length of the property key.
686 next_property_value (char *s
, size_t *length
)
702 // If we've reached the end, return NULL.
706 // Determine the length of the property value.
725 process_gcj_properties ()
727 char *props
= getenv("GCJ_PROPERTIES");
730 size_t property_count
= 0;
735 // Whip through props quickly in order to count the number of
737 while (p
&& (p
= next_property_key (p
, &length
)))
739 // Skip to the end of the key
742 p
= next_property_value (p
, &length
);
749 // Allocate an array of property value/key pairs.
750 _Jv_Environment_Properties
=
751 (property_pair
*) malloc (sizeof(property_pair
)
752 * (property_count
+ 1));
754 // Go through the properties again, initializing _Jv_Properties
758 while (p
&& (p
= next_property_key (p
, &length
)))
760 _Jv_Environment_Properties
[property_count
].key
= p
;
761 _Jv_Environment_Properties
[property_count
].key_length
= length
;
763 // Skip to the end of the key
766 p
= next_property_value (p
, &length
);
768 _Jv_Environment_Properties
[property_count
].value
= p
;
769 _Jv_Environment_Properties
[property_count
].value_length
= length
;
776 memset ((void *) &_Jv_Environment_Properties
[property_count
],
777 0, sizeof (property_pair
));
781 // Null terminate the strings.
782 while (_Jv_Environment_Properties
[i
].key
)
784 _Jv_Environment_Properties
[i
].key
[_Jv_Environment_Properties
[i
].key_length
] = 0;
785 _Jv_Environment_Properties
[i
++].value
[_Jv_Environment_Properties
[i
].value_length
] = 0;
789 #endif // DISABLE_GETENV_PROPERTIES
792 JvRunMain (jclass klass
, int argc
, const char **argv
)
794 PROCESS_GCJ_PROPERTIES
;
798 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
799 main_group
= new java::lang::ThreadGroup (23);
800 main_thread
= new java::lang::FirstThread (main_group
, klass
, arg_vec
);
802 main_thread
->start();
805 java::lang::Runtime::getRuntime ()->exit (0);
809 _Jv_RunMain (const char *class_name
, int argc
, const char **argv
)
811 PROCESS_GCJ_PROPERTIES
;
815 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
816 main_group
= new java::lang::ThreadGroup (23);
817 main_thread
= new java::lang::FirstThread (main_group
,
818 JvNewStringLatin1 (class_name
),
820 main_thread
->start();
823 java::lang::Runtime::getRuntime ()->exit (0);
828 // Parse a string and return a heap size.
830 parse_heap_size (const char *spec
)
833 unsigned long val
= strtoul (spec
, &end
, 10);
834 if (*end
== 'k' || *end
== 'K')
836 else if (*end
== 'm' || *end
== 'M')
841 // Set the initial heap size. This might be ignored by the GC layer.
842 // This must be called before _Jv_RunMain.
844 _Jv_SetInitialHeapSize (const char *arg
)
846 size_t size
= parse_heap_size (arg
);
847 _Jv_GCSetInitialHeapSize (size
);
850 // Set the maximum heap size. This might be ignored by the GC layer.
851 // This must be called before _Jv_RunMain.
853 _Jv_SetMaximumHeapSize (const char *arg
)
855 size_t size
= parse_heap_size (arg
);
856 _Jv_GCSetMaximumHeapSize (size
);
862 _Jv_Malloc (jsize size
)
866 void *ptr
= malloc ((size_t) size
);
880 // In theory, these routines can be #ifdef'd away on machines which
881 // support divide overflow signals. However, we never know if some
882 // code might have been compiled with "-fuse-divide-subroutine", so we
883 // always include them in libgcj.
886 _Jv_divI (jint dividend
, jint divisor
)
889 _Jv_Throw (arithexception
);
891 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
894 return dividend
/ divisor
;
898 _Jv_remI (jint dividend
, jint divisor
)
901 _Jv_Throw (arithexception
);
903 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
906 return dividend
% divisor
;
910 _Jv_divJ (jlong dividend
, jlong divisor
)
913 _Jv_Throw (arithexception
);
915 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
918 return dividend
/ divisor
;
922 _Jv_remJ (jlong dividend
, jlong divisor
)
925 _Jv_Throw (arithexception
);
927 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
930 return dividend
% divisor
;