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