2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Dalvik initialization, shutdown, and command-line argument processing.
20 #define __STDC_LIMIT_MACROS
26 #include <sys/mount.h>
29 #include <cutils/fs.h>
31 #ifdef HAVE_ANDROID_OS
32 #include <sys/prctl.h>
36 #include "test/Test.h"
37 #include "mterp/Mterp.h"
39 #include "JniConstants.h"
42 #include "compiler/codegen/Optimizer.h"
45 #define kMinHeapStartSize (1*1024*1024)
46 #define kMinHeapSize (2*1024*1024)
47 #define kMaxHeapSize (1*1024*1024*1024)
50 * Register VM-agnostic native methods for system classes.
52 extern int jniRegisterSystemMethods(JNIEnv* env);
55 static bool registerSystemNatives(JNIEnv* pEnv);
56 static bool initJdwp();
57 static bool initZygote();
61 struct DvmGlobals gDvm;
62 struct DvmJniGlobals gDvmJni;
64 /* JIT-specific global state */
66 struct DvmJitGlobals gDvmJit;
68 #if defined(WITH_JIT_TUNING)
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.
81 * We follow the tradition of unhyphenated compound words.
83 static void usage(const char* progName)
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");
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)
114 " -Xint (extended to accept ':portable', ':fast' and ':jit')\n");
117 " -Xint (extended to accept ':portable' and ':fast')\n");
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, " -Xjniopts:{warnonly,forcecopy}\n");
125 dvmFprintf(stderr, " -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
126 dvmFprintf(stderr, " -Xstacktracefile:<filename>\n");
127 dvmFprintf(stderr, " -Xgc:[no]precise\n");
128 dvmFprintf(stderr, " -Xgc:[no]preverify\n");
129 dvmFprintf(stderr, " -Xgc:[no]postverify\n");
130 dvmFprintf(stderr, " -Xgc:[no]concurrent\n");
131 dvmFprintf(stderr, " -Xgc:[no]verifycardtable\n");
132 dvmFprintf(stderr, " -XX:+DisableExplicitGC\n");
133 dvmFprintf(stderr, " -X[no]genregmap\n");
134 dvmFprintf(stderr, " -Xverifyopt:[no]checkmon\n");
135 dvmFprintf(stderr, " -Xcheckdexsum\n");
136 #if defined(WITH_JIT)
137 dvmFprintf(stderr, " -Xincludeselectedop\n");
138 dvmFprintf(stderr, " -Xjitop:hexopvalue[-endvalue]"
139 "[,hexopvalue[-endvalue]]*\n");
140 dvmFprintf(stderr, " -Xincludeselectedmethod\n");
141 dvmFprintf(stderr, " -Xjitthreshold:decimalvalue\n");
142 dvmFprintf(stderr, " -Xjitcodecachesize:decimalvalueofkbytes\n");
143 dvmFprintf(stderr, " -Xjitblocking\n");
144 dvmFprintf(stderr, " -Xjitmethod:signature[,signature]* "
145 "(eg Ljava/lang/String\\;replace)\n");
146 dvmFprintf(stderr, " -Xjitclass:classname[,classname]*\n");
147 dvmFprintf(stderr, " -Xjitoffset:offset[,offset]\n");
148 dvmFprintf(stderr, " -Xjitconfig:filename\n");
149 dvmFprintf(stderr, " -Xjitcheckcg\n");
150 dvmFprintf(stderr, " -Xjitverbose\n");
151 dvmFprintf(stderr, " -Xjitprofile\n");
152 dvmFprintf(stderr, " -Xjitdisableopt\n");
153 dvmFprintf(stderr, " -Xjitsuspendpoll\n");
155 dvmFprintf(stderr, "\n");
156 dvmFprintf(stderr, "Configured with:"
160 #ifdef WITH_TRACKREF_CHECKS
163 #ifdef WITH_INSTR_CHECKS
166 #ifdef WITH_EXTRA_OBJECT_VALIDATION
167 " extra_object_validation"
169 #ifdef WITH_EXTRA_GC_CHECKS
172 #if !defined(NDEBUG) && defined(WITH_DALVIK_ASSERT)
175 #ifdef WITH_JNI_STACK_CHECK
184 #if defined(WITH_JIT)
185 " jit(" ARCH_VARIANT ")"
187 #if defined(WITH_SELF_VERIFICATION)
194 #ifdef DVM_SHOW_EXCEPTION
195 dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
197 dvmFprintf(stderr, "\n\n");
201 * Show helpful information on JDWP options.
203 static void showJdwpHelp()
206 "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
208 "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
212 * Show version and copyright info.
214 static void showVersion()
216 dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
217 DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
219 "Copyright (C) 2007 The Android Open Source Project\n\n"
220 "This software is built from source code licensed under the "
222 "Version 2.0 (the \"License\"). You may obtain a copy of the "
224 " http://www.apache.org/licenses/LICENSE-2.0\n\n"
225 "See the associated NOTICE file for this software for further "
230 * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
231 * memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
234 * "s" should point just past the "-Xm?" part of the string.
235 * "min" specifies the lowest acceptable value described by "s".
236 * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
239 * The spec says the -Xmx and -Xms options must be multiples of 1024. It
240 * doesn't say anything about -Xss.
242 * Returns 0 (a useless size) if "s" is malformed or specifies a low or
243 * non-evenly-divisible value.
245 static size_t parseMemOption(const char* s, size_t div)
247 /* strtoul accepts a leading [+-], which we don't want,
248 * so make sure our string starts with a decimal digit.
254 val = strtoul(s, (char* *)&s2, 10);
256 /* s2 should be pointing just after the number.
257 * If this is the end of the string, the user
258 * has specified a number of bytes. Otherwise,
259 * there should be exactly one more character
260 * that specifies a multiplier.
265 /* The remainder of the string is either a single multiplier
266 * character, or nothing to indicate that the value is in
275 } else if (c == 'k' || c == 'K') {
277 } else if (c == 'm' || c == 'M') {
279 } else if (c == 'g' || c == 'G') {
280 mul = 1024 * 1024 * 1024;
282 /* Unknown multiplier character.
287 if (val <= SIZE_MAX / mul) {
290 /* Clamp to a multiple of 1024.
292 val = SIZE_MAX & ~(1024-1);
295 /* There's more than one character after the
302 /* The man page says that a -Xm value must be
303 * a multiple of 1024.
305 if (val % div == 0) {
315 * Handle one of the JDWP name/value pairs.
318 * help: if specified, show help message and bail
319 * transport: may be dt_socket or dt_shmem
320 * address: for dt_socket, "host:port", or just "port" when listening
321 * server: if "y", wait for debugger to attach; if "n", attach to debugger
322 * timeout: how long to wait for debugger to connect / listen
324 * Useful with server=n (these aren't supported yet):
325 * onthrow=<exception-name>: connect to debugger when exception thrown
326 * onuncaught=y|n: connect to debugger when uncaught exception thrown
327 * launch=<command-line>: launch the debugger itself
329 * The "transport" option is required, as is "address" if server=n.
331 static bool handleJdwpOption(const char* name, const char* value)
333 if (strcmp(name, "transport") == 0) {
334 if (strcmp(value, "dt_socket") == 0) {
335 gDvm.jdwpTransport = kJdwpTransportSocket;
336 } else if (strcmp(value, "dt_android_adb") == 0) {
337 gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
339 ALOGE("JDWP transport '%s' not supported", value);
342 } else if (strcmp(name, "server") == 0) {
344 gDvm.jdwpServer = false;
345 else if (*value == 'y')
346 gDvm.jdwpServer = true;
348 ALOGE("JDWP option 'server' must be 'y' or 'n'");
351 } else if (strcmp(name, "suspend") == 0) {
353 gDvm.jdwpSuspend = false;
354 else if (*value == 'y')
355 gDvm.jdwpSuspend = true;
357 ALOGE("JDWP option 'suspend' must be 'y' or 'n'");
360 } else if (strcmp(name, "address") == 0) {
361 /* this is either <port> or <host>:<port> */
362 const char* colon = strchr(value, ':');
368 gDvm.jdwpHost = (char*) malloc(colon - value +1);
369 strncpy(gDvm.jdwpHost, value, colon - value +1);
370 gDvm.jdwpHost[colon-value] = '\0';
373 if (*value == '\0') {
374 ALOGE("JDWP address missing port");
377 port = strtol(value, &end, 10);
379 ALOGE("JDWP address has junk in port field '%s'", value);
382 gDvm.jdwpPort = port;
383 } else if (strcmp(name, "launch") == 0 ||
384 strcmp(name, "onthrow") == 0 ||
385 strcmp(name, "oncaught") == 0 ||
386 strcmp(name, "timeout") == 0)
388 /* valid but unsupported */
389 ALOGI("Ignoring JDWP option '%s'='%s'", name, value);
391 ALOGI("Ignoring unrecognized JDWP option '%s'='%s'", name, value);
398 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
399 * "transport=dt_socket,address=8000,server=y,suspend=n"
401 static bool parseJdwpOptions(const char* str)
403 char* mangle = strdup(str);
408 * Process all of the name=value pairs.
414 value = strchr(name, '=');
416 ALOGE("JDWP opts: garbage at '%s'", name);
420 comma = strchr(name, ','); // use name, not value, for safety
423 ALOGE("JDWP opts: found comma before '=' in '%s'", mangle);
429 *value++ = '\0'; // stomp the '='
431 if (!handleJdwpOption(name, value))
442 * Make sure the combination of arguments makes sense.
444 if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
445 ALOGE("JDWP opts: must specify transport");
448 if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
449 ALOGE("JDWP opts: when server=n, must specify host and port");
452 // transport mandatory
453 // outbound server address
455 gDvm.jdwpConfigured = true;
464 * Handle one of the four kinds of assertion arguments.
466 * "pkgOrClass" is the last part of an enable/disable line. For a package
467 * the arg looks like "-ea:com.google.fubar...", for a class it looks
468 * like "-ea:com.google.fubar.Wahoo". The string we get starts at the ':'.
470 * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
472 * Multiple instances of these arguments can be specified, e.g. you can
473 * enable assertions for a package and then disable them for one class in
476 static bool enableAssertions(const char* pkgOrClass, bool enable)
478 AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
479 pCtrl->enable = enable;
481 if (pkgOrClass == NULL) {
482 /* enable or disable for all system classes */
483 pCtrl->isPackage = false;
484 pCtrl->pkgOrClass = NULL;
485 pCtrl->pkgOrClassLen = 0;
487 if (*pkgOrClass == '\0') {
488 /* global enable/disable for all but system */
489 pCtrl->isPackage = false;
490 pCtrl->pkgOrClass = strdup("");
491 pCtrl->pkgOrClassLen = 0;
493 pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1); // skip ':'
494 if (pCtrl->pkgOrClass == NULL) {
495 /* can happen if class name includes an illegal '/' */
496 ALOGW("Unable to process assertion arg '%s'", pkgOrClass);
500 int len = strlen(pCtrl->pkgOrClass);
501 if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
502 /* mark as package, truncate two of the three slashes */
503 pCtrl->isPackage = true;
504 *(pCtrl->pkgOrClass + len-2) = '\0';
505 pCtrl->pkgOrClassLen = len - 2;
508 pCtrl->isPackage = false;
509 pCtrl->pkgOrClassLen = len;
518 * Turn assertions on when requested to do so by the Zygote.
520 * This is a bit sketchy. We can't (easily) go back and fiddle with all
521 * of the classes that have already been initialized, so this only
522 * affects classes that have yet to be loaded. If some or all assertions
523 * have been enabled through some other means, we don't want to mess with
524 * it here, so we do nothing. Finally, we assume that there's room in
525 * "assertionCtrl" to hold at least one entry; this is guaranteed by the
528 * This must only be called from the main thread during zygote init.
530 void dvmLateEnableAssertions()
532 if (gDvm.assertionCtrl == NULL) {
533 ALOGD("Not late-enabling assertions: no assertionCtrl array");
535 } else if (gDvm.assertionCtrlCount != 0) {
536 ALOGD("Not late-enabling assertions: some asserts already configured");
539 ALOGD("Late-enabling assertions");
541 /* global enable for all but system */
542 AssertionControl* pCtrl = gDvm.assertionCtrl;
543 pCtrl->pkgOrClass = strdup("");
544 pCtrl->pkgOrClassLen = 0;
545 pCtrl->isPackage = false;
546 pCtrl->enable = true;
547 gDvm.assertionCtrlCount = 1;
552 * Release memory associated with the AssertionCtrl array.
554 static void freeAssertionCtrl()
558 for (i = 0; i < gDvm.assertionCtrlCount; i++)
559 free(gDvm.assertionCtrl[i].pkgOrClass);
560 free(gDvm.assertionCtrl);
563 #if defined(WITH_JIT)
564 /* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
565 static void processXjitop(const char* opt)
568 const char* startPtr = &opt[8];
572 long startValue, endValue;
574 startValue = strtol(startPtr, &endPtr, 16);
575 if (startPtr != endPtr) {
576 /* Just in case value is out of range */
577 startValue %= kNumPackedOpcodes;
579 if (*endPtr == '-') {
580 endValue = strtol(endPtr+1, &endPtr, 16);
581 endValue %= kNumPackedOpcodes;
583 endValue = startValue;
586 for (; startValue <= endValue; startValue++) {
587 ALOGW("Dalvik opcode %x is selected for debugging",
588 (unsigned int) startValue);
589 /* Mark the corresponding bit to 1 */
590 gDvmJit.opList[startValue >> 3] |= 1 << (startValue & 0x7);
597 startPtr = endPtr + 1;
603 "Warning: Unrecognized opcode value substring "
611 for (i = 0; i < (kNumPackedOpcodes+7)/8; i++) {
612 gDvmJit.opList[i] = 0xff;
614 dvmFprintf(stderr, "Warning: select all opcodes\n");
618 /* Parse -Xjitoffset to selectively turn on/off traces with certain offsets for JIT */
619 static void processXjitoffset(const char* opt) {
620 gDvmJit.num_entries_pcTable = 0;
621 char* buf = strdup(opt);
626 end = strchr(start, ',');
631 dvmFprintf(stderr, "processXjitoffset start = %s\n", start);
632 char* tmp = strdup(start);
633 gDvmJit.pcTable[idx++] = atoi(tmp);
635 if (idx >= COMPILER_PC_OFFSET_SIZE) {
636 dvmFprintf(stderr, "processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
645 gDvmJit.num_entries_pcTable = idx;
649 /* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
650 static void processXjitmethod(const char* opt, bool isMethod) {
651 char* buf = strdup(opt);
653 if (isMethod && gDvmJit.methodTable == NULL) {
654 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
656 if (!isMethod && gDvmJit.classTable == NULL) {
657 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
663 * Break comma-separated method signatures and enter them into the hash
664 * table individually.
669 end = strchr(start, ',');
674 hashValue = dvmComputeUtf8Hash(start);
675 dvmHashTableLookup(isMethod ? gDvmJit.methodTable : gDvmJit.classTable,
676 hashValue, strdup(start), (HashCompareFunc) strcmp, true);
687 /* The format of jit_config.list:
694 index ... //each pair is a range, if pcOff falls into a range, JIT
696 static int processXjitconfig(const char* opt) {
697 FILE* fp = fopen(opt, "r");
703 bool startClass = false, startMethod = false, startOffset = false;
704 gDvmJit.num_entries_pcTable = 0;
707 while (fgets(fLine, 500, fp) != NULL) {
708 char* curLine = strtok(fLine, " \t\r\n");
709 /* handles keyword CLASS, METHOD, INCLUDE, EXCLUDE */
710 if (!strncmp(curLine, "CLASS", 5)) {
716 if (!strncmp(curLine, "METHOD", 6)) {
722 if (!strncmp(curLine, "OFFSET", 6)) {
728 if (!strncmp(curLine, "EXCLUDE", 7)) {
729 gDvmJit.includeSelectedMethod = false;
732 if (!strncmp(curLine, "INCLUDE", 7)) {
733 gDvmJit.includeSelectedMethod = true;
736 if (!startMethod && !startClass && !startOffset) {
740 int hashValue = dvmComputeUtf8Hash(curLine);
742 if (gDvmJit.methodTable == NULL) {
743 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
745 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
747 (HashCompareFunc) strcmp, true);
748 } else if (startClass) {
749 if (gDvmJit.classTable == NULL) {
750 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
752 dvmHashTableLookup(gDvmJit.classTable, hashValue,
754 (HashCompareFunc) strcmp, true);
755 } else if (startOffset) {
756 int tmpInt = atoi(curLine);
757 gDvmJit.pcTable[idx++] = tmpInt;
758 if (idx >= COMPILER_PC_OFFSET_SIZE) {
759 printf("processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
764 gDvmJit.num_entries_pcTable = idx;
771 * Process an argument vector full of options. Unlike standard C programs,
772 * argv[0] does not contain the name of the program.
774 * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
775 * that we don't recognize. Otherwise, we return with an error as soon as
776 * we see anything we can't identify.
778 * Returns 0 on success, -1 on failure, and 1 for the special case of
779 * "-version" where we want to stop without showing an error message.
781 static int processOptions(int argc, const char* const argv[],
782 bool ignoreUnrecognized)
786 ALOGV("VM options (%d):", argc);
787 for (i = 0; i < argc; i++)
788 ALOGV(" %d: '%s'", i, argv[i]);
791 * Over-allocate AssertionControl array for convenience. If allocated,
792 * the array must be able to hold at least one entry, so that the
793 * zygote-time activation can do its business.
795 assert(gDvm.assertionCtrl == NULL);
798 (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
799 if (gDvm.assertionCtrl == NULL)
801 assert(gDvm.assertionCtrlCount == 0);
804 for (i = 0; i < argc; i++) {
805 if (strcmp(argv[i], "-help") == 0) {
806 /* show usage and stop */
809 } else if (strcmp(argv[i], "-version") == 0) {
810 /* show version and stop */
813 } else if (strcmp(argv[i], "-showversion") == 0) {
814 /* show version and continue */
817 } else if (strcmp(argv[i], "-classpath") == 0 ||
818 strcmp(argv[i], "-cp") == 0)
822 dvmFprintf(stderr, "Missing classpath path list\n");
825 free(gDvm.classPathStr); /* in case we have compiled-in default */
826 gDvm.classPathStr = strdup(argv[++i]);
828 } else if (strncmp(argv[i], "-Xbootclasspath:",
829 sizeof("-Xbootclasspath:")-1) == 0)
831 /* set bootclasspath */
832 const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
835 dvmFprintf(stderr, "Missing bootclasspath path list\n");
838 free(gDvm.bootClassPathStr);
839 gDvm.bootClassPathStr = strdup(path);
841 } else if (strncmp(argv[i], "-Xbootclasspath/a:",
842 sizeof("-Xbootclasspath/a:")-1) == 0) {
843 const char* appPath = argv[i] + sizeof("-Xbootclasspath/a:")-1;
845 if (*(appPath) == '\0') {
846 dvmFprintf(stderr, "Missing appending bootclasspath path list\n");
851 if (asprintf(&allPath, "%s:%s", gDvm.bootClassPathStr, appPath) < 0) {
852 dvmFprintf(stderr, "Can't append to bootclasspath path list\n");
855 free(gDvm.bootClassPathStr);
856 gDvm.bootClassPathStr = allPath;
858 } else if (strncmp(argv[i], "-Xbootclasspath/p:",
859 sizeof("-Xbootclasspath/p:")-1) == 0) {
860 const char* prePath = argv[i] + sizeof("-Xbootclasspath/p:")-1;
862 if (*(prePath) == '\0') {
863 dvmFprintf(stderr, "Missing prepending bootclasspath path list\n");
868 if (asprintf(&allPath, "%s:%s", prePath, gDvm.bootClassPathStr) < 0) {
869 dvmFprintf(stderr, "Can't prepend to bootclasspath path list\n");
872 free(gDvm.bootClassPathStr);
873 gDvm.bootClassPathStr = allPath;
875 } else if (strncmp(argv[i], "-D", 2) == 0) {
876 /* Properties are handled in managed code. We just check syntax. */
877 if (strchr(argv[i], '=') == NULL) {
878 dvmFprintf(stderr, "Bad system property setting: \"%s\"\n",
882 gDvm.properties->push_back(argv[i] + 2);
884 } else if (strcmp(argv[i], "-jar") == 0) {
885 // TODO: handle this; name of jar should be in argv[i+1]
886 dvmFprintf(stderr, "-jar not yet handled\n");
889 } else if (strncmp(argv[i], "-Xms", 4) == 0) {
890 size_t val = parseMemOption(argv[i]+4, 1024);
892 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
893 gDvm.heapStartingSize = val;
896 "Invalid -Xms '%s', range is %dKB to %dKB\n",
897 argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
901 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
904 } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
905 size_t val = parseMemOption(argv[i]+4, 1024);
907 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
908 gDvm.heapMaximumSize = val;
911 "Invalid -Xmx '%s', range is %dKB to %dKB\n",
912 argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
916 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
919 } else if (strncmp(argv[i], "-XX:HeapGrowthLimit=", 20) == 0) {
920 size_t val = parseMemOption(argv[i] + 20, 1024);
922 gDvm.heapGrowthLimit = val;
924 dvmFprintf(stderr, "Invalid -XX:HeapGrowthLimit option '%s'\n", argv[i]);
927 } else if (strncmp(argv[i], "-XX:HeapMinFree=", 16) == 0) {
928 size_t val = parseMemOption(argv[i] + 16, 1024);
930 gDvm.heapMinFree = val;
932 dvmFprintf(stderr, "Invalid -XX:HeapMinFree option '%s'\n", argv[i]);
935 } else if (strncmp(argv[i], "-XX:HeapMaxFree=", 16) == 0) {
936 size_t val = parseMemOption(argv[i] + 16, 1024);
938 gDvm.heapMaxFree = val;
940 dvmFprintf(stderr, "Invalid -XX:HeapMaxFree option '%s'\n", argv[i]);
943 } else if (strcmp(argv[i], "-XX:LowMemoryMode") == 0) {
944 gDvm.lowMemoryMode = true;
945 } else if (strncmp(argv[i], "-XX:HeapTargetUtilization=", 26) == 0) {
946 const char* start = argv[i] + 26;
947 const char* end = start;
948 double val = strtod(start, const_cast<char**>(&end));
949 // Ensure that we have a value, there was no cruft after it and it
950 // satisfies a sensible range.
951 bool sane_val = (start != end) && (end[0] == '\0') &&
952 (val >= 0.1) && (val <= 0.9);
954 gDvm.heapTargetUtilization = val;
956 dvmFprintf(stderr, "Invalid -XX:HeapTargetUtilization option '%s'\n", argv[i]);
959 } else if (strncmp(argv[i], "-Xss", 4) == 0) {
960 size_t val = parseMemOption(argv[i]+4, 1);
962 if (val >= kMinStackSize && val <= kMaxStackSize) {
963 gDvm.stackSize = val;
964 if (val > gDvm.mainThreadStackSize) {
965 gDvm.mainThreadStackSize = val;
968 dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
969 argv[i], kMinStackSize, kMaxStackSize);
973 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
977 } else if (strncmp(argv[i], "-XX:mainThreadStackSize=", strlen("-XX:mainThreadStackSize=")) == 0) {
978 size_t val = parseMemOption(argv[i] + strlen("-XX:mainThreadStackSize="), 1);
980 if (val >= kMinStackSize && val <= kMaxStackSize) {
981 gDvm.mainThreadStackSize = val;
983 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize '%s', range is %d to %d\n",
984 argv[i], kMinStackSize, kMaxStackSize);
988 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize option '%s'\n", argv[i]);
992 } else if (strncmp(argv[i], "-XX:+DisableExplicitGC", 22) == 0) {
993 gDvm.disableExplicitGc = true;
994 } else if (strcmp(argv[i], "-verbose") == 0 ||
995 strcmp(argv[i], "-verbose:class") == 0)
997 // JNI spec says "-verbose:gc,class" is valid, but cmd line
998 // doesn't work that way; may want to support.
999 gDvm.verboseClass = true;
1000 } else if (strcmp(argv[i], "-verbose:jni") == 0) {
1001 gDvm.verboseJni = true;
1002 } else if (strcmp(argv[i], "-verbose:gc") == 0) {
1003 gDvm.verboseGc = true;
1004 } else if (strcmp(argv[i], "-verbose:shutdown") == 0) {
1005 gDvm.verboseShutdown = true;
1007 } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
1008 enableAssertions(argv[i] + 17, true);
1009 } else if (strncmp(argv[i], "-ea", 3) == 0) {
1010 enableAssertions(argv[i] + 3, true);
1011 } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
1012 enableAssertions(argv[i] + 18, false);
1013 } else if (strncmp(argv[i], "-da", 3) == 0) {
1014 enableAssertions(argv[i] + 3, false);
1015 } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
1016 strcmp(argv[i], "-esa") == 0)
1018 enableAssertions(NULL, true);
1019 } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
1020 strcmp(argv[i], "-dsa") == 0)
1022 enableAssertions(NULL, false);
1024 } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
1025 /* nothing to do now -- was handled during JNI init */
1027 } else if (strcmp(argv[i], "-Xdebug") == 0) {
1028 /* accept but ignore */
1030 } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
1031 strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
1035 if (argv[i][1] == 'X')
1036 tail = argv[i] + 10;
1038 tail = argv[i] + 15;
1040 if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
1044 } else if (strcmp(argv[i], "-Xrs") == 0) {
1045 gDvm.reduceSignals = true;
1046 } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
1047 /* disables SIGQUIT handler thread while still blocking SIGQUIT */
1048 /* (useful if we don't want thread but system still signals us) */
1049 gDvm.noQuitHandler = true;
1050 } else if (strcmp(argv[i], "-Xzygote") == 0) {
1052 #if defined(WITH_JIT)
1053 gDvmJit.runningInAndroidFramework = true;
1055 } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
1056 if (strcmp(argv[i] + 9, "none") == 0)
1057 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
1058 else if (strcmp(argv[i] + 9, "verified") == 0)
1059 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1060 else if (strcmp(argv[i] + 9, "all") == 0)
1061 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
1062 else if (strcmp(argv[i] + 9, "full") == 0)
1063 gDvm.dexOptMode = OPTIMIZE_MODE_FULL;
1065 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
1068 } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
1069 if (strcmp(argv[i] + 9, "none") == 0)
1070 gDvm.classVerifyMode = VERIFY_MODE_NONE;
1071 else if (strcmp(argv[i] + 9, "remote") == 0)
1072 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
1073 else if (strcmp(argv[i] + 9, "all") == 0)
1074 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1076 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
1079 } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
1080 // Ignored for backwards compatibility.
1081 } else if (strncmp(argv[i], "-Xjnitrace:", 11) == 0) {
1082 gDvm.jniTrace = strdup(argv[i] + 11);
1083 } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
1084 gDvm.logStdio = true;
1086 } else if (strncmp(argv[i], "-Xint", 5) == 0) {
1087 if (argv[i][5] == ':') {
1088 if (strcmp(argv[i] + 6, "portable") == 0)
1089 gDvm.executionMode = kExecutionModeInterpPortable;
1090 else if (strcmp(argv[i] + 6, "fast") == 0)
1091 gDvm.executionMode = kExecutionModeInterpFast;
1093 else if (strcmp(argv[i] + 6, "jit") == 0)
1094 gDvm.executionMode = kExecutionModeJit;
1098 "Warning: Unrecognized interpreter mode %s\n",argv[i]);
1102 /* disable JIT if it was enabled by default */
1103 gDvm.executionMode = kExecutionModeInterpFast;
1106 } else if (strncmp(argv[i], "-Xlockprofthreshold:", 20) == 0) {
1107 gDvm.lockProfThreshold = atoi(argv[i] + 20);
1110 } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
1111 processXjitop(argv[i]);
1112 } else if (strncmp(argv[i], "-Xjitmethod:", 12) == 0) {
1113 processXjitmethod(argv[i] + strlen("-Xjitmethod:"), true);
1114 } else if (strncmp(argv[i], "-Xjitclass:", 11) == 0) {
1115 processXjitmethod(argv[i] + strlen("-Xjitclass:"), false);
1116 } else if (strncmp(argv[i], "-Xjitoffset:", 12) == 0) {
1117 processXjitoffset(argv[i] + strlen("-Xjitoffset:"));
1118 } else if (strncmp(argv[i], "-Xjitconfig:", 12) == 0) {
1119 processXjitconfig(argv[i] + strlen("-Xjitconfig:"));
1120 } else if (strncmp(argv[i], "-Xjitblocking", 13) == 0) {
1121 gDvmJit.blockingMode = true;
1122 } else if (strncmp(argv[i], "-Xjitthreshold:", 15) == 0) {
1123 gDvmJit.threshold = atoi(argv[i] + 15);
1124 } else if (strncmp(argv[i], "-Xjitcodecachesize:", 19) == 0) {
1125 gDvmJit.codeCacheSize = atoi(argv[i] + 19) * 1024;
1126 if (gDvmJit.codeCacheSize == 0) {
1127 gDvm.executionMode = kExecutionModeInterpFast;
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 */
1149 gDvmJit.disableOpt = -1;
1151 } else if (strncmp(argv[i], "-Xjitsuspendpoll", 16) == 0) {
1152 gDvmJit.genSuspendPoll = true;
1155 } else if (strncmp(argv[i], "-Xstacktracefile:", 17) == 0) {
1156 gDvm.stackTraceFile = strdup(argv[i]+17);
1158 } else if (strcmp(argv[i], "-Xgenregmap") == 0) {
1159 gDvm.generateRegisterMaps = true;
1160 } else if (strcmp(argv[i], "-Xnogenregmap") == 0) {
1161 gDvm.generateRegisterMaps = false;
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;
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;
1190 dvmFprintf(stderr, "Bad value for -Xgc");
1193 ALOGV("Precise GC configured %s", gDvm.preciseGc ? "ON" : "OFF");
1195 } else if (strcmp(argv[i], "-Xcheckdexsum") == 0) {
1196 gDvm.verifyDexChecksum = true;
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;
1206 if (!ignoreUnrecognized) {
1207 dvmFprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
1217 * Set defaults for fields altered or modified by arguments.
1219 * Globals are initialized to 0 (a/k/a NULL or false).
1221 static void setCommandLineDefaults()
1223 const char* envStr = getenv("CLASSPATH");
1224 if (envStr != NULL) {
1225 gDvm.classPathStr = strdup(envStr);
1227 gDvm.classPathStr = strdup(".");
1229 envStr = getenv("BOOTCLASSPATH");
1230 if (envStr != NULL) {
1231 gDvm.bootClassPathStr = strdup(envStr);
1233 gDvm.bootClassPathStr = strdup(".");
1236 gDvm.properties = new std::vector<std::string>();
1238 /* Defaults overridden by -Xms and -Xmx.
1239 * TODO: base these on a system or application-specific default
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.lowMemoryMode = false;
1245 gDvm.stackSize = kDefaultStackSize;
1246 gDvm.mainThreadStackSize = kDefaultStackSize;
1247 // When the heap is less than the maximum or growth limited size,
1248 // fix the free portion of the heap. The utilization is the ratio
1249 // of live to free memory, 0.5 implies half the heap is available
1250 // to allocate into before a GC occurs. Min free and max free
1251 // force the free memory to never be smaller than min free or
1252 // larger than max free.
1253 gDvm.heapTargetUtilization = 0.5;
1254 gDvm.heapMaxFree = 2 * 1024 * 1024;
1255 gDvm.heapMinFree = gDvm.heapMaxFree / 4;
1257 gDvm.concurrentMarkSweep = true;
1259 /* gDvm.jdwpSuspend = true; */
1261 /* allowed unless zygote config doesn't allow it */
1262 gDvm.jdwpAllowed = true;
1264 /* default verification and optimization modes */
1265 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1266 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1267 gDvm.monitorVerification = false;
1268 gDvm.generateRegisterMaps = true;
1269 gDvm.registerMapMode = kRegisterMapModeTypePrecise;
1272 * Default execution mode.
1274 * This should probably interact with the mterp code somehow, e.g. if
1275 * we know we're using the "desktop" build we should probably be
1276 * using "portable" rather than "fast".
1278 #if defined(WITH_JIT)
1279 gDvm.executionMode = kExecutionModeJit;
1280 gDvmJit.num_entries_pcTable = 0;
1281 gDvmJit.includeSelectedMethod = false;
1282 gDvmJit.includeSelectedOffset = false;
1283 gDvmJit.methodTable = NULL;
1284 gDvmJit.classTable = NULL;
1285 gDvmJit.codeCacheSize = DEFAULT_CODE_CACHE_SIZE;
1287 gDvm.constInit = false;
1288 gDvm.commonInit = false;
1290 gDvm.executionMode = kExecutionModeInterpFast;
1294 * SMP support is a compile-time define, but we may want to have
1295 * dexopt target a differently-configured device.
1297 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1300 * Default profiler configuration.
1302 gDvm.profilerClockSource = kProfilerClockSourceDual;
1307 * Handle a SIGBUS, which frequently occurs because somebody replaced an
1308 * optimized DEX file out from under us.
1310 static void busCatcher(int signum, siginfo_t* info, void* context)
1312 void* addr = info->si_addr;
1314 ALOGE("Caught a SIGBUS (%d), addr=%p", signum, addr);
1317 * If we return at this point the SIGBUS just keeps happening, so we
1318 * remove the signal handler and allow it to kill us. TODO: restore
1319 * the original, which points to a debuggerd stub; if we don't then
1320 * debuggerd won't be notified.
1322 signal(SIGBUS, SIG_DFL);
1326 * Configure signals. We need to block SIGQUIT so that the signal only
1327 * reaches the dump-stack-trace thread.
1329 * This can be disabled with the "-Xrs" flag.
1331 static void blockSignals()
1337 sigaddset(&mask, SIGQUIT);
1338 sigaddset(&mask, SIGUSR1); // used to initiate heap dump
1339 #if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1340 sigaddset(&mask, SIGUSR2); // used to investigate JIT internals
1342 sigaddset(&mask, SIGPIPE);
1343 cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1347 /* TODO: save the old sigaction in a global */
1348 struct sigaction sa;
1349 memset(&sa, 0, sizeof(sa));
1350 sa.sa_sigaction = busCatcher;
1351 sa.sa_flags = SA_SIGINFO;
1352 cc = sigaction(SIGBUS, &sa, NULL);
1357 class ScopedShutdown {
1359 ScopedShutdown() : armed_(true) {
1377 * VM initialization. Pass in any options provided on the command line.
1378 * Do not pass in the class name or the options for the class.
1380 * Returns 0 on success.
1382 std::string dvmStartup(int argc, const char* const argv[],
1383 bool ignoreUnrecognized, JNIEnv* pEnv)
1385 ScopedShutdown scopedShutdown;
1387 assert(gDvm.initializing);
1389 ALOGV("VM init args (%d):", argc);
1390 for (int i = 0; i < argc; i++) {
1391 ALOGV(" %d: '%s'", i, argv[i]);
1393 setCommandLineDefaults();
1396 * Process the option flags (if any).
1398 int cc = processOptions(argc, argv, ignoreUnrecognized);
1401 dvmFprintf(stderr, "\n");
1404 return "syntax error";
1407 #if WITH_EXTRA_GC_CHECKS > 1
1408 /* only "portable" interp has the extra goodies */
1409 if (gDvm.executionMode != kExecutionModeInterpPortable) {
1410 ALOGI("Switching to 'portable' interpreter for GC checks");
1411 gDvm.executionMode = kExecutionModeInterpPortable;
1415 /* Configure group scheduling capabilities */
1416 if (!access("/dev/cpuctl/tasks", F_OK)) {
1417 ALOGV("Using kernel group scheduling");
1418 gDvm.kernelGroupScheduling = 1;
1420 ALOGV("Using kernel scheduler policies");
1423 /* configure signal handling */
1424 if (!gDvm.reduceSignals)
1427 /* verify system page size */
1428 if (sysconf(_SC_PAGESIZE) != SYSTEM_PAGE_SIZE) {
1429 return StringPrintf("expected page size %d, got %d",
1430 SYSTEM_PAGE_SIZE, (int) sysconf(_SC_PAGESIZE));
1434 ALOGV("Using executionMode %d", gDvm.executionMode);
1435 dvmCheckAsmConstants();
1438 * Initialize components.
1440 dvmQuasiAtomicsStartup();
1441 if (!dvmAllocTrackerStartup()) {
1442 return "dvmAllocTrackerStartup failed";
1444 if (!dvmGcStartup()) {
1445 return "dvmGcStartup failed";
1447 if (!dvmThreadStartup()) {
1448 return "dvmThreadStartup failed";
1450 if (!dvmInlineNativeStartup()) {
1451 return "dvmInlineNativeStartup";
1453 if (!dvmRegisterMapStartup()) {
1454 return "dvmRegisterMapStartup failed";
1456 if (!dvmInstanceofStartup()) {
1457 return "dvmInstanceofStartup failed";
1459 if (!dvmClassStartup()) {
1460 return "dvmClassStartup failed";
1464 * At this point, the system is guaranteed to be sufficiently
1465 * initialized that we can look up classes and class members. This
1466 * call populates the gDvm instance with all the class and member
1467 * references that the VM wants to use directly.
1469 if (!dvmFindRequiredClassesAndMembers()) {
1470 return "dvmFindRequiredClassesAndMembers failed";
1473 if (!dvmStringInternStartup()) {
1474 return "dvmStringInternStartup failed";
1476 if (!dvmNativeStartup()) {
1477 return "dvmNativeStartup failed";
1479 if (!dvmInternalNativeStartup()) {
1480 return "dvmInternalNativeStartup failed";
1482 if (!dvmJniStartup()) {
1483 return "dvmJniStartup failed";
1485 if (!dvmProfilingStartup()) {
1486 return "dvmProfilingStartup failed";
1490 * Create a table of methods for which we will substitute an "inline"
1491 * version for performance.
1493 if (!dvmCreateInlineSubsTable()) {
1494 return "dvmCreateInlineSubsTable failed";
1498 * Miscellaneous class library validation.
1500 if (!dvmValidateBoxClasses()) {
1501 return "dvmValidateBoxClasses failed";
1505 * Do the last bits of Thread struct initialization we need to allow
1506 * JNI calls to work.
1508 if (!dvmPrepMainForJni(pEnv)) {
1509 return "dvmPrepMainForJni failed";
1513 * Explicitly initialize java.lang.Class. This doesn't happen
1514 * automatically because it's allocated specially (it's an instance
1515 * of itself). Must happen before registration of system natives,
1516 * which make some calls that throw assertions if the classes they
1517 * operate on aren't initialized.
1519 if (!dvmInitClass(gDvm.classJavaLangClass)) {
1520 return "couldn't initialized java.lang.Class";
1524 * Register the system native methods, which are registered through JNI.
1526 if (!registerSystemNatives(pEnv)) {
1527 return "couldn't register system natives";
1531 * Do some "late" initialization for the memory allocator. This may
1532 * allocate storage and initialize classes.
1534 if (!dvmCreateStockExceptions()) {
1535 return "dvmCreateStockExceptions failed";
1539 * At this point, the VM is in a pretty good state. Finish prep on
1540 * the main thread (specifically, create a java.lang.Thread object to go
1541 * along with our Thread struct). Note we will probably be executing
1542 * some interpreted class initializer code in here.
1544 if (!dvmPrepMainThread()) {
1545 return "dvmPrepMainThread failed";
1549 * Make sure we haven't accumulated any tracked references. The main
1550 * thread should be starting with a clean slate.
1552 if (dvmReferenceTableEntries(&dvmThreadSelf()->internalLocalRefTable) != 0)
1554 ALOGW("Warning: tracked references remain post-initialization");
1555 dvmDumpReferenceTable(&dvmThreadSelf()->internalLocalRefTable, "MAIN");
1558 /* general debugging setup */
1559 if (!dvmDebuggerStartup()) {
1560 return "dvmDebuggerStartup failed";
1563 if (!dvmGcStartupClasses()) {
1564 return "dvmGcStartupClasses failed";
1568 * Init for either zygote mode or non-zygote mode. The key difference
1569 * is that we don't start any additional threads in Zygote mode.
1572 if (!initZygote()) {
1573 return "initZygote failed";
1576 if (!dvmInitAfterZygote()) {
1577 return "dvmInitAfterZygote failed";
1584 ALOGE("dvmTestHash FAILED");
1585 if (false /*noisy!*/ && !dvmTestIndirectRefTable())
1586 ALOGE("dvmTestIndirectRefTable FAILED");
1589 if (dvmCheckException(dvmThreadSelf())) {
1590 dvmLogExceptionStackTrace();
1591 return "Exception pending at end of VM initialization";
1594 scopedShutdown.disarm();
1598 static void loadJniLibrary(const char* name) {
1599 std::string mappedName(StringPrintf(OS_SHARED_LIB_FORMAT_STR, name));
1600 char* reason = NULL;
1601 if (!dvmLoadNativeCode(mappedName.c_str(), NULL, &reason)) {
1602 ALOGE("dvmLoadNativeCode failed for \"%s\": %s", name, reason);
1608 * Register java.* natives from our class libraries. We need to do
1609 * this after we're ready for JNI registration calls, but before we
1610 * do any class initialization.
1612 * If we get this wrong, we will blow up in the ThreadGroup class init if
1613 * interpreted code makes any reference to System. It will likely do this
1614 * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1616 * We need to have gDvm.initializing raised here so that JNI FindClass
1617 * won't try to use the system/application class loader.
1619 static bool registerSystemNatives(JNIEnv* pEnv)
1621 // Main thread is always first in list.
1622 Thread* self = gDvm.threadList;
1624 // Must set this before allowing JNI-based method registration.
1625 self->status = THREAD_NATIVE;
1627 // First set up JniConstants, which is used by libcore.
1628 JniConstants::init(pEnv);
1630 // Set up our single JNI method.
1631 // TODO: factor this out if we add more.
1632 jclass c = pEnv->FindClass("java/lang/Class");
1636 JNIEXPORT jobject JNICALL Java_java_lang_Class_getDex(JNIEnv* env, jclass javaClass);
1637 const JNINativeMethod Java_java_lang_Class[] = {
1638 { "getDex", "()Lcom/android/dex/Dex;", (void*) Java_java_lang_Class_getDex },
1640 if (pEnv->RegisterNatives(c, Java_java_lang_Class, 1) != JNI_OK) {
1644 // Most JNI libraries can just use System.loadLibrary, but you can't
1645 // if you're the library that implements System.loadLibrary!
1646 loadJniLibrary("javacore");
1647 loadJniLibrary("nativehelper");
1649 // Back to run mode.
1650 self->status = THREAD_RUNNING;
1656 * Copied and modified slightly from system/core/toolbox/mount.c
1658 static std::string getMountsDevDir(const char *arg)
1660 char mount_dev[256];
1661 char mount_dir[256];
1664 FILE *fp = fopen("/proc/self/mounts", "r");
1666 ALOGE("Could not open /proc/self/mounts: %s", strerror(errno));
1670 while ((match = fscanf(fp, "%255s %255s %*s %*s %*d %*d\n", mount_dev, mount_dir)) != EOF) {
1673 if (match == 2 && (strcmp(arg, mount_dir) == 0)) {
1684 * Do zygote-mode-only initialization.
1686 static bool initZygote()
1688 /* zygote goes into its own process group */
1691 // See storage config details at http://source.android.com/tech/storage/
1692 // Create private mount namespace shared by all children
1693 if (unshare(CLONE_NEWNS) == -1) {
1694 SLOGE("Failed to unshare(): %s", strerror(errno));
1698 // Mark rootfs as being a slave so that changes from default
1699 // namespace only flow into our children.
1700 if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
1701 SLOGE("Failed to mount() rootfs as MS_SLAVE: %s", strerror(errno));
1705 // Create a staging tmpfs that is shared by our children; they will
1706 // bind mount storage into their respective private namespaces, which
1707 // are isolated from each other.
1708 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1709 if (target_base != NULL) {
1710 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1711 "uid=0,gid=1028,mode=0050") == -1) {
1712 SLOGE("Failed to mount tmpfs to %s: %s", target_base, strerror(errno));
1717 // Mark /system as NOSUID | NODEV
1718 const char* android_root = getenv("ANDROID_ROOT");
1720 if (android_root == NULL) {
1721 SLOGE("environment variable ANDROID_ROOT does not exist?!?!");
1725 std::string mountDev(getMountsDevDir(android_root));
1726 if (mountDev.empty()) {
1727 SLOGE("Unable to find mount point for %s", android_root);
1731 if (mount(mountDev.c_str(), android_root, "none",
1732 MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_RDONLY | MS_BIND, NULL) == -1) {
1733 SLOGE("Remount of %s failed: %s", android_root, strerror(errno));
1737 #ifdef HAVE_ANDROID_OS
1738 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1739 // Older kernels don't understand PR_SET_NO_NEW_PRIVS and return
1740 // EINVAL. Don't die on such kernels.
1741 if (errno != EINVAL) {
1742 SLOGE("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
1752 * Do non-zygote-mode initialization. This is done during VM init for
1753 * standard startup, or after a "zygote fork" when creating a new process.
1755 bool dvmInitAfterZygote()
1757 u8 startHeap, startQuit, startJdwp;
1758 u8 endHeap, endQuit, endJdwp;
1760 startHeap = dvmGetRelativeTimeUsec();
1763 * Post-zygote heap initialization, including starting
1764 * the HeapWorker thread.
1766 if (!dvmGcStartupAfterZygote())
1769 endHeap = dvmGetRelativeTimeUsec();
1770 startQuit = dvmGetRelativeTimeUsec();
1772 /* start signal catcher thread that dumps stacks on SIGQUIT */
1773 if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1774 if (!dvmSignalCatcherStartup())
1778 /* start stdout/stderr copier, if requested */
1779 if (gDvm.logStdio) {
1780 if (!dvmStdioConverterStartup())
1784 endQuit = dvmGetRelativeTimeUsec();
1785 startJdwp = dvmGetRelativeTimeUsec();
1788 * Start JDWP thread. If the command-line debugger flags specified
1789 * "suspend=y", this will pause the VM. We probably want this to
1793 ALOGD("JDWP init failed; continuing anyway");
1796 endJdwp = dvmGetRelativeTimeUsec();
1798 ALOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec",
1799 (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1800 (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1803 if (gDvm.executionMode == kExecutionModeJit) {
1804 if (!dvmCompilerStartup())
1813 * Prepare for a connection to a JDWP-compliant debugger.
1815 * Note this needs to happen fairly late in the startup process, because
1816 * we need to have all of the java.* native methods registered (which in
1817 * turn requires JNI to be fully prepped).
1819 * There are several ways to initialize:
1821 * We immediately try to connect to host:port. Bail on failure. On
1822 * success, send VM_START (suspending the VM if "suspend=y").
1823 * server=y suspend=n
1824 * Passively listen for a debugger to connect. Return immediately.
1825 * server=y suspend=y
1826 * Wait until debugger connects. Send VM_START ASAP, suspending the
1827 * VM after the message is sent.
1829 * This gets more complicated with a nonzero value for "timeout".
1831 static bool initJdwp()
1833 assert(!gDvm.zygote);
1836 * Init JDWP if the debugger is enabled. This may connect out to a
1837 * debugger, passively listen for a debugger, or block waiting for a
1840 if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1841 JdwpStartupParams params;
1843 if (gDvm.jdwpHost != NULL) {
1844 if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1845 ALOGE("ERROR: hostname too long: '%s'", gDvm.jdwpHost);
1848 strcpy(params.host, gDvm.jdwpHost);
1850 params.host[0] = '\0';
1852 params.transport = gDvm.jdwpTransport;
1853 params.server = gDvm.jdwpServer;
1854 params.suspend = gDvm.jdwpSuspend;
1855 params.port = gDvm.jdwpPort;
1857 gDvm.jdwpState = dvmJdwpStartup(¶ms);
1858 if (gDvm.jdwpState == NULL) {
1859 ALOGW("WARNING: debugger thread failed to initialize");
1860 /* TODO: ignore? fail? need to mimic "expected" behavior */
1865 * If a debugger has already attached, send the "welcome" message. This
1866 * may cause us to suspend all threads.
1868 if (dvmJdwpIsActive(gDvm.jdwpState)) {
1869 //dvmChangeStatus(NULL, THREAD_RUNNING);
1870 if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1871 ALOGW("WARNING: failed to post 'start' message to debugger");
1874 //dvmChangeStatus(NULL, THREAD_NATIVE);
1881 * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1882 * of initialization and then returns with "initializing" still set. (Used
1883 * by DexOpt command-line utility.)
1885 * Attempting to use JNI or internal natives will fail. It's best
1886 * if no bytecode gets executed, which means no <clinit>, which means
1887 * no exception-throwing. (In practice we need to initialize Class and
1888 * Object, and probably some exception classes.)
1890 * Returns 0 on success.
1892 int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1893 DexClassVerifyMode verifyMode, int dexoptFlags)
1895 gDvm.initializing = true;
1896 gDvm.optimizing = true;
1898 /* configure signal handling */
1901 /* set some defaults */
1902 setCommandLineDefaults();
1903 free(gDvm.bootClassPathStr);
1904 gDvm.bootClassPathStr = strdup(bootClassPath);
1906 /* set opt/verify modes */
1907 gDvm.dexOptMode = dexOptMode;
1908 gDvm.classVerifyMode = verifyMode;
1909 gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1910 if (dexoptFlags & DEXOPT_SMP) {
1911 assert((dexoptFlags & DEXOPT_UNIPROCESSOR) == 0);
1912 gDvm.dexOptForSmp = true;
1913 } else if (dexoptFlags & DEXOPT_UNIPROCESSOR) {
1914 gDvm.dexOptForSmp = false;
1916 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1920 * Initialize the heap, some basic thread control mutexes, and
1921 * get the bootclasspath prepped.
1923 * We can't load any classes yet because we may not yet have a source
1924 * for things like java.lang.Object and java.lang.Class.
1926 if (!dvmGcStartup())
1928 if (!dvmThreadStartup())
1930 if (!dvmInlineNativeStartup())
1932 if (!dvmRegisterMapStartup())
1934 if (!dvmInstanceofStartup())
1936 if (!dvmClassStartup())
1940 * We leave gDvm.initializing set to "true" so that, if we're not
1941 * able to process the "core" classes, we don't go into a death-spin
1942 * trying to throw a "class not found" exception.
1954 * All threads have stopped. Finish the shutdown procedure.
1956 * We can also be called if startup fails partway through, so be prepared
1957 * to deal with partially initialized data.
1959 * Free any storage allocated in gGlobals.
1961 * We can't dlclose() shared libs we've loaded, because it's possible a
1962 * thread not associated with the VM is running code in one.
1964 * This is called from the JNI DestroyJavaVM function, which can be
1965 * called from any thread. (In practice, this will usually run in the
1966 * same thread that started the VM, a/k/a the main thread, but we don't
1967 * want to assume that.)
1971 ALOGV("VM shutting down");
1973 if (CALC_CACHE_STATS)
1974 dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1977 * Stop our internal threads.
1979 dvmGcThreadShutdown();
1981 if (gDvm.jdwpState != NULL)
1982 dvmJdwpShutdown(gDvm.jdwpState);
1983 free(gDvm.jdwpHost);
1984 gDvm.jdwpHost = NULL;
1985 free(gDvm.jniTrace);
1986 gDvm.jniTrace = NULL;
1987 free(gDvm.stackTraceFile);
1988 gDvm.stackTraceFile = NULL;
1990 /* tell signal catcher to shut down if it was started */
1991 dvmSignalCatcherShutdown();
1993 /* shut down stdout/stderr conversion */
1994 dvmStdioConverterShutdown();
1997 if (gDvm.executionMode == kExecutionModeJit) {
1998 /* shut down the compiler thread */
1999 dvmCompilerShutdown();
2004 * Kill any daemon threads that still exist. Actively-running threads
2005 * are likely to crash the process if they continue to execute while
2006 * the VM shuts down.
2010 if (gDvm.verboseShutdown)
2011 ALOGD("VM cleaning up");
2013 dvmDebuggerShutdown();
2014 dvmProfilingShutdown();
2016 dvmStringInternShutdown();
2017 dvmThreadShutdown();
2019 dvmRegisterMapShutdown();
2020 dvmInstanceofShutdown();
2021 dvmInlineNativeShutdown();
2023 dvmAllocTrackerShutdown();
2025 /* these must happen AFTER dvmClassShutdown has walked through class data */
2026 dvmNativeShutdown();
2027 dvmInternalNativeShutdown();
2029 dvmFreeInlineSubsTable();
2031 free(gDvm.bootClassPathStr);
2032 free(gDvm.classPathStr);
2033 delete gDvm.properties;
2035 freeAssertionCtrl();
2037 dvmQuasiAtomicsShutdown();
2040 * We want valgrind to report anything we forget to free as "definitely
2041 * lost". If there's a pointer in the global chunk, it would be reported
2042 * as "still reachable". Erasing the memory fixes this.
2044 * This must be erased to zero if we want to restart the VM within this
2047 memset(&gDvm, 0xcd, sizeof(gDvm));
2052 * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
2053 * one was specified.
2055 int dvmFprintf(FILE* fp, const char* format, ...)
2060 va_start(args, format);
2061 if (gDvm.vfprintfHook != NULL)
2062 result = (*gDvm.vfprintfHook)(fp, format, args);
2064 result = vfprintf(fp, format, args);
2071 #include <execinfo.h>
2073 * glibc-only stack dump function. Requires link with "--export-dynamic".
2075 * TODO: move this into libs/cutils and make it work for all platforms.
2077 void dvmPrintNativeBackTrace()
2079 size_t MAX_STACK_FRAMES = 64;
2080 void* stackFrames[MAX_STACK_FRAMES];
2081 size_t frameCount = backtrace(stackFrames, MAX_STACK_FRAMES);
2084 * TODO: in practice, we may find that we should use backtrace_symbols_fd
2085 * to avoid allocation, rather than use our own custom formatting.
2087 char** strings = backtrace_symbols(stackFrames, frameCount);
2088 if (strings == NULL) {
2089 ALOGE("backtrace_symbols failed: %s", strerror(errno));
2094 for (i = 0; i < frameCount; ++i) {
2095 ALOGW("#%-2d %s", i, strings[i]);
2100 void dvmPrintNativeBackTrace() {
2101 /* Hopefully, you're on an Android device and debuggerd will do this. */
2106 * Abort the VM. We get here on fatal errors. Try very hard not to use
2107 * this; whenever possible, return an error to somebody responsible.
2112 * Leave gDvm.lastMessage on the stack frame which can be decoded in the
2113 * tombstone file. This is for situations where we only have tombstone files
2114 * but no logs (ie b/5372634).
2116 * For example, in the tombstone file you usually see this:
2118 * #00 pc 00050ef2 /system/lib/libdvm.so (dvmAbort)
2119 * #01 pc 00077670 /system/lib/libdvm.so (_Z15dvmClassStartupv)
2124 * #00 beed2658 00000000
2134 * The ascii values between beed265c and beed2674 belongs to messageBuffer
2135 * and it can be decoded as "/system/framework/core.jar".
2137 const int messageLength = 512;
2138 char messageBuffer[messageLength] = {0};
2141 snprintf(messageBuffer, messageLength, "%s", gDvm.lastMessage);
2143 /* So that messageBuffer[] looks like useful stuff to the compiler */
2144 for (int i = 0; i < messageLength && messageBuffer[i]; i++) {
2145 result += messageBuffer[i];
2148 ALOGE("VM aborting");
2150 fflush(NULL); // flush all open file buffers
2152 /* JNI-supplied abort hook gets right of first refusal */
2153 if (gDvm.abortHook != NULL)
2154 (*gDvm.abortHook)();
2157 * On the device, debuggerd will give us a stack trace.
2158 * On the host, we have to help ourselves.
2160 dvmPrintNativeBackTrace();