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