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