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