* src/vm/vm.cpp (VM::VM) [ENABLE_SSA]: Declare variable in for.
[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                         // FIXME Make class_path const char*.
872                         class_path = (char*) properties_get("java.class.path");
873
874                         p = MNEW(char, strlen(opt_arg) + strlen("0"));
875
876                         strcpy(p, opt_arg);
877
878 #if defined(ENABLE_JAVASE)
879                         properties_add("java.class.path", p);
880 #endif
881
882                         MFREE(class_path, char, strlen(class_path));
883                         break;
884
885                 case OPT_D:
886                         for (unsigned int i = 0; i < strlen(opt_arg); i++) {
887                                 if (opt_arg[i] == '=') {
888                                         opt_arg[i] = '\0';
889                                         properties_add(opt_arg, opt_arg + i + 1);
890                                         goto opt_d_done;
891                                 }
892                         }
893
894                         /* if no '=' is given, just create an empty property */
895
896                         properties_add(opt_arg, "");
897
898                 opt_d_done:
899                         break;
900
901                 case OPT_BOOTCLASSPATH:
902                         /* Forget default bootclasspath and set the argument as
903                            new boot classpath. */
904
905                         // FIXME Make boot_class_path const char*.
906                         boot_class_path = (char*) properties_get("sun.boot.class.path");
907
908                         p = MNEW(char, strlen(opt_arg) + strlen("0"));
909
910                         strcpy(p, opt_arg);
911
912                         properties_add("sun.boot.class.path", p);
913                         properties_add("java.boot.class.path", p);
914
915                         MFREE(boot_class_path, char, strlen(boot_class_path));
916                         break;
917
918                 case OPT_BOOTCLASSPATH_A:
919                         /* Append to bootclasspath. */
920
921                         // FIXME Make boot_class_path const char*.
922                         boot_class_path = (char*) properties_get("sun.boot.class.path");
923
924                         len = strlen(boot_class_path);
925
926                         // XXX (char*) quick hack
927                         p = (char*) MREALLOC(boot_class_path,
928                                                  char,
929                                                  len + strlen("0"),
930                                                  len + strlen(":") +
931                                                  strlen(opt_arg) + strlen("0"));
932
933                         strcat(p, ":");
934                         strcat(p, opt_arg);
935
936                         properties_add("sun.boot.class.path", p);
937                         properties_add("java.boot.class.path", p);
938                         break;
939
940                 case OPT_BOOTCLASSPATH_P:
941                         /* Prepend to bootclasspath. */
942
943                         // FIXME Make boot_class_path const char*.
944                         boot_class_path = (char*) properties_get("sun.boot.class.path");
945
946                         len = strlen(boot_class_path);
947
948                         p = MNEW(char, strlen(opt_arg) + strlen(":") + len + strlen("0"));
949
950                         strcpy(p, opt_arg);
951                         strcat(p, ":");
952                         strcat(p, boot_class_path);
953
954                         properties_add("sun.boot.class.path", p);
955                         properties_add("java.boot.class.path", p);
956
957                         MFREE(boot_class_path, char, len);
958                         break;
959
960                 case OPT_BOOTCLASSPATH_C:
961                         /* Use as Java core library, but prepend VM interface
962                            classes. */
963
964                         // FIXME Make boot_class_path const char*.
965                         boot_class_path = (char*) properties_get("sun.boot.class.path");
966
967                         len =
968                                 strlen(CACAO_VM_ZIP) +
969                                 strlen(":") +
970                                 strlen(opt_arg) +
971                                 strlen("0");
972
973                         p = MNEW(char, len);
974
975                         strcpy(p, CACAO_VM_ZIP);
976                         strcat(p, ":");
977                         strcat(p, opt_arg);
978
979                         properties_add("sun.boot.class.path", p);
980                         properties_add("java.boot.class.path", p);
981
982                         MFREE(boot_class_path, char, strlen(boot_class_path));
983                         break;
984
985 #if defined(ENABLE_JVMTI)
986                 case OPT_DEBUG:
987                         /* this option exists only for compatibility reasons */
988                         break;
989
990                 case OPT_NOAGENT:
991                         /* I don't know yet what Xnoagent should do. This is only for 
992                            compatiblity with eclipse - motse */
993                         break;
994
995                 case OPT_XRUNJDWP:
996                         agentbypath = true;
997                         jvmti       = true;
998                         jdwp        = true;
999
1000                         len =
1001                                 strlen(CACAO_LIBDIR) +
1002                                 strlen("/libjdwp.so=") +
1003                                 strlen(opt_arg) +
1004                                 strlen("0");
1005
1006                         agentarg = MNEW(char, len);
1007
1008                         strcpy(agentarg, CACAO_LIBDIR);
1009                         strcat(agentarg, "/libjdwp.so=");
1010                         strcat(agentarg, &opt_arg[1]);
1011                         break;
1012
1013                 case OPT_AGENTPATH:
1014                         agentbypath = true;
1015
1016                 case OPT_AGENTLIB:
1017                         jvmti = true;
1018                         agentarg = opt_arg;
1019                         break;
1020 #endif
1021                         
1022                 case OPT_MX:
1023                 case OPT_MS:
1024                 case OPT_SS:
1025                         {
1026                                 char c;
1027                                 int j;
1028
1029                                 c = opt_arg[strlen(opt_arg) - 1];
1030
1031                                 if ((c == 'k') || (c == 'K')) {
1032                                         j = atoi(opt_arg) * 1024;
1033
1034                                 } else if ((c == 'm') || (c == 'M')) {
1035                                         j = atoi(opt_arg) * 1024 * 1024;
1036
1037                                 } else
1038                                         j = atoi(opt_arg);
1039
1040                                 if (opt == OPT_MX)
1041                                         opt_heapmaxsize = j;
1042                                 else if (opt == OPT_MS)
1043                                         opt_heapstartsize = j;
1044                                 else
1045                                         opt_stacksize = j;
1046                         }
1047                         break;
1048
1049                 case OPT_VERBOSE1:
1050                         opt_verbose = true;
1051                         break;
1052
1053                 case OPT_VERBOSE:
1054                         if (strcmp("class", opt_arg) == 0) {
1055                                 opt_verboseclass = true;
1056                         }
1057                         else if (strcmp("gc", opt_arg) == 0) {
1058                                 opt_verbosegc = true;
1059                         }
1060                         else if (strcmp("jni", opt_arg) == 0) {
1061                                 opt_verbosejni = true;
1062                         }
1063 #if !defined(NDEBUG)
1064                         else if (strcmp("jit", opt_arg) == 0) {
1065                                 opt_verbose = true;
1066                                 loadverbose = true;
1067                                 initverbose = true;
1068                                 compileverbose = true;
1069                         }
1070 #endif
1071                         else {
1072                                 printf("Unknown -verbose option: %s\n", opt_arg);
1073                                 usage();
1074                         }
1075                         break;
1076
1077                 case OPT_DEBUGCOLOR:
1078                         opt_debugcolor = true;
1079                         break;
1080
1081 #if defined(ENABLE_VERIFIER) && defined(TYPECHECK_VERBOSE)
1082                 case OPT_VERBOSETC:
1083                         opt_typecheckverbose = true;
1084                         break;
1085 #endif
1086                                 
1087                 case OPT_VERSION:
1088                         opt_version = true;
1089                         opt_exit    = true;
1090                         break;
1091
1092                 case OPT_FULLVERSION:
1093                         fullversion();
1094                         break;
1095
1096                 case OPT_SHOWVERSION:
1097                         opt_version = true;
1098                         break;
1099
1100                 case OPT_NOIEEE:
1101                         opt_noieee = true;
1102                         break;
1103
1104 #if defined(ENABLE_VERIFIER)
1105                 case OPT_NOVERIFY:
1106                         opt_verify = false;
1107                         break;
1108 #endif
1109
1110 #if defined(ENABLE_STATISTICS)
1111                 case OPT_TIME:
1112                         opt_getcompilingtime = true;
1113                         opt_getloadingtime = true;
1114                         break;
1115                                         
1116                 case OPT_STAT:
1117                         opt_stat = true;
1118                         break;
1119 #endif
1120                                         
1121                 case OPT_LOG:
1122                         log_init(opt_arg);
1123                         break;
1124                         
1125                 case OPT_CHECK:
1126                         for (unsigned int i = 0; i < strlen(opt_arg); i++) {
1127                                 switch (opt_arg[i]) {
1128                                 case 'b':
1129                                         checkbounds = false;
1130                                         break;
1131                                 case 's':
1132                                         checksync = false;
1133                                         break;
1134                                 default:
1135                                         usage();
1136                                 }
1137                         }
1138                         break;
1139                         
1140                 case OPT_LOAD:
1141                         opt_run = false;
1142                         makeinitializations = false;
1143                         break;
1144
1145 #if !defined(NDEBUG)
1146                 case OPT_ALL:
1147                         compileall = true;
1148                         opt_run = false;
1149                         makeinitializations = false;
1150                         break;
1151
1152                 case OPT_METHOD:
1153                         opt_run = false;
1154                         opt_method = opt_arg;
1155                         makeinitializations = false;
1156                         break;
1157
1158                 case OPT_SIGNATURE:
1159                         opt_signature = opt_arg;
1160                         break;
1161 #endif
1162
1163                 case OPT_SHOW:       /* Display options */
1164                         for (unsigned int i = 0; i < strlen(opt_arg); i++) {            
1165                                 switch (opt_arg[i]) {
1166                                 case 'c':
1167                                         showconstantpool = true;
1168                                         break;
1169
1170                                 case 'u':
1171                                         showutf = true;
1172                                         break;
1173
1174                                 case 'm':
1175                                         showmethods = true;
1176                                         break;
1177
1178                                 case 'i':
1179                                         opt_showintermediate = true;
1180                                         compileverbose = true;
1181                                         break;
1182
1183 #if defined(ENABLE_DISASSEMBLER)
1184                                 case 'a':
1185                                         opt_showdisassemble = true;
1186                                         compileverbose = true;
1187                                         break;
1188
1189                                 case 'o':
1190                                         opt_shownops = true;
1191                                         break;
1192 #endif
1193
1194                                 case 'd':
1195                                         opt_showddatasegment = true;
1196                                         break;
1197
1198                                 default:
1199                                         usage();
1200                                 }
1201                         }
1202                         break;
1203                         
1204 #if defined(ENABLE_LOOP)
1205                 case OPT_OLOOP:
1206                         opt_loops = true;
1207                         break;
1208 #endif
1209
1210 #if defined(ENABLE_IFCONV)
1211                 case OPT_IFCONV:
1212                         opt_ifconv = true;
1213                         break;
1214 #endif
1215
1216 #if defined(ENABLE_LSRA)
1217                 case OPT_LSRA:
1218                         opt_lsra = true;
1219                         break;
1220 #endif
1221 #if  defined(ENABLE_SSA)
1222                 case OPT_LSRA:
1223                         opt_lsra = true;
1224                         for (unsigned int i = 0; i < strlen(opt_arg); i++) {            
1225                                 switch (opt_arg[i]) {
1226                                 case 'c':
1227                                         opt_ssa_cp = true;
1228                                         break;
1229
1230                                 case 'd':
1231                                         opt_ssa_dce = true;
1232                                         break;
1233
1234                                 case ':':
1235                                         break;
1236
1237                                 default:
1238                                         usage();
1239                                 }
1240                         }
1241                         break;
1242 #endif
1243
1244                 case OPT_HELP:
1245                         usage();
1246                         break;
1247
1248                 case OPT_X:
1249                         Xusage();
1250                         break;
1251
1252                 case OPT_XX:
1253                         /* Already parsed. */
1254                         break;
1255
1256                 case OPT_EA:
1257 #if defined(ENABLE_ASSERTION)
1258                         assertion_ea_da(opt_arg, true);
1259 #endif
1260                         break;
1261
1262                 case OPT_DA:
1263 #if defined(ENABLE_ASSERTION)
1264                         assertion_ea_da(opt_arg, false);
1265 #endif
1266                         break;
1267
1268                 case OPT_EA_NOARG:
1269 #if defined(ENABLE_ASSERTION)
1270                         assertion_user_enabled = true;
1271 #endif
1272                         break;
1273
1274                 case OPT_DA_NOARG:
1275 #if defined(ENABLE_ASSERTION)
1276                         assertion_user_enabled = false;
1277 #endif
1278                         break;
1279
1280                 case OPT_ESA:
1281 #if defined(ENABLE_ASSERTION)
1282                         assertion_system_enabled = true;
1283 #endif
1284                         break;
1285
1286                 case OPT_DSA:
1287 #if defined(ENABLE_ASSERTION)
1288                         assertion_system_enabled = false;
1289 #endif
1290                         break;
1291
1292 #if defined(ENABLE_PROFILING)
1293                 case OPT_PROF_OPTION:
1294                         /* use <= to get the last \0 too */
1295
1296                         for (unsigned int i = 0, j = 0; i <= strlen(opt_arg); i++) {
1297                                 if (opt_arg[i] == ',')
1298                                         opt_arg[i] = '\0';
1299
1300                                 if (opt_arg[i] == '\0') {
1301                                         if (strcmp("bb", opt_arg + j) == 0)
1302                                                 opt_prof_bb = true;
1303
1304                                         else {
1305                                                 printf("Unknown option: -Xprof:%s\n", opt_arg + j);
1306                                                 usage();
1307                                         }
1308
1309                                         /* set k to next char */
1310
1311                                         j = i + 1;
1312                                 }
1313                         }
1314                         /* fall through */
1315
1316                 case OPT_PROF:
1317                         opt_prof = true;
1318                         break;
1319 #endif
1320
1321                 case OPT_JIT:
1322 #if defined(ENABLE_JIT)
1323                         opt_jit = true;
1324 #else
1325                         printf("-Xjit option not enabled.\n");
1326                         exit(1);
1327 #endif
1328                         break;
1329
1330                 case OPT_INTRP:
1331 #if defined(ENABLE_INTRP)
1332                         opt_intrp = true;
1333 #else
1334                         printf("-Xint option not enabled.\n");
1335                         exit(1);
1336 #endif
1337                         break;
1338
1339 #if defined(ENABLE_INTRP)
1340                 case OPT_STATIC_SUPERS:
1341                         opt_static_supers = atoi(opt_arg);
1342                         break;
1343
1344                 case OPT_NO_DYNAMIC:
1345                         opt_no_dynamic = true;
1346                         break;
1347
1348                 case OPT_NO_REPLICATION:
1349                         opt_no_replication = true;
1350                         break;
1351
1352                 case OPT_NO_QUICKSUPER:
1353                         opt_no_quicksuper = true;
1354                         break;
1355
1356                 case OPT_TRACE:
1357                         vm_debug = true;
1358                         break;
1359 #endif
1360
1361 #if defined(ENABLE_DEBUG_FILTER)
1362                 case OPT_FILTER_VERBOSECALL_INCLUDE:
1363                         opt_filter_verbosecall_include = opt_arg;
1364                         break;
1365
1366                 case OPT_FILTER_VERBOSECALL_EXCLUDE:
1367                         opt_filter_verbosecall_exclude = opt_arg;
1368                         break;
1369
1370                 case OPT_FILTER_SHOW_METHOD:
1371                         opt_filter_show_method = opt_arg;
1372                         break;
1373
1374 #endif
1375                 default:
1376                         printf("Unknown option: %s\n",
1377                                    vm_args->options[opt_index].optionString);
1378                         usage();
1379                 }
1380         }
1381
1382 #if defined(ENABLE_JVMTI)
1383         if (jvmti) {
1384                 jvmti_set_phase(JVMTI_PHASE_ONLOAD);
1385                 jvmti_agentload(agentarg, agentbypath, &handle, &libname);
1386
1387                 if (jdwp)
1388                         MFREE(agentarg, char, strlen(agentarg));
1389
1390                 jvmti_set_phase(JVMTI_PHASE_PRIMORDIAL);
1391         }
1392 #endif
1393
1394         /* initialize the garbage collector */
1395
1396         gc_init(opt_heapmaxsize, opt_heapstartsize);
1397
1398 #if defined(ENABLE_THREADS)
1399         /* BEFORE: threads_preinit */
1400
1401         threadlist_init();
1402
1403         /* AFTER: gc_init */
1404
1405         threads_preinit();
1406         lock_init();
1407 #endif
1408
1409         /* install architecture dependent signal handlers */
1410
1411         if (!signal_init())
1412                 vm_abort("vm_create: signal_init failed");
1413
1414 #if defined(ENABLE_INTRP)
1415         /* Allocate main thread stack on the Java heap. */
1416
1417         if (opt_intrp) {
1418                 intrp_main_stack = GCMNEW(u1, opt_stacksize);
1419                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1420         }
1421 #endif
1422
1423         /* AFTER: threads_preinit */
1424
1425         if (!string_init())
1426                 vm_abort("vm_create: string_init failed");
1427
1428         /* AFTER: threads_preinit */
1429
1430         utf8_init();
1431
1432         /* AFTER: thread_preinit */
1433
1434         if (!suck_init())
1435                 vm_abort("vm_create: suck_init failed");
1436
1437         suck_add_from_property("java.endorsed.dirs");
1438
1439         /* Now we have all options handled and we can print the version
1440            information.
1441
1442            AFTER: suck_add_from_property("java.endorsed.dirs"); */
1443
1444         if (opt_version)
1445                 version(opt_exit);
1446
1447         /* AFTER: utf8_init */
1448
1449         // FIXME Make boot_class_path const char*.
1450         boot_class_path = (char*) properties_get("sun.boot.class.path");
1451         suck_add(boot_class_path);
1452
1453         /* initialize the classcache hashtable stuff: lock, hashtable
1454            (must be done _after_ threads_preinit) */
1455
1456         if (!classcache_init())
1457                 vm_abort("vm_create: classcache_init failed");
1458
1459         /* Initialize the code memory management. */
1460         /* AFTER: threads_preinit */
1461
1462         codememory_init();
1463
1464         /* initialize the finalizer stuff (must be done _after_
1465            threads_preinit) */
1466
1467         if (!finalizer_init())
1468                 vm_abort("vm_create: finalizer_init failed");
1469
1470         /* Initialize the JIT compiler. */
1471
1472         jit_init();
1473         code_init();
1474         methodtree_init();
1475
1476 #if defined(ENABLE_PYTHON)
1477         pythonpass_init();
1478 #endif
1479
1480         /* BEFORE: loader_preinit */
1481
1482         Package::initialize();
1483
1484         /* AFTER: utf8_init, classcache_init */
1485
1486         loader_preinit();
1487         linker_preinit();
1488
1489         /* AFTER: loader_preinit, linker_preinit */
1490
1491         primitive_init();
1492
1493         loader_init();
1494         linker_init();
1495
1496         /* AFTER: loader_init, linker_init */
1497
1498         primitive_postinit();
1499         method_init();
1500
1501 #if defined(ENABLE_JIT)
1502         trap_init();
1503 #endif
1504
1505         if (!builtin_init())
1506                 vm_abort("vm_create: builtin_init failed");
1507
1508         /* Initialize the native subsystem. */
1509         /* BEFORE: threads_init */
1510
1511         if (!native_init())
1512                 vm_abort("vm_create: native_init failed");
1513
1514         /* Register the native methods implemented in the VM. */
1515         /* BEFORE: threads_init */
1516
1517         nativevm_preinit();
1518
1519 #if defined(ENABLE_JNI)
1520         /* Initialize the JNI subsystem (must be done _before_
1521            threads_init, as threads_init can call JNI methods
1522            (e.g. NewGlobalRef). */
1523
1524         if (!jni_init())
1525                 vm_abort("vm_create: jni_init failed");
1526 #endif
1527
1528 #if defined(ENABLE_JNI) || defined(ENABLE_HANDLES)
1529         /* Initialize the local reference table for the main thread. */
1530         /* BEFORE: threads_init */
1531
1532         if (!localref_table_init())
1533                 vm_abort("vm_create: localref_table_init failed");
1534 #endif
1535
1536         /* Iinitialize some important system classes. */
1537         /* BEFORE: threads_init */
1538
1539         initialize_init();
1540
1541 #if defined(ENABLE_THREADS)
1542         threads_init();
1543 #endif
1544
1545         /* Initialize the native VM subsystem. */
1546         /* AFTER: threads_init (at least for SUN's classes) */
1547
1548         nativevm_init();
1549
1550 #if defined(ENABLE_PROFILING)
1551         /* initialize profiling */
1552
1553         if (!profile_init())
1554                 vm_abort("vm_create: profile_init failed");
1555 #endif
1556
1557 #if defined(ENABLE_THREADS)
1558         /* initialize recompilation */
1559
1560         if (!recompile_init())
1561                 vm_abort("vm_create: recompile_init failed");
1562
1563         /* start the signal handler thread */
1564
1565 #if defined(__LINUX__)
1566         /* XXX Remove for exact-GC. */
1567         if (threads_pthreads_implementation_nptl)
1568 #endif
1569                 if (!signal_start_thread())
1570                         vm_abort("vm_create: signal_start_thread failed");
1571
1572         /* finally, start the finalizer thread */
1573
1574         if (!finalizer_start_thread())
1575                 vm_abort("vm_create: finalizer_start_thread failed");
1576
1577 # if !defined(NDEBUG)
1578         /* start the memory profiling thread */
1579
1580         if (opt_ProfileMemoryUsage || opt_ProfileGCMemoryUsage)
1581                 if (!memory_start_thread())
1582                         vm_abort("vm_create: memory_start_thread failed");
1583 # endif
1584
1585         /* start the recompilation thread (must be done before the
1586            profiling thread) */
1587
1588         if (!recompile_start_thread())
1589                 vm_abort("vm_create: recompile_start_thread failed");
1590
1591 # if defined(ENABLE_PROFILING)
1592         /* start the profile sampling thread */
1593
1594 /*      if (opt_prof) */
1595 /*              if (!profile_start_thread()) */
1596 /*                      vm_abort("vm_create: profile_start_thread failed"); */
1597 # endif
1598 #endif
1599
1600 #if defined(ENABLE_JVMTI)
1601 # if defined(ENABLE_GC_CACAO)
1602         /* XXX this will not work with the new indirection cells for classloaders!!! */
1603         assert(0);
1604 # endif
1605         if (jvmti) {
1606                 /* add agent library to native library hashtable */
1607                 native_hashtable_library_add(utf_new_char(libname), class_java_lang_Object->classloader, handle);
1608         }
1609 #endif
1610
1611         /* Increment the number of VMs. */
1612
1613         vms++;
1614
1615         // Initialization is done, VM is created.
1616         _created      = true;
1617         _initializing = false;
1618         
1619         /* Print the VM configuration after all stuff is set and the VM is
1620            initialized. */
1621
1622         if (opt_PrintConfig)
1623                 vm_printconfig();
1624 }
1625
1626
1627 /* vm_run **********************************************************************
1628
1629    Runs the main-method of the passed class.
1630
1631 *******************************************************************************/
1632
1633 void vm_run(JavaVM *vm, JavaVMInitArgs *vm_args)
1634 {
1635         char*                      option;
1636         char*                      mainname;
1637         char*                      p;
1638         utf                       *mainutf;
1639         classinfo                 *mainclass;
1640         java_handle_t             *e;
1641         methodinfo                *m;
1642         java_handle_objectarray_t *oa; 
1643         s4                         oalength;
1644         utf                       *u;
1645         java_handle_t             *s;
1646         int                        status;
1647
1648         // Prevent compiler warnings.
1649         oa = NULL;
1650
1651 #if !defined(NDEBUG)
1652         if (compileall) {
1653                 vm_compile_all();
1654                 return;
1655         }
1656 #endif
1657
1658         /* Get the main class plus it's arguments. */
1659
1660         mainname = NULL;
1661
1662         if (opt_index < vm_args->nOptions) {
1663                 /* Get main-class argument. */
1664
1665                 mainname = vm_args->options[opt_index].optionString;
1666
1667                 /* If the main class argument is a jar file, put it into the
1668                    classpath. */
1669
1670                 if (opt_jar == true) {
1671                         p = MNEW(char, strlen(mainname) + strlen("0"));
1672
1673                         strcpy(p, mainname);
1674
1675 #if defined(ENABLE_JAVASE)
1676                         properties_add("java.class.path", p);
1677 #endif
1678                 }
1679                 else {
1680                         /* Replace dots with slashes in the class name. */
1681
1682                         for (unsigned int i = 0; i < strlen(mainname); i++)
1683                                 if (mainname[i] == '.')
1684                                         mainname[i] = '/';
1685                 }
1686
1687                 /* Build argument array.  Move index to first argument. */
1688
1689                 opt_index++;
1690
1691                 oalength = vm_args->nOptions - opt_index;
1692
1693                 oa = builtin_anewarray(oalength, class_java_lang_String);
1694
1695                 for (int i = 0; i < oalength; i++) {
1696                         option = vm_args->options[opt_index + i].optionString;
1697
1698                         u = utf_new_char(option);
1699                         s = javastring_new(u);
1700
1701                         array_objectarray_element_set(oa, i, s);
1702                 }
1703         }
1704
1705         /* Do we have a main-class argument? */
1706
1707         if (mainname == NULL)
1708                 usage();
1709
1710 #if !defined(NDEBUG)
1711         if (opt_method != NULL) {
1712                 vm_compile_method(mainname);
1713                 return;
1714         }
1715 #endif
1716
1717         /* set return value to OK */
1718
1719         status = 0;
1720
1721         if (opt_jar == true) {
1722                 /* open jar file with java.util.jar.JarFile */
1723
1724                 mainname = vm_get_mainclass_from_jar(mainname);
1725
1726                 if (mainname == NULL)
1727                         vm_exit(1);
1728         }
1729
1730         /* load the main class */
1731
1732         mainutf = utf_new_char(mainname);
1733
1734 #if defined(ENABLE_JAVAME_CLDC1_1)
1735         mainclass = load_class_bootstrap(mainutf);
1736 #else
1737         mainclass = load_class_from_sysloader(mainutf);
1738 #endif
1739
1740         /* error loading class */
1741
1742         e = exceptions_get_and_clear_exception();
1743
1744         if ((e != NULL) || (mainclass == NULL)) {
1745                 exceptions_throw_noclassdeffounderror_cause(e);
1746                 exceptions_print_stacktrace(); 
1747                 vm_exit(1);
1748         }
1749
1750         if (!link_class(mainclass)) {
1751                 exceptions_print_stacktrace();
1752                 vm_exit(1);
1753         }
1754                         
1755         /* find the `main' method of the main class */
1756
1757         m = class_resolveclassmethod(mainclass,
1758                                                                  utf_new_char("main"), 
1759                                                                  utf_new_char("([Ljava/lang/String;)V"),
1760                                                                  class_java_lang_Object,
1761                                                                  false);
1762
1763         if (exceptions_get_exception()) {
1764                 exceptions_print_stacktrace();
1765                 vm_exit(1);
1766         }
1767
1768         /* there is no main method or it isn't static */
1769
1770         if ((m == NULL) || !(m->flags & ACC_STATIC)) {
1771                 exceptions_clear_exception();
1772                 exceptions_throw_nosuchmethoderror(mainclass,
1773                                                                                    utf_new_char("main"), 
1774                                                                                    utf_new_char("([Ljava/lang/String;)V"));
1775
1776                 exceptions_print_stacktrace();
1777                 vm_exit(1);
1778         }
1779
1780 #ifdef TYPEINFO_DEBUG_TEST
1781         /* test the typeinfo system */
1782         typeinfo_test();
1783 #endif
1784
1785 #if defined(ENABLE_JVMTI)
1786         jvmti_set_phase(JVMTI_PHASE_LIVE);
1787 #endif
1788
1789         /* set ThreadMXBean variables */
1790
1791 //      _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1792 //      _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1793
1794 //      if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1795 //              _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1796 //              _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1797 //                      _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1798 #warning Move to C++
1799
1800         /* start the main thread */
1801
1802         (void) vm_call_method(m, NULL, oa);
1803
1804         /* exception occurred? */
1805
1806         if (exceptions_get_exception()) {
1807                 exceptions_print_stacktrace();
1808                 status = 1;
1809         }
1810
1811 #if defined(ENABLE_THREADS)
1812     /* Detach the main thread so that it appears to have ended when
1813            the application's main method exits. */
1814
1815         if (!thread_detach_current_thread())
1816                 vm_abort("vm_run: Could not detach main thread.");
1817 #endif
1818
1819         /* Destroy the JavaVM. */
1820
1821         (void) vm_destroy(vm);
1822
1823         /* And exit. */
1824
1825         vm_exit(status);
1826 }
1827
1828
1829 /* vm_destroy ******************************************************************
1830
1831    Unloads a Java VM and reclaims its resources.
1832
1833 *******************************************************************************/
1834
1835 int vm_destroy(JavaVM *vm)
1836 {
1837 #if defined(ENABLE_THREADS)
1838         /* Create a a trivial new Java waiter thread called
1839            "DestroyJavaVM". */
1840
1841         JavaVMAttachArgs args;
1842
1843         args.name  = (char*) "DestroyJavaVM";
1844         args.group = NULL;
1845
1846         if (!thread_attach_current_thread(&args, false))
1847                 return 1;
1848
1849         /* Wait until we are the last non-daemon thread. */
1850
1851         threads_join_all_threads();
1852 #endif
1853
1854         /* VM is gone. */
1855
1856 //      _created = false;
1857 #warning Move to C++
1858
1859         /* Everything is ok. */
1860
1861         return 0;
1862 }
1863
1864
1865 /* vm_exit *********************************************************************
1866
1867    Calls java.lang.System.exit(I)V to exit the JavaVM correctly.
1868
1869 *******************************************************************************/
1870
1871 void vm_exit(s4 status)
1872 {
1873         methodinfo *m;
1874
1875         /* signal that we are exiting */
1876
1877 //      _exiting = true;
1878 #warning Move to C++
1879
1880         assert(class_java_lang_System);
1881         assert(class_java_lang_System->state & CLASS_LOADED);
1882
1883 #if defined(ENABLE_JVMTI)
1884         if (jvmti || (dbgcom!=NULL)) {
1885                 jvmti_set_phase(JVMTI_PHASE_DEAD);
1886                 if (jvmti) jvmti_agentunload();
1887         }
1888 #endif
1889
1890         if (!link_class(class_java_lang_System)) {
1891                 exceptions_print_stacktrace();
1892                 exit(1);
1893         }
1894
1895         /* call java.lang.System.exit(I)V */
1896
1897         m = class_resolveclassmethod(class_java_lang_System,
1898                                                                  utf_new_char("exit"),
1899                                                                  utf_int__void,
1900                                                                  class_java_lang_Object,
1901                                                                  true);
1902         
1903         if (m == NULL) {
1904                 exceptions_print_stacktrace();
1905                 exit(1);
1906         }
1907
1908         /* call the exit function with passed exit status */
1909
1910         (void) vm_call_method(m, NULL, status);
1911
1912         /* If we had an exception, just ignore the exception and exit with
1913            the proper code. */
1914
1915         vm_shutdown(status);
1916 }
1917
1918
1919 /* vm_shutdown *****************************************************************
1920
1921    Terminates the system immediately without freeing memory explicitly
1922    (to be used only for abnormal termination).
1923         
1924 *******************************************************************************/
1925
1926 void vm_shutdown(s4 status)
1927 {
1928         if (opt_verbose 
1929 #if defined(ENABLE_STATISTICS)
1930                 || opt_getcompilingtime || opt_stat
1931 #endif
1932            ) 
1933         {
1934                 log_text("CACAO terminated by shutdown");
1935                 dolog("Exit status: %d\n", (s4) status);
1936
1937         }
1938
1939 #if defined(ENABLE_JVMTI)
1940         /* terminate cacaodbgserver */
1941         if (dbgcom!=NULL) {
1942                 mutex_lock(&dbgcomlock);
1943                 dbgcom->running=1;
1944                 mutex_unlock(&dbgcomlock);
1945                 jvmti_cacaodbgserver_quit();
1946         }       
1947 #endif
1948
1949         exit(status);
1950 }
1951
1952
1953 /* vm_exit_handler *************************************************************
1954
1955    The exit_handler function is called upon program termination.
1956
1957    ATTENTION: Don't free system resources here! Some threads may still
1958    be running as this is called from VMRuntime.exit(). The OS does the
1959    cleanup for us.
1960
1961 *******************************************************************************/
1962
1963 void vm_exit_handler(void)
1964 {
1965 #if !defined(NDEBUG)
1966         if (showmethods)
1967                 class_showmethods(mainclass);
1968
1969         if (showconstantpool)
1970                 class_showconstantpool(mainclass);
1971
1972         if (showutf)
1973                 utf_show();
1974
1975 # if defined(ENABLE_PROFILING)
1976         if (opt_prof)
1977                 profile_printstats();
1978 # endif
1979 #endif /* !defined(NDEBUG) */
1980
1981 #if defined(ENABLE_RT_TIMING)
1982         rt_timing_print_time_stats(stderr);
1983 #endif
1984
1985 #if defined(ENABLE_CYCLES_STATS)
1986         builtin_print_cycles_stats(stderr);
1987         stacktrace_print_cycles_stats(stderr);
1988 #endif
1989
1990         if (opt_verbose 
1991 #if defined(ENABLE_STATISTICS)
1992                 || opt_getcompilingtime || opt_stat
1993 #endif
1994            ) 
1995         {
1996                 log_text("CACAO terminated");
1997
1998 #if defined(ENABLE_STATISTICS)
1999                 if (opt_stat) {
2000                         print_stats();
2001 #ifdef TYPECHECK_STATISTICS
2002                         typecheck_print_statistics(get_logfile());
2003 #endif
2004                 }
2005
2006                 if (opt_getcompilingtime)
2007                         print_times();
2008 #endif /* defined(ENABLE_STATISTICS) */
2009         }
2010         /* vm_print_profile(stderr);*/
2011 }
2012
2013
2014 /* vm_abort ********************************************************************
2015
2016    Prints an error message and aborts the VM.
2017
2018    IN:
2019        text ... error message to print
2020
2021 *******************************************************************************/
2022
2023 void vm_abort(const char *text, ...)
2024 {
2025         va_list ap;
2026
2027         /* Print the log message. */
2028
2029         log_start();
2030
2031         va_start(ap, text);
2032         log_vprint(text, ap);
2033         va_end(ap);
2034
2035         log_finish();
2036
2037         /* Now abort the VM. */
2038
2039         system_abort();
2040 }
2041
2042
2043 /* vm_abort_errnum *************************************************************
2044
2045    Prints an error message, appends ":" plus the strerror-message of
2046    errnum and aborts the VM.
2047
2048    IN:
2049        errnum ... error number
2050        text ..... error message to print
2051
2052 *******************************************************************************/
2053
2054 void vm_abort_errnum(int errnum, const char *text, ...)
2055 {
2056         va_list ap;
2057
2058         /* Print the log message. */
2059
2060         log_start();
2061
2062         va_start(ap, text);
2063         log_vprint(text, ap);
2064         va_end(ap);
2065
2066         /* Print the strerror-message of errnum. */
2067
2068         log_print(": %s", system_strerror(errnum));
2069
2070         log_finish();
2071
2072         /* Now abort the VM. */
2073
2074         system_abort();
2075 }
2076
2077
2078 /* vm_abort_errno **************************************************************
2079
2080    Equal to vm_abort_errnum, but uses errno to get the error number.
2081
2082    IN:
2083        text ... error message to print
2084
2085 *******************************************************************************/
2086
2087 void vm_abort_errno(const char *text, ...)
2088 {
2089         va_list ap;
2090
2091         va_start(ap, text);
2092         vm_abort_errnum(errno, text, ap);
2093         va_end(ap);
2094 }
2095
2096
2097 /* vm_abort_disassemble ********************************************************
2098
2099    Prints an error message, disassemble the given code range (if
2100    enabled) and aborts the VM.
2101
2102    IN:
2103        pc.......PC to disassemble
2104            count....number of instructions to disassemble
2105
2106 *******************************************************************************/
2107
2108 void vm_abort_disassemble(void *pc, int count, const char *text, ...)
2109 {
2110         va_list ap;
2111 #if defined(ENABLE_DISASSEMBLER)
2112         int     i;
2113 #endif
2114
2115         /* Print debug message. */
2116
2117         log_start();
2118
2119         va_start(ap, text);
2120         log_vprint(text, ap);
2121         va_end(ap);
2122
2123         log_finish();
2124
2125         /* Print the PC. */
2126
2127 #if SIZEOF_VOID_P == 8
2128         log_println("PC=0x%016lx", pc);
2129 #else
2130         log_println("PC=0x%08x", pc);
2131 #endif
2132
2133 #if defined(ENABLE_DISASSEMBLER)
2134         log_println("machine instructions at PC:");
2135
2136         /* Disassemble the given number of instructions. */
2137
2138         for (i = 0; i < count; i++)
2139                 // FIXME disassinstr should use void*.
2140                 pc = disassinstr((u1*) pc);
2141 #endif
2142
2143         vm_abort("Aborting...");
2144 }
2145
2146
2147 /* vm_get_mainclass_from_jar ***************************************************
2148
2149    Gets the name of the main class from a JAR's manifest file.
2150
2151 *******************************************************************************/
2152
2153 static char *vm_get_mainclass_from_jar(char *mainname)
2154 {
2155         classinfo     *c;
2156         java_handle_t *o;
2157         methodinfo    *m;
2158         java_handle_t *s;
2159
2160         c = load_class_from_sysloader(utf_new_char("java/util/jar/JarFile"));
2161
2162         if (c == NULL) {
2163                 exceptions_print_stacktrace();
2164                 return NULL;
2165         }
2166
2167         /* create JarFile object */
2168
2169         o = builtin_new(c);
2170
2171         if (o == NULL) {
2172                 exceptions_print_stacktrace();
2173                 return NULL;
2174         }
2175
2176         m = class_resolveclassmethod(c,
2177                                                                  utf_init, 
2178                                                                  utf_java_lang_String__void,
2179                                                                  class_java_lang_Object,
2180                                                                  true);
2181
2182         if (m == NULL) {
2183                 exceptions_print_stacktrace();
2184                 return NULL;
2185         }
2186
2187         s = javastring_new_from_ascii(mainname);
2188
2189         (void) vm_call_method(m, o, s);
2190
2191         if (exceptions_get_exception()) {
2192                 exceptions_print_stacktrace();
2193                 return NULL;
2194         }
2195
2196         /* get manifest object */
2197
2198         m = class_resolveclassmethod(c,
2199                                                                  utf_new_char("getManifest"), 
2200                                                                  utf_new_char("()Ljava/util/jar/Manifest;"),
2201                                                                  class_java_lang_Object,
2202                                                                  true);
2203
2204         if (m == NULL) {
2205                 exceptions_print_stacktrace();
2206                 return NULL;
2207         }
2208
2209         o = vm_call_method(m, o);
2210
2211         if (o == NULL) {
2212                 fprintf(stderr, "Could not get manifest from %s (invalid or corrupt jarfile?)\n", mainname);
2213                 return NULL;
2214         }
2215
2216
2217         /* get Main Attributes */
2218
2219         LLNI_class_get(o, c);
2220
2221         m = class_resolveclassmethod(c,
2222                                                                  utf_new_char("getMainAttributes"), 
2223                                                                  utf_new_char("()Ljava/util/jar/Attributes;"),
2224                                                                  class_java_lang_Object,
2225                                                                  true);
2226
2227         if (m == NULL) {
2228                 exceptions_print_stacktrace();
2229                 return NULL;
2230         }
2231
2232         o = vm_call_method(m, o);
2233
2234         if (o == NULL) {
2235                 fprintf(stderr, "Could not get main attributes from %s (invalid or corrupt jarfile?)\n", mainname);
2236                 return NULL;
2237         }
2238
2239
2240         /* get property Main-Class */
2241
2242         LLNI_class_get(o, c);
2243
2244         m = class_resolveclassmethod(c,
2245                                                                  utf_new_char("getValue"), 
2246                                                                  utf_new_char("(Ljava/lang/String;)Ljava/lang/String;"),
2247                                                                  class_java_lang_Object,
2248                                                                  true);
2249
2250         if (m == NULL) {
2251                 exceptions_print_stacktrace();
2252                 return NULL;
2253         }
2254
2255         s = javastring_new_from_ascii("Main-Class");
2256
2257         o = vm_call_method(m, o, s);
2258
2259         if (o == NULL) {
2260                 fprintf(stderr, "Failed to load Main-Class manifest attribute from\n");
2261                 fprintf(stderr, "%s\n", mainname);
2262                 return NULL;
2263         }
2264
2265         return javastring_tochar(o);
2266 }
2267
2268
2269 /* vm_compile_all **************************************************************
2270
2271    Compile all methods found in the bootclasspath.
2272
2273 *******************************************************************************/
2274
2275 #if !defined(NDEBUG)
2276 static void vm_compile_all(void)
2277 {
2278         classinfo              *c;
2279         methodinfo             *m;
2280         u4                      slot;
2281         classcache_name_entry  *nmen;
2282         classcache_class_entry *clsen;
2283         s4                      i;
2284
2285         /* create all classes found in the bootclasspath */
2286         /* XXX currently only works with zip/jar's */
2287
2288         loader_load_all_classes();
2289
2290         /* link all classes */
2291
2292         for (slot = 0; slot < hashtable_classcache.size; slot++) {
2293                 nmen = (classcache_name_entry *) hashtable_classcache.ptr[slot];
2294
2295                 for (; nmen; nmen = nmen->hashlink) {
2296                         /* iterate over all class entries */
2297
2298                         for (clsen = nmen->classes; clsen; clsen = clsen->next) {
2299                                 c = clsen->classobj;
2300
2301                                 if (c == NULL)
2302                                         continue;
2303
2304                                 if (!(c->state & CLASS_LINKED)) {
2305                                         if (!link_class(c)) {
2306                                                 fprintf(stderr, "Error linking: ");
2307                                                 utf_fprint_printable_ascii_classname(stderr, c->name);
2308                                                 fprintf(stderr, "\n");
2309
2310                                                 /* print out exception and cause */
2311
2312                                                 exceptions_print_current_exception();
2313
2314                                                 /* goto next class */
2315
2316                                                 continue;
2317                                         }
2318                                 }
2319
2320                                 /* compile all class methods */
2321
2322                                 for (i = 0; i < c->methodscount; i++) {
2323                                         m = &(c->methods[i]);
2324
2325                                         if (m->jcode != NULL) {
2326                                                 if (!jit_compile(m)) {
2327                                                         fprintf(stderr, "Error compiling: ");
2328                                                         utf_fprint_printable_ascii_classname(stderr, c->name);
2329                                                         fprintf(stderr, ".");
2330                                                         utf_fprint_printable_ascii(stderr, m->name);
2331                                                         utf_fprint_printable_ascii(stderr, m->descriptor);
2332                                                         fprintf(stderr, "\n");
2333
2334                                                         /* print out exception and cause */
2335
2336                                                         exceptions_print_current_exception();
2337                                                 }
2338                                         }
2339                                 }
2340                         }
2341                 }
2342         }
2343 }
2344 #endif /* !defined(NDEBUG) */
2345
2346
2347 /* vm_compile_method ***********************************************************
2348
2349    Compile a specific method.
2350
2351 *******************************************************************************/
2352
2353 #if !defined(NDEBUG)
2354 static void vm_compile_method(char* mainname)
2355 {
2356         methodinfo *m;
2357
2358         /* create, load and link the main class */
2359
2360         mainclass = load_class_bootstrap(utf_new_char(mainname));
2361
2362         if (mainclass == NULL)
2363                 exceptions_print_stacktrace();
2364
2365         if (!link_class(mainclass))
2366                 exceptions_print_stacktrace();
2367
2368         if (opt_signature != NULL) {
2369                 m = class_resolveclassmethod(mainclass,
2370                                                                          utf_new_char(opt_method),
2371                                                                          utf_new_char(opt_signature),
2372                                                                          mainclass,
2373                                                                          false);
2374         }
2375         else {
2376                 m = class_resolveclassmethod(mainclass,
2377                                                                          utf_new_char(opt_method),
2378                                                                          NULL,
2379                                                                          mainclass,
2380                                                                          false);
2381         }
2382
2383         if (m == NULL)
2384                 vm_abort("vm_compile_method: java.lang.NoSuchMethodException: %s.%s",
2385                                  opt_method, opt_signature ? opt_signature : "");
2386                 
2387         jit_compile(m);
2388 }
2389 #endif /* !defined(NDEBUG) */
2390
2391
2392 /* vm_call_array ***************************************************************
2393
2394    Calls a Java method with a variable number of arguments, passed via
2395    an argument array.
2396
2397    ATTENTION: This function has to be used outside the nativeworld.
2398
2399 *******************************************************************************/
2400
2401 #define VM_CALL_ARRAY(name, type)                                 \
2402 static type vm_call##name##_array(methodinfo *m, uint64_t *array) \
2403 {                                                                 \
2404         methoddesc *md;                                               \
2405         void       *pv;                                               \
2406         type        value;                                            \
2407                                                                   \
2408         assert(m->code != NULL);                                      \
2409                                                                   \
2410         md = m->parseddesc;                                           \
2411         pv = m->code->entrypoint;                                     \
2412                                                                   \
2413         STATISTICS(count_calls_native_to_java++);                     \
2414                                                                   \
2415         value = asm_vm_call_method##name(pv, array, md->memuse);      \
2416                                                                   \
2417         return value;                                                 \
2418 }
2419
2420 static java_handle_t *vm_call_array(methodinfo *m, uint64_t *array)
2421 {
2422         methoddesc    *md;
2423         void          *pv;
2424         java_object_t *o;
2425
2426         assert(m->code != NULL);
2427
2428         md = m->parseddesc;
2429         pv = m->code->entrypoint;
2430
2431         STATISTICS(count_calls_native_to_java++);
2432
2433         o = asm_vm_call_method(pv, array, md->memuse);
2434
2435         if (md->returntype.type == TYPE_VOID)
2436                 o = NULL;
2437
2438         return LLNI_WRAP(o);
2439 }
2440
2441 VM_CALL_ARRAY(_int,    int32_t)
2442 VM_CALL_ARRAY(_long,   int64_t)
2443 VM_CALL_ARRAY(_float,  float)
2444 VM_CALL_ARRAY(_double, double)
2445
2446
2447 /* vm_call_method **************************************************************
2448
2449    Calls a Java method with a variable number of arguments.
2450
2451 *******************************************************************************/
2452
2453 #define VM_CALL_METHOD(name, type)                                  \
2454 type vm_call_method##name(methodinfo *m, java_handle_t *o, ...)     \
2455 {                                                                   \
2456         va_list ap;                                                     \
2457         type    value;                                                  \
2458                                                                     \
2459         va_start(ap, o);                                                \
2460         value = vm_call_method##name##_valist(m, o, ap);                \
2461         va_end(ap);                                                     \
2462                                                                     \
2463         return value;                                                   \
2464 }
2465
2466 VM_CALL_METHOD(,        java_handle_t *)
2467 VM_CALL_METHOD(_int,    int32_t)
2468 VM_CALL_METHOD(_long,   int64_t)
2469 VM_CALL_METHOD(_float,  float)
2470 VM_CALL_METHOD(_double, double)
2471
2472
2473 /* vm_call_method_valist *******************************************************
2474
2475    Calls a Java method with a variable number of arguments, passed via
2476    a va_list.
2477
2478 *******************************************************************************/
2479
2480 #define VM_CALL_METHOD_VALIST(name, type)                               \
2481 type vm_call_method##name##_valist(methodinfo *m, java_handle_t *o,     \
2482                                                                    va_list ap)                          \
2483 {                                                                       \
2484         uint64_t *array;                                                    \
2485         type      value;                                                    \
2486         int32_t   dumpmarker;                                               \
2487                                                                         \
2488         if (m->code == NULL)                                                \
2489                 if (!jit_compile(m))                                            \
2490                         return 0;                                                   \
2491                                                                         \
2492         THREAD_NATIVEWORLD_EXIT;                                            \
2493         DMARKER;                                                            \
2494                                                                         \
2495         array = argument_vmarray_from_valist(m, o, ap);                     \
2496         value = vm_call##name##_array(m, array);                            \
2497                                                                         \
2498         DRELEASE;                                                           \
2499         THREAD_NATIVEWORLD_ENTER;                                           \
2500                                                                         \
2501         return value;                                                       \
2502 }
2503
2504 VM_CALL_METHOD_VALIST(,        java_handle_t *)
2505 VM_CALL_METHOD_VALIST(_int,    int32_t)
2506 VM_CALL_METHOD_VALIST(_long,   int64_t)
2507 VM_CALL_METHOD_VALIST(_float,  float)
2508 VM_CALL_METHOD_VALIST(_double, double)
2509
2510
2511 /* vm_call_method_jvalue *******************************************************
2512
2513    Calls a Java method with a variable number of arguments, passed via
2514    a jvalue array.
2515
2516 *******************************************************************************/
2517
2518 #define VM_CALL_METHOD_JVALUE(name, type)                               \
2519 type vm_call_method##name##_jvalue(methodinfo *m, java_handle_t *o,     \
2520                                                            const jvalue *args)                  \
2521 {                                                                       \
2522         uint64_t *array;                                                    \
2523         type      value;                                                    \
2524         int32_t   dumpmarker;                                               \
2525                                                                         \
2526         if (m->code == NULL)                                                \
2527                 if (!jit_compile(m))                                            \
2528                         return 0;                                                   \
2529                                                                         \
2530         THREAD_NATIVEWORLD_EXIT;                                            \
2531         DMARKER;                                                            \
2532                                                                         \
2533         array = argument_vmarray_from_jvalue(m, o, args);                   \
2534         value = vm_call##name##_array(m, array);                            \
2535                                                                         \
2536         DRELEASE;                                                           \
2537         THREAD_NATIVEWORLD_ENTER;                                           \
2538                                                                         \
2539         return value;                                                       \
2540 }
2541
2542 VM_CALL_METHOD_JVALUE(,        java_handle_t *)
2543 VM_CALL_METHOD_JVALUE(_int,    int32_t)
2544 VM_CALL_METHOD_JVALUE(_long,   int64_t)
2545 VM_CALL_METHOD_JVALUE(_float,  float)
2546 VM_CALL_METHOD_JVALUE(_double, double)
2547
2548
2549 /* vm_call_method_objectarray **************************************************
2550
2551    Calls a Java method with a variable number if arguments, passed via
2552    an objectarray of boxed values. Returns a boxed value.
2553
2554 *******************************************************************************/
2555
2556 java_handle_t *vm_call_method_objectarray(methodinfo *m, java_handle_t *o,
2557                                                                                   java_handle_objectarray_t *params)
2558 {
2559         uint64_t      *array;
2560         java_handle_t *xptr;
2561         java_handle_t *ro;
2562         imm_union      value;
2563         int32_t        dumpmarker;
2564
2565         /* Prevent compiler warnings. */
2566
2567         ro = NULL;
2568
2569         /* compile methods which are not yet compiled */
2570
2571         if (m->code == NULL)
2572                 if (!jit_compile(m))
2573                         return NULL;
2574
2575         /* leave the nativeworld */
2576
2577         THREAD_NATIVEWORLD_EXIT;
2578
2579         /* mark start of dump memory area */
2580
2581         DMARKER;
2582
2583         /* Fill the argument array from a object-array. */
2584
2585         array = argument_vmarray_from_objectarray(m, o, params);
2586
2587         if (array == NULL) {
2588                 /* release dump area */
2589
2590                 DRELEASE;
2591
2592                 /* enter the nativeworld again */
2593
2594                 THREAD_NATIVEWORLD_ENTER;
2595
2596                 exceptions_throw_illegalargumentexception();
2597
2598                 return NULL;
2599         }
2600
2601         switch (m->parseddesc->returntype.decltype) {
2602         case PRIMITIVETYPE_VOID:
2603                 value.a = vm_call_array(m, array);
2604                 break;
2605
2606         case PRIMITIVETYPE_BOOLEAN:
2607         case PRIMITIVETYPE_BYTE:
2608         case PRIMITIVETYPE_CHAR:
2609         case PRIMITIVETYPE_SHORT:
2610         case PRIMITIVETYPE_INT:
2611                 value.i = vm_call_int_array(m, array);
2612                 break;
2613
2614         case PRIMITIVETYPE_LONG:
2615                 value.l = vm_call_long_array(m, array);
2616                 break;
2617
2618         case PRIMITIVETYPE_FLOAT:
2619                 value.f = vm_call_float_array(m, array);
2620                 break;
2621
2622         case PRIMITIVETYPE_DOUBLE:
2623                 value.d = vm_call_double_array(m, array);
2624                 break;
2625
2626         case TYPE_ADR:
2627                 ro = vm_call_array(m, array);
2628                 break;
2629
2630         default:
2631                 vm_abort("vm_call_method_objectarray: invalid return type %d", m->parseddesc->returntype.decltype);
2632         }
2633
2634         /* release dump area */
2635
2636         DRELEASE;
2637
2638         /* enter the nativeworld again */
2639
2640         THREAD_NATIVEWORLD_ENTER;
2641
2642         /* box the return value if necesarry */
2643
2644         if (m->parseddesc->returntype.decltype != TYPE_ADR)
2645                 ro = Primitive::box(m->parseddesc->returntype.decltype, value);
2646
2647         /* check for an exception */
2648
2649         xptr = exceptions_get_exception();
2650
2651         if (xptr != NULL) {
2652                 /* clear exception pointer, we are calling JIT code again */
2653
2654                 exceptions_clear_exception();
2655
2656                 exceptions_throw_invocationtargetexception(xptr);
2657         }
2658
2659         return ro;
2660 }
2661
2662
2663 /* Legacy C interface *********************************************************/
2664
2665 extern "C" {
2666
2667 JavaVM* VM_get_javavm()      { return vm->get_javavm(); }
2668 JNIEnv* VM_get_jnienv()      { return vm->get_jnienv(); }
2669 bool    VM_is_initializing() { return vm->is_initializing(); }
2670 bool    VM_is_created()      { return vm->is_created(); }
2671 int64_t VM_get_starttime()   { return vm->get_starttime(); }
2672
2673 }
2674
2675
2676 /*
2677  * These are local overrides for various environment variables in Emacs.
2678  * Please do not remove this and leave it at the end of the file, where
2679  * Emacs will automagically detect them.
2680  * ---------------------------------------------------------------------
2681  * Local variables:
2682  * mode: c++
2683  * indent-tabs-mode: t
2684  * c-basic-offset: 4
2685  * tab-width: 4
2686  * End:
2687  * vim:noexpandtab:sw=4:ts=4:
2688  */