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