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