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