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