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