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