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