OSDN Git Service

42901cf183dc8bdd08d17fbda15f7ddd8c4beda2
[android-x86/dalvik.git] / vm / Init.cpp
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 #define __STDC_LIMIT_MACROS
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <signal.h>
24 #include <limits.h>
25 #include <ctype.h>
26 #include <sys/mount.h>
27 #include <sys/wait.h>
28 #include <linux/fs.h>
29 #include <cutils/fs.h>
30 #include <unistd.h>
31 #ifdef HAVE_ANDROID_OS
32 #include <sys/prctl.h>
33 #endif
34
35 #include "Dalvik.h"
36 #include "test/Test.h"
37 #include "mterp/Mterp.h"
38 #include "Hash.h"
39 #include "JniConstants.h"
40
41 #if defined(WITH_JIT)
42 #include "compiler/codegen/Optimizer.h"
43 #endif
44
45 #define kMinHeapStartSize   (1*1024*1024)
46 #define kMinHeapSize        (2*1024*1024)
47 #define kMaxHeapSize        (1*1024*1024*1024)
48
49 /*
50  * Register VM-agnostic native methods for system classes.
51  */
52 extern int jniRegisterSystemMethods(JNIEnv* env);
53
54 /* fwd */
55 static bool registerSystemNatives(JNIEnv* pEnv);
56 static bool initJdwp();
57 static bool initZygote();
58
59
60 /* global state */
61 struct DvmGlobals gDvm;
62 struct DvmJniGlobals gDvmJni;
63
64 /* JIT-specific global state */
65 #if defined(WITH_JIT)
66 struct DvmJitGlobals gDvmJit;
67
68 #if defined(WITH_JIT_TUNING)
69 /*
70  * Track the number of hits in the inline cache for predicted chaining.
71  * Use an ugly global variable here since it is accessed in assembly code.
72  */
73 int gDvmICHitCount;
74 #endif
75
76 #endif
77
78 /*
79  * Show usage.
80  *
81  * We follow the tradition of unhyphenated compound words.
82  */
83 static void usage(const char* progName)
84 {
85     dvmFprintf(stderr, "%s: [options] class [argument ...]\n", progName);
86     dvmFprintf(stderr, "%s: [options] -jar file.jar [argument ...]\n",progName);
87     dvmFprintf(stderr, "\n");
88     dvmFprintf(stderr, "The following standard options are recognized:\n");
89     dvmFprintf(stderr, "  -classpath classpath\n");
90     dvmFprintf(stderr, "  -Dproperty=value\n");
91     dvmFprintf(stderr, "  -verbose:tag  ('gc', 'jni', or 'class')\n");
92     dvmFprintf(stderr, "  -ea[:<package name>... |:<class name>]\n");
93     dvmFprintf(stderr, "  -da[:<package name>... |:<class name>]\n");
94     dvmFprintf(stderr, "   (-enableassertions, -disableassertions)\n");
95     dvmFprintf(stderr, "  -esa\n");
96     dvmFprintf(stderr, "  -dsa\n");
97     dvmFprintf(stderr,
98                 "   (-enablesystemassertions, -disablesystemassertions)\n");
99     dvmFprintf(stderr, "  -showversion\n");
100     dvmFprintf(stderr, "  -help\n");
101     dvmFprintf(stderr, "\n");
102     dvmFprintf(stderr, "The following extended options are recognized:\n");
103     dvmFprintf(stderr, "  -Xrunjdwp:<options>\n");
104     dvmFprintf(stderr, "  -Xbootclasspath:bootclasspath\n");
105     dvmFprintf(stderr, "  -Xcheck:tag  (e.g. 'jni')\n");
106     dvmFprintf(stderr, "  -XmsN  (min heap, must be multiple of 1K, >= 1MB)\n");
107     dvmFprintf(stderr, "  -XmxN  (max heap, must be multiple of 1K, >= 2MB)\n");
108     dvmFprintf(stderr, "  -XssN  (stack size, >= %dKB, <= %dKB)\n",
109         kMinStackSize / 1024, kMaxStackSize / 1024);
110     dvmFprintf(stderr, "  -Xverify:{none,remote,all}\n");
111     dvmFprintf(stderr, "  -Xrs\n");
112 #if defined(WITH_JIT)
113     dvmFprintf(stderr,
114                 "  -Xint  (extended to accept ':portable', ':fast' and ':jit')\n");
115 #else
116     dvmFprintf(stderr,
117                 "  -Xint  (extended to accept ':portable' and ':fast')\n");
118 #endif
119     dvmFprintf(stderr, "\n");
120     dvmFprintf(stderr, "These are unique to Dalvik:\n");
121     dvmFprintf(stderr, "  -Xzygote\n");
122     dvmFprintf(stderr, "  -Xdexopt:{none,verified,all,full}\n");
123     dvmFprintf(stderr, "  -Xnoquithandler\n");
124     dvmFprintf(stderr,
125                 "  -Xjnigreflimit:N  (must be multiple of 100, >= 200)\n");
126     dvmFprintf(stderr, "  -Xjniopts:{warnonly,forcecopy}\n");
127     dvmFprintf(stderr, "  -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
128     dvmFprintf(stderr, "  -Xstacktracefile:<filename>\n");
129     dvmFprintf(stderr, "  -Xgc:[no]precise\n");
130     dvmFprintf(stderr, "  -Xgc:[no]preverify\n");
131     dvmFprintf(stderr, "  -Xgc:[no]postverify\n");
132     dvmFprintf(stderr, "  -Xgc:[no]concurrent\n");
133     dvmFprintf(stderr, "  -Xgc:[no]verifycardtable\n");
134     dvmFprintf(stderr, "  -XX:+DisableExplicitGC\n");
135     dvmFprintf(stderr, "  -X[no]genregmap\n");
136     dvmFprintf(stderr, "  -Xverifyopt:[no]checkmon\n");
137     dvmFprintf(stderr, "  -Xcheckdexsum\n");
138 #if defined(WITH_JIT)
139     dvmFprintf(stderr, "  -Xincludeselectedop\n");
140     dvmFprintf(stderr, "  -Xjitop:hexopvalue[-endvalue]"
141                        "[,hexopvalue[-endvalue]]*\n");
142     dvmFprintf(stderr, "  -Xincludeselectedmethod\n");
143     dvmFprintf(stderr, "  -Xjitthreshold:decimalvalue\n");
144     dvmFprintf(stderr, "  -Xjitblocking\n");
145     dvmFprintf(stderr, "  -Xjitmethod:signature[,signature]* "
146                        "(eg Ljava/lang/String\\;replace)\n");
147     dvmFprintf(stderr, "  -Xjitclass:classname[,classname]*\n");
148     dvmFprintf(stderr, "  -Xjitoffset:offset[,offset]\n");
149     dvmFprintf(stderr, "  -Xjitconfig:filename\n");
150     dvmFprintf(stderr, "  -Xjitcheckcg\n");
151     dvmFprintf(stderr, "  -Xjitverbose\n");
152     dvmFprintf(stderr, "  -Xjitprofile\n");
153     dvmFprintf(stderr, "  -Xjitdisableopt\n");
154     dvmFprintf(stderr, "  -Xjitsuspendpoll\n");
155 #endif
156     dvmFprintf(stderr, "\n");
157     dvmFprintf(stderr, "Configured with:"
158         " debugger"
159         " profiler"
160         " hprof"
161 #ifdef WITH_TRACKREF_CHECKS
162         " trackref_checks"
163 #endif
164 #ifdef WITH_INSTR_CHECKS
165         " instr_checks"
166 #endif
167 #ifdef WITH_EXTRA_OBJECT_VALIDATION
168         " extra_object_validation"
169 #endif
170 #ifdef WITH_EXTRA_GC_CHECKS
171         " extra_gc_checks"
172 #endif
173 #if !defined(NDEBUG) && defined(WITH_DALVIK_ASSERT)
174         " dalvik_assert"
175 #endif
176 #ifdef WITH_JNI_STACK_CHECK
177         " jni_stack_check"
178 #endif
179 #ifdef EASY_GDB
180         " easy_gdb"
181 #endif
182 #ifdef CHECK_MUTEX
183         " check_mutex"
184 #endif
185 #if defined(WITH_JIT)
186         " jit(" ARCH_VARIANT ")"
187 #endif
188 #if defined(WITH_SELF_VERIFICATION)
189         " self_verification"
190 #endif
191 #if ANDROID_SMP != 0
192         " smp"
193 #endif
194     );
195 #ifdef DVM_SHOW_EXCEPTION
196     dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
197 #endif
198     dvmFprintf(stderr, "\n\n");
199 }
200
201 /*
202  * Show helpful information on JDWP options.
203  */
204 static void showJdwpHelp()
205 {
206     dvmFprintf(stderr,
207         "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
208     dvmFprintf(stderr,
209         "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
210 }
211
212 /*
213  * Show version and copyright info.
214  */
215 static void showVersion()
216 {
217     dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
218         DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
219     dvmFprintf(stdout,
220         "Copyright (C) 2007 The Android Open Source Project\n\n"
221         "This software is built from source code licensed under the "
222         "Apache License,\n"
223         "Version 2.0 (the \"License\"). You may obtain a copy of the "
224         "License at\n\n"
225         "     http://www.apache.org/licenses/LICENSE-2.0\n\n"
226         "See the associated NOTICE file for this software for further "
227         "details.\n");
228 }
229
230 /*
231  * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
232  * memory sizes.  [kK] indicates kilobytes, [mM] megabytes, and
233  * [gG] gigabytes.
234  *
235  * "s" should point just past the "-Xm?" part of the string.
236  * "min" specifies the lowest acceptable value described by "s".
237  * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
238  * of 1024.
239  *
240  * The spec says the -Xmx and -Xms options must be multiples of 1024.  It
241  * doesn't say anything about -Xss.
242  *
243  * Returns 0 (a useless size) if "s" is malformed or specifies a low or
244  * non-evenly-divisible value.
245  */
246 static size_t parseMemOption(const char* s, size_t div)
247 {
248     /* strtoul accepts a leading [+-], which we don't want,
249      * so make sure our string starts with a decimal digit.
250      */
251     if (isdigit(*s)) {
252         const char* s2;
253         size_t val;
254
255         val = strtoul(s, (char* *)&s2, 10);
256         if (s2 != s) {
257             /* s2 should be pointing just after the number.
258              * If this is the end of the string, the user
259              * has specified a number of bytes.  Otherwise,
260              * there should be exactly one more character
261              * that specifies a multiplier.
262              */
263             if (*s2 != '\0') {
264                 char c;
265
266                 /* The remainder of the string is either a single multiplier
267                  * character, or nothing to indicate that the value is in
268                  * bytes.
269                  */
270                 c = *s2++;
271                 if (*s2 == '\0') {
272                     size_t mul;
273
274                     if (c == '\0') {
275                         mul = 1;
276                     } else if (c == 'k' || c == 'K') {
277                         mul = 1024;
278                     } else if (c == 'm' || c == 'M') {
279                         mul = 1024 * 1024;
280                     } else if (c == 'g' || c == 'G') {
281                         mul = 1024 * 1024 * 1024;
282                     } else {
283                         /* Unknown multiplier character.
284                          */
285                         return 0;
286                     }
287
288                     if (val <= SIZE_MAX / mul) {
289                         val *= mul;
290                     } else {
291                         /* Clamp to a multiple of 1024.
292                          */
293                         val = SIZE_MAX & ~(1024-1);
294                     }
295                 } else {
296                     /* There's more than one character after the
297                      * numeric part.
298                      */
299                     return 0;
300                 }
301             }
302
303             /* The man page says that a -Xm value must be
304              * a multiple of 1024.
305              */
306             if (val % div == 0) {
307                 return val;
308             }
309         }
310     }
311
312     return 0;
313 }
314
315 /*
316  * Handle one of the JDWP name/value pairs.
317  *
318  * JDWP options are:
319  *  help: if specified, show help message and bail
320  *  transport: may be dt_socket or dt_shmem
321  *  address: for dt_socket, "host:port", or just "port" when listening
322  *  server: if "y", wait for debugger to attach; if "n", attach to debugger
323  *  timeout: how long to wait for debugger to connect / listen
324  *
325  * Useful with server=n (these aren't supported yet):
326  *  onthrow=<exception-name>: connect to debugger when exception thrown
327  *  onuncaught=y|n: connect to debugger when uncaught exception thrown
328  *  launch=<command-line>: launch the debugger itself
329  *
330  * The "transport" option is required, as is "address" if server=n.
331  */
332 static bool handleJdwpOption(const char* name, const char* value)
333 {
334     if (strcmp(name, "transport") == 0) {
335         if (strcmp(value, "dt_socket") == 0) {
336             gDvm.jdwpTransport = kJdwpTransportSocket;
337         } else if (strcmp(value, "dt_android_adb") == 0) {
338             gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
339         } else {
340             ALOGE("JDWP transport '%s' not supported", value);
341             return false;
342         }
343     } else if (strcmp(name, "server") == 0) {
344         if (*value == 'n')
345             gDvm.jdwpServer = false;
346         else if (*value == 'y')
347             gDvm.jdwpServer = true;
348         else {
349             ALOGE("JDWP option 'server' must be 'y' or 'n'");
350             return false;
351         }
352     } else if (strcmp(name, "suspend") == 0) {
353         if (*value == 'n')
354             gDvm.jdwpSuspend = false;
355         else if (*value == 'y')
356             gDvm.jdwpSuspend = true;
357         else {
358             ALOGE("JDWP option 'suspend' must be 'y' or 'n'");
359             return false;
360         }
361     } else if (strcmp(name, "address") == 0) {
362         /* this is either <port> or <host>:<port> */
363         const char* colon = strchr(value, ':');
364         char* end;
365         long port;
366
367         if (colon != NULL) {
368             free(gDvm.jdwpHost);
369             gDvm.jdwpHost = (char*) malloc(colon - value +1);
370             strncpy(gDvm.jdwpHost, value, colon - value +1);
371             gDvm.jdwpHost[colon-value] = '\0';
372             value = colon + 1;
373         }
374         if (*value == '\0') {
375             ALOGE("JDWP address missing port");
376             return false;
377         }
378         port = strtol(value, &end, 10);
379         if (*end != '\0') {
380             ALOGE("JDWP address has junk in port field '%s'", value);
381             return false;
382         }
383         gDvm.jdwpPort = port;
384     } else if (strcmp(name, "launch") == 0 ||
385                strcmp(name, "onthrow") == 0 ||
386                strcmp(name, "oncaught") == 0 ||
387                strcmp(name, "timeout") == 0)
388     {
389         /* valid but unsupported */
390         ALOGI("Ignoring JDWP option '%s'='%s'", name, value);
391     } else {
392         ALOGI("Ignoring unrecognized JDWP option '%s'='%s'", name, value);
393     }
394
395     return true;
396 }
397
398 /*
399  * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
400  * "transport=dt_socket,address=8000,server=y,suspend=n"
401  */
402 static bool parseJdwpOptions(const char* str)
403 {
404     char* mangle = strdup(str);
405     char* name = mangle;
406     bool result = false;
407
408     /*
409      * Process all of the name=value pairs.
410      */
411     while (true) {
412         char* value;
413         char* comma;
414
415         value = strchr(name, '=');
416         if (value == NULL) {
417             ALOGE("JDWP opts: garbage at '%s'", name);
418             goto bail;
419         }
420
421         comma = strchr(name, ',');      // use name, not value, for safety
422         if (comma != NULL) {
423             if (comma < value) {
424                 ALOGE("JDWP opts: found comma before '=' in '%s'", mangle);
425                 goto bail;
426             }
427             *comma = '\0';
428         }
429
430         *value++ = '\0';        // stomp the '='
431
432         if (!handleJdwpOption(name, value))
433             goto bail;
434
435         if (comma == NULL) {
436             /* out of options */
437             break;
438         }
439         name = comma+1;
440     }
441
442     /*
443      * Make sure the combination of arguments makes sense.
444      */
445     if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
446         ALOGE("JDWP opts: must specify transport");
447         goto bail;
448     }
449     if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
450         ALOGE("JDWP opts: when server=n, must specify host and port");
451         goto bail;
452     }
453     // transport mandatory
454     // outbound server address
455
456     gDvm.jdwpConfigured = true;
457     result = true;
458
459 bail:
460     free(mangle);
461     return result;
462 }
463
464 /*
465  * Handle one of the four kinds of assertion arguments.
466  *
467  * "pkgOrClass" is the last part of an enable/disable line.  For a package
468  * the arg looks like "-ea:com.google.fubar...", for a class it looks
469  * like "-ea:com.google.fubar.Wahoo".  The string we get starts at the ':'.
470  *
471  * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
472  *
473  * Multiple instances of these arguments can be specified, e.g. you can
474  * enable assertions for a package and then disable them for one class in
475  * the package.
476  */
477 static bool enableAssertions(const char* pkgOrClass, bool enable)
478 {
479     AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
480     pCtrl->enable = enable;
481
482     if (pkgOrClass == NULL) {
483         /* enable or disable for all system classes */
484         pCtrl->isPackage = false;
485         pCtrl->pkgOrClass = NULL;
486         pCtrl->pkgOrClassLen = 0;
487     } else {
488         if (*pkgOrClass == '\0') {
489             /* global enable/disable for all but system */
490             pCtrl->isPackage = false;
491             pCtrl->pkgOrClass = strdup("");
492             pCtrl->pkgOrClassLen = 0;
493         } else {
494             pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1);    // skip ':'
495             if (pCtrl->pkgOrClass == NULL) {
496                 /* can happen if class name includes an illegal '/' */
497                 ALOGW("Unable to process assertion arg '%s'", pkgOrClass);
498                 return false;
499             }
500
501             int len = strlen(pCtrl->pkgOrClass);
502             if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
503                 /* mark as package, truncate two of the three slashes */
504                 pCtrl->isPackage = true;
505                 *(pCtrl->pkgOrClass + len-2) = '\0';
506                 pCtrl->pkgOrClassLen = len - 2;
507             } else {
508                 /* just a class */
509                 pCtrl->isPackage = false;
510                 pCtrl->pkgOrClassLen = len;
511             }
512         }
513     }
514
515     return true;
516 }
517
518 /*
519  * Turn assertions on when requested to do so by the Zygote.
520  *
521  * This is a bit sketchy.  We can't (easily) go back and fiddle with all
522  * of the classes that have already been initialized, so this only
523  * affects classes that have yet to be loaded.  If some or all assertions
524  * have been enabled through some other means, we don't want to mess with
525  * it here, so we do nothing.  Finally, we assume that there's room in
526  * "assertionCtrl" to hold at least one entry; this is guaranteed by the
527  * allocator.
528  *
529  * This must only be called from the main thread during zygote init.
530  */
531 void dvmLateEnableAssertions()
532 {
533     if (gDvm.assertionCtrl == NULL) {
534         ALOGD("Not late-enabling assertions: no assertionCtrl array");
535         return;
536     } else if (gDvm.assertionCtrlCount != 0) {
537         ALOGD("Not late-enabling assertions: some asserts already configured");
538         return;
539     }
540     ALOGD("Late-enabling assertions");
541
542     /* global enable for all but system */
543     AssertionControl* pCtrl = gDvm.assertionCtrl;
544     pCtrl->pkgOrClass = strdup("");
545     pCtrl->pkgOrClassLen = 0;
546     pCtrl->isPackage = false;
547     pCtrl->enable = true;
548     gDvm.assertionCtrlCount = 1;
549 }
550
551
552 /*
553  * Release memory associated with the AssertionCtrl array.
554  */
555 static void freeAssertionCtrl()
556 {
557     int i;
558
559     for (i = 0; i < gDvm.assertionCtrlCount; i++)
560         free(gDvm.assertionCtrl[i].pkgOrClass);
561     free(gDvm.assertionCtrl);
562 }
563
564 #if defined(WITH_JIT)
565 /* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
566 static void processXjitop(const char* opt)
567 {
568     if (opt[7] == ':') {
569         const char* startPtr = &opt[8];
570         char* endPtr = NULL;
571
572         do {
573             long startValue, endValue;
574
575             startValue = strtol(startPtr, &endPtr, 16);
576             if (startPtr != endPtr) {
577                 /* Just in case value is out of range */
578                 startValue %= kNumPackedOpcodes;
579
580                 if (*endPtr == '-') {
581                     endValue = strtol(endPtr+1, &endPtr, 16);
582                     endValue %= kNumPackedOpcodes;
583                 } else {
584                     endValue = startValue;
585                 }
586
587                 for (; startValue <= endValue; startValue++) {
588                     ALOGW("Dalvik opcode %x is selected for debugging",
589                          (unsigned int) startValue);
590                     /* Mark the corresponding bit to 1 */
591                     gDvmJit.opList[startValue >> 3] |= 1 << (startValue & 0x7);
592                 }
593
594                 if (*endPtr == 0) {
595                     break;
596                 }
597
598                 startPtr = endPtr + 1;
599
600                 continue;
601             } else {
602                 if (*endPtr != 0) {
603                     dvmFprintf(stderr,
604                         "Warning: Unrecognized opcode value substring "
605                         "%s\n", endPtr);
606                 }
607                 break;
608             }
609         } while (1);
610     } else {
611         int i;
612         for (i = 0; i < (kNumPackedOpcodes+7)/8; i++) {
613             gDvmJit.opList[i] = 0xff;
614         }
615         dvmFprintf(stderr, "Warning: select all opcodes\n");
616     }
617 }
618
619 /* Parse -Xjitoffset to selectively turn on/off traces with certain offsets for JIT */
620 static void processXjitoffset(const char* opt) {
621     gDvmJit.num_entries_pcTable = 0;
622     char* buf = strdup(opt);
623     char* start, *end;
624     start = buf;
625     int idx = 0;
626     do {
627         end = strchr(start, ',');
628         if (end) {
629             *end = 0;
630         }
631
632         dvmFprintf(stderr, "processXjitoffset start = %s\n", start);
633         char* tmp = strdup(start);
634         gDvmJit.pcTable[idx++] = atoi(tmp);
635         free(tmp);
636         if (idx >= COMPILER_PC_OFFSET_SIZE) {
637             dvmFprintf(stderr, "processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
638             break;
639         }
640         if (end) {
641             start = end + 1;
642         } else {
643             break;
644         }
645     } while (1);
646     gDvmJit.num_entries_pcTable = idx;
647     free(buf);
648 }
649
650 /* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
651 static void processXjitmethod(const char* opt, bool isMethod) {
652     char* buf = strdup(opt);
653
654     if (isMethod && gDvmJit.methodTable == NULL) {
655         gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
656     }
657     if (!isMethod && gDvmJit.classTable == NULL) {
658         gDvmJit.classTable = dvmHashTableCreate(8, NULL);
659     }
660
661     char* start = buf;
662     char* end;
663     /*
664      * Break comma-separated method signatures and enter them into the hash
665      * table individually.
666      */
667     do {
668         int hashValue;
669
670         end = strchr(start, ',');
671         if (end) {
672             *end = 0;
673         }
674
675         hashValue = dvmComputeUtf8Hash(start);
676         dvmHashTableLookup(isMethod ? gDvmJit.methodTable : gDvmJit.classTable,
677                            hashValue, strdup(start), (HashCompareFunc) strcmp, true);
678
679         if (end) {
680             start = end + 1;
681         } else {
682             break;
683         }
684     } while (1);
685     free(buf);
686 }
687
688 /* The format of jit_config.list:
689    EXCLUDE or INCLUDE
690    CLASS
691    prefix1 ...
692    METHOD
693    prefix 1 ...
694    OFFSET
695    index ... //each pair is a range, if pcOff falls into a range, JIT
696 */
697 static int processXjitconfig(const char* opt) {
698    FILE* fp = fopen(opt, "r");
699    if (fp == NULL) {
700        return -1;
701    }
702
703    char fLine[500];
704    bool startClass = false, startMethod = false, startOffset = false;
705    gDvmJit.num_entries_pcTable = 0;
706    int idx = 0;
707
708    while (fgets(fLine, 500, fp) != NULL) {
709        char* curLine = strtok(fLine, " \t\r\n");
710        /* handles keyword CLASS, METHOD, INCLUDE, EXCLUDE */
711        if (!strncmp(curLine, "CLASS", 5)) {
712            startClass = true;
713            startMethod = false;
714            startOffset = false;
715            continue;
716        }
717        if (!strncmp(curLine, "METHOD", 6)) {
718            startMethod = true;
719            startClass = false;
720            startOffset = false;
721            continue;
722        }
723        if (!strncmp(curLine, "OFFSET", 6)) {
724            startOffset = true;
725            startMethod = false;
726            startClass = false;
727            continue;
728        }
729        if (!strncmp(curLine, "EXCLUDE", 7)) {
730           gDvmJit.includeSelectedMethod = false;
731           continue;
732        }
733        if (!strncmp(curLine, "INCLUDE", 7)) {
734           gDvmJit.includeSelectedMethod = true;
735           continue;
736        }
737        if (!startMethod && !startClass && !startOffset) {
738          continue;
739        }
740
741         int hashValue = dvmComputeUtf8Hash(curLine);
742         if (startMethod) {
743             if (gDvmJit.methodTable == NULL) {
744                 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
745             }
746             dvmHashTableLookup(gDvmJit.methodTable, hashValue,
747                                strdup(curLine),
748                                (HashCompareFunc) strcmp, true);
749         } else if (startClass) {
750             if (gDvmJit.classTable == NULL) {
751                 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
752             }
753             dvmHashTableLookup(gDvmJit.classTable, hashValue,
754                                strdup(curLine),
755                                (HashCompareFunc) strcmp, true);
756         } else if (startOffset) {
757            int tmpInt = atoi(curLine);
758            gDvmJit.pcTable[idx++] = tmpInt;
759            if (idx >= COMPILER_PC_OFFSET_SIZE) {
760                printf("processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
761                break;
762            }
763         }
764    }
765    gDvmJit.num_entries_pcTable = idx;
766    fclose(fp);
767    return 0;
768 }
769 #endif
770
771 /*
772  * Process an argument vector full of options.  Unlike standard C programs,
773  * argv[0] does not contain the name of the program.
774  *
775  * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
776  * that we don't recognize.  Otherwise, we return with an error as soon as
777  * we see anything we can't identify.
778  *
779  * Returns 0 on success, -1 on failure, and 1 for the special case of
780  * "-version" where we want to stop without showing an error message.
781  */
782 static int processOptions(int argc, const char* const argv[],
783     bool ignoreUnrecognized)
784 {
785     int i;
786
787     ALOGV("VM options (%d):", argc);
788     for (i = 0; i < argc; i++)
789         ALOGV("  %d: '%s'", i, argv[i]);
790
791     /*
792      * Over-allocate AssertionControl array for convenience.  If allocated,
793      * the array must be able to hold at least one entry, so that the
794      * zygote-time activation can do its business.
795      */
796     assert(gDvm.assertionCtrl == NULL);
797     if (argc > 0) {
798         gDvm.assertionCtrl =
799             (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
800         if (gDvm.assertionCtrl == NULL)
801             return -1;
802         assert(gDvm.assertionCtrlCount == 0);
803     }
804
805     for (i = 0; i < argc; i++) {
806         if (strcmp(argv[i], "-help") == 0) {
807             /* show usage and stop */
808             return -1;
809
810         } else if (strcmp(argv[i], "-version") == 0) {
811             /* show version and stop */
812             showVersion();
813             return 1;
814         } else if (strcmp(argv[i], "-showversion") == 0) {
815             /* show version and continue */
816             showVersion();
817
818         } else if (strcmp(argv[i], "-classpath") == 0 ||
819                    strcmp(argv[i], "-cp") == 0)
820         {
821             /* set classpath */
822             if (i == argc-1) {
823                 dvmFprintf(stderr, "Missing classpath path list\n");
824                 return -1;
825             }
826             free(gDvm.classPathStr); /* in case we have compiled-in default */
827             gDvm.classPathStr = strdup(argv[++i]);
828
829         } else if (strncmp(argv[i], "-Xbootclasspath:",
830                 sizeof("-Xbootclasspath:")-1) == 0)
831         {
832             /* set bootclasspath */
833             const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
834
835             if (*path == '\0') {
836                 dvmFprintf(stderr, "Missing bootclasspath path list\n");
837                 return -1;
838             }
839             free(gDvm.bootClassPathStr);
840             gDvm.bootClassPathStr = strdup(path);
841
842         } else if (strncmp(argv[i], "-Xbootclasspath/a:",
843                 sizeof("-Xbootclasspath/a:")-1) == 0) {
844             const char* appPath = argv[i] + sizeof("-Xbootclasspath/a:")-1;
845
846             if (*(appPath) == '\0') {
847                 dvmFprintf(stderr, "Missing appending bootclasspath path list\n");
848                 return -1;
849             }
850             char* allPath;
851
852             if (asprintf(&allPath, "%s:%s", gDvm.bootClassPathStr, appPath) < 0) {
853                 dvmFprintf(stderr, "Can't append to bootclasspath path list\n");
854                 return -1;
855             }
856             free(gDvm.bootClassPathStr);
857             gDvm.bootClassPathStr = allPath;
858
859         } else if (strncmp(argv[i], "-Xbootclasspath/p:",
860                 sizeof("-Xbootclasspath/p:")-1) == 0) {
861             const char* prePath = argv[i] + sizeof("-Xbootclasspath/p:")-1;
862
863             if (*(prePath) == '\0') {
864                 dvmFprintf(stderr, "Missing prepending bootclasspath path list\n");
865                 return -1;
866             }
867             char* allPath;
868
869             if (asprintf(&allPath, "%s:%s", prePath, gDvm.bootClassPathStr) < 0) {
870                 dvmFprintf(stderr, "Can't prepend to bootclasspath path list\n");
871                 return -1;
872             }
873             free(gDvm.bootClassPathStr);
874             gDvm.bootClassPathStr = allPath;
875
876         } else if (strncmp(argv[i], "-D", 2) == 0) {
877             /* Properties are handled in managed code. We just check syntax. */
878             if (strchr(argv[i], '=') == NULL) {
879                 dvmFprintf(stderr, "Bad system property setting: \"%s\"\n",
880                     argv[i]);
881                 return -1;
882             }
883             gDvm.properties->push_back(argv[i] + 2);
884
885         } else if (strcmp(argv[i], "-jar") == 0) {
886             // TODO: handle this; name of jar should be in argv[i+1]
887             dvmFprintf(stderr, "-jar not yet handled\n");
888             assert(false);
889
890         } else if (strncmp(argv[i], "-Xms", 4) == 0) {
891             size_t val = parseMemOption(argv[i]+4, 1024);
892             if (val != 0) {
893                 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
894                     gDvm.heapStartingSize = val;
895                 } else {
896                     dvmFprintf(stderr,
897                         "Invalid -Xms '%s', range is %dKB to %dKB\n",
898                         argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
899                     return -1;
900                 }
901             } else {
902                 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
903                 return -1;
904             }
905         } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
906             size_t val = parseMemOption(argv[i]+4, 1024);
907             if (val != 0) {
908                 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
909                     gDvm.heapMaximumSize = val;
910                 } else {
911                     dvmFprintf(stderr,
912                         "Invalid -Xmx '%s', range is %dKB to %dKB\n",
913                         argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
914                     return -1;
915                 }
916             } else {
917                 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
918                 return -1;
919             }
920         } else if (strncmp(argv[i], "-XX:HeapGrowthLimit=", 20) == 0) {
921             size_t val = parseMemOption(argv[i] + 20, 1024);
922             if (val != 0) {
923                 gDvm.heapGrowthLimit = val;
924             } else {
925                 dvmFprintf(stderr, "Invalid -XX:HeapGrowthLimit option '%s'\n", argv[i]);
926                 return -1;
927             }
928         } else if (strncmp(argv[i], "-XX:HeapMinFree=", 16) == 0) {
929             size_t val = parseMemOption(argv[i] + 16, 1024);
930             if (val != 0) {
931                 gDvm.heapMinFree = val;
932             } else {
933                 dvmFprintf(stderr, "Invalid -XX:HeapMinFree option '%s'\n", argv[i]);
934                 return -1;
935             }
936         } else if (strncmp(argv[i], "-XX:HeapMaxFree=", 16) == 0) {
937             size_t val = parseMemOption(argv[i] + 16, 1024);
938             if (val != 0) {
939                 gDvm.heapMaxFree = val;
940             } else {
941                 dvmFprintf(stderr, "Invalid -XX:HeapMaxFree option '%s'\n", argv[i]);
942                 return -1;
943             }
944         } else if (strncmp(argv[i], "-XX:HeapTargetUtilization=", 26) == 0) {
945             const char* start = argv[i] + 26;
946             const char* end = start;
947             double val = strtod(start, const_cast<char**>(&end));
948             // Ensure that we have a value, there was no cruft after it and it
949             // satisfies a sensible range.
950             bool sane_val = (start != end) && (end[0] == '\0') &&
951                 (val >= 0.1) && (val <= 0.9);
952             if (sane_val) {
953                 gDvm.heapTargetUtilization = val;
954             } else {
955                 dvmFprintf(stderr, "Invalid -XX:HeapTargetUtilization option '%s'\n", argv[i]);
956                 return -1;
957             }
958         } else if (strncmp(argv[i], "-Xss", 4) == 0) {
959             size_t val = parseMemOption(argv[i]+4, 1);
960             if (val != 0) {
961                 if (val >= kMinStackSize && val <= kMaxStackSize) {
962                     gDvm.stackSize = val;
963                     if (val > gDvm.mainThreadStackSize) {
964                         gDvm.mainThreadStackSize = val;
965                     }
966                 } else {
967                     dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
968                         argv[i], kMinStackSize, kMaxStackSize);
969                     return -1;
970                 }
971             } else {
972                 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
973                 return -1;
974             }
975
976         } else if (strncmp(argv[i], "-XX:mainThreadStackSize=", strlen("-XX:mainThreadStackSize=")) == 0) {
977             size_t val = parseMemOption(argv[i] + strlen("-XX:mainThreadStackSize="), 1);
978             if (val != 0) {
979                 if (val >= kMinStackSize && val <= kMaxStackSize) {
980                     gDvm.mainThreadStackSize = val;
981                 } else {
982                     dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize '%s', range is %d to %d\n",
983                                argv[i], kMinStackSize, kMaxStackSize);
984                     return -1;
985                 }
986             } else {
987                 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize option '%s'\n", argv[i]);
988                 return -1;
989             }
990
991         } else if (strncmp(argv[i], "-XX:+DisableExplicitGC", 22) == 0) {
992             gDvm.disableExplicitGc = true;
993         } else if (strcmp(argv[i], "-verbose") == 0 ||
994             strcmp(argv[i], "-verbose:class") == 0)
995         {
996             // JNI spec says "-verbose:gc,class" is valid, but cmd line
997             // doesn't work that way; may want to support.
998             gDvm.verboseClass = true;
999         } else if (strcmp(argv[i], "-verbose:jni") == 0) {
1000             gDvm.verboseJni = true;
1001         } else if (strcmp(argv[i], "-verbose:gc") == 0) {
1002             gDvm.verboseGc = true;
1003         } else if (strcmp(argv[i], "-verbose:shutdown") == 0) {
1004             gDvm.verboseShutdown = true;
1005
1006         } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
1007             enableAssertions(argv[i] + 17, true);
1008         } else if (strncmp(argv[i], "-ea", 3) == 0) {
1009             enableAssertions(argv[i] + 3, true);
1010         } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
1011             enableAssertions(argv[i] + 18, false);
1012         } else if (strncmp(argv[i], "-da", 3) == 0) {
1013             enableAssertions(argv[i] + 3, false);
1014         } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
1015                    strcmp(argv[i], "-esa") == 0)
1016         {
1017             enableAssertions(NULL, true);
1018         } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
1019                    strcmp(argv[i], "-dsa") == 0)
1020         {
1021             enableAssertions(NULL, false);
1022
1023         } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
1024             /* nothing to do now -- was handled during JNI init */
1025
1026         } else if (strcmp(argv[i], "-Xdebug") == 0) {
1027             /* accept but ignore */
1028
1029         } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
1030             strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
1031         {
1032             const char* tail;
1033
1034             if (argv[i][1] == 'X')
1035                 tail = argv[i] + 10;
1036             else
1037                 tail = argv[i] + 15;
1038
1039             if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
1040                 showJdwpHelp();
1041                 return 1;
1042             }
1043         } else if (strcmp(argv[i], "-Xrs") == 0) {
1044             gDvm.reduceSignals = true;
1045         } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
1046             /* disables SIGQUIT handler thread while still blocking SIGQUIT */
1047             /* (useful if we don't want thread but system still signals us) */
1048             gDvm.noQuitHandler = true;
1049         } else if (strcmp(argv[i], "-Xzygote") == 0) {
1050             gDvm.zygote = true;
1051 #if defined(WITH_JIT)
1052             gDvmJit.runningInAndroidFramework = true;
1053 #endif
1054         } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
1055             if (strcmp(argv[i] + 9, "none") == 0)
1056                 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
1057             else if (strcmp(argv[i] + 9, "verified") == 0)
1058                 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1059             else if (strcmp(argv[i] + 9, "all") == 0)
1060                 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
1061             else if (strcmp(argv[i] + 9, "full") == 0)
1062                 gDvm.dexOptMode = OPTIMIZE_MODE_FULL;
1063             else {
1064                 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
1065                 return -1;
1066             }
1067         } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
1068             if (strcmp(argv[i] + 9, "none") == 0)
1069                 gDvm.classVerifyMode = VERIFY_MODE_NONE;
1070             else if (strcmp(argv[i] + 9, "remote") == 0)
1071                 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
1072             else if (strcmp(argv[i] + 9, "all") == 0)
1073                 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1074             else {
1075                 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
1076                 return -1;
1077             }
1078         } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
1079             int lim = atoi(argv[i] + 15);
1080             if (lim < 200 || (lim % 100) != 0) {
1081                 dvmFprintf(stderr, "Bad value for -Xjnigreflimit: '%s'\n",
1082                     argv[i]+15);
1083                 return -1;
1084             }
1085             gDvm.jniGrefLimit = lim;
1086         } else if (strncmp(argv[i], "-Xjnitrace:", 11) == 0) {
1087             gDvm.jniTrace = strdup(argv[i] + 11);
1088         } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
1089             gDvm.logStdio = true;
1090
1091         } else if (strncmp(argv[i], "-Xint", 5) == 0) {
1092             if (argv[i][5] == ':') {
1093                 if (strcmp(argv[i] + 6, "portable") == 0)
1094                     gDvm.executionMode = kExecutionModeInterpPortable;
1095                 else if (strcmp(argv[i] + 6, "fast") == 0)
1096                     gDvm.executionMode = kExecutionModeInterpFast;
1097 #ifdef WITH_JIT
1098                 else if (strcmp(argv[i] + 6, "jit") == 0)
1099                     gDvm.executionMode = kExecutionModeJit;
1100 #endif
1101                 else {
1102                     dvmFprintf(stderr,
1103                         "Warning: Unrecognized interpreter mode %s\n",argv[i]);
1104                     /* keep going */
1105                 }
1106             } else {
1107                 /* disable JIT if it was enabled by default */
1108                 gDvm.executionMode = kExecutionModeInterpFast;
1109             }
1110
1111         } else if (strncmp(argv[i], "-Xlockprofthreshold:", 20) == 0) {
1112             gDvm.lockProfThreshold = atoi(argv[i] + 20);
1113
1114 #ifdef WITH_JIT
1115         } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
1116             processXjitop(argv[i]);
1117         } else if (strncmp(argv[i], "-Xjitmethod:", 12) == 0) {
1118             processXjitmethod(argv[i] + strlen("-Xjitmethod:"), true);
1119         } else if (strncmp(argv[i], "-Xjitclass:", 11) == 0) {
1120             processXjitmethod(argv[i] + strlen("-Xjitclass:"), false);
1121         } else if (strncmp(argv[i], "-Xjitoffset:", 12) == 0) {
1122             processXjitoffset(argv[i] + strlen("-Xjitoffset:"));
1123         } else if (strncmp(argv[i], "-Xjitconfig:", 12) == 0) {
1124             processXjitconfig(argv[i] + strlen("-Xjitconfig:"));
1125         } else if (strncmp(argv[i], "-Xjitblocking", 13) == 0) {
1126           gDvmJit.blockingMode = true;
1127         } else if (strncmp(argv[i], "-Xjitthreshold:", 15) == 0) {
1128           gDvmJit.threshold = atoi(argv[i] + 15);
1129         } else if (strncmp(argv[i], "-Xincludeselectedop", 19) == 0) {
1130           gDvmJit.includeSelectedOp = true;
1131         } else if (strncmp(argv[i], "-Xincludeselectedmethod", 23) == 0) {
1132           gDvmJit.includeSelectedMethod = true;
1133         } else if (strncmp(argv[i], "-Xjitcheckcg", 12) == 0) {
1134           gDvmJit.checkCallGraph = true;
1135           /* Need to enable blocking mode due to stack crawling */
1136           gDvmJit.blockingMode = true;
1137         } else if (strncmp(argv[i], "-Xjitdumpbin", 12) == 0) {
1138           gDvmJit.printBinary = true;
1139         } else if (strncmp(argv[i], "-Xjitverbose", 12) == 0) {
1140           gDvmJit.printMe = true;
1141         } else if (strncmp(argv[i], "-Xjitprofile", 12) == 0) {
1142           gDvmJit.profileMode = kTraceProfilingContinuous;
1143         } else if (strncmp(argv[i], "-Xjitdisableopt", 15) == 0) {
1144           /* Disable selected optimizations */
1145           if (argv[i][15] == ':') {
1146               sscanf(argv[i] + 16, "%x", &gDvmJit.disableOpt);
1147           /* Disable all optimizations */
1148           } else {
1149               gDvmJit.disableOpt = -1;
1150           }
1151         } else if (strncmp(argv[i], "-Xjitsuspendpoll", 16) == 0) {
1152           gDvmJit.genSuspendPoll = true;
1153 #endif
1154
1155         } else if (strncmp(argv[i], "-Xstacktracefile:", 17) == 0) {
1156             gDvm.stackTraceFile = strdup(argv[i]+17);
1157
1158         } else if (strcmp(argv[i], "-Xgenregmap") == 0) {
1159             gDvm.generateRegisterMaps = true;
1160         } else if (strcmp(argv[i], "-Xnogenregmap") == 0) {
1161             gDvm.generateRegisterMaps = false;
1162
1163         } else if (strcmp(argv[i], "Xverifyopt:checkmon") == 0) {
1164             gDvm.monitorVerification = true;
1165         } else if (strcmp(argv[i], "Xverifyopt:nocheckmon") == 0) {
1166             gDvm.monitorVerification = false;
1167
1168         } else if (strncmp(argv[i], "-Xgc:", 5) == 0) {
1169             if (strcmp(argv[i] + 5, "precise") == 0)
1170                 gDvm.preciseGc = true;
1171             else if (strcmp(argv[i] + 5, "noprecise") == 0)
1172                 gDvm.preciseGc = false;
1173             else if (strcmp(argv[i] + 5, "preverify") == 0)
1174                 gDvm.preVerify = true;
1175             else if (strcmp(argv[i] + 5, "nopreverify") == 0)
1176                 gDvm.preVerify = false;
1177             else if (strcmp(argv[i] + 5, "postverify") == 0)
1178                 gDvm.postVerify = true;
1179             else if (strcmp(argv[i] + 5, "nopostverify") == 0)
1180                 gDvm.postVerify = false;
1181             else if (strcmp(argv[i] + 5, "concurrent") == 0)
1182                 gDvm.concurrentMarkSweep = true;
1183             else if (strcmp(argv[i] + 5, "noconcurrent") == 0)
1184                 gDvm.concurrentMarkSweep = false;
1185             else if (strcmp(argv[i] + 5, "verifycardtable") == 0)
1186                 gDvm.verifyCardTable = true;
1187             else if (strcmp(argv[i] + 5, "noverifycardtable") == 0)
1188                 gDvm.verifyCardTable = false;
1189             else {
1190                 dvmFprintf(stderr, "Bad value for -Xgc");
1191                 return -1;
1192             }
1193             ALOGV("Precise GC configured %s", gDvm.preciseGc ? "ON" : "OFF");
1194
1195         } else if (strcmp(argv[i], "-Xcheckdexsum") == 0) {
1196             gDvm.verifyDexChecksum = true;
1197
1198         } else if (strcmp(argv[i], "-Xprofile:threadcpuclock") == 0) {
1199             gDvm.profilerClockSource = kProfilerClockSourceThreadCpu;
1200         } else if (strcmp(argv[i], "-Xprofile:wallclock") == 0) {
1201             gDvm.profilerClockSource = kProfilerClockSourceWall;
1202         } else if (strcmp(argv[i], "-Xprofile:dualclock") == 0) {
1203             gDvm.profilerClockSource = kProfilerClockSourceDual;
1204
1205         } else {
1206             if (!ignoreUnrecognized) {
1207                 dvmFprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
1208                 return -1;
1209             }
1210         }
1211     }
1212
1213     return 0;
1214 }
1215
1216 /*
1217  * Set defaults for fields altered or modified by arguments.
1218  *
1219  * Globals are initialized to 0 (a/k/a NULL or false).
1220  */
1221 static void setCommandLineDefaults()
1222 {
1223     const char* envStr = getenv("CLASSPATH");
1224     if (envStr != NULL) {
1225         gDvm.classPathStr = strdup(envStr);
1226     } else {
1227         gDvm.classPathStr = strdup(".");
1228     }
1229     envStr = getenv("BOOTCLASSPATH");
1230     if (envStr != NULL) {
1231         gDvm.bootClassPathStr = strdup(envStr);
1232     } else {
1233         gDvm.bootClassPathStr = strdup(".");
1234     }
1235
1236     gDvm.properties = new std::vector<std::string>();
1237
1238     /* Defaults overridden by -Xms and -Xmx.
1239      * TODO: base these on a system or application-specific default
1240      */
1241     gDvm.heapStartingSize = 2 * 1024 * 1024;  // Spec says 16MB; too big for us.
1242     gDvm.heapMaximumSize = 16 * 1024 * 1024;  // Spec says 75% physical mem
1243     gDvm.heapGrowthLimit = 0;  // 0 means no growth limit
1244     gDvm.stackSize = kDefaultStackSize;
1245     gDvm.mainThreadStackSize = kDefaultStackSize;
1246     // When the heap is less than the maximum or growth limited size,
1247     // fix the free portion of the heap. The utilization is the ratio
1248     // of live to free memory, 0.5 implies half the heap is available
1249     // to allocate into before a GC occurs. Min free and max free
1250     // force the free memory to never be smaller than min free or
1251     // larger than max free.
1252     gDvm.heapTargetUtilization = 0.5;
1253     gDvm.heapMaxFree = 2 * 1024 * 1024;
1254     gDvm.heapMinFree = gDvm.heapMaxFree / 4;
1255
1256     gDvm.concurrentMarkSweep = true;
1257
1258     /* gDvm.jdwpSuspend = true; */
1259
1260     /* allowed unless zygote config doesn't allow it */
1261     gDvm.jdwpAllowed = true;
1262
1263     /* default verification and optimization modes */
1264     gDvm.classVerifyMode = VERIFY_MODE_ALL;
1265     gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1266     gDvm.monitorVerification = false;
1267     gDvm.generateRegisterMaps = true;
1268     gDvm.registerMapMode = kRegisterMapModeTypePrecise;
1269
1270     /*
1271      * Default execution mode.
1272      *
1273      * This should probably interact with the mterp code somehow, e.g. if
1274      * we know we're using the "desktop" build we should probably be
1275      * using "portable" rather than "fast".
1276      */
1277 #if defined(WITH_JIT)
1278     gDvm.executionMode = kExecutionModeJit;
1279     gDvmJit.num_entries_pcTable = 0;
1280     gDvmJit.includeSelectedMethod = false;
1281     gDvmJit.includeSelectedOffset = false;
1282     gDvmJit.methodTable = NULL;
1283     gDvmJit.classTable = NULL;
1284
1285     gDvm.constInit = false;
1286     gDvm.commonInit = false;
1287 #else
1288     gDvm.executionMode = kExecutionModeInterpFast;
1289 #endif
1290
1291     /*
1292      * SMP support is a compile-time define, but we may want to have
1293      * dexopt target a differently-configured device.
1294      */
1295     gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1296
1297     /*
1298      * Default profiler configuration.
1299      */
1300     gDvm.profilerClockSource = kProfilerClockSourceDual;
1301 }
1302
1303
1304 /*
1305  * Handle a SIGBUS, which frequently occurs because somebody replaced an
1306  * optimized DEX file out from under us.
1307  */
1308 static void busCatcher(int signum, siginfo_t* info, void* context)
1309 {
1310     void* addr = info->si_addr;
1311
1312     ALOGE("Caught a SIGBUS (%d), addr=%p", signum, addr);
1313
1314     /*
1315      * If we return at this point the SIGBUS just keeps happening, so we
1316      * remove the signal handler and allow it to kill us.  TODO: restore
1317      * the original, which points to a debuggerd stub; if we don't then
1318      * debuggerd won't be notified.
1319      */
1320     signal(SIGBUS, SIG_DFL);
1321 }
1322
1323 /*
1324  * Configure signals.  We need to block SIGQUIT so that the signal only
1325  * reaches the dump-stack-trace thread.
1326  *
1327  * This can be disabled with the "-Xrs" flag.
1328  */
1329 static void blockSignals()
1330 {
1331     sigset_t mask;
1332     int cc;
1333
1334     sigemptyset(&mask);
1335     sigaddset(&mask, SIGQUIT);
1336     sigaddset(&mask, SIGUSR1);      // used to initiate heap dump
1337 #if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1338     sigaddset(&mask, SIGUSR2);      // used to investigate JIT internals
1339 #endif
1340     //sigaddset(&mask, SIGPIPE);
1341     cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1342     assert(cc == 0);
1343
1344     if (false) {
1345         /* TODO: save the old sigaction in a global */
1346         struct sigaction sa;
1347         memset(&sa, 0, sizeof(sa));
1348         sa.sa_sigaction = busCatcher;
1349         sa.sa_flags = SA_SIGINFO;
1350         cc = sigaction(SIGBUS, &sa, NULL);
1351         assert(cc == 0);
1352     }
1353 }
1354
1355 class ScopedShutdown {
1356 public:
1357     ScopedShutdown() : armed_(true) {
1358     }
1359
1360     ~ScopedShutdown() {
1361         if (armed_) {
1362             dvmShutdown();
1363         }
1364     }
1365
1366     void disarm() {
1367         armed_ = false;
1368     }
1369
1370 private:
1371     bool armed_;
1372 };
1373
1374 /*
1375  * VM initialization.  Pass in any options provided on the command line.
1376  * Do not pass in the class name or the options for the class.
1377  *
1378  * Returns 0 on success.
1379  */
1380 std::string dvmStartup(int argc, const char* const argv[],
1381         bool ignoreUnrecognized, JNIEnv* pEnv)
1382 {
1383     ScopedShutdown scopedShutdown;
1384
1385     assert(gDvm.initializing);
1386
1387     ALOGV("VM init args (%d):", argc);
1388     for (int i = 0; i < argc; i++) {
1389         ALOGV("  %d: '%s'", i, argv[i]);
1390     }
1391     setCommandLineDefaults();
1392
1393     /*
1394      * Process the option flags (if any).
1395      */
1396     int cc = processOptions(argc, argv, ignoreUnrecognized);
1397     if (cc != 0) {
1398         if (cc < 0) {
1399             dvmFprintf(stderr, "\n");
1400             usage("dalvikvm");
1401         }
1402         return "syntax error";
1403     }
1404
1405 #if WITH_EXTRA_GC_CHECKS > 1
1406     /* only "portable" interp has the extra goodies */
1407     if (gDvm.executionMode != kExecutionModeInterpPortable) {
1408         ALOGI("Switching to 'portable' interpreter for GC checks");
1409         gDvm.executionMode = kExecutionModeInterpPortable;
1410     }
1411 #endif
1412
1413     /* Configure group scheduling capabilities */
1414     if (!access("/dev/cpuctl/tasks", F_OK)) {
1415         ALOGV("Using kernel group scheduling");
1416         gDvm.kernelGroupScheduling = 1;
1417     } else {
1418         ALOGV("Using kernel scheduler policies");
1419     }
1420
1421     /* configure signal handling */
1422     if (!gDvm.reduceSignals)
1423         blockSignals();
1424
1425     /* verify system page size */
1426     if (sysconf(_SC_PAGESIZE) != SYSTEM_PAGE_SIZE) {
1427         return StringPrintf("expected page size %d, got %d",
1428                 SYSTEM_PAGE_SIZE, (int) sysconf(_SC_PAGESIZE));
1429     }
1430
1431     /* mterp setup */
1432     ALOGV("Using executionMode %d", gDvm.executionMode);
1433     dvmCheckAsmConstants();
1434
1435     /*
1436      * Initialize components.
1437      */
1438     dvmQuasiAtomicsStartup();
1439     if (!dvmAllocTrackerStartup()) {
1440         return "dvmAllocTrackerStartup failed";
1441     }
1442     if (!dvmGcStartup()) {
1443         return "dvmGcStartup failed";
1444     }
1445     if (!dvmThreadStartup()) {
1446         return "dvmThreadStartup failed";
1447     }
1448     if (!dvmInlineNativeStartup()) {
1449         return "dvmInlineNativeStartup";
1450     }
1451     if (!dvmRegisterMapStartup()) {
1452         return "dvmRegisterMapStartup failed";
1453     }
1454     if (!dvmInstanceofStartup()) {
1455         return "dvmInstanceofStartup failed";
1456     }
1457     if (!dvmClassStartup()) {
1458         return "dvmClassStartup failed";
1459     }
1460
1461     /*
1462      * At this point, the system is guaranteed to be sufficiently
1463      * initialized that we can look up classes and class members. This
1464      * call populates the gDvm instance with all the class and member
1465      * references that the VM wants to use directly.
1466      */
1467     if (!dvmFindRequiredClassesAndMembers()) {
1468         return "dvmFindRequiredClassesAndMembers failed";
1469     }
1470
1471     if (!dvmStringInternStartup()) {
1472         return "dvmStringInternStartup failed";
1473     }
1474     if (!dvmNativeStartup()) {
1475         return "dvmNativeStartup failed";
1476     }
1477     if (!dvmInternalNativeStartup()) {
1478         return "dvmInternalNativeStartup failed";
1479     }
1480     if (!dvmJniStartup()) {
1481         return "dvmJniStartup failed";
1482     }
1483     if (!dvmProfilingStartup()) {
1484         return "dvmProfilingStartup failed";
1485     }
1486
1487     /*
1488      * Create a table of methods for which we will substitute an "inline"
1489      * version for performance.
1490      */
1491     if (!dvmCreateInlineSubsTable()) {
1492         return "dvmCreateInlineSubsTable failed";
1493     }
1494
1495     /*
1496      * Miscellaneous class library validation.
1497      */
1498     if (!dvmValidateBoxClasses()) {
1499         return "dvmValidateBoxClasses failed";
1500     }
1501
1502     /*
1503      * Do the last bits of Thread struct initialization we need to allow
1504      * JNI calls to work.
1505      */
1506     if (!dvmPrepMainForJni(pEnv)) {
1507         return "dvmPrepMainForJni failed";
1508     }
1509
1510     /*
1511      * Explicitly initialize java.lang.Class.  This doesn't happen
1512      * automatically because it's allocated specially (it's an instance
1513      * of itself).  Must happen before registration of system natives,
1514      * which make some calls that throw assertions if the classes they
1515      * operate on aren't initialized.
1516      */
1517     if (!dvmInitClass(gDvm.classJavaLangClass)) {
1518         return "couldn't initialized java.lang.Class";
1519     }
1520
1521     /*
1522      * Register the system native methods, which are registered through JNI.
1523      */
1524     if (!registerSystemNatives(pEnv)) {
1525         return "couldn't register system natives";
1526     }
1527
1528     /*
1529      * Do some "late" initialization for the memory allocator.  This may
1530      * allocate storage and initialize classes.
1531      */
1532     if (!dvmCreateStockExceptions()) {
1533         return "dvmCreateStockExceptions failed";
1534     }
1535
1536     /*
1537      * At this point, the VM is in a pretty good state.  Finish prep on
1538      * the main thread (specifically, create a java.lang.Thread object to go
1539      * along with our Thread struct).  Note we will probably be executing
1540      * some interpreted class initializer code in here.
1541      */
1542     if (!dvmPrepMainThread()) {
1543         return "dvmPrepMainThread failed";
1544     }
1545
1546     /*
1547      * Make sure we haven't accumulated any tracked references.  The main
1548      * thread should be starting with a clean slate.
1549      */
1550     if (dvmReferenceTableEntries(&dvmThreadSelf()->internalLocalRefTable) != 0)
1551     {
1552         ALOGW("Warning: tracked references remain post-initialization");
1553         dvmDumpReferenceTable(&dvmThreadSelf()->internalLocalRefTable, "MAIN");
1554     }
1555
1556     /* general debugging setup */
1557     if (!dvmDebuggerStartup()) {
1558         return "dvmDebuggerStartup failed";
1559     }
1560
1561     if (!dvmGcStartupClasses()) {
1562         return "dvmGcStartupClasses failed";
1563     }
1564
1565     /*
1566      * Init for either zygote mode or non-zygote mode.  The key difference
1567      * is that we don't start any additional threads in Zygote mode.
1568      */
1569     if (gDvm.zygote) {
1570         if (!initZygote()) {
1571             return "initZygote failed";
1572         }
1573     } else {
1574         if (!dvmInitAfterZygote()) {
1575             return "dvmInitAfterZygote failed";
1576         }
1577     }
1578
1579
1580 #ifndef NDEBUG
1581     if (!dvmTestHash())
1582         ALOGE("dvmTestHash FAILED");
1583     if (false /*noisy!*/ && !dvmTestIndirectRefTable())
1584         ALOGE("dvmTestIndirectRefTable FAILED");
1585 #endif
1586
1587     if (dvmCheckException(dvmThreadSelf())) {
1588         dvmLogExceptionStackTrace();
1589         return "Exception pending at end of VM initialization";
1590     }
1591
1592     scopedShutdown.disarm();
1593     return "";
1594 }
1595
1596 static void loadJniLibrary(const char* name) {
1597     std::string mappedName(StringPrintf(OS_SHARED_LIB_FORMAT_STR, name));
1598     char* reason = NULL;
1599     if (!dvmLoadNativeCode(mappedName.c_str(), NULL, &reason)) {
1600         ALOGE("dvmLoadNativeCode failed for \"%s\": %s", name, reason);
1601         dvmAbort();
1602     }
1603 }
1604
1605 /*
1606  * Register java.* natives from our class libraries.  We need to do
1607  * this after we're ready for JNI registration calls, but before we
1608  * do any class initialization.
1609  *
1610  * If we get this wrong, we will blow up in the ThreadGroup class init if
1611  * interpreted code makes any reference to System.  It will likely do this
1612  * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1613  *
1614  * We need to have gDvm.initializing raised here so that JNI FindClass
1615  * won't try to use the system/application class loader.
1616  */
1617 static bool registerSystemNatives(JNIEnv* pEnv)
1618 {
1619     // Main thread is always first in list.
1620     Thread* self = gDvm.threadList;
1621
1622     // Must set this before allowing JNI-based method registration.
1623     self->status = THREAD_NATIVE;
1624
1625     // First set up JniConstants, which is used by libcore.
1626     JniConstants::init(pEnv);
1627
1628     // Most JNI libraries can just use System.loadLibrary, but you can't
1629     // if you're the library that implements System.loadLibrary!
1630     loadJniLibrary("javacore");
1631     loadJniLibrary("nativehelper");
1632
1633     // Back to run mode.
1634     self->status = THREAD_RUNNING;
1635
1636     return true;
1637 }
1638
1639 /*
1640  * Copied and modified slightly from system/core/toolbox/mount.c
1641  */
1642 static std::string getMountsDevDir(const char *arg)
1643 {
1644     char mount_dev[256];
1645     char mount_dir[256];
1646     int match;
1647
1648     FILE *fp = fopen("/proc/self/mounts", "r");
1649     if (fp == NULL) {
1650         ALOGE("Could not open /proc/self/mounts: %s", strerror(errno));
1651         return "";
1652     }
1653
1654     while ((match = fscanf(fp, "%255s %255s %*s %*s %*d %*d\n", mount_dev, mount_dir)) != EOF) {
1655         mount_dev[255] = 0;
1656         mount_dir[255] = 0;
1657         if (match == 2 && (strcmp(arg, mount_dir) == 0)) {
1658             fclose(fp);
1659             return mount_dev;
1660         }
1661     }
1662
1663     fclose(fp);
1664     return "";
1665 }
1666
1667 /*
1668  * Do zygote-mode-only initialization.
1669  */
1670 static bool initZygote()
1671 {
1672     /* zygote goes into its own process group */
1673     setpgid(0,0);
1674
1675     // See storage config details at http://source.android.com/tech/storage/
1676     // Create private mount namespace shared by all children
1677     if (unshare(CLONE_NEWNS) == -1) {
1678         SLOGE("Failed to unshare(): %s", strerror(errno));
1679         return -1;
1680     }
1681
1682     // Mark rootfs as being a slave so that changes from default
1683     // namespace only flow into our children.
1684     if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
1685         SLOGE("Failed to mount() rootfs as MS_SLAVE: %s", strerror(errno));
1686         return -1;
1687     }
1688
1689     // Create a staging tmpfs that is shared by our children; they will
1690     // bind mount storage into their respective private namespaces, which
1691     // are isolated from each other.
1692     const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1693     if (target_base != NULL) {
1694         if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1695                 "uid=0,gid=1028,mode=0050") == -1) {
1696             SLOGE("Failed to mount tmpfs to %s: %s", target_base, strerror(errno));
1697             return -1;
1698         }
1699     }
1700
1701     // Mark /system as NOSUID | NODEV
1702     const char* android_root = getenv("ANDROID_ROOT");
1703
1704     if (android_root == NULL) {
1705         SLOGE("environment variable ANDROID_ROOT does not exist?!?!");
1706         return -1;
1707     }
1708
1709     std::string mountDev(getMountsDevDir(android_root));
1710     if (mountDev.empty()) {
1711         SLOGE("Unable to find mount point for %s", android_root);
1712         return -1;
1713     }
1714
1715     if (mount(mountDev.c_str(), android_root, "none",
1716             MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_RDONLY | MS_BIND, NULL) == -1) {
1717         SLOGE("Remount of %s failed: %s", android_root, strerror(errno));
1718         return -1;
1719     }
1720
1721 #ifdef HAVE_ANDROID_OS
1722     if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1723         if (errno == EINVAL) {
1724             SLOGW("PR_SET_NO_NEW_PRIVS failed. "
1725                   "Is your kernel compiled correctly?: %s", strerror(errno));
1726             // Don't return -1 here, since it's expected that not all
1727             // kernels will support this option.
1728         } else {
1729             SLOGW("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
1730             return -1;
1731         }
1732     }
1733 #endif
1734
1735     return true;
1736 }
1737
1738 /*
1739  * Do non-zygote-mode initialization.  This is done during VM init for
1740  * standard startup, or after a "zygote fork" when creating a new process.
1741  */
1742 bool dvmInitAfterZygote()
1743 {
1744     u8 startHeap, startQuit, startJdwp;
1745     u8 endHeap, endQuit, endJdwp;
1746
1747     startHeap = dvmGetRelativeTimeUsec();
1748
1749     /*
1750      * Post-zygote heap initialization, including starting
1751      * the HeapWorker thread.
1752      */
1753     if (!dvmGcStartupAfterZygote())
1754         return false;
1755
1756     endHeap = dvmGetRelativeTimeUsec();
1757     startQuit = dvmGetRelativeTimeUsec();
1758
1759     /* start signal catcher thread that dumps stacks on SIGQUIT */
1760     if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1761         if (!dvmSignalCatcherStartup())
1762             return false;
1763     }
1764
1765     /* start stdout/stderr copier, if requested */
1766     if (gDvm.logStdio) {
1767         if (!dvmStdioConverterStartup())
1768             return false;
1769     }
1770
1771     endQuit = dvmGetRelativeTimeUsec();
1772     startJdwp = dvmGetRelativeTimeUsec();
1773
1774     /*
1775      * Start JDWP thread.  If the command-line debugger flags specified
1776      * "suspend=y", this will pause the VM.  We probably want this to
1777      * come last.
1778      */
1779     if (!initJdwp()) {
1780         ALOGD("JDWP init failed; continuing anyway");
1781     }
1782
1783     endJdwp = dvmGetRelativeTimeUsec();
1784
1785     ALOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec",
1786         (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1787         (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1788
1789 #ifdef WITH_JIT
1790     if (gDvm.executionMode == kExecutionModeJit) {
1791         if (!dvmCompilerStartup())
1792             return false;
1793     }
1794 #endif
1795
1796     return true;
1797 }
1798
1799 /*
1800  * Prepare for a connection to a JDWP-compliant debugger.
1801  *
1802  * Note this needs to happen fairly late in the startup process, because
1803  * we need to have all of the java.* native methods registered (which in
1804  * turn requires JNI to be fully prepped).
1805  *
1806  * There are several ways to initialize:
1807  *   server=n
1808  *     We immediately try to connect to host:port.  Bail on failure.  On
1809  *     success, send VM_START (suspending the VM if "suspend=y").
1810  *   server=y suspend=n
1811  *     Passively listen for a debugger to connect.  Return immediately.
1812  *   server=y suspend=y
1813  *     Wait until debugger connects.  Send VM_START ASAP, suspending the
1814  *     VM after the message is sent.
1815  *
1816  * This gets more complicated with a nonzero value for "timeout".
1817  */
1818 static bool initJdwp()
1819 {
1820     assert(!gDvm.zygote);
1821
1822     /*
1823      * Init JDWP if the debugger is enabled.  This may connect out to a
1824      * debugger, passively listen for a debugger, or block waiting for a
1825      * debugger.
1826      */
1827     if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1828         JdwpStartupParams params;
1829
1830         if (gDvm.jdwpHost != NULL) {
1831             if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1832                 ALOGE("ERROR: hostname too long: '%s'", gDvm.jdwpHost);
1833                 return false;
1834             }
1835             strcpy(params.host, gDvm.jdwpHost);
1836         } else {
1837             params.host[0] = '\0';
1838         }
1839         params.transport = gDvm.jdwpTransport;
1840         params.server = gDvm.jdwpServer;
1841         params.suspend = gDvm.jdwpSuspend;
1842         params.port = gDvm.jdwpPort;
1843
1844         gDvm.jdwpState = dvmJdwpStartup(&params);
1845         if (gDvm.jdwpState == NULL) {
1846             ALOGW("WARNING: debugger thread failed to initialize");
1847             /* TODO: ignore? fail? need to mimic "expected" behavior */
1848         }
1849     }
1850
1851     /*
1852      * If a debugger has already attached, send the "welcome" message.  This
1853      * may cause us to suspend all threads.
1854      */
1855     if (dvmJdwpIsActive(gDvm.jdwpState)) {
1856         //dvmChangeStatus(NULL, THREAD_RUNNING);
1857         if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1858             ALOGW("WARNING: failed to post 'start' message to debugger");
1859             /* keep going */
1860         }
1861         //dvmChangeStatus(NULL, THREAD_NATIVE);
1862     }
1863
1864     return true;
1865 }
1866
1867 /*
1868  * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1869  * of initialization and then returns with "initializing" still set.  (Used
1870  * by DexOpt command-line utility.)
1871  *
1872  * Attempting to use JNI or internal natives will fail.  It's best
1873  * if no bytecode gets executed, which means no <clinit>, which means
1874  * no exception-throwing.  (In practice we need to initialize Class and
1875  * Object, and probably some exception classes.)
1876  *
1877  * Returns 0 on success.
1878  */
1879 int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1880     DexClassVerifyMode verifyMode, int dexoptFlags)
1881 {
1882     gDvm.initializing = true;
1883     gDvm.optimizing = true;
1884
1885     /* configure signal handling */
1886     blockSignals();
1887
1888     /* set some defaults */
1889     setCommandLineDefaults();
1890     free(gDvm.bootClassPathStr);
1891     gDvm.bootClassPathStr = strdup(bootClassPath);
1892
1893     /* set opt/verify modes */
1894     gDvm.dexOptMode = dexOptMode;
1895     gDvm.classVerifyMode = verifyMode;
1896     gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1897     if (dexoptFlags & DEXOPT_SMP) {
1898         assert((dexoptFlags & DEXOPT_UNIPROCESSOR) == 0);
1899         gDvm.dexOptForSmp = true;
1900     } else if (dexoptFlags & DEXOPT_UNIPROCESSOR) {
1901         gDvm.dexOptForSmp = false;
1902     } else {
1903         gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1904     }
1905
1906     /*
1907      * Initialize the heap, some basic thread control mutexes, and
1908      * get the bootclasspath prepped.
1909      *
1910      * We can't load any classes yet because we may not yet have a source
1911      * for things like java.lang.Object and java.lang.Class.
1912      */
1913     if (!dvmGcStartup())
1914         goto fail;
1915     if (!dvmThreadStartup())
1916         goto fail;
1917     if (!dvmInlineNativeStartup())
1918         goto fail;
1919     if (!dvmRegisterMapStartup())
1920         goto fail;
1921     if (!dvmInstanceofStartup())
1922         goto fail;
1923     if (!dvmClassStartup())
1924         goto fail;
1925
1926     /*
1927      * We leave gDvm.initializing set to "true" so that, if we're not
1928      * able to process the "core" classes, we don't go into a death-spin
1929      * trying to throw a "class not found" exception.
1930      */
1931
1932     return 0;
1933
1934 fail:
1935     dvmShutdown();
1936     return 1;
1937 }
1938
1939
1940 /*
1941  * All threads have stopped.  Finish the shutdown procedure.
1942  *
1943  * We can also be called if startup fails partway through, so be prepared
1944  * to deal with partially initialized data.
1945  *
1946  * Free any storage allocated in gGlobals.
1947  *
1948  * We can't dlclose() shared libs we've loaded, because it's possible a
1949  * thread not associated with the VM is running code in one.
1950  *
1951  * This is called from the JNI DestroyJavaVM function, which can be
1952  * called from any thread.  (In practice, this will usually run in the
1953  * same thread that started the VM, a/k/a the main thread, but we don't
1954  * want to assume that.)
1955  */
1956 void dvmShutdown()
1957 {
1958     ALOGV("VM shutting down");
1959
1960     if (CALC_CACHE_STATS)
1961         dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1962
1963     /*
1964      * Stop our internal threads.
1965      */
1966     dvmGcThreadShutdown();
1967
1968     if (gDvm.jdwpState != NULL)
1969         dvmJdwpShutdown(gDvm.jdwpState);
1970     free(gDvm.jdwpHost);
1971     gDvm.jdwpHost = NULL;
1972     free(gDvm.jniTrace);
1973     gDvm.jniTrace = NULL;
1974     free(gDvm.stackTraceFile);
1975     gDvm.stackTraceFile = NULL;
1976
1977     /* tell signal catcher to shut down if it was started */
1978     dvmSignalCatcherShutdown();
1979
1980     /* shut down stdout/stderr conversion */
1981     dvmStdioConverterShutdown();
1982
1983 #ifdef WITH_JIT
1984     if (gDvm.executionMode == kExecutionModeJit) {
1985         /* shut down the compiler thread */
1986         dvmCompilerShutdown();
1987     }
1988 #endif
1989
1990     /*
1991      * Kill any daemon threads that still exist.  Actively-running threads
1992      * are likely to crash the process if they continue to execute while
1993      * the VM shuts down.
1994      */
1995     dvmSlayDaemons();
1996
1997     if (gDvm.verboseShutdown)
1998         ALOGD("VM cleaning up");
1999
2000     dvmDebuggerShutdown();
2001     dvmProfilingShutdown();
2002     dvmJniShutdown();
2003     dvmStringInternShutdown();
2004     dvmThreadShutdown();
2005     dvmClassShutdown();
2006     dvmRegisterMapShutdown();
2007     dvmInstanceofShutdown();
2008     dvmInlineNativeShutdown();
2009     dvmGcShutdown();
2010     dvmAllocTrackerShutdown();
2011
2012     /* these must happen AFTER dvmClassShutdown has walked through class data */
2013     dvmNativeShutdown();
2014     dvmInternalNativeShutdown();
2015
2016     dvmFreeInlineSubsTable();
2017
2018     free(gDvm.bootClassPathStr);
2019     free(gDvm.classPathStr);
2020     delete gDvm.properties;
2021
2022     freeAssertionCtrl();
2023
2024     dvmQuasiAtomicsShutdown();
2025
2026     /*
2027      * We want valgrind to report anything we forget to free as "definitely
2028      * lost".  If there's a pointer in the global chunk, it would be reported
2029      * as "still reachable".  Erasing the memory fixes this.
2030      *
2031      * This must be erased to zero if we want to restart the VM within this
2032      * process.
2033      */
2034     memset(&gDvm, 0xcd, sizeof(gDvm));
2035 }
2036
2037
2038 /*
2039  * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
2040  * one was specified.
2041  */
2042 int dvmFprintf(FILE* fp, const char* format, ...)
2043 {
2044     va_list args;
2045     int result;
2046
2047     va_start(args, format);
2048     if (gDvm.vfprintfHook != NULL)
2049         result = (*gDvm.vfprintfHook)(fp, format, args);
2050     else
2051         result = vfprintf(fp, format, args);
2052     va_end(args);
2053
2054     return result;
2055 }
2056
2057 #ifdef __GLIBC__
2058 #include <execinfo.h>
2059 /*
2060  * glibc-only stack dump function.  Requires link with "--export-dynamic".
2061  *
2062  * TODO: move this into libs/cutils and make it work for all platforms.
2063  */
2064 void dvmPrintNativeBackTrace()
2065 {
2066     size_t MAX_STACK_FRAMES = 64;
2067     void* stackFrames[MAX_STACK_FRAMES];
2068     size_t frameCount = backtrace(stackFrames, MAX_STACK_FRAMES);
2069
2070     /*
2071      * TODO: in practice, we may find that we should use backtrace_symbols_fd
2072      * to avoid allocation, rather than use our own custom formatting.
2073      */
2074     char** strings = backtrace_symbols(stackFrames, frameCount);
2075     if (strings == NULL) {
2076         ALOGE("backtrace_symbols failed: %s", strerror(errno));
2077         return;
2078     }
2079
2080     size_t i;
2081     for (i = 0; i < frameCount; ++i) {
2082         ALOGW("#%-2d %s", i, strings[i]);
2083     }
2084     free(strings);
2085 }
2086 #else
2087 void dvmPrintNativeBackTrace() {
2088     /* Hopefully, you're on an Android device and debuggerd will do this. */
2089 }
2090 #endif
2091
2092 /*
2093  * Abort the VM.  We get here on fatal errors.  Try very hard not to use
2094  * this; whenever possible, return an error to somebody responsible.
2095  */
2096 void dvmAbort()
2097 {
2098     /*
2099      * Leave gDvm.lastMessage on the stack frame which can be decoded in the
2100      * tombstone file. This is for situations where we only have tombstone files
2101      * but no logs (ie b/5372634).
2102      *
2103      * For example, in the tombstone file you usually see this:
2104      *
2105      *   #00  pc 00050ef2  /system/lib/libdvm.so (dvmAbort)
2106      *   #01  pc 00077670  /system/lib/libdvm.so (_Z15dvmClassStartupv)
2107      *     :
2108      *
2109      * stack:
2110      *     :
2111      * #00 beed2658  00000000
2112      *     beed265c  7379732f
2113      *     beed2660  2f6d6574
2114      *     beed2664  6d617266
2115      *     beed2668  726f7765
2116      *     beed266c  6f632f6b
2117      *     beed2670  6a2e6572
2118      *     beed2674  00007261
2119      *     beed2678  00000000
2120      *
2121      * The ascii values between beed265c and beed2674 belongs to messageBuffer
2122      * and it can be decoded as "/system/framework/core.jar".
2123      */
2124     const int messageLength = 512;
2125     char messageBuffer[messageLength] = {0};
2126     int result = 0;
2127
2128     snprintf(messageBuffer, messageLength, "%s", gDvm.lastMessage);
2129
2130     /* So that messageBuffer[] looks like useful stuff to the compiler */
2131     for (int i = 0; i < messageLength && messageBuffer[i]; i++) {
2132         result += messageBuffer[i];
2133     }
2134
2135     ALOGE("VM aborting");
2136
2137     fflush(NULL);       // flush all open file buffers
2138
2139     /* JNI-supplied abort hook gets right of first refusal */
2140     if (gDvm.abortHook != NULL)
2141         (*gDvm.abortHook)();
2142
2143     /*
2144      * On the device, debuggerd will give us a stack trace.
2145      * On the host, we have to help ourselves.
2146      */
2147     dvmPrintNativeBackTrace();
2148
2149     /*
2150      * If we call abort(), all threads in the process receives a SIBABRT.
2151      * debuggerd dumps the stack trace of the main thread, whether or not
2152      * that was the thread that failed.
2153      *
2154      * By stuffing a value into a bogus address, we cause a segmentation
2155      * fault in the current thread, and get a useful log from debuggerd.
2156      * We can also trivially tell the difference between a VM crash and
2157      * a deliberate abort by looking at the fault address.
2158      */
2159     *((char*)0xdeadd00d) = result;
2160     abort();
2161
2162     /* notreached */
2163 }