1 // prims.cc - Code for core of runtime environment.
3 /* Copyright (C) 1998, 1999, 2000 Free Software Foundation
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
13 #ifdef USE_WIN32_SIGNALLING
15 #endif /* USE_WIN32_SIGNALLING */
18 #undef __INSIDE_CYGWIN__
20 #endif /* USE_WINSOCK */
34 #include <java-signal.h>
35 #include <java-threads.h>
41 #ifndef DISABLE_GETENV_PROPERTIES
43 #include <java-props.h>
44 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
46 #define PROCESS_GCJ_PROPERTIES
47 #endif // DISABLE_GETENV_PROPERTIES
49 #include <java/lang/Class.h>
50 #include <java/lang/Runtime.h>
51 #include <java/lang/String.h>
52 #include <java/lang/Thread.h>
53 #include <java/lang/ThreadGroup.h>
54 #include <gnu/gcj/runtime/FirstThread.h>
55 #include <java/lang/ArrayIndexOutOfBoundsException.h>
56 #include <java/lang/ArithmeticException.h>
57 #include <java/lang/ClassFormatError.h>
58 #include <java/lang/NegativeArraySizeException.h>
59 #include <java/lang/NullPointerException.h>
60 #include <java/lang/OutOfMemoryError.h>
61 #include <java/lang/System.h>
62 #include <java/lang/reflect/Modifier.h>
63 #include <java/io/PrintStream.h>
69 #define ObjectClass _CL_Q34java4lang6Object
70 extern java::lang::Class ObjectClass
;
72 // We allocate a single OutOfMemoryError exception which we keep
73 // around for use if we run out of memory.
74 static java::lang::OutOfMemoryError
*no_memory
;
76 // Largest representable size_t.
77 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
79 // Properties set at compile time.
80 const char **_Jv_Compiler_Properties
;
82 #ifndef DISABLE_GETENV_PROPERTIES
83 // Property key/value pairs.
84 property_pair
*_Jv_Environment_Properties
;
87 // The name of this executable.
88 static char * _Jv_execName
;
91 // Pointer to JVMPI notification functions.
92 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (JVMPI_Event
*event
);
93 void (*_Jv_JVMPI_Notify_THREAD_START
) (JVMPI_Event
*event
);
94 void (*_Jv_JVMPI_Notify_THREAD_END
) (JVMPI_Event
*event
);
99 static java::lang::NullPointerException
*nullp
;
100 SIGNAL_HANDLER (catch_segv
)
103 nullp
->fillInStackTrace ();
108 static java::lang::ArithmeticException
*arithexception
;
111 SIGNAL_HANDLER (catch_fpe
)
113 #ifdef HANDLE_DIVIDE_OVERFLOW
114 HANDLE_DIVIDE_OVERFLOW
;
118 arithexception
->fillInStackTrace ();
119 _Jv_Throw (arithexception
);
126 _Jv_equalUtf8Consts (Utf8Const
* a
, Utf8Const
*b
)
129 register _Jv_ushort
*aptr
, *bptr
;
132 if (a
->hash
!= b
->hash
)
135 if (b
->length
!= len
)
137 aptr
= (_Jv_ushort
*)a
->data
;
138 bptr
= (_Jv_ushort
*)b
->data
;
139 len
= (len
+ 1) >> 1;
141 if (*aptr
++ != *bptr
++)
146 /* True iff A is equal to STR.
147 HASH is STR->hashCode().
151 _Jv_equal (Utf8Const
* a
, jstring str
, jint hash
)
153 if (a
->hash
!= (_Jv_ushort
) hash
)
155 jint len
= str
->length();
157 jchar
*sptr
= _Jv_GetStringChars (str
);
158 register unsigned char* ptr
= (unsigned char*) a
->data
;
159 register unsigned char* limit
= ptr
+ a
->length
;
162 int ch
= UTF8_GET (ptr
, limit
);
171 /* Like _Jv_equal, but stop after N characters. */
173 _Jv_equaln (Utf8Const
*a
, jstring str
, jint n
)
175 jint len
= str
->length();
177 jchar
*sptr
= _Jv_GetStringChars (str
);
178 register unsigned char* ptr
= (unsigned char*) a
->data
;
179 register unsigned char* limit
= ptr
+ a
->length
;
180 for (; n
-- > 0; i
++, sptr
++)
182 int ch
= UTF8_GET (ptr
, limit
);
191 /* Count the number of Unicode chars encoded in a given Ut8 string. */
193 _Jv_strLengthUtf8(char* str
, int len
)
195 register unsigned char* ptr
;
196 register unsigned char* limit
;
199 ptr
= (unsigned char*) str
;
202 for (; ptr
< limit
; str_length
++) {
203 if (UTF8_GET (ptr
, limit
) < 0) {
210 /* Calculate a hash value for a string encoded in Utf8 format.
211 * This returns the same hash value as specified or java.lang.String.hashCode.
214 hashUtf8String (char* str
, int len
)
216 register unsigned char* ptr
= (unsigned char*) str
;
217 register unsigned char* limit
= ptr
+ len
;
222 int ch
= UTF8_GET (ptr
, limit
);
223 /* Updated specification from
224 http://www.javasoft.com/docs/books/jls/clarify.html. */
225 hash
= (31 * hash
) + ch
;
231 _Jv_makeUtf8Const (char* s
, int len
)
235 Utf8Const
* m
= (Utf8Const
*) _Jv_AllocBytes (sizeof(Utf8Const
) + len
+ 1);
238 memcpy (m
->data
, s
, len
);
241 m
->hash
= hashUtf8String (s
, len
) & 0xFFFF;
246 _Jv_makeUtf8Const (jstring string
)
248 jint hash
= string
->hashCode ();
249 jint len
= _Jv_GetStringUTFLength (string
);
251 Utf8Const
* m
= (Utf8Const
*)
252 _Jv_AllocBytesChecked (sizeof(Utf8Const
) + len
+ 1);
257 _Jv_GetStringUTFRegion (string
, 0, string
->length (), m
->data
);
267 _Jv_Abort (const char *function
, const char *file
, int line
,
271 _Jv_Abort (const char *, const char *, int, const char *message
)
276 "libgcj failure: %s\n in function %s, file %s, line %d\n",
277 message
, function
, file
, line
);
279 java::io::PrintStream
*err
= java::lang::System::err
;
280 err
->print(JvNewStringLatin1 ("libgcj failure: "));
281 err
->println(JvNewStringLatin1 (message
));
288 fail_on_finalization (jobject
)
290 JvFail ("object was finalized");
294 _Jv_GCWatch (jobject obj
)
296 _Jv_RegisterFinalizer (obj
, fail_on_finalization
);
300 _Jv_ThrowBadArrayIndex(jint bad_index
)
302 JvThrow (new java::lang::ArrayIndexOutOfBoundsException
303 (java::lang::String::valueOf(bad_index
)));
306 // Allocate some unscanned memory and throw an exception if no memory.
308 _Jv_AllocBytesChecked (jsize size
)
310 void *r
= _Jv_AllocBytes (size
);
312 _Jv_Throw (no_memory
);
316 // Allocate a new object of class C. SIZE is the size of the object
317 // to allocate. You might think this is redundant, but it isn't; some
318 // classes, such as String, aren't of fixed size.
320 _Jv_AllocObject (jclass c
, jint size
)
324 jobject obj
= (jobject
) _Jv_AllocObj (size
);
327 *((_Jv_VTable
**) obj
) = c
->vtable
;
329 // If this class has inherited finalize from Object, then don't
330 // bother registering a finalizer. We know that finalize() is the
331 // very first method after the dummy entry. If this turns out to be
332 // unreliable, a more robust implementation can be written. Such an
333 // implementation would look for Object.finalize in Object's method
334 // table at startup, and then use that information to find the
335 // appropriate index in the method vector.
336 if (c
->vtable
->method
[1] != ObjectClass
.vtable
->method
[1])
337 _Jv_RegisterFinalizer (obj
, _Jv_FinalizeObject
);
340 // Service JVMPI request.
342 if (_Jv_JVMPI_Notify_OBJECT_ALLOC
)
346 event
.event_type
= JVMPI_EVENT_OBJECT_ALLOC
;
348 event
.u
.obj_alloc
.arena_id
= 0;
349 event
.u
.obj_alloc
.class_id
= (jobjectID
) c
;
350 event
.u
.obj_alloc
.is_array
= 0;
351 event
.u
.obj_alloc
.size
= size
;
352 event
.u
.obj_alloc
.obj_id
= (jobjectID
) obj
;
355 (*_Jv_JVMPI_Notify_OBJECT_ALLOC
) (&event
);
363 // Allocate a new array of Java objects. Each object is of type
364 // `elementClass'. `init' is used to initialize each slot in the
367 _Jv_NewObjectArray (jsize count
, jclass elementClass
, jobject init
)
370 JvThrow (new java::lang::NegativeArraySizeException
);
372 JvAssert (! elementClass
->isPrimitive ());
374 jobjectArray obj
= NULL
;
375 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (obj
,
378 // Check for overflow.
379 if ((size_t) count
> (SIZE_T_MAX
- size
) / sizeof (jobject
))
382 size
+= count
* sizeof (jobject
);
384 // FIXME: second argument should be "current loader" //
385 jclass clas
= _Jv_FindArrayClass (elementClass
, 0);
387 obj
= (jobjectArray
) _Jv_AllocArray (size
);
391 jobject
* ptr
= elements(obj
);
392 // We know the allocator returns zeroed memory. So don't bother
399 // Set the vtbl last to avoid problems if the GC happens during the
400 // window in this function between the allocation and this
402 *((_Jv_VTable
**) obj
) = clas
->vtable
;
406 // Allocate a new array of primitives. ELTYPE is the type of the
407 // element, COUNT is the size of the array.
409 _Jv_NewPrimArray (jclass eltype
, jint count
)
411 int elsize
= eltype
->size();
413 JvThrow (new java::lang::NegativeArraySizeException ());
415 JvAssert (eltype
->isPrimitive ());
416 jobject dummy
= NULL
;
417 size_t size
= (size_t) _Jv_GetArrayElementFromElementType (dummy
, eltype
);
419 // Check for overflow.
420 if ((size_t) count
> (SIZE_T_MAX
- size
) / elsize
)
423 __JArray
*arr
= (__JArray
*) _Jv_AllocObj (size
+ elsize
* count
);
427 // Note that we assume we are given zeroed memory by the allocator.
429 jclass klass
= _Jv_FindArrayClass (eltype
, 0);
430 // Set the vtbl last to avoid problems if the GC happens during the
431 // window in this function between the allocation and this
433 *((_Jv_VTable
**) arr
) = klass
->vtable
;
438 _Jv_NewArray (jint type
, jint size
)
442 case 4: return JvNewBooleanArray (size
);
443 case 5: return JvNewCharArray (size
);
444 case 6: return JvNewFloatArray (size
);
445 case 7: return JvNewDoubleArray (size
);
446 case 8: return JvNewByteArray (size
);
447 case 9: return JvNewShortArray (size
);
448 case 10: return JvNewIntArray (size
);
449 case 11: return JvNewLongArray (size
);
451 JvFail ("newarray - bad type code");
452 return NULL
; // Placate compiler.
456 _Jv_NewMultiArray (jclass type
, jint dimensions
, jint
*sizes
)
458 JvAssert (type
->isArray());
459 jclass element_type
= type
->getComponentType();
461 if (element_type
->isPrimitive())
462 result
= _Jv_NewPrimArray (element_type
, sizes
[0]);
464 result
= _Jv_NewObjectArray (sizes
[0], element_type
, NULL
);
468 JvAssert (! element_type
->isPrimitive());
469 JvAssert (element_type
->isArray());
470 jobject
*contents
= elements ((jobjectArray
) result
);
471 for (int i
= 0; i
< sizes
[0]; ++i
)
472 contents
[i
] = _Jv_NewMultiArray (element_type
, dimensions
- 1,
480 _Jv_NewMultiArray (jclass array_type
, jint dimensions
, ...)
483 jint sizes
[dimensions
];
484 va_start (args
, dimensions
);
485 for (int i
= 0; i
< dimensions
; ++i
)
487 jint size
= va_arg (args
, jint
);
492 return _Jv_NewMultiArray (array_type
, dimensions
, sizes
);
497 class _Jv_PrimClass
: public java::lang::Class
500 // FIXME: calling convention is weird. If we use the natural types
501 // then the compiler will complain because they aren't Java types.
502 _Jv_PrimClass (jobject cname
, jbyte sig
, jint len
)
504 using namespace java::lang::reflect
;
506 // We must initialize every field of the class. We do this in
507 // the same order they are declared in Class.h.
509 name
= _Jv_makeUtf8Const ((char *) cname
, -1);
510 accflags
= Modifier::PUBLIC
| Modifier::FINAL
;
513 constants
.tags
= NULL
;
514 constants
.data
= NULL
;
517 vtable_method_count
= 0;
521 static_field_count
= 0;
522 vtable
= JV_PRIMITIVE_VTABLE
;
526 state
= JV_STATE_NOTHING
;
531 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
532 _Jv_PrimClass _Jv_##NAME##Class((jobject) #NAME, (jbyte) SIG, (jint) LEN)
534 DECLARE_PRIM_TYPE(byte
, 'B', 1);
535 DECLARE_PRIM_TYPE(short, 'S', 2);
536 DECLARE_PRIM_TYPE(int, 'I', 4);
537 DECLARE_PRIM_TYPE(long, 'J', 8);
538 DECLARE_PRIM_TYPE(boolean
, 'Z', 1);
539 DECLARE_PRIM_TYPE(char, 'C', 2);
540 DECLARE_PRIM_TYPE(float, 'F', 4);
541 DECLARE_PRIM_TYPE(double, 'D', 8);
542 DECLARE_PRIM_TYPE(void, 'V', 0);
545 _Jv_FindClassFromSignature (char *sig
, java::lang::ClassLoader
*loader
)
550 return JvPrimClass (byte
);
552 return JvPrimClass (short);
554 return JvPrimClass (int);
556 return JvPrimClass (long);
558 return JvPrimClass (boolean
);
560 return JvPrimClass (char);
562 return JvPrimClass (float);
564 return JvPrimClass (double);
566 return JvPrimClass (void);
570 for (i
= 1; sig
[i
] && sig
[i
] != ';'; ++i
)
572 _Jv_Utf8Const
*name
= _Jv_makeUtf8Const (&sig
[1], i
- 1);
573 return _Jv_FindClass (name
, loader
);
577 return _Jv_FindArrayClass (_Jv_FindClassFromSignature (&sig
[1], loader
),
580 JvFail ("couldn't understand class signature");
581 return NULL
; // Placate compiler.
587 JvConvertArgv (int argc
, const char **argv
)
591 jobjectArray ar
= JvNewObjectArray(argc
, &StringClass
, NULL
);
592 jobject
* ptr
= elements(ar
);
593 for (int i
= 0; i
< argc
; i
++)
595 const char *arg
= argv
[i
];
596 // FIXME - should probably use JvNewStringUTF.
597 *ptr
++ = JvNewStringLatin1(arg
, strlen(arg
));
599 return (JArray
<jstring
>*) ar
;
602 // FIXME: These variables are static so that they will be
603 // automatically scanned by the Boehm collector. This is needed
604 // because with qthreads the collector won't scan the initial stack --
605 // it will only scan the qthreads stacks.
607 // Command line arguments.
608 static jobject arg_vec
;
610 // The primary threadgroup.
611 static java::lang::ThreadGroup
*main_group
;
613 // The primary thread.
614 static java::lang::Thread
*main_thread
;
617 _Jv_ThisExecutable (void)
623 _Jv_ThisExecutable (const char *name
)
627 _Jv_execName
= new char[strlen (name
) + 1];
628 strcpy (_Jv_execName
, name
);
632 #ifdef USE_WIN32_SIGNALLING
634 extern "C" int* win32_get_restart_frame (void *);
637 win32_exception_handler (LPEXCEPTION_POINTERS e
)
640 if (e
->ExceptionRecord
->ExceptionCode
== EXCEPTION_ACCESS_VIOLATION
)
641 setjmp_buf
= win32_get_restart_frame (nullp
);
642 else if (e
->ExceptionRecord
->ExceptionCode
== EXCEPTION_INT_DIVIDE_BY_ZERO
)
643 setjmp_buf
= win32_get_restart_frame (arithexception
);
645 return EXCEPTION_CONTINUE_SEARCH
;
647 e
->ContextRecord
->Ebp
= setjmp_buf
[0];
648 // FIXME: Why does i386-signal.h increment the PC here, do we need to do it?
649 e
->ContextRecord
->Eip
= setjmp_buf
[1];
650 // FIXME: Is this the stack pointer? Do we need it?
651 e
->ContextRecord
->Esp
= setjmp_buf
[2];
653 return EXCEPTION_CONTINUE_EXECUTION
;
665 arithexception
= new java::lang::ArithmeticException
666 (JvNewStringLatin1 ("/ by zero"));
669 no_memory
= new java::lang::OutOfMemoryError
;
672 LTDL_SET_PRELOADED_SYMBOLS ();
676 // Initialise winsock for networking
678 if (WSAStartup (MAKEWORD (1, 1), &data
))
679 MessageBox (NULL
, "Error initialising winsock library.", "Error", MB_OK
| MB_ICONEXCLAMATION
);
680 #endif /* USE_WINSOCK */
682 #ifdef USE_WIN32_SIGNALLING
683 // Install exception handler
684 SetUnhandledExceptionFilter (win32_exception_handler
);
686 // We only want this on POSIX systems.
687 struct sigaction act
;
688 act
.sa_handler
= SIG_IGN
;
689 sigemptyset (&act
.sa_mask
);
691 sigaction (SIGPIPE
, &act
, NULL
);
692 #endif /* USE_WIN32_SIGNALLING */
697 #ifndef DISABLE_GETENV_PROPERTIES
700 next_property_key (char *s
, size_t *length
)
706 // Skip over whitespace
710 // If we've reached the end, return NULL. Also return NULL if for
711 // some reason we've come across a malformed property string.
717 // Determine the length of the property key.
735 next_property_value (char *s
, size_t *length
)
751 // If we've reached the end, return NULL.
755 // Determine the length of the property value.
774 process_gcj_properties ()
776 char *props
= getenv("GCJ_PROPERTIES");
779 size_t property_count
= 0;
784 // Whip through props quickly in order to count the number of
786 while (p
&& (p
= next_property_key (p
, &length
)))
788 // Skip to the end of the key
791 p
= next_property_value (p
, &length
);
798 // Allocate an array of property value/key pairs.
799 _Jv_Environment_Properties
=
800 (property_pair
*) malloc (sizeof(property_pair
)
801 * (property_count
+ 1));
803 // Go through the properties again, initializing _Jv_Properties
807 while (p
&& (p
= next_property_key (p
, &length
)))
809 _Jv_Environment_Properties
[property_count
].key
= p
;
810 _Jv_Environment_Properties
[property_count
].key_length
= length
;
812 // Skip to the end of the key
815 p
= next_property_value (p
, &length
);
817 _Jv_Environment_Properties
[property_count
].value
= p
;
818 _Jv_Environment_Properties
[property_count
].value_length
= length
;
825 memset ((void *) &_Jv_Environment_Properties
[property_count
],
826 0, sizeof (property_pair
));
830 // Null terminate the strings.
831 while (_Jv_Environment_Properties
[i
].key
)
833 _Jv_Environment_Properties
[i
].key
[_Jv_Environment_Properties
[i
].key_length
] = 0;
834 _Jv_Environment_Properties
[i
++].value
[_Jv_Environment_Properties
[i
].value_length
] = 0;
838 #endif // DISABLE_GETENV_PROPERTIES
841 JvRunMain (jclass klass
, int argc
, const char **argv
)
843 PROCESS_GCJ_PROPERTIES
;
846 #ifdef HAVE_PROC_SELF_EXE
848 sprintf (exec_name
, "/proc/%d/exe", getpid ());
849 _Jv_ThisExecutable (exec_name
);
851 _Jv_ThisExecutable (argv
[0]);
854 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
855 main_group
= new java::lang::ThreadGroup (23);
856 main_thread
= new gnu::gcj::runtime::FirstThread (main_group
,
859 main_thread
->start();
862 java::lang::Runtime::getRuntime ()->exit (0);
866 _Jv_RunMain (const char *class_name
, int argc
, const char **argv
)
868 PROCESS_GCJ_PROPERTIES
;
872 #ifdef HAVE_PROC_SELF_EXE
874 sprintf (exec_name
, "/proc/%d/exe", getpid ());
875 _Jv_ThisExecutable (exec_name
);
878 arg_vec
= JvConvertArgv (argc
- 1, argv
+ 1);
879 main_group
= new java::lang::ThreadGroup (23);
880 main_thread
= new gnu::gcj::runtime::FirstThread (main_group
,
881 JvNewStringLatin1 (class_name
),
883 main_thread
->start();
886 java::lang::Runtime::getRuntime ()->exit (0);
891 // Parse a string and return a heap size.
893 parse_heap_size (const char *spec
)
896 unsigned long val
= strtoul (spec
, &end
, 10);
897 if (*end
== 'k' || *end
== 'K')
899 else if (*end
== 'm' || *end
== 'M')
904 // Set the initial heap size. This might be ignored by the GC layer.
905 // This must be called before _Jv_RunMain.
907 _Jv_SetInitialHeapSize (const char *arg
)
909 size_t size
= parse_heap_size (arg
);
910 _Jv_GCSetInitialHeapSize (size
);
913 // Set the maximum heap size. This might be ignored by the GC layer.
914 // This must be called before _Jv_RunMain.
916 _Jv_SetMaximumHeapSize (const char *arg
)
918 size_t size
= parse_heap_size (arg
);
919 _Jv_GCSetMaximumHeapSize (size
);
925 _Jv_Malloc (jsize size
)
929 void *ptr
= malloc ((size_t) size
);
936 _Jv_Realloc (void *ptr
, jsize size
)
940 ptr
= realloc (ptr
, (size_t) size
);
947 _Jv_MallocUnchecked (jsize size
)
951 return malloc ((size_t) size
);
962 // In theory, these routines can be #ifdef'd away on machines which
963 // support divide overflow signals. However, we never know if some
964 // code might have been compiled with "-fuse-divide-subroutine", so we
965 // always include them in libgcj.
968 _Jv_divI (jint dividend
, jint divisor
)
971 _Jv_Throw (arithexception
);
973 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
976 return dividend
/ divisor
;
980 _Jv_remI (jint dividend
, jint divisor
)
983 _Jv_Throw (arithexception
);
985 if (dividend
== (jint
) 0x80000000L
&& divisor
== -1)
988 return dividend
% divisor
;
992 _Jv_divJ (jlong dividend
, jlong divisor
)
995 _Jv_Throw (arithexception
);
997 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1000 return dividend
/ divisor
;
1004 _Jv_remJ (jlong dividend
, jlong divisor
)
1007 _Jv_Throw (arithexception
);
1009 if (dividend
== (jlong
) 0x8000000000000000LL
&& divisor
== -1)
1012 return dividend
% divisor
;