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");
125 " -Xjnigreflimit:N (must be multiple of 100, >= 200)\n");
126 dvmFprintf(stderr, " -Xjniopts:{warnonly,forcecopy}\n");
127 dvmFprintf(stderr, " -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
128 dvmFprintf(stderr, " -Xstacktracefile:<filename>\n");
129 dvmFprintf(stderr, " -Xgc:[no]precise\n");
130 dvmFprintf(stderr, " -Xgc:[no]preverify\n");
131 dvmFprintf(stderr, " -Xgc:[no]postverify\n");
132 dvmFprintf(stderr, " -Xgc:[no]concurrent\n");
133 dvmFprintf(stderr, " -Xgc:[no]verifycardtable\n");
134 dvmFprintf(stderr, " -XX:+DisableExplicitGC\n");
135 dvmFprintf(stderr, " -X[no]genregmap\n");
136 dvmFprintf(stderr, " -Xverifyopt:[no]checkmon\n");
137 dvmFprintf(stderr, " -Xcheckdexsum\n");
138 #if defined(WITH_JIT)
139 dvmFprintf(stderr, " -Xincludeselectedop\n");
140 dvmFprintf(stderr, " -Xjitop:hexopvalue[-endvalue]"
141 "[,hexopvalue[-endvalue]]*\n");
142 dvmFprintf(stderr, " -Xincludeselectedmethod\n");
143 dvmFprintf(stderr, " -Xjitthreshold:decimalvalue\n");
144 dvmFprintf(stderr, " -Xjitblocking\n");
145 dvmFprintf(stderr, " -Xjitmethod:signature[,signature]* "
146 "(eg Ljava/lang/String\\;replace)\n");
147 dvmFprintf(stderr, " -Xjitclass:classname[,classname]*\n");
148 dvmFprintf(stderr, " -Xjitoffset:offset[,offset]\n");
149 dvmFprintf(stderr, " -Xjitconfig:filename\n");
150 dvmFprintf(stderr, " -Xjitcheckcg\n");
151 dvmFprintf(stderr, " -Xjitverbose\n");
152 dvmFprintf(stderr, " -Xjitprofile\n");
153 dvmFprintf(stderr, " -Xjitdisableopt\n");
154 dvmFprintf(stderr, " -Xjitsuspendpoll\n");
156 dvmFprintf(stderr, "\n");
157 dvmFprintf(stderr, "Configured with:"
161 #ifdef WITH_TRACKREF_CHECKS
164 #ifdef WITH_INSTR_CHECKS
167 #ifdef WITH_EXTRA_OBJECT_VALIDATION
168 " extra_object_validation"
170 #ifdef WITH_EXTRA_GC_CHECKS
173 #if !defined(NDEBUG) && defined(WITH_DALVIK_ASSERT)
176 #ifdef WITH_JNI_STACK_CHECK
185 #if defined(WITH_JIT)
186 " jit(" ARCH_VARIANT ")"
188 #if defined(WITH_SELF_VERIFICATION)
195 #ifdef DVM_SHOW_EXCEPTION
196 dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
198 dvmFprintf(stderr, "\n\n");
202 * Show helpful information on JDWP options.
204 static void showJdwpHelp()
207 "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
209 "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
213 * Show version and copyright info.
215 static void showVersion()
217 dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
218 DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
220 "Copyright (C) 2007 The Android Open Source Project\n\n"
221 "This software is built from source code licensed under the "
223 "Version 2.0 (the \"License\"). You may obtain a copy of the "
225 " http://www.apache.org/licenses/LICENSE-2.0\n\n"
226 "See the associated NOTICE file for this software for further "
231 * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
232 * memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
235 * "s" should point just past the "-Xm?" part of the string.
236 * "min" specifies the lowest acceptable value described by "s".
237 * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
240 * The spec says the -Xmx and -Xms options must be multiples of 1024. It
241 * doesn't say anything about -Xss.
243 * Returns 0 (a useless size) if "s" is malformed or specifies a low or
244 * non-evenly-divisible value.
246 static size_t parseMemOption(const char* s, size_t div)
248 /* strtoul accepts a leading [+-], which we don't want,
249 * so make sure our string starts with a decimal digit.
255 val = strtoul(s, (char* *)&s2, 10);
257 /* s2 should be pointing just after the number.
258 * If this is the end of the string, the user
259 * has specified a number of bytes. Otherwise,
260 * there should be exactly one more character
261 * that specifies a multiplier.
266 /* The remainder of the string is either a single multiplier
267 * character, or nothing to indicate that the value is in
276 } else if (c == 'k' || c == 'K') {
278 } else if (c == 'm' || c == 'M') {
280 } else if (c == 'g' || c == 'G') {
281 mul = 1024 * 1024 * 1024;
283 /* Unknown multiplier character.
288 if (val <= SIZE_MAX / mul) {
291 /* Clamp to a multiple of 1024.
293 val = SIZE_MAX & ~(1024-1);
296 /* There's more than one character after the
303 /* The man page says that a -Xm value must be
304 * a multiple of 1024.
306 if (val % div == 0) {
316 * Handle one of the JDWP name/value pairs.
319 * help: if specified, show help message and bail
320 * transport: may be dt_socket or dt_shmem
321 * address: for dt_socket, "host:port", or just "port" when listening
322 * server: if "y", wait for debugger to attach; if "n", attach to debugger
323 * timeout: how long to wait for debugger to connect / listen
325 * Useful with server=n (these aren't supported yet):
326 * onthrow=<exception-name>: connect to debugger when exception thrown
327 * onuncaught=y|n: connect to debugger when uncaught exception thrown
328 * launch=<command-line>: launch the debugger itself
330 * The "transport" option is required, as is "address" if server=n.
332 static bool handleJdwpOption(const char* name, const char* value)
334 if (strcmp(name, "transport") == 0) {
335 if (strcmp(value, "dt_socket") == 0) {
336 gDvm.jdwpTransport = kJdwpTransportSocket;
337 } else if (strcmp(value, "dt_android_adb") == 0) {
338 gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
340 ALOGE("JDWP transport '%s' not supported", value);
343 } else if (strcmp(name, "server") == 0) {
345 gDvm.jdwpServer = false;
346 else if (*value == 'y')
347 gDvm.jdwpServer = true;
349 ALOGE("JDWP option 'server' must be 'y' or 'n'");
352 } else if (strcmp(name, "suspend") == 0) {
354 gDvm.jdwpSuspend = false;
355 else if (*value == 'y')
356 gDvm.jdwpSuspend = true;
358 ALOGE("JDWP option 'suspend' must be 'y' or 'n'");
361 } else if (strcmp(name, "address") == 0) {
362 /* this is either <port> or <host>:<port> */
363 const char* colon = strchr(value, ':');
369 gDvm.jdwpHost = (char*) malloc(colon - value +1);
370 strncpy(gDvm.jdwpHost, value, colon - value +1);
371 gDvm.jdwpHost[colon-value] = '\0';
374 if (*value == '\0') {
375 ALOGE("JDWP address missing port");
378 port = strtol(value, &end, 10);
380 ALOGE("JDWP address has junk in port field '%s'", value);
383 gDvm.jdwpPort = port;
384 } else if (strcmp(name, "launch") == 0 ||
385 strcmp(name, "onthrow") == 0 ||
386 strcmp(name, "oncaught") == 0 ||
387 strcmp(name, "timeout") == 0)
389 /* valid but unsupported */
390 ALOGI("Ignoring JDWP option '%s'='%s'", name, value);
392 ALOGI("Ignoring unrecognized JDWP option '%s'='%s'", name, value);
399 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
400 * "transport=dt_socket,address=8000,server=y,suspend=n"
402 static bool parseJdwpOptions(const char* str)
404 char* mangle = strdup(str);
409 * Process all of the name=value pairs.
415 value = strchr(name, '=');
417 ALOGE("JDWP opts: garbage at '%s'", name);
421 comma = strchr(name, ','); // use name, not value, for safety
424 ALOGE("JDWP opts: found comma before '=' in '%s'", mangle);
430 *value++ = '\0'; // stomp the '='
432 if (!handleJdwpOption(name, value))
443 * Make sure the combination of arguments makes sense.
445 if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
446 ALOGE("JDWP opts: must specify transport");
449 if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
450 ALOGE("JDWP opts: when server=n, must specify host and port");
453 // transport mandatory
454 // outbound server address
456 gDvm.jdwpConfigured = true;
465 * Handle one of the four kinds of assertion arguments.
467 * "pkgOrClass" is the last part of an enable/disable line. For a package
468 * the arg looks like "-ea:com.google.fubar...", for a class it looks
469 * like "-ea:com.google.fubar.Wahoo". The string we get starts at the ':'.
471 * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
473 * Multiple instances of these arguments can be specified, e.g. you can
474 * enable assertions for a package and then disable them for one class in
477 static bool enableAssertions(const char* pkgOrClass, bool enable)
479 AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
480 pCtrl->enable = enable;
482 if (pkgOrClass == NULL) {
483 /* enable or disable for all system classes */
484 pCtrl->isPackage = false;
485 pCtrl->pkgOrClass = NULL;
486 pCtrl->pkgOrClassLen = 0;
488 if (*pkgOrClass == '\0') {
489 /* global enable/disable for all but system */
490 pCtrl->isPackage = false;
491 pCtrl->pkgOrClass = strdup("");
492 pCtrl->pkgOrClassLen = 0;
494 pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1); // skip ':'
495 if (pCtrl->pkgOrClass == NULL) {
496 /* can happen if class name includes an illegal '/' */
497 ALOGW("Unable to process assertion arg '%s'", pkgOrClass);
501 int len = strlen(pCtrl->pkgOrClass);
502 if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
503 /* mark as package, truncate two of the three slashes */
504 pCtrl->isPackage = true;
505 *(pCtrl->pkgOrClass + len-2) = '\0';
506 pCtrl->pkgOrClassLen = len - 2;
509 pCtrl->isPackage = false;
510 pCtrl->pkgOrClassLen = len;
519 * Turn assertions on when requested to do so by the Zygote.
521 * This is a bit sketchy. We can't (easily) go back and fiddle with all
522 * of the classes that have already been initialized, so this only
523 * affects classes that have yet to be loaded. If some or all assertions
524 * have been enabled through some other means, we don't want to mess with
525 * it here, so we do nothing. Finally, we assume that there's room in
526 * "assertionCtrl" to hold at least one entry; this is guaranteed by the
529 * This must only be called from the main thread during zygote init.
531 void dvmLateEnableAssertions()
533 if (gDvm.assertionCtrl == NULL) {
534 ALOGD("Not late-enabling assertions: no assertionCtrl array");
536 } else if (gDvm.assertionCtrlCount != 0) {
537 ALOGD("Not late-enabling assertions: some asserts already configured");
540 ALOGD("Late-enabling assertions");
542 /* global enable for all but system */
543 AssertionControl* pCtrl = gDvm.assertionCtrl;
544 pCtrl->pkgOrClass = strdup("");
545 pCtrl->pkgOrClassLen = 0;
546 pCtrl->isPackage = false;
547 pCtrl->enable = true;
548 gDvm.assertionCtrlCount = 1;
553 * Release memory associated with the AssertionCtrl array.
555 static void freeAssertionCtrl()
559 for (i = 0; i < gDvm.assertionCtrlCount; i++)
560 free(gDvm.assertionCtrl[i].pkgOrClass);
561 free(gDvm.assertionCtrl);
564 #if defined(WITH_JIT)
565 /* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
566 static void processXjitop(const char* opt)
569 const char* startPtr = &opt[8];
573 long startValue, endValue;
575 startValue = strtol(startPtr, &endPtr, 16);
576 if (startPtr != endPtr) {
577 /* Just in case value is out of range */
578 startValue %= kNumPackedOpcodes;
580 if (*endPtr == '-') {
581 endValue = strtol(endPtr+1, &endPtr, 16);
582 endValue %= kNumPackedOpcodes;
584 endValue = startValue;
587 for (; startValue <= endValue; startValue++) {
588 ALOGW("Dalvik opcode %x is selected for debugging",
589 (unsigned int) startValue);
590 /* Mark the corresponding bit to 1 */
591 gDvmJit.opList[startValue >> 3] |= 1 << (startValue & 0x7);
598 startPtr = endPtr + 1;
604 "Warning: Unrecognized opcode value substring "
612 for (i = 0; i < (kNumPackedOpcodes+7)/8; i++) {
613 gDvmJit.opList[i] = 0xff;
615 dvmFprintf(stderr, "Warning: select all opcodes\n");
619 /* Parse -Xjitoffset to selectively turn on/off traces with certain offsets for JIT */
620 static void processXjitoffset(const char* opt) {
621 gDvmJit.num_entries_pcTable = 0;
622 char* buf = strdup(opt);
627 end = strchr(start, ',');
632 dvmFprintf(stderr, "processXjitoffset start = %s\n", start);
633 char* tmp = strdup(start);
634 gDvmJit.pcTable[idx++] = atoi(tmp);
636 if (idx >= COMPILER_PC_OFFSET_SIZE) {
637 dvmFprintf(stderr, "processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
646 gDvmJit.num_entries_pcTable = idx;
650 /* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
651 static void processXjitmethod(const char* opt, bool isMethod) {
652 char* buf = strdup(opt);
654 if (isMethod && gDvmJit.methodTable == NULL) {
655 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
657 if (!isMethod && gDvmJit.classTable == NULL) {
658 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
664 * Break comma-separated method signatures and enter them into the hash
665 * table individually.
670 end = strchr(start, ',');
675 hashValue = dvmComputeUtf8Hash(start);
676 dvmHashTableLookup(isMethod ? gDvmJit.methodTable : gDvmJit.classTable,
677 hashValue, strdup(start), (HashCompareFunc) strcmp, true);
688 /* The format of jit_config.list:
695 index ... //each pair is a range, if pcOff falls into a range, JIT
697 static int processXjitconfig(const char* opt) {
698 FILE* fp = fopen(opt, "r");
704 bool startClass = false, startMethod = false, startOffset = false;
705 gDvmJit.num_entries_pcTable = 0;
708 while (fgets(fLine, 500, fp) != NULL) {
709 char* curLine = strtok(fLine, " \t\r\n");
710 /* handles keyword CLASS, METHOD, INCLUDE, EXCLUDE */
711 if (!strncmp(curLine, "CLASS", 5)) {
717 if (!strncmp(curLine, "METHOD", 6)) {
723 if (!strncmp(curLine, "OFFSET", 6)) {
729 if (!strncmp(curLine, "EXCLUDE", 7)) {
730 gDvmJit.includeSelectedMethod = false;
733 if (!strncmp(curLine, "INCLUDE", 7)) {
734 gDvmJit.includeSelectedMethod = true;
737 if (!startMethod && !startClass && !startOffset) {
741 int hashValue = dvmComputeUtf8Hash(curLine);
743 if (gDvmJit.methodTable == NULL) {
744 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
746 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
748 (HashCompareFunc) strcmp, true);
749 } else if (startClass) {
750 if (gDvmJit.classTable == NULL) {
751 gDvmJit.classTable = dvmHashTableCreate(8, NULL);
753 dvmHashTableLookup(gDvmJit.classTable, hashValue,
755 (HashCompareFunc) strcmp, true);
756 } else if (startOffset) {
757 int tmpInt = atoi(curLine);
758 gDvmJit.pcTable[idx++] = tmpInt;
759 if (idx >= COMPILER_PC_OFFSET_SIZE) {
760 printf("processXjitoffset: ignore entries beyond %d\n", COMPILER_PC_OFFSET_SIZE);
765 gDvmJit.num_entries_pcTable = idx;
772 * Process an argument vector full of options. Unlike standard C programs,
773 * argv[0] does not contain the name of the program.
775 * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
776 * that we don't recognize. Otherwise, we return with an error as soon as
777 * we see anything we can't identify.
779 * Returns 0 on success, -1 on failure, and 1 for the special case of
780 * "-version" where we want to stop without showing an error message.
782 static int processOptions(int argc, const char* const argv[],
783 bool ignoreUnrecognized)
787 ALOGV("VM options (%d):", argc);
788 for (i = 0; i < argc; i++)
789 ALOGV(" %d: '%s'", i, argv[i]);
792 * Over-allocate AssertionControl array for convenience. If allocated,
793 * the array must be able to hold at least one entry, so that the
794 * zygote-time activation can do its business.
796 assert(gDvm.assertionCtrl == NULL);
799 (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
800 if (gDvm.assertionCtrl == NULL)
802 assert(gDvm.assertionCtrlCount == 0);
805 for (i = 0; i < argc; i++) {
806 if (strcmp(argv[i], "-help") == 0) {
807 /* show usage and stop */
810 } else if (strcmp(argv[i], "-version") == 0) {
811 /* show version and stop */
814 } else if (strcmp(argv[i], "-showversion") == 0) {
815 /* show version and continue */
818 } else if (strcmp(argv[i], "-classpath") == 0 ||
819 strcmp(argv[i], "-cp") == 0)
823 dvmFprintf(stderr, "Missing classpath path list\n");
826 free(gDvm.classPathStr); /* in case we have compiled-in default */
827 gDvm.classPathStr = strdup(argv[++i]);
829 } else if (strncmp(argv[i], "-Xbootclasspath:",
830 sizeof("-Xbootclasspath:")-1) == 0)
832 /* set bootclasspath */
833 const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
836 dvmFprintf(stderr, "Missing bootclasspath path list\n");
839 free(gDvm.bootClassPathStr);
840 gDvm.bootClassPathStr = strdup(path);
842 } else if (strncmp(argv[i], "-Xbootclasspath/a:",
843 sizeof("-Xbootclasspath/a:")-1) == 0) {
844 const char* appPath = argv[i] + sizeof("-Xbootclasspath/a:")-1;
846 if (*(appPath) == '\0') {
847 dvmFprintf(stderr, "Missing appending bootclasspath path list\n");
852 if (asprintf(&allPath, "%s:%s", gDvm.bootClassPathStr, appPath) < 0) {
853 dvmFprintf(stderr, "Can't append to bootclasspath path list\n");
856 free(gDvm.bootClassPathStr);
857 gDvm.bootClassPathStr = allPath;
859 } else if (strncmp(argv[i], "-Xbootclasspath/p:",
860 sizeof("-Xbootclasspath/p:")-1) == 0) {
861 const char* prePath = argv[i] + sizeof("-Xbootclasspath/p:")-1;
863 if (*(prePath) == '\0') {
864 dvmFprintf(stderr, "Missing prepending bootclasspath path list\n");
869 if (asprintf(&allPath, "%s:%s", prePath, gDvm.bootClassPathStr) < 0) {
870 dvmFprintf(stderr, "Can't prepend to bootclasspath path list\n");
873 free(gDvm.bootClassPathStr);
874 gDvm.bootClassPathStr = allPath;
876 } else if (strncmp(argv[i], "-D", 2) == 0) {
877 /* Properties are handled in managed code. We just check syntax. */
878 if (strchr(argv[i], '=') == NULL) {
879 dvmFprintf(stderr, "Bad system property setting: \"%s\"\n",
883 gDvm.properties->push_back(argv[i] + 2);
885 } else if (strcmp(argv[i], "-jar") == 0) {
886 // TODO: handle this; name of jar should be in argv[i+1]
887 dvmFprintf(stderr, "-jar not yet handled\n");
890 } else if (strncmp(argv[i], "-Xms", 4) == 0) {
891 size_t val = parseMemOption(argv[i]+4, 1024);
893 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
894 gDvm.heapStartingSize = val;
897 "Invalid -Xms '%s', range is %dKB to %dKB\n",
898 argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
902 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
905 } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
906 size_t val = parseMemOption(argv[i]+4, 1024);
908 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
909 gDvm.heapMaximumSize = val;
912 "Invalid -Xmx '%s', range is %dKB to %dKB\n",
913 argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
917 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
920 } else if (strncmp(argv[i], "-XX:HeapGrowthLimit=", 20) == 0) {
921 size_t val = parseMemOption(argv[i] + 20, 1024);
923 gDvm.heapGrowthLimit = val;
925 dvmFprintf(stderr, "Invalid -XX:HeapGrowthLimit option '%s'\n", argv[i]);
928 } else if (strncmp(argv[i], "-XX:HeapMinFree=", 16) == 0) {
929 size_t val = parseMemOption(argv[i] + 16, 1024);
931 gDvm.heapMinFree = val;
933 dvmFprintf(stderr, "Invalid -XX:HeapMinFree option '%s'\n", argv[i]);
936 } else if (strncmp(argv[i], "-XX:HeapMaxFree=", 16) == 0) {
937 size_t val = parseMemOption(argv[i] + 16, 1024);
939 gDvm.heapMaxFree = val;
941 dvmFprintf(stderr, "Invalid -XX:HeapMaxFree option '%s'\n", argv[i]);
944 } else if (strncmp(argv[i], "-XX:HeapTargetUtilization=", 26) == 0) {
945 const char* start = argv[i] + 26;
946 const char* end = start;
947 double val = strtod(start, const_cast<char**>(&end));
948 // Ensure that we have a value, there was no cruft after it and it
949 // satisfies a sensible range.
950 bool sane_val = (start != end) && (end[0] == '\0') &&
951 (val >= 0.1) && (val <= 0.9);
953 gDvm.heapTargetUtilization = val;
955 dvmFprintf(stderr, "Invalid -XX:HeapTargetUtilization option '%s'\n", argv[i]);
958 } else if (strncmp(argv[i], "-Xss", 4) == 0) {
959 size_t val = parseMemOption(argv[i]+4, 1);
961 if (val >= kMinStackSize && val <= kMaxStackSize) {
962 gDvm.stackSize = val;
963 if (val > gDvm.mainThreadStackSize) {
964 gDvm.mainThreadStackSize = val;
967 dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
968 argv[i], kMinStackSize, kMaxStackSize);
972 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
976 } else if (strncmp(argv[i], "-XX:mainThreadStackSize=", strlen("-XX:mainThreadStackSize=")) == 0) {
977 size_t val = parseMemOption(argv[i] + strlen("-XX:mainThreadStackSize="), 1);
979 if (val >= kMinStackSize && val <= kMaxStackSize) {
980 gDvm.mainThreadStackSize = val;
982 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize '%s', range is %d to %d\n",
983 argv[i], kMinStackSize, kMaxStackSize);
987 dvmFprintf(stderr, "Invalid -XX:mainThreadStackSize option '%s'\n", argv[i]);
991 } else if (strncmp(argv[i], "-XX:+DisableExplicitGC", 22) == 0) {
992 gDvm.disableExplicitGc = true;
993 } else if (strcmp(argv[i], "-verbose") == 0 ||
994 strcmp(argv[i], "-verbose:class") == 0)
996 // JNI spec says "-verbose:gc,class" is valid, but cmd line
997 // doesn't work that way; may want to support.
998 gDvm.verboseClass = true;
999 } else if (strcmp(argv[i], "-verbose:jni") == 0) {
1000 gDvm.verboseJni = true;
1001 } else if (strcmp(argv[i], "-verbose:gc") == 0) {
1002 gDvm.verboseGc = true;
1003 } else if (strcmp(argv[i], "-verbose:shutdown") == 0) {
1004 gDvm.verboseShutdown = true;
1006 } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
1007 enableAssertions(argv[i] + 17, true);
1008 } else if (strncmp(argv[i], "-ea", 3) == 0) {
1009 enableAssertions(argv[i] + 3, true);
1010 } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
1011 enableAssertions(argv[i] + 18, false);
1012 } else if (strncmp(argv[i], "-da", 3) == 0) {
1013 enableAssertions(argv[i] + 3, false);
1014 } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
1015 strcmp(argv[i], "-esa") == 0)
1017 enableAssertions(NULL, true);
1018 } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
1019 strcmp(argv[i], "-dsa") == 0)
1021 enableAssertions(NULL, false);
1023 } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
1024 /* nothing to do now -- was handled during JNI init */
1026 } else if (strcmp(argv[i], "-Xdebug") == 0) {
1027 /* accept but ignore */
1029 } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
1030 strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
1034 if (argv[i][1] == 'X')
1035 tail = argv[i] + 10;
1037 tail = argv[i] + 15;
1039 if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
1043 } else if (strcmp(argv[i], "-Xrs") == 0) {
1044 gDvm.reduceSignals = true;
1045 } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
1046 /* disables SIGQUIT handler thread while still blocking SIGQUIT */
1047 /* (useful if we don't want thread but system still signals us) */
1048 gDvm.noQuitHandler = true;
1049 } else if (strcmp(argv[i], "-Xzygote") == 0) {
1051 #if defined(WITH_JIT)
1052 gDvmJit.runningInAndroidFramework = true;
1054 } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
1055 if (strcmp(argv[i] + 9, "none") == 0)
1056 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
1057 else if (strcmp(argv[i] + 9, "verified") == 0)
1058 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1059 else if (strcmp(argv[i] + 9, "all") == 0)
1060 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
1061 else if (strcmp(argv[i] + 9, "full") == 0)
1062 gDvm.dexOptMode = OPTIMIZE_MODE_FULL;
1064 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
1067 } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
1068 if (strcmp(argv[i] + 9, "none") == 0)
1069 gDvm.classVerifyMode = VERIFY_MODE_NONE;
1070 else if (strcmp(argv[i] + 9, "remote") == 0)
1071 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
1072 else if (strcmp(argv[i] + 9, "all") == 0)
1073 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1075 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
1078 } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
1079 int lim = atoi(argv[i] + 15);
1080 if (lim < 200 || (lim % 100) != 0) {
1081 dvmFprintf(stderr, "Bad value for -Xjnigreflimit: '%s'\n",
1085 gDvm.jniGrefLimit = lim;
1086 } else if (strncmp(argv[i], "-Xjnitrace:", 11) == 0) {
1087 gDvm.jniTrace = strdup(argv[i] + 11);
1088 } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
1089 gDvm.logStdio = true;
1091 } else if (strncmp(argv[i], "-Xint", 5) == 0) {
1092 if (argv[i][5] == ':') {
1093 if (strcmp(argv[i] + 6, "portable") == 0)
1094 gDvm.executionMode = kExecutionModeInterpPortable;
1095 else if (strcmp(argv[i] + 6, "fast") == 0)
1096 gDvm.executionMode = kExecutionModeInterpFast;
1098 else if (strcmp(argv[i] + 6, "jit") == 0)
1099 gDvm.executionMode = kExecutionModeJit;
1103 "Warning: Unrecognized interpreter mode %s\n",argv[i]);
1107 /* disable JIT if it was enabled by default */
1108 gDvm.executionMode = kExecutionModeInterpFast;
1111 } else if (strncmp(argv[i], "-Xlockprofthreshold:", 20) == 0) {
1112 gDvm.lockProfThreshold = atoi(argv[i] + 20);
1115 } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
1116 processXjitop(argv[i]);
1117 } else if (strncmp(argv[i], "-Xjitmethod:", 12) == 0) {
1118 processXjitmethod(argv[i] + strlen("-Xjitmethod:"), true);
1119 } else if (strncmp(argv[i], "-Xjitclass:", 11) == 0) {
1120 processXjitmethod(argv[i] + strlen("-Xjitclass:"), false);
1121 } else if (strncmp(argv[i], "-Xjitoffset:", 12) == 0) {
1122 processXjitoffset(argv[i] + strlen("-Xjitoffset:"));
1123 } else if (strncmp(argv[i], "-Xjitconfig:", 12) == 0) {
1124 processXjitconfig(argv[i] + strlen("-Xjitconfig:"));
1125 } else if (strncmp(argv[i], "-Xjitblocking", 13) == 0) {
1126 gDvmJit.blockingMode = true;
1127 } else if (strncmp(argv[i], "-Xjitthreshold:", 15) == 0) {
1128 gDvmJit.threshold = atoi(argv[i] + 15);
1129 } else if (strncmp(argv[i], "-Xincludeselectedop", 19) == 0) {
1130 gDvmJit.includeSelectedOp = true;
1131 } else if (strncmp(argv[i], "-Xincludeselectedmethod", 23) == 0) {
1132 gDvmJit.includeSelectedMethod = true;
1133 } else if (strncmp(argv[i], "-Xjitcheckcg", 12) == 0) {
1134 gDvmJit.checkCallGraph = true;
1135 /* Need to enable blocking mode due to stack crawling */
1136 gDvmJit.blockingMode = true;
1137 } else if (strncmp(argv[i], "-Xjitdumpbin", 12) == 0) {
1138 gDvmJit.printBinary = true;
1139 } else if (strncmp(argv[i], "-Xjitverbose", 12) == 0) {
1140 gDvmJit.printMe = true;
1141 } else if (strncmp(argv[i], "-Xjitprofile", 12) == 0) {
1142 gDvmJit.profileMode = kTraceProfilingContinuous;
1143 } else if (strncmp(argv[i], "-Xjitdisableopt", 15) == 0) {
1144 /* Disable selected optimizations */
1145 if (argv[i][15] == ':') {
1146 sscanf(argv[i] + 16, "%x", &gDvmJit.disableOpt);
1147 /* Disable all optimizations */
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.stackSize = kDefaultStackSize;
1245 gDvm.mainThreadStackSize = kDefaultStackSize;
1246 // When the heap is less than the maximum or growth limited size,
1247 // fix the free portion of the heap. The utilization is the ratio
1248 // of live to free memory, 0.5 implies half the heap is available
1249 // to allocate into before a GC occurs. Min free and max free
1250 // force the free memory to never be smaller than min free or
1251 // larger than max free.
1252 gDvm.heapTargetUtilization = 0.5;
1253 gDvm.heapMaxFree = 2 * 1024 * 1024;
1254 gDvm.heapMinFree = gDvm.heapMaxFree / 4;
1256 gDvm.concurrentMarkSweep = true;
1258 /* gDvm.jdwpSuspend = true; */
1260 /* allowed unless zygote config doesn't allow it */
1261 gDvm.jdwpAllowed = true;
1263 /* default verification and optimization modes */
1264 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1265 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1266 gDvm.monitorVerification = false;
1267 gDvm.generateRegisterMaps = true;
1268 gDvm.registerMapMode = kRegisterMapModeTypePrecise;
1271 * Default execution mode.
1273 * This should probably interact with the mterp code somehow, e.g. if
1274 * we know we're using the "desktop" build we should probably be
1275 * using "portable" rather than "fast".
1277 #if defined(WITH_JIT)
1278 gDvm.executionMode = kExecutionModeJit;
1279 gDvmJit.num_entries_pcTable = 0;
1280 gDvmJit.includeSelectedMethod = false;
1281 gDvmJit.includeSelectedOffset = false;
1282 gDvmJit.methodTable = NULL;
1283 gDvmJit.classTable = NULL;
1285 gDvm.constInit = false;
1286 gDvm.commonInit = false;
1288 gDvm.executionMode = kExecutionModeInterpFast;
1292 * SMP support is a compile-time define, but we may want to have
1293 * dexopt target a differently-configured device.
1295 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1298 * Default profiler configuration.
1300 gDvm.profilerClockSource = kProfilerClockSourceDual;
1305 * Handle a SIGBUS, which frequently occurs because somebody replaced an
1306 * optimized DEX file out from under us.
1308 static void busCatcher(int signum, siginfo_t* info, void* context)
1310 void* addr = info->si_addr;
1312 ALOGE("Caught a SIGBUS (%d), addr=%p", signum, addr);
1315 * If we return at this point the SIGBUS just keeps happening, so we
1316 * remove the signal handler and allow it to kill us. TODO: restore
1317 * the original, which points to a debuggerd stub; if we don't then
1318 * debuggerd won't be notified.
1320 signal(SIGBUS, SIG_DFL);
1324 * Configure signals. We need to block SIGQUIT so that the signal only
1325 * reaches the dump-stack-trace thread.
1327 * This can be disabled with the "-Xrs" flag.
1329 static void blockSignals()
1335 sigaddset(&mask, SIGQUIT);
1336 sigaddset(&mask, SIGUSR1); // used to initiate heap dump
1337 #if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1338 sigaddset(&mask, SIGUSR2); // used to investigate JIT internals
1340 //sigaddset(&mask, SIGPIPE);
1341 cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1345 /* TODO: save the old sigaction in a global */
1346 struct sigaction sa;
1347 memset(&sa, 0, sizeof(sa));
1348 sa.sa_sigaction = busCatcher;
1349 sa.sa_flags = SA_SIGINFO;
1350 cc = sigaction(SIGBUS, &sa, NULL);
1355 class ScopedShutdown {
1357 ScopedShutdown() : armed_(true) {
1375 * VM initialization. Pass in any options provided on the command line.
1376 * Do not pass in the class name or the options for the class.
1378 * Returns 0 on success.
1380 std::string dvmStartup(int argc, const char* const argv[],
1381 bool ignoreUnrecognized, JNIEnv* pEnv)
1383 ScopedShutdown scopedShutdown;
1385 assert(gDvm.initializing);
1387 ALOGV("VM init args (%d):", argc);
1388 for (int i = 0; i < argc; i++) {
1389 ALOGV(" %d: '%s'", i, argv[i]);
1391 setCommandLineDefaults();
1394 * Process the option flags (if any).
1396 int cc = processOptions(argc, argv, ignoreUnrecognized);
1399 dvmFprintf(stderr, "\n");
1402 return "syntax error";
1405 #if WITH_EXTRA_GC_CHECKS > 1
1406 /* only "portable" interp has the extra goodies */
1407 if (gDvm.executionMode != kExecutionModeInterpPortable) {
1408 ALOGI("Switching to 'portable' interpreter for GC checks");
1409 gDvm.executionMode = kExecutionModeInterpPortable;
1413 /* Configure group scheduling capabilities */
1414 if (!access("/dev/cpuctl/tasks", F_OK)) {
1415 ALOGV("Using kernel group scheduling");
1416 gDvm.kernelGroupScheduling = 1;
1418 ALOGV("Using kernel scheduler policies");
1421 /* configure signal handling */
1422 if (!gDvm.reduceSignals)
1425 /* verify system page size */
1426 if (sysconf(_SC_PAGESIZE) != SYSTEM_PAGE_SIZE) {
1427 return StringPrintf("expected page size %d, got %d",
1428 SYSTEM_PAGE_SIZE, (int) sysconf(_SC_PAGESIZE));
1432 ALOGV("Using executionMode %d", gDvm.executionMode);
1433 dvmCheckAsmConstants();
1436 * Initialize components.
1438 dvmQuasiAtomicsStartup();
1439 if (!dvmAllocTrackerStartup()) {
1440 return "dvmAllocTrackerStartup failed";
1442 if (!dvmGcStartup()) {
1443 return "dvmGcStartup failed";
1445 if (!dvmThreadStartup()) {
1446 return "dvmThreadStartup failed";
1448 if (!dvmInlineNativeStartup()) {
1449 return "dvmInlineNativeStartup";
1451 if (!dvmRegisterMapStartup()) {
1452 return "dvmRegisterMapStartup failed";
1454 if (!dvmInstanceofStartup()) {
1455 return "dvmInstanceofStartup failed";
1457 if (!dvmClassStartup()) {
1458 return "dvmClassStartup failed";
1462 * At this point, the system is guaranteed to be sufficiently
1463 * initialized that we can look up classes and class members. This
1464 * call populates the gDvm instance with all the class and member
1465 * references that the VM wants to use directly.
1467 if (!dvmFindRequiredClassesAndMembers()) {
1468 return "dvmFindRequiredClassesAndMembers failed";
1471 if (!dvmStringInternStartup()) {
1472 return "dvmStringInternStartup failed";
1474 if (!dvmNativeStartup()) {
1475 return "dvmNativeStartup failed";
1477 if (!dvmInternalNativeStartup()) {
1478 return "dvmInternalNativeStartup failed";
1480 if (!dvmJniStartup()) {
1481 return "dvmJniStartup failed";
1483 if (!dvmProfilingStartup()) {
1484 return "dvmProfilingStartup failed";
1488 * Create a table of methods for which we will substitute an "inline"
1489 * version for performance.
1491 if (!dvmCreateInlineSubsTable()) {
1492 return "dvmCreateInlineSubsTable failed";
1496 * Miscellaneous class library validation.
1498 if (!dvmValidateBoxClasses()) {
1499 return "dvmValidateBoxClasses failed";
1503 * Do the last bits of Thread struct initialization we need to allow
1504 * JNI calls to work.
1506 if (!dvmPrepMainForJni(pEnv)) {
1507 return "dvmPrepMainForJni failed";
1511 * Explicitly initialize java.lang.Class. This doesn't happen
1512 * automatically because it's allocated specially (it's an instance
1513 * of itself). Must happen before registration of system natives,
1514 * which make some calls that throw assertions if the classes they
1515 * operate on aren't initialized.
1517 if (!dvmInitClass(gDvm.classJavaLangClass)) {
1518 return "couldn't initialized java.lang.Class";
1522 * Register the system native methods, which are registered through JNI.
1524 if (!registerSystemNatives(pEnv)) {
1525 return "couldn't register system natives";
1529 * Do some "late" initialization for the memory allocator. This may
1530 * allocate storage and initialize classes.
1532 if (!dvmCreateStockExceptions()) {
1533 return "dvmCreateStockExceptions failed";
1537 * At this point, the VM is in a pretty good state. Finish prep on
1538 * the main thread (specifically, create a java.lang.Thread object to go
1539 * along with our Thread struct). Note we will probably be executing
1540 * some interpreted class initializer code in here.
1542 if (!dvmPrepMainThread()) {
1543 return "dvmPrepMainThread failed";
1547 * Make sure we haven't accumulated any tracked references. The main
1548 * thread should be starting with a clean slate.
1550 if (dvmReferenceTableEntries(&dvmThreadSelf()->internalLocalRefTable) != 0)
1552 ALOGW("Warning: tracked references remain post-initialization");
1553 dvmDumpReferenceTable(&dvmThreadSelf()->internalLocalRefTable, "MAIN");
1556 /* general debugging setup */
1557 if (!dvmDebuggerStartup()) {
1558 return "dvmDebuggerStartup failed";
1561 if (!dvmGcStartupClasses()) {
1562 return "dvmGcStartupClasses failed";
1566 * Init for either zygote mode or non-zygote mode. The key difference
1567 * is that we don't start any additional threads in Zygote mode.
1570 if (!initZygote()) {
1571 return "initZygote failed";
1574 if (!dvmInitAfterZygote()) {
1575 return "dvmInitAfterZygote failed";
1582 ALOGE("dvmTestHash FAILED");
1583 if (false /*noisy!*/ && !dvmTestIndirectRefTable())
1584 ALOGE("dvmTestIndirectRefTable FAILED");
1587 if (dvmCheckException(dvmThreadSelf())) {
1588 dvmLogExceptionStackTrace();
1589 return "Exception pending at end of VM initialization";
1592 scopedShutdown.disarm();
1596 static void loadJniLibrary(const char* name) {
1597 std::string mappedName(StringPrintf(OS_SHARED_LIB_FORMAT_STR, name));
1598 char* reason = NULL;
1599 if (!dvmLoadNativeCode(mappedName.c_str(), NULL, &reason)) {
1600 ALOGE("dvmLoadNativeCode failed for \"%s\": %s", name, reason);
1606 * Register java.* natives from our class libraries. We need to do
1607 * this after we're ready for JNI registration calls, but before we
1608 * do any class initialization.
1610 * If we get this wrong, we will blow up in the ThreadGroup class init if
1611 * interpreted code makes any reference to System. It will likely do this
1612 * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1614 * We need to have gDvm.initializing raised here so that JNI FindClass
1615 * won't try to use the system/application class loader.
1617 static bool registerSystemNatives(JNIEnv* pEnv)
1619 // Main thread is always first in list.
1620 Thread* self = gDvm.threadList;
1622 // Must set this before allowing JNI-based method registration.
1623 self->status = THREAD_NATIVE;
1625 // First set up JniConstants, which is used by libcore.
1626 JniConstants::init(pEnv);
1628 // Most JNI libraries can just use System.loadLibrary, but you can't
1629 // if you're the library that implements System.loadLibrary!
1630 loadJniLibrary("javacore");
1631 loadJniLibrary("nativehelper");
1633 // Back to run mode.
1634 self->status = THREAD_RUNNING;
1640 * Copied and modified slightly from system/core/toolbox/mount.c
1642 static std::string getMountsDevDir(const char *arg)
1644 char mount_dev[256];
1645 char mount_dir[256];
1648 FILE *fp = fopen("/proc/self/mounts", "r");
1650 ALOGE("Could not open /proc/self/mounts: %s", strerror(errno));
1654 while ((match = fscanf(fp, "%255s %255s %*s %*s %*d %*d\n", mount_dev, mount_dir)) != EOF) {
1657 if (match == 2 && (strcmp(arg, mount_dir) == 0)) {
1668 * Do zygote-mode-only initialization.
1670 static bool initZygote()
1672 /* zygote goes into its own process group */
1675 // See storage config details at http://source.android.com/tech/storage/
1676 // Create private mount namespace shared by all children
1677 if (unshare(CLONE_NEWNS) == -1) {
1678 SLOGE("Failed to unshare(): %s", strerror(errno));
1682 // Mark rootfs as being a slave so that changes from default
1683 // namespace only flow into our children.
1684 if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
1685 SLOGE("Failed to mount() rootfs as MS_SLAVE: %s", strerror(errno));
1689 // Create a staging tmpfs that is shared by our children; they will
1690 // bind mount storage into their respective private namespaces, which
1691 // are isolated from each other.
1692 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1693 if (target_base != NULL) {
1694 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1695 "uid=0,gid=1028,mode=0050") == -1) {
1696 SLOGE("Failed to mount tmpfs to %s: %s", target_base, strerror(errno));
1701 // Mark /system as NOSUID | NODEV
1702 const char* android_root = getenv("ANDROID_ROOT");
1704 if (android_root == NULL) {
1705 SLOGE("environment variable ANDROID_ROOT does not exist?!?!");
1709 std::string mountDev(getMountsDevDir(android_root));
1710 if (mountDev.empty()) {
1711 SLOGE("Unable to find mount point for %s", android_root);
1715 if (mount(mountDev.c_str(), android_root, "none",
1716 MS_REMOUNT | MS_NOSUID | MS_NODEV | MS_RDONLY | MS_BIND, NULL) == -1) {
1717 SLOGE("Remount of %s failed: %s", android_root, strerror(errno));
1721 #ifdef HAVE_ANDROID_OS
1722 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1723 if (errno == EINVAL) {
1724 SLOGW("PR_SET_NO_NEW_PRIVS failed. "
1725 "Is your kernel compiled correctly?: %s", strerror(errno));
1726 // Don't return -1 here, since it's expected that not all
1727 // kernels will support this option.
1729 SLOGW("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
1739 * Do non-zygote-mode initialization. This is done during VM init for
1740 * standard startup, or after a "zygote fork" when creating a new process.
1742 bool dvmInitAfterZygote()
1744 u8 startHeap, startQuit, startJdwp;
1745 u8 endHeap, endQuit, endJdwp;
1747 startHeap = dvmGetRelativeTimeUsec();
1750 * Post-zygote heap initialization, including starting
1751 * the HeapWorker thread.
1753 if (!dvmGcStartupAfterZygote())
1756 endHeap = dvmGetRelativeTimeUsec();
1757 startQuit = dvmGetRelativeTimeUsec();
1759 /* start signal catcher thread that dumps stacks on SIGQUIT */
1760 if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1761 if (!dvmSignalCatcherStartup())
1765 /* start stdout/stderr copier, if requested */
1766 if (gDvm.logStdio) {
1767 if (!dvmStdioConverterStartup())
1771 endQuit = dvmGetRelativeTimeUsec();
1772 startJdwp = dvmGetRelativeTimeUsec();
1775 * Start JDWP thread. If the command-line debugger flags specified
1776 * "suspend=y", this will pause the VM. We probably want this to
1780 ALOGD("JDWP init failed; continuing anyway");
1783 endJdwp = dvmGetRelativeTimeUsec();
1785 ALOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec",
1786 (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1787 (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1790 if (gDvm.executionMode == kExecutionModeJit) {
1791 if (!dvmCompilerStartup())
1800 * Prepare for a connection to a JDWP-compliant debugger.
1802 * Note this needs to happen fairly late in the startup process, because
1803 * we need to have all of the java.* native methods registered (which in
1804 * turn requires JNI to be fully prepped).
1806 * There are several ways to initialize:
1808 * We immediately try to connect to host:port. Bail on failure. On
1809 * success, send VM_START (suspending the VM if "suspend=y").
1810 * server=y suspend=n
1811 * Passively listen for a debugger to connect. Return immediately.
1812 * server=y suspend=y
1813 * Wait until debugger connects. Send VM_START ASAP, suspending the
1814 * VM after the message is sent.
1816 * This gets more complicated with a nonzero value for "timeout".
1818 static bool initJdwp()
1820 assert(!gDvm.zygote);
1823 * Init JDWP if the debugger is enabled. This may connect out to a
1824 * debugger, passively listen for a debugger, or block waiting for a
1827 if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1828 JdwpStartupParams params;
1830 if (gDvm.jdwpHost != NULL) {
1831 if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1832 ALOGE("ERROR: hostname too long: '%s'", gDvm.jdwpHost);
1835 strcpy(params.host, gDvm.jdwpHost);
1837 params.host[0] = '\0';
1839 params.transport = gDvm.jdwpTransport;
1840 params.server = gDvm.jdwpServer;
1841 params.suspend = gDvm.jdwpSuspend;
1842 params.port = gDvm.jdwpPort;
1844 gDvm.jdwpState = dvmJdwpStartup(¶ms);
1845 if (gDvm.jdwpState == NULL) {
1846 ALOGW("WARNING: debugger thread failed to initialize");
1847 /* TODO: ignore? fail? need to mimic "expected" behavior */
1852 * If a debugger has already attached, send the "welcome" message. This
1853 * may cause us to suspend all threads.
1855 if (dvmJdwpIsActive(gDvm.jdwpState)) {
1856 //dvmChangeStatus(NULL, THREAD_RUNNING);
1857 if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1858 ALOGW("WARNING: failed to post 'start' message to debugger");
1861 //dvmChangeStatus(NULL, THREAD_NATIVE);
1868 * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1869 * of initialization and then returns with "initializing" still set. (Used
1870 * by DexOpt command-line utility.)
1872 * Attempting to use JNI or internal natives will fail. It's best
1873 * if no bytecode gets executed, which means no <clinit>, which means
1874 * no exception-throwing. (In practice we need to initialize Class and
1875 * Object, and probably some exception classes.)
1877 * Returns 0 on success.
1879 int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1880 DexClassVerifyMode verifyMode, int dexoptFlags)
1882 gDvm.initializing = true;
1883 gDvm.optimizing = true;
1885 /* configure signal handling */
1888 /* set some defaults */
1889 setCommandLineDefaults();
1890 free(gDvm.bootClassPathStr);
1891 gDvm.bootClassPathStr = strdup(bootClassPath);
1893 /* set opt/verify modes */
1894 gDvm.dexOptMode = dexOptMode;
1895 gDvm.classVerifyMode = verifyMode;
1896 gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1897 if (dexoptFlags & DEXOPT_SMP) {
1898 assert((dexoptFlags & DEXOPT_UNIPROCESSOR) == 0);
1899 gDvm.dexOptForSmp = true;
1900 } else if (dexoptFlags & DEXOPT_UNIPROCESSOR) {
1901 gDvm.dexOptForSmp = false;
1903 gDvm.dexOptForSmp = (ANDROID_SMP != 0);
1907 * Initialize the heap, some basic thread control mutexes, and
1908 * get the bootclasspath prepped.
1910 * We can't load any classes yet because we may not yet have a source
1911 * for things like java.lang.Object and java.lang.Class.
1913 if (!dvmGcStartup())
1915 if (!dvmThreadStartup())
1917 if (!dvmInlineNativeStartup())
1919 if (!dvmRegisterMapStartup())
1921 if (!dvmInstanceofStartup())
1923 if (!dvmClassStartup())
1927 * We leave gDvm.initializing set to "true" so that, if we're not
1928 * able to process the "core" classes, we don't go into a death-spin
1929 * trying to throw a "class not found" exception.
1941 * All threads have stopped. Finish the shutdown procedure.
1943 * We can also be called if startup fails partway through, so be prepared
1944 * to deal with partially initialized data.
1946 * Free any storage allocated in gGlobals.
1948 * We can't dlclose() shared libs we've loaded, because it's possible a
1949 * thread not associated with the VM is running code in one.
1951 * This is called from the JNI DestroyJavaVM function, which can be
1952 * called from any thread. (In practice, this will usually run in the
1953 * same thread that started the VM, a/k/a the main thread, but we don't
1954 * want to assume that.)
1958 ALOGV("VM shutting down");
1960 if (CALC_CACHE_STATS)
1961 dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1964 * Stop our internal threads.
1966 dvmGcThreadShutdown();
1968 if (gDvm.jdwpState != NULL)
1969 dvmJdwpShutdown(gDvm.jdwpState);
1970 free(gDvm.jdwpHost);
1971 gDvm.jdwpHost = NULL;
1972 free(gDvm.jniTrace);
1973 gDvm.jniTrace = NULL;
1974 free(gDvm.stackTraceFile);
1975 gDvm.stackTraceFile = NULL;
1977 /* tell signal catcher to shut down if it was started */
1978 dvmSignalCatcherShutdown();
1980 /* shut down stdout/stderr conversion */
1981 dvmStdioConverterShutdown();
1984 if (gDvm.executionMode == kExecutionModeJit) {
1985 /* shut down the compiler thread */
1986 dvmCompilerShutdown();
1991 * Kill any daemon threads that still exist. Actively-running threads
1992 * are likely to crash the process if they continue to execute while
1993 * the VM shuts down.
1997 if (gDvm.verboseShutdown)
1998 ALOGD("VM cleaning up");
2000 dvmDebuggerShutdown();
2001 dvmProfilingShutdown();
2003 dvmStringInternShutdown();
2004 dvmThreadShutdown();
2006 dvmRegisterMapShutdown();
2007 dvmInstanceofShutdown();
2008 dvmInlineNativeShutdown();
2010 dvmAllocTrackerShutdown();
2012 /* these must happen AFTER dvmClassShutdown has walked through class data */
2013 dvmNativeShutdown();
2014 dvmInternalNativeShutdown();
2016 dvmFreeInlineSubsTable();
2018 free(gDvm.bootClassPathStr);
2019 free(gDvm.classPathStr);
2020 delete gDvm.properties;
2022 freeAssertionCtrl();
2024 dvmQuasiAtomicsShutdown();
2027 * We want valgrind to report anything we forget to free as "definitely
2028 * lost". If there's a pointer in the global chunk, it would be reported
2029 * as "still reachable". Erasing the memory fixes this.
2031 * This must be erased to zero if we want to restart the VM within this
2034 memset(&gDvm, 0xcd, sizeof(gDvm));
2039 * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
2040 * one was specified.
2042 int dvmFprintf(FILE* fp, const char* format, ...)
2047 va_start(args, format);
2048 if (gDvm.vfprintfHook != NULL)
2049 result = (*gDvm.vfprintfHook)(fp, format, args);
2051 result = vfprintf(fp, format, args);
2058 #include <execinfo.h>
2060 * glibc-only stack dump function. Requires link with "--export-dynamic".
2062 * TODO: move this into libs/cutils and make it work for all platforms.
2064 void dvmPrintNativeBackTrace()
2066 size_t MAX_STACK_FRAMES = 64;
2067 void* stackFrames[MAX_STACK_FRAMES];
2068 size_t frameCount = backtrace(stackFrames, MAX_STACK_FRAMES);
2071 * TODO: in practice, we may find that we should use backtrace_symbols_fd
2072 * to avoid allocation, rather than use our own custom formatting.
2074 char** strings = backtrace_symbols(stackFrames, frameCount);
2075 if (strings == NULL) {
2076 ALOGE("backtrace_symbols failed: %s", strerror(errno));
2081 for (i = 0; i < frameCount; ++i) {
2082 ALOGW("#%-2d %s", i, strings[i]);
2087 void dvmPrintNativeBackTrace() {
2088 /* Hopefully, you're on an Android device and debuggerd will do this. */
2093 * Abort the VM. We get here on fatal errors. Try very hard not to use
2094 * this; whenever possible, return an error to somebody responsible.
2099 * Leave gDvm.lastMessage on the stack frame which can be decoded in the
2100 * tombstone file. This is for situations where we only have tombstone files
2101 * but no logs (ie b/5372634).
2103 * For example, in the tombstone file you usually see this:
2105 * #00 pc 00050ef2 /system/lib/libdvm.so (dvmAbort)
2106 * #01 pc 00077670 /system/lib/libdvm.so (_Z15dvmClassStartupv)
2111 * #00 beed2658 00000000
2121 * The ascii values between beed265c and beed2674 belongs to messageBuffer
2122 * and it can be decoded as "/system/framework/core.jar".
2124 const int messageLength = 512;
2125 char messageBuffer[messageLength] = {0};
2128 snprintf(messageBuffer, messageLength, "%s", gDvm.lastMessage);
2130 /* So that messageBuffer[] looks like useful stuff to the compiler */
2131 for (int i = 0; i < messageLength && messageBuffer[i]; i++) {
2132 result += messageBuffer[i];
2135 ALOGE("VM aborting");
2137 fflush(NULL); // flush all open file buffers
2139 /* JNI-supplied abort hook gets right of first refusal */
2140 if (gDvm.abortHook != NULL)
2141 (*gDvm.abortHook)();
2144 * On the device, debuggerd will give us a stack trace.
2145 * On the host, we have to help ourselves.
2147 dvmPrintNativeBackTrace();
2150 * If we call abort(), all threads in the process receives a SIBABRT.
2151 * debuggerd dumps the stack trace of the main thread, whether or not
2152 * that was the thread that failed.
2154 * By stuffing a value into a bogus address, we cause a segmentation
2155 * fault in the current thread, and get a useful log from debuggerd.
2156 * We can also trivially tell the difference between a VM crash and
2157 * a deliberate abort by looking at the fault address.
2159 *((char*)0xdeadd00d) = result;