* Merged with f9adc5b4d7f0.
[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_CLASSPATH_SUN)
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/mutex.h"
63 #include "threads/threadlist.h"
64 #include "threads/thread.h"
65
66 #include "toolbox/logging.h"
67
68 #include "vm/array.h"
69
70 #if defined(ENABLE_ASSERTION)
71 #include "vm/assertion.h"
72 #endif
73
74 #include "vm/builtin.h"
75 #include "vm/exceptions.h"
76 #include "vm/finalizer.h"
77 #include "vm/global.h"
78 #include "vm/initialize.h"
79 #include "vm/package.h"
80 #include "vm/primitive.h"
81 #include "vm/properties.h"
82 #include "vm/signallocal.h"
83 #include "vm/stringlocal.h"
84 #include "vm/vm.h"
85
86 #include "vm/jit/argument.h"
87 #include "vm/jit/asmpart.h"
88 #include "vm/jit/code.h"
89
90 #if defined(ENABLE_DISASSEMBLER)
91 # include "vm/jit/disass.h"
92 #endif
93
94 #include "vm/jit/jit.h"
95 #include "vm/jit/methodtree.h"
96
97 #if defined(ENABLE_PROFILING)
98 # include "vm/jit/optimizing/profile.h"
99 #endif
100
101 #include "vm/jit/optimizing/recompile.h"
102
103 #if defined(ENABLE_PYTHON)
104 # include "vm/jit/python.h"
105 #endif
106
107 #include "vmcore/classcache.h"
108 #include "vmcore/options.h"
109 #include "vmcore/statistics.h"
110 #include "vmcore/suck.h"
111 #include "vmcore/system.h"
112
113 #if defined(ENABLE_JVMTI)
114 # include "native/jvmti/cacaodbg.h"
115 #endif
116
117 #if defined(ENABLE_VMLOG)
118 #include <vmlog_cacao.h>
119 #endif
120
121
122 /* Invocation API variables ***************************************************/
123
124 _Jv_JavaVM *_Jv_jvm;                    /* denotes a Java VM                  */
125 _Jv_JNIEnv *_Jv_env;                    /* pointer to native method interface */
126
127
128 /* global variables ***********************************************************/
129
130 s4 vms = 0;                             /* number of VMs created              */
131
132 bool vm_initializing = false;
133 bool vm_created      = false;
134 bool vm_exiting      = false;
135
136 char      *mainstring = NULL;
137 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(WITH_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_CLASSPATH_GNU)
641         puts("  gnu.classpath.boot.library.path: "CLASSPATH_LIBDIR);
642         puts("  java.boot.class.path           : "CACAO_VM_ZIP":"CLASSPATH_CLASSES"");
643 # elif defined(WITH_CLASSPATH_SUN)
644         puts("  sun.boot.library.path          : "CLASSPATH_LIBDIR);
645         puts("  java.boot.class.path           : "CLASSPATH_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_CLASSPATH_GNU)
657         printf("  gnu.classpath.boot.library.path: %s\n", properties_get("gnu.classpath.boot.library.path"));
658 #elif defined(WITH_CLASSPATH_SUN)
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(void);
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         /* get the main class *****************************************************/
1365
1366         if (opt_index < vm_args->nOptions) {
1367                 mainstring = vm_args->options[opt_index++].optionString;
1368
1369                 /* Put the jar file into the classpath (if any). */
1370
1371                 if (opt_jar == true) {
1372                         /* free old classpath */
1373
1374 /*                      MFREE(_Jv_classpath, char, strlen(_Jv_classpath)); */
1375
1376                         /* put jarfile into classpath */
1377
1378                         p = MNEW(char, strlen(mainstring) + strlen("0"));
1379
1380                         strcpy(p, mainstring);
1381
1382 #if defined(ENABLE_JAVASE)
1383                         properties_add("java.class.path", p);
1384 #endif
1385                 }
1386                 else {
1387                         /* replace .'s with /'s in classname */
1388
1389                         for (i = strlen(mainstring) - 1; i >= 0; i--)
1390                                 if (mainstring[i] == '.')
1391                                         mainstring[i] = '/';
1392                 }
1393         }
1394
1395 #if defined(ENABLE_JVMTI)
1396         if (jvmti) {
1397                 jvmti_set_phase(JVMTI_PHASE_ONLOAD);
1398                 jvmti_agentload(agentarg, agentbypath, &handle, &libname);
1399
1400                 if (jdwp)
1401                         MFREE(agentarg, char, strlen(agentarg));
1402
1403                 jvmti_set_phase(JVMTI_PHASE_PRIMORDIAL);
1404         }
1405 #endif
1406
1407         /* initialize this JVM ****************************************************/
1408
1409         vm_initializing = true;
1410
1411         /* initialize the garbage collector */
1412
1413         gc_init(opt_heapmaxsize, opt_heapstartsize);
1414
1415 #if defined(ENABLE_THREADS)
1416         /* BEFORE: threads_preinit */
1417
1418         threadlist_init();
1419
1420         /* AFTER: gc_init (directly after, as this initializes the
1421            stopworldlock lock */
1422
1423         threads_preinit();
1424         lock_init();
1425         critical_init();
1426 #endif
1427
1428         /* install architecture dependent signal handlers */
1429
1430         if (!signal_init())
1431                 vm_abort("vm_create: signal_init failed");
1432
1433 #if defined(ENABLE_INTRP)
1434         /* Allocate main thread stack on the Java heap. */
1435
1436         if (opt_intrp) {
1437                 intrp_main_stack = GCMNEW(u1, opt_stacksize);
1438                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1439         }
1440 #endif
1441
1442         /* AFTER: threads_preinit */
1443
1444         if (!string_init())
1445                 vm_abort("vm_create: string_init failed");
1446
1447         /* AFTER: threads_preinit */
1448
1449         utf8_init();
1450
1451         /* AFTER: thread_preinit */
1452
1453         if (!suck_init())
1454                 vm_abort("vm_create: suck_init failed");
1455
1456         suck_add_from_property("java.endorsed.dirs");
1457
1458         /* Now we have all options handled and we can print the version
1459            information.
1460
1461            AFTER: suck_add_from_property("java.endorsed.dirs"); */
1462
1463         if (opt_version)
1464                 version(opt_exit);
1465
1466         /* AFTER: utf8_init */
1467
1468         boot_class_path = properties_get("sun.boot.class.path");
1469         suck_add(boot_class_path);
1470
1471         /* initialize the classcache hashtable stuff: lock, hashtable
1472            (must be done _after_ threads_preinit) */
1473
1474         if (!classcache_init())
1475                 vm_abort("vm_create: classcache_init failed");
1476
1477         /* Initialize the code memory management. */
1478         /* AFTER: threads_preinit */
1479
1480         codememory_init();
1481
1482         /* initialize the finalizer stuff (must be done _after_
1483            threads_preinit) */
1484
1485         if (!finalizer_init())
1486                 vm_abort("vm_create: finalizer_init failed");
1487
1488         /* Initialize the JIT compiler. */
1489
1490         jit_init();
1491         code_init();
1492         methodtree_init();
1493
1494 #if defined(ENABLE_PYTHON)
1495         pythonpass_init();
1496 #endif
1497
1498         /* BEFORE: loader_preinit */
1499
1500         package_init();
1501
1502         /* AFTER: utf8_init, classcache_init */
1503
1504         loader_preinit();
1505         linker_preinit();
1506
1507         /* AFTER: loader_preinit, linker_preinit */
1508
1509         primitive_init();
1510
1511         loader_init();
1512         linker_init();
1513
1514         /* AFTER: loader_init, linker_init */
1515
1516         primitive_postinit();
1517         method_init();
1518
1519         exceptions_init();
1520
1521         if (!builtin_init())
1522                 vm_abort("vm_create: builtin_init failed");
1523
1524         /* Initialize the native subsystem. */
1525         /* BEFORE: threads_init */
1526
1527         if (!native_init())
1528                 vm_abort("vm_create: native_init failed");
1529
1530         /* Register the native methods implemented in the VM. */
1531         /* BEFORE: threads_init */
1532
1533         nativevm_preinit();
1534
1535 #if defined(ENABLE_JNI)
1536         /* Initialize the JNI subsystem (must be done _before_
1537            threads_init, as threads_init can call JNI methods
1538            (e.g. NewGlobalRef). */
1539
1540         if (!jni_init())
1541                 vm_abort("vm_create: jni_init failed");
1542 #endif
1543
1544 #if defined(ENABLE_JNI) || defined(ENABLE_HANDLES)
1545         /* Initialize the local reference table for the main thread. */
1546         /* BEFORE: threads_init */
1547
1548         if (!localref_table_init())
1549                 vm_abort("vm_create: localref_table_init failed");
1550 #endif
1551
1552         /* Iinitialize some important system classes. */
1553         /* BEFORE: threads_init */
1554
1555         initialize_init();
1556
1557 #if defined(ENABLE_THREADS)
1558         threads_init();
1559 #endif
1560
1561         /* Initialize the native VM subsystem. */
1562         /* AFTER: threads_init (at least for SUN's classes) */
1563
1564         nativevm_init();
1565
1566 #if defined(ENABLE_PROFILING)
1567         /* initialize profiling */
1568
1569         if (!profile_init())
1570                 vm_abort("vm_create: profile_init failed");
1571 #endif
1572
1573 #if defined(ENABLE_THREADS)
1574         /* initialize recompilation */
1575
1576         if (!recompile_init())
1577                 vm_abort("vm_create: recompile_init failed");
1578
1579         /* start the signal handler thread */
1580
1581 #if defined(__LINUX__)
1582         /* XXX Remove for exact-GC. */
1583         if (threads_pthreads_implementation_nptl)
1584 #endif
1585                 if (!signal_start_thread())
1586                         vm_abort("vm_create: signal_start_thread failed");
1587
1588         /* finally, start the finalizer thread */
1589
1590         if (!finalizer_start_thread())
1591                 vm_abort("vm_create: finalizer_start_thread failed");
1592
1593 # if !defined(NDEBUG)
1594         /* start the memory profiling thread */
1595
1596         if (opt_ProfileMemoryUsage || opt_ProfileGCMemoryUsage)
1597                 if (!memory_start_thread())
1598                         vm_abort("vm_create: memory_start_thread failed");
1599 # endif
1600
1601         /* start the recompilation thread (must be done before the
1602            profiling thread) */
1603
1604         if (!recompile_start_thread())
1605                 vm_abort("vm_create: recompile_start_thread failed");
1606
1607 # if defined(ENABLE_PROFILING)
1608         /* start the profile sampling thread */
1609
1610 /*      if (opt_prof) */
1611 /*              if (!profile_start_thread()) */
1612 /*                      vm_abort("vm_create: profile_start_thread failed"); */
1613 # endif
1614 #endif
1615
1616 #if defined(ENABLE_JVMTI)
1617 # if defined(ENABLE_GC_CACAO)
1618         /* XXX this will not work with the new indirection cells for classloaders!!! */
1619         assert(0);
1620 # endif
1621         if (jvmti) {
1622                 /* add agent library to native library hashtable */
1623                 native_hashtable_library_add(utf_new_char(libname), class_java_lang_Object->classloader, handle);
1624         }
1625 #endif
1626
1627         /* Increment the number of VMs. */
1628
1629         vms++;
1630
1631         /* Initialization is done, VM is created.. */
1632
1633         vm_created      = true;
1634         vm_initializing = false;
1635
1636         /* Print the VM configuration after all stuff is set and the VM is
1637            initialized. */
1638
1639         if (opt_PrintConfig)
1640                 vm_printconfig();
1641
1642         /* everything's ok */
1643
1644         return true;
1645 }
1646
1647
1648 /* vm_run **********************************************************************
1649
1650    Runs the main-method of the passed class.
1651
1652 *******************************************************************************/
1653
1654 void vm_run(JavaVM *vm, JavaVMInitArgs *vm_args)
1655 {
1656         utf                       *mainutf;
1657         classinfo                 *mainclass;
1658         java_handle_t             *e;
1659         methodinfo                *m;
1660         java_handle_objectarray_t *oa; 
1661         s4                         oalength;
1662         utf                       *u;
1663         java_handle_t             *s;
1664         int                        status;
1665         int                        i;
1666
1667 #if defined(ENABLE_THREADS)
1668         threadobject              *t;
1669 #endif
1670
1671 #if !defined(NDEBUG)
1672         if (compileall) {
1673                 vm_compile_all();
1674                 return;
1675         }
1676
1677         if (opt_method != NULL) {
1678                 vm_compile_method();
1679                 return;
1680         }
1681 #endif /* !defined(NDEBUG) */
1682
1683         /* should we run the main-method? */
1684
1685         if (mainstring == NULL)
1686                 usage();
1687
1688         /* set return value to OK */
1689
1690         status = 0;
1691
1692         if (opt_jar == true) {
1693                 /* open jar file with java.util.jar.JarFile */
1694
1695                 mainstring = vm_get_mainclass_from_jar(mainstring);
1696
1697                 if (mainstring == NULL)
1698                         vm_exit(1);
1699         }
1700
1701         /* load the main class */
1702
1703         mainutf = utf_new_char(mainstring);
1704
1705 #if defined(ENABLE_JAVAME_CLDC1_1)
1706         mainclass = load_class_bootstrap(mainutf);
1707 #else
1708         mainclass = load_class_from_sysloader(mainutf);
1709 #endif
1710
1711         /* error loading class */
1712
1713         e = exceptions_get_and_clear_exception();
1714
1715         if ((e != NULL) || (mainclass == NULL)) {
1716                 exceptions_throw_noclassdeffounderror_cause(e);
1717                 exceptions_print_stacktrace(); 
1718                 vm_exit(1);
1719         }
1720
1721         if (!link_class(mainclass)) {
1722                 exceptions_print_stacktrace();
1723                 vm_exit(1);
1724         }
1725                         
1726         /* find the `main' method of the main class */
1727
1728         m = class_resolveclassmethod(mainclass,
1729                                                                  utf_new_char("main"), 
1730                                                                  utf_new_char("([Ljava/lang/String;)V"),
1731                                                                  class_java_lang_Object,
1732                                                                  false);
1733
1734         if (exceptions_get_exception()) {
1735                 exceptions_print_stacktrace();
1736                 vm_exit(1);
1737         }
1738
1739         /* there is no main method or it isn't static */
1740
1741         if ((m == NULL) || !(m->flags & ACC_STATIC)) {
1742                 exceptions_clear_exception();
1743                 exceptions_throw_nosuchmethoderror(mainclass,
1744                                                                                    utf_new_char("main"), 
1745                                                                                    utf_new_char("([Ljava/lang/String;)V"));
1746
1747                 exceptions_print_stacktrace();
1748                 vm_exit(1);
1749         }
1750
1751         /* build argument array */
1752
1753         oalength = vm_args->nOptions - opt_index;
1754
1755         oa = builtin_anewarray(oalength, class_java_lang_String);
1756
1757         for (i = 0; i < oalength; i++) {
1758                 u = utf_new_char(vm_args->options[opt_index + i].optionString);
1759                 s = javastring_new(u);
1760
1761                 array_objectarray_element_set(oa, i, s);
1762         }
1763
1764 #ifdef TYPEINFO_DEBUG_TEST
1765         /* test the typeinfo system */
1766         typeinfo_test();
1767 #endif
1768         /*class_showmethods(currentThread->group->header.vftbl->class); */
1769
1770 #if defined(ENABLE_JVMTI)
1771         jvmti_set_phase(JVMTI_PHASE_LIVE);
1772 #endif
1773
1774         /* set ThreadMXBean variables */
1775
1776         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1777         _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1778
1779         if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1780                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1781                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1782                         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1783
1784         /* start the main thread */
1785
1786         (void) vm_call_method(m, NULL, oa);
1787
1788         /* exception occurred? */
1789
1790         if (exceptions_get_exception()) {
1791                 exceptions_print_stacktrace();
1792                 status = 1;
1793         }
1794
1795 #if defined(ENABLE_THREADS)
1796     /* Detach the main thread so that it appears to have ended when
1797            the application's main method exits. */
1798
1799         t = thread_get_current();
1800
1801         if (!threads_detach_thread(t))
1802                 vm_abort("vm_run: Could not detach main thread.");
1803 #endif
1804
1805         /* Destroy the JavaVM. */
1806
1807         (void) vm_destroy(vm);
1808
1809         /* And exit. */
1810
1811         vm_exit(status);
1812 }
1813
1814
1815 /* vm_destroy ******************************************************************
1816
1817    Unloads a Java VM and reclaims its resources.
1818
1819 *******************************************************************************/
1820
1821 int vm_destroy(JavaVM *vm)
1822 {
1823 #if defined(ENABLE_THREADS)
1824         /* Create a a trivial new Java waiter thread called
1825            "DestroyJavaVM". */
1826
1827         JavaVMAttachArgs args;
1828
1829         args.name  = "DestroyJavaVM";
1830         args.group = NULL;
1831
1832         if (!threads_attach_current_thread(&args, false))
1833                 return 1;
1834
1835         /* Wait until we are the last non-daemon thread. */
1836
1837         threads_join_all_threads();
1838 #endif
1839
1840         /* VM is gone. */
1841
1842         vm_created = false;
1843
1844         /* Everything is ok. */
1845
1846         return 0;
1847 }
1848
1849
1850 /* vm_exit *********************************************************************
1851
1852    Calls java.lang.System.exit(I)V to exit the JavaVM correctly.
1853
1854 *******************************************************************************/
1855
1856 void vm_exit(s4 status)
1857 {
1858         methodinfo *m;
1859
1860         /* signal that we are exiting */
1861
1862         vm_exiting = true;
1863
1864         assert(class_java_lang_System);
1865         assert(class_java_lang_System->state & CLASS_LOADED);
1866
1867 #if defined(ENABLE_JVMTI)
1868         if (jvmti || (dbgcom!=NULL)) {
1869                 jvmti_set_phase(JVMTI_PHASE_DEAD);
1870                 if (jvmti) jvmti_agentunload();
1871         }
1872 #endif
1873
1874         if (!link_class(class_java_lang_System)) {
1875                 exceptions_print_stacktrace();
1876                 exit(1);
1877         }
1878
1879         /* call java.lang.System.exit(I)V */
1880
1881         m = class_resolveclassmethod(class_java_lang_System,
1882                                                                  utf_new_char("exit"),
1883                                                                  utf_int__void,
1884                                                                  class_java_lang_Object,
1885                                                                  true);
1886         
1887         if (m == NULL) {
1888                 exceptions_print_stacktrace();
1889                 exit(1);
1890         }
1891
1892         /* call the exit function with passed exit status */
1893
1894         (void) vm_call_method(m, NULL, status);
1895
1896         /* If we had an exception, just ignore the exception and exit with
1897            the proper code. */
1898
1899         vm_shutdown(status);
1900 }
1901
1902
1903 /* vm_shutdown *****************************************************************
1904
1905    Terminates the system immediately without freeing memory explicitly
1906    (to be used only for abnormal termination).
1907         
1908 *******************************************************************************/
1909
1910 void vm_shutdown(s4 status)
1911 {
1912         if (opt_verbose 
1913 #if defined(ENABLE_STATISTICS)
1914                 || opt_getcompilingtime || opt_stat
1915 #endif
1916            ) 
1917         {
1918                 log_text("CACAO terminated by shutdown");
1919                 dolog("Exit status: %d\n", (s4) status);
1920
1921         }
1922
1923 #if defined(ENABLE_JVMTI)
1924         /* terminate cacaodbgserver */
1925         if (dbgcom!=NULL) {
1926                 mutex_lock(&dbgcomlock);
1927                 dbgcom->running=1;
1928                 mutex_unlock(&dbgcomlock);
1929                 jvmti_cacaodbgserver_quit();
1930         }       
1931 #endif
1932
1933         exit(status);
1934 }
1935
1936
1937 /* vm_exit_handler *************************************************************
1938
1939    The exit_handler function is called upon program termination.
1940
1941    ATTENTION: Don't free system resources here! Some threads may still
1942    be running as this is called from VMRuntime.exit(). The OS does the
1943    cleanup for us.
1944
1945 *******************************************************************************/
1946
1947 void vm_exit_handler(void)
1948 {
1949 #if !defined(NDEBUG)
1950         if (showmethods)
1951                 class_showmethods(mainclass);
1952
1953         if (showconstantpool)
1954                 class_showconstantpool(mainclass);
1955
1956         if (showutf)
1957                 utf_show();
1958
1959 # if defined(ENABLE_PROFILING)
1960         if (opt_prof)
1961                 profile_printstats();
1962 # endif
1963 #endif /* !defined(NDEBUG) */
1964
1965 #if defined(ENABLE_RT_TIMING)
1966         rt_timing_print_time_stats(stderr);
1967 #endif
1968
1969 #if defined(ENABLE_CYCLES_STATS)
1970         builtin_print_cycles_stats(stderr);
1971         stacktrace_print_cycles_stats(stderr);
1972 #endif
1973
1974         if (opt_verbose 
1975 #if defined(ENABLE_STATISTICS)
1976                 || opt_getcompilingtime || opt_stat
1977 #endif
1978            ) 
1979         {
1980                 log_text("CACAO terminated");
1981
1982 #if defined(ENABLE_STATISTICS)
1983                 if (opt_stat) {
1984                         print_stats();
1985 #ifdef TYPECHECK_STATISTICS
1986                         typecheck_print_statistics(get_logfile());
1987 #endif
1988                 }
1989
1990                 if (opt_getcompilingtime)
1991                         print_times();
1992 #endif /* defined(ENABLE_STATISTICS) */
1993         }
1994         /* vm_print_profile(stderr);*/
1995 }
1996
1997
1998 /* vm_abort ********************************************************************
1999
2000    Prints an error message and aborts the VM.
2001
2002    IN:
2003        text ... error message to print
2004
2005 *******************************************************************************/
2006
2007 void vm_abort(const char *text, ...)
2008 {
2009         va_list ap;
2010
2011         /* Print the log message. */
2012
2013         log_start();
2014
2015         va_start(ap, text);
2016         log_vprint(text, ap);
2017         va_end(ap);
2018
2019         log_finish();
2020
2021         /* Now abort the VM. */
2022
2023         system_abort();
2024 }
2025
2026
2027 /* vm_abort_errnum *************************************************************
2028
2029    Prints an error message, appends ":" plus the strerror-message of
2030    errnum and aborts the VM.
2031
2032    IN:
2033        errnum ... error number
2034        text ..... error message to print
2035
2036 *******************************************************************************/
2037
2038 void vm_abort_errnum(int errnum, const char *text, ...)
2039 {
2040         va_list ap;
2041
2042         /* Print the log message. */
2043
2044         log_start();
2045
2046         va_start(ap, text);
2047         log_vprint(text, ap);
2048         va_end(ap);
2049
2050         /* Print the strerror-message of errnum. */
2051
2052         log_print(": %s", system_strerror(errnum));
2053
2054         log_finish();
2055
2056         /* Now abort the VM. */
2057
2058         system_abort();
2059 }
2060
2061
2062 /* vm_abort_errno **************************************************************
2063
2064    Equal to vm_abort_errnum, but uses errno to get the error number.
2065
2066    IN:
2067        text ... error message to print
2068
2069 *******************************************************************************/
2070
2071 void vm_abort_errno(const char *text, ...)
2072 {
2073         va_list ap;
2074
2075         va_start(ap, text);
2076         vm_abort_errnum(errno, text, ap);
2077         va_end(ap);
2078 }
2079
2080
2081 /* vm_abort_disassemble ********************************************************
2082
2083    Prints an error message, disassemble the given code range (if
2084    enabled) and aborts the VM.
2085
2086    IN:
2087        pc.......PC to disassemble
2088            count....number of instructions to disassemble
2089
2090 *******************************************************************************/
2091
2092 void vm_abort_disassemble(void *pc, int count, const char *text, ...)
2093 {
2094         va_list ap;
2095 #if defined(ENABLE_DISASSEMBLER)
2096         int     i;
2097 #endif
2098
2099         /* Print debug message. */
2100
2101         log_start();
2102
2103         va_start(ap, text);
2104         log_vprint(text, ap);
2105         va_end(ap);
2106
2107         log_finish();
2108
2109         /* Print the PC. */
2110
2111 #if SIZEOF_VOID_P == 8
2112         log_println("PC=0x%016lx", pc);
2113 #else
2114         log_println("PC=0x%08x", pc);
2115 #endif
2116
2117 #if defined(ENABLE_DISASSEMBLER)
2118         log_println("machine instructions at PC:");
2119
2120         /* Disassemble the given number of instructions. */
2121
2122         for (i = 0; i < count; i++)
2123                 pc = disassinstr(pc);
2124 #endif
2125
2126         vm_abort("Aborting...");
2127 }
2128
2129
2130 /* vm_get_mainclass_from_jar ***************************************************
2131
2132    Gets the name of the main class from a JAR's manifest file.
2133
2134 *******************************************************************************/
2135
2136 static char *vm_get_mainclass_from_jar(char *mainstring)
2137 {
2138         classinfo     *c;
2139         java_handle_t *o;
2140         methodinfo    *m;
2141         java_handle_t *s;
2142
2143         c = load_class_from_sysloader(utf_new_char("java/util/jar/JarFile"));
2144
2145         if (c == NULL) {
2146                 exceptions_print_stacktrace();
2147                 return NULL;
2148         }
2149
2150         /* create JarFile object */
2151
2152         o = builtin_new(c);
2153
2154         if (o == NULL) {
2155                 exceptions_print_stacktrace();
2156                 return NULL;
2157         }
2158
2159         m = class_resolveclassmethod(c,
2160                                                                  utf_init, 
2161                                                                  utf_java_lang_String__void,
2162                                                                  class_java_lang_Object,
2163                                                                  true);
2164
2165         if (m == NULL) {
2166                 exceptions_print_stacktrace();
2167                 return NULL;
2168         }
2169
2170         s = javastring_new_from_ascii(mainstring);
2171
2172         (void) vm_call_method(m, o, s);
2173
2174         if (exceptions_get_exception()) {
2175                 exceptions_print_stacktrace();
2176                 return NULL;
2177         }
2178
2179         /* get manifest object */
2180
2181         m = class_resolveclassmethod(c,
2182                                                                  utf_new_char("getManifest"), 
2183                                                                  utf_new_char("()Ljava/util/jar/Manifest;"),
2184                                                                  class_java_lang_Object,
2185                                                                  true);
2186
2187         if (m == NULL) {
2188                 exceptions_print_stacktrace();
2189                 return NULL;
2190         }
2191
2192         o = vm_call_method(m, o);
2193
2194         if (o == NULL) {
2195                 fprintf(stderr, "Could not get manifest from %s (invalid or corrupt jarfile?)\n", mainstring);
2196                 return NULL;
2197         }
2198
2199
2200         /* get Main Attributes */
2201
2202         LLNI_class_get(o, c);
2203
2204         m = class_resolveclassmethod(c,
2205                                                                  utf_new_char("getMainAttributes"), 
2206                                                                  utf_new_char("()Ljava/util/jar/Attributes;"),
2207                                                                  class_java_lang_Object,
2208                                                                  true);
2209
2210         if (m == NULL) {
2211                 exceptions_print_stacktrace();
2212                 return NULL;
2213         }
2214
2215         o = vm_call_method(m, o);
2216
2217         if (o == NULL) {
2218                 fprintf(stderr, "Could not get main attributes from %s (invalid or corrupt jarfile?)\n", mainstring);
2219                 return NULL;
2220         }
2221
2222
2223         /* get property Main-Class */
2224
2225         LLNI_class_get(o, c);
2226
2227         m = class_resolveclassmethod(c,
2228                                                                  utf_new_char("getValue"), 
2229                                                                  utf_new_char("(Ljava/lang/String;)Ljava/lang/String;"),
2230                                                                  class_java_lang_Object,
2231                                                                  true);
2232
2233         if (m == NULL) {
2234                 exceptions_print_stacktrace();
2235                 return NULL;
2236         }
2237
2238         s = javastring_new_from_ascii("Main-Class");
2239
2240         o = vm_call_method(m, o, s);
2241
2242         if (o == NULL) {
2243                 fprintf(stderr, "Failed to load Main-Class manifest attribute from\n");
2244                 fprintf(stderr, "%s\n", mainstring);
2245                 return NULL;
2246         }
2247
2248         return javastring_tochar(o);
2249 }
2250
2251
2252 /* vm_compile_all **************************************************************
2253
2254    Compile all methods found in the bootclasspath.
2255
2256 *******************************************************************************/
2257
2258 #if !defined(NDEBUG)
2259 static void vm_compile_all(void)
2260 {
2261         classinfo              *c;
2262         methodinfo             *m;
2263         u4                      slot;
2264         classcache_name_entry  *nmen;
2265         classcache_class_entry *clsen;
2266         s4                      i;
2267
2268         /* create all classes found in the bootclasspath */
2269         /* XXX currently only works with zip/jar's */
2270
2271         loader_load_all_classes();
2272
2273         /* link all classes */
2274
2275         for (slot = 0; slot < hashtable_classcache.size; slot++) {
2276                 nmen = (classcache_name_entry *) hashtable_classcache.ptr[slot];
2277
2278                 for (; nmen; nmen = nmen->hashlink) {
2279                         /* iterate over all class entries */
2280
2281                         for (clsen = nmen->classes; clsen; clsen = clsen->next) {
2282                                 c = clsen->classobj;
2283
2284                                 if (c == NULL)
2285                                         continue;
2286
2287                                 if (!(c->state & CLASS_LINKED)) {
2288                                         if (!link_class(c)) {
2289                                                 fprintf(stderr, "Error linking: ");
2290                                                 utf_fprint_printable_ascii_classname(stderr, c->name);
2291                                                 fprintf(stderr, "\n");
2292
2293                                                 /* print out exception and cause */
2294
2295                                                 exceptions_print_current_exception();
2296
2297                                                 /* goto next class */
2298
2299                                                 continue;
2300                                         }
2301                                 }
2302
2303                                 /* compile all class methods */
2304
2305                                 for (i = 0; i < c->methodscount; i++) {
2306                                         m = &(c->methods[i]);
2307
2308                                         if (m->jcode != NULL) {
2309                                                 if (!jit_compile(m)) {
2310                                                         fprintf(stderr, "Error compiling: ");
2311                                                         utf_fprint_printable_ascii_classname(stderr, c->name);
2312                                                         fprintf(stderr, ".");
2313                                                         utf_fprint_printable_ascii(stderr, m->name);
2314                                                         utf_fprint_printable_ascii(stderr, m->descriptor);
2315                                                         fprintf(stderr, "\n");
2316
2317                                                         /* print out exception and cause */
2318
2319                                                         exceptions_print_current_exception();
2320                                                 }
2321                                         }
2322                                 }
2323                         }
2324                 }
2325         }
2326 }
2327 #endif /* !defined(NDEBUG) */
2328
2329
2330 /* vm_compile_method ***********************************************************
2331
2332    Compile a specific method.
2333
2334 *******************************************************************************/
2335
2336 #if !defined(NDEBUG)
2337 static void vm_compile_method(void)
2338 {
2339         methodinfo *m;
2340
2341         /* create, load and link the main class */
2342
2343         mainclass = load_class_bootstrap(utf_new_char(mainstring));
2344
2345         if (mainclass == NULL)
2346                 exceptions_print_stacktrace();
2347
2348         if (!link_class(mainclass))
2349                 exceptions_print_stacktrace();
2350
2351         if (opt_signature != NULL) {
2352                 m = class_resolveclassmethod(mainclass,
2353                                                                          utf_new_char(opt_method),
2354                                                                          utf_new_char(opt_signature),
2355                                                                          mainclass,
2356                                                                          false);
2357         }
2358         else {
2359                 m = class_resolveclassmethod(mainclass,
2360                                                                          utf_new_char(opt_method),
2361                                                                          NULL,
2362                                                                          mainclass,
2363                                                                          false);
2364         }
2365
2366         if (m == NULL)
2367                 vm_abort("vm_compile_method: java.lang.NoSuchMethodException: %s.%s",
2368                                  opt_method, opt_signature ? opt_signature : "");
2369                 
2370         jit_compile(m);
2371 }
2372 #endif /* !defined(NDEBUG) */
2373
2374
2375 /* vm_call_array ***************************************************************
2376
2377    Calls a Java method with a variable number of arguments, passed via
2378    an argument array.
2379
2380    ATTENTION: This function has to be used outside the nativeworld.
2381
2382 *******************************************************************************/
2383
2384 #define VM_CALL_ARRAY(name, type)                                 \
2385 static type vm_call##name##_array(methodinfo *m, uint64_t *array) \
2386 {                                                                 \
2387         methoddesc *md;                                               \
2388         void       *pv;                                               \
2389         type        value;                                            \
2390                                                                   \
2391         assert(m->code != NULL);                                      \
2392                                                                   \
2393         md = m->parseddesc;                                           \
2394         pv = m->code->entrypoint;                                     \
2395                                                                   \
2396         STATISTICS(count_calls_native_to_java++);                     \
2397                                                                   \
2398         value = asm_vm_call_method##name(pv, array, md->memuse);      \
2399                                                                   \
2400         return value;                                                 \
2401 }
2402
2403 static java_handle_t *vm_call_array(methodinfo *m, uint64_t *array)
2404 {
2405         methoddesc    *md;
2406         void          *pv;
2407         java_object_t *o;
2408
2409         assert(m->code != NULL);
2410
2411         md = m->parseddesc;
2412         pv = m->code->entrypoint;
2413
2414         STATISTICS(count_calls_native_to_java++);
2415
2416         o = asm_vm_call_method(pv, array, md->memuse);
2417
2418         if (md->returntype.type == TYPE_VOID)
2419                 o = NULL;
2420
2421         return LLNI_WRAP(o);
2422 }
2423
2424 VM_CALL_ARRAY(_int,    int32_t)
2425 VM_CALL_ARRAY(_long,   int64_t)
2426 VM_CALL_ARRAY(_float,  float)
2427 VM_CALL_ARRAY(_double, double)
2428
2429
2430 /* vm_call_method **************************************************************
2431
2432    Calls a Java method with a variable number of arguments.
2433
2434 *******************************************************************************/
2435
2436 #define VM_CALL_METHOD(name, type)                                  \
2437 type vm_call_method##name(methodinfo *m, java_handle_t *o, ...)     \
2438 {                                                                   \
2439         va_list ap;                                                     \
2440         type    value;                                                  \
2441                                                                     \
2442         va_start(ap, o);                                                \
2443         value = vm_call_method##name##_valist(m, o, ap);                \
2444         va_end(ap);                                                     \
2445                                                                     \
2446         return value;                                                   \
2447 }
2448
2449 VM_CALL_METHOD(,        java_handle_t *)
2450 VM_CALL_METHOD(_int,    int32_t)
2451 VM_CALL_METHOD(_long,   int64_t)
2452 VM_CALL_METHOD(_float,  float)
2453 VM_CALL_METHOD(_double, double)
2454
2455
2456 /* vm_call_method_valist *******************************************************
2457
2458    Calls a Java method with a variable number of arguments, passed via
2459    a va_list.
2460
2461 *******************************************************************************/
2462
2463 #define VM_CALL_METHOD_VALIST(name, type)                               \
2464 type vm_call_method##name##_valist(methodinfo *m, java_handle_t *o,     \
2465                                                                    va_list ap)                          \
2466 {                                                                       \
2467         uint64_t *array;                                                    \
2468         type      value;                                                    \
2469         int32_t   dumpmarker;                                               \
2470                                                                         \
2471         if (m->code == NULL)                                                \
2472                 if (!jit_compile(m))                                            \
2473                         return 0;                                                   \
2474                                                                         \
2475         THREAD_NATIVEWORLD_EXIT;                                            \
2476         DMARKER;                                                            \
2477                                                                         \
2478         array = argument_vmarray_from_valist(m, o, ap);                     \
2479         value = vm_call##name##_array(m, array);                            \
2480                                                                         \
2481         DRELEASE;                                                           \
2482         THREAD_NATIVEWORLD_ENTER;                                           \
2483                                                                         \
2484         return value;                                                       \
2485 }
2486
2487 VM_CALL_METHOD_VALIST(,        java_handle_t *)
2488 VM_CALL_METHOD_VALIST(_int,    int32_t)
2489 VM_CALL_METHOD_VALIST(_long,   int64_t)
2490 VM_CALL_METHOD_VALIST(_float,  float)
2491 VM_CALL_METHOD_VALIST(_double, double)
2492
2493
2494 /* vm_call_method_jvalue *******************************************************
2495
2496    Calls a Java method with a variable number of arguments, passed via
2497    a jvalue array.
2498
2499 *******************************************************************************/
2500
2501 #define VM_CALL_METHOD_JVALUE(name, type)                               \
2502 type vm_call_method##name##_jvalue(methodinfo *m, java_handle_t *o,     \
2503                                                            const jvalue *args)                  \
2504 {                                                                       \
2505         uint64_t *array;                                                    \
2506         type      value;                                                    \
2507         int32_t   dumpmarker;                                               \
2508                                                                         \
2509         if (m->code == NULL)                                                \
2510                 if (!jit_compile(m))                                            \
2511                         return 0;                                                   \
2512                                                                         \
2513         THREAD_NATIVEWORLD_EXIT;                                            \
2514         DMARKER;                                                            \
2515                                                                         \
2516         array = argument_vmarray_from_jvalue(m, o, args);                   \
2517         value = vm_call##name##_array(m, array);                            \
2518                                                                         \
2519         DRELEASE;                                                           \
2520         THREAD_NATIVEWORLD_ENTER;                                           \
2521                                                                         \
2522         return value;                                                       \
2523 }
2524
2525 VM_CALL_METHOD_JVALUE(,        java_handle_t *)
2526 VM_CALL_METHOD_JVALUE(_int,    int32_t)
2527 VM_CALL_METHOD_JVALUE(_long,   int64_t)
2528 VM_CALL_METHOD_JVALUE(_float,  float)
2529 VM_CALL_METHOD_JVALUE(_double, double)
2530
2531
2532 /* vm_call_method_objectarray **************************************************
2533
2534    Calls a Java method with a variable number if arguments, passed via
2535    an objectarray of boxed values. Returns a boxed value.
2536
2537 *******************************************************************************/
2538
2539 java_handle_t *vm_call_method_objectarray(methodinfo *m, java_handle_t *o,
2540                                                                                   java_handle_objectarray_t *params)
2541 {
2542         uint64_t      *array;
2543         java_handle_t *xptr;
2544         java_handle_t *ro;
2545         imm_union      value;
2546         int32_t        dumpmarker;
2547
2548         /* Prevent compiler warnings. */
2549
2550         ro = NULL;
2551
2552         /* compile methods which are not yet compiled */
2553
2554         if (m->code == NULL)
2555                 if (!jit_compile(m))
2556                         return NULL;
2557
2558         /* leave the nativeworld */
2559
2560         THREAD_NATIVEWORLD_EXIT;
2561
2562         /* mark start of dump memory area */
2563
2564         DMARKER;
2565
2566         /* Fill the argument array from a object-array. */
2567
2568         array = argument_vmarray_from_objectarray(m, o, params);
2569
2570         if (array == NULL) {
2571                 /* release dump area */
2572
2573                 DRELEASE;
2574
2575                 /* enter the nativeworld again */
2576
2577                 THREAD_NATIVEWORLD_ENTER;
2578
2579                 exceptions_throw_illegalargumentexception();
2580
2581                 return NULL;
2582         }
2583
2584         switch (m->parseddesc->returntype.decltype) {
2585         case PRIMITIVETYPE_VOID:
2586                 value.a = vm_call_array(m, array);
2587                 break;
2588
2589         case PRIMITIVETYPE_BOOLEAN:
2590         case PRIMITIVETYPE_BYTE:
2591         case PRIMITIVETYPE_CHAR:
2592         case PRIMITIVETYPE_SHORT:
2593         case PRIMITIVETYPE_INT:
2594                 value.i = vm_call_int_array(m, array);
2595                 break;
2596
2597         case PRIMITIVETYPE_LONG:
2598                 value.l = vm_call_long_array(m, array);
2599                 break;
2600
2601         case PRIMITIVETYPE_FLOAT:
2602                 value.f = vm_call_float_array(m, array);
2603                 break;
2604
2605         case PRIMITIVETYPE_DOUBLE:
2606                 value.d = vm_call_double_array(m, array);
2607                 break;
2608
2609         case TYPE_ADR:
2610                 ro = vm_call_array(m, array);
2611                 break;
2612
2613         default:
2614                 vm_abort("vm_call_method_objectarray: invalid return type %d", m->parseddesc->returntype.decltype);
2615         }
2616
2617         /* release dump area */
2618
2619         DRELEASE;
2620
2621         /* enter the nativeworld again */
2622
2623         THREAD_NATIVEWORLD_ENTER;
2624
2625         /* box the return value if necesarry */
2626
2627         if (m->parseddesc->returntype.decltype != TYPE_ADR)
2628                 ro = primitive_box(m->parseddesc->returntype.decltype, value);
2629
2630         /* check for an exception */
2631
2632         xptr = exceptions_get_exception();
2633
2634         if (xptr != NULL) {
2635                 /* clear exception pointer, we are calling JIT code again */
2636
2637                 exceptions_clear_exception();
2638
2639                 exceptions_throw_invocationtargetexception(xptr);
2640         }
2641
2642         return ro;
2643 }
2644
2645
2646 /*
2647  * These are local overrides for various environment variables in Emacs.
2648  * Please do not remove this and leave it at the end of the file, where
2649  * Emacs will automagically detect them.
2650  * ---------------------------------------------------------------------
2651  * Local variables:
2652  * mode: c
2653  * indent-tabs-mode: t
2654  * c-basic-offset: 4
2655  * tab-width: 4
2656  * End:
2657  * vim:noexpandtab:sw=4:ts=4:
2658  */