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