OSDN Git Service

Merge change 8538
[android-x86/dalvik.git] / vm / Init.c
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * Dalvik initialization, shutdown, and command-line argument processing.
19  */
20 #include "Dalvik.h"
21 #include "test/Test.h"
22 #include "mterp/Mterp.h"
23 #include "Hash.h"
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <signal.h>
28 #include <limits.h>
29 #include <ctype.h>
30 #include <sys/wait.h>
31 #include <unistd.h>
32
33 #define kMinHeapStartSize   (1*1024*1024)
34 #define kMinHeapSize        (2*1024*1024)
35 #define kMaxHeapSize        (1*1024*1024*1024)
36
37 /*
38  * Register VM-agnostic native methods for system classes.
39  *
40  * Currently defined in ../include/nativehelper/AndroidSystemNatives.h
41  */
42 extern int jniRegisterSystemMethods(JNIEnv* env);
43
44 /* fwd */
45 static bool registerSystemNatives(JNIEnv* pEnv);
46 static bool dvmInitJDWP(void);
47 static bool dvmInitZygote(void);
48
49
50 /* global state */
51 struct DvmGlobals gDvm;
52
53 /* JIT-specific global state */
54 #if defined(WITH_JIT)
55 struct DvmJitGlobals gDvmJit;
56 #endif
57
58 /*
59  * Show usage.
60  *
61  * We follow the tradition of unhyphenated compound words.
62  */
63 static void dvmUsage(const char* progName)
64 {
65     dvmFprintf(stderr, "%s: [options] class [argument ...]\n", progName);
66     dvmFprintf(stderr, "%s: [options] -jar file.jar [argument ...]\n",progName);
67     dvmFprintf(stderr, "\n");
68     dvmFprintf(stderr, "The following standard options are recognized:\n");
69     dvmFprintf(stderr, "  -classpath classpath\n");
70     dvmFprintf(stderr, "  -Dproperty=value\n");
71     dvmFprintf(stderr, "  -verbose:tag  ('gc', 'jni', or 'class')\n");
72     dvmFprintf(stderr, "  -ea[:<package name>... |:<class name>]\n");
73     dvmFprintf(stderr, "  -da[:<package name>... |:<class name>]\n");
74     dvmFprintf(stderr, "   (-enableassertions, -disableassertions)\n");
75     dvmFprintf(stderr, "  -esa\n");
76     dvmFprintf(stderr, "  -dsa\n");
77     dvmFprintf(stderr,
78                 "   (-enablesystemassertions, -disablesystemassertions)\n");
79     dvmFprintf(stderr, "  -showversion\n");
80     dvmFprintf(stderr, "  -help\n");
81     dvmFprintf(stderr, "\n");
82     dvmFprintf(stderr, "The following extended options are recognized:\n");
83     dvmFprintf(stderr, "  -Xrunjdwp:<options>\n");
84     dvmFprintf(stderr, "  -Xbootclasspath:bootclasspath\n");
85     dvmFprintf(stderr, "  -Xcheck:tag  (e.g. 'jni')\n");
86     dvmFprintf(stderr, "  -XmsN  (min heap, must be multiple of 1K, >= 1MB)\n");
87     dvmFprintf(stderr, "  -XmxN  (max heap, must be multiple of 1K, >= 2MB)\n");
88     dvmFprintf(stderr, "  -XssN  (stack size, >= %dKB, <= %dKB)\n",
89         kMinStackSize / 1024, kMaxStackSize / 1024);
90     dvmFprintf(stderr, "  -Xverify:{none,remote,all}\n");
91     dvmFprintf(stderr, "  -Xrs\n");
92 #if defined(WITH_JIT)
93     dvmFprintf(stderr,
94                 "  -Xint  (extended to accept ':portable', ':fast' and ':jit')\n");
95 #else
96     dvmFprintf(stderr,
97                 "  -Xint  (extended to accept ':portable' and ':fast')\n");
98 #endif
99     dvmFprintf(stderr, "\n");
100     dvmFprintf(stderr, "These are unique to Dalvik:\n");
101     dvmFprintf(stderr, "  -Xzygote\n");
102     dvmFprintf(stderr, "  -Xdexopt:{none,verified,all}\n");
103     dvmFprintf(stderr, "  -Xnoquithandler\n");
104     dvmFprintf(stderr,
105                 "  -Xjnigreflimit:N  (must be multiple of 100, >= 200)\n");
106     dvmFprintf(stderr, "  -Xjniopts:{warnonly,forcecopy}\n");
107     dvmFprintf(stderr, "  -Xdeadlockpredict:{off,warn,err,abort}\n");
108     dvmFprintf(stderr, "  -Xstacktracefile:<filename>\n");
109     dvmFprintf(stderr, "  -Xgc:[no]precise\n");
110     dvmFprintf(stderr, "  -Xgenregmap\n");
111     dvmFprintf(stderr, "  -Xcheckdexsum\n");
112 #if defined(WITH_JIT)
113     dvmFprintf(stderr, "  -Xincludeselectedop\n");
114     dvmFprintf(stderr, "  -Xjitop:hexopvalue[-endvalue]"
115                        "[,hexopvalue[-endvalue]]*\n");
116     dvmFprintf(stderr, "  -Xincludeselectedmethod\n");
117     dvmFprintf(stderr, "  -Xthreshold:decimalvalue\n");
118     dvmFprintf(stderr, "  -Xblocking\n");
119     dvmFprintf(stderr, "  -Xjitmethod:signture[,signature]* "
120                        "(eg Ljava/lang/String\\;replace)\n");
121     dvmFprintf(stderr, "  -Xjitverbose\n");
122     dvmFprintf(stderr, "  -Xjitprofile\n");
123 #endif
124     dvmFprintf(stderr, "\n");
125     dvmFprintf(stderr, "Configured with:"
126 #ifdef WITH_DEBUGGER
127         " debugger"
128 #endif
129 #ifdef WITH_PROFILER
130         " profiler"
131 #endif
132 #ifdef WITH_MONITOR_TRACKING
133         " monitor_tracking"
134 #endif
135 #ifdef WITH_DEADLOCK_PREDICTION
136         " deadlock_prediction"
137 #endif
138 #ifdef WITH_HPROF
139         " hprof"
140 #endif
141 #ifdef WITH_HPROF_STACK
142         " hprof_stack"
143 #endif
144 #ifdef WITH_HPROF_STACK_UNREACHABLE
145         " hprof_stack_unreachable"
146 #endif
147 #ifdef WITH_ALLOC_LIMITS
148         " alloc_limits"
149 #endif
150 #ifdef WITH_TRACKREF_CHECKS
151         " trackref_checks"
152 #endif
153 #ifdef WITH_INSTR_CHECKS
154         " instr_checks"
155 #endif
156 #ifdef WITH_EXTRA_OBJECT_VALIDATION
157         " extra_object_validation"
158 #endif
159 #ifdef WITH_EXTRA_GC_CHECKS
160         " extra_gc_checks"
161 #endif
162 #ifdef WITH_DALVIK_ASSERT
163         " dalvik_assert"
164 #endif
165 #ifdef WITH_JNI_STACK_CHECK
166         " jni_stack_check"
167 #endif
168 #ifdef EASY_GDB
169         " easy_gdb"
170 #endif
171 #ifdef CHECK_MUTEX
172         " check_mutex"
173 #endif
174 #ifdef PROFILE_FIELD_ACCESS
175         " profile_field_access"
176 #endif
177 #ifdef DVM_TRACK_HEAP_MARKING
178         " track_heap_marking"
179 #endif
180 #if DVM_RESOLVER_CACHE == DVM_RC_REDUCING
181         " resolver_cache_reducing"
182 #elif DVM_RESOLVER_CACHE == DVM_RC_EXPANDING
183         " resolver_cache_expanding"
184 #elif DVM_RESOLVER_CACHE == DVM_RC_NO_CACHE
185         " resolver_cache_disabled"
186 #endif
187 #if defined(WITH_JIT)
188         " with_jit"
189 #endif
190     );
191 #ifdef DVM_SHOW_EXCEPTION
192     dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
193 #endif
194     dvmFprintf(stderr, "\n\n");
195 }
196
197 /*
198  * Show helpful information on JDWP options.
199  */
200 static void showJdwpHelp(void)
201 {
202     dvmFprintf(stderr,
203         "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
204     dvmFprintf(stderr,
205         "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
206 }
207
208 /*
209  * Show version and copyright info.
210  */
211 static void showVersion(void)
212 {
213     dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
214         DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
215     dvmFprintf(stdout, 
216         "Copyright (C) 2007 The Android Open Source Project\n\n"
217         "This software is built from source code licensed under the "
218         "Apache License,\n"
219         "Version 2.0 (the \"License\"). You may obtain a copy of the "
220         "License at\n\n"
221         "     http://www.apache.org/licenses/LICENSE-2.0\n\n"
222         "See the associated NOTICE file for this software for further "
223         "details.\n");
224 }
225
226 /*
227  * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
228  * memory sizes.  [kK] indicates kilobytes, [mM] megabytes, and
229  * [gG] gigabytes.
230  *
231  * "s" should point just past the "-Xm?" part of the string.
232  * "min" specifies the lowest acceptable value described by "s".
233  * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
234  * of 1024.
235  *
236  * The spec says the -Xmx and -Xms options must be multiples of 1024.  It
237  * doesn't say anything about -Xss.
238  *
239  * Returns 0 (a useless size) if "s" is malformed or specifies a low or
240  * non-evenly-divisible value.
241  */
242 static unsigned int dvmParseMemOption(const char *s, unsigned int div)
243 {
244     /* strtoul accepts a leading [+-], which we don't want,
245      * so make sure our string starts with a decimal digit.
246      */
247     if (isdigit(*s)) {
248         const char *s2;
249         unsigned int val;
250
251         val = (unsigned int)strtoul(s, (char **)&s2, 10);
252         if (s2 != s) {
253             /* s2 should be pointing just after the number.
254              * If this is the end of the string, the user
255              * has specified a number of bytes.  Otherwise,
256              * there should be exactly one more character
257              * that specifies a multiplier.
258              */
259             if (*s2 != '\0') {
260                 char c;
261
262                 /* The remainder of the string is either a single multiplier
263                  * character, or nothing to indicate that the value is in
264                  * bytes.
265                  */
266                 c = *s2++;
267                 if (*s2 == '\0') {
268                     unsigned int mul;
269
270                     if (c == '\0') {
271                         mul = 1;
272                     } else if (c == 'k' || c == 'K') {
273                         mul = 1024;
274                     } else if (c == 'm' || c == 'M') {
275                         mul = 1024 * 1024;
276                     } else if (c == 'g' || c == 'G') {
277                         mul = 1024 * 1024 * 1024;
278                     } else {
279                         /* Unknown multiplier character.
280                          */
281                         return 0;
282                     }
283
284                     if (val <= UINT_MAX / mul) {
285                         val *= mul;
286                     } else {
287                         /* Clamp to a multiple of 1024.
288                          */
289                         val = UINT_MAX & ~(1024-1);
290                     }
291                 } else {
292                     /* There's more than one character after the
293                      * numeric part.
294                      */
295                     return 0;
296                 }
297             }
298
299             /* The man page says that a -Xm value must be
300              * a multiple of 1024.
301              */
302             if (val % div == 0) {
303                 return val;
304             }
305         }
306     }
307
308     return 0;
309 }
310
311 /*
312  * Handle one of the JDWP name/value pairs.
313  *
314  * JDWP options are:
315  *  help: if specified, show help message and bail
316  *  transport: may be dt_socket or dt_shmem
317  *  address: for dt_socket, "host:port", or just "port" when listening
318  *  server: if "y", wait for debugger to attach; if "n", attach to debugger
319  *  timeout: how long to wait for debugger to connect / listen
320  *
321  * Useful with server=n (these aren't supported yet):
322  *  onthrow=<exception-name>: connect to debugger when exception thrown
323  *  onuncaught=y|n: connect to debugger when uncaught exception thrown
324  *  launch=<command-line>: launch the debugger itself
325  *
326  * The "transport" option is required, as is "address" if server=n.
327  */
328 static bool handleJdwpOption(const char* name, const char* value)
329 {
330     if (strcmp(name, "transport") == 0) {
331         if (strcmp(value, "dt_socket") == 0) {
332             gDvm.jdwpTransport = kJdwpTransportSocket;
333         } else if (strcmp(value, "dt_android_adb") == 0) {
334             gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
335         } else {
336             LOGE("JDWP transport '%s' not supported\n", value);
337             return false;
338         }
339     } else if (strcmp(name, "server") == 0) {
340         if (*value == 'n')
341             gDvm.jdwpServer = false;
342         else if (*value == 'y')
343             gDvm.jdwpServer = true;
344         else {
345             LOGE("JDWP option 'server' must be 'y' or 'n'\n");
346             return false;
347         }
348     } else if (strcmp(name, "suspend") == 0) {
349         if (*value == 'n')
350             gDvm.jdwpSuspend = false;
351         else if (*value == 'y')
352             gDvm.jdwpSuspend = true;
353         else {
354             LOGE("JDWP option 'suspend' must be 'y' or 'n'\n");
355             return false;
356         }
357     } else if (strcmp(name, "address") == 0) {
358         /* this is either <port> or <host>:<port> */
359         const char* colon = strchr(value, ':');
360         char* end;
361         long port;
362
363         if (colon != NULL) {
364             free(gDvm.jdwpHost);
365             gDvm.jdwpHost = (char*) malloc(colon - value +1);
366             strncpy(gDvm.jdwpHost, value, colon - value +1);
367             gDvm.jdwpHost[colon-value] = '\0';
368             value = colon + 1;
369         }
370         if (*value == '\0') {
371             LOGE("JDWP address missing port\n");
372             return false;
373         }
374         port = strtol(value, &end, 10);
375         if (*end != '\0') {
376             LOGE("JDWP address has junk in port field '%s'\n", value);
377             return false;
378         }
379         gDvm.jdwpPort = port;
380     } else if (strcmp(name, "launch") == 0 ||
381                strcmp(name, "onthrow") == 0 ||
382                strcmp(name, "oncaught") == 0 ||
383                strcmp(name, "timeout") == 0)
384     {
385         /* valid but unsupported */
386         LOGI("Ignoring JDWP option '%s'='%s'\n", name, value);
387     } else {
388         LOGI("Ignoring unrecognized JDWP option '%s'='%s'\n", name, value);
389     }
390
391     return true;
392 }
393
394 /*
395  * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
396  * "transport=dt_socket,address=8000,server=y,suspend=n"
397  */
398 static bool parseJdwpOptions(const char* str)
399 {
400     char* mangle = strdup(str);
401     char* name = mangle;
402     bool result = false;
403
404     /*
405      * Process all of the name=value pairs.
406      */
407     while (true) {
408         char* value;
409         char* comma;
410
411         value = strchr(name, '=');
412         if (value == NULL) {
413             LOGE("JDWP opts: garbage at '%s'\n", name);
414             goto bail;
415         }
416
417         comma = strchr(name, ',');      // use name, not value, for safety
418         if (comma != NULL) {
419             if (comma < value) {
420                 LOGE("JDWP opts: found comma before '=' in '%s'\n", mangle);
421                 goto bail;
422             }
423             *comma = '\0';
424         }
425
426         *value++ = '\0';        // stomp the '='
427
428         if (!handleJdwpOption(name, value))
429             goto bail;
430
431         if (comma == NULL) {
432             /* out of options */
433             break;
434         }
435         name = comma+1;
436     }
437
438     /*
439      * Make sure the combination of arguments makes sense.
440      */
441     if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
442         LOGE("JDWP opts: must specify transport\n");
443         goto bail;
444     }
445     if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
446         LOGE("JDWP opts: when server=n, must specify host and port\n");
447         goto bail;
448     }
449     // transport mandatory
450     // outbound server address
451
452     gDvm.jdwpConfigured = true;
453     result = true;
454
455 bail:
456     free(mangle);
457     return result;
458 }
459
460 /*
461  * Handle one of the four kinds of assertion arguments.
462  *
463  * "pkgOrClass" is the last part of an enable/disable line.  For a package
464  * the arg looks like "-ea:com.google.fubar...", for a class it looks
465  * like "-ea:com.google.fubar.Wahoo".  The string we get starts at the ':'.
466  *
467  * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
468  *
469  * Multiple instances of these arguments can be specified, e.g. you can
470  * enable assertions for a package and then disable them for one class in
471  * the package.
472  */
473 static bool enableAssertions(const char* pkgOrClass, bool enable)
474 {
475     AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
476     pCtrl->enable = enable;
477
478     if (pkgOrClass == NULL) {
479         /* enable or disable for all system classes */
480         pCtrl->isPackage = false;
481         pCtrl->pkgOrClass = NULL;
482         pCtrl->pkgOrClassLen = 0;
483     } else {
484         if (*pkgOrClass == '\0') {
485             /* global enable/disable for all but system */
486             pCtrl->isPackage = false;
487             pCtrl->pkgOrClass = strdup("");
488             pCtrl->pkgOrClassLen = 0;
489         } else {
490             pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1);    // skip ':'
491             if (pCtrl->pkgOrClass == NULL) {
492                 /* can happen if class name includes an illegal '/' */
493                 LOGW("Unable to process assertion arg '%s'\n", pkgOrClass);
494                 return false;
495             }
496
497             int len = strlen(pCtrl->pkgOrClass);
498             if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
499                 /* mark as package, truncate two of the three slashes */
500                 pCtrl->isPackage = true;
501                 *(pCtrl->pkgOrClass + len-2) = '\0';
502                 pCtrl->pkgOrClassLen = len - 2;
503             } else {
504                 /* just a class */
505                 pCtrl->isPackage = false;
506                 pCtrl->pkgOrClassLen = len;
507             }
508         }
509     }
510
511     return true;
512 }
513
514 /*
515  * Turn assertions on when requested to do so by the Zygote.
516  *
517  * This is a bit sketchy.  We can't (easily) go back and fiddle with all
518  * of the classes that have already been initialized, so this only
519  * affects classes that have yet to be loaded.  If some or all assertions
520  * have been enabled through some other means, we don't want to mess with
521  * it here, so we do nothing.  Finally, we assume that there's room in
522  * "assertionCtrl" to hold at least one entry; this is guaranteed by the
523  * allocator.
524  *
525  * This must only be called from the main thread during zygote init.
526  */
527 void dvmLateEnableAssertions(void)
528 {
529     if (gDvm.assertionCtrl == NULL) {
530         LOGD("Not late-enabling assertions: no assertionCtrl array\n");
531         return;
532     } else if (gDvm.assertionCtrlCount != 0) {
533         LOGD("Not late-enabling assertions: some asserts already configured\n");
534         return;
535     }
536     LOGD("Late-enabling assertions\n");
537
538     /* global enable for all but system */
539     AssertionControl* pCtrl = gDvm.assertionCtrl;
540     pCtrl->pkgOrClass = strdup("");
541     pCtrl->pkgOrClassLen = 0;
542     pCtrl->isPackage = false;
543     pCtrl->enable = true;
544     gDvm.assertionCtrlCount = 1;
545 }
546
547
548 /*
549  * Release memory associated with the AssertionCtrl array.
550  */
551 static void freeAssertionCtrl(void)
552 {
553     int i;
554
555     for (i = 0; i < gDvm.assertionCtrlCount; i++)
556         free(gDvm.assertionCtrl[i].pkgOrClass);
557     free(gDvm.assertionCtrl);
558 }
559
560 #if defined(WITH_JIT)
561 /* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
562 static void processXjitop(const char *opt)
563 {
564     if (opt[7] == ':') {
565         const char *startPtr = &opt[8];
566         char *endPtr = NULL;
567
568         do {
569             long startValue, endValue;
570
571             startValue = strtol(startPtr, &endPtr, 16);
572             if (startPtr != endPtr) {
573                 /* Just in case value is out of range */
574                 startValue &= 0xff;
575
576                 if (*endPtr == '-') {
577                     endValue = strtol(endPtr+1, &endPtr, 16);
578                     endValue &= 0xff;
579                 } else {
580                     endValue = startValue;
581                 }
582
583                 for (; startValue <= endValue; startValue++) {
584                     LOGW("Dalvik opcode %x is selected for debugging",
585                          (unsigned int) startValue);
586                     /* Mark the corresponding bit to 1 */
587                     gDvmJit.opList[startValue >> 3] |=
588                         1 << (startValue & 0x7);
589                 }
590
591                 if (*endPtr == 0) {
592                     break;
593                 }
594
595                 startPtr = endPtr + 1;
596
597                 continue;
598             } else {
599                 if (*endPtr != 0) {
600                     dvmFprintf(stderr,
601                         "Warning: Unrecognized opcode value substring "
602                         "%s\n", endPtr);
603                 }
604                 break;
605             }
606         } while (1);
607     } else {
608         int i;
609         for (i = 0; i < 32; i++) {
610             gDvmJit.opList[i] = 0xff;
611         }
612         dvmFprintf(stderr, "Warning: select all opcodes\n");
613     }
614 }
615
616 /* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
617 static void processXjitmethod(const char *opt)
618 {
619     char *buf = strdup(&opt[12]);
620     char *start, *end;
621
622     gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
623
624     start = buf;
625     /* 
626      * Break comma-separated method signatures and enter them into the hash
627      * table individually.
628      */
629     do {
630         int hashValue;
631
632         end = strchr(start, ',');
633         if (end) {
634             *end = 0;
635         }
636
637         hashValue = dvmComputeUtf8Hash(start);
638
639         dvmHashTableLookup(gDvmJit.methodTable, hashValue,
640                            strdup(start),
641                            (HashCompareFunc) strcmp, true);
642         if (end) {
643             start = end + 1;
644         } else {
645             break;
646         }
647     } while (1);
648     free(buf);
649 }
650 #endif
651
652 /*
653  * Process an argument vector full of options.  Unlike standard C programs,
654  * argv[0] does not contain the name of the program.
655  *
656  * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
657  * that we don't recognize.  Otherwise, we return with an error as soon as
658  * we see anything we can't identify.
659  *
660  * Returns 0 on success, -1 on failure, and 1 for the special case of
661  * "-version" where we want to stop without showing an error message.
662  */
663 static int dvmProcessOptions(int argc, const char* const argv[],
664     bool ignoreUnrecognized)
665 {
666     int i;
667
668     LOGV("VM options (%d):\n", argc);
669     for (i = 0; i < argc; i++)
670         LOGV("  %d: '%s'\n", i, argv[i]);
671
672     /*
673      * Over-allocate AssertionControl array for convenience.  If allocated,
674      * the array must be able to hold at least one entry, so that the
675      * zygote-time activation can do its business.
676      */
677     assert(gDvm.assertionCtrl == NULL);
678     if (argc > 0) {
679         gDvm.assertionCtrl =
680             (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
681         if (gDvm.assertionCtrl == NULL)
682             return -1;
683         assert(gDvm.assertionCtrlCount == 0);
684     }
685
686     for (i = 0; i < argc; i++) {
687         if (strcmp(argv[i], "-help") == 0) {
688             /* show usage and stop */
689             return -1;
690
691         } else if (strcmp(argv[i], "-version") == 0) {
692             /* show version and stop */
693             showVersion();
694             return 1;
695         } else if (strcmp(argv[i], "-showversion") == 0) {
696             /* show version and continue */
697             showVersion();
698
699         } else if (strcmp(argv[i], "-classpath") == 0 ||
700                    strcmp(argv[i], "-cp") == 0)
701         {
702             /* set classpath */
703             if (i == argc-1) {
704                 dvmFprintf(stderr, "Missing classpath path list\n");
705                 return -1;
706             }
707             free(gDvm.classPathStr); /* in case we have compiled-in default */
708             gDvm.classPathStr = strdup(argv[++i]);
709
710         } else if (strncmp(argv[i], "-Xbootclasspath:",
711                 sizeof("-Xbootclasspath:")-1) == 0)
712         {
713             /* set bootclasspath */
714             const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
715
716             if (*path == '\0') {
717                 dvmFprintf(stderr, "Missing bootclasspath path list\n");
718                 return -1;
719             }
720             free(gDvm.bootClassPathStr);
721             gDvm.bootClassPathStr = strdup(path);
722
723             /*
724              * TODO: support -Xbootclasspath/a and /p, which append or
725              * prepend to the default bootclasspath.  We set the default
726              * path earlier.
727              */
728
729         } else if (strncmp(argv[i], "-D", 2) == 0) {
730             /* set property */
731             dvmAddCommandLineProperty(argv[i] + 2);
732
733         } else if (strcmp(argv[i], "-jar") == 0) {
734             // TODO: handle this; name of jar should be in argv[i+1]
735             dvmFprintf(stderr, "-jar not yet handled\n");
736             assert(false);
737
738         } else if (strncmp(argv[i], "-Xms", 4) == 0) {
739             unsigned int val = dvmParseMemOption(argv[i]+4, 1024);
740             if (val != 0) {
741                 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
742                     gDvm.heapSizeStart = val;
743                 } else {
744                     dvmFprintf(stderr,
745                         "Invalid -Xms '%s', range is %dKB to %dKB\n",
746                         argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
747                     return -1;
748                 }
749             } else {
750                 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
751                 return -1;
752             }
753         } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
754             unsigned int val = dvmParseMemOption(argv[i]+4, 1024);
755             if (val != 0) {
756                 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
757                     gDvm.heapSizeMax = val;
758                 } else {
759                     dvmFprintf(stderr,
760                         "Invalid -Xmx '%s', range is %dKB to %dKB\n",
761                         argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
762                     return -1;
763                 }
764             } else {
765                 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
766                 return -1;
767             }
768         } else if (strncmp(argv[i], "-Xss", 4) == 0) {
769             unsigned int val = dvmParseMemOption(argv[i]+4, 1);
770             if (val != 0) {
771                 if (val >= kMinStackSize && val <= kMaxStackSize) {
772                     gDvm.stackSize = val;
773                 } else {
774                     dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
775                         argv[i], kMinStackSize, kMaxStackSize);
776                     return -1;
777                 }
778             } else {
779                 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
780                 return -1;
781             }
782
783         } else if (strcmp(argv[i], "-verbose") == 0 ||
784             strcmp(argv[i], "-verbose:class") == 0)
785         {
786             // JNI spec says "-verbose:gc,class" is valid, but cmd line
787             // doesn't work that way; may want to support.
788             gDvm.verboseClass = true;
789         } else if (strcmp(argv[i], "-verbose:jni") == 0) {
790             gDvm.verboseJni = true;
791         } else if (strcmp(argv[i], "-verbose:gc") == 0) {
792             gDvm.verboseGc = true;
793
794         } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
795             enableAssertions(argv[i] + 17, true);
796         } else if (strncmp(argv[i], "-ea", 3) == 0) {
797             enableAssertions(argv[i] + 3, true);
798         } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
799             enableAssertions(argv[i] + 18, false);
800         } else if (strncmp(argv[i], "-da", 3) == 0) {
801             enableAssertions(argv[i] + 3, false);
802         } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
803                    strcmp(argv[i], "-esa") == 0)
804         {
805             enableAssertions(NULL, true);
806         } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
807                    strcmp(argv[i], "-dsa") == 0)
808         {
809             enableAssertions(NULL, false);
810
811         } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
812             /* nothing to do now -- was handled during JNI init */
813
814         } else if (strcmp(argv[i], "-Xdebug") == 0) {
815             /* accept but ignore */
816
817         } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
818             strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
819         {
820             const char* tail;
821             bool result = false;
822
823             if (argv[i][1] == 'X')
824                 tail = argv[i] + 10;
825             else
826                 tail = argv[i] + 15;
827
828             if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
829                 showJdwpHelp();
830                 return 1;
831             }
832         } else if (strcmp(argv[i], "-Xrs") == 0) {
833             gDvm.reduceSignals = true;
834         } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
835             /* disables SIGQUIT handler thread while still blocking SIGQUIT */
836             /* (useful if we don't want thread but system still signals us) */
837             gDvm.noQuitHandler = true;
838         } else if (strcmp(argv[i], "-Xzygote") == 0) {
839             gDvm.zygote = true;
840         } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
841             if (strcmp(argv[i] + 9, "none") == 0)
842                 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
843             else if (strcmp(argv[i] + 9, "verified") == 0)
844                 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
845             else if (strcmp(argv[i] + 9, "all") == 0)
846                 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
847             else {
848                 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
849                 return -1;
850             }
851         } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
852             if (strcmp(argv[i] + 9, "none") == 0)
853                 gDvm.classVerifyMode = VERIFY_MODE_NONE;
854             else if (strcmp(argv[i] + 9, "remote") == 0)
855                 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
856             else if (strcmp(argv[i] + 9, "all") == 0)
857                 gDvm.classVerifyMode = VERIFY_MODE_ALL;
858             else {
859                 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
860                 return -1;
861             }
862         } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
863             int lim = atoi(argv[i] + 15);
864             if (lim < 200 || (lim % 100) != 0) {
865                 dvmFprintf(stderr, "Bad value for -Xjnigreflimit: '%s'\n",
866                     argv[i]+15);
867                 return -1;
868             }
869             gDvm.jniGrefLimit = lim;
870
871         } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
872             gDvm.logStdio = true;
873
874         } else if (strncmp(argv[i], "-Xint", 5) == 0) {
875             if (argv[i][5] == ':') {
876                 if (strcmp(argv[i] + 6, "portable") == 0)
877                     gDvm.executionMode = kExecutionModeInterpPortable;
878                 else if (strcmp(argv[i] + 6, "fast") == 0)
879                     gDvm.executionMode = kExecutionModeInterpFast;
880 #ifdef WITH_JIT
881                 else if (strcmp(argv[i] + 6, "jit") == 0)
882                     gDvm.executionMode = kExecutionModeJit;
883 #endif
884                 else {
885                     dvmFprintf(stderr,
886                         "Warning: Unrecognized interpreter mode %s\n",argv[i]);
887                     /* keep going */
888                 }
889             } else {
890                 /* disable JIT -- nothing to do here for now */
891             }
892
893 #ifdef WITH_JIT
894         } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
895             processXjitop(argv[i]);
896         } else if (strncmp(argv[i], "-Xjitmethod", 11) == 0) {
897             processXjitmethod(argv[i]);
898         } else if (strncmp(argv[i], "-Xblocking", 10) == 0) {
899           gDvmJit.blockingMode = true;
900         } else if (strncmp(argv[i], "-Xthreshold:", 12) == 0) {
901           gDvmJit.threshold = atoi(argv[i] + 12);
902         } else if (strncmp(argv[i], "-Xincludeselectedop", 19) == 0) {
903           gDvmJit.includeSelectedOp = true;
904         } else if (strncmp(argv[i], "-Xincludeselectedmethod", 23) == 0) {
905           gDvmJit.includeSelectedMethod = true;
906         } else if (strncmp(argv[i], "-Xjitverbose", 12) == 0) {
907           gDvmJit.printMe = true;
908         } else if (strncmp(argv[i], "-Xjitprofile", 12) == 0) {
909           gDvmJit.profile = true;
910 #endif
911
912         } else if (strncmp(argv[i], "-Xdeadlockpredict:", 18) == 0) {
913 #ifdef WITH_DEADLOCK_PREDICTION
914             if (strcmp(argv[i] + 18, "off") == 0)
915                 gDvm.deadlockPredictMode = kDPOff;
916             else if (strcmp(argv[i] + 18, "warn") == 0)
917                 gDvm.deadlockPredictMode = kDPWarn;
918             else if (strcmp(argv[i] + 18, "err") == 0)
919                 gDvm.deadlockPredictMode = kDPErr;
920             else if (strcmp(argv[i] + 18, "abort") == 0)
921                 gDvm.deadlockPredictMode = kDPAbort;
922             else {
923                 dvmFprintf(stderr, "Bad value for -Xdeadlockpredict");
924                 return -1;
925             }
926             if (gDvm.deadlockPredictMode != kDPOff)
927                 LOGD("Deadlock prediction enabled (%s)\n", argv[i]+18);
928 #endif
929
930         } else if (strncmp(argv[i], "-Xstacktracefile:", 17) == 0) {
931             gDvm.stackTraceFile = strdup(argv[i]+17);
932
933         } else if (strcmp(argv[i], "-Xgenregmap") == 0) {
934             gDvm.generateRegisterMaps = true;
935             LOGD("Register maps will be generated during verification\n");
936
937         } else if (strncmp(argv[i], "-Xgc:", 5) == 0) {
938             if (strcmp(argv[i] + 5, "precise") == 0)
939                 gDvm.preciseGc = true;
940             else if (strcmp(argv[i] + 5, "noprecise") == 0)
941                 gDvm.preciseGc = false;
942             else {
943                 dvmFprintf(stderr, "Bad value for -Xgc");
944                 return -1;
945             }
946             LOGD("Precise GC configured %s\n", gDvm.preciseGc ? "ON" : "OFF");
947
948         } else if (strcmp(argv[i], "-Xcheckdexsum") == 0) {
949             gDvm.verifyDexChecksum = true;
950
951         } else {
952             if (!ignoreUnrecognized) {
953                 dvmFprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
954                 return -1;
955             }
956         }
957     }
958
959     if (gDvm.heapSizeStart > gDvm.heapSizeMax) {
960         dvmFprintf(stderr, "Heap start size must be <= heap max size\n");
961         return -1;
962     }
963
964     return 0;
965 }
966
967 /*
968  * Set defaults for fields altered or modified by arguments.
969  *
970  * Globals are initialized to 0 (a/k/a NULL or false).
971  */
972 static void setCommandLineDefaults()
973 {
974     const char* envStr;
975
976     envStr = getenv("CLASSPATH");
977     if (envStr != NULL)
978         gDvm.classPathStr = strdup(envStr);
979     else
980         gDvm.classPathStr = strdup(".");
981     envStr = getenv("BOOTCLASSPATH");
982     if (envStr != NULL)
983         gDvm.bootClassPathStr = strdup(envStr);
984     else
985         gDvm.bootClassPathStr = strdup(".");
986
987     /* Defaults overridden by -Xms and -Xmx.
988      * TODO: base these on a system or application-specific default
989      */
990     gDvm.heapSizeStart = 2 * 1024 * 1024;   // Spec says 16MB; too big for us.
991     gDvm.heapSizeMax = 16 * 1024 * 1024;    // Spec says 75% physical mem
992     gDvm.stackSize = kDefaultStackSize;
993
994     /* gDvm.jdwpSuspend = true; */
995
996     /* allowed unless zygote config doesn't allow it */
997     gDvm.jdwpAllowed = true;
998
999     /* default verification and optimization modes */
1000     gDvm.classVerifyMode = VERIFY_MODE_ALL;
1001     gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1002
1003     /*
1004      * Default execution mode.
1005      *
1006      * This should probably interact with the mterp code somehow, e.g. if
1007      * we know we're using the "desktop" build we should probably be
1008      * using "portable" rather than "fast".
1009      */
1010 #if defined(WITH_JIT)
1011     gDvm.executionMode = kExecutionModeJit;
1012     /* 
1013      * TODO - check system property and insert command-line options in 
1014      *        frameworks/base/core/jni/AndroidRuntime.cpp
1015      */
1016     gDvmJit.blockingMode = false;
1017     gDvmJit.jitTableSize = 512;
1018     gDvmJit.jitTableMask = gDvmJit.jitTableSize - 1;
1019     gDvmJit.threshold = 200;
1020 #else
1021     gDvm.executionMode = kExecutionModeInterpFast;
1022 #endif
1023 }
1024
1025
1026 /*
1027  * Handle a SIGBUS, which frequently occurs because somebody replaced an
1028  * optimized DEX file out from under us.
1029  */
1030 static void busCatcher(int signum, siginfo_t* info, void* context)
1031 {
1032     void* addr = info->si_addr;
1033
1034     LOGE("Caught a SIGBUS (%d), addr=%p\n", signum, addr);
1035
1036     /*
1037      * If we return at this point the SIGBUS just keeps happening, so we
1038      * remove the signal handler and allow it to kill us.  TODO: restore
1039      * the original, which points to a debuggerd stub; if we don't then
1040      * debuggerd won't be notified.
1041      */
1042     signal(SIGBUS, SIG_DFL);
1043 }
1044
1045 /*
1046  * Configure signals.  We need to block SIGQUIT so that the signal only
1047  * reaches the dump-stack-trace thread.
1048  *
1049  * This can be disabled with the "-Xrs" flag.
1050  */
1051 static void blockSignals()
1052 {
1053     sigset_t mask;
1054     int cc;
1055
1056     sigemptyset(&mask);
1057     sigaddset(&mask, SIGQUIT);
1058     sigaddset(&mask, SIGUSR1);      // used to initiate heap dump
1059 #if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1060     sigaddset(&mask, SIGUSR2);      // used to investigate JIT internals
1061 #endif
1062     //sigaddset(&mask, SIGPIPE);
1063     cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1064     assert(cc == 0);
1065
1066     if (false) {
1067         /* TODO: save the old sigaction in a global */
1068         struct sigaction sa;
1069         memset(&sa, 0, sizeof(sa));
1070         sa.sa_sigaction = busCatcher;
1071         sa.sa_flags = SA_SIGINFO;
1072         cc = sigaction(SIGBUS, &sa, NULL);
1073         assert(cc == 0);
1074     }
1075 }
1076
1077 /*
1078  * VM initialization.  Pass in any options provided on the command line.
1079  * Do not pass in the class name or the options for the class.
1080  *
1081  * Returns 0 on success.
1082  */
1083 int dvmStartup(int argc, const char* const argv[], bool ignoreUnrecognized,
1084     JNIEnv* pEnv)
1085 {
1086     int i, cc;
1087
1088     assert(gDvm.initializing);
1089
1090     LOGV("VM init args (%d):\n", argc);
1091     for (i = 0; i < argc; i++)
1092         LOGV("  %d: '%s'\n", i, argv[i]);
1093
1094     setCommandLineDefaults();
1095
1096     /* prep properties storage */
1097     if (!dvmPropertiesStartup(argc))
1098         goto fail;
1099
1100     /*
1101      * Process the option flags (if any).
1102      */
1103     cc = dvmProcessOptions(argc, argv, ignoreUnrecognized);
1104     if (cc != 0) {
1105         if (cc < 0) {
1106             dvmFprintf(stderr, "\n");
1107             dvmUsage("dalvikvm");
1108         }
1109         goto fail;
1110     }
1111
1112 #if WITH_EXTRA_GC_CHECKS > 1
1113     /* only "portable" interp has the extra goodies */
1114     if (gDvm.executionMode != kExecutionModeInterpPortable) {
1115         LOGI("Switching to 'portable' interpreter for GC checks\n");
1116         gDvm.executionMode = kExecutionModeInterpPortable;
1117     }
1118 #endif
1119
1120     /* configure signal handling */
1121     if (!gDvm.reduceSignals)
1122         blockSignals();
1123
1124     /* mterp setup */
1125     LOGV("Using executionMode %d\n", gDvm.executionMode);
1126     dvmCheckAsmConstants();
1127
1128     /*
1129      * Initialize components.
1130      */
1131     if (!dvmAllocTrackerStartup())
1132         goto fail;
1133     if (!dvmGcStartup())
1134         goto fail;
1135     if (!dvmThreadStartup())
1136         goto fail;
1137     if (!dvmInlineNativeStartup())
1138         goto fail;
1139     if (!dvmVerificationStartup())
1140         goto fail;
1141     if (!dvmRegisterMapStartup())
1142         goto fail;
1143     if (!dvmInstanceofStartup())
1144         goto fail;
1145     if (!dvmClassStartup())
1146         goto fail;
1147     if (!dvmThreadObjStartup())
1148         goto fail;
1149     if (!dvmExceptionStartup())
1150         goto fail;
1151     if (!dvmStringInternStartup())
1152         goto fail;
1153     if (!dvmNativeStartup())
1154         goto fail;
1155     if (!dvmInternalNativeStartup())
1156         goto fail;
1157     if (!dvmJniStartup())
1158         goto fail;
1159     if (!dvmReflectStartup())
1160         goto fail;
1161 #ifdef WITH_PROFILER
1162     if (!dvmProfilingStartup())
1163         goto fail;
1164 #endif
1165
1166     /* make sure we got these [can this go away?] */
1167     assert(gDvm.classJavaLangClass != NULL);
1168     assert(gDvm.classJavaLangObject != NULL);
1169     //assert(gDvm.classJavaLangString != NULL);
1170     assert(gDvm.classJavaLangThread != NULL);
1171     assert(gDvm.classJavaLangVMThread != NULL);
1172     assert(gDvm.classJavaLangThreadGroup != NULL);
1173
1174     /*
1175      * Make sure these exist.  If they don't, we can return a failure out
1176      * of main and nip the whole thing in the bud.
1177      */
1178     static const char* earlyClasses[] = {
1179         "Ljava/lang/InternalError;",
1180         "Ljava/lang/StackOverflowError;",
1181         "Ljava/lang/UnsatisfiedLinkError;",
1182         "Ljava/lang/NoClassDefFoundError;",
1183         NULL
1184     };
1185     const char** pClassName;
1186     for (pClassName = earlyClasses; *pClassName != NULL; pClassName++) {
1187         if (dvmFindSystemClassNoInit(*pClassName) == NULL)
1188             goto fail;
1189     }
1190
1191     /*
1192      * Miscellaneous class library validation.
1193      */
1194     if (!dvmValidateBoxClasses())
1195         goto fail;
1196
1197     /*
1198      * Do the last bits of Thread struct initialization we need to allow
1199      * JNI calls to work.
1200      */
1201     if (!dvmPrepMainForJni(pEnv))
1202         goto fail;
1203
1204     /*
1205      * Register the system native methods, which are registered through JNI.
1206      */
1207     if (!registerSystemNatives(pEnv))
1208         goto fail;
1209
1210     /*
1211      * Do some "late" initialization for the memory allocator.  This may
1212      * allocate storage and initialize classes.
1213      */
1214     if (!dvmCreateStockExceptions())
1215         goto fail;
1216
1217     /*
1218      * At this point, the VM is in a pretty good state.  Finish prep on
1219      * the main thread (specifically, create a java.lang.Thread object to go
1220      * along with our Thread struct).  Note we will probably be executing
1221      * some interpreted class initializer code in here.
1222      */
1223     if (!dvmPrepMainThread())
1224         goto fail;
1225
1226     /* general debugging setup */
1227     if (!dvmDebuggerStartup())
1228         goto fail;
1229
1230     /*
1231      * Init for either zygote mode or non-zygote mode.  The key difference
1232      * is that we don't start any additional threads in Zygote mode.
1233      */
1234     if (gDvm.zygote) {
1235         if (!dvmInitZygote())
1236             goto fail;
1237     } else {
1238         if (!dvmInitAfterZygote())
1239             goto fail;
1240     }
1241
1242
1243 #ifndef NDEBUG
1244     if (!dvmTestHash())
1245         LOGE("dmvTestHash FAILED\n");
1246     if (false /*noisy!*/ && !dvmTestIndirectRefTable())
1247         LOGE("dvmTestIndirectRefTable FAILED\n");
1248 #endif
1249
1250     assert(!dvmCheckException(dvmThreadSelf()));
1251     gDvm.initExceptionCount = 0;
1252
1253     return 0;
1254
1255 fail:
1256     dvmShutdown();
1257     return 1;
1258 }
1259
1260 /*
1261  * Register java.* natives from our class libraries.  We need to do
1262  * this after we're ready for JNI registration calls, but before we
1263  * do any class initialization.
1264  *
1265  * If we get this wrong, we will blow up in the ThreadGroup class init if
1266  * interpreted code makes any reference to System.  It will likely do this
1267  * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1268  *
1269  * We need to have gDvm.initializing raised here so that JNI FindClass
1270  * won't try to use the system/application class loader.
1271  */
1272 static bool registerSystemNatives(JNIEnv* pEnv)
1273 {
1274     Thread* self;
1275
1276     /* main thread is always first in list */
1277     self = gDvm.threadList;
1278
1279     /* must set this before allowing JNI-based method registration */
1280     self->status = THREAD_NATIVE;
1281
1282     if (jniRegisterSystemMethods(pEnv) < 0) {
1283         LOGW("jniRegisterSystemMethods failed\n");
1284         return false;
1285     }
1286
1287     /* back to run mode */
1288     self->status = THREAD_RUNNING;
1289
1290     return true;
1291 }
1292
1293
1294 /*
1295  * Do zygote-mode-only initialization.
1296  */
1297 static bool dvmInitZygote(void)
1298 {
1299     /* zygote goes into its own process group */
1300     setpgid(0,0);
1301
1302     return true;
1303 }
1304
1305 /*
1306  * Do non-zygote-mode initialization.  This is done during VM init for
1307  * standard startup, or after a "zygote fork" when creating a new process.
1308  */
1309 bool dvmInitAfterZygote(void)
1310 {
1311     u8 startHeap, startQuit, startJdwp;
1312     u8 endHeap, endQuit, endJdwp;
1313     
1314     startHeap = dvmGetRelativeTimeUsec();
1315
1316     /*
1317      * Post-zygote heap initialization, including starting
1318      * the HeapWorker thread.
1319      */
1320     if (!dvmGcStartupAfterZygote())
1321         return false;
1322
1323     endHeap = dvmGetRelativeTimeUsec();
1324     startQuit = dvmGetRelativeTimeUsec();
1325
1326     /* start signal catcher thread that dumps stacks on SIGQUIT */
1327     if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1328         if (!dvmSignalCatcherStartup())
1329             return false;
1330     }
1331
1332     /* start stdout/stderr copier, if requested */
1333     if (gDvm.logStdio) {
1334         if (!dvmStdioConverterStartup())
1335             return false;
1336     }
1337
1338     endQuit = dvmGetRelativeTimeUsec();
1339     startJdwp = dvmGetRelativeTimeUsec();
1340
1341     /*
1342      * Start JDWP thread.  If the command-line debugger flags specified
1343      * "suspend=y", this will pause the VM.  We probably want this to
1344      * come last.
1345      */
1346     if (!dvmInitJDWP()) {
1347         LOGD("JDWP init failed; continuing anyway\n");
1348     }
1349
1350     endJdwp = dvmGetRelativeTimeUsec();
1351
1352     LOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec\n",
1353         (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1354         (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1355
1356 #ifdef WITH_JIT
1357     if (!dvmJitStartup())
1358         return false;
1359 #endif
1360
1361     return true;
1362 }
1363
1364 /*
1365  * Prepare for a connection to a JDWP-compliant debugger.
1366  *
1367  * Note this needs to happen fairly late in the startup process, because
1368  * we need to have all of the java.* native methods registered (which in
1369  * turn requires JNI to be fully prepped).
1370  *
1371  * There are several ways to initialize:
1372  *   server=n
1373  *     We immediately try to connect to host:port.  Bail on failure.  On
1374  *     success, send VM_START (suspending the VM if "suspend=y").
1375  *   server=y suspend=n
1376  *     Passively listen for a debugger to connect.  Return immediately.
1377  *   server=y suspend=y
1378  *     Wait until debugger connects.  Send VM_START ASAP, suspending the
1379  *     VM after the message is sent.
1380  *
1381  * This gets more complicated with a nonzero value for "timeout".
1382  */
1383 static bool dvmInitJDWP(void)
1384 {
1385     assert(!gDvm.zygote);
1386
1387 #ifndef WITH_DEBUGGER
1388     LOGI("Debugger support not compiled into VM\n");
1389     return false;
1390 #endif
1391
1392     /*
1393      * Init JDWP if the debugger is enabled.  This may connect out to a
1394      * debugger, passively listen for a debugger, or block waiting for a
1395      * debugger.
1396      */
1397     if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1398         JdwpStartupParams params;
1399
1400         if (gDvm.jdwpHost != NULL) {
1401             if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1402                 LOGE("ERROR: hostname too long: '%s'\n", gDvm.jdwpHost);
1403                 return false;
1404             }
1405             strcpy(params.host, gDvm.jdwpHost);
1406         } else {
1407             params.host[0] = '\0';
1408         }
1409         params.transport = gDvm.jdwpTransport;
1410         params.server = gDvm.jdwpServer;
1411         params.suspend = gDvm.jdwpSuspend;
1412         params.port = gDvm.jdwpPort;
1413
1414         gDvm.jdwpState = dvmJdwpStartup(&params);
1415         if (gDvm.jdwpState == NULL) {
1416             LOGW("WARNING: debugger thread failed to initialize\n");
1417             /* TODO: ignore? fail? need to mimic "expected" behavior */
1418         }
1419     }
1420
1421     /*
1422      * If a debugger has already attached, send the "welcome" message.  This
1423      * may cause us to suspend all threads.
1424      */
1425     if (dvmJdwpIsActive(gDvm.jdwpState)) {
1426         //dvmChangeStatus(NULL, THREAD_RUNNING);
1427         if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1428             LOGW("WARNING: failed to post 'start' message to debugger\n");
1429             /* keep going */
1430         }
1431         //dvmChangeStatus(NULL, THREAD_NATIVE);
1432     }
1433
1434     return true;
1435 }
1436
1437 /*
1438  * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1439  * of initialization and then returns with "initializing" still set.  (Used
1440  * by DexOpt command-line utility.)
1441  *
1442  * Attempting to use JNI or internal natives will fail.  It's best if
1443  * no bytecode gets executed, which means no <clinit>, which means no
1444  * exception-throwing.  We check the "initializing" flag anyway when
1445  * throwing an exception, so we can insert some code that avoids chucking
1446  * an exception when we're optimizing stuff.
1447  *
1448  * Returns 0 on success.
1449  */
1450 int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1451     DexClassVerifyMode verifyMode, int dexoptFlags)
1452 {
1453     gDvm.initializing = true;
1454     gDvm.optimizing = true;
1455
1456     /* configure signal handling */
1457     blockSignals();
1458
1459     /* set some defaults */
1460     setCommandLineDefaults();
1461     free(gDvm.bootClassPathStr);
1462     gDvm.bootClassPathStr = strdup(bootClassPath);
1463
1464     /* set opt/verify modes */
1465     gDvm.dexOptMode = dexOptMode;
1466     gDvm.classVerifyMode = verifyMode;
1467     gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1468
1469     /*
1470      * Initialize the heap, some basic thread control mutexes, and
1471      * get the bootclasspath prepped.
1472      *
1473      * We can't load any classes yet because we may not yet have a source
1474      * for things like java.lang.Object and java.lang.Class.
1475      */
1476     if (!dvmGcStartup())
1477         goto fail;
1478     if (!dvmThreadStartup())
1479         goto fail;
1480     if (!dvmInlineNativeStartup())
1481         goto fail;
1482     if (!dvmVerificationStartup())
1483         goto fail;
1484     if (!dvmRegisterMapStartup())
1485         goto fail;
1486     if (!dvmInstanceofStartup())
1487         goto fail;
1488     if (!dvmClassStartup())
1489         goto fail;
1490
1491     /*
1492      * We leave gDvm.initializing set to "true" so that, if we're not
1493      * able to process the "core" classes, we don't go into a death-spin
1494      * trying to throw a "class not found" exception.
1495      */
1496
1497     return 0;
1498
1499 fail:
1500     dvmShutdown();
1501     return 1;
1502 }
1503
1504
1505 /*
1506  * All threads have stopped.  Finish the shutdown procedure.
1507  *
1508  * We can also be called if startup fails partway through, so be prepared
1509  * to deal with partially initialized data.
1510  *
1511  * Free any storage allocated in gGlobals.
1512  *
1513  * We can't dlclose() shared libs we've loaded, because it's possible a
1514  * thread not associated with the VM is running code in one.
1515  *
1516  * This is called from the JNI DestroyJavaVM function, which can be
1517  * called from any thread.  (In practice, this will usually run in the
1518  * same thread that started the VM, a/k/a the main thread, but we don't
1519  * want to assume that.)
1520  */
1521 void dvmShutdown(void)
1522 {
1523     LOGV("VM shutting down\n");
1524
1525     if (CALC_CACHE_STATS)
1526         dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1527
1528     /*
1529      * Stop our internal threads.
1530      */
1531     dvmHeapWorkerShutdown();
1532
1533     if (gDvm.jdwpState != NULL)
1534         dvmJdwpShutdown(gDvm.jdwpState);
1535     free(gDvm.jdwpHost);
1536     gDvm.jdwpHost = NULL;
1537     free(gDvm.stackTraceFile);
1538     gDvm.stackTraceFile = NULL;
1539
1540     /* tell signal catcher to shut down if it was started */
1541     dvmSignalCatcherShutdown();
1542
1543     /* shut down stdout/stderr conversion */
1544     dvmStdioConverterShutdown();
1545
1546 #ifdef WITH_JIT
1547     /* tell the compiler to shut down if it was started */
1548     dvmJitShutdown();
1549 #endif
1550
1551     /*
1552      * Kill any daemon threads that still exist.  Actively-running threads
1553      * are likely to crash the process if they continue to execute while
1554      * the VM shuts down.
1555      */
1556     dvmSlayDaemons();
1557
1558     LOGD("VM cleaning up\n");
1559
1560     dvmDebuggerShutdown();
1561     dvmReflectShutdown();
1562 #ifdef WITH_PROFILER
1563     dvmProfilingShutdown();
1564 #endif
1565     dvmJniShutdown();
1566     dvmStringInternShutdown();
1567     dvmExceptionShutdown();
1568     dvmThreadShutdown();
1569     dvmClassShutdown();
1570     dvmVerificationShutdown();
1571     dvmRegisterMapShutdown();
1572     dvmInstanceofShutdown();
1573     dvmInlineNativeShutdown();
1574     dvmGcShutdown();
1575     dvmAllocTrackerShutdown();
1576     dvmPropertiesShutdown();
1577
1578     /* these must happen AFTER dvmClassShutdown has walked through class data */
1579     dvmNativeShutdown();
1580     dvmInternalNativeShutdown();
1581
1582     free(gDvm.bootClassPathStr);
1583     free(gDvm.classPathStr);
1584
1585     freeAssertionCtrl();
1586
1587     /*
1588      * We want valgrind to report anything we forget to free as "definitely
1589      * lost".  If there's a pointer in the global chunk, it would be reported
1590      * as "still reachable".  Erasing the memory fixes this.
1591      *
1592      * This must be erased to zero if we want to restart the VM within this
1593      * process.
1594      */
1595     memset(&gDvm, 0xcd, sizeof(gDvm));
1596 }
1597
1598
1599 /*
1600  * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
1601  * one was specified.
1602  */
1603 int dvmFprintf(FILE* fp, const char* format, ...)
1604 {
1605     va_list args;
1606     int result;
1607
1608     va_start(args, format);
1609     if (gDvm.vfprintfHook != NULL)
1610         result = (*gDvm.vfprintfHook)(fp, format, args);
1611     else
1612         result = vfprintf(fp, format, args);
1613     va_end(args);
1614
1615     return result;
1616 }
1617
1618 /*
1619  * Abort the VM.  We get here on fatal errors.  Try very hard not to use
1620  * this; whenever possible, return an error to somebody responsible.
1621  */
1622 void dvmAbort(void)
1623 {
1624     LOGE("VM aborting\n");
1625
1626     fflush(NULL);       // flush all open file buffers
1627
1628     /* JNI-supplied abort hook gets right of first refusal */
1629     if (gDvm.abortHook != NULL)
1630         (*gDvm.abortHook)();
1631
1632     /*
1633      * If we call abort(), all threads in the process receives a SIBABRT.
1634      * debuggerd dumps the stack trace of the main thread, whether or not
1635      * that was the thread that failed.
1636      *
1637      * By stuffing a value into a bogus address, we cause a segmentation
1638      * fault in the current thread, and get a useful log from debuggerd.
1639      * We can also trivially tell the difference between a VM crash and
1640      * a deliberate abort by looking at the fault address.
1641      */
1642     *((char*)0xdeadd00d) = 38;
1643     abort();
1644
1645     /* notreached */
1646 }