1/*
2** Copyright 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#include <inttypes.h>
18#include <sys/capability.h>
19#include "installd.h"
20#include <cutils/sched_policy.h>
21#include <diskusage/dirsize.h>
22#include <selinux/android.h>
23#include <system/thread_defs.h>
24
25/* Directory records that are used in execution of commands. */
26dir_rec_t android_data_dir;
27dir_rec_t android_asec_dir;
28dir_rec_t android_app_dir;
29dir_rec_t android_app_private_dir;
30dir_rec_t android_app_lib_dir;
31dir_rec_t android_media_dir;
32dir_rec_array_t android_system_dirs;
33
34int install(const char *pkgname, uid_t uid, gid_t gid, const char *seinfo)
35{
36    char pkgdir[PKG_PATH_MAX];
37    char libsymlink[PKG_PATH_MAX];
38    char applibdir[PKG_PATH_MAX];
39    struct stat libStat;
40
41    if ((uid < AID_SYSTEM) || (gid < AID_SYSTEM)) {
42        ALOGE("invalid uid/gid: %d %d\n", uid, gid);
43        return -1;
44    }
45
46    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, 0)) {
47        ALOGE("cannot create package path\n");
48        return -1;
49    }
50
51    if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, 0)) {
52        ALOGE("cannot create package lib symlink origin path\n");
53        return -1;
54    }
55
56    if (create_pkg_path_in_dir(applibdir, &android_app_lib_dir, pkgname, PKG_DIR_POSTFIX)) {
57        ALOGE("cannot create package lib symlink dest path\n");
58        return -1;
59    }
60
61    if (mkdir(pkgdir, 0751) < 0) {
62        ALOGE("cannot create dir '%s': %s\n", pkgdir, strerror(errno));
63        return -1;
64    }
65    if (chmod(pkgdir, 0751) < 0) {
66        ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
67        unlink(pkgdir);
68        return -1;
69    }
70
71    if (lstat(libsymlink, &libStat) < 0) {
72        if (errno != ENOENT) {
73            ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
74            return -1;
75        }
76    } else {
77        if (S_ISDIR(libStat.st_mode)) {
78            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
79                ALOGE("couldn't delete lib directory during install for: %s", libsymlink);
80                return -1;
81            }
82        } else if (S_ISLNK(libStat.st_mode)) {
83            if (unlink(libsymlink) < 0) {
84                ALOGE("couldn't unlink lib directory during install for: %s", libsymlink);
85                return -1;
86            }
87        }
88    }
89
90    if (selinux_android_setfilecon(pkgdir, pkgname, seinfo, uid) < 0) {
91        ALOGE("cannot setfilecon dir '%s': %s\n", pkgdir, strerror(errno));
92        unlink(libsymlink);
93        unlink(pkgdir);
94        return -errno;
95    }
96
97    if (symlink(applibdir, libsymlink) < 0) {
98        ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, applibdir,
99                strerror(errno));
100        unlink(pkgdir);
101        return -1;
102    }
103
104    if (chown(pkgdir, uid, gid) < 0) {
105        ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
106        unlink(libsymlink);
107        unlink(pkgdir);
108        return -1;
109    }
110
111    return 0;
112}
113
114int uninstall(const char *pkgname, userid_t userid)
115{
116    char pkgdir[PKG_PATH_MAX];
117
118    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid))
119        return -1;
120
121    remove_profile_file(pkgname);
122
123    /* delete contents AND directory, no exceptions */
124    return delete_dir_contents(pkgdir, 1, NULL);
125}
126
127int renamepkg(const char *oldpkgname, const char *newpkgname)
128{
129    char oldpkgdir[PKG_PATH_MAX];
130    char newpkgdir[PKG_PATH_MAX];
131
132    if (create_pkg_path(oldpkgdir, oldpkgname, PKG_DIR_POSTFIX, 0))
133        return -1;
134    if (create_pkg_path(newpkgdir, newpkgname, PKG_DIR_POSTFIX, 0))
135        return -1;
136
137    if (rename(oldpkgdir, newpkgdir) < 0) {
138        ALOGE("cannot rename dir '%s' to '%s': %s\n", oldpkgdir, newpkgdir, strerror(errno));
139        return -errno;
140    }
141    return 0;
142}
143
144int fix_uid(const char *pkgname, uid_t uid, gid_t gid)
145{
146    char pkgdir[PKG_PATH_MAX];
147    struct stat s;
148    int rc = 0;
149
150    if ((uid < AID_SYSTEM) || (gid < AID_SYSTEM)) {
151        ALOGE("invalid uid/gid: %d %d\n", uid, gid);
152        return -1;
153    }
154
155    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, 0)) {
156        ALOGE("cannot create package path\n");
157        return -1;
158    }
159
160    if (stat(pkgdir, &s) < 0) return -1;
161
162    if (s.st_uid != 0 || s.st_gid != 0) {
163        ALOGE("fixing uid of non-root pkg: %s %" PRIu32 " %" PRIu32 "\n", pkgdir, s.st_uid, s.st_gid);
164        return -1;
165    }
166
167    if (chmod(pkgdir, 0751) < 0) {
168        ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
169        unlink(pkgdir);
170        return -errno;
171    }
172    if (chown(pkgdir, uid, gid) < 0) {
173        ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
174        unlink(pkgdir);
175        return -errno;
176    }
177
178    return 0;
179}
180
181int delete_user_data(const char *pkgname, userid_t userid)
182{
183    char pkgdir[PKG_PATH_MAX];
184
185    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid))
186        return -1;
187
188    return delete_dir_contents(pkgdir, 0, NULL);
189}
190
191int make_user_data(const char *pkgname, uid_t uid, userid_t userid, const char* seinfo)
192{
193    char pkgdir[PKG_PATH_MAX];
194    char applibdir[PKG_PATH_MAX];
195    char libsymlink[PKG_PATH_MAX];
196    struct stat libStat;
197
198    // Create the data dir for the package
199    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid)) {
200        return -1;
201    }
202    if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, userid)) {
203        ALOGE("cannot create package lib symlink origin path\n");
204        return -1;
205    }
206    if (create_pkg_path_in_dir(applibdir, &android_app_lib_dir, pkgname, PKG_DIR_POSTFIX)) {
207        ALOGE("cannot create package lib symlink dest path\n");
208        return -1;
209    }
210
211    if (mkdir(pkgdir, 0751) < 0) {
212        ALOGE("cannot create dir '%s': %s\n", pkgdir, strerror(errno));
213        return -errno;
214    }
215    if (chmod(pkgdir, 0751) < 0) {
216        ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
217        unlink(pkgdir);
218        return -errno;
219    }
220
221    if (lstat(libsymlink, &libStat) < 0) {
222        if (errno != ENOENT) {
223            ALOGE("couldn't stat lib dir for non-primary: %s\n", strerror(errno));
224            unlink(pkgdir);
225            return -1;
226        }
227    } else {
228        if (S_ISDIR(libStat.st_mode)) {
229            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
230                ALOGE("couldn't delete lib directory during install for non-primary: %s",
231                        libsymlink);
232                unlink(pkgdir);
233                return -1;
234            }
235        } else if (S_ISLNK(libStat.st_mode)) {
236            if (unlink(libsymlink) < 0) {
237                ALOGE("couldn't unlink lib directory during install for non-primary: %s",
238                        libsymlink);
239                unlink(pkgdir);
240                return -1;
241            }
242        }
243    }
244
245    if (selinux_android_setfilecon(pkgdir, pkgname, seinfo, uid) < 0) {
246        ALOGE("cannot setfilecon dir '%s': %s\n", pkgdir, strerror(errno));
247        unlink(libsymlink);
248        unlink(pkgdir);
249        return -errno;
250    }
251
252    if (symlink(applibdir, libsymlink) < 0) {
253        ALOGE("couldn't symlink directory for non-primary '%s' -> '%s': %s\n", libsymlink,
254                applibdir, strerror(errno));
255        unlink(pkgdir);
256        return -1;
257    }
258
259    if (chown(pkgdir, uid, uid) < 0) {
260        ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
261        unlink(libsymlink);
262        unlink(pkgdir);
263        return -errno;
264    }
265
266    return 0;
267}
268
269int make_user_config(userid_t userid)
270{
271    if (ensure_config_user_dirs(userid) == -1) {
272        return -1;
273    }
274
275    return 0;
276}
277
278int delete_user(userid_t userid)
279{
280    int status = 0;
281
282    char data_path[PKG_PATH_MAX];
283    if ((create_user_path(data_path, userid) != 0)
284            || (delete_dir_contents(data_path, 1, NULL) != 0)) {
285        status = -1;
286    }
287
288    char media_path[PATH_MAX];
289    if ((create_user_media_path(media_path, userid) != 0)
290            || (delete_dir_contents(media_path, 1, NULL) != 0)) {
291        status = -1;
292    }
293
294    char config_path[PATH_MAX];
295    if ((create_user_config_path(config_path, userid) != 0)
296            || (delete_dir_contents(config_path, 1, NULL) != 0)) {
297        status = -1;
298    }
299
300    return status;
301}
302
303int delete_cache(const char *pkgname, userid_t userid)
304{
305    char cachedir[PKG_PATH_MAX];
306
307    if (create_pkg_path(cachedir, pkgname, CACHE_DIR_POSTFIX, userid))
308        return -1;
309
310    /* delete contents, not the directory, no exceptions */
311    return delete_dir_contents(cachedir, 0, NULL);
312}
313
314int delete_code_cache(const char *pkgname, userid_t userid)
315{
316    char codecachedir[PKG_PATH_MAX];
317    struct stat s;
318
319    if (create_pkg_path(codecachedir, pkgname, CODE_CACHE_DIR_POSTFIX, userid))
320        return -1;
321
322    /* it's okay if code cache is missing */
323    if (lstat(codecachedir, &s) == -1 && errno == ENOENT) {
324        return 0;
325    }
326
327    /* delete contents, not the directory, no exceptions */
328    return delete_dir_contents(codecachedir, 0, NULL);
329}
330
331/* Try to ensure free_size bytes of storage are available.
332 * Returns 0 on success.
333 * This is rather simple-minded because doing a full LRU would
334 * be potentially memory-intensive, and without atime it would
335 * also require that apps constantly modify file metadata even
336 * when just reading from the cache, which is pretty awful.
337 */
338int free_cache(int64_t free_size)
339{
340    cache_t* cache;
341    int64_t avail;
342    DIR *d;
343    struct dirent *de;
344    char tmpdir[PATH_MAX];
345    char *dirpos;
346
347    avail = data_disk_free();
348    if (avail < 0) return -1;
349
350    ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
351    if (avail >= free_size) return 0;
352
353    cache = start_cache_collection();
354
355    // Collect cache files for primary user.
356    if (create_user_path(tmpdir, 0) == 0) {
357        //ALOGI("adding cache files from %s\n", tmpdir);
358        add_cache_files(cache, tmpdir, "cache");
359    }
360
361    // Search for other users and add any cache files from them.
362    snprintf(tmpdir, sizeof(tmpdir), "%s%s", android_data_dir.path,
363            SECONDARY_USER_PREFIX);
364    dirpos = tmpdir + strlen(tmpdir);
365    d = opendir(tmpdir);
366    if (d != NULL) {
367        while ((de = readdir(d))) {
368            if (de->d_type == DT_DIR) {
369                const char *name = de->d_name;
370                    /* always skip "." and ".." */
371                if (name[0] == '.') {
372                    if (name[1] == 0) continue;
373                    if ((name[1] == '.') && (name[2] == 0)) continue;
374                }
375                if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
376                    strcpy(dirpos, name);
377                    //ALOGI("adding cache files from %s\n", tmpdir);
378                    add_cache_files(cache, tmpdir, "cache");
379                } else {
380                    ALOGW("Path exceeds limit: %s%s", tmpdir, name);
381                }
382            }
383        }
384        closedir(d);
385    }
386
387    // Collect cache files on external storage for all users (if it is mounted as part
388    // of the internal storage).
389    strcpy(tmpdir, android_media_dir.path);
390    dirpos = tmpdir + strlen(tmpdir);
391    d = opendir(tmpdir);
392    if (d != NULL) {
393        while ((de = readdir(d))) {
394            if (de->d_type == DT_DIR) {
395                const char *name = de->d_name;
396                    /* skip any dir that doesn't start with a number, so not a user */
397                if (name[0] < '0' || name[0] > '9') {
398                    continue;
399                }
400                if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
401                    strcpy(dirpos, name);
402                    if (lookup_media_dir(tmpdir, "Android") == 0
403                            && lookup_media_dir(tmpdir, "data") == 0) {
404                        //ALOGI("adding cache files from %s\n", tmpdir);
405                        add_cache_files(cache, tmpdir, "cache");
406                    }
407                } else {
408                    ALOGW("Path exceeds limit: %s%s", tmpdir, name);
409                }
410            }
411        }
412        closedir(d);
413    }
414
415    clear_cache_files(cache, free_size);
416    finish_cache_collection(cache);
417
418    return data_disk_free() >= free_size ? 0 : -1;
419}
420
421int move_dex(const char *src, const char *dst, const char *instruction_set)
422{
423    char src_dex[PKG_PATH_MAX];
424    char dst_dex[PKG_PATH_MAX];
425
426    if (validate_apk_path(src)) {
427        ALOGE("invalid apk path '%s' (bad prefix)\n", src);
428        return -1;
429    }
430    if (validate_apk_path(dst)) {
431        ALOGE("invalid apk path '%s' (bad prefix)\n", dst);
432        return -1;
433    }
434
435    if (create_cache_path(src_dex, src, instruction_set)) return -1;
436    if (create_cache_path(dst_dex, dst, instruction_set)) return -1;
437
438    ALOGV("move %s -> %s\n", src_dex, dst_dex);
439    if (rename(src_dex, dst_dex) < 0) {
440        ALOGE("Couldn't move %s: %s\n", src_dex, strerror(errno));
441        return -1;
442    } else {
443        return 0;
444    }
445}
446
447int rm_dex(const char *path, const char *instruction_set)
448{
449    char dex_path[PKG_PATH_MAX];
450
451    if (validate_apk_path(path) && validate_system_app_path(path)) {
452        ALOGE("invalid apk path '%s' (bad prefix)\n", path);
453        return -1;
454    }
455
456    if (create_cache_path(dex_path, path, instruction_set)) return -1;
457
458    ALOGV("unlink %s\n", dex_path);
459    if (unlink(dex_path) < 0) {
460        if (errno != ENOENT) {
461            ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
462        }
463        return -1;
464    } else {
465        return 0;
466    }
467}
468
469int get_size(const char *pkgname, userid_t userid, const char *apkpath,
470             const char *libdirpath, const char *fwdlock_apkpath, const char *asecpath,
471             const char *instruction_set, int64_t *_codesize, int64_t *_datasize,
472             int64_t *_cachesize, int64_t* _asecsize)
473{
474    DIR *d;
475    int dfd;
476    struct dirent *de;
477    struct stat s;
478    char path[PKG_PATH_MAX];
479
480    int64_t codesize = 0;
481    int64_t datasize = 0;
482    int64_t cachesize = 0;
483    int64_t asecsize = 0;
484
485        /* count the source apk as code -- but only if it's not
486         * on the /system partition and its not on the sdcard.
487         */
488    if (validate_system_app_path(apkpath) &&
489            strncmp(apkpath, android_asec_dir.path, android_asec_dir.len) != 0) {
490        if (stat(apkpath, &s) == 0) {
491            codesize += stat_size(&s);
492        }
493    }
494        /* count the forward locked apk as code if it is given
495         */
496    if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
497        if (stat(fwdlock_apkpath, &s) == 0) {
498            codesize += stat_size(&s);
499        }
500    }
501        /* count the cached dexfile as code */
502    if (!create_cache_path(path, apkpath, instruction_set)) {
503        if (stat(path, &s) == 0) {
504            codesize += stat_size(&s);
505        }
506    }
507
508        /* add in size of any libraries */
509    if (libdirpath != NULL && libdirpath[0] != '!') {
510        d = opendir(libdirpath);
511        if (d != NULL) {
512            dfd = dirfd(d);
513            codesize += calculate_dir_size(dfd);
514            closedir(d);
515        }
516    }
517
518        /* compute asec size if it is given
519         */
520    if (asecpath != NULL && asecpath[0] != '!') {
521        if (stat(asecpath, &s) == 0) {
522            asecsize += stat_size(&s);
523        }
524    }
525
526    if (create_pkg_path(path, pkgname, PKG_DIR_POSTFIX, userid)) {
527        goto done;
528    }
529
530    d = opendir(path);
531    if (d == NULL) {
532        goto done;
533    }
534    dfd = dirfd(d);
535
536    /* most stuff in the pkgdir is data, except for the "cache"
537     * directory and below, which is cache, and the "lib" directory
538     * and below, which is code...
539     */
540    while ((de = readdir(d))) {
541        const char *name = de->d_name;
542
543        if (de->d_type == DT_DIR) {
544            int subfd;
545            int64_t statsize = 0;
546            int64_t dirsize = 0;
547                /* always skip "." and ".." */
548            if (name[0] == '.') {
549                if (name[1] == 0) continue;
550                if ((name[1] == '.') && (name[2] == 0)) continue;
551            }
552            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
553                statsize = stat_size(&s);
554            }
555            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
556            if (subfd >= 0) {
557                dirsize = calculate_dir_size(subfd);
558            }
559            if(!strcmp(name,"lib")) {
560                codesize += dirsize + statsize;
561            } else if(!strcmp(name,"cache")) {
562                cachesize += dirsize + statsize;
563            } else {
564                datasize += dirsize + statsize;
565            }
566        } else if (de->d_type == DT_LNK && !strcmp(name,"lib")) {
567            // This is the symbolic link to the application's library
568            // code.  We'll count this as code instead of data, since
569            // it is not something that the app creates.
570            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
571                codesize += stat_size(&s);
572            }
573        } else {
574            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
575                datasize += stat_size(&s);
576            }
577        }
578    }
579    closedir(d);
580done:
581    *_codesize = codesize;
582    *_datasize = datasize;
583    *_cachesize = cachesize;
584    *_asecsize = asecsize;
585    return 0;
586}
587
588int create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set)
589{
590    char *tmp;
591    int srclen;
592    int dstlen;
593
594    srclen = strlen(src);
595
596        /* demand that we are an absolute path */
597    if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
598        return -1;
599    }
600
601    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
602        return -1;
603    }
604
605    dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +
606        strlen(instruction_set) +
607        strlen(DALVIK_CACHE_POSTFIX) + 2;
608
609    if (dstlen > PKG_PATH_MAX) {
610        return -1;
611    }
612
613    sprintf(path,"%s%s/%s%s",
614            DALVIK_CACHE_PREFIX,
615            instruction_set,
616            src + 1, /* skip the leading / */
617            DALVIK_CACHE_POSTFIX);
618
619    for(tmp = path + strlen(DALVIK_CACHE_PREFIX) + strlen(instruction_set) + 1; *tmp; tmp++) {
620        if (*tmp == '/') {
621            *tmp = '@';
622        }
623    }
624
625    return 0;
626}
627
628static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name,
629    const char* output_file_name)
630{
631    /* platform-specific flags affecting optimization and verification */
632    char dexopt_flags[PROPERTY_VALUE_MAX];
633    property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");
634    ALOGV("dalvik.vm.dexopt-flags=%s\n", dexopt_flags);
635
636    static const char* DEX_OPT_BIN = "/system/bin/dexopt";
637    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
638    char zip_num[MAX_INT_LEN];
639    char odex_num[MAX_INT_LEN];
640
641    sprintf(zip_num, "%d", zip_fd);
642    sprintf(odex_num, "%d", odex_fd);
643
644    ALOGV("Running %s in=%s out=%s\n", DEX_OPT_BIN, input_file_name, output_file_name);
645    execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name,
646        dexopt_flags, (char*) NULL);
647    ALOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno));
648}
649
650static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
651    const char* output_file_name, const char *pkgname, const char *instruction_set)
652{
653    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
654    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
655
656    static const char* PATCHOAT_BIN = "/system/bin/patchoat";
657    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
658        ALOGE("Instruction set %s longer than max length of %d",
659              instruction_set, MAX_INSTRUCTION_SET_LEN);
660        return;
661    }
662
663    /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
664    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
665    char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
666    char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
667    const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
668    // The caller has already gotten all the locks we need.
669    const char* no_lock_arg = "--no-lock-output";
670    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
671    sprintf(output_oat_fd_arg, "--output-oat-fd=%d", oat_fd);
672    sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_fd);
673    ALOGE("Running %s isa=%s in-fd=%d (%s) out-fd=%d (%s)\n",
674          PATCHOAT_BIN, instruction_set, input_fd, input_file_name, oat_fd, output_file_name);
675
676    /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
677    char* argv[7];
678    argv[0] = (char*) PATCHOAT_BIN;
679    argv[1] = (char*) patched_image_location_arg;
680    argv[2] = (char*) no_lock_arg;
681    argv[3] = instruction_set_arg;
682    argv[4] = output_oat_fd_arg;
683    argv[5] = input_oat_fd_arg;
684    argv[6] = NULL;
685
686    execv(PATCHOAT_BIN, (char* const *)argv);
687    ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
688}
689
690static void run_dex2oat(int zip_fd, int oat_fd, const char* input_file_name,
691    const char* output_file_name, int swap_fd, const char *pkgname, const char *instruction_set,
692    bool vm_safe_mode)
693{
694    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
695
696    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
697        ALOGE("Instruction set %s longer than max length of %d",
698              instruction_set, MAX_INSTRUCTION_SET_LEN);
699        return;
700    }
701
702    char prop_buf[PROPERTY_VALUE_MAX];
703    bool profiler = (property_get("dalvik.vm.profiler", prop_buf, "0") > 0) && (prop_buf[0] == '1');
704
705    char dex2oat_Xms_flag[PROPERTY_VALUE_MAX];
706    bool have_dex2oat_Xms_flag = property_get("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
707
708    char dex2oat_Xmx_flag[PROPERTY_VALUE_MAX];
709    bool have_dex2oat_Xmx_flag = property_get("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
710
711    char dex2oat_compiler_filter_flag[PROPERTY_VALUE_MAX];
712    bool have_dex2oat_compiler_filter_flag = property_get("dalvik.vm.dex2oat-filter",
713                                                          dex2oat_compiler_filter_flag, NULL) > 0;
714
715    char dex2oat_isa_features_key[PROPERTY_KEY_MAX];
716    sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
717    char dex2oat_isa_features[PROPERTY_VALUE_MAX];
718    bool have_dex2oat_isa_features = property_get(dex2oat_isa_features_key,
719                                                  dex2oat_isa_features, NULL) > 0;
720
721    char dex2oat_flags[PROPERTY_VALUE_MAX];
722    bool have_dex2oat_flags = property_get("dalvik.vm.dex2oat-flags", dex2oat_flags, NULL) > 0;
723    ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
724
725    // If we booting without the real /data, don't spend time compiling.
726    char vold_decrypt[PROPERTY_VALUE_MAX];
727    bool have_vold_decrypt = property_get("vold.decrypt", vold_decrypt, "") > 0;
728    bool skip_compilation = (have_vold_decrypt &&
729                             (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
730                             (strcmp(vold_decrypt, "1") == 0)));
731
732    static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
733
734    static const char* RUNTIME_ARG = "--runtime-arg";
735
736    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
737
738    char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
739    char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
740    char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
741    char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
742    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
743    char instruction_set_features_arg[strlen("--instruction-set-features=") + PROPERTY_VALUE_MAX];
744    char profile_file_arg[strlen("--profile-file=") + PKG_PATH_MAX];
745    char top_k_profile_threshold_arg[strlen("--top-k-profile-threshold=") + PROPERTY_VALUE_MAX];
746    char dex2oat_Xms_arg[strlen("-Xms") + PROPERTY_VALUE_MAX];
747    char dex2oat_Xmx_arg[strlen("-Xmx") + PROPERTY_VALUE_MAX];
748    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + PROPERTY_VALUE_MAX];
749    bool have_dex2oat_swap_fd = false;
750    char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
751
752    sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
753    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
754    sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
755    sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
756    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
757    sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
758    if (swap_fd >= 0) {
759        have_dex2oat_swap_fd = true;
760        sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
761    }
762
763    bool have_profile_file = false;
764    bool have_top_k_profile_threshold = false;
765    if (profiler && (strcmp(pkgname, "*") != 0)) {
766        char profile_file[PKG_PATH_MAX];
767        snprintf(profile_file, sizeof(profile_file), "%s/%s",
768                 DALVIK_CACHE_PREFIX "profiles", pkgname);
769        struct stat st;
770        if ((stat(profile_file, &st) == 0) && (st.st_size > 0)) {
771            sprintf(profile_file_arg, "--profile-file=%s", profile_file);
772            have_profile_file = true;
773            if (property_get("dalvik.vm.profile.top-k-thr", prop_buf, NULL) > 0) {
774                snprintf(top_k_profile_threshold_arg, sizeof(top_k_profile_threshold_arg),
775                         "--top-k-profile-threshold=%s", prop_buf);
776                have_top_k_profile_threshold = true;
777            }
778        }
779    }
780
781    if (have_dex2oat_Xms_flag) {
782        sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
783    }
784    if (have_dex2oat_Xmx_flag) {
785        sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
786    }
787    if (skip_compilation) {
788        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
789        have_dex2oat_compiler_filter_flag = true;
790    } else if (vm_safe_mode) {
791        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
792        have_dex2oat_compiler_filter_flag = true;
793    } else if (have_dex2oat_compiler_filter_flag) {
794        sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", dex2oat_compiler_filter_flag);
795    }
796
797    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
798
799    char* argv[7  // program name, mandatory arguments and the final NULL
800               + (have_dex2oat_isa_features ? 1 : 0)
801               + (have_profile_file ? 1 : 0)
802               + (have_top_k_profile_threshold ? 1 : 0)
803               + (have_dex2oat_Xms_flag ? 2 : 0)
804               + (have_dex2oat_Xmx_flag ? 2 : 0)
805               + (have_dex2oat_compiler_filter_flag ? 1 : 0)
806               + (have_dex2oat_flags ? 1 : 0)
807               + (have_dex2oat_swap_fd ? 1 : 0)];
808    int i = 0;
809    argv[i++] = (char*)DEX2OAT_BIN;
810    argv[i++] = zip_fd_arg;
811    argv[i++] = zip_location_arg;
812    argv[i++] = oat_fd_arg;
813    argv[i++] = oat_location_arg;
814    argv[i++] = instruction_set_arg;
815    if (have_dex2oat_isa_features) {
816        argv[i++] = instruction_set_features_arg;
817    }
818    if (have_profile_file) {
819        argv[i++] = profile_file_arg;
820    }
821    if (have_top_k_profile_threshold) {
822        argv[i++] = top_k_profile_threshold_arg;
823    }
824    if (have_dex2oat_Xms_flag) {
825        argv[i++] = (char*)RUNTIME_ARG;
826        argv[i++] = dex2oat_Xms_arg;
827    }
828    if (have_dex2oat_Xmx_flag) {
829        argv[i++] = (char*)RUNTIME_ARG;
830        argv[i++] = dex2oat_Xmx_arg;
831    }
832    if (have_dex2oat_compiler_filter_flag) {
833        argv[i++] = dex2oat_compiler_filter_arg;
834    }
835    if (have_dex2oat_flags) {
836        argv[i++] = dex2oat_flags;
837    }
838    if (have_dex2oat_swap_fd) {
839        argv[i++] = dex2oat_swap_fd;
840    }
841    // Do not add after dex2oat_flags, they should override others for debugging.
842    argv[i] = NULL;
843
844    execv(DEX2OAT_BIN, (char* const *)argv);
845    ALOGE("execl(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
846}
847
848static int wait_child(pid_t pid)
849{
850    int status;
851    pid_t got_pid;
852
853    while (1) {
854        got_pid = waitpid(pid, &status, 0);
855        if (got_pid == -1 && errno == EINTR) {
856            printf("waitpid interrupted, retrying\n");
857        } else {
858            break;
859        }
860    }
861    if (got_pid != pid) {
862        ALOGW("waitpid failed: wanted %d, got %d: %s\n",
863            (int) pid, (int) got_pid, strerror(errno));
864        return 1;
865    }
866
867    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
868        return 0;
869    } else {
870        return status;      /* always nonzero */
871    }
872}
873
874/*
875 * Whether dexopt should use a swap file when compiling an APK. If kAlwaysProvideSwapFile, do this
876 * on all devices (dex2oat will make a more informed decision itself, anyways). Otherwise, only do
877 * this on a low-mem device.
878 */
879static bool kAlwaysProvideSwapFile = true;
880
881static bool ShouldUseSwapFileForDexopt() {
882    if (kAlwaysProvideSwapFile) {
883        return true;
884    }
885
886    char low_mem_buf[PROPERTY_VALUE_MAX];
887    property_get("ro.config.low_ram", low_mem_buf, "");
888    return (strcmp(low_mem_buf, "true") == 0);
889}
890
891int dexopt(const char *apk_path, uid_t uid, bool is_public,
892           const char *pkgname, const char *instruction_set,
893           bool vm_safe_mode, bool is_patchoat)
894{
895    struct utimbuf ut;
896    struct stat input_stat, dex_stat;
897    char out_path[PKG_PATH_MAX];
898    char persist_sys_dalvik_vm_lib[PROPERTY_VALUE_MAX];
899    char swap_file_name[PKG_PATH_MAX];
900    char *end;
901    const char *input_file;
902    char in_odex_path[PKG_PATH_MAX];
903    int res, input_fd=-1, out_fd=-1, swap_fd=-1;
904
905    // Early best-effort check whether we can fit the the path into our buffers.
906    // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
907    // without a swap file, if necessary.
908    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
909        return -1;
910    }
911
912    /* The command to run depend on the value of persist.sys.dalvik.vm.lib */
913    property_get("persist.sys.dalvik.vm.lib.2", persist_sys_dalvik_vm_lib, "libart.so");
914
915    if (is_patchoat && strncmp(persist_sys_dalvik_vm_lib, "libart", 6) != 0) {
916        /* We may only patch if we are libart */
917        ALOGE("Patching is only supported in libart\n");
918        return -1;
919    }
920
921    /* Before anything else: is there a .odex file?  If so, we have
922     * precompiled the apk and there is nothing to do here.
923     *
924     * We skip this if we are doing a patchoat.
925     */
926    strcpy(out_path, apk_path);
927    end = strrchr(out_path, '.');
928    if (end != NULL && !is_patchoat) {
929        strcpy(end, ".odex");
930        if (stat(out_path, &dex_stat) == 0) {
931            return 0;
932        }
933    }
934
935    if (create_cache_path(out_path, apk_path, instruction_set)) {
936        return -1;
937    }
938
939    if (is_patchoat) {
940        /* /system/framework/whatever.jar -> /system/framework/<isa>/whatever.odex */
941        strcpy(in_odex_path, apk_path);
942        end = strrchr(in_odex_path, '/');
943        if (end == NULL) {
944            ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
945            return -1;
946        }
947        const char *apk_end = apk_path + (end - in_odex_path); // strrchr(apk_path, '/');
948        strcpy(end + 1, instruction_set); // in_odex_path now is /system/framework/<isa>\0
949        strcat(in_odex_path, apk_end);
950        end = strrchr(in_odex_path, '.');
951        if (end == NULL) {
952            return -1;
953        }
954        strcpy(end + 1, "odex");
955        input_file = in_odex_path;
956    } else {
957        input_file = apk_path;
958    }
959
960    memset(&input_stat, 0, sizeof(input_stat));
961    stat(input_file, &input_stat);
962
963    input_fd = open(input_file, O_RDONLY, 0);
964    if (input_fd < 0) {
965        ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
966        return -1;
967    }
968
969    unlink(out_path);
970    out_fd = open(out_path, O_RDWR | O_CREAT | O_EXCL, 0644);
971    if (out_fd < 0) {
972        ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
973        goto fail;
974    }
975    if (fchmod(out_fd,
976               S_IRUSR|S_IWUSR|S_IRGRP |
977               (is_public ? S_IROTH : 0)) < 0) {
978        ALOGE("installd cannot chmod '%s' during dexopt\n", out_path);
979        goto fail;
980    }
981    if (fchown(out_fd, AID_SYSTEM, uid) < 0) {
982        ALOGE("installd cannot chown '%s' during dexopt\n", out_path);
983        goto fail;
984    }
985
986    // Create profile file if there is a package name present.
987    if (strcmp(pkgname, "*") != 0) {
988        create_profile_file(pkgname, uid);
989    }
990
991    // Create a swap file if necessary.
992    if (!is_patchoat && ShouldUseSwapFileForDexopt()) {
993        // Make sure there really is enough space.
994        size_t out_len = strlen(out_path);
995        if (out_len + strlen(".swap") + 1 <= PKG_PATH_MAX) {
996            strcpy(swap_file_name, out_path);
997            strcpy(swap_file_name + strlen(out_path), ".swap");
998            unlink(swap_file_name);
999            swap_fd = open(swap_file_name, O_RDWR | O_CREAT | O_EXCL, 0600);
1000            if (swap_fd < 0) {
1001                // Could not create swap file. Optimistically go on and hope that we can compile
1002                // without it.
1003                ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1004            } else {
1005                // Immediately unlink. We don't really want to hit flash.
1006                unlink(swap_file_name);
1007            }
1008        } else {
1009            // Swap file path is too long. Try to run without.
1010            ALOGE("installd could not create swap file for path %s during dexopt\n", out_path);
1011        }
1012    }
1013
1014    ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
1015
1016    pid_t pid;
1017    pid = fork();
1018    if (pid == 0) {
1019        /* child -- drop privileges before continuing */
1020        if (setgid(uid) != 0) {
1021            ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1022            exit(64);
1023        }
1024        if (setuid(uid) != 0) {
1025            ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1026            exit(65);
1027        }
1028        // drop capabilities
1029        struct __user_cap_header_struct capheader;
1030        struct __user_cap_data_struct capdata[2];
1031        memset(&capheader, 0, sizeof(capheader));
1032        memset(&capdata, 0, sizeof(capdata));
1033        capheader.version = _LINUX_CAPABILITY_VERSION_3;
1034        if (capset(&capheader, &capdata[0]) < 0) {
1035            ALOGE("capset failed: %s\n", strerror(errno));
1036            exit(66);
1037        }
1038        if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1039            ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1040            exit(70);
1041        }
1042        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1043            ALOGE("setpriority failed: %s\n", strerror(errno));
1044            exit(71);
1045        }
1046        if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
1047            ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
1048            exit(67);
1049        }
1050
1051        if (strncmp(persist_sys_dalvik_vm_lib, "libdvm", 6) == 0) {
1052            run_dexopt(input_fd, out_fd, input_file, out_path);
1053        } else if (strncmp(persist_sys_dalvik_vm_lib, "libart", 6) == 0) {
1054            if (is_patchoat) {
1055                run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
1056            } else {
1057                run_dex2oat(input_fd, out_fd, input_file, out_path, swap_fd, pkgname,
1058                            instruction_set, vm_safe_mode);
1059            }
1060        } else {
1061            exit(69);   /* Unexpected persist.sys.dalvik.vm.lib value */
1062        }
1063        exit(68);   /* only get here on exec failure */
1064    } else {
1065        res = wait_child(pid);
1066        if (res == 0) {
1067            ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
1068        } else {
1069            ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
1070            goto fail;
1071        }
1072    }
1073
1074    ut.actime = input_stat.st_atime;
1075    ut.modtime = input_stat.st_mtime;
1076    utime(out_path, &ut);
1077
1078    close(out_fd);
1079    close(input_fd);
1080    if (swap_fd != -1) {
1081        close(swap_fd);
1082    }
1083    return 0;
1084
1085fail:
1086    if (out_fd >= 0) {
1087        close(out_fd);
1088        unlink(out_path);
1089    }
1090    if (input_fd >= 0) {
1091        close(input_fd);
1092    }
1093    return -1;
1094}
1095
1096int mark_boot_complete(const char* instruction_set)
1097{
1098  char boot_marker_path[PKG_PATH_MAX];
1099  sprintf(boot_marker_path,"%s%s/.booting", DALVIK_CACHE_PREFIX, instruction_set);
1100
1101  ALOGV("mark_boot_complete : %s", boot_marker_path);
1102  if (unlink(boot_marker_path) != 0) {
1103      ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
1104            strerror(errno));
1105      return -1;
1106  }
1107
1108  return 0;
1109}
1110
1111void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1112        struct stat* statbuf)
1113{
1114    while (path[basepos] != 0) {
1115        if (path[basepos] == '/') {
1116            path[basepos] = 0;
1117            if (lstat(path, statbuf) < 0) {
1118                ALOGV("Making directory: %s\n", path);
1119                if (mkdir(path, mode) == 0) {
1120                    chown(path, uid, gid);
1121                } else {
1122                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1123                }
1124            }
1125            path[basepos] = '/';
1126            basepos++;
1127        }
1128        basepos++;
1129    }
1130}
1131
1132int movefileordir(char* srcpath, char* dstpath, int dstbasepos,
1133        int dstuid, int dstgid, struct stat* statbuf)
1134{
1135    DIR *d;
1136    struct dirent *de;
1137    int res;
1138
1139    int srcend = strlen(srcpath);
1140    int dstend = strlen(dstpath);
1141
1142    if (lstat(srcpath, statbuf) < 0) {
1143        ALOGW("Unable to stat %s: %s\n", srcpath, strerror(errno));
1144        return 1;
1145    }
1146
1147    if ((statbuf->st_mode&S_IFDIR) == 0) {
1148        mkinnerdirs(dstpath, dstbasepos, S_IRWXU|S_IRWXG|S_IXOTH,
1149                dstuid, dstgid, statbuf);
1150        ALOGV("Renaming %s to %s (uid %d)\n", srcpath, dstpath, dstuid);
1151        if (rename(srcpath, dstpath) >= 0) {
1152            if (chown(dstpath, dstuid, dstgid) < 0) {
1153                ALOGE("cannot chown %s: %s\n", dstpath, strerror(errno));
1154                unlink(dstpath);
1155                return 1;
1156            }
1157        } else {
1158            ALOGW("Unable to rename %s to %s: %s\n",
1159                srcpath, dstpath, strerror(errno));
1160            return 1;
1161        }
1162        return 0;
1163    }
1164
1165    d = opendir(srcpath);
1166    if (d == NULL) {
1167        ALOGW("Unable to opendir %s: %s\n", srcpath, strerror(errno));
1168        return 1;
1169    }
1170
1171    res = 0;
1172
1173    while ((de = readdir(d))) {
1174        const char *name = de->d_name;
1175            /* always skip "." and ".." */
1176        if (name[0] == '.') {
1177            if (name[1] == 0) continue;
1178            if ((name[1] == '.') && (name[2] == 0)) continue;
1179        }
1180
1181        if ((srcend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1182            ALOGW("Source path too long; skipping: %s/%s\n", srcpath, name);
1183            continue;
1184        }
1185
1186        if ((dstend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1187            ALOGW("Destination path too long; skipping: %s/%s\n", dstpath, name);
1188            continue;
1189        }
1190
1191        srcpath[srcend] = dstpath[dstend] = '/';
1192        strcpy(srcpath+srcend+1, name);
1193        strcpy(dstpath+dstend+1, name);
1194
1195        if (movefileordir(srcpath, dstpath, dstbasepos, dstuid, dstgid, statbuf) != 0) {
1196            res = 1;
1197        }
1198
1199        // Note: we will be leaving empty directories behind in srcpath,
1200        // but that is okay, the package manager will be erasing all of the
1201        // data associated with .apks that disappear.
1202
1203        srcpath[srcend] = dstpath[dstend] = 0;
1204    }
1205
1206    closedir(d);
1207    return res;
1208}
1209
1210int movefiles()
1211{
1212    DIR *d;
1213    int dfd, subfd;
1214    struct dirent *de;
1215    struct stat s;
1216    char buf[PKG_PATH_MAX+1];
1217    int bufp, bufe, bufi, readlen;
1218
1219    char srcpkg[PKG_NAME_MAX];
1220    char dstpkg[PKG_NAME_MAX];
1221    char srcpath[PKG_PATH_MAX];
1222    char dstpath[PKG_PATH_MAX];
1223    int dstuid=-1, dstgid=-1;
1224    int hasspace;
1225
1226    d = opendir(UPDATE_COMMANDS_DIR_PREFIX);
1227    if (d == NULL) {
1228        goto done;
1229    }
1230    dfd = dirfd(d);
1231
1232        /* Iterate through all files in the directory, executing the
1233         * file movements requested there-in.
1234         */
1235    while ((de = readdir(d))) {
1236        const char *name = de->d_name;
1237
1238        if (de->d_type == DT_DIR) {
1239            continue;
1240        } else {
1241            subfd = openat(dfd, name, O_RDONLY);
1242            if (subfd < 0) {
1243                ALOGW("Unable to open update commands at %s%s\n",
1244                        UPDATE_COMMANDS_DIR_PREFIX, name);
1245                continue;
1246            }
1247
1248            bufp = 0;
1249            bufe = 0;
1250            buf[PKG_PATH_MAX] = 0;
1251            srcpkg[0] = dstpkg[0] = 0;
1252            while (1) {
1253                bufi = bufp;
1254                while (bufi < bufe && buf[bufi] != '\n') {
1255                    bufi++;
1256                }
1257                if (bufi < bufe) {
1258                    buf[bufi] = 0;
1259                    ALOGV("Processing line: %s\n", buf+bufp);
1260                    hasspace = 0;
1261                    while (bufp < bufi && isspace(buf[bufp])) {
1262                        hasspace = 1;
1263                        bufp++;
1264                    }
1265                    if (buf[bufp] == '#' || bufp == bufi) {
1266                        // skip comments and empty lines.
1267                    } else if (hasspace) {
1268                        if (dstpkg[0] == 0) {
1269                            ALOGW("Path before package line in %s%s: %s\n",
1270                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1271                        } else if (srcpkg[0] == 0) {
1272                            // Skip -- source package no longer exists.
1273                        } else {
1274                            ALOGV("Move file: %s (from %s to %s)\n", buf+bufp, srcpkg, dstpkg);
1275                            if (!create_move_path(srcpath, srcpkg, buf+bufp, 0) &&
1276                                    !create_move_path(dstpath, dstpkg, buf+bufp, 0)) {
1277                                movefileordir(srcpath, dstpath,
1278                                        strlen(dstpath)-strlen(buf+bufp),
1279                                        dstuid, dstgid, &s);
1280                            }
1281                        }
1282                    } else {
1283                        char* div = strchr(buf+bufp, ':');
1284                        if (div == NULL) {
1285                            ALOGW("Bad package spec in %s%s; no ':' sep: %s\n",
1286                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1287                        } else {
1288                            *div = 0;
1289                            div++;
1290                            if (strlen(buf+bufp) < PKG_NAME_MAX) {
1291                                strcpy(dstpkg, buf+bufp);
1292                            } else {
1293                                srcpkg[0] = dstpkg[0] = 0;
1294                                ALOGW("Package name too long in %s%s: %s\n",
1295                                        UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1296                            }
1297                            if (strlen(div) < PKG_NAME_MAX) {
1298                                strcpy(srcpkg, div);
1299                            } else {
1300                                srcpkg[0] = dstpkg[0] = 0;
1301                                ALOGW("Package name too long in %s%s: %s\n",
1302                                        UPDATE_COMMANDS_DIR_PREFIX, name, div);
1303                            }
1304                            if (srcpkg[0] != 0) {
1305                                if (!create_pkg_path(srcpath, srcpkg, PKG_DIR_POSTFIX, 0)) {
1306                                    if (lstat(srcpath, &s) < 0) {
1307                                        // Package no longer exists -- skip.
1308                                        srcpkg[0] = 0;
1309                                    }
1310                                } else {
1311                                    srcpkg[0] = 0;
1312                                    ALOGW("Can't create path %s in %s%s\n",
1313                                            div, UPDATE_COMMANDS_DIR_PREFIX, name);
1314                                }
1315                                if (srcpkg[0] != 0) {
1316                                    if (!create_pkg_path(dstpath, dstpkg, PKG_DIR_POSTFIX, 0)) {
1317                                        if (lstat(dstpath, &s) == 0) {
1318                                            dstuid = s.st_uid;
1319                                            dstgid = s.st_gid;
1320                                        } else {
1321                                            // Destination package doesn't
1322                                            // exist...  due to original-package,
1323                                            // this is normal, so don't be
1324                                            // noisy about it.
1325                                            srcpkg[0] = 0;
1326                                        }
1327                                    } else {
1328                                        srcpkg[0] = 0;
1329                                        ALOGW("Can't create path %s in %s%s\n",
1330                                                div, UPDATE_COMMANDS_DIR_PREFIX, name);
1331                                    }
1332                                }
1333                                ALOGV("Transfering from %s to %s: uid=%d\n",
1334                                    srcpkg, dstpkg, dstuid);
1335                            }
1336                        }
1337                    }
1338                    bufp = bufi+1;
1339                } else {
1340                    if (bufp == 0) {
1341                        if (bufp < bufe) {
1342                            ALOGW("Line too long in %s%s, skipping: %s\n",
1343                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf);
1344                        }
1345                    } else if (bufp < bufe) {
1346                        memcpy(buf, buf+bufp, bufe-bufp);
1347                        bufe -= bufp;
1348                        bufp = 0;
1349                    }
1350                    readlen = read(subfd, buf+bufe, PKG_PATH_MAX-bufe);
1351                    if (readlen < 0) {
1352                        ALOGW("Failure reading update commands in %s%s: %s\n",
1353                                UPDATE_COMMANDS_DIR_PREFIX, name, strerror(errno));
1354                        break;
1355                    } else if (readlen == 0) {
1356                        break;
1357                    }
1358                    bufe += readlen;
1359                    buf[bufe] = 0;
1360                    ALOGV("Read buf: %s\n", buf);
1361                }
1362            }
1363            close(subfd);
1364        }
1365    }
1366    closedir(d);
1367done:
1368    return 0;
1369}
1370
1371int linklib(const char* pkgname, const char* asecLibDir, int userId)
1372{
1373    char pkgdir[PKG_PATH_MAX];
1374    char libsymlink[PKG_PATH_MAX];
1375    struct stat s, libStat;
1376    int rc = 0;
1377
1378    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userId)) {
1379        ALOGE("cannot create package path\n");
1380        return -1;
1381    }
1382    if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, userId)) {
1383        ALOGE("cannot create package lib symlink origin path\n");
1384        return -1;
1385    }
1386
1387    if (stat(pkgdir, &s) < 0) return -1;
1388
1389    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1390        ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1391        return -1;
1392    }
1393
1394    if (chmod(pkgdir, 0700) < 0) {
1395        ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1396        rc = -1;
1397        goto out;
1398    }
1399
1400    if (lstat(libsymlink, &libStat) < 0) {
1401        if (errno != ENOENT) {
1402            ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1403            rc = -1;
1404            goto out;
1405        }
1406    } else {
1407        if (S_ISDIR(libStat.st_mode)) {
1408            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1409                rc = -1;
1410                goto out;
1411            }
1412        } else if (S_ISLNK(libStat.st_mode)) {
1413            if (unlink(libsymlink) < 0) {
1414                ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1415                rc = -1;
1416                goto out;
1417            }
1418        }
1419    }
1420
1421    if (symlink(asecLibDir, libsymlink) < 0) {
1422        ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1423                strerror(errno));
1424        rc = -errno;
1425        goto out;
1426    }
1427
1428out:
1429    if (chmod(pkgdir, s.st_mode) < 0) {
1430        ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1431        rc = -errno;
1432    }
1433
1434    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1435        ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1436        return -errno;
1437    }
1438
1439    return rc;
1440}
1441
1442static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1443{
1444    static const char *IDMAP_BIN = "/system/bin/idmap";
1445    static const size_t MAX_INT_LEN = 32;
1446    char idmap_str[MAX_INT_LEN];
1447
1448    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1449
1450    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1451    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1452}
1453
1454// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1455// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1456static int flatten_path(const char *prefix, const char *suffix,
1457        const char *overlay_path, char *idmap_path, size_t N)
1458{
1459    if (overlay_path == NULL || idmap_path == NULL) {
1460        return -1;
1461    }
1462    const size_t len_overlay_path = strlen(overlay_path);
1463    // will access overlay_path + 1 further below; requires absolute path
1464    if (len_overlay_path < 2 || *overlay_path != '/') {
1465        return -1;
1466    }
1467    const size_t len_idmap_root = strlen(prefix);
1468    const size_t len_suffix = strlen(suffix);
1469    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1470            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1471        // additions below would cause overflow
1472        return -1;
1473    }
1474    if (N < len_idmap_root + len_overlay_path + len_suffix) {
1475        return -1;
1476    }
1477    memset(idmap_path, 0, N);
1478    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1479    char *ch = idmap_path + len_idmap_root;
1480    while (*ch != '\0') {
1481        if (*ch == '/') {
1482            *ch = '@';
1483        }
1484        ++ch;
1485    }
1486    return 0;
1487}
1488
1489int idmap(const char *target_apk, const char *overlay_apk, uid_t uid)
1490{
1491    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1492
1493    int idmap_fd = -1;
1494    char idmap_path[PATH_MAX];
1495
1496    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1497                idmap_path, sizeof(idmap_path)) == -1) {
1498        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1499        goto fail;
1500    }
1501
1502    unlink(idmap_path);
1503    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1504    if (idmap_fd < 0) {
1505        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1506        goto fail;
1507    }
1508    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1509        ALOGE("idmap cannot chown '%s'\n", idmap_path);
1510        goto fail;
1511    }
1512    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1513        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1514        goto fail;
1515    }
1516
1517    pid_t pid;
1518    pid = fork();
1519    if (pid == 0) {
1520        /* child -- drop privileges before continuing */
1521        if (setgid(uid) != 0) {
1522            ALOGE("setgid(%d) failed during idmap\n", uid);
1523            exit(1);
1524        }
1525        if (setuid(uid) != 0) {
1526            ALOGE("setuid(%d) failed during idmap\n", uid);
1527            exit(1);
1528        }
1529        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1530            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1531            exit(1);
1532        }
1533
1534        run_idmap(target_apk, overlay_apk, idmap_fd);
1535        exit(1); /* only if exec call to idmap failed */
1536    } else {
1537        int status = wait_child(pid);
1538        if (status != 0) {
1539            ALOGE("idmap failed, status=0x%04x\n", status);
1540            goto fail;
1541        }
1542    }
1543
1544    close(idmap_fd);
1545    return 0;
1546fail:
1547    if (idmap_fd >= 0) {
1548        close(idmap_fd);
1549        unlink(idmap_path);
1550    }
1551    return -1;
1552}
1553
1554int restorecon_data(const char* pkgName, const char* seinfo, uid_t uid)
1555{
1556    struct dirent *entry;
1557    DIR *d;
1558    struct stat s;
1559    char *userdir;
1560    char *primarydir;
1561    char *pkgdir;
1562    int ret = 0;
1563
1564    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1565    unsigned int flags = SELINUX_ANDROID_RESTORECON_RECURSE;
1566
1567    if (!pkgName || !seinfo) {
1568        ALOGE("Package name or seinfo tag is null when trying to restorecon.");
1569        return -1;
1570    }
1571
1572    if (asprintf(&primarydir, "%s%s%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgName) < 0) {
1573        return -1;
1574    }
1575
1576    // Relabel for primary user.
1577    if (selinux_android_restorecon_pkgdir(primarydir, seinfo, uid, flags) < 0) {
1578        ALOGE("restorecon failed for %s: %s\n", primarydir, strerror(errno));
1579        ret |= -1;
1580    }
1581
1582    if (asprintf(&userdir, "%s%s", android_data_dir.path, SECONDARY_USER_PREFIX) < 0) {
1583        free(primarydir);
1584        return -1;
1585    }
1586
1587    // Relabel package directory for all secondary users.
1588    d = opendir(userdir);
1589    if (d == NULL) {
1590        free(primarydir);
1591        free(userdir);
1592        return -1;
1593    }
1594
1595    while ((entry = readdir(d))) {
1596        if (entry->d_type != DT_DIR) {
1597            continue;
1598        }
1599
1600        const char *user = entry->d_name;
1601        // Ignore "." and ".."
1602        if (!strcmp(user, ".") || !strcmp(user, "..")) {
1603            continue;
1604        }
1605
1606        // user directories start with a number
1607        if (user[0] < '0' || user[0] > '9') {
1608            ALOGE("Expecting numbered directory during restorecon. Instead got '%s'.", user);
1609            continue;
1610        }
1611
1612        if (asprintf(&pkgdir, "%s%s/%s", userdir, user, pkgName) < 0) {
1613            continue;
1614        }
1615
1616        if (stat(pkgdir, &s) < 0) {
1617            free(pkgdir);
1618            continue;
1619        }
1620
1621        if (selinux_android_restorecon_pkgdir(pkgdir, seinfo, uid, flags) < 0) {
1622            ALOGE("restorecon failed for %s: %s\n", pkgdir, strerror(errno));
1623            ret |= -1;
1624        }
1625        free(pkgdir);
1626    }
1627
1628    closedir(d);
1629    free(primarydir);
1630    free(userdir);
1631    return ret;
1632}
1633
1634