* src/vm/vm.c [WITH_JRE_LAYOUT] (libgen.h, unistd.h): Removed.
[cacao.git] / src / vm / vm.c
1 /* src/vm/vm.c - VM startup and shutdown functions
2
3    Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25    $Id: vm.c 8401 2007-08-22 18:45:31Z twisti $
26
27 */
28
29
30 #include "config.h"
31
32 #include <assert.h>
33 #include <errno.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36
37 #include "vm/types.h"
38
39 #include "arch.h"
40 #include "md-abi.h"
41
42 #include "vm/jit/abi-asm.h"
43
44 #include "mm/gc-common.h"
45 #include "mm/memory.h"
46
47 #include "native/jni.h"
48 #include "native/llni.h"
49 #include "native/native.h"
50
51 #include "native/include/java_lang_Object.h"             /* required by j.l.C */
52 #include "native/include/java_lang_String.h"             /* required by j.l.C */
53
54 #if defined(WITH_CLASSPATH_SUN)
55 # include "native/include/java_nio_ByteBuffer.h"        /* required by j.l.CL */
56 # include "native/include/java_lang_ClassLoader.h"       /* required by j.l.C */
57 #endif
58
59 #include "native/include/java_lang_Class.h"
60
61 #include "native/vm/nativevm.h"
62
63 #include "threads/threads-common.h"
64
65 #include "toolbox/logging.h"
66
67 #include "vm/builtin.h"
68 #include "vm/exceptions.h"
69 #include "vm/finalizer.h"
70 #include "vm/global.h"
71 #include "vm/initialize.h"
72 #include "vm/primitive.h"
73 #include "vm/properties.h"
74 #include "vm/signallocal.h"
75 #include "vm/stringlocal.h"
76 #include "vm/vm.h"
77
78 #include "vm/jit/jit.h"
79 #include "vm/jit/md.h"
80 #include "vm/jit/asmpart.h"
81
82 #if defined(ENABLE_PROFILING)
83 # include "vm/jit/optimizing/profile.h"
84 #endif
85
86 #include "vm/jit/optimizing/recompile.h"
87
88 #include "vmcore/classcache.h"
89 #include "vmcore/options.h"
90 #include "vmcore/statistics.h"
91 #include "vmcore/suck.h"
92
93 #if defined(ENABLE_JVMTI)
94 # include "native/jvmti/cacaodbg.h"
95 #endif
96
97 #if defined(ENABLE_VMLOG)
98 #include <vmlog_cacao.h>
99 #endif
100
101
102 /* Invocation API variables ***************************************************/
103
104 _Jv_JavaVM *_Jv_jvm;                    /* denotes a Java VM                  */
105 _Jv_JNIEnv *_Jv_env;                    /* pointer to native method interface */
106
107
108 /* global variables ***********************************************************/
109
110 s4 vms = 0;                             /* number of VMs created              */
111
112 bool vm_initializing = false;
113 bool vm_exiting = false;
114
115 char      *mainstring = NULL;
116 classinfo *mainclass = NULL;
117
118 #if defined(ENABLE_INTRP)
119 u1 *intrp_main_stack = NULL;
120 #endif
121
122
123 /* define heap sizes **********************************************************/
124
125 #define HEAP_MAXSIZE      128 * 1024 * 1024 /* default 128MB                  */
126 #define HEAP_STARTSIZE      2 * 1024 * 1024 /* default 2MB                    */
127 #define STACK_SIZE                64 * 1024 /* default 64kB                   */
128
129
130 /* define command line options ************************************************/
131
132 enum {
133         OPT_FOO,
134
135         /* Java options */
136
137         OPT_JAR,
138
139         OPT_D32,
140         OPT_D64,
141
142         OPT_CLASSPATH,
143         OPT_D,
144
145         OPT_VERBOSE,
146
147         OPT_VERSION,
148         OPT_SHOWVERSION,
149         OPT_FULLVERSION,
150
151         OPT_HELP,
152         OPT_X,
153         OPT_XX,
154
155         OPT_EA,
156         OPT_DA,
157
158         OPT_ESA,
159         OPT_DSA,
160
161         /* Java non-standard options */
162
163         OPT_JIT,
164         OPT_INTRP,
165
166         OPT_BOOTCLASSPATH,
167         OPT_BOOTCLASSPATH_A,
168         OPT_BOOTCLASSPATH_P,
169
170         OPT_BOOTCLASSPATH_C,
171
172 #if defined(ENABLE_PROFILING)
173         OPT_PROF,
174         OPT_PROF_OPTION,
175 #endif
176
177         OPT_MS,
178         OPT_MX,
179
180         /* CACAO options */
181
182         OPT_VERBOSE1,
183         OPT_NOIEEE,
184
185 #if defined(ENABLE_STATISTICS)
186         OPT_TIME,
187         OPT_STAT,
188 #endif
189
190         OPT_LOG,
191         OPT_CHECK,
192         OPT_LOAD,
193         OPT_SHOW,
194         OPT_DEBUGCOLOR,
195
196 #if !defined(NDEBUG)
197         OPT_ALL,
198         OPT_METHOD,
199         OPT_SIGNATURE,
200 #endif
201
202 #if defined(ENABLE_VERIFIER)
203         OPT_NOVERIFY,
204 #if defined(TYPECHECK_VERBOSE)
205         OPT_VERBOSETC,
206 #endif
207 #endif /* defined(ENABLE_VERIFIER) */
208
209         /* optimization options */
210
211 #if defined(ENABLE_LOOP)
212         OPT_OLOOP,
213 #endif
214         
215 #if defined(ENABLE_IFCONV)
216         OPT_IFCONV,
217 #endif
218
219 #if defined(ENABLE_LSRA) || defined(ENABLE_SSA)
220         OPT_LSRA,
221 #endif
222
223 #if defined(ENABLE_INLINING)
224         OPT_INLINING,
225 #if !defined(NDEBUG)
226         OPT_INLINE_LOG,
227 #endif
228 #if defined(ENABLE_INLINING_DEBUG)
229         OPT_INLINE_DEBUG_ALL,
230         OPT_INLINE_DEBUG_END,
231         OPT_INLINE_DEBUG_MIN,
232         OPT_INLINE_DEBUG_MAX,
233 #endif /* defined(ENABLE_INLINING_DEBUG) */
234 #endif /* defined(ENABLE_INLINING) */
235
236 #if defined(ENABLE_INTRP)
237         /* interpreter options */
238
239         OPT_NO_DYNAMIC,
240         OPT_NO_REPLICATION,
241         OPT_NO_QUICKSUPER,
242         OPT_STATIC_SUPERS,
243         OPT_TRACE,
244 #endif
245
246         OPT_SS,
247
248 #ifdef ENABLE_JVMTI
249         OPT_DEBUG,
250         OPT_XRUNJDWP,
251         OPT_NOAGENT,
252         OPT_AGENTLIB,
253         OPT_AGENTPATH,
254 #endif
255
256 #if defined(ENABLE_DEBUG_FILTER)
257         OPT_FILTER_VERBOSECALL_INCLUDE,
258         OPT_FILTER_VERBOSECALL_EXCLUDE,
259         OPT_FILTER_SHOW_METHOD,
260 #endif
261
262         DUMMY
263 };
264
265
266 opt_struct opts[] = {
267         { "foo",               false, OPT_FOO },
268
269         /* Java options */
270
271         { "jar",               false, OPT_JAR },
272
273         { "d32",               false, OPT_D32 },
274         { "d64",               false, OPT_D64 },
275         { "client",            false, OPT_IGNORE },
276         { "server",            false, OPT_IGNORE },
277         { "jvm",               false, OPT_IGNORE },
278         { "hotspot",           false, OPT_IGNORE },
279
280         { "classpath",         true,  OPT_CLASSPATH },
281         { "cp",                true,  OPT_CLASSPATH },
282         { "D",                 true,  OPT_D },
283         { "version",           false, OPT_VERSION },
284         { "showversion",       false, OPT_SHOWVERSION },
285         { "fullversion",       false, OPT_FULLVERSION },
286         { "help",              false, OPT_HELP },
287         { "?",                 false, OPT_HELP },
288         { "X",                 false, OPT_X },
289         { "XX:",               true,  OPT_XX },
290         { "XX",                false, OPT_XX },
291
292         { "ea:",               true,  OPT_EA },
293         { "da:",               true,  OPT_DA },
294         { "ea",                false, OPT_EA },
295         { "da",                false, OPT_DA },
296
297         { "esa",                     false, OPT_ESA },
298         { "enablesystemassertions",  false, OPT_ESA },
299         { "dsa",                     false, OPT_DSA },
300         { "disablesystemassertions", false, OPT_DSA },
301
302         { "noasyncgc",         false, OPT_IGNORE },
303 #if defined(ENABLE_VERIFIER)
304         { "noverify",          false, OPT_NOVERIFY },
305         { "Xverify:none",      false, OPT_NOVERIFY },
306 #endif
307         { "v",                 false, OPT_VERBOSE1 },
308         { "verbose:",          true,  OPT_VERBOSE },
309
310 #if defined(ENABLE_VERIFIER) && defined(TYPECHECK_VERBOSE)
311         { "verbosetc",         false, OPT_VERBOSETC },
312 #endif
313 #if defined(__ALPHA__)
314         { "noieee",            false, OPT_NOIEEE },
315 #endif
316 #if defined(ENABLE_STATISTICS)
317         { "time",              false, OPT_TIME },
318         { "stat",              false, OPT_STAT },
319 #endif
320         { "log",               true,  OPT_LOG },
321         { "c",                 true,  OPT_CHECK },
322         { "l",                 false, OPT_LOAD },
323
324 #if !defined(NDEBUG)
325         { "all",               false, OPT_ALL },
326         { "sig",               true,  OPT_SIGNATURE },
327 #endif
328
329 #if defined(ENABLE_LOOP)
330         { "oloop",             false, OPT_OLOOP },
331 #endif
332 #if defined(ENABLE_IFCONV)
333         { "ifconv",            false, OPT_IFCONV },
334 #endif
335 #if defined(ENABLE_LSRA) || defined(ENABLE_SSA)
336         { "lsra",              false, OPT_LSRA },
337 #endif
338
339 #if defined(ENABLE_INTRP)
340         /* interpreter options */
341
342         { "trace",             false, OPT_TRACE },
343         { "static-supers",     true,  OPT_STATIC_SUPERS },
344         { "no-dynamic",        false, OPT_NO_DYNAMIC },
345         { "no-replication",    false, OPT_NO_REPLICATION },
346         { "no-quicksuper",     false, OPT_NO_QUICKSUPER },
347 #endif
348
349         /* JVMTI Agent Command Line Options */
350 #ifdef ENABLE_JVMTI
351         { "agentlib:",         true,  OPT_AGENTLIB },
352         { "agentpath:",        true,  OPT_AGENTPATH },
353 #endif
354
355         /* Java non-standard options */
356
357         { "Xjit",              false, OPT_JIT },
358         { "Xint",              false, OPT_INTRP },
359         { "Xbootclasspath:",   true,  OPT_BOOTCLASSPATH },
360         { "Xbootclasspath/a:", true,  OPT_BOOTCLASSPATH_A },
361         { "Xbootclasspath/p:", true,  OPT_BOOTCLASSPATH_P },
362         { "Xbootclasspath/c:", true,  OPT_BOOTCLASSPATH_C },
363
364 #ifdef ENABLE_JVMTI
365         { "Xdebug",            false, OPT_DEBUG },
366         { "Xnoagent",          false, OPT_NOAGENT },
367         { "Xrunjdwp",          true,  OPT_XRUNJDWP },
368 #endif 
369
370         { "Xms",               true,  OPT_MS },
371         { "ms",                true,  OPT_MS },
372         { "Xmx",               true,  OPT_MX },
373         { "mx",                true,  OPT_MX },
374         { "Xss",               true,  OPT_SS },
375         { "ss",                true,  OPT_SS },
376
377 #if defined(ENABLE_PROFILING)
378         { "Xprof:",            true,  OPT_PROF_OPTION },
379         { "Xprof",             false, OPT_PROF },
380 #endif
381
382         /* inlining options */
383
384 #if defined(ENABLE_INLINING)
385 #if defined(ENABLE_INLINING_DEBUG)
386         { "ia",                false, OPT_INLINE_DEBUG_ALL },
387         { "ii",                true,  OPT_INLINE_DEBUG_MIN },
388         { "im",                true,  OPT_INLINE_DEBUG_MAX },
389         { "ie",                true,  OPT_INLINE_DEBUG_END },
390 #endif /* defined(ENABLE_INLINING_DEBUG) */
391 #if !defined(NDEBUG)
392         { "il",                false, OPT_INLINE_LOG },
393 #endif
394         { "i",                 false, OPT_INLINING },
395 #endif /* defined(ENABLE_INLINING) */
396
397         /* keep these at the end of the list */
398
399 #if !defined(NDEBUG)
400         { "m",                 true,  OPT_METHOD },
401 #endif
402
403         { "s",                 true,  OPT_SHOW },
404         { "debug-color",      false,  OPT_DEBUGCOLOR },
405
406 #if defined(ENABLE_DEBUG_FILTER)
407         { "XXfi",              true,  OPT_FILTER_VERBOSECALL_INCLUDE },
408         { "XXfx",              true,  OPT_FILTER_VERBOSECALL_EXCLUDE },
409         { "XXfm",              true,  OPT_FILTER_SHOW_METHOD },
410 #endif
411
412         { NULL,                false, 0 }
413 };
414
415
416 /* usage ***********************************************************************
417
418    Prints the correct usage syntax to stdout.
419
420 *******************************************************************************/
421
422 void usage(void)
423 {
424         puts("Usage: cacao [-options] classname [arguments]");
425         puts("               (to run a class file)");
426         puts("   or  cacao [-options] -jar jarfile [arguments]");
427         puts("               (to run a standalone jar file)\n");
428
429         puts("where options include:");
430         puts("    -d32                     use 32-bit data model if available");
431         puts("    -d64                     use 64-bit data model if available");
432         puts("    -client                  compatibility (currently ignored)");
433         puts("    -server                  compatibility (currently ignored)");
434         puts("    -jvm                     compatibility (currently ignored)");
435         puts("    -hotspot                 compatibility (currently ignored)\n");
436
437         puts("    -cp <path>               specify a path to look for classes");
438         puts("    -classpath <path>        specify a path to look for classes");
439         puts("    -D<name>=<value>         add an entry to the property list");
440         puts("    -verbose[:class|gc|jni]  enable specific verbose output");
441         puts("    -version                 print product version and exit");
442         puts("    -fullversion             print jpackage-compatible product version and exit");
443         puts("    -showversion             print product version and continue");
444         puts("    -help, -?                print this help message");
445         puts("    -X                       print help on non-standard Java options");
446         puts("    -XX                      print help on debugging options");
447     puts("    -ea[:<packagename>...|:<classname>]");
448     puts("    -enableassertions[:<packagename>...|:<classname>]");
449         puts("                             enable assertions with specified granularity");
450         puts("    -da[:<packagename>...|:<classname>]");
451         puts("    -disableassertions[:<packagename>...|:<classname>]");
452         puts("                             disable assertions with specified granularity");
453         puts("    -esa | -enablesystemassertions");
454         puts("                             enable system assertions");
455         puts("    -dsa | -disablesystemassertions");
456         puts("                             disable system assertions");
457
458 #ifdef ENABLE_JVMTI
459         puts("    -agentlib:<agent-lib-name>=<options>  library to load containg JVMTI agent");
460         puts ("                                         for jdwp help use: -agentlib:jdwp=help");
461         puts("    -agentpath:<path-to-agent>=<options>  path to library containg JVMTI agent");
462 #endif
463
464         /* exit with error code */
465
466         exit(1);
467 }   
468
469
470 static void Xusage(void)
471 {
472 #if defined(ENABLE_JIT)
473         puts("    -Xjit                    JIT mode execution (default)");
474 #endif
475 #if defined(ENABLE_INTRP)
476         puts("    -Xint                    interpreter mode execution");
477 #endif
478         puts("    -Xbootclasspath:<zip/jar files and directories separated by :>");
479     puts("                             value is set as bootstrap class path");
480         puts("    -Xbootclasspath/a:<zip/jar files and directories separated by :>");
481         puts("                             value is appended to the bootstrap class path");
482         puts("    -Xbootclasspath/p:<zip/jar files and directories separated by :>");
483         puts("                             value is prepended to the bootstrap class path");
484         puts("    -Xbootclasspath/c:<zip/jar files and directories separated by :>");
485         puts("                             value is used as Java core library, but the");
486         puts("                             hardcoded VM interface classes are prepended");
487         printf("    -Xms<size>               set the initial size of the heap (default: %dMB)\n", HEAP_STARTSIZE / 1024 / 1024);
488         printf("    -Xmx<size>               set the maximum size of the heap (default: %dMB)\n", HEAP_MAXSIZE / 1024 / 1024);
489         printf("    -Xss<size>               set the thread stack size (default: %dkB)\n", STACK_SIZE / 1024);
490
491 #if defined(ENABLE_PROFILING)
492         puts("    -Xprof[:bb]              collect and print profiling data");
493 #endif
494
495 #if defined(ENABLE_JVMTI)
496     /* -Xdebug option depend on gnu classpath JDWP options. options: 
497          transport=dt_socket,address=<hostname:port>,server=(y|n),suspend(y|n) */
498         puts("    -Xdebug                  enable remote debugging\n");
499         puts("    -Xrunjdwp transport=[dt_socket|...],address=<hostname:port>,server=[y|n],suspend=[y|n]\n");
500         puts("                             enable remote debugging\n");
501 #endif 
502
503         /* exit with error code */
504
505         exit(1);
506 }   
507
508
509 #if 0
510 static void XXusage(void)
511 {
512         puts("    -v                       write state-information");
513 #if !defined(NDEBUG)
514         puts("    -verbose[:jit|threads]");
515         puts("                             enable specific verbose output");
516         puts("    -debug-color             colored output for ANSI terms");
517 #endif
518 #ifdef TYPECHECK_VERBOSE
519         puts("    -verbosetc               write debug messages while typechecking");
520 #endif
521 #if defined(__ALPHA__)
522         puts("    -noieee                  don't use ieee compliant arithmetic");
523 #endif
524 #if defined(ENABLE_VERIFIER)
525         puts("    -noverify                don't verify classfiles");
526 #endif
527 #if defined(ENABLE_STATISTICS)
528         puts("    -time                    measure the runtime");
529         puts("    -stat                    detailed compiler statistics");
530 #endif
531         puts("    -log logfile             specify a name for the logfile");
532         puts("    -c(heck)b(ounds)         don't check array bounds");
533         puts("            s(ync)           don't check for synchronization");
534 #if defined(ENABLE_LOOP)
535         puts("    -oloop                   optimize array accesses in loops");
536 #endif
537         puts("    -l                       don't start the class after loading");
538 #if !defined(NDEBUG)
539         puts("    -all                     compile all methods, no execution");
540         puts("    -m                       compile only a specific method");
541         puts("    -sig                     specify signature for a specific method");
542 #endif
543
544         puts("    -s...                    show...");
545         puts("      (c)onstants            the constant pool");
546         puts("      (m)ethods              class fields and methods");
547         puts("      (u)tf                  the utf - hash");
548         puts("      (i)ntermediate         intermediate representation");
549 #if defined(ENABLE_DISASSEMBLER)
550         puts("      (a)ssembler            disassembled listing");
551         puts("      n(o)ps                 show NOPs in disassembler output");
552         puts("      (e)xceptionstubs       disassembled exception stubs (only with -sa)");
553         puts("      (n)ative               disassembled native stubs");
554 #endif
555         puts("      (d)atasegment          data segment listing");
556
557 #if defined(ENABLE_INLINING)
558         puts("    -i                       activate inlining");
559 #if !defined(NDEBUG)
560         puts("    -il                      log inlining");
561 #endif
562 #if defined(ENABLE_INLINING_DEBUG)
563         puts("    -ia                      use inlining for all methods");
564         puts("    -ii <size>               set minimum size for inlined result");
565         puts("    -im <size>               set maximum size for inlined result");
566         puts("    -ie <number>             stop inlining after the given number of roots");
567 #endif /* defined(ENABLE_INLINING_DEBUG) */
568 #endif /* defined(ENABLE_INLINING) */
569
570 #if defined(ENABLE_IFCONV)
571         puts("    -ifconv                  use if-conversion");
572 #endif
573 #if defined(ENABLE_LSRA)
574         puts("    -lsra                    use linear scan register allocation");
575 #endif
576 #if defined(ENABLE_SSA)
577         puts("    -lsra                    use linear scan register allocation (with SSA)");
578 #endif
579 #if defined(ENABLE_DEBUG_FILTER)
580         puts("    -XXfi <regex>            begin of dynamic scope for verbosecall filter");
581         puts("    -XXfx <regex>            end of dynamic scope for verbosecall filter");
582         puts("    -XXfm <regex>            filter for show options");
583 #endif
584         /* exit with error code */
585
586         exit(1);
587 }
588 #endif
589
590
591 /* version *********************************************************************
592
593    Only prints cacao version information.
594
595 *******************************************************************************/
596
597 static void version(bool opt_exit)
598 {
599         puts("java version \""JAVA_VERSION"\"");
600         puts("CACAO version "VERSION"");
601
602         puts("Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,");
603         puts("C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,");
604         puts("E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,");
605         puts("J. Wenninger, Institut f. Computersprachen - TU Wien\n");
606
607         puts("This program is free software; you can redistribute it and/or");
608         puts("modify it under the terms of the GNU General Public License as");
609         puts("published by the Free Software Foundation; either version 2, or (at");
610         puts("your option) any later version.\n");
611
612         puts("This program is distributed in the hope that it will be useful, but");
613         puts("WITHOUT ANY WARRANTY; without even the implied warranty of");
614         puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU");
615         puts("General Public License for more details.");
616
617         /* exit normally, if requested */
618
619         if (opt_exit)
620                 exit(0);
621 }
622
623
624 /* fullversion *****************************************************************
625
626    Prints a Sun compatible version information (required e.g. by
627    jpackage, www.jpackage.org).
628
629 *******************************************************************************/
630
631 static void fullversion(void)
632 {
633         puts("java full version \"cacao-"JAVA_VERSION"\"");
634
635         /* exit normally */
636
637         exit(0);
638 }
639
640
641 void vm_printconfig(void)
642 {
643         puts("Configure/Build options:\n");
644         puts("  ./configure: "VERSION_CONFIGURE_ARGS"");
645 #if defined(__VERSION__)
646         puts("  CC         : "VERSION_CC" ("__VERSION__")");
647 #else
648         puts("  CC         : "VERSION_CC"");
649 #endif
650         puts("  CFLAGS     : "VERSION_CFLAGS"\n");
651
652         puts("Default variables:\n");
653         printf("  maximum heap size              : %d\n", HEAP_MAXSIZE);
654         printf("  initial heap size              : %d\n", HEAP_STARTSIZE);
655         printf("  stack size                     : %d\n", STACK_SIZE);
656 #if defined(WITH_CLASSPATH_GNU)
657         puts("  java.boot.class.path           : "CACAO_VM_ZIP":"CLASSPATH_CLASSES"");
658 #else
659         puts("  java.boot.class.path           : "CLASSPATH_CLASSES"");
660 #endif
661         puts("  gnu.classpath.boot.library.path: "CLASSPATH_LIBDIR"/classpath\n");
662
663         puts("Runtime variables:\n");
664         printf("  maximum heap size              : %d\n", opt_heapmaxsize);
665         printf("  initial heap size              : %d\n", opt_heapstartsize);
666         printf("  stack size                     : %d\n", opt_stacksize);
667         printf("  java.boot.class.path           : %s\n", properties_get("java.boot.class.path"));
668         printf("  java.class.path                : %s\n", properties_get("java.class.path"));
669
670         printf("  gnu.classpath.boot.library.path: %s\n", properties_get("gnu.classpath.boot.library.path"));
671 }
672
673
674 /* forward declarations *******************************************************/
675
676 static char *vm_get_mainclass_from_jar(char *mainstring);
677 #if !defined(NDEBUG)
678 static void  vm_compile_all(void);
679 static void  vm_compile_method(void);
680 #endif
681
682
683 /* vm_createjvm ****************************************************************
684
685    Implementation for JNI_CreateJavaVM.
686
687 *******************************************************************************/
688
689 bool vm_createjvm(JavaVM **p_vm, void **p_env, void *vm_args)
690 {
691         JavaVMInitArgs *_vm_args;
692         _Jv_JNIEnv     *env;
693         _Jv_JavaVM     *vm;
694
695         /* get the arguments for the new JVM */
696
697         _vm_args = (JavaVMInitArgs *) vm_args;
698
699         /* get the VM and Env tables (must be set before vm_create) */
700
701         env = NEW(_Jv_JNIEnv);
702
703 #if defined(ENABLE_JNI)
704         env->env = &_Jv_JNINativeInterface;
705 #endif
706
707         /* XXX Set the global variable.  Maybe we should do that differently. */
708
709         _Jv_env = env;
710
711         /* create and fill a JavaVM structure */
712
713         vm = NEW(_Jv_JavaVM);
714
715 #if defined(ENABLE_JNI)
716         vm->functions = &_Jv_JNIInvokeInterface;
717 #endif
718
719         /* XXX Set the global variable.  Maybe we should do that differently. */
720         /* XXX JVMTI Agents needs a JavaVM  */
721
722         _Jv_jvm = vm;
723
724         /* actually create the JVM */
725
726         if (!vm_create(_vm_args))
727                 goto error;
728
729 #if defined(ENABLE_JNI)
730         /* setup the local ref table (must be created after vm_create) */
731
732         if (!localref_table_init())
733                 goto error;
734 #endif
735
736         /* now return the values */
737
738         *p_vm  = (JavaVM *) vm;
739         *p_env = (void *) env;
740
741         return true;
742
743  error:
744         /* release allocated memory */
745
746         FREE(env, _Jv_JNIEnv);
747         FREE(vm, _Jv_JavaVM);
748
749         return false;
750 }
751
752
753 /* vm_create *******************************************************************
754
755    Creates a JVM.  Called by vm_createjvm.
756
757 *******************************************************************************/
758
759 bool vm_create(JavaVMInitArgs *vm_args)
760 {
761         int   len;
762         char *p;
763         char *boot_class_path;
764         char *class_path;
765         int   opt;
766         int   i, j;
767         bool  opt_version;
768         bool  opt_exit;
769
770 #if defined(ENABLE_JVMTI)
771         lt_dlhandle  handle;
772         char *libname, *agentarg;
773         bool jdwp,agentbypath;
774         jdwp = agentbypath = false;
775 #endif
776
777 #if defined(ENABLE_VMLOG)
778         vmlog_cacao_init(vm_args);
779 #endif
780
781         /* check the JNI version requested */
782
783         switch (vm_args->version) {
784         case JNI_VERSION_1_1:
785                 break;
786         case JNI_VERSION_1_2:
787         case JNI_VERSION_1_4:
788                 break;
789         default:
790                 return false;
791         }
792
793         /* we only support 1 JVM instance */
794
795         if (vms > 0)
796                 return false;
797
798         if (atexit(vm_exit_handler))
799                 vm_abort("atexit failed: %s\n", strerror(errno));
800
801         if (opt_verbose)
802                 log_text("CACAO started -------------------------------------------------------");
803
804         /* We need to check if the actual size of a java.lang.Class object
805            is smaller or equal than the assumption made in
806            src/vmcore/class.h. */
807
808         if (sizeof(java_lang_Class) > sizeof(dummy_java_lang_Class))
809                 vm_abort("vm_create: java_lang_Class structure is bigger than classinfo.object (%d > %d)", sizeof(java_lang_Class), sizeof(dummy_java_lang_Class));
810
811         /* set the VM starttime */
812
813         _Jv_jvm->starttime = builtin_currenttimemillis();
814
815         /* interpret the options **************************************************/
816
817         opt_version       = false;
818         opt_exit          = false;
819
820         opt_noieee        = false;
821
822         opt_heapmaxsize   = HEAP_MAXSIZE;
823         opt_heapstartsize = HEAP_STARTSIZE;
824         opt_stacksize     = STACK_SIZE;
825
826
827 #if defined(ENABLE_JVMTI)
828         /* initialize JVMTI related  **********************************************/
829         jvmti = false;
830 #endif
831
832         /* Initialize and fill properties before command-line handling. */
833
834         properties_init();
835         properties_set();
836
837         /* iterate over all passed options */
838
839         while ((opt = options_get(opts, vm_args)) != OPT_DONE) {
840                 switch (opt) {
841                 case OPT_FOO:
842                         opt_foo = true;
843                         break;
844
845                 case OPT_IGNORE:
846                         break;
847                         
848                 case OPT_JAR:
849                         opt_jar = true;
850                         break;
851
852                 case OPT_D32:
853 #if SIZEOF_VOID_P == 8
854                         puts("Running a 32-bit JVM is not supported on this platform.");
855                         exit(1);
856 #endif
857                         break;
858
859                 case OPT_D64:
860 #if SIZEOF_VOID_P == 4
861                         puts("Running a 64-bit JVM is not supported on this platform.");
862                         exit(1);
863 #endif
864                         break;
865
866                 case OPT_CLASSPATH:
867                         /* Forget old classpath and set the argument as new
868                            classpath. */
869
870                         class_path = properties_get("java.class.path");
871
872                         MFREE(class_path, char, len);
873
874                         p = MNEW(char, strlen(opt_arg) + strlen("0"));
875
876                         strcpy(p, opt_arg);
877
878 #if defined(ENABLE_JAVASE)
879                         properties_add("java.class.path", p);
880 #endif
881                         break;
882
883                 case OPT_D:
884                         for (i = 0; i < strlen(opt_arg); i++) {
885                                 if (opt_arg[i] == '=') {
886                                         opt_arg[i] = '\0';
887                                         properties_add(opt_arg, opt_arg + i + 1);
888                                         goto opt_d_done;
889                                 }
890                         }
891
892                         /* if no '=' is given, just create an empty property */
893
894                         properties_add(opt_arg, "");
895
896                 opt_d_done:
897                         break;
898
899                 case OPT_BOOTCLASSPATH:
900                         /* Forget default bootclasspath and set the argument as
901                            new boot classpath. */
902
903                         boot_class_path = properties_get("sun.boot.class.path");
904
905                         MFREE(boot_class_path, char, len);
906
907                         p = MNEW(char, strlen(opt_arg) + strlen("0"));
908
909                         strcpy(p, opt_arg);
910
911 #if defined(ENABLE_JAVASE)
912                         properties_add("sun.boot.class.path", p);
913                         properties_add("java.boot.class.path", p);
914 #endif
915                         break;
916
917                 case OPT_BOOTCLASSPATH_A:
918                         /* Append to bootclasspath. */
919
920                         boot_class_path = properties_get("sun.boot.class.path");
921
922                         len = strlen(boot_class_path);
923
924                         p = MREALLOC(boot_class_path,
925                                                  char,
926                                                  len + strlen("0"),
927                                                  len + strlen(":") +
928                                                  strlen(opt_arg) + strlen("0"));
929
930                         strcat(p, ":");
931                         strcat(p, opt_arg);
932
933 #if defined(ENABLE_JAVASE)
934                         properties_add("sun.boot.class.path", p);
935                         properties_add("java.boot.class.path", p);
936 #endif
937                         break;
938
939                 case OPT_BOOTCLASSPATH_P:
940                         /* Prepend to bootclasspath. */
941
942                         boot_class_path = properties_get("sun.boot.class.path");
943
944                         len = strlen(boot_class_path);
945
946                         p = MNEW(char, strlen(opt_arg) + strlen(":") + len + strlen("0"));
947
948                         strcpy(p, opt_arg);
949                         strcat(p, ":");
950                         strcat(p, boot_class_path);
951
952                         MFREE(boot_class_path, char, len);
953
954 #if defined(ENABLE_JAVASE)
955                         properties_add("sun.boot.class.path", p);
956                         properties_add("java.boot.class.path", p);
957 #endif
958                         break;
959
960                 case OPT_BOOTCLASSPATH_C:
961                         /* Use as Java core library, but prepend VM interface
962                            classes. */
963
964                         boot_class_path = properties_get("sun.boot.class.path");
965
966                         MFREE(boot_class_path, char, strlen(boot_class_path));
967
968                         len =
969                                 strlen(CACAO_VM_ZIP) +
970                                 strlen(":") +
971                                 strlen(opt_arg) +
972                                 strlen("0");
973
974                         p = MNEW(char, len);
975
976                         strcpy(p, CACAO_VM_ZIP);
977                         strcat(p, ":");
978                         strcat(p, opt_arg);
979
980 #if defined(ENABLE_JAVASE)
981                         properties_add("sun.boot.class.path", p);
982                         properties_add("java.boot.class.path", p);
983 #endif
984                         break;
985
986 #if defined(ENABLE_JVMTI)
987                 case OPT_DEBUG:
988                         /* this option exists only for compatibility reasons */
989                         break;
990
991                 case OPT_NOAGENT:
992                         /* I don't know yet what Xnoagent should do. This is only for 
993                            compatiblity with eclipse - motse */
994                         break;
995
996                 case OPT_XRUNJDWP:
997                         agentbypath = true;
998                         jvmti       = true;
999                         jdwp        = true;
1000
1001                         len =
1002                                 strlen(CACAO_LIBDIR) +
1003                                 strlen("/libjdwp.so=") +
1004                                 strlen(opt_arg) +
1005                                 strlen("0");
1006
1007                         agentarg = MNEW(char, len);
1008
1009                         strcpy(agentarg, CACAO_LIBDIR);
1010                         strcat(agentarg, "/libjdwp.so=");
1011                         strcat(agentarg, &opt_arg[1]);
1012                         break;
1013
1014                 case OPT_AGENTPATH:
1015                         agentbypath = true;
1016
1017                 case OPT_AGENTLIB:
1018                         jvmti = true;
1019                         agentarg = opt_arg;
1020                         break;
1021 #endif
1022                         
1023                 case OPT_MX:
1024                 case OPT_MS:
1025                 case OPT_SS:
1026                         {
1027                                 char c;
1028                                 c = opt_arg[strlen(opt_arg) - 1];
1029
1030                                 if ((c == 'k') || (c == 'K')) {
1031                                         j = atoi(opt_arg) * 1024;
1032
1033                                 } else if ((c == 'm') || (c == 'M')) {
1034                                         j = atoi(opt_arg) * 1024 * 1024;
1035
1036                                 } else
1037                                         j = atoi(opt_arg);
1038
1039                                 if (opt == OPT_MX)
1040                                         opt_heapmaxsize = j;
1041                                 else if (opt == OPT_MS)
1042                                         opt_heapstartsize = j;
1043                                 else
1044                                         opt_stacksize = j;
1045                         }
1046                         break;
1047
1048                 case OPT_VERBOSE1:
1049                         opt_verbose = true;
1050                         break;
1051
1052                 case OPT_VERBOSE:
1053                         if (strcmp("class", opt_arg) == 0) {
1054                                 opt_verboseclass = true;
1055                         }
1056                         else if (strcmp("gc", opt_arg) == 0) {
1057                                 opt_verbosegc = true;
1058                         }
1059                         else if (strcmp("jni", opt_arg) == 0) {
1060                                 opt_verbosejni = true;
1061                         }
1062 #if !defined(NDEBUG)
1063                         else if (strcmp("jit", opt_arg) == 0) {
1064                                 opt_verbose = true;
1065                                 loadverbose = true;
1066                                 initverbose = true;
1067                                 compileverbose = true;
1068                         }
1069                         else if (strcmp("threads", opt_arg) == 0) {
1070                                 opt_verbosethreads = true;
1071                         }
1072 #endif
1073                         else {
1074                                 printf("Unknown -verbose option: %s\n", opt_arg);
1075                                 usage();
1076                         }
1077                         break;
1078
1079                 case OPT_DEBUGCOLOR:
1080                         opt_debugcolor = true;
1081                         break;
1082
1083 #if defined(ENABLE_VERIFIER) && defined(TYPECHECK_VERBOSE)
1084                 case OPT_VERBOSETC:
1085                         opt_typecheckverbose = true;
1086                         break;
1087 #endif
1088                                 
1089                 case OPT_VERSION:
1090                         opt_version = true;
1091                         opt_exit    = true;
1092                         break;
1093
1094                 case OPT_FULLVERSION:
1095                         fullversion();
1096                         break;
1097
1098                 case OPT_SHOWVERSION:
1099                         opt_version = true;
1100                         break;
1101
1102                 case OPT_NOIEEE:
1103                         opt_noieee = true;
1104                         break;
1105
1106 #if defined(ENABLE_VERIFIER)
1107                 case OPT_NOVERIFY:
1108                         opt_verify = false;
1109                         break;
1110 #endif
1111
1112 #if defined(ENABLE_STATISTICS)
1113                 case OPT_TIME:
1114                         opt_getcompilingtime = true;
1115                         opt_getloadingtime = true;
1116                         break;
1117                                         
1118                 case OPT_STAT:
1119                         opt_stat = true;
1120                         break;
1121 #endif
1122                                         
1123                 case OPT_LOG:
1124                         log_init(opt_arg);
1125                         break;
1126                         
1127                 case OPT_CHECK:
1128                         for (i = 0; i < strlen(opt_arg); i++) {
1129                                 switch (opt_arg[i]) {
1130                                 case 'b':
1131                                         checkbounds = false;
1132                                         break;
1133                                 case 's':
1134                                         checksync = false;
1135                                         break;
1136                                 default:
1137                                         usage();
1138                                 }
1139                         }
1140                         break;
1141                         
1142                 case OPT_LOAD:
1143                         opt_run = false;
1144                         makeinitializations = false;
1145                         break;
1146
1147 #if !defined(NDEBUG)
1148                 case OPT_ALL:
1149                         compileall = true;
1150                         opt_run = false;
1151                         makeinitializations = false;
1152                         break;
1153
1154                 case OPT_METHOD:
1155                         opt_run = false;
1156                         opt_method = opt_arg;
1157                         makeinitializations = false;
1158                         break;
1159
1160                 case OPT_SIGNATURE:
1161                         opt_signature = opt_arg;
1162                         break;
1163 #endif
1164
1165                 case OPT_SHOW:       /* Display options */
1166                         for (i = 0; i < strlen(opt_arg); i++) {         
1167                                 switch (opt_arg[i]) {
1168                                 case 'c':
1169                                         showconstantpool = true;
1170                                         break;
1171
1172                                 case 'u':
1173                                         showutf = true;
1174                                         break;
1175
1176                                 case 'm':
1177                                         showmethods = true;
1178                                         break;
1179
1180                                 case 'i':
1181                                         opt_showintermediate = true;
1182                                         compileverbose = true;
1183                                         break;
1184
1185 #if defined(ENABLE_DISASSEMBLER)
1186                                 case 'a':
1187                                         opt_showdisassemble = true;
1188                                         compileverbose = true;
1189                                         break;
1190
1191                                 case 'o':
1192                                         opt_shownops = true;
1193                                         break;
1194
1195                                 case 'e':
1196                                         opt_showexceptionstubs = true;
1197                                         break;
1198
1199                                 case 'n':
1200                                         opt_shownativestub = true;
1201                                         break;
1202 #endif
1203
1204                                 case 'd':
1205                                         opt_showddatasegment = true;
1206                                         break;
1207
1208                                 default:
1209                                         usage();
1210                                 }
1211                         }
1212                         break;
1213                         
1214 #if defined(ENABLE_LOOP)
1215                 case OPT_OLOOP:
1216                         opt_loops = true;
1217                         break;
1218 #endif
1219
1220 #if defined(ENABLE_INLINING)
1221 #if defined(ENABLE_INLINING_DEBUG)
1222                 case OPT_INLINE_DEBUG_ALL:
1223                         opt_inline_debug_all = true;
1224                         break;
1225                 case OPT_INLINE_DEBUG_END:
1226                         opt_inline_debug_end_counter = atoi(opt_arg);
1227                         break;
1228                 case OPT_INLINE_DEBUG_MIN:
1229                         opt_inline_debug_min_size = atoi(opt_arg);
1230                         break;
1231                 case OPT_INLINE_DEBUG_MAX:
1232                         opt_inline_debug_max_size = atoi(opt_arg);
1233                         break;
1234 #endif /* defined(ENABLE_INLINING_DEBUG) */
1235 #if !defined(NDEBUG)
1236                 case OPT_INLINE_LOG:
1237                         opt_inline_debug_log = true;
1238                         break;
1239 #endif /* !defined(NDEBUG) */
1240
1241                 case OPT_INLINING:
1242                         opt_inlining = true;
1243                         break;
1244 #endif /* defined(ENABLE_INLINING) */
1245
1246 #if defined(ENABLE_IFCONV)
1247                 case OPT_IFCONV:
1248                         opt_ifconv = true;
1249                         break;
1250 #endif
1251
1252 #if defined(ENABLE_LSRA) || defined(ENABLE_SSA)
1253                 case OPT_LSRA:
1254                         opt_lsra = true;
1255                         break;
1256 #endif
1257
1258                 case OPT_HELP:
1259                         usage();
1260                         break;
1261
1262                 case OPT_X:
1263                         Xusage();
1264                         break;
1265
1266                 case OPT_XX:
1267                         options_xx(opt_arg);
1268                         break;
1269
1270                 case OPT_EA:
1271                         /* currently ignored */
1272                         break;
1273
1274                 case OPT_DA:
1275                         /* currently ignored */
1276                         break;
1277
1278                 case OPT_ESA:
1279                         _Jv_jvm->Java_java_lang_VMClassLoader_defaultAssertionStatus = true;
1280                         break;
1281
1282                 case OPT_DSA:
1283                         _Jv_jvm->Java_java_lang_VMClassLoader_defaultAssertionStatus = false;
1284                         break;
1285
1286 #if defined(ENABLE_PROFILING)
1287                 case OPT_PROF_OPTION:
1288                         /* use <= to get the last \0 too */
1289
1290                         for (i = 0, j = 0; i <= strlen(opt_arg); i++) {
1291                                 if (opt_arg[i] == ',')
1292                                         opt_arg[i] = '\0';
1293
1294                                 if (opt_arg[i] == '\0') {
1295                                         if (strcmp("bb", opt_arg + j) == 0)
1296                                                 opt_prof_bb = true;
1297
1298                                         else {
1299                                                 printf("Unknown option: -Xprof:%s\n", opt_arg + j);
1300                                                 usage();
1301                                         }
1302
1303                                         /* set k to next char */
1304
1305                                         j = i + 1;
1306                                 }
1307                         }
1308                         /* fall through */
1309
1310                 case OPT_PROF:
1311                         opt_prof = true;
1312                         break;
1313 #endif
1314
1315                 case OPT_JIT:
1316 #if defined(ENABLE_JIT)
1317                         opt_jit = true;
1318 #else
1319                         printf("-Xjit option not enabled.\n");
1320                         exit(1);
1321 #endif
1322                         break;
1323
1324                 case OPT_INTRP:
1325 #if defined(ENABLE_INTRP)
1326                         opt_intrp = true;
1327 #else
1328                         printf("-Xint option not enabled.\n");
1329                         exit(1);
1330 #endif
1331                         break;
1332
1333 #if defined(ENABLE_INTRP)
1334                 case OPT_STATIC_SUPERS:
1335                         opt_static_supers = atoi(opt_arg);
1336                         break;
1337
1338                 case OPT_NO_DYNAMIC:
1339                         opt_no_dynamic = true;
1340                         break;
1341
1342                 case OPT_NO_REPLICATION:
1343                         opt_no_replication = true;
1344                         break;
1345
1346                 case OPT_NO_QUICKSUPER:
1347                         opt_no_quicksuper = true;
1348                         break;
1349
1350                 case OPT_TRACE:
1351                         vm_debug = true;
1352                         break;
1353 #endif
1354
1355 #if defined(ENABLE_DEBUG_FILTER)
1356                 case OPT_FILTER_VERBOSECALL_INCLUDE:
1357                         opt_filter_verbosecall_include = opt_arg;
1358                         break;
1359
1360                 case OPT_FILTER_VERBOSECALL_EXCLUDE:
1361                         opt_filter_verbosecall_exclude = opt_arg;
1362                         break;
1363
1364                 case OPT_FILTER_SHOW_METHOD:
1365                         opt_filter_show_method = opt_arg;
1366                         break;
1367
1368 #endif
1369                 default:
1370                         printf("Unknown option: %s\n",
1371                                    vm_args->options[opt_index].optionString);
1372                         usage();
1373                 }
1374         }
1375
1376         /* get the main class *****************************************************/
1377
1378         if (opt_index < vm_args->nOptions) {
1379                 mainstring = vm_args->options[opt_index++].optionString;
1380
1381                 /* Put the jar file into the classpath (if any). */
1382
1383                 if (opt_jar == true) {
1384                         /* free old classpath */
1385
1386 /*                      MFREE(_Jv_classpath, char, strlen(_Jv_classpath)); */
1387
1388                         /* put jarfile into classpath */
1389
1390                         p = MNEW(char, strlen(mainstring) + strlen("0"));
1391
1392                         strcpy(p, mainstring);
1393
1394 #if defined(ENABLE_JAVASE)
1395                         properties_add("java.class.path", p);
1396 #endif
1397                 }
1398                 else {
1399                         /* replace .'s with /'s in classname */
1400
1401                         for (i = strlen(mainstring) - 1; i >= 0; i--)
1402                                 if (mainstring[i] == '.')
1403                                         mainstring[i] = '/';
1404                 }
1405         }
1406
1407 #if defined(ENABLE_JVMTI)
1408         if (jvmti) {
1409                 jvmti_set_phase(JVMTI_PHASE_ONLOAD);
1410                 jvmti_agentload(agentarg, agentbypath, &handle, &libname);
1411
1412                 if (jdwp)
1413                         MFREE(agentarg, char, strlen(agentarg));
1414
1415                 jvmti_set_phase(JVMTI_PHASE_PRIMORDIAL);
1416         }
1417 #endif
1418
1419         /* initialize this JVM ****************************************************/
1420
1421         vm_initializing = true;
1422
1423         /* initialize the garbage collector */
1424
1425         gc_init(opt_heapmaxsize, opt_heapstartsize);
1426
1427 #if defined(ENABLE_THREADS)
1428         /* AFTER: gc_init (directly after, as this initializes the
1429            stopworldlock lock */
1430
1431         threads_preinit();
1432 #endif
1433
1434         /* install architecture dependent signal handlers */
1435
1436         if (!signal_init())
1437                 vm_abort("vm_create: signal_init failed");
1438
1439 #if defined(ENABLE_INTRP)
1440         /* Allocate main thread stack on the Java heap. */
1441
1442         if (opt_intrp) {
1443                 intrp_main_stack = GCMNEW(u1, opt_stacksize);
1444                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1445         }
1446 #endif
1447
1448         /* AFTER: threads_preinit */
1449
1450         if (!string_init())
1451                 vm_abort("vm_create: string_init failed");
1452
1453         /* AFTER: threads_preinit */
1454
1455         if (!utf8_init())
1456                 vm_abort("vm_create: utf8_init failed");
1457
1458         /* AFTER: thread_preinit */
1459
1460         if (!suck_init())
1461                 vm_abort("vm_create: suck_init failed");
1462
1463         suck_add_from_property("java.endorsed.dirs");
1464
1465         /* Now we have all options handled and we can print the version
1466            information.
1467
1468            AFTER: suck_add_from_property("java.endorsed.dirs"); */
1469
1470         if (opt_version)
1471                 version(opt_exit);
1472
1473         /* AFTER: utf8_init */
1474
1475         boot_class_path = properties_get("sun.boot.class.path");
1476         suck_add(boot_class_path);
1477
1478         /* initialize the classcache hashtable stuff: lock, hashtable
1479            (must be done _after_ threads_preinit) */
1480
1481         if (!classcache_init())
1482                 vm_abort("vm_create: classcache_init failed");
1483
1484         /* initialize the memory subsystem (must be done _after_
1485            threads_preinit) */
1486
1487         if (!memory_init())
1488                 vm_abort("vm_create: memory_init failed");
1489
1490         /* initialize the finalizer stuff (must be done _after_
1491            threads_preinit) */
1492
1493         if (!finalizer_init())
1494                 vm_abort("vm_create: finalizer_init failed");
1495
1496         /* initialize the codegen subsystems */
1497
1498         codegen_init();
1499
1500         /* initializes jit compiler */
1501
1502         jit_init();
1503
1504         /* machine dependent initialization */
1505
1506 #if defined(ENABLE_JIT)
1507 # if defined(ENABLE_INTRP)
1508         if (opt_intrp)
1509                 intrp_md_init();
1510         else
1511 # endif
1512                 md_init();
1513 #else
1514         intrp_md_init();
1515 #endif
1516
1517         /* initialize the loader subsystems (must be done _after_
1518        classcache_init) */
1519
1520         if (!loader_init())
1521                 vm_abort("vm_create: loader_init failed");
1522
1523         /* Link some important VM classes. */
1524         /* AFTER: utf8_init */
1525
1526         if (!linker_init())
1527                 vm_abort("vm_create: linker_init failed");
1528
1529         if (!primitive_init())
1530                 vm_abort("vm_create: primitive_init failed");
1531
1532         if (!exceptions_init())
1533                 vm_abort("vm_create: exceptions_init failed");
1534
1535         if (!builtin_init())
1536                 vm_abort("vm_create: builtin_init failed");
1537
1538         /* Initialize the native subsystem. */
1539         /* BEFORE: threads_init */
1540
1541         if (!native_init())
1542                 vm_abort("vm_create: native_init failed");
1543
1544         /* Register the native methods implemented in the VM. */
1545         /* BEFORE: threads_init */
1546
1547         if (!nativevm_preinit())
1548                 vm_abort("vm_create: nativevm_preinit failed");
1549
1550 #if defined(ENABLE_JNI)
1551         /* Initialize the JNI subsystem (must be done _before_
1552            threads_init, as threads_init can call JNI methods
1553            (e.g. NewGlobalRef). */
1554
1555         if (!jni_init())
1556                 vm_abort("vm_create: jni_init failed");
1557 #endif
1558
1559 #if defined(ENABLE_THREADS)
1560         if (!threads_init())
1561                 vm_abort("vm_create: threads_init failed");
1562 #endif
1563
1564         /* Initialize the native VM subsystem. */
1565         /* AFTER: threads_init (at least for SUN's classes) */
1566
1567         if (!nativevm_init())
1568                 vm_abort("vm_create: nativevm_init failed");
1569
1570 #if defined(ENABLE_PROFILING)
1571         /* initialize profiling */
1572
1573         if (!profile_init())
1574                 vm_abort("vm_create: profile_init failed");
1575 #endif
1576
1577 #if defined(ENABLE_THREADS)
1578         /* initialize recompilation */
1579
1580         if (!recompile_init())
1581                 vm_abort("vm_create: recompile_init failed");
1582
1583         /* start the signal handler thread */
1584
1585 #if defined(__LINUX__)
1586         /* XXX Remove for exact-GC. */
1587         if (threads_pthreads_implementation_nptl)
1588 #endif
1589                 if (!signal_start_thread())
1590                         vm_abort("vm_create: signal_start_thread failed");
1591
1592         /* finally, start the finalizer thread */
1593
1594         if (!finalizer_start_thread())
1595                 vm_abort("vm_create: finalizer_start_thread failed");
1596
1597 # if !defined(NDEBUG)
1598         /* start the memory profiling thread */
1599
1600         if (opt_ProfileMemoryUsage || opt_ProfileGCMemoryUsage)
1601                 if (!memory_start_thread())
1602                         vm_abort("vm_create: memory_start_thread failed");
1603 # endif
1604
1605         /* start the recompilation thread (must be done before the
1606            profiling thread) */
1607
1608         if (!recompile_start_thread())
1609                 vm_abort("vm_create: recompile_start_thread failed");
1610
1611 # if defined(ENABLE_PROFILING)
1612         /* start the profile sampling thread */
1613
1614 /*      if (opt_prof) */
1615 /*              if (!profile_start_thread()) */
1616 /*                      vm_abort("vm_create: profile_start_thread failed"); */
1617 # endif
1618 #endif
1619
1620 #if defined(ENABLE_JVMTI)
1621         if (jvmti) {
1622                 /* add agent library to native library hashtable */
1623                 native_hashtable_library_add(utf_new_char(libname), class_java_lang_Object->classloader, handle);
1624         }
1625 #endif
1626
1627         /* increment the number of VMs */
1628
1629         vms++;
1630
1631         /* initialization is done */
1632
1633         vm_initializing = false;
1634
1635         /* everything's ok */
1636
1637         return true;
1638 }
1639
1640
1641 /* vm_run **********************************************************************
1642
1643    Runs the main-method of the passed class.
1644
1645 *******************************************************************************/
1646
1647 void vm_run(JavaVM *vm, JavaVMInitArgs *vm_args)
1648 {
1649         utf                       *mainutf;
1650         classinfo                 *mainclass;
1651         java_handle_t             *e;
1652         methodinfo                *m;
1653         java_handle_objectarray_t *oa; 
1654         s4                         oalength;
1655         utf                       *u;
1656         java_handle_t             *s;
1657         s4                         status;
1658         s4                         i;
1659
1660 #if !defined(NDEBUG)
1661         if (compileall) {
1662                 vm_compile_all();
1663                 return;
1664         }
1665
1666         if (opt_method != NULL) {
1667                 vm_compile_method();
1668                 return;
1669         }
1670 #endif /* !defined(NDEBUG) */
1671
1672         /* should we run the main-method? */
1673
1674         if (mainstring == NULL)
1675                 usage();
1676
1677         /* set return value to OK */
1678
1679         status = 0;
1680
1681         if (opt_jar == true) {
1682                 /* open jar file with java.util.jar.JarFile */
1683
1684                 mainstring = vm_get_mainclass_from_jar(mainstring);
1685
1686                 if (mainstring == NULL)
1687                         vm_exit(1);
1688         }
1689
1690         /* load the main class */
1691
1692         mainutf = utf_new_char(mainstring);
1693
1694 #if defined(ENABLE_JAVAME_CLDC1_1)
1695         mainclass = load_class_bootstrap(mainutf);
1696 #else
1697         mainclass = load_class_from_sysloader(mainutf);
1698 #endif
1699
1700         /* error loading class */
1701
1702         e = exceptions_get_and_clear_exception();
1703
1704         if ((e != NULL) || (mainclass == NULL)) {
1705                 exceptions_throw_noclassdeffounderror_cause(e);
1706                 exceptions_print_stacktrace(); 
1707                 vm_exit(1);
1708         }
1709
1710         if (!link_class(mainclass)) {
1711                 exceptions_print_stacktrace();
1712                 vm_exit(1);
1713         }
1714                         
1715         /* find the `main' method of the main class */
1716
1717         m = class_resolveclassmethod(mainclass,
1718                                                                  utf_new_char("main"), 
1719                                                                  utf_new_char("([Ljava/lang/String;)V"),
1720                                                                  class_java_lang_Object,
1721                                                                  false);
1722
1723         if (exceptions_get_exception()) {
1724                 exceptions_print_stacktrace();
1725                 vm_exit(1);
1726         }
1727
1728         /* there is no main method or it isn't static */
1729
1730         if ((m == NULL) || !(m->flags & ACC_STATIC)) {
1731                 exceptions_clear_exception();
1732                 exceptions_throw_nosuchmethoderror(mainclass,
1733                                                                                    utf_new_char("main"), 
1734                                                                                    utf_new_char("([Ljava/lang/String;)V"));
1735
1736                 exceptions_print_stacktrace();
1737                 vm_exit(1);
1738         }
1739
1740         /* build argument array */
1741
1742         oalength = vm_args->nOptions - opt_index;
1743
1744         oa = builtin_anewarray(oalength, class_java_lang_String);
1745
1746         for (i = 0; i < oalength; i++) {
1747                 u = utf_new_char(vm_args->options[opt_index + i].optionString);
1748                 s = javastring_new(u);
1749
1750                 LLNI_objectarray_element_set(oa, i, s);
1751         }
1752
1753 #ifdef TYPEINFO_DEBUG_TEST
1754         /* test the typeinfo system */
1755         typeinfo_test();
1756 #endif
1757         /*class_showmethods(currentThread->group->header.vftbl->class); */
1758
1759 #if defined(ENABLE_JVMTI)
1760         jvmti_set_phase(JVMTI_PHASE_LIVE);
1761 #endif
1762
1763         /* set ThreadMXBean variables */
1764
1765         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1766         _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1767
1768         if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1769                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1770                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1771                         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1772
1773         /* start the main thread */
1774
1775         (void) vm_call_method(m, NULL, oa);
1776
1777         /* exception occurred? */
1778
1779         if (exceptions_get_exception()) {
1780                 exceptions_print_stacktrace();
1781                 status = 1;
1782         }
1783
1784         /* unload the JavaVM */
1785
1786         (void) vm_destroy(vm);
1787
1788         /* and exit */
1789
1790         vm_exit(status);
1791 }
1792
1793
1794 /* vm_destroy ******************************************************************
1795
1796    Unloads a Java VM and reclaims its resources.
1797
1798 *******************************************************************************/
1799
1800 s4 vm_destroy(JavaVM *vm)
1801 {
1802 #if defined(ENABLE_THREADS)
1803         threads_join_all_threads();
1804 #endif
1805
1806         /* everything's ok */
1807
1808         return 0;
1809 }
1810
1811
1812 /* vm_exit *********************************************************************
1813
1814    Calls java.lang.System.exit(I)V to exit the JavaVM correctly.
1815
1816 *******************************************************************************/
1817
1818 void vm_exit(s4 status)
1819 {
1820         methodinfo *m;
1821
1822         /* signal that we are exiting */
1823
1824         vm_exiting = true;
1825
1826         assert(class_java_lang_System);
1827         assert(class_java_lang_System->state & CLASS_LOADED);
1828
1829 #if defined(ENABLE_JVMTI)
1830         if (jvmti || (dbgcom!=NULL)) {
1831                 jvmti_set_phase(JVMTI_PHASE_DEAD);
1832                 if (jvmti) jvmti_agentunload();
1833         }
1834 #endif
1835
1836         if (!link_class(class_java_lang_System)) {
1837                 exceptions_print_stacktrace();
1838                 exit(1);
1839         }
1840
1841         /* call java.lang.System.exit(I)V */
1842
1843         m = class_resolveclassmethod(class_java_lang_System,
1844                                                                  utf_new_char("exit"),
1845                                                                  utf_int__void,
1846                                                                  class_java_lang_Object,
1847                                                                  true);
1848         
1849         if (m == NULL) {
1850                 exceptions_print_stacktrace();
1851                 exit(1);
1852         }
1853
1854         /* call the exit function with passed exit status */
1855
1856         (void) vm_call_method(m, NULL, status);
1857
1858         /* If we had an exception, just ignore the exception and exit with
1859            the proper code. */
1860
1861         vm_shutdown(status);
1862 }
1863
1864
1865 /* vm_shutdown *****************************************************************
1866
1867    Terminates the system immediately without freeing memory explicitly
1868    (to be used only for abnormal termination).
1869         
1870 *******************************************************************************/
1871
1872 void vm_shutdown(s4 status)
1873 {
1874         if (opt_verbose 
1875 #if defined(ENABLE_STATISTICS)
1876                 || opt_getcompilingtime || opt_stat
1877 #endif
1878            ) 
1879         {
1880                 log_text("CACAO terminated by shutdown");
1881                 dolog("Exit status: %d\n", (s4) status);
1882
1883         }
1884
1885 #if defined(ENABLE_JVMTI)
1886         /* terminate cacaodbgserver */
1887         if (dbgcom!=NULL) {
1888                 pthread_mutex_lock(&dbgcomlock);
1889                 dbgcom->running=1;
1890                 pthread_mutex_unlock(&dbgcomlock);
1891                 jvmti_cacaodbgserver_quit();
1892         }       
1893 #endif
1894
1895         exit(status);
1896 }
1897
1898
1899 /* vm_exit_handler *************************************************************
1900
1901    The exit_handler function is called upon program termination.
1902
1903    ATTENTION: Don't free system resources here! Some threads may still
1904    be running as this is called from VMRuntime.exit(). The OS does the
1905    cleanup for us.
1906
1907 *******************************************************************************/
1908
1909 void vm_exit_handler(void)
1910 {
1911 #if !defined(NDEBUG)
1912         if (showmethods)
1913                 class_showmethods(mainclass);
1914
1915         if (showconstantpool)
1916                 class_showconstantpool(mainclass);
1917
1918         if (showutf)
1919                 utf_show();
1920
1921 # if defined(ENABLE_PROFILING)
1922         if (opt_prof)
1923                 profile_printstats();
1924 # endif
1925 #endif /* !defined(NDEBUG) */
1926
1927 #if defined(ENABLE_RT_TIMING)
1928         rt_timing_print_time_stats(stderr);
1929 #endif
1930
1931 #if defined(ENABLE_CYCLES_STATS)
1932         builtin_print_cycles_stats(stderr);
1933         stacktrace_print_cycles_stats(stderr);
1934 #endif
1935
1936         if (opt_verbose 
1937 #if defined(ENABLE_STATISTICS)
1938                 || opt_getcompilingtime || opt_stat
1939 #endif
1940            ) 
1941         {
1942                 log_text("CACAO terminated");
1943
1944 #if defined(ENABLE_STATISTICS)
1945                 if (opt_stat) {
1946                         print_stats();
1947 #ifdef TYPECHECK_STATISTICS
1948                         typecheck_print_statistics(get_logfile());
1949 #endif
1950                 }
1951
1952                 if (opt_getcompilingtime)
1953                         print_times();
1954 #endif /* defined(ENABLE_STATISTICS) */
1955         }
1956         /* vm_print_profile(stderr);*/
1957 }
1958
1959
1960 /* vm_abort ********************************************************************
1961
1962    Prints an error message and aborts the VM.
1963
1964 *******************************************************************************/
1965
1966 void vm_abort(const char *text, ...)
1967 {
1968         va_list ap;
1969
1970         /* print the log message */
1971
1972         log_start();
1973
1974         va_start(ap, text);
1975         log_vprint(text, ap);
1976         va_end(ap);
1977
1978         log_finish();
1979
1980         /* now abort the VM */
1981
1982         abort();
1983 }
1984
1985
1986 /* vm_get_mainclass_from_jar ***************************************************
1987
1988    Gets the name of the main class from a JAR's manifest file.
1989
1990 *******************************************************************************/
1991
1992 static char *vm_get_mainclass_from_jar(char *mainstring)
1993 {
1994         classinfo     *c;
1995         java_handle_t *o;
1996         methodinfo    *m;
1997         java_handle_t *s;
1998
1999         c = load_class_from_sysloader(utf_new_char("java/util/jar/JarFile"));
2000
2001         if (c == NULL) {
2002                 exceptions_print_stacktrace();
2003                 return NULL;
2004         }
2005
2006         /* create JarFile object */
2007
2008         o = builtin_new(c);
2009
2010         if (o == NULL) {
2011                 exceptions_print_stacktrace();
2012                 return NULL;
2013         }
2014
2015         m = class_resolveclassmethod(c,
2016                                                                  utf_init, 
2017                                                                  utf_java_lang_String__void,
2018                                                                  class_java_lang_Object,
2019                                                                  true);
2020
2021         if (m == NULL) {
2022                 exceptions_print_stacktrace();
2023                 return NULL;
2024         }
2025
2026         s = javastring_new_from_ascii(mainstring);
2027
2028         (void) vm_call_method(m, o, s);
2029
2030         if (exceptions_get_exception()) {
2031                 exceptions_print_stacktrace();
2032                 return NULL;
2033         }
2034
2035         /* get manifest object */
2036
2037         m = class_resolveclassmethod(c,
2038                                                                  utf_new_char("getManifest"), 
2039                                                                  utf_new_char("()Ljava/util/jar/Manifest;"),
2040                                                                  class_java_lang_Object,
2041                                                                  true);
2042
2043         if (m == NULL) {
2044                 exceptions_print_stacktrace();
2045                 return NULL;
2046         }
2047
2048         o = vm_call_method(m, o);
2049
2050         if (o == NULL) {
2051                 fprintf(stderr, "Could not get manifest from %s (invalid or corrupt jarfile?)\n", mainstring);
2052                 return NULL;
2053         }
2054
2055
2056         /* get Main Attributes */
2057
2058         m = class_resolveclassmethod(o->vftbl->class,
2059                                                                  utf_new_char("getMainAttributes"), 
2060                                                                  utf_new_char("()Ljava/util/jar/Attributes;"),
2061                                                                  class_java_lang_Object,
2062                                                                  true);
2063
2064         if (m == NULL) {
2065                 exceptions_print_stacktrace();
2066                 return NULL;
2067         }
2068
2069         o = vm_call_method(m, o);
2070
2071         if (o == NULL) {
2072                 fprintf(stderr, "Could not get main attributes from %s (invalid or corrupt jarfile?)\n", mainstring);
2073                 return NULL;
2074         }
2075
2076
2077         /* get property Main-Class */
2078
2079         m = class_resolveclassmethod(o->vftbl->class,
2080                                                                  utf_new_char("getValue"), 
2081                                                                  utf_new_char("(Ljava/lang/String;)Ljava/lang/String;"),
2082                                                                  class_java_lang_Object,
2083                                                                  true);
2084
2085         if (m == NULL) {
2086                 exceptions_print_stacktrace();
2087                 return NULL;
2088         }
2089
2090         s = javastring_new_from_ascii("Main-Class");
2091
2092         o = vm_call_method(m, o, s);
2093
2094         if (o == NULL) {
2095                 exceptions_print_stacktrace();
2096                 return NULL;
2097         }
2098
2099         return javastring_tochar(o);
2100 }
2101
2102
2103 /* vm_compile_all **************************************************************
2104
2105    Compile all methods found in the bootclasspath.
2106
2107 *******************************************************************************/
2108
2109 #if !defined(NDEBUG)
2110 static void vm_compile_all(void)
2111 {
2112         classinfo              *c;
2113         methodinfo             *m;
2114         u4                      slot;
2115         classcache_name_entry  *nmen;
2116         classcache_class_entry *clsen;
2117         s4                      i;
2118
2119         /* create all classes found in the bootclasspath */
2120         /* XXX currently only works with zip/jar's */
2121
2122         loader_load_all_classes();
2123
2124         /* link all classes */
2125
2126         for (slot = 0; slot < hashtable_classcache.size; slot++) {
2127                 nmen = (classcache_name_entry *) hashtable_classcache.ptr[slot];
2128
2129                 for (; nmen; nmen = nmen->hashlink) {
2130                         /* iterate over all class entries */
2131
2132                         for (clsen = nmen->classes; clsen; clsen = clsen->next) {
2133                                 c = clsen->classobj;
2134
2135                                 if (c == NULL)
2136                                         continue;
2137
2138                                 if (!(c->state & CLASS_LINKED)) {
2139                                         if (!link_class(c)) {
2140                                                 fprintf(stderr, "Error linking: ");
2141                                                 utf_fprint_printable_ascii_classname(stderr, c->name);
2142                                                 fprintf(stderr, "\n");
2143
2144                                                 /* print out exception and cause */
2145
2146                                                 exceptions_print_current_exception();
2147
2148                                                 /* goto next class */
2149
2150                                                 continue;
2151                                         }
2152                                 }
2153
2154                                 /* compile all class methods */
2155
2156                                 for (i = 0; i < c->methodscount; i++) {
2157                                         m = &(c->methods[i]);
2158
2159                                         if (m->jcode != NULL) {
2160                                                 if (!jit_compile(m)) {
2161                                                         fprintf(stderr, "Error compiling: ");
2162                                                         utf_fprint_printable_ascii_classname(stderr, c->name);
2163                                                         fprintf(stderr, ".");
2164                                                         utf_fprint_printable_ascii(stderr, m->name);
2165                                                         utf_fprint_printable_ascii(stderr, m->descriptor);
2166                                                         fprintf(stderr, "\n");
2167
2168                                                         /* print out exception and cause */
2169
2170                                                         exceptions_print_current_exception();
2171                                                 }
2172                                         }
2173                                 }
2174                         }
2175                 }
2176         }
2177 }
2178 #endif /* !defined(NDEBUG) */
2179
2180
2181 /* vm_compile_method ***********************************************************
2182
2183    Compile a specific method.
2184
2185 *******************************************************************************/
2186
2187 #if !defined(NDEBUG)
2188 static void vm_compile_method(void)
2189 {
2190         methodinfo *m;
2191
2192         /* create, load and link the main class */
2193
2194         mainclass = load_class_bootstrap(utf_new_char(mainstring));
2195
2196         if (mainclass == NULL)
2197                 exceptions_print_stacktrace();
2198
2199         if (!link_class(mainclass))
2200                 exceptions_print_stacktrace();
2201
2202         if (opt_signature != NULL) {
2203                 m = class_resolveclassmethod(mainclass,
2204                                                                          utf_new_char(opt_method),
2205                                                                          utf_new_char(opt_signature),
2206                                                                          mainclass,
2207                                                                          false);
2208         }
2209         else {
2210                 m = class_resolveclassmethod(mainclass,
2211                                                                          utf_new_char(opt_method),
2212                                                                          NULL,
2213                                                                          mainclass,
2214                                                                          false);
2215         }
2216
2217         if (m == NULL)
2218                 vm_abort("vm_compile_method: java.lang.NoSuchMethodException: %s.%s",
2219                                  opt_method, opt_signature ? opt_signature : "");
2220                 
2221         jit_compile(m);
2222 }
2223 #endif /* !defined(NDEBUG) */
2224
2225
2226 /* vm_array_store_int **********************************************************
2227
2228    Helper function to store an integer into the argument array, taking
2229    care of architecture specific issues.
2230
2231 *******************************************************************************/
2232
2233 static void vm_array_store_int(uint64_t *array, paramdesc *pd, int32_t value)
2234 {
2235         int32_t index;
2236
2237         if (!pd->inmemory) {
2238                 index        = pd->index;
2239                 array[index] = (int64_t) value;
2240         }
2241         else {
2242                 index        = ARG_CNT + pd->index;
2243 #if SIZEOF_VOID_P == 8
2244                 array[index] = (int64_t) value;
2245 #else
2246 # if WORDS_BIGENDIAN == 1
2247                 array[index] = ((int64_t) value) << 32;
2248 # else
2249                 array[index] = (int64_t) value;
2250 # endif
2251 #endif
2252         }
2253 }
2254
2255
2256 /* vm_array_store_lng **********************************************************
2257
2258    Helper function to store a long into the argument array, taking
2259    care of architecture specific issues.
2260
2261 *******************************************************************************/
2262
2263 static void vm_array_store_lng(uint64_t *array, paramdesc *pd, int64_t value)
2264 {
2265         int32_t index;
2266
2267 #if SIZEOF_VOID_P == 8
2268         if (!pd->inmemory)
2269                 index = pd->index;
2270         else
2271                 index = ARG_CNT + pd->index;
2272
2273         array[index] = value;
2274 #else
2275         if (!pd->inmemory) {
2276                 /* move low and high 32-bits into it's own argument slot */
2277
2278                 index        = GET_LOW_REG(pd->index);
2279                 array[index] = value & 0x00000000ffffffff;
2280
2281                 index        = GET_HIGH_REG(pd->index);
2282                 array[index] = value >> 32;
2283         }
2284         else {
2285                 index        = ARG_CNT + pd->index;
2286                 array[index] = value;
2287         }
2288 #endif
2289 }
2290
2291
2292 /* vm_array_store_flt **********************************************************
2293
2294    Helper function to store a float into the argument array, taking
2295    care of architecture specific issues.
2296
2297 *******************************************************************************/
2298
2299 static void vm_array_store_flt(uint64_t *array, paramdesc *pd, uint64_t value)
2300 {
2301         int32_t index;
2302
2303         if (!pd->inmemory) {
2304 #if defined(SUPPORT_PASS_FLOATARGS_IN_INTREGS)
2305                 index        = pd->index;
2306 #else
2307                 index        = INT_ARG_CNT + pd->index;
2308 #endif
2309 #if WORDS_BIGENDIAN == 1 && !defined(__POWERPC__) && !defined(__POWERPC64__) && !defined(__S390__)
2310                 array[index] = value >> 32;
2311 #else
2312                 array[index] = value;
2313 #endif
2314         }
2315         else {
2316                 index        = ARG_CNT + pd->index;
2317 #if defined(__SPARC_64__)
2318                 array[index] = value >> 32;
2319 #else
2320                 array[index] = value;
2321 #endif
2322         }
2323 }
2324
2325
2326 /* vm_array_store_dbl **********************************************************
2327
2328    Helper function to store a double into the argument array, taking
2329    care of architecture specific issues.
2330
2331 *******************************************************************************/
2332
2333 static void vm_array_store_dbl(uint64_t *array, paramdesc *pd, uint64_t value)
2334 {
2335         int32_t index;
2336
2337         if (!pd->inmemory) {
2338 #if SIZEOF_VOID_P != 8 && defined(SUPPORT_PASS_FLOATARGS_IN_INTREGS)
2339                 index        = GET_LOW_REG(pd->index);
2340                 array[index] = value & 0x00000000ffffffff;
2341
2342                 index        = GET_HIGH_REG(pd->index);
2343                 array[index] = value >> 32;
2344 #else
2345                 index        = INT_ARG_CNT + pd->index;
2346                 array[index] = value;
2347 #endif
2348         }
2349         else {
2350                 index        = ARG_CNT + pd->index;
2351                 array[index] = value;
2352         }
2353 }
2354
2355
2356 /* vm_array_store_adr **********************************************************
2357
2358    Helper function to store an address into the argument array, taking
2359    care of architecture specific issues.
2360
2361 *******************************************************************************/
2362
2363 static void vm_array_store_adr(uint64_t *array, paramdesc *pd, void *value)
2364 {
2365         int32_t index;
2366
2367         if (!pd->inmemory) {
2368 #if defined(HAS_ADDRESS_REGISTER_FILE)
2369                 /* When the architecture has address registers, place them
2370                    after integer and float registers. */
2371
2372                 index        = INT_ARG_CNT + FLT_ARG_CNT + pd->index;
2373 #else
2374                 index        = pd->index;
2375 #endif
2376                 array[index] = (uint64_t) (intptr_t) value;
2377         }
2378         else {
2379                 index        = ARG_CNT + pd->index;
2380 #if SIZEOF_VOID_P == 8
2381                 array[index] = (uint64_t) (intptr_t) value;
2382 #else
2383 # if WORDS_BIGENDIAN == 1
2384                 array[index] = ((uint64_t) (intptr_t) value) << 32;
2385 # else
2386                 array[index] = (uint64_t) (intptr_t) value;
2387 # endif
2388 #endif
2389         }
2390 }
2391
2392
2393 /* vm_array_from_valist ********************************************************
2394
2395    XXX
2396
2397 *******************************************************************************/
2398
2399 uint64_t *vm_array_from_valist(methodinfo *m, java_object_t *o, va_list ap)
2400 {
2401         methoddesc *md;
2402         paramdesc  *pd;
2403         typedesc   *td;
2404         uint64_t   *array;
2405         int32_t     i;
2406         imm_union   value;
2407
2408         /* get the descriptors */
2409
2410         md = m->parseddesc;
2411         pd = md->params;
2412         td = md->paramtypes;
2413
2414         /* allocate argument array */
2415
2416         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2417
2418         /* if method is non-static fill first block and skip `this' pointer */
2419
2420         i = 0;
2421
2422         if (o != NULL) {
2423                 /* the `this' pointer */
2424                 vm_array_store_adr(array, pd, o);
2425
2426                 pd++;
2427                 td++;
2428                 i++;
2429         } 
2430
2431         for (; i < md->paramcount; i++, pd++, td++) {
2432                 switch (td->type) {
2433                 case TYPE_INT:
2434                         value.i = va_arg(ap, int32_t);
2435                         vm_array_store_int(array, pd, value.i);
2436                         break;
2437
2438                 case TYPE_LNG:
2439                         value.l = va_arg(ap, int64_t);
2440                         vm_array_store_lng(array, pd, value.l);
2441                         break;
2442
2443                 case TYPE_FLT:
2444 #if defined(__ALPHA__) || defined(__POWERPC__) || defined(__POWERPC64__)
2445                         /* This is required to load the correct float value in
2446                            assembler code. */
2447
2448                         value.d = (double) va_arg(ap, double);
2449 #else
2450                         value.f = (float) va_arg(ap, double);
2451 #endif
2452                         vm_array_store_flt(array, pd, value.l);
2453                         break;
2454
2455                 case TYPE_DBL:
2456                         value.d = va_arg(ap, double);
2457                         vm_array_store_dbl(array, pd, value.l);
2458                         break;
2459
2460                 case TYPE_ADR: 
2461                         value.a = va_arg(ap, void*);
2462                         vm_array_store_adr(array, pd, value.a);
2463                         break;
2464                 }
2465         }
2466
2467         return array;
2468 }
2469
2470
2471 /* vm_array_from_jvalue ********************************************************
2472
2473    XXX
2474
2475 *******************************************************************************/
2476
2477 static uint64_t *vm_array_from_jvalue(methodinfo *m, java_object_t *o,
2478                                                                           const jvalue *args)
2479 {
2480         methoddesc *md;
2481         paramdesc  *pd;
2482         typedesc   *td;
2483         uint64_t   *array;
2484         int32_t     i;
2485         int32_t     j;
2486
2487         /* get the descriptors */
2488
2489         md = m->parseddesc;
2490         pd = md->params;
2491         td = md->paramtypes;
2492
2493         /* allocate argument array */
2494
2495 #if defined(HAS_ADDRESS_REGISTER_FILE)
2496         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + ADR_ARG_CNT + md->memuse);
2497 #else
2498         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2499 #endif
2500
2501         /* if method is non-static fill first block and skip `this' pointer */
2502
2503         i = 0;
2504
2505         if (o != NULL) {
2506                 /* the `this' pointer */
2507                 vm_array_store_adr(array, pd, o);
2508
2509                 pd++;
2510                 td++;
2511                 i++;
2512         } 
2513
2514         for (j = 0; i < md->paramcount; i++, j++, pd++, td++) {
2515                 switch (td->decltype) {
2516                 case TYPE_INT:
2517                         vm_array_store_int(array, pd, args[j].i);
2518                         break;
2519
2520                 case TYPE_LNG:
2521                         vm_array_store_lng(array, pd, args[j].j);
2522                         break;
2523
2524                 case TYPE_FLT:
2525                         vm_array_store_flt(array, pd, args[j].j);
2526                         break;
2527
2528                 case TYPE_DBL:
2529                         vm_array_store_dbl(array, pd, args[j].j);
2530                         break;
2531
2532                 case TYPE_ADR: 
2533                         vm_array_store_adr(array, pd, args[j].l);
2534                         break;
2535                 }
2536         }
2537
2538         return array;
2539 }
2540
2541
2542 /* vm_array_from_objectarray ***************************************************
2543
2544    XXX
2545
2546 *******************************************************************************/
2547
2548 uint64_t *vm_array_from_objectarray(methodinfo *m, java_object_t *o,
2549                                                                         java_handle_objectarray_t *params)
2550 {
2551         methoddesc    *md;
2552         paramdesc     *pd;
2553         typedesc      *td;
2554         uint64_t      *array;
2555         java_handle_t *param;
2556         classinfo     *c;
2557         int            type;
2558         int32_t        i;
2559         int32_t        j;
2560         imm_union      value;
2561
2562         /* get the descriptors */
2563
2564         md = m->parseddesc;
2565         pd = md->params;
2566         td = md->paramtypes;
2567
2568         /* allocate argument array */
2569
2570         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2571
2572         /* if method is non-static fill first block and skip `this' pointer */
2573
2574         i = 0;
2575
2576         if (o != NULL) {
2577                 /* this pointer */
2578                 vm_array_store_adr(array, pd, o);
2579
2580                 pd++;
2581                 td++;
2582                 i++;
2583         }
2584
2585         for (j = 0; i < md->paramcount; i++, j++, pd++, td++) {
2586                 LLNI_objectarray_element_get(params, j, param);
2587
2588                 switch (td->type) {
2589                 case TYPE_INT:
2590                         if (param == NULL)
2591                                 goto illegal_arg;
2592
2593                         /* convert the value according to its declared type */
2594
2595                         c    = param->vftbl->class;
2596                         type = primitive_type_get_by_wrapperclass(c);
2597
2598                         switch (td->decltype) {
2599                         case PRIMITIVETYPE_BOOLEAN:
2600                                 switch (type) {
2601                                 case PRIMITIVETYPE_BOOLEAN:
2602                                         /* This type is OK. */
2603                                         break;
2604                                 default:
2605                                         goto illegal_arg;
2606                                 }
2607                                 break;
2608
2609                         case PRIMITIVETYPE_BYTE:
2610                                 switch (type) {
2611                                 case PRIMITIVETYPE_BYTE:
2612                                         /* This type is OK. */
2613                                         break;
2614                                 default:
2615                                         goto illegal_arg;
2616                                 }
2617                                 break;
2618
2619                         case PRIMITIVETYPE_CHAR:
2620                                 switch (type) {
2621                                 case PRIMITIVETYPE_CHAR:
2622                                         /* This type is OK. */
2623                                         break;
2624                                 default:
2625                                         goto illegal_arg;
2626                                 }
2627                                 break;
2628
2629                         case PRIMITIVETYPE_SHORT:
2630                                 switch (type) {
2631                                 case PRIMITIVETYPE_BYTE:
2632                                 case PRIMITIVETYPE_SHORT:
2633                                         /* These types are OK. */
2634                                         break;
2635                                 default:
2636                                         goto illegal_arg;
2637                                 }
2638                                 break;
2639
2640                         case PRIMITIVETYPE_INT:
2641                                 switch (type) {
2642                                 case PRIMITIVETYPE_BYTE:
2643                                 case PRIMITIVETYPE_SHORT:
2644                                 case PRIMITIVETYPE_INT:
2645                                         /* These types are OK. */
2646                                         break;
2647                                 default:
2648                                         goto illegal_arg;
2649                                 }
2650                                 break;
2651
2652                         default:
2653                                 vm_abort("vm_array_from_objectarray: invalid type %d",
2654                                                  td->decltype);
2655                         }
2656
2657                         value = primitive_unbox(param);
2658                         vm_array_store_int(array, pd, value.i);
2659                         break;
2660
2661                 case TYPE_LNG:
2662                         if (param == NULL)
2663                                 goto illegal_arg;
2664
2665                         c    = param->vftbl->class;
2666                         type = primitive_type_get_by_wrapperclass(c);
2667
2668                         assert(td->decltype == PRIMITIVETYPE_LONG);
2669
2670                         switch (type) {
2671                         case PRIMITIVETYPE_BYTE:
2672                         case PRIMITIVETYPE_SHORT:
2673                         case PRIMITIVETYPE_INT:
2674                         case PRIMITIVETYPE_LONG:
2675                                 /* These types are OK. */
2676                                 break;
2677                         default:
2678                                 goto illegal_arg;
2679                         }
2680
2681                         value = primitive_unbox(param);
2682                         vm_array_store_lng(array, pd, value.l);
2683                         break;
2684
2685                 case TYPE_FLT:
2686                         if (param == NULL)
2687                                 goto illegal_arg;
2688
2689                         c    = param->vftbl->class;
2690                         type = primitive_type_get_by_wrapperclass(c);
2691
2692                         assert(td->decltype == PRIMITIVETYPE_FLOAT);
2693
2694                         switch (type) {
2695                         case PRIMITIVETYPE_FLOAT:
2696                                 /* This type is OK. */
2697                                 break;
2698                         default:
2699                                 goto illegal_arg;
2700                         }
2701
2702                         value = primitive_unbox(param);
2703                         vm_array_store_flt(array, pd, value.l);
2704                         break;
2705
2706                 case TYPE_DBL:
2707                         if (param == NULL)
2708                                 goto illegal_arg;
2709
2710                         c    = param->vftbl->class;
2711                         type = primitive_type_get_by_wrapperclass(c);
2712
2713                         assert(td->decltype == PRIMITIVETYPE_DOUBLE);
2714
2715                         switch (type) {
2716                         case PRIMITIVETYPE_FLOAT:
2717                         case PRIMITIVETYPE_DOUBLE:
2718                                 /* These types are OK. */
2719                                 break;
2720                         default:
2721                                 goto illegal_arg;
2722                         }
2723
2724                         value = primitive_unbox(param);
2725                         vm_array_store_dbl(array, pd, value.l);
2726                         break;
2727                 
2728                 case TYPE_ADR:
2729                         if (!resolve_class_from_typedesc(td, true, true, &c))
2730                                 return false;
2731
2732                         if (param != NULL) {
2733                                 if (td->arraydim > 0) {
2734                                         if (!builtin_arrayinstanceof(param, c))
2735                                                 goto illegal_arg;
2736                                 }
2737                                 else {
2738                                         if (!builtin_instanceof(param, c))
2739                                                 goto illegal_arg;
2740                                 }
2741                         }
2742
2743                         vm_array_store_adr(array, pd, param);
2744                         break;
2745
2746                 default:
2747                         vm_abort("vm_array_from_objectarray: invalid type %d", td->type);
2748                 }
2749         }
2750
2751         return array;
2752
2753 illegal_arg:
2754         exceptions_throw_illegalargumentexception();
2755         return NULL;
2756 }
2757
2758
2759 /* vm_call_method **************************************************************
2760
2761    Calls a Java method with a variable number of arguments.
2762
2763 *******************************************************************************/
2764
2765 #define VM_CALL_METHOD(name, type)                                  \
2766 type vm_call_method##name(methodinfo *m, java_handle_t *o, ...)     \
2767 {                                                                   \
2768         va_list ap;                                                     \
2769         type    value;                                                  \
2770                                                                     \
2771         va_start(ap, o);                                                \
2772         value = vm_call_method##name##_valist(m, o, ap);                \
2773         va_end(ap);                                                     \
2774                                                                     \
2775         return value;                                                   \
2776 }
2777
2778 VM_CALL_METHOD(,        java_handle_t *)
2779 VM_CALL_METHOD(_int,    int32_t)
2780 VM_CALL_METHOD(_long,   int64_t)
2781 VM_CALL_METHOD(_float,  float)
2782 VM_CALL_METHOD(_double, double)
2783
2784
2785 /* vm_call_method_valist *******************************************************
2786
2787    Calls a Java method with a variable number of arguments, passed via
2788    a va_list.
2789
2790 *******************************************************************************/
2791
2792 #define VM_CALL_METHOD_VALIST(name, type)                               \
2793 type vm_call_method##name##_valist(methodinfo *m, java_handle_t *o,     \
2794                                                                    va_list ap)                          \
2795 {                                                                       \
2796         int32_t   dumpsize;                                                 \
2797         uint64_t *array;                                                    \
2798         type      value;                                                    \
2799                                                                         \
2800         dumpsize = dump_size();                                             \
2801         array = vm_array_from_valist(m, o, ap);                             \
2802         value = vm_call##name##_array(m, array);                            \
2803         dump_release(dumpsize);                                             \
2804                                                                         \
2805         return value;                                                       \
2806 }
2807
2808 VM_CALL_METHOD_VALIST(,        java_handle_t *)
2809 VM_CALL_METHOD_VALIST(_int,    int32_t)
2810 VM_CALL_METHOD_VALIST(_long,   int64_t)
2811 VM_CALL_METHOD_VALIST(_float,  float)
2812 VM_CALL_METHOD_VALIST(_double, double)
2813
2814
2815 /* vm_call_method_jvalue *******************************************************
2816
2817    Calls a Java method with a variable number of arguments, passed via
2818    a jvalue array.
2819
2820 *******************************************************************************/
2821
2822 #define VM_CALL_METHOD_JVALUE(name, type)                               \
2823 type vm_call_method##name##_jvalue(methodinfo *m, java_handle_t *o,     \
2824                                                            const jvalue *args)                  \
2825 {                                                                       \
2826         int32_t   dumpsize;                                                 \
2827         uint64_t *array;                                                    \
2828         type      value;                                                    \
2829                                                                         \
2830         dumpsize = dump_size();                                             \
2831         array = vm_array_from_jvalue(m, o, args);                           \
2832         value = vm_call##name##_array(m, array);                            \
2833         dump_release(dumpsize);                                             \
2834                                                                         \
2835         return value;                                                       \
2836 }
2837
2838 VM_CALL_METHOD_JVALUE(,        java_handle_t *)
2839 VM_CALL_METHOD_JVALUE(_int,    int32_t)
2840 VM_CALL_METHOD_JVALUE(_long,   int64_t)
2841 VM_CALL_METHOD_JVALUE(_float,  float)
2842 VM_CALL_METHOD_JVALUE(_double, double)
2843
2844
2845 /* vm_call_array ***************************************************************
2846
2847    Calls a Java method with a variable number of arguments, passed via
2848    an argument array.
2849
2850 *******************************************************************************/
2851
2852 #define VM_CALL_ARRAY(name, type)                            \
2853 type vm_call##name##_array(methodinfo *m, uint64_t *array)   \
2854 {                                                            \
2855         methoddesc *md;                                          \
2856         void       *pv;                                          \
2857         type        value;                                       \
2858                                                              \
2859         md = m->parseddesc;                                      \
2860                                                              \
2861         if (m->code == NULL)                                     \
2862                 if (!jit_compile(m))                                 \
2863                         return 0;                                        \
2864                                                              \
2865     pv = m->code->entrypoint;                                \
2866                                                              \
2867         STATISTICS(count_calls_native_to_java++);                \
2868                                                              \
2869         value = asm_vm_call_method##name(pv, array, md->memuse); \
2870                                                              \
2871         return value;                                            \
2872 }
2873
2874 VM_CALL_ARRAY(,        java_handle_t *)
2875 VM_CALL_ARRAY(_int,    int32_t)
2876 VM_CALL_ARRAY(_long,   int64_t)
2877 VM_CALL_ARRAY(_float,  float)
2878 VM_CALL_ARRAY(_double, double)
2879
2880
2881 /*
2882  * These are local overrides for various environment variables in Emacs.
2883  * Please do not remove this and leave it at the end of the file, where
2884  * Emacs will automagically detect them.
2885  * ---------------------------------------------------------------------
2886  * Local variables:
2887  * mode: c
2888  * indent-tabs-mode: t
2889  * c-basic-offset: 4
2890  * tab-width: 4
2891  * End:
2892  */