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