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