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