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, " -Xjitblocking\n");
143 dvmFprintf(stderr, " -Xjitmethod:signature[,signature]* "
144 "(eg Ljava/lang/String\\;replace)\n");
145 dvmFprintf(stderr, " -Xjitclass:classname[,classname]*\n");
146 dvmFprintf(stderr, " -Xjitoffset:offset[,offset]\n");
147 dvmFprintf(stderr, " -Xjitconfig:filename\n");
148 dvmFprintf(stderr, " -Xjitcheckcg\n");
149 dvmFprintf(stderr, " -Xjitverbose\n");
150 dvmFprintf(stderr, " -Xjitprofile\n");
151 dvmFprintf(stderr, " -Xjitdisableopt\n");
152 dvmFprintf(stderr, " -Xjitsuspendpoll\n");
154 dvmFprintf(stderr, "\n");
155 dvmFprintf(stderr, "Configured with:"
159 #ifdef WITH_TRACKREF_CHECKS
162 #ifdef WITH_INSTR_CHECKS
165 #ifdef WITH_EXTRA_OBJECT_VALIDATION
166 " extra_object_validation"
168 #ifdef WITH_EXTRA_GC_CHECKS
171 #if !defined(NDEBUG) && defined(WITH_DALVIK_ASSERT)
174 #ifdef WITH_JNI_STACK_CHECK
183 #if defined(WITH_JIT)
184 " jit(" ARCH_VARIANT ")"
186 #if defined(WITH_SELF_VERIFICATION)
193 #ifdef DVM_SHOW_EXCEPTION
194 dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
196 dvmFprintf(stderr, "\n\n");
200 * Show helpful information on JDWP options.
202 static void showJdwpHelp()
205 "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
207 "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
211 * Show version and copyright info.
213 static void showVersion()
215 dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
216 DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
218 "Copyright (C) 2007 The Android Open Source Project\n\n"
219 "This software is built from source code licensed under the "
221 "Version 2.0 (the \"License\"). You may obtain a copy of the "
223 " http://www.apache.org/licenses/LICENSE-2.0\n\n"
224 "See the associated NOTICE file for this software for further "
229 * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
230 * memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
233 * "s" should point just past the "-Xm?" part of the string.
234 * "min" specifies the lowest acceptable value described by "s".
235 * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
238 * The spec says the -Xmx and -Xms options must be multiples of 1024. It
239 * doesn't say anything about -Xss.
241 * Returns 0 (a useless size) if "s" is malformed or specifies a low or
242 * non-evenly-divisible value.
244 static size_t parseMemOption(const char* s, size_t div)
246 /* strtoul accepts a leading [+-], which we don't want,
247 * so make sure our string starts with a decimal digit.
253 val = strtoul(s, (char* *)&s2, 10);
255 /* s2 should be pointing just after the number.
256 * If this is the end of the string, the user
257 * has specified a number of bytes. Otherwise,
258 * there should be exactly one more character
259 * that specifies a multiplier.
264 /* The remainder of the string is either a single multiplier
265 * character, or nothing to indicate that the value is in
274 } else if (c == 'k' || c == 'K') {
276 } else if (c == 'm' || c == 'M') {
278 } else if (c == 'g' || c == 'G') {
279 mul = 1024 * 1024 * 1024;
281 /* Unknown multiplier character.
286 if (val <= SIZE_MAX / mul) {
289 /* Clamp to a multiple of 1024.
291 val = SIZE_MAX & ~(1024-1);
294 /* There's more than one character after the
301 /* The man page says that a -Xm value must be
302 * a multiple of 1024.
304 if (val % div == 0) {
314 * Handle one of the JDWP name/value pairs.
317 * help: if specified, show help message and bail
318 * transport: may be dt_socket or dt_shmem
319 * address: for dt_socket, "host:port", or just "port" when listening
320 * server: if "y", wait for debugger to attach; if "n", attach to debugger
321 * timeout: how long to wait for debugger to connect / listen
323 * Useful with server=n (these aren't supported yet):
324 * onthrow=<exception-name>: connect to debugger when exception thrown
325 * onuncaught=y|n: connect to debugger when uncaught exception thrown
326 * launch=<command-line>: launch the debugger itself
328 * The "transport" option is required, as is "address" if server=n.
330 static bool handleJdwpOption(const char* name, const char* value)
332 if (strcmp(name, "transport") == 0) {
333 if (strcmp(value, "dt_socket") == 0) {
334 gDvm.jdwpTransport = kJdwpTransportSocket;
335 } else if (strcmp(value, "dt_android_adb") == 0) {
336 gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
338 ALOGE("JDWP transport '%s' not supported", value);
341 } else if (strcmp(name, "server") == 0) {
343 gDvm.jdwpServer = false;
344 else if (*value == 'y')
345 gDvm.jdwpServer = true;
347 ALOGE("JDWP option 'server' must be 'y' or 'n'");
350 } else if (strcmp(name, "suspend") == 0) {
352 gDvm.jdwpSuspend = false;
353 else if (*value == 'y')
354 gDvm.jdwpSuspend = true;
356 ALOGE("JDWP option 'suspend' must be 'y' or 'n'");
359 } else if (strcmp(name, "address") == 0) {
360 /* this is either <port> or <host>:<port> */
361 const char* colon = strchr(value, ':');
367 gDvm.jdwpHost = (char*) malloc(colon - value +1);
368 strncpy(gDvm.jdwpHost, value, colon - value +1);
369 gDvm.jdwpHost[colon-value] = '\0';
372 if (*value == '\0') {
373 ALOGE("JDWP address missing port");
376 port = strtol(value, &end, 10);
378 ALOGE("JDWP address has junk in port field '%s'", value);
381 gDvm.jdwpPort = port;
382 } else if (strcmp(name, "launch") == 0 ||
383 strcmp(name, "onthrow") == 0 ||
384 strcmp(name, "oncaught") == 0 ||
385 strcmp(name, "timeout") == 0)
387 /* valid but unsupported */
388 ALOGI("Ignoring JDWP option '%s'='%s'", name, value);
390 ALOGI("Ignoring unrecognized JDWP option '%s'='%s'", name, value);
397 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
398 * "transport=dt_socket,address=8000,server=y,suspend=n"
400 static bool parseJdwpOptions(const char* str)
402 char* mangle = strdup(str);
407 * Process all of the name=value pairs.
413 value = strchr(name, '=');
415 ALOGE("JDWP opts: garbage at '%s'", name);
419 comma = strchr(name, ','); // use name, not value, for safety
422 ALOGE("JDWP opts: found comma before '=' in '%s'", mangle);
428 *value++ = '\0'; // stomp the '='
430 if (!handleJdwpOption(name, value))
441 * Make sure the combination of arguments makes sense.
443 if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
444 ALOGE("JDWP opts: must specify transport");
447 if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
448 ALOGE("JDWP opts: when server=n, must specify host and port");
451 // transport mandatory
452 // outbound server address
454 gDvm.jdwpConfigured = true;
463 * Handle one of the four kinds of assertion arguments.
465 * "pkgOrClass" is the last part of an enable/disable line. For a package
466 * the arg looks like "-ea:com.google.fubar...", for a class it looks
467 * like "-ea:com.google.fubar.Wahoo". The string we get starts at the ':'.
469 * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
471 * Multiple instances of these arguments can be specified, e.g. you can
472 * enable assertions for a package and then disable them for one class in
475 static bool enableAssertions(const char* pkgOrClass, bool enable)
477 AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
478 pCtrl->enable = enable;
480 if (pkgOrClass == NULL) {
481 /* enable or disable for all system classes */
482 pCtrl->isPackage = false;
483 pCtrl->pkgOrClass = NULL;
484 pCtrl->pkgOrClassLen = 0;
486 if (*pkgOrClass == '\0') {
487 /* global enable/disable for all but system */
488 pCtrl->isPackage = false;
489 pCtrl->pkgOrClass = strdup("");
490 pCtrl->pkgOrClassLen = 0;
492 pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1); // skip ':'
493 if (pCtrl->pkgOrClass == NULL) {
494 /* can happen if class name includes an illegal '/' */
495 ALOGW("Unable to process assertion arg '%s'", pkgOrClass);
499 int len = strlen(pCtrl->pkgOrClass);
500 if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
501 /* mark as package, truncate two of the three slashes */
502 pCtrl->isPackage = true;
503 *(pCtrl->pkgOrClass + len-2) = '\0';
504 pCtrl->pkgOrClassLen = len - 2;
507 pCtrl->isPackage = false;
508 pCtrl->pkgOrClassLen = len;
517 * Turn assertions on when requested to do so by the Zygote.
519 * This is a bit sketchy. We can't (easily) go back and fiddle with all
520 * of the classes that have already been initialized, so this only
521 * affects classes that have yet to be loaded. If some or all assertions
522 * have been enabled through some other means, we don't want to mess with
523 * it here, so we do nothing. Finally, we assume that there's room in
524 * "assertionCtrl" to hold at least one entry; this is guaranteed by the
527 * This must only be called from the main thread during zygote init.
529 void dvmLateEnableAssertions()
531 if (gDvm.assertionCtrl == NULL) {
532 ALOGD("Not late-enabling assertions: no assertionCtrl array");
534 } else if (gDvm.assertionCtrlCount != 0) {
535 ALOGD("Not late-enabling assertions: some asserts already configured");
538 ALOGD("Late-enabling assertions");
540 /* global enable for all but system */
541 AssertionControl* pCtrl = gDvm.assertionCtrl;
542 pCtrl->pkgOrClass = strdup("");
543 pCtrl->pkgOrClassLen = 0;
544 pCtrl->isPackage = false;
545 pCtrl->enable = true;
546 gDvm.assertionCtrlCount = 1;
551 * Release memory associated with the AssertionCtrl array.
553 static void freeAssertionCtrl()
557 for (i = 0; i < gDvm.assertionCtrlCount; i++)
558 free(gDvm.assertionCtrl[i].pkgOrClass);
559 free(gDvm.assertionCtrl);
562 #if defined(WITH_JIT)
563 /* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
564 static void processXjitop(const char* opt)
567 const char* startPtr = &opt[8];
571 long startValue, endValue;
573 startValue = strtol(startPtr, &endPtr, 16);
574 if (startPtr != endPtr) {
575 /* Just in case value is out of range */
576 startValue %= kNumPackedOpcodes;
578 if (*endPtr == '-') {
579 endValue = strtol(endPtr+1, &endPtr, 16);
580 endValue %= kNumPackedOpcodes;
582 endValue = startValue;
585 for (; startValue <= endValue; startValue++) {
586 ALOGW("Dalvik opcode %x is selected for debugging",
587 (unsigned int) startValue);
588 /* Mark the corresponding bit to 1 */
589 gDvmJit.opList[startValue >> 3] |= 1 << (startValue & 0x7);
596 startPtr = endPtr + 1;
602 "Warning: Unrecognized opcode value substring "
610 for (i = 0; i < (kNumPackedOpcodes+7)/8; i++) {
611 gDvmJit.opList[i] = 0xff;
613 dvmFprintf(stderr, "Warning: select all opcodes\n");
617 /* Parse -Xjitoffset to selectively turn on/off traces with certain offsets for JIT */
618 static void processXjitoffset(const char* opt) {
619 gDvmJit.num_entries_pcTable = 0;
620 char* buf = strdup(opt);
625 end = strchr(start, ',');
630 dvmFprintf(stderr, "processXjitoffset start = %s\n", start);
631 char* tmp = strdup(start);
632 gDvmJit.pcTable[idx++] = atoi(tmp);
634 if (idx >= COMPILER_PC_OFFSET_SIZE) {
635 dvmFprintf(stderr, "processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
644 gDvmJit.num_entries_pcTable = idx;
648 /* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
649 static void processXjitmethod(const char* opt, bool isMethod) {
650 char* buf = strdup(opt);
652 if (isMethod && gDvmJit.methodTable == NULL) {
653 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
655 if (!isMethod && gDvmJit.classTable == NULL) {
656 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
662 * Break comma-separated method signatures and enter them into the hash
663 * table individually.
668 end = strchr(start, ',');
673 hashValue = dvmComputeUtf8Hash(start);
674 dvmHashTableLookup(isMethod ? gDvmJit.methodTable : gDvmJit.classTable,
675 hashValue, strdup(start), (HashCompareFunc) strcmp, true);
686 /* The format of jit_config.list:
693 index ... //each pair is a range, if pcOff falls into a range, JIT
695 static int processXjitconfig(const char* opt) {
696 FILE* fp = fopen(opt, "r");
702 bool startClass = false, startMethod = false, startOffset = false;
703 gDvmJit.num_entries_pcTable = 0;
706 while (fgets(fLine, 500, fp) != NULL) {
707 char* curLine = strtok(fLine, " \t\r\n");
708 /* handles keyword CLASS, METHOD, INCLUDE, EXCLUDE */
709 if (!strncmp(curLine, "CLASS", 5)) {
715 if (!strncmp(curLine, "METHOD", 6)) {
721 if (!strncmp(curLine, "OFFSET", 6)) {
727 if (!strncmp(curLine, "EXCLUDE", 7)) {
728 gDvmJit.includeSelectedMethod = false;
731 if (!strncmp(curLine, "INCLUDE", 7)) {
732 gDvmJit.includeSelectedMethod = true;
735 if (!startMethod && !startClass && !startOffset) {
739 int hashValue = dvmComputeUtf8Hash(curLine);
741 if (gDvmJit.methodTable == NULL) {
742 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
744 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
746 (HashCompareFunc) strcmp, true);
747 } else if (startClass) {
748 if (gDvmJit.classTable == NULL) {
749 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
751 dvmHashTableLookup(gDvmJit.classTable, hashValue,
753 (HashCompareFunc) strcmp, true);
754 } else if (startOffset) {
755 int tmpInt = atoi(curLine);
756 gDvmJit.pcTable[idx++] = tmpInt;
757 if (idx >= COMPILER_PC_OFFSET_SIZE) {
758 printf("processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
763 gDvmJit.num_entries_pcTable = idx;
770 * Process an argument vector full of options. Unlike standard C programs,
771 * argv[0] does not contain the name of the program.
773 * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
774 * that we don't recognize. Otherwise, we return with an error as soon as
775 * we see anything we can't identify.
777 * Returns 0 on success, -1 on failure, and 1 for the special case of
778 * "-version" where we want to stop without showing an error message.
780 static int processOptions(int argc, const char* const argv[],
781 bool ignoreUnrecognized)
785 ALOGV("VM options (%d):", argc);
786 for (i = 0; i < argc; i++)
787 ALOGV(" %d: '%s'", i, argv[i]);
790 * Over-allocate AssertionControl array for convenience. If allocated,
791 * the array must be able to hold at least one entry, so that the
792 * zygote-time activation can do its business.
794 assert(gDvm.assertionCtrl == NULL);
797 (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
798 if (gDvm.assertionCtrl == NULL)
800 assert(gDvm.assertionCtrlCount == 0);
803 for (i = 0; i < argc; i++) {
804 if (strcmp(argv[i], "-help") == 0) {
805 /* show usage and stop */
808 } else if (strcmp(argv[i], "-version") == 0) {
809 /* show version and stop */
812 } else if (strcmp(argv[i], "-showversion") == 0) {
813 /* show version and continue */
816 } else if (strcmp(argv[i], "-classpath") == 0 ||
817 strcmp(argv[i], "-cp") == 0)
821 dvmFprintf(stderr, "Missing classpath path list\n");
824 free(gDvm.classPathStr); /* in case we have compiled-in default */
825 gDvm.classPathStr = strdup(argv[++i]);
827 } else if (strncmp(argv[i], "-Xbootclasspath:",
828 sizeof("-Xbootclasspath:")-1) == 0)
830 /* set bootclasspath */
831 const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
834 dvmFprintf(stderr, "Missing bootclasspath path list\n");
837 free(gDvm.bootClassPathStr);
838 gDvm.bootClassPathStr = strdup(path);
840 } else if (strncmp(argv[i], "-Xbootclasspath/a:",
841 sizeof("-Xbootclasspath/a:")-1) == 0) {
842 const char* appPath = argv[i] + sizeof("-Xbootclasspath/a:")-1;
844 if (*(appPath) == '\0') {
845 dvmFprintf(stderr, "Missing appending bootclasspath path list\n");
850 if (asprintf(&allPath, "%s:%s", gDvm.bootClassPathStr, appPath) < 0) {
851 dvmFprintf(stderr, "Can't append to bootclasspath path list\n");
854 free(gDvm.bootClassPathStr);
855 gDvm.bootClassPathStr = allPath;
857 } else if (strncmp(argv[i], "-Xbootclasspath/p:",
858 sizeof("-Xbootclasspath/p:")-1) == 0) {
859 const char* prePath = argv[i] + sizeof("-Xbootclasspath/p:")-1;
861 if (*(prePath) == '\0') {
862 dvmFprintf(stderr, "Missing prepending bootclasspath path list\n");
867 if (asprintf(&allPath, "%s:%s", prePath, gDvm.bootClassPathStr) < 0) {
868 dvmFprintf(stderr, "Can't prepend to bootclasspath path list\n");
871 free(gDvm.bootClassPathStr);
872 gDvm.bootClassPathStr = allPath;
874 } else if (strncmp(argv[i], "-D", 2) == 0) {
875 /* Properties are handled in managed code. We just check syntax. */
876 if (strchr(argv[i], '=') == NULL) {
877 dvmFprintf(stderr, "Bad system property setting: \"%s\"\n",
881 gDvm.properties->push_back(argv[i] + 2);
883 } else if (strcmp(argv[i], "-jar") == 0) {
884 // TODO: handle this; name of jar should be in argv[i+1]
885 dvmFprintf(stderr, "-jar not yet handled\n");
888 } else if (strncmp(argv[i], "-Xms", 4) == 0) {
889 size_t val = parseMemOption(argv[i]+4, 1024);
891 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
892 gDvm.heapStartingSize = val;
895 "Invalid -Xms '%s', range is %dKB to %dKB\n",
896 argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
900 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
903 } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
904 size_t val = parseMemOption(argv[i]+4, 1024);
906 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
907 gDvm.heapMaximumSize = val;
910 "Invalid -Xmx '%s', range is %dKB to %dKB\n",
911 argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
915 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
918 } else if (strncmp(argv[i], "-XX:HeapGrowthLimit=", 20) == 0) {
919 size_t val = parseMemOption(argv[i] + 20, 1024);
921 gDvm.heapGrowthLimit = val;
923 dvmFprintf(stderr, "Invalid -XX:HeapGrowthLimit option '%s'\n", argv[i]);
926 } else if (strncmp(argv[i], "-XX:HeapMinFree=", 16) == 0) {
927 size_t val = parseMemOption(argv[i] + 16, 1024);
929 gDvm.heapMinFree = val;
931 dvmFprintf(stderr, "Invalid -XX:HeapMinFree option '%s'\n", argv[i]);
934 } else if (strncmp(argv[i], "-XX:HeapMaxFree=", 16) == 0) {
935 size_t val = parseMemOption(argv[i] + 16, 1024);
937 gDvm.heapMaxFree = val;
939 dvmFprintf(stderr, "Invalid -XX:HeapMaxFree option '%s'\n", argv[i]);
942 } else if (strncmp(argv[i], "-XX:HeapTargetUtilization=", 26) == 0) {
943 const char* start = argv[i] + 26;
944 const char* end = start;
945 double val = strtod(start, const_cast<char**>(&end));
946 // Ensure that we have a value, there was no cruft after it and it
947 // satisfies a sensible range.
948 bool sane_val = (start != end) && (end[0] == '\0') &&
949 (val >= 0.1) && (val <= 0.9);
951 gDvm.heapTargetUtilization = val;
953 dvmFprintf(stderr, "Invalid -XX:HeapTargetUtilization option '%s'\n", argv[i]);
956 } else if (strncmp(argv[i], "-Xss", 4) == 0) {
957 size_t val = parseMemOption(argv[i]+4, 1);
959 if (val >= kMinStackSize && val <= kMaxStackSize) {
960 gDvm.stackSize = val;
961 if (val > gDvm.mainThreadStackSize) {
962 gDvm.mainThreadStackSize = val;
965 dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
966 argv[i], kMinStackSize, kMaxStackSize);
970 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
974 } else if (strncmp(argv[i], "-XX:mainThreadStackSize=", strlen("-XX:mainThreadStackSize=")) == 0) {
975 size_t val = parseMemOption(argv[i] + strlen("-XX:mainThreadStackSize="), 1);
977 if (val >= kMinStackSize && val <= kMaxStackSize) {
978 gDvm.mainThreadStackSize = val;
980 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize '%s', range is %d to %d\n",
981 argv[i], kMinStackSize, kMaxStackSize);
985 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize option '%s'\n", argv[i]);
989 } else if (strncmp(argv[i], "-XX:+DisableExplicitGC", 22) == 0) {
990 gDvm.disableExplicitGc = true;
991 } else if (strcmp(argv[i], "-verbose") == 0 ||
992 strcmp(argv[i], "-verbose:class") == 0)
994 // JNI spec says "-verbose:gc,class" is valid, but cmd line
995 // doesn't work that way; may want to support.
996 gDvm.verboseClass = true;
997 } else if (strcmp(argv[i], "-verbose:jni") == 0) {
998 gDvm.verboseJni = true;
999 } else if (strcmp(argv[i], "-verbose:gc") == 0) {
1000 gDvm.verboseGc = true;
1001 } else if (strcmp(argv[i], "-verbose:shutdown") == 0) {
1002 gDvm.verboseShutdown = true;
1004 } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
1005 enableAssertions(argv[i] + 17, true);
1006 } else if (strncmp(argv[i], "-ea", 3) == 0) {
1007 enableAssertions(argv[i] + 3, true);
1008 } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
1009 enableAssertions(argv[i] + 18, false);
1010 } else if (strncmp(argv[i], "-da", 3) == 0) {
1011 enableAssertions(argv[i] + 3, false);
1012 } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
1013 strcmp(argv[i], "-esa") == 0)
1015 enableAssertions(NULL, true);
1016 } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
1017 strcmp(argv[i], "-dsa") == 0)
1019 enableAssertions(NULL, false);
1021 } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
1022 /* nothing to do now -- was handled during JNI init */
1024 } else if (strcmp(argv[i], "-Xdebug") == 0) {
1025 /* accept but ignore */
1027 } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
1028 strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
1032 if (argv[i][1] == 'X')
1033 tail = argv[i] + 10;
1035 tail = argv[i] + 15;
1037 if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
1041 } else if (strcmp(argv[i], "-Xrs") == 0) {
1042 gDvm.reduceSignals = true;
1043 } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
1044 /* disables SIGQUIT handler thread while still blocking SIGQUIT */
1045 /* (useful if we don't want thread but system still signals us) */
1046 gDvm.noQuitHandler = true;
1047 } else if (strcmp(argv[i], "-Xzygote") == 0) {
1049 #if defined(WITH_JIT)
1050 gDvmJit.runningInAndroidFramework = true;
1052 } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
1053 if (strcmp(argv[i] + 9, "none") == 0)
1054 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
1055 else if (strcmp(argv[i] + 9, "verified") == 0)
1056 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1057 else if (strcmp(argv[i] + 9, "all") == 0)
1058 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
1059 else if (strcmp(argv[i] + 9, "full") == 0)
1060 gDvm.dexOptMode = OPTIMIZE_MODE_FULL;
1062 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
1065 } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
1066 if (strcmp(argv[i] + 9, "none") == 0)
1067 gDvm.classVerifyMode = VERIFY_MODE_NONE;
1068 else if (strcmp(argv[i] + 9, "remote") == 0)
1069 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
1070 else if (strcmp(argv[i] + 9, "all") == 0)
1071 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1073 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
1076 } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
1077 // Ignored for backwards compatibility.
1078 } else if (strncmp(argv[i], "-Xjnitrace:", 11) == 0) {
1079 gDvm.jniTrace = strdup(argv[i] + 11);
1080 } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
1081 gDvm.logStdio = true;
1083 } else if (strncmp(argv[i], "-Xint", 5) == 0) {
1084 if (argv[i][5] == ':') {
1085 if (strcmp(argv[i] + 6, "portable") == 0)
1086 gDvm.executionMode = kExecutionModeInterpPortable;
1087 else if (strcmp(argv[i] + 6, "fast") == 0)
1088 gDvm.executionMode = kExecutionModeInterpFast;
1090 else if (strcmp(argv[i] + 6, "jit") == 0)
1091 gDvm.executionMode = kExecutionModeJit;
1095 "Warning: Unrecognized interpreter mode %s\n",argv[i]);
1099 /* disable JIT if it was enabled by default */
1100 gDvm.executionMode = kExecutionModeInterpFast;
1103 } else if (strncmp(argv[i], "-Xlockprofthreshold:", 20) == 0) {
1104 gDvm.lockProfThreshold = atoi(argv[i] + 20);
1107 } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
1108 processXjitop(argv[i]);
1109 } else if (strncmp(argv[i], "-Xjitmethod:", 12) == 0) {
1110 processXjitmethod(argv[i] + strlen("-Xjitmethod:"), true);
1111 } else if (strncmp(argv[i], "-Xjitclass:", 11) == 0) {
1112 processXjitmethod(argv[i] + strlen("-Xjitclass:"), false);
1113 } else if (strncmp(argv[i], "-Xjitoffset:", 12) == 0) {
1114 processXjitoffset(argv[i] + strlen("-Xjitoffset:"));
1115 } else if (strncmp(argv[i], "-Xjitconfig:", 12) == 0) {
1116 processXjitconfig(argv[i] + strlen("-Xjitconfig:"));
1117 } else if (strncmp(argv[i], "-Xjitblocking", 13) == 0) {
1118 gDvmJit.blockingMode = true;
1119 } else if (strncmp(argv[i], "-Xjitthreshold:", 15) == 0) {
1120 gDvmJit.threshold = atoi(argv[i] + 15);
1121 } else if (strncmp(argv[i], "-Xincludeselectedop", 19) == 0) {
1122 gDvmJit.includeSelectedOp = true;
1123 } else if (strncmp(argv[i], "-Xincludeselectedmethod", 23) == 0) {
1124 gDvmJit.includeSelectedMethod = true;
1125 } else if (strncmp(argv[i], "-Xjitcheckcg", 12) == 0) {
1126 gDvmJit.checkCallGraph = true;
1127 /* Need to enable blocking mode due to stack crawling */
1128 gDvmJit.blockingMode = true;
1129 } else if (strncmp(argv[i], "-Xjitdumpbin", 12) == 0) {
1130 gDvmJit.printBinary = true;
1131 } else if (strncmp(argv[i], "-Xjitverbose", 12) == 0) {
1132 gDvmJit.printMe = true;
1133 } else if (strncmp(argv[i], "-Xjitprofile", 12) == 0) {
1134 gDvmJit.profileMode = kTraceProfilingContinuous;
1135 } else if (strncmp(argv[i], "-Xjitdisableopt", 15) == 0) {
1136 /* Disable selected optimizations */
1137 if (argv[i][15] == ':') {
1138 sscanf(argv[i] + 16, "%x", &gDvmJit.disableOpt);
1139 /* Disable all optimizations */
1141 gDvmJit.disableOpt = -1;
1143 } else if (strncmp(argv[i], "-Xjitsuspendpoll", 16) == 0) {
1144 gDvmJit.genSuspendPoll = true;
1147 } else if (strncmp(argv[i], "-Xstacktracefile:", 17) == 0) {
1148 gDvm.stackTraceFile = strdup(argv[i]+17);
1150 } else if (strcmp(argv[i], "-Xgenregmap") == 0) {
1151 gDvm.generateRegisterMaps = true;
1152 } else if (strcmp(argv[i], "-Xnogenregmap") == 0) {
1153 gDvm.generateRegisterMaps = false;
1155 } else if (strcmp(argv[i], "Xverifyopt:checkmon") == 0) {
1156 gDvm.monitorVerification = true;
1157 } else if (strcmp(argv[i], "Xverifyopt:nocheckmon") == 0) {
1158 gDvm.monitorVerification = false;
1160 } else if (strncmp(argv[i], "-Xgc:", 5) == 0) {
1161 if (strcmp(argv[i] + 5, "precise") == 0)
1162 gDvm.preciseGc = true;
1163 else if (strcmp(argv[i] + 5, "noprecise") == 0)
1164 gDvm.preciseGc = false;
1165 else if (strcmp(argv[i] + 5, "preverify") == 0)
1166 gDvm.preVerify = true;
1167 else if (strcmp(argv[i] + 5, "nopreverify") == 0)
1168 gDvm.preVerify = false;
1169 else if (strcmp(argv[i] + 5, "postverify") == 0)
1170 gDvm.postVerify = true;
1171 else if (strcmp(argv[i] + 5, "nopostverify") == 0)
1172 gDvm.postVerify = false;
1173 else if (strcmp(argv[i] + 5, "concurrent") == 0)
1174 gDvm.concurrentMarkSweep = true;
1175 else if (strcmp(argv[i] + 5, "noconcurrent") == 0)
1176 gDvm.concurrentMarkSweep = false;
1177 else if (strcmp(argv[i] + 5, "verifycardtable") == 0)
1178 gDvm.verifyCardTable = true;
1179 else if (strcmp(argv[i] + 5, "noverifycardtable") == 0)
1180 gDvm.verifyCardTable = false;
1182 dvmFprintf(stderr, "Bad value for -Xgc");
1185 ALOGV("Precise GC configured %s", gDvm.preciseGc ? "ON" : "OFF");
1187 } else if (strcmp(argv[i], "-Xcheckdexsum") == 0) {
1188 gDvm.verifyDexChecksum = true;
1190 } else if (strcmp(argv[i], "-Xprofile:threadcpuclock") == 0) {
1191 gDvm.profilerClockSource = kProfilerClockSourceThreadCpu;
1192 } else if (strcmp(argv[i], "-Xprofile:wallclock") == 0) {
1193 gDvm.profilerClockSource = kProfilerClockSourceWall;
1194 } else if (strcmp(argv[i], "-Xprofile:dualclock") == 0) {
1195 gDvm.profilerClockSource = kProfilerClockSourceDual;
1198 if (!ignoreUnrecognized) {
1199 dvmFprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
1209 * Set defaults for fields altered or modified by arguments.
1211 * Globals are initialized to 0 (a/k/a NULL or false).
1213 static void setCommandLineDefaults()
1215 const char* envStr = getenv("CLASSPATH");
1216 if (envStr != NULL) {
1217 gDvm.classPathStr = strdup(envStr);
1219 gDvm.classPathStr = strdup(".");
1221 envStr = getenv("BOOTCLASSPATH");
1222 if (envStr != NULL) {
1223 gDvm.bootClassPathStr = strdup(envStr);
1225 gDvm.bootClassPathStr = strdup(".");
1228 gDvm.properties = new std::vector<std::string>();
1230 /* Defaults overridden by -Xms and -Xmx.
1231 * TODO: base these on a system or application-specific default
1233 gDvm.heapStartingSize = 2 * 1024 * 1024; // Spec says 16MB; too big for us.
1234 gDvm.heapMaximumSize = 16 * 1024 * 1024; // Spec says 75% physical mem
1235 gDvm.heapGrowthLimit = 0; // 0 means no growth limit
1236 gDvm.stackSize = kDefaultStackSize;
1237 gDvm.mainThreadStackSize = kDefaultStackSize;
1238 // When the heap is less than the maximum or growth limited size,
1239 // fix the free portion of the heap. The utilization is the ratio
1240 // of live to free memory, 0.5 implies half the heap is available
1241 // to allocate into before a GC occurs. Min free and max free
1242 // force the free memory to never be smaller than min free or
1243 // larger than max free.
1244 gDvm.heapTargetUtilization = 0.5;
1245 gDvm.heapMaxFree = 2 * 1024 * 1024;
1246 gDvm.heapMinFree = gDvm.heapMaxFree / 4;
1248 gDvm.concurrentMarkSweep = true;
1250 /* gDvm.jdwpSuspend = true; */
1252 /* allowed unless zygote config doesn't allow it */
1253 gDvm.jdwpAllowed = true;
1255 /* default verification and optimization modes */
1256 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1257 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1258 gDvm.monitorVerification = false;
1259 gDvm.generateRegisterMaps = true;
1260 gDvm.registerMapMode = kRegisterMapModeTypePrecise;
1263 * Default execution mode.
1265 * This should probably interact with the mterp code somehow, e.g. if
1266 * we know we're using the "desktop" build we should probably be
1267 * using "portable" rather than "fast".
1269 #if defined(WITH_JIT)
1270 gDvm.executionMode = kExecutionModeJit;
1271 gDvmJit.num_entries_pcTable = 0;
1272 gDvmJit.includeSelectedMethod = false;
1273 gDvmJit.includeSelectedOffset = false;
1274 gDvmJit.methodTable = NULL;
1275 gDvmJit.classTable = NULL;
1277 gDvm.constInit = false;
1278 gDvm.commonInit = false;
1280 gDvm.executionMode = kExecutionModeInterpFast;
1284 * SMP support is a compile-time define, but we may want to have
1285 * dexopt target a differently-configured device.
1287 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1290 * Default profiler configuration.
1292 gDvm.profilerClockSource = kProfilerClockSourceDual;
1297 * Handle a SIGBUS, which frequently occurs because somebody replaced an
1298 * optimized DEX file out from under us.
1300 static void busCatcher(int signum, siginfo_t* info, void* context)
1302 void* addr = info->si_addr;
1304 ALOGE("Caught a SIGBUS (%d), addr=%p", signum, addr);
1307 * If we return at this point the SIGBUS just keeps happening, so we
1308 * remove the signal handler and allow it to kill us. TODO: restore
1309 * the original, which points to a debuggerd stub; if we don't then
1310 * debuggerd won't be notified.
1312 signal(SIGBUS, SIG_DFL);
1316 * Configure signals. We need to block SIGQUIT so that the signal only
1317 * reaches the dump-stack-trace thread.
1319 * This can be disabled with the "-Xrs" flag.
1321 static void blockSignals()
1327 sigaddset(&mask, SIGQUIT);
1328 sigaddset(&mask, SIGUSR1); // used to initiate heap dump
1329 #if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1330 sigaddset(&mask, SIGUSR2); // used to investigate JIT internals
1332 //sigaddset(&mask, SIGPIPE);
1333 cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1337 /* TODO: save the old sigaction in a global */
1338 struct sigaction sa;
1339 memset(&sa, 0, sizeof(sa));
1340 sa.sa_sigaction = busCatcher;
1341 sa.sa_flags = SA_SIGINFO;
1342 cc = sigaction(SIGBUS, &sa, NULL);
1347 class ScopedShutdown {
1349 ScopedShutdown() : armed_(true) {
1367 * VM initialization. Pass in any options provided on the command line.
1368 * Do not pass in the class name or the options for the class.
1370 * Returns 0 on success.
1372 std::string dvmStartup(int argc, const char* const argv[],
1373 bool ignoreUnrecognized, JNIEnv* pEnv)
1375 ScopedShutdown scopedShutdown;
1377 assert(gDvm.initializing);
1379 ALOGV("VM init args (%d):", argc);
1380 for (int i = 0; i < argc; i++) {
1381 ALOGV(" %d: '%s'", i, argv[i]);
1383 setCommandLineDefaults();
1386 * Process the option flags (if any).
1388 int cc = processOptions(argc, argv, ignoreUnrecognized);
1391 dvmFprintf(stderr, "\n");
1394 return "syntax error";
1397 #if WITH_EXTRA_GC_CHECKS > 1
1398 /* only "portable" interp has the extra goodies */
1399 if (gDvm.executionMode != kExecutionModeInterpPortable) {
1400 ALOGI("Switching to 'portable' interpreter for GC checks");
1401 gDvm.executionMode = kExecutionModeInterpPortable;
1405 /* Configure group scheduling capabilities */
1406 if (!access("/dev/cpuctl/tasks", F_OK)) {
1407 ALOGV("Using kernel group scheduling");
1408 gDvm.kernelGroupScheduling = 1;
1410 ALOGV("Using kernel scheduler policies");
1413 /* configure signal handling */
1414 if (!gDvm.reduceSignals)
1417 /* verify system page size */
1418 if (sysconf(_SC_PAGESIZE) != SYSTEM_PAGE_SIZE) {
1419 return StringPrintf("expected page size %d, got %d",
1420 SYSTEM_PAGE_SIZE, (int) sysconf(_SC_PAGESIZE));
1424 ALOGV("Using executionMode %d", gDvm.executionMode);
1425 dvmCheckAsmConstants();
1428 * Initialize components.
1430 dvmQuasiAtomicsStartup();
1431 if (!dvmAllocTrackerStartup()) {
1432 return "dvmAllocTrackerStartup failed";
1434 if (!dvmGcStartup()) {
1435 return "dvmGcStartup failed";
1437 if (!dvmThreadStartup()) {
1438 return "dvmThreadStartup failed";
1440 if (!dvmInlineNativeStartup()) {
1441 return "dvmInlineNativeStartup";
1443 if (!dvmRegisterMapStartup()) {
1444 return "dvmRegisterMapStartup failed";
1446 if (!dvmInstanceofStartup()) {
1447 return "dvmInstanceofStartup failed";
1449 if (!dvmClassStartup()) {
1450 return "dvmClassStartup failed";
1454 * At this point, the system is guaranteed to be sufficiently
1455 * initialized that we can look up classes and class members. This
1456 * call populates the gDvm instance with all the class and member
1457 * references that the VM wants to use directly.
1459 if (!dvmFindRequiredClassesAndMembers()) {
1460 return "dvmFindRequiredClassesAndMembers failed";
1463 if (!dvmStringInternStartup()) {
1464 return "dvmStringInternStartup failed";
1466 if (!dvmNativeStartup()) {
1467 return "dvmNativeStartup failed";
1469 if (!dvmInternalNativeStartup()) {
1470 return "dvmInternalNativeStartup failed";
1472 if (!dvmJniStartup()) {
1473 return "dvmJniStartup failed";
1475 if (!dvmProfilingStartup()) {
1476 return "dvmProfilingStartup failed";
1480 * Create a table of methods for which we will substitute an "inline"
1481 * version for performance.
1483 if (!dvmCreateInlineSubsTable()) {
1484 return "dvmCreateInlineSubsTable failed";
1488 * Miscellaneous class library validation.
1490 if (!dvmValidateBoxClasses()) {
1491 return "dvmValidateBoxClasses failed";
1495 * Do the last bits of Thread struct initialization we need to allow
1496 * JNI calls to work.
1498 if (!dvmPrepMainForJni(pEnv)) {
1499 return "dvmPrepMainForJni failed";
1503 * Explicitly initialize java.lang.Class. This doesn't happen
1504 * automatically because it's allocated specially (it's an instance
1505 * of itself). Must happen before registration of system natives,
1506 * which make some calls that throw assertions if the classes they
1507 * operate on aren't initialized.
1509 if (!dvmInitClass(gDvm.classJavaLangClass)) {
1510 return "couldn't initialized java.lang.Class";
1514 * Register the system native methods, which are registered through JNI.
1516 if (!registerSystemNatives(pEnv)) {
1517 return "couldn't register system natives";
1521 * Do some "late" initialization for the memory allocator. This may
1522 * allocate storage and initialize classes.
1524 if (!dvmCreateStockExceptions()) {
1525 return "dvmCreateStockExceptions failed";
1529 * At this point, the VM is in a pretty good state. Finish prep on
1530 * the main thread (specifically, create a java.lang.Thread object to go
1531 * along with our Thread struct). Note we will probably be executing
1532 * some interpreted class initializer code in here.
1534 if (!dvmPrepMainThread()) {
1535 return "dvmPrepMainThread failed";
1539 * Make sure we haven't accumulated any tracked references. The main
1540 * thread should be starting with a clean slate.
1542 if (dvmReferenceTableEntries(&dvmThreadSelf()->internalLocalRefTable) != 0)
1544 ALOGW("Warning: tracked references remain post-initialization");
1545 dvmDumpReferenceTable(&dvmThreadSelf()->internalLocalRefTable, "MAIN");
1548 /* general debugging setup */
1549 if (!dvmDebuggerStartup()) {
1550 return "dvmDebuggerStartup failed";
1553 if (!dvmGcStartupClasses()) {
1554 return "dvmGcStartupClasses failed";
1558 * Init for either zygote mode or non-zygote mode. The key difference
1559 * is that we don't start any additional threads in Zygote mode.
1562 if (!initZygote()) {
1563 return "initZygote failed";
1566 if (!dvmInitAfterZygote()) {
1567 return "dvmInitAfterZygote failed";
1574 ALOGE("dvmTestHash FAILED");
1575 if (false /*noisy!*/ && !dvmTestIndirectRefTable())
1576 ALOGE("dvmTestIndirectRefTable FAILED");
1579 if (dvmCheckException(dvmThreadSelf())) {
1580 dvmLogExceptionStackTrace();
1581 return "Exception pending at end of VM initialization";
1584 scopedShutdown.disarm();
1588 static void loadJniLibrary(const char* name) {
1589 std::string mappedName(StringPrintf(OS_SHARED_LIB_FORMAT_STR, name));
1590 char* reason = NULL;
1591 if (!dvmLoadNativeCode(mappedName.c_str(), NULL, &reason)) {
1592 ALOGE("dvmLoadNativeCode failed for \"%s\": %s", name, reason);
1598 * Register java.* natives from our class libraries. We need to do
1599 * this after we're ready for JNI registration calls, but before we
1600 * do any class initialization.
1602 * If we get this wrong, we will blow up in the ThreadGroup class init if
1603 * interpreted code makes any reference to System. It will likely do this
1604 * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1606 * We need to have gDvm.initializing raised here so that JNI FindClass
1607 * won't try to use the system/application class loader.
1609 static bool registerSystemNatives(JNIEnv* pEnv)
1611 // Main thread is always first in list.
1612 Thread* self = gDvm.threadList;
1614 // Must set this before allowing JNI-based method registration.
1615 self->status = THREAD_NATIVE;
1617 // First set up JniConstants, which is used by libcore.
1618 JniConstants::init(pEnv);
1620 // Set up our single JNI method.
1621 // TODO: factor this out if we add more.
1622 jclass c = pEnv->FindClass("java/lang/Class");
1626 JNIEXPORT jobject JNICALL Java_java_lang_Class_getDex(JNIEnv* env, jclass javaClass);
1627 const JNINativeMethod Java_java_lang_Class[] = {
1628 { "getDex", "()Lcom/android/dex/Dex;", (void*) Java_java_lang_Class_getDex },
1630 if (pEnv->RegisterNatives(c, Java_java_lang_Class, 1) != JNI_OK) {
1634 // Most JNI libraries can just use System.loadLibrary, but you can't
1635 // if you're the library that implements System.loadLibrary!
1636 loadJniLibrary("javacore");
1637 loadJniLibrary("nativehelper");
1639 // Back to run mode.
1640 self->status = THREAD_RUNNING;
1646 * Copied and modified slightly from system/core/toolbox/mount.c
1648 static std::string getMountsDevDir(const char *arg)
1650 char mount_dev[256];
1651 char mount_dir[256];
1654 FILE *fp = fopen("/proc/self/mounts", "r");
1656 ALOGE("Could not open /proc/self/mounts: %s", strerror(errno));
1660 while ((match = fscanf(fp, "%255s %255s %*s %*s %*d %*d\n", mount_dev, mount_dir)) != EOF) {
1663 if (match == 2 && (strcmp(arg, mount_dir) == 0)) {
1674 * Do zygote-mode-only initialization.
1676 static bool initZygote()
1678 /* zygote goes into its own process group */
1681 // See storage config details at http://source.android.com/tech/storage/
1682 // Create private mount namespace shared by all children
1683 if (unshare(CLONE_NEWNS) == -1) {
1684 SLOGE("Failed to unshare(): %s", strerror(errno));
1688 // Mark rootfs as being a slave so that changes from default
1689 // namespace only flow into our children.
1690 if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
1691 SLOGE("Failed to mount() rootfs as MS_SLAVE: %s", strerror(errno));
1695 // Create a staging tmpfs that is shared by our children; they will
1696 // bind mount storage into their respective private namespaces, which
1697 // are isolated from each other.
1698 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1699 if (target_base != NULL) {
1700 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1701 "uid=0,gid=1028,mode=0050") == -1) {
1702 SLOGE("Failed to mount tmpfs to %s: %s", target_base, strerror(errno));
1707 // Mark /system as NOSUID | NODEV
1708 const char* android_root = getenv("ANDROID_ROOT");
1710 if (android_root == NULL) {
1711 SLOGE("environment variable ANDROID_ROOT does not exist?!?!");
1715 std::string mountDev(getMountsDevDir(android_root));
1716 if (mountDev.empty()) {
1717 SLOGE("Unable to find mount point for %s", android_root);
1721 if (mount(mountDev.c_str(), android_root, "none",
1722 MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_RDONLY | MS_BIND, NULL) == -1) {
1723 SLOGE("Remount of %s failed: %s", android_root, strerror(errno));
1727 #ifdef HAVE_ANDROID_OS
1728 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1729 if (errno == EINVAL) {
1730 SLOGW("PR_SET_NO_NEW_PRIVS failed. "
1731 "Is your kernel compiled correctly?: %s", strerror(errno));
1732 // Don't return -1 here, since it's expected that not all
1733 // kernels will support this option.
1735 SLOGW("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
1745 * Do non-zygote-mode initialization. This is done during VM init for
1746 * standard startup, or after a "zygote fork" when creating a new process.
1748 bool dvmInitAfterZygote()
1750 u8 startHeap, startQuit, startJdwp;
1751 u8 endHeap, endQuit, endJdwp;
1753 startHeap = dvmGetRelativeTimeUsec();
1756 * Post-zygote heap initialization, including starting
1757 * the HeapWorker thread.
1759 if (!dvmGcStartupAfterZygote())
1762 endHeap = dvmGetRelativeTimeUsec();
1763 startQuit = dvmGetRelativeTimeUsec();
1765 /* start signal catcher thread that dumps stacks on SIGQUIT */
1766 if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1767 if (!dvmSignalCatcherStartup())
1771 /* start stdout/stderr copier, if requested */
1772 if (gDvm.logStdio) {
1773 if (!dvmStdioConverterStartup())
1777 endQuit = dvmGetRelativeTimeUsec();
1778 startJdwp = dvmGetRelativeTimeUsec();
1781 * Start JDWP thread. If the command-line debugger flags specified
1782 * "suspend=y", this will pause the VM. We probably want this to
1786 ALOGD("JDWP init failed; continuing anyway");
1789 endJdwp = dvmGetRelativeTimeUsec();
1791 ALOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec",
1792 (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1793 (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1796 if (gDvm.executionMode == kExecutionModeJit) {
1797 if (!dvmCompilerStartup())
1806 * Prepare for a connection to a JDWP-compliant debugger.
1808 * Note this needs to happen fairly late in the startup process, because
1809 * we need to have all of the java.* native methods registered (which in
1810 * turn requires JNI to be fully prepped).
1812 * There are several ways to initialize:
1814 * We immediately try to connect to host:port. Bail on failure. On
1815 * success, send VM_START (suspending the VM if "suspend=y").
1816 * server=y suspend=n
1817 * Passively listen for a debugger to connect. Return immediately.
1818 * server=y suspend=y
1819 * Wait until debugger connects. Send VM_START ASAP, suspending the
1820 * VM after the message is sent.
1822 * This gets more complicated with a nonzero value for "timeout".
1824 static bool initJdwp()
1826 assert(!gDvm.zygote);
1829 * Init JDWP if the debugger is enabled. This may connect out to a
1830 * debugger, passively listen for a debugger, or block waiting for a
1833 if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1834 JdwpStartupParams params;
1836 if (gDvm.jdwpHost != NULL) {
1837 if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1838 ALOGE("ERROR: hostname too long: '%s'", gDvm.jdwpHost);
1841 strcpy(params.host, gDvm.jdwpHost);
1843 params.host[0] = '\0';
1845 params.transport = gDvm.jdwpTransport;
1846 params.server = gDvm.jdwpServer;
1847 params.suspend = gDvm.jdwpSuspend;
1848 params.port = gDvm.jdwpPort;
1850 gDvm.jdwpState = dvmJdwpStartup(¶ms);
1851 if (gDvm.jdwpState == NULL) {
1852 ALOGW("WARNING: debugger thread failed to initialize");
1853 /* TODO: ignore? fail? need to mimic "expected" behavior */
1858 * If a debugger has already attached, send the "welcome" message. This
1859 * may cause us to suspend all threads.
1861 if (dvmJdwpIsActive(gDvm.jdwpState)) {
1862 //dvmChangeStatus(NULL, THREAD_RUNNING);
1863 if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1864 ALOGW("WARNING: failed to post 'start' message to debugger");
1867 //dvmChangeStatus(NULL, THREAD_NATIVE);
1874 * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1875 * of initialization and then returns with "initializing" still set. (Used
1876 * by DexOpt command-line utility.)
1878 * Attempting to use JNI or internal natives will fail. It's best
1879 * if no bytecode gets executed, which means no <clinit>, which means
1880 * no exception-throwing. (In practice we need to initialize Class and
1881 * Object, and probably some exception classes.)
1883 * Returns 0 on success.
1885 int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1886 DexClassVerifyMode verifyMode, int dexoptFlags)
1888 gDvm.initializing = true;
1889 gDvm.optimizing = true;
1891 /* configure signal handling */
1894 /* set some defaults */
1895 setCommandLineDefaults();
1896 free(gDvm.bootClassPathStr);
1897 gDvm.bootClassPathStr = strdup(bootClassPath);
1899 /* set opt/verify modes */
1900 gDvm.dexOptMode = dexOptMode;
1901 gDvm.classVerifyMode = verifyMode;
1902 gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1903 if (dexoptFlags & DEXOPT_SMP) {
1904 assert((dexoptFlags & DEXOPT_UNIPROCESSOR) == 0);
1905 gDvm.dexOptForSmp = true;
1906 } else if (dexoptFlags & DEXOPT_UNIPROCESSOR) {
1907 gDvm.dexOptForSmp = false;
1909 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1913 * Initialize the heap, some basic thread control mutexes, and
1914 * get the bootclasspath prepped.
1916 * We can't load any classes yet because we may not yet have a source
1917 * for things like java.lang.Object and java.lang.Class.
1919 if (!dvmGcStartup())
1921 if (!dvmThreadStartup())
1923 if (!dvmInlineNativeStartup())
1925 if (!dvmRegisterMapStartup())
1927 if (!dvmInstanceofStartup())
1929 if (!dvmClassStartup())
1933 * We leave gDvm.initializing set to "true" so that, if we're not
1934 * able to process the "core" classes, we don't go into a death-spin
1935 * trying to throw a "class not found" exception.
1947 * All threads have stopped. Finish the shutdown procedure.
1949 * We can also be called if startup fails partway through, so be prepared
1950 * to deal with partially initialized data.
1952 * Free any storage allocated in gGlobals.
1954 * We can't dlclose() shared libs we've loaded, because it's possible a
1955 * thread not associated with the VM is running code in one.
1957 * This is called from the JNI DestroyJavaVM function, which can be
1958 * called from any thread. (In practice, this will usually run in the
1959 * same thread that started the VM, a/k/a the main thread, but we don't
1960 * want to assume that.)
1964 ALOGV("VM shutting down");
1966 if (CALC_CACHE_STATS)
1967 dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1970 * Stop our internal threads.
1972 dvmGcThreadShutdown();
1974 if (gDvm.jdwpState != NULL)
1975 dvmJdwpShutdown(gDvm.jdwpState);
1976 free(gDvm.jdwpHost);
1977 gDvm.jdwpHost = NULL;
1978 free(gDvm.jniTrace);
1979 gDvm.jniTrace = NULL;
1980 free(gDvm.stackTraceFile);
1981 gDvm.stackTraceFile = NULL;
1983 /* tell signal catcher to shut down if it was started */
1984 dvmSignalCatcherShutdown();
1986 /* shut down stdout/stderr conversion */
1987 dvmStdioConverterShutdown();
1990 if (gDvm.executionMode == kExecutionModeJit) {
1991 /* shut down the compiler thread */
1992 dvmCompilerShutdown();
1997 * Kill any daemon threads that still exist. Actively-running threads
1998 * are likely to crash the process if they continue to execute while
1999 * the VM shuts down.
2003 if (gDvm.verboseShutdown)
2004 ALOGD("VM cleaning up");
2006 dvmDebuggerShutdown();
2007 dvmProfilingShutdown();
2009 dvmStringInternShutdown();
2010 dvmThreadShutdown();
2012 dvmRegisterMapShutdown();
2013 dvmInstanceofShutdown();
2014 dvmInlineNativeShutdown();
2016 dvmAllocTrackerShutdown();
2018 /* these must happen AFTER dvmClassShutdown has walked through class data */
2019 dvmNativeShutdown();
2020 dvmInternalNativeShutdown();
2022 dvmFreeInlineSubsTable();
2024 free(gDvm.bootClassPathStr);
2025 free(gDvm.classPathStr);
2026 delete gDvm.properties;
2028 freeAssertionCtrl();
2030 dvmQuasiAtomicsShutdown();
2033 * We want valgrind to report anything we forget to free as "definitely
2034 * lost". If there's a pointer in the global chunk, it would be reported
2035 * as "still reachable". Erasing the memory fixes this.
2037 * This must be erased to zero if we want to restart the VM within this
2040 memset(&gDvm, 0xcd, sizeof(gDvm));
2045 * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
2046 * one was specified.
2048 int dvmFprintf(FILE* fp, const char* format, ...)
2053 va_start(args, format);
2054 if (gDvm.vfprintfHook != NULL)
2055 result = (*gDvm.vfprintfHook)(fp, format, args);
2057 result = vfprintf(fp, format, args);
2064 #include <execinfo.h>
2066 * glibc-only stack dump function. Requires link with "--export-dynamic".
2068 * TODO: move this into libs/cutils and make it work for all platforms.
2070 void dvmPrintNativeBackTrace()
2072 size_t MAX_STACK_FRAMES = 64;
2073 void* stackFrames[MAX_STACK_FRAMES];
2074 size_t frameCount = backtrace(stackFrames, MAX_STACK_FRAMES);
2077 * TODO: in practice, we may find that we should use backtrace_symbols_fd
2078 * to avoid allocation, rather than use our own custom formatting.
2080 char** strings = backtrace_symbols(stackFrames, frameCount);
2081 if (strings == NULL) {
2082 ALOGE("backtrace_symbols failed: %s", strerror(errno));
2087 for (i = 0; i < frameCount; ++i) {
2088 ALOGW("#%-2d %s", i, strings[i]);
2093 void dvmPrintNativeBackTrace() {
2094 /* Hopefully, you're on an Android device and debuggerd will do this. */
2099 * Abort the VM. We get here on fatal errors. Try very hard not to use
2100 * this; whenever possible, return an error to somebody responsible.
2105 * Leave gDvm.lastMessage on the stack frame which can be decoded in the
2106 * tombstone file. This is for situations where we only have tombstone files
2107 * but no logs (ie b/5372634).
2109 * For example, in the tombstone file you usually see this:
2111 * #00 pc 00050ef2 /system/lib/libdvm.so (dvmAbort)
2112 * #01 pc 00077670 /system/lib/libdvm.so (_Z15dvmClassStartupv)
2117 * #00 beed2658 00000000
2127 * The ascii values between beed265c and beed2674 belongs to messageBuffer
2128 * and it can be decoded as "/system/framework/core.jar".
2130 const int messageLength = 512;
2131 char messageBuffer[messageLength] = {0};
2134 snprintf(messageBuffer, messageLength, "%s", gDvm.lastMessage);
2136 /* So that messageBuffer[] looks like useful stuff to the compiler */
2137 for (int i = 0; i < messageLength && messageBuffer[i]; i++) {
2138 result += messageBuffer[i];
2141 ALOGE("VM aborting");
2143 fflush(NULL); // flush all open file buffers
2145 /* JNI-supplied abort hook gets right of first refusal */
2146 if (gDvm.abortHook != NULL)
2147 (*gDvm.abortHook)();
2150 * On the device, debuggerd will give us a stack trace.
2151 * On the host, we have to help ourselves.
2153 dvmPrintNativeBackTrace();