Makefile.am: New friends for java/lang/Thread.h.
[gcc.git] / libjava / prims.cc
1 // prims.cc - Code for core of runtime environment.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation
4
5 This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
10
11 #include <config.h>
12
13 #ifdef USE_WIN32_SIGNALLING
14 #include <windows.h>
15 #endif /* USE_WIN32_SIGNALLING */
16
17 #ifdef USE_WINSOCK
18 #undef __INSIDE_CYGWIN__
19 #include <winsock.h>
20 #endif /* USE_WINSOCK */
21
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <signal.h>
27
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31
32 #include <gcj/cni.h>
33 #include <jvm.h>
34 #include <java-signal.h>
35 #include <java-threads.h>
36
37 #ifdef ENABLE_JVMPI
38 #include <jvmpi.h>
39 #include <java/lang/ThreadGroup.h>
40 #endif
41
42 #ifndef DISABLE_GETENV_PROPERTIES
43 #include <ctype.h>
44 #include <java-props.h>
45 #define PROCESS_GCJ_PROPERTIES process_gcj_properties()
46 #else
47 #define PROCESS_GCJ_PROPERTIES
48 #endif // DISABLE_GETENV_PROPERTIES
49
50 #include <java/lang/Class.h>
51 #include <java/lang/ClassLoader.h>
52 #include <java/lang/Runtime.h>
53 #include <java/lang/String.h>
54 #include <java/lang/Thread.h>
55 #include <java/lang/ThreadGroup.h>
56 #include <gnu/gcj/runtime/FirstThread.h>
57 #include <java/lang/ArrayIndexOutOfBoundsException.h>
58 #include <java/lang/ArithmeticException.h>
59 #include <java/lang/ClassFormatError.h>
60 #include <java/lang/NegativeArraySizeException.h>
61 #include <java/lang/NullPointerException.h>
62 #include <java/lang/OutOfMemoryError.h>
63 #include <java/lang/System.h>
64 #include <java/lang/reflect/Modifier.h>
65 #include <java/io/PrintStream.h>
66 #include <java/lang/UnsatisfiedLinkError.h>
67
68 #ifdef USE_LTDL
69 #include <ltdl.h>
70 #endif
71
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;
75
76 // Largest representable size_t.
77 #define SIZE_T_MAX ((size_t) (~ (size_t) 0))
78
79 static const char *no_properties[] = { NULL };
80
81 // Properties set at compile time.
82 const char **_Jv_Compiler_Properties = no_properties;
83
84 // The JAR file to add to the beginning of java.class.path.
85 const char *_Jv_Jar_Class_Path;
86
87 #ifndef DISABLE_GETENV_PROPERTIES
88 // Property key/value pairs.
89 property_pair *_Jv_Environment_Properties;
90 #endif
91
92 // The name of this executable.
93 static char *_Jv_execName;
94
95 // Stash the argv pointer to benefit native libraries that need it.
96 const char **_Jv_argv;
97 int _Jv_argc;
98
99 #ifdef ENABLE_JVMPI
100 // Pointer to JVMPI notification functions.
101 void (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (JVMPI_Event *event);
102 void (*_Jv_JVMPI_Notify_THREAD_START) (JVMPI_Event *event);
103 void (*_Jv_JVMPI_Notify_THREAD_END) (JVMPI_Event *event);
104 #endif
105 \f
106
107 extern "C" void _Jv_ThrowSignal (jthrowable) __attribute ((noreturn));
108
109 // Just like _Jv_Throw, but fill in the stack trace first. Although
110 // this is declared extern in order that its name not be mangled, it
111 // is not intended to be used outside this file.
112 void
113 _Jv_ThrowSignal (jthrowable throwable)
114 {
115 throwable->fillInStackTrace ();
116 throw throwable;
117 }
118
119 #ifdef HANDLE_SEGV
120 static java::lang::NullPointerException *nullp;
121
122 SIGNAL_HANDLER (catch_segv)
123 {
124 MAKE_THROW_FRAME (nullp);
125 _Jv_ThrowSignal (nullp);
126 }
127 #endif
128
129 static java::lang::ArithmeticException *arithexception;
130
131 #ifdef HANDLE_FPE
132 SIGNAL_HANDLER (catch_fpe)
133 {
134 #ifdef HANDLE_DIVIDE_OVERFLOW
135 HANDLE_DIVIDE_OVERFLOW;
136 #else
137 MAKE_THROW_FRAME (arithexception);
138 #endif
139 _Jv_ThrowSignal (arithexception);
140 }
141 #endif
142
143 \f
144
145 jboolean
146 _Jv_equalUtf8Consts (Utf8Const* a, Utf8Const *b)
147 {
148 int len;
149 _Jv_ushort *aptr, *bptr;
150 if (a == b)
151 return true;
152 if (a->hash != b->hash)
153 return false;
154 len = a->length;
155 if (b->length != len)
156 return false;
157 aptr = (_Jv_ushort *)a->data;
158 bptr = (_Jv_ushort *)b->data;
159 len = (len + 1) >> 1;
160 while (--len >= 0)
161 if (*aptr++ != *bptr++)
162 return false;
163 return true;
164 }
165
166 /* True iff A is equal to STR.
167 HASH is STR->hashCode().
168 */
169
170 jboolean
171 _Jv_equal (Utf8Const* a, jstring str, jint hash)
172 {
173 if (a->hash != (_Jv_ushort) hash)
174 return false;
175 jint len = str->length();
176 jint i = 0;
177 jchar *sptr = _Jv_GetStringChars (str);
178 unsigned char* ptr = (unsigned char*) a->data;
179 unsigned char* limit = ptr + a->length;
180 for (;; i++, sptr++)
181 {
182 int ch = UTF8_GET (ptr, limit);
183 if (i == len)
184 return ch < 0;
185 if (ch != *sptr)
186 return false;
187 }
188 return true;
189 }
190
191 /* Like _Jv_equal, but stop after N characters. */
192 jboolean
193 _Jv_equaln (Utf8Const *a, jstring str, jint n)
194 {
195 jint len = str->length();
196 jint i = 0;
197 jchar *sptr = _Jv_GetStringChars (str);
198 unsigned char* ptr = (unsigned char*) a->data;
199 unsigned char* limit = ptr + a->length;
200 for (; n-- > 0; i++, sptr++)
201 {
202 int ch = UTF8_GET (ptr, limit);
203 if (i == len)
204 return ch < 0;
205 if (ch != *sptr)
206 return false;
207 }
208 return true;
209 }
210
211 /* Count the number of Unicode chars encoded in a given Ut8 string. */
212 int
213 _Jv_strLengthUtf8(char* str, int len)
214 {
215 unsigned char* ptr;
216 unsigned char* limit;
217 int str_length;
218
219 ptr = (unsigned char*) str;
220 limit = ptr + len;
221 str_length = 0;
222 for (; ptr < limit; str_length++)
223 {
224 if (UTF8_GET (ptr, limit) < 0)
225 return (-1);
226 }
227 return (str_length);
228 }
229
230 /* Calculate a hash value for a string encoded in Utf8 format.
231 * This returns the same hash value as specified or java.lang.String.hashCode.
232 */
233 static jint
234 hashUtf8String (char* str, int len)
235 {
236 unsigned char* ptr = (unsigned char*) str;
237 unsigned char* limit = ptr + len;
238 jint hash = 0;
239
240 for (; ptr < limit;)
241 {
242 int ch = UTF8_GET (ptr, limit);
243 /* Updated specification from
244 http://www.javasoft.com/docs/books/jls/clarify.html. */
245 hash = (31 * hash) + ch;
246 }
247 return hash;
248 }
249
250 _Jv_Utf8Const *
251 _Jv_makeUtf8Const (char* s, int len)
252 {
253 if (len < 0)
254 len = strlen (s);
255 Utf8Const* m = (Utf8Const*) _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
256 if (! m)
257 throw no_memory;
258 memcpy (m->data, s, len);
259 m->data[len] = 0;
260 m->length = len;
261 m->hash = hashUtf8String (s, len) & 0xFFFF;
262 return (m);
263 }
264
265 _Jv_Utf8Const *
266 _Jv_makeUtf8Const (jstring string)
267 {
268 jint hash = string->hashCode ();
269 jint len = _Jv_GetStringUTFLength (string);
270
271 Utf8Const* m = (Utf8Const*)
272 _Jv_AllocBytes (sizeof(Utf8Const) + len + 1);
273
274 m->hash = hash;
275 m->length = len;
276
277 _Jv_GetStringUTFRegion (string, 0, string->length (), m->data);
278 m->data[len] = 0;
279
280 return m;
281 }
282
283 \f
284
285 #ifdef DEBUG
286 void
287 _Jv_Abort (const char *function, const char *file, int line,
288 const char *message)
289 #else
290 void
291 _Jv_Abort (const char *, const char *, int, const char *message)
292 #endif
293 {
294 #ifdef DEBUG
295 fprintf (stderr,
296 "libgcj failure: %s\n in function %s, file %s, line %d\n",
297 message, function, file, line);
298 #else
299 java::io::PrintStream *err = java::lang::System::err;
300 err->print(JvNewStringLatin1 ("libgcj failure: "));
301 err->println(JvNewStringLatin1 (message));
302 err->flush();
303 #endif
304 abort ();
305 }
306
307 static void
308 fail_on_finalization (jobject)
309 {
310 JvFail ("object was finalized");
311 }
312
313 void
314 _Jv_GCWatch (jobject obj)
315 {
316 _Jv_RegisterFinalizer (obj, fail_on_finalization);
317 }
318
319 void
320 _Jv_ThrowBadArrayIndex(jint bad_index)
321 {
322 throw new java::lang::ArrayIndexOutOfBoundsException
323 (java::lang::String::valueOf (bad_index));
324 }
325
326 void
327 _Jv_ThrowNullPointerException ()
328 {
329 throw new java::lang::NullPointerException;
330 }
331
332 // Explicitly throw a no memory exception.
333 // The collector calls this when it encounters an out-of-memory condition.
334 void _Jv_ThrowNoMemory()
335 {
336 _Jv_Throw (no_memory);
337 }
338
339 // Allocate a new object of class KLASS. SIZE is the size of the object
340 // to allocate. You might think this is redundant, but it isn't; some
341 // classes, such as String, aren't of fixed size.
342 jobject
343 _Jv_AllocObject (jclass klass, jint size)
344 {
345 _Jv_InitClass (klass);
346
347 jobject obj = (jobject) _Jv_AllocObj (size, klass);
348
349 // If this class has inherited finalize from Object, then don't
350 // bother registering a finalizer. We know that finalize() is the
351 // very first method after the dummy entry. If this turns out to be
352 // unreliable, a more robust implementation can be written. Such an
353 // implementation would look for Object.finalize in Object's method
354 // table at startup, and then use that information to find the
355 // appropriate index in the method vector.
356 if (klass->vtable->get_finalizer()
357 != java::lang::Object::class$.vtable->get_finalizer())
358 _Jv_RegisterFinalizer (obj, _Jv_FinalizeObject);
359
360 #ifdef ENABLE_JVMPI
361 // Service JVMPI request.
362
363 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
364 {
365 JVMPI_Event event;
366
367 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
368 event.env_id = NULL;
369 event.u.obj_alloc.arena_id = 0;
370 event.u.obj_alloc.class_id = (jobjectID) klass;
371 event.u.obj_alloc.is_array = 0;
372 event.u.obj_alloc.size = size;
373 event.u.obj_alloc.obj_id = (jobjectID) obj;
374
375 // FIXME: This doesn't look right for the Boehm GC. A GC may
376 // already be in progress. _Jv_DisableGC () doesn't wait for it.
377 // More importantly, I don't see the need for disabling GC, since we
378 // blatantly have a pointer to obj on our stack, ensuring that the
379 // object can't be collected. Even for a nonconservative collector,
380 // it appears to me that this must be true, since we are about to
381 // return obj. Isn't this whole approach way too intrusive for
382 // a useful profiling interface? - HB
383 _Jv_DisableGC ();
384 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
385 _Jv_EnableGC ();
386 }
387 #endif
388
389 return obj;
390 }
391
392 // A version of the above that assumes the object contains no pointers,
393 // and requires no finalization. This can't happen if we need pointers
394 // to locks.
395 #ifdef JV_HASH_SYNCHRONIZATION
396 jobject
397 _Jv_AllocPtrFreeObject (jclass klass, jint size)
398 {
399 _Jv_InitClass (klass);
400
401 jobject obj = (jobject) _Jv_AllocPtrFreeObj (size, klass);
402
403 #ifdef ENABLE_JVMPI
404 // Service JVMPI request.
405
406 if (__builtin_expect (_Jv_JVMPI_Notify_OBJECT_ALLOC != 0, false))
407 {
408 JVMPI_Event event;
409
410 event.event_type = JVMPI_EVENT_OBJECT_ALLOC;
411 event.env_id = NULL;
412 event.u.obj_alloc.arena_id = 0;
413 event.u.obj_alloc.class_id = (jobjectID) klass;
414 event.u.obj_alloc.is_array = 0;
415 event.u.obj_alloc.size = size;
416 event.u.obj_alloc.obj_id = (jobjectID) obj;
417
418 _Jv_DisableGC ();
419 (*_Jv_JVMPI_Notify_OBJECT_ALLOC) (&event);
420 _Jv_EnableGC ();
421 }
422 #endif
423
424 return obj;
425 }
426 #endif /* JV_HASH_SYNCHRONIZATION */
427
428
429 // Allocate a new array of Java objects. Each object is of type
430 // `elementClass'. `init' is used to initialize each slot in the
431 // array.
432 jobjectArray
433 _Jv_NewObjectArray (jsize count, jclass elementClass, jobject init)
434 {
435 if (__builtin_expect (count < 0, false))
436 throw new java::lang::NegativeArraySizeException;
437
438 JvAssert (! elementClass->isPrimitive ());
439
440 // Ensure that elements pointer is properly aligned.
441 jobjectArray obj = NULL;
442 size_t size = (size_t) elements (obj);
443 size += count * sizeof (jobject);
444
445 // FIXME: second argument should be "current loader"
446 jclass klass = _Jv_GetArrayClass (elementClass, 0);
447
448 obj = (jobjectArray) _Jv_AllocArray (size, klass);
449 // Cast away const.
450 jsize *lp = const_cast<jsize *> (&obj->length);
451 *lp = count;
452 // We know the allocator returns zeroed memory. So don't bother
453 // zeroing it again.
454 if (init)
455 {
456 jobject *ptr = elements(obj);
457 while (--count >= 0)
458 *ptr++ = init;
459 }
460 return obj;
461 }
462
463 // Allocate a new array of primitives. ELTYPE is the type of the
464 // element, COUNT is the size of the array.
465 jobject
466 _Jv_NewPrimArray (jclass eltype, jint count)
467 {
468 int elsize = eltype->size();
469 if (__builtin_expect (count < 0, false))
470 throw new java::lang::NegativeArraySizeException;
471
472 JvAssert (eltype->isPrimitive ());
473 jobject dummy = NULL;
474 size_t size = (size_t) _Jv_GetArrayElementFromElementType (dummy, eltype);
475
476 // Check for overflow.
477 if (__builtin_expect ((size_t) count >
478 (SIZE_T_MAX - size) / elsize, false))
479 throw no_memory;
480
481 jclass klass = _Jv_GetArrayClass (eltype, 0);
482
483 # ifdef JV_HASH_SYNCHRONIZATION
484 // Since the vtable is always statically allocated,
485 // these are completely pointerfree! Make sure the GC doesn't touch them.
486 __JArray *arr =
487 (__JArray*) _Jv_AllocPtrFreeObj (size + elsize * count, klass);
488 memset((char *)arr + size, 0, elsize * count);
489 # else
490 __JArray *arr = (__JArray*) _Jv_AllocObj (size + elsize * count, klass);
491 // Note that we assume we are given zeroed memory by the allocator.
492 # endif
493 // Cast away const.
494 jsize *lp = const_cast<jsize *> (&arr->length);
495 *lp = count;
496
497 return arr;
498 }
499
500 jobject
501 _Jv_NewArray (jint type, jint size)
502 {
503 switch (type)
504 {
505 case 4: return JvNewBooleanArray (size);
506 case 5: return JvNewCharArray (size);
507 case 6: return JvNewFloatArray (size);
508 case 7: return JvNewDoubleArray (size);
509 case 8: return JvNewByteArray (size);
510 case 9: return JvNewShortArray (size);
511 case 10: return JvNewIntArray (size);
512 case 11: return JvNewLongArray (size);
513 }
514 JvFail ("newarray - bad type code");
515 return NULL; // Placate compiler.
516 }
517
518 jobject
519 _Jv_NewMultiArray (jclass type, jint dimensions, jint *sizes)
520 {
521 JvAssert (type->isArray());
522 jclass element_type = type->getComponentType();
523 jobject result;
524 if (element_type->isPrimitive())
525 result = _Jv_NewPrimArray (element_type, sizes[0]);
526 else
527 result = _Jv_NewObjectArray (sizes[0], element_type, NULL);
528
529 if (dimensions > 1)
530 {
531 JvAssert (! element_type->isPrimitive());
532 JvAssert (element_type->isArray());
533 jobject *contents = elements ((jobjectArray) result);
534 for (int i = 0; i < sizes[0]; ++i)
535 contents[i] = _Jv_NewMultiArray (element_type, dimensions - 1,
536 sizes + 1);
537 }
538
539 return result;
540 }
541
542 jobject
543 _Jv_NewMultiArray (jclass array_type, jint dimensions, ...)
544 {
545 va_list args;
546 jint sizes[dimensions];
547 va_start (args, dimensions);
548 for (int i = 0; i < dimensions; ++i)
549 {
550 jint size = va_arg (args, jint);
551 sizes[i] = size;
552 }
553 va_end (args);
554
555 return _Jv_NewMultiArray (array_type, dimensions, sizes);
556 }
557
558 \f
559
560 #define DECLARE_PRIM_TYPE(NAME, SIG, LEN) \
561 _Jv_ArrayVTable _Jv_##NAME##VTable; \
562 java::lang::Class _Jv_##NAME##Class ((jobject) #NAME, \
563 (jbyte) SIG, (jint) LEN, \
564 (jobject) &_Jv_##NAME##VTable);
565
566 DECLARE_PRIM_TYPE(byte, 'B', 1);
567 DECLARE_PRIM_TYPE(short, 'S', 2);
568 DECLARE_PRIM_TYPE(int, 'I', 4);
569 DECLARE_PRIM_TYPE(long, 'J', 8);
570 DECLARE_PRIM_TYPE(boolean, 'Z', 1);
571 DECLARE_PRIM_TYPE(char, 'C', 2);
572 DECLARE_PRIM_TYPE(float, 'F', 4);
573 DECLARE_PRIM_TYPE(double, 'D', 8);
574 DECLARE_PRIM_TYPE(void, 'V', 0);
575
576 jclass
577 _Jv_FindClassFromSignature (char *sig, java::lang::ClassLoader *loader)
578 {
579 switch (*sig)
580 {
581 case 'B':
582 return JvPrimClass (byte);
583 case 'S':
584 return JvPrimClass (short);
585 case 'I':
586 return JvPrimClass (int);
587 case 'J':
588 return JvPrimClass (long);
589 case 'Z':
590 return JvPrimClass (boolean);
591 case 'C':
592 return JvPrimClass (char);
593 case 'F':
594 return JvPrimClass (float);
595 case 'D':
596 return JvPrimClass (double);
597 case 'V':
598 return JvPrimClass (void);
599 case 'L':
600 {
601 int i;
602 for (i = 1; sig[i] && sig[i] != ';'; ++i)
603 ;
604 _Jv_Utf8Const *name = _Jv_makeUtf8Const (&sig[1], i - 1);
605 return _Jv_FindClass (name, loader);
606
607 }
608 case '[':
609 {
610 jclass klass = _Jv_FindClassFromSignature (&sig[1], loader);
611 if (! klass)
612 return NULL;
613 return _Jv_GetArrayClass (klass, loader);
614 }
615 }
616
617 return NULL; // Placate compiler.
618 }
619
620 \f
621
622 JArray<jstring> *
623 JvConvertArgv (int argc, const char **argv)
624 {
625 if (argc < 0)
626 argc = 0;
627 jobjectArray ar = JvNewObjectArray(argc, &StringClass, NULL);
628 jobject* ptr = elements(ar);
629 for (int i = 0; i < argc; i++)
630 {
631 const char *arg = argv[i];
632 // FIXME - should probably use JvNewStringUTF.
633 *ptr++ = JvNewStringLatin1(arg, strlen(arg));
634 }
635 return (JArray<jstring>*) ar;
636 }
637
638 // FIXME: These variables are static so that they will be
639 // automatically scanned by the Boehm collector. This is needed
640 // because with qthreads the collector won't scan the initial stack --
641 // it will only scan the qthreads stacks.
642
643 // Command line arguments.
644 static JArray<jstring> *arg_vec;
645
646 // The primary thread.
647 static java::lang::Thread *main_thread;
648
649 char *
650 _Jv_ThisExecutable (void)
651 {
652 return _Jv_execName;
653 }
654
655 void
656 _Jv_ThisExecutable (const char *name)
657 {
658 if (name)
659 {
660 _Jv_execName = (char *) _Jv_Malloc (strlen (name) + 1);
661 strcpy (_Jv_execName, name);
662 }
663 }
664
665 #ifdef USE_WIN32_SIGNALLING
666
667 extern "C" int* win32_get_restart_frame (void *);
668
669 LONG CALLBACK
670 win32_exception_handler (LPEXCEPTION_POINTERS e)
671 {
672 int* setjmp_buf;
673 if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
674 setjmp_buf = win32_get_restart_frame (nullp);
675 else if (e->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO)
676 setjmp_buf = win32_get_restart_frame (arithexception);
677 else
678 return EXCEPTION_CONTINUE_SEARCH;
679
680 e->ContextRecord->Ebp = setjmp_buf[0];
681 // FIXME: Why does i386-signal.h increment the PC here, do we need to do it?
682 e->ContextRecord->Eip = setjmp_buf[1];
683 // FIXME: Is this the stack pointer? Do we need it?
684 e->ContextRecord->Esp = setjmp_buf[2];
685
686 return EXCEPTION_CONTINUE_EXECUTION;
687 }
688
689 #endif
690
691 #ifndef DISABLE_GETENV_PROPERTIES
692
693 static char *
694 next_property_key (char *s, size_t *length)
695 {
696 size_t l = 0;
697
698 JvAssert (s);
699
700 // Skip over whitespace
701 while (isspace (*s))
702 s++;
703
704 // If we've reached the end, return NULL. Also return NULL if for
705 // some reason we've come across a malformed property string.
706 if (*s == 0
707 || *s == ':'
708 || *s == '=')
709 return NULL;
710
711 // Determine the length of the property key.
712 while (s[l] != 0
713 && ! isspace (s[l])
714 && s[l] != ':'
715 && s[l] != '=')
716 {
717 if (s[l] == '\\'
718 && s[l+1] != 0)
719 l++;
720 l++;
721 }
722
723 *length = l;
724
725 return s;
726 }
727
728 static char *
729 next_property_value (char *s, size_t *length)
730 {
731 size_t l = 0;
732
733 JvAssert (s);
734
735 while (isspace (*s))
736 s++;
737
738 if (*s == ':'
739 || *s == '=')
740 s++;
741
742 while (isspace (*s))
743 s++;
744
745 // If we've reached the end, return NULL.
746 if (*s == 0)
747 return NULL;
748
749 // Determine the length of the property value.
750 while (s[l] != 0
751 && ! isspace (s[l])
752 && s[l] != ':'
753 && s[l] != '=')
754 {
755 if (s[l] == '\\'
756 && s[l+1] != 0)
757 l += 2;
758 else
759 l++;
760 }
761
762 *length = l;
763
764 return s;
765 }
766
767 static void
768 process_gcj_properties ()
769 {
770 char *props = getenv("GCJ_PROPERTIES");
771 char *p = props;
772 size_t length;
773 size_t property_count = 0;
774
775 if (NULL == props)
776 return;
777
778 // Whip through props quickly in order to count the number of
779 // property values.
780 while (p && (p = next_property_key (p, &length)))
781 {
782 // Skip to the end of the key
783 p += length;
784
785 p = next_property_value (p, &length);
786 if (p)
787 p += length;
788
789 property_count++;
790 }
791
792 // Allocate an array of property value/key pairs.
793 _Jv_Environment_Properties =
794 (property_pair *) malloc (sizeof(property_pair)
795 * (property_count + 1));
796
797 // Go through the properties again, initializing _Jv_Properties
798 // along the way.
799 p = props;
800 property_count = 0;
801 while (p && (p = next_property_key (p, &length)))
802 {
803 _Jv_Environment_Properties[property_count].key = p;
804 _Jv_Environment_Properties[property_count].key_length = length;
805
806 // Skip to the end of the key
807 p += length;
808
809 p = next_property_value (p, &length);
810
811 _Jv_Environment_Properties[property_count].value = p;
812 _Jv_Environment_Properties[property_count].value_length = length;
813
814 if (p)
815 p += length;
816
817 property_count++;
818 }
819 memset ((void *) &_Jv_Environment_Properties[property_count],
820 0, sizeof (property_pair));
821 {
822 size_t i = 0;
823
824 // Null terminate the strings.
825 while (_Jv_Environment_Properties[i].key)
826 {
827 _Jv_Environment_Properties[i].key[_Jv_Environment_Properties[i].key_length] = 0;
828 _Jv_Environment_Properties[i++].value[_Jv_Environment_Properties[i].value_length] = 0;
829 }
830 }
831 }
832 #endif // DISABLE_GETENV_PROPERTIES
833
834 jint
835 _Jv_CreateJavaVM (void* /*vm_args*/)
836 {
837 PROCESS_GCJ_PROPERTIES;
838
839 // Turn stack trace generation off while creating exception objects.
840 _Jv_InitClass (&java::lang::Throwable::class$);
841 java::lang::Throwable::trace_enabled = 0;
842
843 INIT_SEGV;
844 #ifdef HANDLE_FPE
845 INIT_FPE;
846 #else
847 arithexception = new java::lang::ArithmeticException
848 (JvNewStringLatin1 ("/ by zero"));
849 #endif
850
851 no_memory = new java::lang::OutOfMemoryError;
852
853 java::lang::Throwable::trace_enabled = 1;
854
855 #ifdef USE_LTDL
856 LTDL_SET_PRELOADED_SYMBOLS ();
857 #endif
858
859 #ifdef USE_WINSOCK
860 // Initialise winsock for networking
861 WSADATA data;
862 if (WSAStartup (MAKEWORD (1, 1), &data))
863 MessageBox (NULL, "Error initialising winsock library.", "Error", MB_OK | MB_ICONEXCLAMATION);
864 #endif /* USE_WINSOCK */
865
866 #ifdef USE_WIN32_SIGNALLING
867 // Install exception handler
868 SetUnhandledExceptionFilter (win32_exception_handler);
869 #elif defined(HAVE_SIGACTION)
870 // We only want this on POSIX systems.
871 struct sigaction act;
872 act.sa_handler = SIG_IGN;
873 sigemptyset (&act.sa_mask);
874 act.sa_flags = 0;
875 sigaction (SIGPIPE, &act, NULL);
876 #else
877 signal (SIGPIPE, SIG_IGN);
878 #endif
879
880 _Jv_JNI_Init ();
881
882 return 0;
883 }
884
885 void
886 _Jv_RunMain (jclass klass, const char *name, int argc, const char **argv,
887 bool is_jar)
888 {
889 _Jv_argv = argv;
890 _Jv_argc = argc;
891
892 java::lang::Runtime *runtime = NULL;
893
894 #ifdef HAVE_PROC_SELF_EXE
895 char exec_name[20];
896 sprintf (exec_name, "/proc/%d/exe", getpid ());
897 _Jv_ThisExecutable (exec_name);
898 #else
899 _Jv_ThisExecutable (argv[0]);
900 #endif
901
902 try
903 {
904 _Jv_CreateJavaVM (NULL);
905
906 // Get the Runtime here. We want to initialize it before searching
907 // for `main'; that way it will be set up if `main' is a JNI method.
908 runtime = java::lang::Runtime::getRuntime ();
909
910 arg_vec = JvConvertArgv (argc - 1, argv + 1);
911
912 if (klass)
913 main_thread = new gnu::gcj::runtime::FirstThread (klass, arg_vec);
914 else
915 main_thread = new gnu::gcj::runtime::FirstThread
916 (JvNewStringLatin1 (name), arg_vec, is_jar);
917
918 if (is_jar)
919 {
920 // We need a new ClassLoader because the classpath must be the
921 // jar file only. The easiest way to do this is to lose our
922 // reference to the previous classloader.
923 _Jv_Jar_Class_Path = strdup (name);
924 java::lang::ClassLoader::system = NULL;
925 }
926 }
927 catch (java::lang::Throwable *t)
928 {
929 java::lang::System::err->println (JvNewStringLatin1
930 ("Exception during runtime initialization"));
931 t->printStackTrace();
932 runtime->exit (1);
933 }
934
935 _Jv_AttachCurrentThread (main_thread);
936 _Jv_ThreadRun (main_thread);
937 _Jv_ThreadWait ();
938
939 int status = (int) java::lang::ThreadGroup::had_uncaught_exception;
940 runtime->exit (status);
941 }
942
943 void
944 JvRunMain (jclass klass, int argc, const char **argv)
945 {
946 _Jv_RunMain (klass, NULL, argc, argv, false);
947 }
948
949 \f
950
951 // Parse a string and return a heap size.
952 static size_t
953 parse_heap_size (const char *spec)
954 {
955 char *end;
956 unsigned long val = strtoul (spec, &end, 10);
957 if (*end == 'k' || *end == 'K')
958 val *= 1024;
959 else if (*end == 'm' || *end == 'M')
960 val *= 1048576;
961 return (size_t) val;
962 }
963
964 // Set the initial heap size. This might be ignored by the GC layer.
965 // This must be called before _Jv_RunMain.
966 void
967 _Jv_SetInitialHeapSize (const char *arg)
968 {
969 size_t size = parse_heap_size (arg);
970 _Jv_GCSetInitialHeapSize (size);
971 }
972
973 // Set the maximum heap size. This might be ignored by the GC layer.
974 // This must be called before _Jv_RunMain.
975 void
976 _Jv_SetMaximumHeapSize (const char *arg)
977 {
978 size_t size = parse_heap_size (arg);
979 _Jv_GCSetMaximumHeapSize (size);
980 }
981
982 \f
983
984 void *
985 _Jv_Malloc (jsize size)
986 {
987 if (__builtin_expect (size == 0, false))
988 size = 1;
989 void *ptr = malloc ((size_t) size);
990 if (__builtin_expect (ptr == NULL, false))
991 throw no_memory;
992 return ptr;
993 }
994
995 void *
996 _Jv_Realloc (void *ptr, jsize size)
997 {
998 if (__builtin_expect (size == 0, false))
999 size = 1;
1000 ptr = realloc (ptr, (size_t) size);
1001 if (__builtin_expect (ptr == NULL, false))
1002 throw no_memory;
1003 return ptr;
1004 }
1005
1006 void *
1007 _Jv_MallocUnchecked (jsize size)
1008 {
1009 if (__builtin_expect (size == 0, false))
1010 size = 1;
1011 return malloc ((size_t) size);
1012 }
1013
1014 void
1015 _Jv_Free (void* ptr)
1016 {
1017 return free (ptr);
1018 }
1019
1020 \f
1021
1022 // In theory, these routines can be #ifdef'd away on machines which
1023 // support divide overflow signals. However, we never know if some
1024 // code might have been compiled with "-fuse-divide-subroutine", so we
1025 // always include them in libgcj.
1026
1027 jint
1028 _Jv_divI (jint dividend, jint divisor)
1029 {
1030 if (__builtin_expect (divisor == 0, false))
1031 _Jv_ThrowSignal (arithexception);
1032
1033 if (dividend == (jint) 0x80000000L && divisor == -1)
1034 return dividend;
1035
1036 return dividend / divisor;
1037 }
1038
1039 jint
1040 _Jv_remI (jint dividend, jint divisor)
1041 {
1042 if (__builtin_expect (divisor == 0, false))
1043 _Jv_ThrowSignal (arithexception);
1044
1045 if (dividend == (jint) 0x80000000L && divisor == -1)
1046 return 0;
1047
1048 return dividend % divisor;
1049 }
1050
1051 jlong
1052 _Jv_divJ (jlong dividend, jlong divisor)
1053 {
1054 if (__builtin_expect (divisor == 0, false))
1055 _Jv_ThrowSignal (arithexception);
1056
1057 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1058 return dividend;
1059
1060 return dividend / divisor;
1061 }
1062
1063 jlong
1064 _Jv_remJ (jlong dividend, jlong divisor)
1065 {
1066 if (__builtin_expect (divisor == 0, false))
1067 _Jv_ThrowSignal (arithexception);
1068
1069 if (dividend == (jlong) 0x8000000000000000LL && divisor == -1)
1070 return 0;
1071
1072 return dividend % divisor;
1073 }