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