* Merged with default branch at rev bac772081960.
[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/primitive.h"
71 #include "vm/properties.h"
72 #include "vm/signallocal.h"
73 #include "vm/stringlocal.h"
74 #include "vm/vm.h"
75
76 #include "vm/jit/jit.h"
77 #include "vm/jit/md.h"
78 #include "vm/jit/asmpart.h"
79
80 #if defined(ENABLE_PROFILING)
81 # include "vm/jit/optimizing/profile.h"
82 #endif
83
84 #include "vm/jit/optimizing/recompile.h"
85
86 #include "vmcore/classcache.h"
87 #include "vmcore/options.h"
88 #include "vmcore/statistics.h"
89 #include "vmcore/suck.h"
90
91 #if defined(ENABLE_JVMTI)
92 # include "native/jvmti/cacaodbg.h"
93 #endif
94
95 #if defined(ENABLE_VMLOG)
96 #include <vmlog_cacao.h>
97 #endif
98
99
100 /* Invocation API variables ***************************************************/
101
102 _Jv_JavaVM *_Jv_jvm;                    /* denotes a Java VM                  */
103 _Jv_JNIEnv *_Jv_env;                    /* pointer to native method interface */
104
105
106 /* global variables ***********************************************************/
107
108 s4 vms = 0;                             /* number of VMs created              */
109
110 bool vm_initializing = false;
111 bool vm_exiting = false;
112
113 char      *mainstring = NULL;
114 classinfo *mainclass = NULL;
115
116 #if defined(ENABLE_INTRP)
117 u1 *intrp_main_stack = NULL;
118 #endif
119
120
121 /* define heap sizes **********************************************************/
122
123 #define HEAP_MAXSIZE      128 * 1024 * 1024 /* default 128MB                  */
124 #define HEAP_STARTSIZE      2 * 1024 * 1024 /* default 2MB                    */
125 #define STACK_SIZE                64 * 1024 /* default 64kB                   */
126
127
128 /* define command line options ************************************************/
129
130 enum {
131         OPT_FOO,
132
133         /* Java options */
134
135         OPT_JAR,
136
137         OPT_D32,
138         OPT_D64,
139
140         OPT_CLASSPATH,
141         OPT_D,
142
143         OPT_VERBOSE,
144
145         OPT_VERSION,
146         OPT_SHOWVERSION,
147         OPT_FULLVERSION,
148
149         OPT_HELP,
150         OPT_X,
151         OPT_XX,
152
153         OPT_EA,
154         OPT_DA,
155
156         OPT_ESA,
157         OPT_DSA,
158
159         /* Java non-standard options */
160
161         OPT_JIT,
162         OPT_INTRP,
163
164         OPT_BOOTCLASSPATH,
165         OPT_BOOTCLASSPATH_A,
166         OPT_BOOTCLASSPATH_P,
167
168         OPT_BOOTCLASSPATH_C,
169
170 #if defined(ENABLE_PROFILING)
171         OPT_PROF,
172         OPT_PROF_OPTION,
173 #endif
174
175         OPT_MS,
176         OPT_MX,
177
178         /* CACAO options */
179
180         OPT_VERBOSE1,
181         OPT_NOIEEE,
182
183 #if defined(ENABLE_STATISTICS)
184         OPT_TIME,
185         OPT_STAT,
186 #endif
187
188         OPT_LOG,
189         OPT_CHECK,
190         OPT_LOAD,
191         OPT_SHOW,
192         OPT_DEBUGCOLOR,
193
194 #if !defined(NDEBUG)
195         OPT_ALL,
196         OPT_METHOD,
197         OPT_SIGNATURE,
198 #endif
199
200 #if defined(ENABLE_VERIFIER)
201         OPT_NOVERIFY,
202 #if defined(TYPECHECK_VERBOSE)
203         OPT_VERBOSETC,
204 #endif
205 #endif /* defined(ENABLE_VERIFIER) */
206
207         /* optimization options */
208
209 #if defined(ENABLE_LOOP)
210         OPT_OLOOP,
211 #endif
212         
213 #if defined(ENABLE_IFCONV)
214         OPT_IFCONV,
215 #endif
216
217 #if defined(ENABLE_LSRA) || defined(ENABLE_SSA)
218         OPT_LSRA,
219 #endif
220
221 #if defined(ENABLE_INLINING)
222         OPT_INLINING,
223 #if !defined(NDEBUG)
224         OPT_INLINE_LOG,
225 #endif
226 #if defined(ENABLE_INLINING_DEBUG)
227         OPT_INLINE_DEBUG_ALL,
228         OPT_INLINE_DEBUG_END,
229         OPT_INLINE_DEBUG_MIN,
230         OPT_INLINE_DEBUG_MAX,
231 #endif /* defined(ENABLE_INLINING_DEBUG) */
232 #endif /* defined(ENABLE_INLINING) */
233
234 #if defined(ENABLE_INTRP)
235         /* interpreter options */
236
237         OPT_NO_DYNAMIC,
238         OPT_NO_REPLICATION,
239         OPT_NO_QUICKSUPER,
240         OPT_STATIC_SUPERS,
241         OPT_TRACE,
242 #endif
243
244         OPT_SS,
245
246 #ifdef ENABLE_JVMTI
247         OPT_DEBUG,
248         OPT_XRUNJDWP,
249         OPT_NOAGENT,
250         OPT_AGENTLIB,
251         OPT_AGENTPATH,
252 #endif
253
254 #if defined(ENABLE_DEBUG_FILTER)
255         OPT_FILTER_VERBOSECALL_INCLUDE,
256         OPT_FILTER_VERBOSECALL_EXCLUDE,
257         OPT_FILTER_SHOW_METHOD,
258 #endif
259
260         DUMMY
261 };
262
263
264 opt_struct opts[] = {
265         { "foo",               false, OPT_FOO },
266
267         /* Java options */
268
269         { "jar",               false, OPT_JAR },
270
271         { "d32",               false, OPT_D32 },
272         { "d64",               false, OPT_D64 },
273         { "client",            false, OPT_IGNORE },
274         { "server",            false, OPT_IGNORE },
275         { "jvm",               false, OPT_IGNORE },
276         { "hotspot",           false, OPT_IGNORE },
277
278         { "classpath",         true,  OPT_CLASSPATH },
279         { "cp",                true,  OPT_CLASSPATH },
280         { "D",                 true,  OPT_D },
281         { "version",           false, OPT_VERSION },
282         { "showversion",       false, OPT_SHOWVERSION },
283         { "fullversion",       false, OPT_FULLVERSION },
284         { "help",              false, OPT_HELP },
285         { "?",                 false, OPT_HELP },
286         { "X",                 false, OPT_X },
287         { "XX:",               true,  OPT_XX },
288         { "XX",                false, 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         puts("      (e)xceptionstubs       disassembled exception stubs (only with -sa)");
551 #endif
552         puts("      (d)atasegment          data segment listing");
553
554 #if defined(ENABLE_INLINING)
555         puts("    -i                       activate inlining");
556 #if !defined(NDEBUG)
557         puts("    -il                      log inlining");
558 #endif
559 #if defined(ENABLE_INLINING_DEBUG)
560         puts("    -ia                      use inlining for all methods");
561         puts("    -ii <size>               set minimum size for inlined result");
562         puts("    -im <size>               set maximum size for inlined result");
563         puts("    -ie <number>             stop inlining after the given number of roots");
564 #endif /* defined(ENABLE_INLINING_DEBUG) */
565 #endif /* defined(ENABLE_INLINING) */
566
567 #if defined(ENABLE_IFCONV)
568         puts("    -ifconv                  use if-conversion");
569 #endif
570 #if defined(ENABLE_LSRA)
571         puts("    -lsra                    use linear scan register allocation");
572 #endif
573 #if defined(ENABLE_SSA)
574         puts("    -lsra                    use linear scan register allocation (with SSA)");
575 #endif
576 #if defined(ENABLE_DEBUG_FILTER)
577         puts("    -XXfi <regex>            begin of dynamic scope for verbosecall filter");
578         puts("    -XXfx <regex>            end of dynamic scope for verbosecall filter");
579         puts("    -XXfm <regex>            filter for show options");
580 #endif
581         /* exit with error code */
582
583         exit(1);
584 }
585 #endif
586
587
588 /* version *********************************************************************
589
590    Only prints cacao version information.
591
592 *******************************************************************************/
593
594 static void version(bool opt_exit)
595 {
596         puts("java version \""JAVA_VERSION"\"");
597         puts("CACAO version "VERSION"");
598
599         puts("Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,");
600         puts("C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,");
601         puts("E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,");
602         puts("J. Wenninger, Institut f. Computersprachen - TU Wien\n");
603
604         puts("This program is free software; you can redistribute it and/or");
605         puts("modify it under the terms of the GNU General Public License as");
606         puts("published by the Free Software Foundation; either version 2, or (at");
607         puts("your option) any later version.\n");
608
609         puts("This program is distributed in the hope that it will be useful, but");
610         puts("WITHOUT ANY WARRANTY; without even the implied warranty of");
611         puts("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU");
612         puts("General Public License for more details.");
613
614         /* exit normally, if requested */
615
616         if (opt_exit)
617                 exit(0);
618 }
619
620
621 /* fullversion *****************************************************************
622
623    Prints a Sun compatible version information (required e.g. by
624    jpackage, www.jpackage.org).
625
626 *******************************************************************************/
627
628 static void fullversion(void)
629 {
630         puts("java full version \"cacao-"JAVA_VERSION"\"");
631
632         /* exit normally */
633
634         exit(0);
635 }
636
637
638 void vm_printconfig(void)
639 {
640         puts("Configure/Build options:\n");
641         puts("  ./configure: "VERSION_CONFIGURE_ARGS"");
642 #if defined(__VERSION__)
643         puts("  CC         : "VERSION_CC" ("__VERSION__")");
644 #else
645         puts("  CC         : "VERSION_CC"");
646 #endif
647         puts("  CFLAGS     : "VERSION_CFLAGS"\n");
648
649         puts("Default variables:\n");
650         printf("  maximum heap size              : %d\n", HEAP_MAXSIZE);
651         printf("  initial heap size              : %d\n", HEAP_STARTSIZE);
652         printf("  stack size                     : %d\n", STACK_SIZE);
653
654 #if defined(WITH_JRE_LAYOUT)
655         /* When we're building with JRE-layout, the default paths are the
656            same as the runtime paths. */
657 #else
658 # if defined(WITH_CLASSPATH_GNU)
659         puts("  gnu.classpath.boot.library.path: "CLASSPATH_LIBDIR);
660         puts("  java.boot.class.path           : "CACAO_VM_ZIP":"CLASSPATH_CLASSES"");
661 # elif defined(WITH_CLASSPATH_SUN)
662         puts("  sun.boot.library.path          : "CLASSPATH_LIBDIR);
663         puts("  java.boot.class.path           : "CLASSPATH_CLASSES);
664 # endif
665 #endif
666
667         puts("");
668
669         puts("Runtime variables:\n");
670         printf("  maximum heap size              : %d\n", opt_heapmaxsize);
671         printf("  initial heap size              : %d\n", opt_heapstartsize);
672         printf("  stack size                     : %d\n", opt_stacksize);
673
674 #if defined(WITH_CLASSPATH_GNU)
675         printf("  gnu.classpath.boot.library.path: %s\n", properties_get("gnu.classpath.boot.library.path"));
676 #elif defined(WITH_CLASSPATH_SUN)
677         printf("  sun.boot.library.path          : %s\n", properties_get("sun.boot.library.path"));
678 #endif
679
680         printf("  java.boot.class.path           : %s\n", properties_get("java.boot.class.path"));
681         printf("  java.class.path                : %s\n", properties_get("java.class.path"));
682 }
683
684
685 /* forward declarations *******************************************************/
686
687 static char *vm_get_mainclass_from_jar(char *mainstring);
688 #if !defined(NDEBUG)
689 static void  vm_compile_all(void);
690 static void  vm_compile_method(void);
691 #endif
692
693
694 /* vm_createjvm ****************************************************************
695
696    Implementation for JNI_CreateJavaVM.
697
698 *******************************************************************************/
699
700 bool vm_createjvm(JavaVM **p_vm, void **p_env, void *vm_args)
701 {
702         JavaVMInitArgs *_vm_args;
703         _Jv_JNIEnv     *env;
704         _Jv_JavaVM     *vm;
705
706         /* get the arguments for the new JVM */
707
708         _vm_args = (JavaVMInitArgs *) vm_args;
709
710         /* get the VM and Env tables (must be set before vm_create) */
711
712         env = NEW(_Jv_JNIEnv);
713
714 #if defined(ENABLE_JNI)
715         env->env = &_Jv_JNINativeInterface;
716 #endif
717
718         /* XXX Set the global variable.  Maybe we should do that differently. */
719
720         _Jv_env = env;
721
722         /* create and fill a JavaVM structure */
723
724         vm = NEW(_Jv_JavaVM);
725
726 #if defined(ENABLE_JNI)
727         vm->functions = &_Jv_JNIInvokeInterface;
728 #endif
729
730         /* XXX Set the global variable.  Maybe we should do that differently. */
731         /* XXX JVMTI Agents needs a JavaVM  */
732
733         _Jv_jvm = vm;
734
735         /* actually create the JVM */
736
737         if (!vm_create(_vm_args))
738                 goto error;
739
740 #if defined(ENABLE_JNI)
741         /* setup the local ref table (must be created after vm_create) */
742
743         /* XXX this one will never get freed for the main thread;
744            call localref_table_destroy() if you want to do it! */
745
746         if (!localref_table_init())
747                 goto error;
748 #endif
749
750         /* now return the values */
751
752         *p_vm  = (JavaVM *) vm;
753         *p_env = (void *) env;
754
755         return true;
756
757  error:
758         /* release allocated memory */
759
760         FREE(env, _Jv_JNIEnv);
761         FREE(vm, _Jv_JavaVM);
762
763         return false;
764 }
765
766
767 /* vm_create *******************************************************************
768
769    Creates a JVM.  Called by vm_createjvm.
770
771 *******************************************************************************/
772
773 bool vm_create(JavaVMInitArgs *vm_args)
774 {
775         int   len;
776         char *p;
777         char *boot_class_path;
778         char *class_path;
779         int   opt;
780         int   i, j;
781         bool  opt_version;
782         bool  opt_exit;
783
784 #if defined(ENABLE_JVMTI)
785         lt_dlhandle  handle;
786         char *libname, *agentarg;
787         bool jdwp,agentbypath;
788         jdwp = agentbypath = false;
789 #endif
790
791 #if defined(ENABLE_VMLOG)
792         vmlog_cacao_init(vm_args);
793 #endif
794
795         /* check the JNI version requested */
796
797         switch (vm_args->version) {
798         case JNI_VERSION_1_1:
799                 break;
800         case JNI_VERSION_1_2:
801         case JNI_VERSION_1_4:
802                 break;
803         default:
804                 return false;
805         }
806
807         /* we only support 1 JVM instance */
808
809         if (vms > 0)
810                 return false;
811
812         if (atexit(vm_exit_handler))
813                 vm_abort("atexit failed: %s\n", strerror(errno));
814
815         if (opt_verbose)
816                 log_text("CACAO started -------------------------------------------------------");
817
818         /* We need to check if the actual size of a java.lang.Class object
819            is smaller or equal than the assumption made in
820            src/vmcore/class.h. */
821
822         if (sizeof(java_lang_Class) > sizeof(dummy_java_lang_Class))
823                 vm_abort("vm_create: java_lang_Class structure is bigger than classinfo.object (%d > %d)", sizeof(java_lang_Class), sizeof(dummy_java_lang_Class));
824
825         /* set the VM starttime */
826
827         _Jv_jvm->starttime = builtin_currenttimemillis();
828
829         /* interpret the options **************************************************/
830
831         opt_version       = false;
832         opt_exit          = false;
833
834         opt_noieee        = false;
835
836         opt_heapmaxsize   = HEAP_MAXSIZE;
837         opt_heapstartsize = HEAP_STARTSIZE;
838         opt_stacksize     = STACK_SIZE;
839
840
841 #if defined(ENABLE_JVMTI)
842         /* initialize JVMTI related  **********************************************/
843         jvmti = false;
844 #endif
845
846         /* Initialize and fill properties before command-line handling. */
847
848         properties_init();
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
1201                                 case 'e':
1202                                         opt_showexceptionstubs = true;
1203                                         break;
1204 #endif
1205
1206                                 case 'd':
1207                                         opt_showddatasegment = true;
1208                                         break;
1209
1210                                 default:
1211                                         usage();
1212                                 }
1213                         }
1214                         break;
1215                         
1216 #if defined(ENABLE_LOOP)
1217                 case OPT_OLOOP:
1218                         opt_loops = true;
1219                         break;
1220 #endif
1221
1222 #if defined(ENABLE_INLINING)
1223 #if defined(ENABLE_INLINING_DEBUG)
1224                 case OPT_INLINE_DEBUG_ALL:
1225                         opt_inline_debug_all = true;
1226                         break;
1227                 case OPT_INLINE_DEBUG_END:
1228                         opt_inline_debug_end_counter = atoi(opt_arg);
1229                         break;
1230                 case OPT_INLINE_DEBUG_MIN:
1231                         opt_inline_debug_min_size = atoi(opt_arg);
1232                         break;
1233                 case OPT_INLINE_DEBUG_MAX:
1234                         opt_inline_debug_max_size = atoi(opt_arg);
1235                         break;
1236 #endif /* defined(ENABLE_INLINING_DEBUG) */
1237 #if !defined(NDEBUG)
1238                 case OPT_INLINE_LOG:
1239                         opt_inline_debug_log = true;
1240                         break;
1241 #endif /* !defined(NDEBUG) */
1242
1243                 case OPT_INLINING:
1244                         opt_inlining = true;
1245                         break;
1246 #endif /* defined(ENABLE_INLINING) */
1247
1248 #if defined(ENABLE_IFCONV)
1249                 case OPT_IFCONV:
1250                         opt_ifconv = true;
1251                         break;
1252 #endif
1253
1254 #if defined(ENABLE_LSRA) || defined(ENABLE_SSA)
1255                 case OPT_LSRA:
1256                         opt_lsra = true;
1257                         break;
1258 #endif
1259
1260                 case OPT_HELP:
1261                         usage();
1262                         break;
1263
1264                 case OPT_X:
1265                         Xusage();
1266                         break;
1267
1268                 case OPT_XX:
1269                         options_xx(opt_arg);
1270                         break;
1271
1272                 case OPT_EA:
1273                         /* currently ignored */
1274                         break;
1275
1276                 case OPT_DA:
1277                         /* currently ignored */
1278                         break;
1279
1280                 case OPT_ESA:
1281                         _Jv_jvm->Java_java_lang_VMClassLoader_defaultAssertionStatus = true;
1282                         break;
1283
1284                 case OPT_DSA:
1285                         _Jv_jvm->Java_java_lang_VMClassLoader_defaultAssertionStatus = false;
1286                         break;
1287
1288 #if defined(ENABLE_PROFILING)
1289                 case OPT_PROF_OPTION:
1290                         /* use <= to get the last \0 too */
1291
1292                         for (i = 0, j = 0; i <= strlen(opt_arg); i++) {
1293                                 if (opt_arg[i] == ',')
1294                                         opt_arg[i] = '\0';
1295
1296                                 if (opt_arg[i] == '\0') {
1297                                         if (strcmp("bb", opt_arg + j) == 0)
1298                                                 opt_prof_bb = true;
1299
1300                                         else {
1301                                                 printf("Unknown option: -Xprof:%s\n", opt_arg + j);
1302                                                 usage();
1303                                         }
1304
1305                                         /* set k to next char */
1306
1307                                         j = i + 1;
1308                                 }
1309                         }
1310                         /* fall through */
1311
1312                 case OPT_PROF:
1313                         opt_prof = true;
1314                         break;
1315 #endif
1316
1317                 case OPT_JIT:
1318 #if defined(ENABLE_JIT)
1319                         opt_jit = true;
1320 #else
1321                         printf("-Xjit option not enabled.\n");
1322                         exit(1);
1323 #endif
1324                         break;
1325
1326                 case OPT_INTRP:
1327 #if defined(ENABLE_INTRP)
1328                         opt_intrp = true;
1329 #else
1330                         printf("-Xint option not enabled.\n");
1331                         exit(1);
1332 #endif
1333                         break;
1334
1335 #if defined(ENABLE_INTRP)
1336                 case OPT_STATIC_SUPERS:
1337                         opt_static_supers = atoi(opt_arg);
1338                         break;
1339
1340                 case OPT_NO_DYNAMIC:
1341                         opt_no_dynamic = true;
1342                         break;
1343
1344                 case OPT_NO_REPLICATION:
1345                         opt_no_replication = true;
1346                         break;
1347
1348                 case OPT_NO_QUICKSUPER:
1349                         opt_no_quicksuper = true;
1350                         break;
1351
1352                 case OPT_TRACE:
1353                         vm_debug = true;
1354                         break;
1355 #endif
1356
1357 #if defined(ENABLE_DEBUG_FILTER)
1358                 case OPT_FILTER_VERBOSECALL_INCLUDE:
1359                         opt_filter_verbosecall_include = opt_arg;
1360                         break;
1361
1362                 case OPT_FILTER_VERBOSECALL_EXCLUDE:
1363                         opt_filter_verbosecall_exclude = opt_arg;
1364                         break;
1365
1366                 case OPT_FILTER_SHOW_METHOD:
1367                         opt_filter_show_method = opt_arg;
1368                         break;
1369
1370 #endif
1371                 default:
1372                         printf("Unknown option: %s\n",
1373                                    vm_args->options[opt_index].optionString);
1374                         usage();
1375                 }
1376         }
1377
1378         /* get the main class *****************************************************/
1379
1380         if (opt_index < vm_args->nOptions) {
1381                 mainstring = vm_args->options[opt_index++].optionString;
1382
1383                 /* Put the jar file into the classpath (if any). */
1384
1385                 if (opt_jar == true) {
1386                         /* free old classpath */
1387
1388 /*                      MFREE(_Jv_classpath, char, strlen(_Jv_classpath)); */
1389
1390                         /* put jarfile into classpath */
1391
1392                         p = MNEW(char, strlen(mainstring) + strlen("0"));
1393
1394                         strcpy(p, mainstring);
1395
1396 #if defined(ENABLE_JAVASE)
1397                         properties_add("java.class.path", p);
1398 #endif
1399                 }
1400                 else {
1401                         /* replace .'s with /'s in classname */
1402
1403                         for (i = strlen(mainstring) - 1; i >= 0; i--)
1404                                 if (mainstring[i] == '.')
1405                                         mainstring[i] = '/';
1406                 }
1407         }
1408
1409 #if defined(ENABLE_JVMTI)
1410         if (jvmti) {
1411                 jvmti_set_phase(JVMTI_PHASE_ONLOAD);
1412                 jvmti_agentload(agentarg, agentbypath, &handle, &libname);
1413
1414                 if (jdwp)
1415                         MFREE(agentarg, char, strlen(agentarg));
1416
1417                 jvmti_set_phase(JVMTI_PHASE_PRIMORDIAL);
1418         }
1419 #endif
1420
1421         /* initialize this JVM ****************************************************/
1422
1423         vm_initializing = true;
1424
1425         /* initialize the garbage collector */
1426
1427         gc_init(opt_heapmaxsize, opt_heapstartsize);
1428
1429 #if defined(ENABLE_THREADS)
1430         /* AFTER: gc_init (directly after, as this initializes the
1431            stopworldlock lock */
1432
1433         threads_preinit();
1434 #endif
1435
1436         /* install architecture dependent signal handlers */
1437
1438         if (!signal_init())
1439                 vm_abort("vm_create: signal_init failed");
1440
1441 #if defined(ENABLE_INTRP)
1442         /* Allocate main thread stack on the Java heap. */
1443
1444         if (opt_intrp) {
1445                 intrp_main_stack = GCMNEW(u1, opt_stacksize);
1446                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1447         }
1448 #endif
1449
1450         /* AFTER: threads_preinit */
1451
1452         if (!string_init())
1453                 vm_abort("vm_create: string_init failed");
1454
1455         /* AFTER: threads_preinit */
1456
1457         if (!utf8_init())
1458                 vm_abort("vm_create: utf8_init failed");
1459
1460         /* AFTER: thread_preinit */
1461
1462         if (!suck_init())
1463                 vm_abort("vm_create: suck_init failed");
1464
1465         suck_add_from_property("java.endorsed.dirs");
1466
1467         /* Now we have all options handled and we can print the version
1468            information.
1469
1470            AFTER: suck_add_from_property("java.endorsed.dirs"); */
1471
1472         if (opt_version)
1473                 version(opt_exit);
1474
1475         /* AFTER: utf8_init */
1476
1477         boot_class_path = properties_get("sun.boot.class.path");
1478         suck_add(boot_class_path);
1479
1480         /* initialize the classcache hashtable stuff: lock, hashtable
1481            (must be done _after_ threads_preinit) */
1482
1483         if (!classcache_init())
1484                 vm_abort("vm_create: classcache_init failed");
1485
1486         /* initialize the memory subsystem (must be done _after_
1487            threads_preinit) */
1488
1489         if (!memory_init())
1490                 vm_abort("vm_create: memory_init failed");
1491
1492         /* initialize the finalizer stuff (must be done _after_
1493            threads_preinit) */
1494
1495         if (!finalizer_init())
1496                 vm_abort("vm_create: finalizer_init failed");
1497
1498         /* initialize the codegen subsystems */
1499
1500         codegen_init();
1501
1502         /* initializes jit compiler */
1503
1504         jit_init();
1505
1506         /* machine dependent initialization */
1507
1508 #if defined(ENABLE_JIT)
1509 # if defined(ENABLE_INTRP)
1510         if (opt_intrp)
1511                 intrp_md_init();
1512         else
1513 # endif
1514                 md_init();
1515 #else
1516         intrp_md_init();
1517 #endif
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         /* everything's ok */
1643
1644         return true;
1645 }
1646
1647
1648 /* vm_run **********************************************************************
1649
1650    Runs the main-method of the passed class.
1651
1652 *******************************************************************************/
1653
1654 void vm_run(JavaVM *vm, JavaVMInitArgs *vm_args)
1655 {
1656         utf                       *mainutf;
1657         classinfo                 *mainclass;
1658         java_handle_t             *e;
1659         methodinfo                *m;
1660         java_handle_objectarray_t *oa; 
1661         s4                         oalength;
1662         utf                       *u;
1663         java_handle_t             *s;
1664         s4                         status;
1665         s4                         i;
1666
1667 #if !defined(NDEBUG)
1668         if (compileall) {
1669                 vm_compile_all();
1670                 return;
1671         }
1672
1673         if (opt_method != NULL) {
1674                 vm_compile_method();
1675                 return;
1676         }
1677 #endif /* !defined(NDEBUG) */
1678
1679         /* should we run the main-method? */
1680
1681         if (mainstring == NULL)
1682                 usage();
1683
1684         /* set return value to OK */
1685
1686         status = 0;
1687
1688         if (opt_jar == true) {
1689                 /* open jar file with java.util.jar.JarFile */
1690
1691                 mainstring = vm_get_mainclass_from_jar(mainstring);
1692
1693                 if (mainstring == NULL)
1694                         vm_exit(1);
1695         }
1696
1697         /* load the main class */
1698
1699         mainutf = utf_new_char(mainstring);
1700
1701 #if defined(ENABLE_JAVAME_CLDC1_1)
1702         mainclass = load_class_bootstrap(mainutf);
1703 #else
1704         mainclass = load_class_from_sysloader(mainutf);
1705 #endif
1706
1707         /* error loading class */
1708
1709         e = exceptions_get_and_clear_exception();
1710
1711         if ((e != NULL) || (mainclass == NULL)) {
1712                 exceptions_throw_noclassdeffounderror_cause(e);
1713                 exceptions_print_stacktrace(); 
1714                 vm_exit(1);
1715         }
1716
1717         if (!link_class(mainclass)) {
1718                 exceptions_print_stacktrace();
1719                 vm_exit(1);
1720         }
1721                         
1722         /* find the `main' method of the main class */
1723
1724         m = class_resolveclassmethod(mainclass,
1725                                                                  utf_new_char("main"), 
1726                                                                  utf_new_char("([Ljava/lang/String;)V"),
1727                                                                  class_java_lang_Object,
1728                                                                  false);
1729
1730         if (exceptions_get_exception()) {
1731                 exceptions_print_stacktrace();
1732                 vm_exit(1);
1733         }
1734
1735         /* there is no main method or it isn't static */
1736
1737         if ((m == NULL) || !(m->flags & ACC_STATIC)) {
1738                 exceptions_clear_exception();
1739                 exceptions_throw_nosuchmethoderror(mainclass,
1740                                                                                    utf_new_char("main"), 
1741                                                                                    utf_new_char("([Ljava/lang/String;)V"));
1742
1743                 exceptions_print_stacktrace();
1744                 vm_exit(1);
1745         }
1746
1747         /* build argument array */
1748
1749         oalength = vm_args->nOptions - opt_index;
1750
1751         oa = builtin_anewarray(oalength, class_java_lang_String);
1752
1753         for (i = 0; i < oalength; i++) {
1754                 u = utf_new_char(vm_args->options[opt_index + i].optionString);
1755                 s = javastring_new(u);
1756
1757                 LLNI_objectarray_element_set(oa, i, s);
1758         }
1759
1760 #ifdef TYPEINFO_DEBUG_TEST
1761         /* test the typeinfo system */
1762         typeinfo_test();
1763 #endif
1764         /*class_showmethods(currentThread->group->header.vftbl->class); */
1765
1766 #if defined(ENABLE_JVMTI)
1767         jvmti_set_phase(JVMTI_PHASE_LIVE);
1768 #endif
1769
1770         /* set ThreadMXBean variables */
1771
1772         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1773         _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1774
1775         if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1776                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1777                 _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1778                         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1779
1780         /* start the main thread */
1781
1782         (void) vm_call_method(m, NULL, oa);
1783
1784         /* exception occurred? */
1785
1786         if (exceptions_get_exception()) {
1787                 exceptions_print_stacktrace();
1788                 status = 1;
1789         }
1790
1791         /* unload the JavaVM */
1792
1793         (void) vm_destroy(vm);
1794
1795         /* and exit */
1796
1797         vm_exit(status);
1798 }
1799
1800
1801 /* vm_destroy ******************************************************************
1802
1803    Unloads a Java VM and reclaims its resources.
1804
1805 *******************************************************************************/
1806
1807 s4 vm_destroy(JavaVM *vm)
1808 {
1809 #if defined(ENABLE_THREADS)
1810         threads_join_all_threads();
1811 #endif
1812
1813         /* everything's ok */
1814
1815         return 0;
1816 }
1817
1818
1819 /* vm_exit *********************************************************************
1820
1821    Calls java.lang.System.exit(I)V to exit the JavaVM correctly.
1822
1823 *******************************************************************************/
1824
1825 void vm_exit(s4 status)
1826 {
1827         methodinfo *m;
1828
1829         /* signal that we are exiting */
1830
1831         vm_exiting = true;
1832
1833         assert(class_java_lang_System);
1834         assert(class_java_lang_System->state & CLASS_LOADED);
1835
1836 #if defined(ENABLE_JVMTI)
1837         if (jvmti || (dbgcom!=NULL)) {
1838                 jvmti_set_phase(JVMTI_PHASE_DEAD);
1839                 if (jvmti) jvmti_agentunload();
1840         }
1841 #endif
1842
1843         if (!link_class(class_java_lang_System)) {
1844                 exceptions_print_stacktrace();
1845                 exit(1);
1846         }
1847
1848         /* call java.lang.System.exit(I)V */
1849
1850         m = class_resolveclassmethod(class_java_lang_System,
1851                                                                  utf_new_char("exit"),
1852                                                                  utf_int__void,
1853                                                                  class_java_lang_Object,
1854                                                                  true);
1855         
1856         if (m == NULL) {
1857                 exceptions_print_stacktrace();
1858                 exit(1);
1859         }
1860
1861         /* call the exit function with passed exit status */
1862
1863         (void) vm_call_method(m, NULL, status);
1864
1865         /* If we had an exception, just ignore the exception and exit with
1866            the proper code. */
1867
1868         vm_shutdown(status);
1869 }
1870
1871
1872 /* vm_shutdown *****************************************************************
1873
1874    Terminates the system immediately without freeing memory explicitly
1875    (to be used only for abnormal termination).
1876         
1877 *******************************************************************************/
1878
1879 void vm_shutdown(s4 status)
1880 {
1881         if (opt_verbose 
1882 #if defined(ENABLE_STATISTICS)
1883                 || opt_getcompilingtime || opt_stat
1884 #endif
1885            ) 
1886         {
1887                 log_text("CACAO terminated by shutdown");
1888                 dolog("Exit status: %d\n", (s4) status);
1889
1890         }
1891
1892 #if defined(ENABLE_JVMTI)
1893         /* terminate cacaodbgserver */
1894         if (dbgcom!=NULL) {
1895                 pthread_mutex_lock(&dbgcomlock);
1896                 dbgcom->running=1;
1897                 pthread_mutex_unlock(&dbgcomlock);
1898                 jvmti_cacaodbgserver_quit();
1899         }       
1900 #endif
1901
1902         exit(status);
1903 }
1904
1905
1906 /* vm_exit_handler *************************************************************
1907
1908    The exit_handler function is called upon program termination.
1909
1910    ATTENTION: Don't free system resources here! Some threads may still
1911    be running as this is called from VMRuntime.exit(). The OS does the
1912    cleanup for us.
1913
1914 *******************************************************************************/
1915
1916 void vm_exit_handler(void)
1917 {
1918 #if !defined(NDEBUG)
1919         if (showmethods)
1920                 class_showmethods(mainclass);
1921
1922         if (showconstantpool)
1923                 class_showconstantpool(mainclass);
1924
1925         if (showutf)
1926                 utf_show();
1927
1928 # if defined(ENABLE_PROFILING)
1929         if (opt_prof)
1930                 profile_printstats();
1931 # endif
1932 #endif /* !defined(NDEBUG) */
1933
1934 #if defined(ENABLE_RT_TIMING)
1935         rt_timing_print_time_stats(stderr);
1936 #endif
1937
1938 #if defined(ENABLE_CYCLES_STATS)
1939         builtin_print_cycles_stats(stderr);
1940         stacktrace_print_cycles_stats(stderr);
1941 #endif
1942
1943         if (opt_verbose 
1944 #if defined(ENABLE_STATISTICS)
1945                 || opt_getcompilingtime || opt_stat
1946 #endif
1947            ) 
1948         {
1949                 log_text("CACAO terminated");
1950
1951 #if defined(ENABLE_STATISTICS)
1952                 if (opt_stat) {
1953                         print_stats();
1954 #ifdef TYPECHECK_STATISTICS
1955                         typecheck_print_statistics(get_logfile());
1956 #endif
1957                 }
1958
1959                 if (opt_getcompilingtime)
1960                         print_times();
1961 #endif /* defined(ENABLE_STATISTICS) */
1962         }
1963         /* vm_print_profile(stderr);*/
1964 }
1965
1966
1967 /* vm_abort ********************************************************************
1968
1969    Prints an error message and aborts the VM.
1970
1971 *******************************************************************************/
1972
1973 void vm_abort(const char *text, ...)
1974 {
1975         va_list ap;
1976
1977         /* print the log message */
1978
1979         log_start();
1980
1981         va_start(ap, text);
1982         log_vprint(text, ap);
1983         va_end(ap);
1984
1985         log_finish();
1986
1987         /* now abort the VM */
1988
1989         abort();
1990 }
1991
1992
1993 /* vm_get_mainclass_from_jar ***************************************************
1994
1995    Gets the name of the main class from a JAR's manifest file.
1996
1997 *******************************************************************************/
1998
1999 static char *vm_get_mainclass_from_jar(char *mainstring)
2000 {
2001         classinfo     *c;
2002         java_handle_t *o;
2003         methodinfo    *m;
2004         java_handle_t *s;
2005
2006         c = load_class_from_sysloader(utf_new_char("java/util/jar/JarFile"));
2007
2008         if (c == NULL) {
2009                 exceptions_print_stacktrace();
2010                 return NULL;
2011         }
2012
2013         /* create JarFile object */
2014
2015         o = builtin_new(c);
2016
2017         if (o == NULL) {
2018                 exceptions_print_stacktrace();
2019                 return NULL;
2020         }
2021
2022         m = class_resolveclassmethod(c,
2023                                                                  utf_init, 
2024                                                                  utf_java_lang_String__void,
2025                                                                  class_java_lang_Object,
2026                                                                  true);
2027
2028         if (m == NULL) {
2029                 exceptions_print_stacktrace();
2030                 return NULL;
2031         }
2032
2033         s = javastring_new_from_ascii(mainstring);
2034
2035         (void) vm_call_method(m, o, s);
2036
2037         if (exceptions_get_exception()) {
2038                 exceptions_print_stacktrace();
2039                 return NULL;
2040         }
2041
2042         /* get manifest object */
2043
2044         m = class_resolveclassmethod(c,
2045                                                                  utf_new_char("getManifest"), 
2046                                                                  utf_new_char("()Ljava/util/jar/Manifest;"),
2047                                                                  class_java_lang_Object,
2048                                                                  true);
2049
2050         if (m == NULL) {
2051                 exceptions_print_stacktrace();
2052                 return NULL;
2053         }
2054
2055         o = vm_call_method(m, o);
2056
2057         if (o == NULL) {
2058                 fprintf(stderr, "Could not get manifest from %s (invalid or corrupt jarfile?)\n", mainstring);
2059                 return NULL;
2060         }
2061
2062
2063         /* get Main Attributes */
2064
2065         LLNI_class_get(o, c);
2066
2067         m = class_resolveclassmethod(c,
2068                                                                  utf_new_char("getMainAttributes"), 
2069                                                                  utf_new_char("()Ljava/util/jar/Attributes;"),
2070                                                                  class_java_lang_Object,
2071                                                                  true);
2072
2073         if (m == NULL) {
2074                 exceptions_print_stacktrace();
2075                 return NULL;
2076         }
2077
2078         o = vm_call_method(m, o);
2079
2080         if (o == NULL) {
2081                 fprintf(stderr, "Could not get main attributes from %s (invalid or corrupt jarfile?)\n", mainstring);
2082                 return NULL;
2083         }
2084
2085
2086         /* get property Main-Class */
2087
2088         LLNI_class_get(o, c);
2089
2090         m = class_resolveclassmethod(c,
2091                                                                  utf_new_char("getValue"), 
2092                                                                  utf_new_char("(Ljava/lang/String;)Ljava/lang/String;"),
2093                                                                  class_java_lang_Object,
2094                                                                  true);
2095
2096         if (m == NULL) {
2097                 exceptions_print_stacktrace();
2098                 return NULL;
2099         }
2100
2101         s = javastring_new_from_ascii("Main-Class");
2102
2103         o = vm_call_method(m, o, s);
2104
2105         if (o == NULL) {
2106                 exceptions_print_stacktrace();
2107                 return NULL;
2108         }
2109
2110         return javastring_tochar(o);
2111 }
2112
2113
2114 /* vm_compile_all **************************************************************
2115
2116    Compile all methods found in the bootclasspath.
2117
2118 *******************************************************************************/
2119
2120 #if !defined(NDEBUG)
2121 static void vm_compile_all(void)
2122 {
2123         classinfo              *c;
2124         methodinfo             *m;
2125         u4                      slot;
2126         classcache_name_entry  *nmen;
2127         classcache_class_entry *clsen;
2128         s4                      i;
2129
2130         /* create all classes found in the bootclasspath */
2131         /* XXX currently only works with zip/jar's */
2132
2133         loader_load_all_classes();
2134
2135         /* link all classes */
2136
2137         for (slot = 0; slot < hashtable_classcache.size; slot++) {
2138                 nmen = (classcache_name_entry *) hashtable_classcache.ptr[slot];
2139
2140                 for (; nmen; nmen = nmen->hashlink) {
2141                         /* iterate over all class entries */
2142
2143                         for (clsen = nmen->classes; clsen; clsen = clsen->next) {
2144                                 c = clsen->classobj;
2145
2146                                 if (c == NULL)
2147                                         continue;
2148
2149                                 if (!(c->state & CLASS_LINKED)) {
2150                                         if (!link_class(c)) {
2151                                                 fprintf(stderr, "Error linking: ");
2152                                                 utf_fprint_printable_ascii_classname(stderr, c->name);
2153                                                 fprintf(stderr, "\n");
2154
2155                                                 /* print out exception and cause */
2156
2157                                                 exceptions_print_current_exception();
2158
2159                                                 /* goto next class */
2160
2161                                                 continue;
2162                                         }
2163                                 }
2164
2165                                 /* compile all class methods */
2166
2167                                 for (i = 0; i < c->methodscount; i++) {
2168                                         m = &(c->methods[i]);
2169
2170                                         if (m->jcode != NULL) {
2171                                                 if (!jit_compile(m)) {
2172                                                         fprintf(stderr, "Error compiling: ");
2173                                                         utf_fprint_printable_ascii_classname(stderr, c->name);
2174                                                         fprintf(stderr, ".");
2175                                                         utf_fprint_printable_ascii(stderr, m->name);
2176                                                         utf_fprint_printable_ascii(stderr, m->descriptor);
2177                                                         fprintf(stderr, "\n");
2178
2179                                                         /* print out exception and cause */
2180
2181                                                         exceptions_print_current_exception();
2182                                                 }
2183                                         }
2184                                 }
2185                         }
2186                 }
2187         }
2188 }
2189 #endif /* !defined(NDEBUG) */
2190
2191
2192 /* vm_compile_method ***********************************************************
2193
2194    Compile a specific method.
2195
2196 *******************************************************************************/
2197
2198 #if !defined(NDEBUG)
2199 static void vm_compile_method(void)
2200 {
2201         methodinfo *m;
2202
2203         /* create, load and link the main class */
2204
2205         mainclass = load_class_bootstrap(utf_new_char(mainstring));
2206
2207         if (mainclass == NULL)
2208                 exceptions_print_stacktrace();
2209
2210         if (!link_class(mainclass))
2211                 exceptions_print_stacktrace();
2212
2213         if (opt_signature != NULL) {
2214                 m = class_resolveclassmethod(mainclass,
2215                                                                          utf_new_char(opt_method),
2216                                                                          utf_new_char(opt_signature),
2217                                                                          mainclass,
2218                                                                          false);
2219         }
2220         else {
2221                 m = class_resolveclassmethod(mainclass,
2222                                                                          utf_new_char(opt_method),
2223                                                                          NULL,
2224                                                                          mainclass,
2225                                                                          false);
2226         }
2227
2228         if (m == NULL)
2229                 vm_abort("vm_compile_method: java.lang.NoSuchMethodException: %s.%s",
2230                                  opt_method, opt_signature ? opt_signature : "");
2231                 
2232         jit_compile(m);
2233 }
2234 #endif /* !defined(NDEBUG) */
2235
2236
2237 /* vm_array_store_int **********************************************************
2238
2239    Helper function to store an integer into the argument array, taking
2240    care of architecture specific issues.
2241
2242 *******************************************************************************/
2243
2244 static void vm_array_store_int(uint64_t *array, paramdesc *pd, int32_t value)
2245 {
2246         int32_t index;
2247
2248         if (!pd->inmemory) {
2249                 index        = pd->index;
2250                 array[index] = (int64_t) value;
2251         }
2252         else {
2253                 index        = ARG_CNT + pd->index;
2254 #if SIZEOF_VOID_P == 8
2255                 array[index] = (int64_t) value;
2256 #else
2257 # if WORDS_BIGENDIAN == 1
2258                 array[index] = ((int64_t) value) << 32;
2259 # else
2260                 array[index] = (int64_t) value;
2261 # endif
2262 #endif
2263         }
2264 }
2265
2266
2267 /* vm_array_store_lng **********************************************************
2268
2269    Helper function to store a long into the argument array, taking
2270    care of architecture specific issues.
2271
2272 *******************************************************************************/
2273
2274 static void vm_array_store_lng(uint64_t *array, paramdesc *pd, int64_t value)
2275 {
2276         int32_t index;
2277
2278 #if SIZEOF_VOID_P == 8
2279         if (!pd->inmemory)
2280                 index = pd->index;
2281         else
2282                 index = ARG_CNT + pd->index;
2283
2284         array[index] = value;
2285 #else
2286         if (!pd->inmemory) {
2287                 /* move low and high 32-bits into it's own argument slot */
2288
2289                 index        = GET_LOW_REG(pd->index);
2290                 array[index] = value & 0x00000000ffffffff;
2291
2292                 index        = GET_HIGH_REG(pd->index);
2293                 array[index] = value >> 32;
2294         }
2295         else {
2296                 index        = ARG_CNT + pd->index;
2297                 array[index] = value;
2298         }
2299 #endif
2300 }
2301
2302
2303 /* vm_array_store_flt **********************************************************
2304
2305    Helper function to store a float into the argument array, taking
2306    care of architecture specific issues.
2307
2308 *******************************************************************************/
2309
2310 static void vm_array_store_flt(uint64_t *array, paramdesc *pd, uint64_t value)
2311 {
2312         int32_t index;
2313
2314         if (!pd->inmemory) {
2315 #if defined(SUPPORT_PASS_FLOATARGS_IN_INTREGS)
2316                 index        = pd->index;
2317 #else
2318                 index        = INT_ARG_CNT + pd->index;
2319 #endif
2320 #if WORDS_BIGENDIAN == 1 && !defined(__POWERPC__) && !defined(__POWERPC64__) && !defined(__S390__)
2321                 array[index] = value >> 32;
2322 #else
2323                 array[index] = value;
2324 #endif
2325         }
2326         else {
2327                 index        = ARG_CNT + pd->index;
2328 #if defined(__SPARC_64__)
2329                 array[index] = value >> 32;
2330 #else
2331                 array[index] = value;
2332 #endif
2333         }
2334 }
2335
2336
2337 /* vm_array_store_dbl **********************************************************
2338
2339    Helper function to store a double into the argument array, taking
2340    care of architecture specific issues.
2341
2342 *******************************************************************************/
2343
2344 static void vm_array_store_dbl(uint64_t *array, paramdesc *pd, uint64_t value)
2345 {
2346         int32_t index;
2347
2348         if (!pd->inmemory) {
2349 #if SIZEOF_VOID_P != 8 && defined(SUPPORT_PASS_FLOATARGS_IN_INTREGS)
2350                 index        = GET_LOW_REG(pd->index);
2351                 array[index] = value & 0x00000000ffffffff;
2352
2353                 index        = GET_HIGH_REG(pd->index);
2354                 array[index] = value >> 32;
2355 #else
2356                 index        = INT_ARG_CNT + pd->index;
2357                 array[index] = value;
2358 #endif
2359         }
2360         else {
2361                 index        = ARG_CNT + pd->index;
2362                 array[index] = value;
2363         }
2364 }
2365
2366
2367 /* vm_array_store_adr **********************************************************
2368
2369    Helper function to store an address into the argument array, taking
2370    care of architecture specific issues.
2371
2372 *******************************************************************************/
2373
2374 static void vm_array_store_adr(uint64_t *array, paramdesc *pd, void *value)
2375 {
2376         int32_t index;
2377
2378         if (!pd->inmemory) {
2379 #if defined(HAS_ADDRESS_REGISTER_FILE)
2380                 /* When the architecture has address registers, place them
2381                    after integer and float registers. */
2382
2383                 index        = INT_ARG_CNT + FLT_ARG_CNT + pd->index;
2384 #else
2385                 index        = pd->index;
2386 #endif
2387                 array[index] = (uint64_t) (intptr_t) value;
2388         }
2389         else {
2390                 index        = ARG_CNT + pd->index;
2391 #if SIZEOF_VOID_P == 8
2392                 array[index] = (uint64_t) (intptr_t) value;
2393 #else
2394 # if WORDS_BIGENDIAN == 1
2395                 array[index] = ((uint64_t) (intptr_t) value) << 32;
2396 # else
2397                 array[index] = (uint64_t) (intptr_t) value;
2398 # endif
2399 #endif
2400         }
2401 }
2402
2403
2404 /* vm_array_from_valist ********************************************************
2405
2406    XXX
2407
2408 *******************************************************************************/
2409
2410 uint64_t *vm_array_from_valist(methodinfo *m, java_handle_t *o, va_list ap)
2411 {
2412         methoddesc *md;
2413         paramdesc  *pd;
2414         typedesc   *td;
2415         uint64_t   *array;
2416         int32_t     i;
2417         imm_union   value;
2418
2419         /* get the descriptors */
2420
2421         md = m->parseddesc;
2422         pd = md->params;
2423         td = md->paramtypes;
2424
2425         /* allocate argument array */
2426
2427         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2428
2429         /* if method is non-static fill first block and skip `this' pointer */
2430
2431         i = 0;
2432
2433         if (o != NULL) {
2434                 /* the `this' pointer */
2435                 vm_array_store_adr(array, pd, o);
2436
2437                 pd++;
2438                 td++;
2439                 i++;
2440         } 
2441
2442         for (; i < md->paramcount; i++, pd++, td++) {
2443                 switch (td->type) {
2444                 case TYPE_INT:
2445                         value.i = va_arg(ap, int32_t);
2446                         vm_array_store_int(array, pd, value.i);
2447                         break;
2448
2449                 case TYPE_LNG:
2450                         value.l = va_arg(ap, int64_t);
2451                         vm_array_store_lng(array, pd, value.l);
2452                         break;
2453
2454                 case TYPE_FLT:
2455 #if defined(__ALPHA__) || defined(__POWERPC__) || defined(__POWERPC64__)
2456                         /* This is required to load the correct float value in
2457                            assembler code. */
2458
2459                         value.d = (double) va_arg(ap, double);
2460 #else
2461                         value.f = (float) va_arg(ap, double);
2462 #endif
2463                         vm_array_store_flt(array, pd, value.l);
2464                         break;
2465
2466                 case TYPE_DBL:
2467                         value.d = va_arg(ap, double);
2468                         vm_array_store_dbl(array, pd, value.l);
2469                         break;
2470
2471                 case TYPE_ADR: 
2472                         value.a = va_arg(ap, void*);
2473                         vm_array_store_adr(array, pd, value.a);
2474                         break;
2475                 }
2476         }
2477
2478         return array;
2479 }
2480
2481
2482 /* vm_array_from_jvalue ********************************************************
2483
2484    XXX
2485
2486 *******************************************************************************/
2487
2488 static uint64_t *vm_array_from_jvalue(methodinfo *m, java_handle_t *o,
2489                                                                           const jvalue *args)
2490 {
2491         methoddesc *md;
2492         paramdesc  *pd;
2493         typedesc   *td;
2494         uint64_t   *array;
2495         int32_t     i;
2496         int32_t     j;
2497
2498         /* get the descriptors */
2499
2500         md = m->parseddesc;
2501         pd = md->params;
2502         td = md->paramtypes;
2503
2504         /* allocate argument array */
2505
2506 #if defined(HAS_ADDRESS_REGISTER_FILE)
2507         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + ADR_ARG_CNT + md->memuse);
2508 #else
2509         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2510 #endif
2511
2512         /* if method is non-static fill first block and skip `this' pointer */
2513
2514         i = 0;
2515
2516         if (o != NULL) {
2517                 /* the `this' pointer */
2518                 vm_array_store_adr(array, pd, o);
2519
2520                 pd++;
2521                 td++;
2522                 i++;
2523         } 
2524
2525         for (j = 0; i < md->paramcount; i++, j++, pd++, td++) {
2526                 switch (td->decltype) {
2527                 case TYPE_INT:
2528                         vm_array_store_int(array, pd, args[j].i);
2529                         break;
2530
2531                 case TYPE_LNG:
2532                         vm_array_store_lng(array, pd, args[j].j);
2533                         break;
2534
2535                 case TYPE_FLT:
2536                         vm_array_store_flt(array, pd, args[j].j);
2537                         break;
2538
2539                 case TYPE_DBL:
2540                         vm_array_store_dbl(array, pd, args[j].j);
2541                         break;
2542
2543                 case TYPE_ADR: 
2544                         vm_array_store_adr(array, pd, args[j].l);
2545                         break;
2546                 }
2547         }
2548
2549         return array;
2550 }
2551
2552
2553 /* vm_array_from_objectarray ***************************************************
2554
2555    XXX
2556
2557 *******************************************************************************/
2558
2559 uint64_t *vm_array_from_objectarray(methodinfo *m, java_handle_t *o,
2560                                                                         java_handle_objectarray_t *params)
2561 {
2562         methoddesc    *md;
2563         paramdesc     *pd;
2564         typedesc      *td;
2565         uint64_t      *array;
2566         java_handle_t *param;
2567         classinfo     *c;
2568         int            type;
2569         int32_t        i;
2570         int32_t        j;
2571         imm_union      value;
2572
2573         /* get the descriptors */
2574
2575         md = m->parseddesc;
2576         pd = md->params;
2577         td = md->paramtypes;
2578
2579         /* allocate argument array */
2580
2581         array = DMNEW(uint64_t, INT_ARG_CNT + FLT_ARG_CNT + md->memuse);
2582
2583         /* if method is non-static fill first block and skip `this' pointer */
2584
2585         i = 0;
2586
2587         if (o != NULL) {
2588                 /* this pointer */
2589                 vm_array_store_adr(array, pd, o);
2590
2591                 pd++;
2592                 td++;
2593                 i++;
2594         }
2595
2596         for (j = 0; i < md->paramcount; i++, j++, pd++, td++) {
2597                 LLNI_objectarray_element_get(params, j, param);
2598
2599                 switch (td->type) {
2600                 case TYPE_INT:
2601                         if (param == NULL)
2602                                 goto illegal_arg;
2603
2604                         /* convert the value according to its declared type */
2605
2606                         LLNI_class_get(param, c);
2607                         type = primitive_type_get_by_wrapperclass(c);
2608
2609                         switch (td->decltype) {
2610                         case PRIMITIVETYPE_BOOLEAN:
2611                                 switch (type) {
2612                                 case PRIMITIVETYPE_BOOLEAN:
2613                                         /* This type is OK. */
2614                                         break;
2615                                 default:
2616                                         goto illegal_arg;
2617                                 }
2618                                 break;
2619
2620                         case PRIMITIVETYPE_BYTE:
2621                                 switch (type) {
2622                                 case PRIMITIVETYPE_BYTE:
2623                                         /* This type is OK. */
2624                                         break;
2625                                 default:
2626                                         goto illegal_arg;
2627                                 }
2628                                 break;
2629
2630                         case PRIMITIVETYPE_CHAR:
2631                                 switch (type) {
2632                                 case PRIMITIVETYPE_CHAR:
2633                                         /* This type is OK. */
2634                                         break;
2635                                 default:
2636                                         goto illegal_arg;
2637                                 }
2638                                 break;
2639
2640                         case PRIMITIVETYPE_SHORT:
2641                                 switch (type) {
2642                                 case PRIMITIVETYPE_BYTE:
2643                                 case PRIMITIVETYPE_SHORT:
2644                                         /* These types are OK. */
2645                                         break;
2646                                 default:
2647                                         goto illegal_arg;
2648                                 }
2649                                 break;
2650
2651                         case PRIMITIVETYPE_INT:
2652                                 switch (type) {
2653                                 case PRIMITIVETYPE_BYTE:
2654                                 case PRIMITIVETYPE_SHORT:
2655                                 case PRIMITIVETYPE_INT:
2656                                         /* These types are OK. */
2657                                         break;
2658                                 default:
2659                                         goto illegal_arg;
2660                                 }
2661                                 break;
2662
2663                         default:
2664                                 vm_abort("vm_array_from_objectarray: invalid type %d",
2665                                                  td->decltype);
2666                         }
2667
2668                         value = primitive_unbox(param);
2669                         vm_array_store_int(array, pd, value.i);
2670                         break;
2671
2672                 case TYPE_LNG:
2673                         if (param == NULL)
2674                                 goto illegal_arg;
2675
2676                         LLNI_class_get(param, c);
2677                         assert(td->decltype == PRIMITIVETYPE_LONG);
2678
2679                         switch (type) {
2680                         case PRIMITIVETYPE_BYTE:
2681                         case PRIMITIVETYPE_SHORT:
2682                         case PRIMITIVETYPE_INT:
2683                         case PRIMITIVETYPE_LONG:
2684                                 /* These types are OK. */
2685                                 break;
2686                         default:
2687                                 goto illegal_arg;
2688                         }
2689
2690                         value = primitive_unbox(param);
2691                         vm_array_store_lng(array, pd, value.l);
2692                         break;
2693
2694                 case TYPE_FLT:
2695                         if (param == NULL)
2696                                 goto illegal_arg;
2697
2698                         LLNI_class_get(param, c);
2699                         type = primitive_type_get_by_wrapperclass(c);
2700
2701                         assert(td->decltype == PRIMITIVETYPE_FLOAT);
2702
2703                         switch (type) {
2704                         case PRIMITIVETYPE_FLOAT:
2705                                 /* This type is OK. */
2706                                 break;
2707                         default:
2708                                 goto illegal_arg;
2709                         }
2710
2711                         value = primitive_unbox(param);
2712                         vm_array_store_flt(array, pd, value.l);
2713                         break;
2714
2715                 case TYPE_DBL:
2716                         if (param == NULL)
2717                                 goto illegal_arg;
2718
2719                         LLNI_class_get(param, c);
2720                         type = primitive_type_get_by_wrapperclass(c);
2721
2722                         assert(td->decltype == PRIMITIVETYPE_DOUBLE);
2723
2724                         switch (type) {
2725                         case PRIMITIVETYPE_FLOAT:
2726                         case PRIMITIVETYPE_DOUBLE:
2727                                 /* These types are OK. */
2728                                 break;
2729                         default:
2730                                 goto illegal_arg;
2731                         }
2732
2733                         value = primitive_unbox(param);
2734                         vm_array_store_dbl(array, pd, value.l);
2735                         break;
2736                 
2737                 case TYPE_ADR:
2738                         if (!resolve_class_from_typedesc(td, true, true, &c))
2739                                 return false;
2740
2741                         if (param != NULL) {
2742                                 if (td->arraydim > 0) {
2743                                         if (!builtin_arrayinstanceof(param, c))
2744                                                 goto illegal_arg;
2745                                 }
2746                                 else {
2747                                         if (!builtin_instanceof(param, c))
2748                                                 goto illegal_arg;
2749                                 }
2750                         }
2751
2752                         vm_array_store_adr(array, pd, param);
2753                         break;
2754
2755                 default:
2756                         vm_abort("vm_array_from_objectarray: invalid type %d", td->type);
2757                 }
2758         }
2759
2760         return array;
2761
2762 illegal_arg:
2763         exceptions_throw_illegalargumentexception();
2764         return NULL;
2765 }
2766
2767
2768 /* vm_call_method **************************************************************
2769
2770    Calls a Java method with a variable number of arguments.
2771
2772 *******************************************************************************/
2773
2774 #define VM_CALL_METHOD(name, type)                                  \
2775 type vm_call_method##name(methodinfo *m, java_handle_t *o, ...)     \
2776 {                                                                   \
2777         va_list ap;                                                     \
2778         type    value;                                                  \
2779                                                                     \
2780         va_start(ap, o);                                                \
2781         value = vm_call_method##name##_valist(m, o, ap);                \
2782         va_end(ap);                                                     \
2783                                                                     \
2784         return value;                                                   \
2785 }
2786
2787 VM_CALL_METHOD(,        java_handle_t *)
2788 VM_CALL_METHOD(_int,    int32_t)
2789 VM_CALL_METHOD(_long,   int64_t)
2790 VM_CALL_METHOD(_float,  float)
2791 VM_CALL_METHOD(_double, double)
2792
2793
2794 /* vm_call_method_valist *******************************************************
2795
2796    Calls a Java method with a variable number of arguments, passed via
2797    a va_list.
2798
2799 *******************************************************************************/
2800
2801 #define VM_CALL_METHOD_VALIST(name, type)                               \
2802 type vm_call_method##name##_valist(methodinfo *m, java_handle_t *o,     \
2803                                                                    va_list ap)                          \
2804 {                                                                       \
2805         int32_t   dumpsize;                                                 \
2806         uint64_t *array;                                                    \
2807         type      value;                                                    \
2808                                                                         \
2809         dumpsize = dump_size();                                             \
2810         array = vm_array_from_valist(m, o, ap);                             \
2811         value = vm_call##name##_array(m, array);                            \
2812         dump_release(dumpsize);                                             \
2813                                                                         \
2814         return value;                                                       \
2815 }
2816
2817 VM_CALL_METHOD_VALIST(,        java_handle_t *)
2818 VM_CALL_METHOD_VALIST(_int,    int32_t)
2819 VM_CALL_METHOD_VALIST(_long,   int64_t)
2820 VM_CALL_METHOD_VALIST(_float,  float)
2821 VM_CALL_METHOD_VALIST(_double, double)
2822
2823
2824 /* vm_call_method_jvalue *******************************************************
2825
2826    Calls a Java method with a variable number of arguments, passed via
2827    a jvalue array.
2828
2829 *******************************************************************************/
2830
2831 #define VM_CALL_METHOD_JVALUE(name, type)                               \
2832 type vm_call_method##name##_jvalue(methodinfo *m, java_handle_t *o,     \
2833                                                            const jvalue *args)                  \
2834 {                                                                       \
2835         int32_t   dumpsize;                                                 \
2836         uint64_t *array;                                                    \
2837         type      value;                                                    \
2838                                                                         \
2839         dumpsize = dump_size();                                             \
2840         array = vm_array_from_jvalue(m, o, args);                           \
2841         value = vm_call##name##_array(m, array);                            \
2842         dump_release(dumpsize);                                             \
2843                                                                         \
2844         return value;                                                       \
2845 }
2846
2847 VM_CALL_METHOD_JVALUE(,        java_handle_t *)
2848 VM_CALL_METHOD_JVALUE(_int,    int32_t)
2849 VM_CALL_METHOD_JVALUE(_long,   int64_t)
2850 VM_CALL_METHOD_JVALUE(_float,  float)
2851 VM_CALL_METHOD_JVALUE(_double, double)
2852
2853
2854 /* vm_call_array ***************************************************************
2855
2856    Calls a Java method with a variable number of arguments, passed via
2857    an argument array.
2858
2859 *******************************************************************************/
2860
2861 #define VM_CALL_ARRAY(name, type)                            \
2862 type vm_call##name##_array(methodinfo *m, uint64_t *array)   \
2863 {                                                            \
2864         methoddesc *md;                                          \
2865         void       *pv;                                          \
2866         type        value;                                       \
2867                                                              \
2868         md = m->parseddesc;                                      \
2869                                                              \
2870         if (m->code == NULL)                                     \
2871                 if (!jit_compile(m))                                 \
2872                         return 0;                                        \
2873                                                              \
2874         pv = m->code->entrypoint;                                \
2875                                                              \
2876         STATISTICS(count_calls_native_to_java++);                \
2877                                                              \
2878         value = asm_vm_call_method##name(pv, array, md->memuse); \
2879                                                              \
2880         return value;                                            \
2881 }
2882
2883 VM_CALL_ARRAY(,        java_handle_t *)
2884 VM_CALL_ARRAY(_int,    int32_t)
2885 VM_CALL_ARRAY(_long,   int64_t)
2886 VM_CALL_ARRAY(_float,  float)
2887 VM_CALL_ARRAY(_double, double)
2888
2889
2890 /*
2891  * These are local overrides for various environment variables in Emacs.
2892  * Please do not remove this and leave it at the end of the file, where
2893  * Emacs will automagically detect them.
2894  * ---------------------------------------------------------------------
2895  * Local variables:
2896  * mode: c
2897  * indent-tabs-mode: t
2898  * c-basic-offset: 4
2899  * tab-width: 4
2900  * End:
2901  * vim:noexpandtab:sw=4:ts=4:
2902  */