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