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