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