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