app_main.cpp revision 7e7c6031821e2aa55c756a9c85f97a22f4875552
1/*
2 * Main entry of app process.
3 *
4 * Starts the interpreted runtime, then starts up the application.
5 *
6 */
7
8#define LOG_TAG "appproc"
9
10#include <binder/IPCThreadState.h>
11#include <binder/ProcessState.h>
12#include <utils/Log.h>
13#include <cutils/memory.h>
14#include <cutils/process_name.h>
15#include <cutils/properties.h>
16#include <cutils/trace.h>
17#include <android_runtime/AndroidRuntime.h>
18#include <private/android_filesystem_config.h>  // for AID_SYSTEM
19
20#include <stdlib.h>
21#include <stdio.h>
22#include <unistd.h>
23#include <sys/prctl.h>
24
25namespace android {
26
27static void app_usage()
28{
29    fprintf(stderr,
30        "Usage: app_process [java-options] cmd-dir start-class-name [options]\n");
31}
32
33class AppRuntime : public AndroidRuntime
34{
35public:
36    AppRuntime(char* argBlockStart, const size_t argBlockLength)
37        : AndroidRuntime(argBlockStart, argBlockLength)
38        , mClass(NULL)
39    {
40    }
41
42    void setClassNameAndArgs(const String8& className, int argc, char * const *argv) {
43        mClassName = className;
44        for (int i = 0; i < argc; ++i) {
45             mArgs.add(String8(argv[i]));
46        }
47    }
48
49    virtual void onVmCreated(JNIEnv* env)
50    {
51        if (mClassName.isEmpty()) {
52            return; // Zygote. Nothing to do here.
53        }
54
55        /*
56         * This is a little awkward because the JNI FindClass call uses the
57         * class loader associated with the native method we're executing in.
58         * If called in onStarted (from RuntimeInit.finishInit because we're
59         * launching "am", for example), FindClass would see that we're calling
60         * from a boot class' native method, and so wouldn't look for the class
61         * we're trying to look up in CLASSPATH. Unfortunately it needs to,
62         * because the "am" classes are not boot classes.
63         *
64         * The easiest fix is to call FindClass here, early on before we start
65         * executing boot class Java code and thereby deny ourselves access to
66         * non-boot classes.
67         */
68        char* slashClassName = toSlashClassName(mClassName.string());
69        mClass = env->FindClass(slashClassName);
70        if (mClass == NULL) {
71            ALOGE("ERROR: could not find class '%s'\n", mClassName.string());
72        }
73        free(slashClassName);
74
75        mClass = reinterpret_cast<jclass>(env->NewGlobalRef(mClass));
76    }
77
78    virtual void onStarted()
79    {
80        sp<ProcessState> proc = ProcessState::self();
81        ALOGV("App process: starting thread pool.\n");
82        proc->startThreadPool();
83
84        AndroidRuntime* ar = AndroidRuntime::getRuntime();
85        ar->callMain(mClassName, mClass, mArgs);
86
87        IPCThreadState::self()->stopProcess();
88    }
89
90    virtual void onZygoteInit()
91    {
92        // Re-enable tracing now that we're no longer in Zygote.
93        atrace_set_tracing_enabled(true);
94
95        sp<ProcessState> proc = ProcessState::self();
96        ALOGV("App process: starting thread pool.\n");
97        proc->startThreadPool();
98    }
99
100    virtual void onExit(int code)
101    {
102        if (mClassName.isEmpty()) {
103            // if zygote
104            IPCThreadState::self()->stopProcess();
105        }
106
107        AndroidRuntime::onExit(code);
108    }
109
110
111    String8 mClassName;
112    Vector<String8> mArgs;
113    jclass mClass;
114};
115
116}
117
118using namespace android;
119
120static size_t computeArgBlockSize(int argc, char* const argv[]) {
121    // TODO: This assumes that all arguments are allocated in
122    // contiguous memory. There isn't any documented guarantee
123    // that this is the case, but this is how the kernel does it
124    // (see fs/exec.c).
125    //
126    // Also note that this is a constant for "normal" android apps.
127    // Since they're forked from zygote, the size of their command line
128    // is the size of the zygote command line.
129    //
130    // We change the process name of the process by over-writing
131    // the start of the argument block (argv[0]) with the new name of
132    // the process, so we'd mysteriously start getting truncated process
133    // names if the zygote command line decreases in size.
134    uintptr_t start = reinterpret_cast<uintptr_t>(argv[0]);
135    uintptr_t end = reinterpret_cast<uintptr_t>(argv[argc - 1]);
136    end += strlen(argv[argc - 1]) + 1;
137    return (end - start);
138}
139
140static void maybeCreateDalvikCache() {
141#if defined(__aarch64__)
142    static const char kInstructionSet[] = "arm64";
143#elif defined(__x86_64__)
144    static const char kInstructionSet[] = "x86_64";
145#elif defined(__arm__)
146    static const char kInstructionSet[] = "arm";
147#elif defined(__i386__)
148    static const char kInstructionSet[] = "x86";
149#elif defined (__mips__) && !defined(__LP64__)
150    static const char kInstructionSet[] = "mips";
151#elif defined (__mips__) && defined(__LP64__)
152    static const char kInstructionSet[] = "mips64";
153#else
154#error "Unknown instruction set"
155#endif
156    const char* androidRoot = getenv("ANDROID_DATA");
157    LOG_ALWAYS_FATAL_IF(androidRoot == NULL, "ANDROID_DATA environment variable unset");
158
159    char dalvikCacheDir[PATH_MAX];
160    const int numChars = snprintf(dalvikCacheDir, PATH_MAX,
161            "%s/dalvik-cache/%s", androidRoot, kInstructionSet);
162    LOG_ALWAYS_FATAL_IF((numChars >= PATH_MAX || numChars < 0),
163            "Error constructing dalvik cache : %s", strerror(errno));
164
165    int result = mkdir(dalvikCacheDir, 0711);
166    LOG_ALWAYS_FATAL_IF((result < 0 && errno != EEXIST),
167            "Error creating cache dir %s : %s", dalvikCacheDir, strerror(errno));
168
169    // We always perform these steps because the directory might
170    // already exist, with wider permissions and a different owner
171    // than we'd like.
172    result = chown(dalvikCacheDir, AID_ROOT, AID_ROOT);
173    LOG_ALWAYS_FATAL_IF((result < 0), "Error changing dalvik-cache ownership : %s", strerror(errno));
174
175    result = chmod(dalvikCacheDir, 0711);
176    LOG_ALWAYS_FATAL_IF((result < 0),
177            "Error changing dalvik-cache permissions : %s", strerror(errno));
178}
179
180#if defined(__LP64__)
181static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
182static const char ZYGOTE_NICE_NAME[] = "zygote64";
183#else
184static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
185static const char ZYGOTE_NICE_NAME[] = "zygote";
186#endif
187
188int main(int argc, char* const argv[])
189{
190    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
191        // Older kernels don't understand PR_SET_NO_NEW_PRIVS and return
192        // EINVAL. Don't die on such kernels.
193        if (errno != EINVAL) {
194            LOG_ALWAYS_FATAL("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
195            return 12;
196        }
197    }
198
199    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
200    // Process command line arguments
201    // ignore argv[0]
202    argc--;
203    argv++;
204
205    // Everything up to '--' or first non '-' arg goes to the vm.
206    //
207    // The first argument after the VM args is the "parent dir", which
208    // is currently unused.
209    //
210    // After the parent dir, we expect one or more the following internal
211    // arguments :
212    //
213    // --zygote : Start in zygote mode
214    // --start-system-server : Start the system server.
215    // --application : Start in application (stand alone, non zygote) mode.
216    // --nice-name : The nice name for this process.
217    //
218    // For non zygote starts, these arguments will be followed by
219    // the main class name. All remaining arguments are passed to
220    // the main method of this class.
221    //
222    // For zygote starts, all remaining arguments are passed to the zygote.
223    // main function.
224    //
225    // Note that we must copy argument string values since we will rewrite the
226    // entire argument block when we apply the nice name to argv0.
227
228    int i;
229    for (i = 0; i < argc; i++) {
230        if (argv[i][0] != '-') {
231            break;
232        }
233        if (argv[i][1] == '-' && argv[i][2] == 0) {
234            ++i; // Skip --.
235            break;
236        }
237        runtime.addOption(strdup(argv[i]));
238    }
239
240    // Parse runtime arguments.  Stop at first unrecognized option.
241    bool zygote = false;
242    bool startSystemServer = false;
243    bool application = false;
244    String8 niceName;
245    String8 className;
246
247    ++i;  // Skip unused "parent dir" argument.
248    while (i < argc) {
249        const char* arg = argv[i++];
250        if (strcmp(arg, "--zygote") == 0) {
251            zygote = true;
252            niceName = ZYGOTE_NICE_NAME;
253        } else if (strcmp(arg, "--start-system-server") == 0) {
254            startSystemServer = true;
255        } else if (strcmp(arg, "--application") == 0) {
256            application = true;
257        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
258            niceName.setTo(arg + 12);
259        } else if (strncmp(arg, "--", 2) != 0) {
260            className.setTo(arg);
261            break;
262        } else {
263            --i;
264            break;
265        }
266    }
267
268    Vector<String8> args;
269    if (!className.isEmpty()) {
270        // We're not in zygote mode, the only argument we need to pass
271        // to RuntimeInit is the application argument.
272        //
273        // The Remainder of args get passed to startup class main(). Make
274        // copies of them before we overwrite them with the process name.
275        args.add(application ? String8("application") : String8("tool"));
276        runtime.setClassNameAndArgs(className, argc - i, argv + i);
277    } else {
278        // We're in zygote mode.
279        maybeCreateDalvikCache();
280
281        if (startSystemServer) {
282            args.add(String8("start-system-server"));
283        }
284
285        char prop[PROP_VALUE_MAX];
286        if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
287            LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
288                ABI_LIST_PROPERTY);
289            return 11;
290        }
291
292        String8 abiFlag("--abi-list=");
293        abiFlag.append(prop);
294        args.add(abiFlag);
295
296        // In zygote mode, pass all remaining arguments to the zygote
297        // main() method.
298        for (; i < argc; ++i) {
299            args.add(String8(argv[i]));
300        }
301    }
302
303    if (!niceName.isEmpty()) {
304        runtime.setArgv0(niceName.string());
305        set_process_name(niceName.string());
306    }
307
308    if (zygote) {
309        runtime.start("com.android.internal.os.ZygoteInit", args);
310    } else if (className) {
311        runtime.start("com.android.internal.os.RuntimeInit", args);
312    } else {
313        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
314        app_usage();
315        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
316        return 10;
317    }
318}
319