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