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 "commands.h"
18
19#include <errno.h>
20#include <inttypes.h>
21#include <stdlib.h>
22#include <sys/capability.h>
23#include <sys/file.h>
24#include <sys/resource.h>
25#include <sys/stat.h>
26#include <sys/types.h>
27#include <sys/wait.h>
28#include <sys/xattr.h>
29#include <unistd.h>
30
31#include <android-base/stringprintf.h>
32#include <android-base/strings.h>
33#include <android-base/logging.h>
34#include <android-base/unique_fd.h>
35#include <cutils/fs.h>
36#include <cutils/log.h>               // TODO: Move everything to base/logging.
37#include <cutils/sched_policy.h>
38#include <diskusage/dirsize.h>
39#include <logwrap/logwrap.h>
40#include <private/android_filesystem_config.h>
41#include <selinux/android.h>
42#include <system/thread_defs.h>
43
44#include <globals.h>
45#include <installd_deps.h>
46#include <utils.h>
47
48#ifndef LOG_TAG
49#define LOG_TAG "installd"
50#endif
51
52using android::base::StringPrintf;
53
54namespace android {
55namespace installd {
56
57static constexpr const char* kCpPath = "/system/bin/cp";
58static constexpr const char* kXattrDefault = "user.default";
59
60#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
61
62typedef int fd_t;
63
64static bool property_get_bool(const char* property_name, bool default_value = false) {
65    char tmp_property_value[kPropertyValueMax];
66    bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
67    if (!have_property) {
68        return default_value;
69    }
70    return strcmp(tmp_property_value, "true") == 0;
71}
72
73// Keep profile paths in sync with ActivityThread.
74constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
75static std::string create_primary_profile(const std::string& profile_dir) {
76    return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
77}
78
79int create_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
80        appid_t appid, const char* seinfo, int target_sdk_version) {
81    uid_t uid = multiuser_get_uid(userid, appid);
82    int target_mode = target_sdk_version >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
83    if (flags & FLAG_STORAGE_CE) {
84        auto path = create_data_user_ce_package_path(uuid, userid, pkgname);
85        if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
86            PLOG(ERROR) << "Failed to prepare " << path;
87            return -1;
88        }
89        if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
90            PLOG(ERROR) << "Failed to setfilecon " << path;
91            return -1;
92        }
93    }
94    if (flags & FLAG_STORAGE_DE) {
95        auto path = create_data_user_de_package_path(uuid, userid, pkgname);
96        if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) == -1) {
97            PLOG(ERROR) << "Failed to prepare " << path;
98            // TODO: include result once 25796509 is fixed
99            return 0;
100        }
101        if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
102            PLOG(ERROR) << "Failed to setfilecon " << path;
103            // TODO: include result once 25796509 is fixed
104            return 0;
105        }
106
107        if (property_get_bool("dalvik.vm.usejitprofiles")) {
108            const std::string profile_path = create_data_user_profile_package_path(userid, pkgname);
109            // read-write-execute only for the app user.
110            if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
111                PLOG(ERROR) << "Failed to prepare " << profile_path;
112                return -1;
113            }
114            std::string profile_file = create_primary_profile(profile_path);
115            // read-write only for the app user.
116            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
117                PLOG(ERROR) << "Failed to prepare " << profile_path;
118                return -1;
119            }
120            const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
121            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
122            // profiles.
123            appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
124            if (fs_prepare_dir_strict(
125                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
126                PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
127                return -1;
128            }
129        }
130    }
131    return 0;
132}
133
134int migrate_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
135    // This method only exists to upgrade system apps that have requested
136    // forceDeviceEncrypted, so their default storage always lives in a
137    // consistent location.  This only works on non-FBE devices, since we
138    // never want to risk exposing data on a device with real CE/DE storage.
139
140    auto ce_path = create_data_user_ce_package_path(uuid, userid, pkgname);
141    auto de_path = create_data_user_de_package_path(uuid, userid, pkgname);
142
143    // If neither directory is marked as default, assume CE is default
144    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
145            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
146        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
147            PLOG(ERROR) << "Failed to mark default storage " << ce_path;
148            return -1;
149        }
150    }
151
152    // Migrate default data location if needed
153    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
154    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
155
156    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
157        LOG(WARNING) << "Requested default storage " << target
158                << " is not active; migrating from " << source;
159        if (delete_dir_contents_and_dir(target) != 0) {
160            PLOG(ERROR) << "Failed to delete";
161            return -1;
162        }
163        if (rename(source.c_str(), target.c_str()) != 0) {
164            PLOG(ERROR) << "Failed to rename";
165            return -1;
166        }
167    }
168
169    return 0;
170}
171
172static bool clear_profile(const std::string& profile) {
173    base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
174    if (ufd.get() < 0) {
175        if (errno != ENOENT) {
176            PLOG(WARNING) << "Could not open profile " << profile;
177            return false;
178        } else {
179            // Nothing to clear. That's ok.
180            return true;
181        }
182    }
183
184    if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
185        if (errno != EWOULDBLOCK) {
186            PLOG(WARNING) << "Error locking profile " << profile;
187        }
188        // This implies that the app owning this profile is running
189        // (and has acquired the lock).
190        //
191        // If we can't acquire the lock bail out since clearing is useless anyway
192        // (the app will write again to the profile).
193        //
194        // Note:
195        // This does not impact the this is not an issue for the profiling correctness.
196        // In case this is needed because of an app upgrade, profiles will still be
197        // eventually cleared by the app itself due to checksum mismatch.
198        // If this is needed because profman advised, then keeping the data around
199        // until the next run is again not an issue.
200        //
201        // If the app attempts to acquire a lock while we've held one here,
202        // it will simply skip the current write cycle.
203        return false;
204    }
205
206    bool truncated = ftruncate(ufd.get(), 0) == 0;
207    if (!truncated) {
208        PLOG(WARNING) << "Could not truncate " << profile;
209    }
210    if (flock(ufd.get(), LOCK_UN) != 0) {
211        PLOG(WARNING) << "Error unlocking profile " << profile;
212    }
213    return truncated;
214}
215
216static bool clear_reference_profile(const char* pkgname) {
217    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
218    std::string reference_profile = create_primary_profile(reference_profile_dir);
219    return clear_profile(reference_profile);
220}
221
222static bool clear_current_profile(const char* pkgname, userid_t user) {
223    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
224    std::string profile = create_primary_profile(profile_dir);
225    return clear_profile(profile);
226}
227
228static bool clear_current_profiles(const char* pkgname) {
229    bool success = true;
230    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
231    for (auto user : users) {
232        success &= clear_current_profile(pkgname, user);
233    }
234    return success;
235}
236
237int clear_app_profiles(const char* pkgname) {
238    bool success = true;
239    success &= clear_reference_profile(pkgname);
240    success &= clear_current_profiles(pkgname);
241    return success ? 0 : -1;
242}
243
244int clear_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
245        ino_t ce_data_inode) {
246    std::string suffix = "";
247    bool only_cache = false;
248    if (flags & FLAG_CLEAR_CACHE_ONLY) {
249        suffix = CACHE_DIR_POSTFIX;
250        only_cache = true;
251    } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
252        suffix = CODE_CACHE_DIR_POSTFIX;
253        only_cache = true;
254    }
255
256    int res = 0;
257    if (flags & FLAG_STORAGE_CE) {
258        auto path = create_data_user_ce_package_path(uuid, userid, pkgname, ce_data_inode) + suffix;
259        if (access(path.c_str(), F_OK) == 0) {
260            res |= delete_dir_contents(path);
261        }
262    }
263    if (flags & FLAG_STORAGE_DE) {
264        auto path = create_data_user_de_package_path(uuid, userid, pkgname) + suffix;
265        if (access(path.c_str(), F_OK) == 0) {
266            // TODO: include result once 25796509 is fixed
267            delete_dir_contents(path);
268        }
269        if (!only_cache) {
270            if (!clear_current_profile(pkgname, userid)) {
271                res |= -1;
272            }
273        }
274    }
275    return res;
276}
277
278static int destroy_app_reference_profile(const char *pkgname) {
279    return delete_dir_contents_and_dir(
280        create_data_ref_profile_package_path(pkgname),
281        /*ignore_if_missing*/ true);
282}
283
284static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
285    return delete_dir_contents_and_dir(
286        create_data_user_profile_package_path(userid, pkgname),
287        /*ignore_if_missing*/ true);
288}
289
290int destroy_app_profiles(const char *pkgname) {
291    int result = 0;
292    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
293    for (auto user : users) {
294        result |= destroy_app_current_profiles(pkgname, user);
295    }
296    result |= destroy_app_reference_profile(pkgname);
297    return result;
298}
299
300int destroy_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
301        ino_t ce_data_inode) {
302    int res = 0;
303    if (flags & FLAG_STORAGE_CE) {
304        res |= delete_dir_contents_and_dir(
305                create_data_user_ce_package_path(uuid, userid, pkgname, ce_data_inode));
306    }
307    if (flags & FLAG_STORAGE_DE) {
308        res |= delete_dir_contents_and_dir(
309                create_data_user_de_package_path(uuid, userid, pkgname));
310        destroy_app_current_profiles(pkgname, userid);
311        // TODO(calin): If the package is still installed by other users it's probably
312        // beneficial to keep the reference profile around.
313        // Verify if it's ok to do that.
314        destroy_app_reference_profile(pkgname);
315    }
316    return res;
317}
318
319int move_complete_app(const char *from_uuid, const char *to_uuid, const char *package_name,
320        const char *data_app_name, appid_t appid, const char* seinfo, int target_sdk_version) {
321    std::vector<userid_t> users = get_known_users(from_uuid);
322
323    // Copy app
324    {
325        auto from = create_data_app_package_path(from_uuid, data_app_name);
326        auto to = create_data_app_package_path(to_uuid, data_app_name);
327        auto to_parent = create_data_app_path(to_uuid);
328
329        char *argv[] = {
330            (char*) kCpPath,
331            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
332            (char*) "-p", /* preserve timestamps, ownership, and permissions */
333            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
334            (char*) "-P", /* Do not follow symlinks [default] */
335            (char*) "-d", /* don't dereference symlinks */
336            (char*) from.c_str(),
337            (char*) to_parent.c_str()
338        };
339
340        LOG(DEBUG) << "Copying " << from << " to " << to;
341        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
342
343        if (rc != 0) {
344            LOG(ERROR) << "Failed copying " << from << " to " << to
345                    << ": status " << rc;
346            goto fail;
347        }
348
349        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
350            LOG(ERROR) << "Failed to restorecon " << to;
351            goto fail;
352        }
353    }
354
355    // Copy private data for all known users
356    for (auto user : users) {
357
358        // Data source may not exist for all users; that's okay
359        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
360        if (access(from_ce.c_str(), F_OK) != 0) {
361            LOG(INFO) << "Missing source " << from_ce;
362            continue;
363        }
364
365        if (create_app_data(to_uuid, package_name, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
366                appid, seinfo, target_sdk_version) != 0) {
367            LOG(ERROR) << "Failed to create package target on " << to_uuid;
368            goto fail;
369        }
370
371        char *argv[] = {
372            (char*) kCpPath,
373            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
374            (char*) "-p", /* preserve timestamps, ownership, and permissions */
375            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
376            (char*) "-P", /* Do not follow symlinks [default] */
377            (char*) "-d", /* don't dereference symlinks */
378            nullptr,
379            nullptr
380        };
381
382        {
383            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
384            auto to = create_data_user_de_path(to_uuid, user);
385            argv[6] = (char*) from.c_str();
386            argv[7] = (char*) to.c_str();
387
388            LOG(DEBUG) << "Copying " << from << " to " << to;
389            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
390            if (rc != 0) {
391                LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
392                goto fail;
393            }
394        }
395        {
396            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
397            auto to = create_data_user_ce_path(to_uuid, user);
398            argv[6] = (char*) from.c_str();
399            argv[7] = (char*) to.c_str();
400
401            LOG(DEBUG) << "Copying " << from << " to " << to;
402            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
403            if (rc != 0) {
404                LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
405                goto fail;
406            }
407        }
408
409        if (restorecon_app_data(to_uuid, package_name, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
410                appid, seinfo) != 0) {
411            LOG(ERROR) << "Failed to restorecon";
412            goto fail;
413        }
414    }
415
416    // We let the framework scan the new location and persist that before
417    // deleting the data in the old location; this ordering ensures that
418    // we can recover from things like battery pulls.
419    return 0;
420
421fail:
422    // Nuke everything we might have already copied
423    {
424        auto to = create_data_app_package_path(to_uuid, data_app_name);
425        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
426            LOG(WARNING) << "Failed to rollback " << to;
427        }
428    }
429    for (auto user : users) {
430        {
431            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
432            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
433                LOG(WARNING) << "Failed to rollback " << to;
434            }
435        }
436        {
437            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
438            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
439                LOG(WARNING) << "Failed to rollback " << to;
440            }
441        }
442    }
443    return -1;
444}
445
446int create_user_data(const char *uuid, userid_t userid, int user_serial ATTRIBUTE_UNUSED,
447        int flags) {
448    if (flags & FLAG_STORAGE_DE) {
449        if (uuid == nullptr) {
450            return ensure_config_user_dirs(userid);
451        }
452    }
453    return 0;
454}
455
456int destroy_user_data(const char *uuid, userid_t userid, int flags) {
457    int res = 0;
458    if (flags & FLAG_STORAGE_DE) {
459        res |= delete_dir_contents_and_dir(create_data_user_de_path(uuid, userid), true);
460        if (uuid == nullptr) {
461            res |= delete_dir_contents_and_dir(create_data_misc_legacy_path(userid), true);
462            res |= delete_dir_contents_and_dir(create_data_user_profiles_path(userid), true);
463        }
464    }
465    if (flags & FLAG_STORAGE_CE) {
466        res |= delete_dir_contents_and_dir(create_data_user_ce_path(uuid, userid), true);
467        res |= delete_dir_contents_and_dir(create_data_media_path(uuid, userid), true);
468    }
469    return res;
470}
471
472/* Try to ensure free_size bytes of storage are available.
473 * Returns 0 on success.
474 * This is rather simple-minded because doing a full LRU would
475 * be potentially memory-intensive, and without atime it would
476 * also require that apps constantly modify file metadata even
477 * when just reading from the cache, which is pretty awful.
478 */
479int free_cache(const char *uuid, int64_t free_size) {
480    cache_t* cache;
481    int64_t avail;
482
483    auto data_path = create_data_path(uuid);
484
485    avail = data_disk_free(data_path);
486    if (avail < 0) return -1;
487
488    ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
489    if (avail >= free_size) return 0;
490
491    cache = start_cache_collection();
492
493    auto users = get_known_users(uuid);
494    for (auto user : users) {
495        add_cache_files(cache, create_data_user_ce_path(uuid, user));
496        add_cache_files(cache, create_data_user_de_path(uuid, user));
497        add_cache_files(cache,
498                StringPrintf("%s/Android/data", create_data_media_path(uuid, user).c_str()));
499    }
500
501    clear_cache_files(data_path, cache, free_size);
502    finish_cache_collection(cache);
503
504    return data_disk_free(data_path) >= free_size ? 0 : -1;
505}
506
507int rm_dex(const char *path, const char *instruction_set)
508{
509    char dex_path[PKG_PATH_MAX];
510
511    if (validate_apk_path(path) && validate_system_app_path(path)) {
512        ALOGE("invalid apk path '%s' (bad prefix)\n", path);
513        return -1;
514    }
515
516    if (!create_cache_path(dex_path, path, instruction_set)) return -1;
517
518    ALOGV("unlink %s\n", dex_path);
519    if (unlink(dex_path) < 0) {
520        if (errno != ENOENT) {
521            ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
522        }
523        return -1;
524    } else {
525        return 0;
526    }
527}
528
529static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
530        int64_t *cachesize) {
531    DIR *d;
532    int dfd;
533    struct dirent *de;
534    struct stat s;
535
536    d = opendir(path.c_str());
537    if (d == nullptr) {
538        PLOG(WARNING) << "Failed to open " << path;
539        return;
540    }
541    dfd = dirfd(d);
542    while ((de = readdir(d))) {
543        const char *name = de->d_name;
544
545        int64_t statsize = 0;
546        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
547            statsize = stat_size(&s);
548        }
549
550        if (de->d_type == DT_DIR) {
551            int subfd;
552            int64_t dirsize = 0;
553            /* always skip "." and ".." */
554            if (name[0] == '.') {
555                if (name[1] == 0) continue;
556                if ((name[1] == '.') && (name[2] == 0)) continue;
557            }
558            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
559            if (subfd >= 0) {
560                dirsize = calculate_dir_size(subfd);
561                close(subfd);
562            }
563            // TODO: check xattrs!
564            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
565                *datasize += statsize;
566                *cachesize += dirsize;
567            } else {
568                *datasize += dirsize + statsize;
569            }
570        } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
571            *codesize += statsize;
572        } else {
573            *datasize += statsize;
574        }
575    }
576    closedir(d);
577}
578
579int get_app_size(const char *uuid, const char *pkgname, int userid, int flags, ino_t ce_data_inode,
580        const char *code_path, int64_t *codesize, int64_t *datasize, int64_t *cachesize,
581        int64_t* asecsize) {
582    DIR *d;
583    int dfd;
584
585    d = opendir(code_path);
586    if (d != nullptr) {
587        dfd = dirfd(d);
588        *codesize += calculate_dir_size(dfd);
589        closedir(d);
590    }
591
592    if (flags & FLAG_STORAGE_CE) {
593        auto path = create_data_user_ce_package_path(uuid, userid, pkgname, ce_data_inode);
594        add_app_data_size(path, codesize, datasize, cachesize);
595    }
596    if (flags & FLAG_STORAGE_DE) {
597        auto path = create_data_user_de_package_path(uuid, userid, pkgname);
598        add_app_data_size(path, codesize, datasize, cachesize);
599    }
600
601    *asecsize = 0;
602
603    return 0;
604}
605
606int get_app_data_inode(const char *uuid, const char *pkgname, int userid, int flags, ino_t *inode) {
607    struct stat buf;
608    memset(&buf, 0, sizeof(buf));
609    if (flags & FLAG_STORAGE_CE) {
610        auto path = create_data_user_ce_package_path(uuid, userid, pkgname);
611        if (stat(path.c_str(), &buf) == 0) {
612            *inode = buf.st_ino;
613            return 0;
614        }
615    }
616    return -1;
617}
618
619static int split_count(const char *str)
620{
621  char *ctx;
622  int count = 0;
623  char buf[kPropertyValueMax];
624
625  strncpy(buf, str, sizeof(buf));
626  char *pBuf = buf;
627
628  while(strtok_r(pBuf, " ", &ctx) != NULL) {
629    count++;
630    pBuf = NULL;
631  }
632
633  return count;
634}
635
636static int split(char *buf, const char **argv)
637{
638  char *ctx;
639  int count = 0;
640  char *tok;
641  char *pBuf = buf;
642
643  while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
644    argv[count++] = tok;
645    pBuf = NULL;
646  }
647
648  return count;
649}
650
651static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
652    const char* output_file_name, const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
653{
654    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
655    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
656
657    static const char* PATCHOAT_BIN = "/system/bin/patchoat";
658    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
659        ALOGE("Instruction set %s longer than max length of %d",
660              instruction_set, MAX_INSTRUCTION_SET_LEN);
661        return;
662    }
663
664    /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
665    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
666    char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
667    char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
668    const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
669    // The caller has already gotten all the locks we need.
670    const char* no_lock_arg = "--no-lock-output";
671    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
672    sprintf(output_oat_fd_arg, "--output-oat-fd=%d", oat_fd);
673    sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_fd);
674    ALOGV("Running %s isa=%s in-fd=%d (%s) out-fd=%d (%s)\n",
675          PATCHOAT_BIN, instruction_set, input_fd, input_file_name, oat_fd, output_file_name);
676
677    /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
678    char* argv[7];
679    argv[0] = (char*) PATCHOAT_BIN;
680    argv[1] = (char*) patched_image_location_arg;
681    argv[2] = (char*) no_lock_arg;
682    argv[3] = instruction_set_arg;
683    argv[4] = output_oat_fd_arg;
684    argv[5] = input_oat_fd_arg;
685    argv[6] = NULL;
686
687    execv(PATCHOAT_BIN, (char* const *)argv);
688    ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
689}
690
691static void run_dex2oat(int zip_fd, int oat_fd, int image_fd, const char* input_file_name,
692        const char* output_file_name, int swap_fd, const char *instruction_set,
693        const char* compiler_filter, bool vm_safe_mode, bool debuggable, bool post_bootcomplete,
694        int profile_fd, const char* shared_libraries) {
695    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
696
697    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
698        ALOGE("Instruction set %s longer than max length of %d",
699              instruction_set, MAX_INSTRUCTION_SET_LEN);
700        return;
701    }
702
703    char dex2oat_Xms_flag[kPropertyValueMax];
704    bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
705
706    char dex2oat_Xmx_flag[kPropertyValueMax];
707    bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
708
709    char dex2oat_threads_buf[kPropertyValueMax];
710    bool have_dex2oat_threads_flag = get_property(post_bootcomplete
711                                                      ? "dalvik.vm.dex2oat-threads"
712                                                      : "dalvik.vm.boot-dex2oat-threads",
713                                                  dex2oat_threads_buf,
714                                                  NULL) > 0;
715    char dex2oat_threads_arg[kPropertyValueMax + 2];
716    if (have_dex2oat_threads_flag) {
717        sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
718    }
719
720    char dex2oat_isa_features_key[kPropertyKeyMax];
721    sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
722    char dex2oat_isa_features[kPropertyValueMax];
723    bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
724                                                  dex2oat_isa_features, NULL) > 0;
725
726    char dex2oat_isa_variant_key[kPropertyKeyMax];
727    sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
728    char dex2oat_isa_variant[kPropertyValueMax];
729    bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
730                                                 dex2oat_isa_variant, NULL) > 0;
731
732    const char *dex2oat_norelocation = "-Xnorelocate";
733    bool have_dex2oat_relocation_skip_flag = false;
734
735    char dex2oat_flags[kPropertyValueMax];
736    int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
737                                 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
738    ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
739
740    // If we booting without the real /data, don't spend time compiling.
741    char vold_decrypt[kPropertyValueMax];
742    bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
743    bool skip_compilation = (have_vold_decrypt &&
744                             (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
745                             (strcmp(vold_decrypt, "1") == 0)));
746
747    bool generate_debug_info = property_get_bool("debug.generate-debug-info");
748
749    char app_image_format[kPropertyValueMax];
750    char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
751    bool have_app_image_format =
752            image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
753    if (have_app_image_format) {
754        sprintf(image_format_arg, "--image-format=%s", app_image_format);
755    }
756
757    static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
758
759    static const char* RUNTIME_ARG = "--runtime-arg";
760
761    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
762
763    char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
764    char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
765    char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
766    char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
767    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
768    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
769    char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
770    char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
771    char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
772    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
773    bool have_dex2oat_swap_fd = false;
774    char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
775    bool have_dex2oat_image_fd = false;
776    char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
777
778    sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
779    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
780    sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
781    sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
782    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
783    sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
784    sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
785    if (swap_fd >= 0) {
786        have_dex2oat_swap_fd = true;
787        sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
788    }
789    if (image_fd >= 0) {
790        have_dex2oat_image_fd = true;
791        sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
792    }
793
794    if (have_dex2oat_Xms_flag) {
795        sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
796    }
797    if (have_dex2oat_Xmx_flag) {
798        sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
799    }
800
801    // Compute compiler filter.
802
803    bool have_dex2oat_compiler_filter_flag;
804    if (skip_compilation) {
805        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
806        have_dex2oat_compiler_filter_flag = true;
807        have_dex2oat_relocation_skip_flag = true;
808    } else if (vm_safe_mode) {
809        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
810        have_dex2oat_compiler_filter_flag = true;
811    } else if (compiler_filter != nullptr &&
812            strlen(compiler_filter) + strlen("--compiler-filter=") <
813                    arraysize(dex2oat_compiler_filter_arg)) {
814        sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
815        have_dex2oat_compiler_filter_flag = true;
816    } else {
817        char dex2oat_compiler_filter_flag[kPropertyValueMax];
818        have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
819                                                         dex2oat_compiler_filter_flag, NULL) > 0;
820        if (have_dex2oat_compiler_filter_flag) {
821            sprintf(dex2oat_compiler_filter_arg,
822                    "--compiler-filter=%s",
823                    dex2oat_compiler_filter_flag);
824        }
825    }
826
827    // Check whether all apps should be compiled debuggable.
828    if (!debuggable) {
829        char prop_buf[kPropertyValueMax];
830        debuggable =
831                (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
832                (prop_buf[0] == '1');
833    }
834    char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
835    if (profile_fd != -1) {
836        sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
837    }
838
839
840    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
841
842    const char* argv[7  // program name, mandatory arguments and the final NULL
843                     + (have_dex2oat_isa_variant ? 1 : 0)
844                     + (have_dex2oat_isa_features ? 1 : 0)
845                     + (have_dex2oat_Xms_flag ? 2 : 0)
846                     + (have_dex2oat_Xmx_flag ? 2 : 0)
847                     + (have_dex2oat_compiler_filter_flag ? 1 : 0)
848                     + (have_dex2oat_threads_flag ? 1 : 0)
849                     + (have_dex2oat_swap_fd ? 1 : 0)
850                     + (have_dex2oat_image_fd ? 1 : 0)
851                     + (have_dex2oat_relocation_skip_flag ? 2 : 0)
852                     + (generate_debug_info ? 1 : 0)
853                     + (debuggable ? 1 : 0)
854                     + (have_app_image_format ? 1 : 0)
855                     + dex2oat_flags_count
856                     + (profile_fd == -1 ? 0 : 1)
857                     + (shared_libraries != nullptr ? 4 : 0)];
858    int i = 0;
859    argv[i++] = DEX2OAT_BIN;
860    argv[i++] = zip_fd_arg;
861    argv[i++] = zip_location_arg;
862    argv[i++] = oat_fd_arg;
863    argv[i++] = oat_location_arg;
864    argv[i++] = instruction_set_arg;
865    if (have_dex2oat_isa_variant) {
866        argv[i++] = instruction_set_variant_arg;
867    }
868    if (have_dex2oat_isa_features) {
869        argv[i++] = instruction_set_features_arg;
870    }
871    if (have_dex2oat_Xms_flag) {
872        argv[i++] = RUNTIME_ARG;
873        argv[i++] = dex2oat_Xms_arg;
874    }
875    if (have_dex2oat_Xmx_flag) {
876        argv[i++] = RUNTIME_ARG;
877        argv[i++] = dex2oat_Xmx_arg;
878    }
879    if (have_dex2oat_compiler_filter_flag) {
880        argv[i++] = dex2oat_compiler_filter_arg;
881    }
882    if (have_dex2oat_threads_flag) {
883        argv[i++] = dex2oat_threads_arg;
884    }
885    if (have_dex2oat_swap_fd) {
886        argv[i++] = dex2oat_swap_fd;
887    }
888    if (have_dex2oat_image_fd) {
889        argv[i++] = dex2oat_image_fd;
890    }
891    if (generate_debug_info) {
892        argv[i++] = "--generate-debug-info";
893    }
894    if (debuggable) {
895        argv[i++] = "--debuggable";
896    }
897    if (have_app_image_format) {
898        argv[i++] = image_format_arg;
899    }
900    if (dex2oat_flags_count) {
901        i += split(dex2oat_flags, argv + i);
902    }
903    if (have_dex2oat_relocation_skip_flag) {
904        argv[i++] = RUNTIME_ARG;
905        argv[i++] = dex2oat_norelocation;
906    }
907    if (profile_fd != -1) {
908        argv[i++] = profile_arg;
909    }
910    if (shared_libraries != nullptr) {
911        argv[i++] = RUNTIME_ARG;
912        argv[i++] = "-classpath";
913        argv[i++] = RUNTIME_ARG;
914        argv[i++] = shared_libraries;
915    }
916    // Do not add after dex2oat_flags, they should override others for debugging.
917    argv[i] = NULL;
918
919    execv(DEX2OAT_BIN, (char * const *)argv);
920    ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
921}
922
923/*
924 * Whether dexopt should use a swap file when compiling an APK.
925 *
926 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
927 * itself, anyways).
928 *
929 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
930 *
931 * Otherwise, return true if this is a low-mem device.
932 *
933 * Otherwise, return default value.
934 */
935static bool kAlwaysProvideSwapFile = false;
936static bool kDefaultProvideSwapFile = true;
937
938static bool ShouldUseSwapFileForDexopt() {
939    if (kAlwaysProvideSwapFile) {
940        return true;
941    }
942
943    // Check the "override" property. If it exists, return value == "true".
944    char dex2oat_prop_buf[kPropertyValueMax];
945    if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
946        if (strcmp(dex2oat_prop_buf, "true") == 0) {
947            return true;
948        } else {
949            return false;
950        }
951    }
952
953    // Shortcut for default value. This is an implementation optimization for the process sketched
954    // above. If the default value is true, we can avoid to check whether this is a low-mem device,
955    // as low-mem is never returning false. The compiler will optimize this away if it can.
956    if (kDefaultProvideSwapFile) {
957        return true;
958    }
959
960    bool is_low_mem = property_get_bool("ro.config.low_ram");
961    if (is_low_mem) {
962        return true;
963    }
964
965    // Default value must be false here.
966    return kDefaultProvideSwapFile;
967}
968
969static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
970    if (set_to_bg) {
971        if (set_sched_policy(0, SP_BACKGROUND) < 0) {
972            ALOGE("set_sched_policy failed: %s\n", strerror(errno));
973            exit(70);
974        }
975        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
976            ALOGE("setpriority failed: %s\n", strerror(errno));
977            exit(71);
978        }
979    }
980}
981
982static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
983    for (size_t i = 0; i < fds.size(); i++) {
984        if (close(fds[i]) != 0) {
985            PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
986        }
987    }
988}
989
990static fd_t open_profile_dir(const std::string& profile_dir) {
991    fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
992            O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
993    if (profile_dir_fd < 0) {
994        // In a multi-user environment, these directories can be created at
995        // different points and it's possible we'll attempt to open a profile
996        // dir before it exists.
997        if (errno != ENOENT) {
998            PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
999        }
1000    }
1001    return profile_dir_fd;
1002}
1003
1004static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1005    fd_t profile_dir_fd  = open_profile_dir(profile_dir);
1006    if (profile_dir_fd < 0) {
1007        return -1;
1008    }
1009
1010    fd_t profile_fd = -1;
1011    std::string profile_file = create_primary_profile(profile_dir);
1012
1013    profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1014    if (profile_fd == -1) {
1015        // It's not an error if the profile file does not exist.
1016        if (errno != ENOENT) {
1017            PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1018        }
1019    }
1020    // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1021    if (close(profile_dir_fd) != 0) {
1022        PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1023    }
1024    return profile_fd;
1025}
1026
1027static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1028    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1029    return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1030}
1031
1032static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1033    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1034    int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1035    fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1036    if (fd < 0) {
1037        return -1;
1038    }
1039    if (read_write) {
1040        // Fix the owner.
1041        if (fchown(fd, uid, uid) < 0) {
1042            close(fd);
1043            return -1;
1044        }
1045    }
1046    return fd;
1047}
1048
1049static void open_profile_files(uid_t uid, const char* pkgname,
1050            /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1051    // Open the reference profile in read-write mode as profman might need to save the merge.
1052    *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
1053    if (*reference_profile_fd < 0) {
1054        // We can't access the reference profile file.
1055        return;
1056    }
1057
1058    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1059    for (auto user : users) {
1060        fd_t profile_fd = open_primary_profile_file(user, pkgname);
1061        // Add to the lists only if both fds are valid.
1062        if (profile_fd >= 0) {
1063            profiles_fd->push_back(profile_fd);
1064        }
1065    }
1066}
1067
1068static void drop_capabilities(uid_t uid) {
1069    if (setgid(uid) != 0) {
1070        ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1071        exit(64);
1072    }
1073    if (setuid(uid) != 0) {
1074        ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1075        exit(65);
1076    }
1077    // drop capabilities
1078    struct __user_cap_header_struct capheader;
1079    struct __user_cap_data_struct capdata[2];
1080    memset(&capheader, 0, sizeof(capheader));
1081    memset(&capdata, 0, sizeof(capdata));
1082    capheader.version = _LINUX_CAPABILITY_VERSION_3;
1083    if (capset(&capheader, &capdata[0]) < 0) {
1084        ALOGE("capset failed: %s\n", strerror(errno));
1085        exit(66);
1086    }
1087}
1088
1089static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1090static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1091static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1092static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1093static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1094
1095static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
1096    static const size_t MAX_INT_LEN = 32;
1097    static const char* PROFMAN_BIN = "/system/bin/profman";
1098
1099    std::vector<std::string> profile_args(profiles_fd.size());
1100    char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1101    for (size_t k = 0; k < profiles_fd.size(); k++) {
1102        sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1103        profile_args[k].assign(profile_buf);
1104    }
1105    char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1106    sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1107
1108    // program name, reference profile fd, the final NULL and the profile fds
1109    const char* argv[3 + profiles_fd.size()];
1110    int i = 0;
1111    argv[i++] = PROFMAN_BIN;
1112    argv[i++] = reference_profile_arg;
1113    for (size_t k = 0; k < profile_args.size(); k++) {
1114        argv[i++] = profile_args[k].c_str();
1115    }
1116    // Do not add after dex2oat_flags, they should override others for debugging.
1117    argv[i] = NULL;
1118
1119    execv(PROFMAN_BIN, (char * const *)argv);
1120    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1121    exit(68);   /* only get here on exec failure */
1122}
1123
1124// Decides if profile guided compilation is needed or not based on existing profiles.
1125// Returns true if there is enough information in the current profiles that worth
1126// a re-compilation of the package.
1127// If the return value is true all the current profiles would have been merged into
1128// the reference profiles accessible with open_reference_profile().
1129static bool analyse_profiles(uid_t uid, const char* pkgname) {
1130    std::vector<fd_t> profiles_fd;
1131    fd_t reference_profile_fd = -1;
1132    open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1133    if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1134        // Skip profile guided compilation because no profiles were found.
1135        // Or if the reference profile info couldn't be opened.
1136        close_all_fds(profiles_fd, "profiles_fd");
1137        if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1138            PLOG(WARNING) << "Failed to close fd for reference profile";
1139        }
1140        return false;
1141    }
1142
1143    ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
1144
1145    pid_t pid = fork();
1146    if (pid == 0) {
1147        /* child -- drop privileges before continuing */
1148        drop_capabilities(uid);
1149        run_profman_merge(profiles_fd, reference_profile_fd);
1150        exit(68);   /* only get here on exec failure */
1151    }
1152    /* parent */
1153    int return_code = wait_child(pid);
1154    bool need_to_compile = false;
1155    bool should_clear_current_profiles = false;
1156    bool should_clear_reference_profile = false;
1157    if (!WIFEXITED(return_code)) {
1158        LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1159    } else {
1160        return_code = WEXITSTATUS(return_code);
1161        switch (return_code) {
1162            case PROFMAN_BIN_RETURN_CODE_COMPILE:
1163                need_to_compile = true;
1164                should_clear_current_profiles = true;
1165                should_clear_reference_profile = false;
1166                break;
1167            case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1168                need_to_compile = false;
1169                should_clear_current_profiles = false;
1170                should_clear_reference_profile = false;
1171                break;
1172            case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1173                LOG(WARNING) << "Bad profiles for package " << pkgname;
1174                need_to_compile = false;
1175                should_clear_current_profiles = true;
1176                should_clear_reference_profile = true;
1177                break;
1178            case PROFMAN_BIN_RETURN_CODE_ERROR_IO:  // fall-through
1179            case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1180                // Temporary IO problem (e.g. locking). Ignore but log a warning.
1181                LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1182                need_to_compile = false;
1183                should_clear_current_profiles = false;
1184                should_clear_reference_profile = false;
1185                break;
1186           default:
1187                // Unknown return code or error. Unlink profiles.
1188                LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1189                        << ": " << return_code;
1190                need_to_compile = false;
1191                should_clear_current_profiles = true;
1192                should_clear_reference_profile = true;
1193                break;
1194        }
1195    }
1196    close_all_fds(profiles_fd, "profiles_fd");
1197    if (close(reference_profile_fd) != 0) {
1198        PLOG(WARNING) << "Failed to close fd for reference profile";
1199    }
1200    if (should_clear_current_profiles) {
1201        clear_current_profiles(pkgname);
1202    }
1203    if (should_clear_reference_profile) {
1204        clear_reference_profile(pkgname);
1205    }
1206    return need_to_compile;
1207}
1208
1209static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1210                             fd_t reference_profile_fd,
1211                             const std::vector<std::string>& dex_locations,
1212                             const std::vector<fd_t>& apk_fds,
1213                             fd_t output_fd) {
1214    std::vector<std::string> profman_args;
1215    static const char* PROFMAN_BIN = "/system/bin/profman";
1216    profman_args.push_back(PROFMAN_BIN);
1217    profman_args.push_back("--dump-only");
1218    profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1219    if (reference_profile_fd != -1) {
1220        profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1221                                            reference_profile_fd));
1222    }
1223    for (fd_t profile_fd : profile_fds) {
1224        profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
1225    }
1226    for (const std::string& dex_location : dex_locations) {
1227        profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
1228    }
1229    for (fd_t apk_fd : apk_fds) {
1230        profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1231    }
1232    const char **argv = new const char*[profman_args.size() + 1];
1233    size_t i = 0;
1234    for (const std::string& profman_arg : profman_args) {
1235        argv[i++] = profman_arg.c_str();
1236    }
1237    argv[i] = NULL;
1238
1239    execv(PROFMAN_BIN, (char * const *)argv);
1240    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1241    exit(68);   /* only get here on exec failure */
1242}
1243
1244static const char* get_location_from_path(const char* path) {
1245    static constexpr char kLocationSeparator = '/';
1246    const char *location = strrchr(path, kLocationSeparator);
1247    if (location == NULL) {
1248        return path;
1249    } else {
1250        // Skip the separator character.
1251        return location + 1;
1252    }
1253}
1254
1255// Dumps the contents of a profile file, using pkgname's dex files for pretty
1256// printing the result.
1257bool dump_profile(uid_t uid, const char* pkgname, const char* code_path_string) {
1258    std::vector<fd_t> profile_fds;
1259    fd_t reference_profile_fd = -1;
1260    std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1261
1262    ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1263
1264    open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1265
1266    const bool has_reference_profile = (reference_profile_fd != -1);
1267    const bool has_profiles = !profile_fds.empty();
1268
1269    if (!has_reference_profile && !has_profiles) {
1270        ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
1271        return false;
1272    }
1273
1274    fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
1275    if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1276        ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
1277        return false;
1278    }
1279    std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1280    std::vector<std::string> dex_locations;
1281    std::vector<fd_t> apk_fds;
1282    for (const std::string& code_full_path : code_full_paths) {
1283        const char* full_path = code_full_path.c_str();
1284        fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1285        if (apk_fd == -1) {
1286            ALOGE("installd cannot open '%s'\n", full_path);
1287            return false;
1288        }
1289        dex_locations.push_back(get_location_from_path(full_path));
1290        apk_fds.push_back(apk_fd);
1291    }
1292
1293    pid_t pid = fork();
1294    if (pid == 0) {
1295        /* child -- drop privileges before continuing */
1296        drop_capabilities(uid);
1297        run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1298                         apk_fds, output_fd);
1299        exit(68);   /* only get here on exec failure */
1300    }
1301    /* parent */
1302    close_all_fds(apk_fds, "apk_fds");
1303    close_all_fds(profile_fds, "profile_fds");
1304    if (close(reference_profile_fd) != 0) {
1305        PLOG(WARNING) << "Failed to close fd for reference profile";
1306    }
1307    int return_code = wait_child(pid);
1308    if (!WIFEXITED(return_code)) {
1309        LOG(WARNING) << "profman failed for package " << pkgname << ": "
1310                << return_code;
1311        return false;
1312    }
1313    return true;
1314}
1315
1316static void trim_extension(char* path) {
1317  // Trim the extension.
1318  int pos = strlen(path);
1319  for (; pos >= 0 && path[pos] != '.'; --pos) {}
1320  if (pos >= 0) {
1321      path[pos] = '\0';  // Trim extension
1322  }
1323}
1324
1325static bool add_extension_to_file_name(char* file_name, const char* extension) {
1326    if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1327        return false;
1328    }
1329    strcat(file_name, extension);
1330    return true;
1331}
1332
1333static int open_output_file(char* file_name, bool recreate, int permissions) {
1334    int flags = O_RDWR | O_CREAT;
1335    if (recreate) {
1336        if (unlink(file_name) < 0) {
1337            if (errno != ENOENT) {
1338                PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1339            }
1340        }
1341        flags |= O_EXCL;
1342    }
1343    return open(file_name, flags, permissions);
1344}
1345
1346static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1347    if (fchmod(fd,
1348               S_IRUSR|S_IWUSR|S_IRGRP |
1349               (is_public ? S_IROTH : 0)) < 0) {
1350        ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1351        return false;
1352    } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1353        ALOGE("installd cannot chown '%s' during dexopt\n", path);
1354        return false;
1355    }
1356    return true;
1357}
1358
1359static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
1360            const char* oat_dir, /*out*/ char* out_path) {
1361    // Early best-effort check whether we can fit the the path into our buffers.
1362    // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1363    // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1364    // extension to the cache path (5 bytes).
1365    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1366        ALOGE("apk_path too long '%s'\n", apk_path);
1367        return false;
1368    }
1369
1370    if (oat_dir != NULL && oat_dir[0] != '!') {
1371        if (validate_apk_path(oat_dir)) {
1372            ALOGE("invalid oat_dir '%s'\n", oat_dir);
1373            return false;
1374        }
1375        if (!calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
1376            return false;
1377        }
1378    } else {
1379        if (!create_cache_path(out_path, apk_path, instruction_set)) {
1380            return false;
1381        }
1382    }
1383    return true;
1384}
1385
1386// TODO: Consider returning error codes.
1387bool merge_profiles(uid_t uid, const char *pkgname) {
1388    return analyse_profiles(uid, pkgname);
1389}
1390
1391int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1392           int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1393           const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries)
1394{
1395    struct utimbuf ut;
1396    struct stat input_stat;
1397    char out_path[PKG_PATH_MAX];
1398    char swap_file_name[PKG_PATH_MAX];
1399    char image_path[PKG_PATH_MAX];
1400    const char *input_file;
1401    char in_odex_path[PKG_PATH_MAX];
1402    int res;
1403    fd_t input_fd=-1, out_fd=-1, image_fd=-1, swap_fd=-1;
1404    bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1405    bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1406    bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1407    bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1408    bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1409
1410    CHECK(pkgname != nullptr);
1411    CHECK(pkgname[0] != 0);
1412
1413    fd_t reference_profile_fd = -1;
1414    // Public apps should not be compiled with profile information ever. Same goes for the special
1415    // package '*' used for the system server.
1416    if (!is_public && pkgname[0] != '*') {
1417        // Open reference profile in read only mode as dex2oat does not get write permissions.
1418        reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ false);
1419        // Note: it's OK to not find a profile here.
1420    }
1421
1422    if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1423        LOG_FATAL("dexopt flags contains unknown fields\n");
1424    }
1425
1426    if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
1427        return false;
1428    }
1429
1430    switch (dexopt_needed) {
1431        case DEXOPT_DEX2OAT_NEEDED:
1432            input_file = apk_path;
1433            break;
1434
1435        case DEXOPT_PATCHOAT_NEEDED:
1436            if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1437                return -1;
1438            }
1439            input_file = in_odex_path;
1440            break;
1441
1442        case DEXOPT_SELF_PATCHOAT_NEEDED:
1443            input_file = out_path;
1444            break;
1445
1446        default:
1447            ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1448            exit(72);
1449    }
1450
1451    memset(&input_stat, 0, sizeof(input_stat));
1452    stat(input_file, &input_stat);
1453
1454    input_fd = open(input_file, O_RDONLY, 0);
1455    if (input_fd < 0) {
1456        ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
1457        return -1;
1458    }
1459
1460    out_fd = open_output_file(out_path, /*recreate*/true, /*permissions*/0644);
1461    if (out_fd < 0) {
1462        ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
1463        goto fail;
1464    }
1465    if (!set_permissions_and_ownership(out_fd, is_public, uid, out_path)) {
1466        goto fail;
1467    }
1468
1469    // Create a swap file if necessary.
1470    if (ShouldUseSwapFileForDexopt()) {
1471        // Make sure there really is enough space.
1472        strcpy(swap_file_name, out_path);
1473        if (add_extension_to_file_name(swap_file_name, ".swap")) {
1474            swap_fd = open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600);
1475        }
1476        if (swap_fd < 0) {
1477            // Could not create swap file. Optimistically go on and hope that we can compile
1478            // without it.
1479            ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1480        } else {
1481            // Immediately unlink. We don't really want to hit flash.
1482            if (unlink(swap_file_name) < 0) {
1483                PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1484            }
1485        }
1486    }
1487
1488    // Avoid generating an app image for extract only since it will not contain any classes.
1489    strcpy(image_path, out_path);
1490    trim_extension(image_path);
1491    if (add_extension_to_file_name(image_path, ".art")) {
1492      char app_image_format[kPropertyValueMax];
1493      bool have_app_image_format =
1494              get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1495      // Use app images only if it is enabled (by a set image format) and we are compiling
1496      // profile-guided (so the app image doesn't conservatively contain all classes).
1497      if (profile_guided && have_app_image_format) {
1498          // Recreate is true since we do not want to modify a mapped image. If the app is already
1499          // running and we modify the image file, it can cause crashes (b/27493510).
1500          image_fd = open_output_file(image_path, /*recreate*/true, /*permissions*/0600);
1501          if (image_fd < 0) {
1502              // Could not create application image file. Go on since we can compile without it.
1503              ALOGE("installd could not create '%s' for image file during dexopt\n", image_path);
1504          } else if (!set_permissions_and_ownership(image_fd, is_public, uid, image_path)) {
1505              image_fd = -1;
1506          }
1507      }
1508      // If we have a valid image file path but no image fd, erase the image file.
1509      if (image_fd < 0) {
1510          if (unlink(image_path) < 0) {
1511              if (errno != ENOENT) {
1512                  PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1513              }
1514          }
1515      }
1516    }
1517
1518    ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
1519
1520    pid_t pid;
1521    pid = fork();
1522    if (pid == 0) {
1523        /* child -- drop privileges before continuing */
1524        drop_capabilities(uid);
1525
1526        SetDex2OatAndPatchOatScheduling(boot_complete);
1527        if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
1528            ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
1529            exit(67);
1530        }
1531
1532        if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
1533            || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
1534            run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
1535        } else if (dexopt_needed == DEXOPT_DEX2OAT_NEEDED) {
1536            // Pass dex2oat the relative path to the input file.
1537            const char *input_file_name = get_location_from_path(input_file);
1538            run_dex2oat(input_fd, out_fd, image_fd, input_file_name, out_path, swap_fd,
1539                        instruction_set, compiler_filter, vm_safe_mode, debuggable, boot_complete,
1540                        reference_profile_fd, shared_libraries);
1541        } else {
1542            ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1543            exit(73);
1544        }
1545        exit(68);   /* only get here on exec failure */
1546    } else {
1547        res = wait_child(pid);
1548        if (res == 0) {
1549            ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
1550        } else {
1551            ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
1552            goto fail;
1553        }
1554    }
1555
1556    ut.actime = input_stat.st_atime;
1557    ut.modtime = input_stat.st_mtime;
1558    utime(out_path, &ut);
1559
1560    close(out_fd);
1561    close(input_fd);
1562    if (swap_fd >= 0) {
1563        close(swap_fd);
1564    }
1565    if (reference_profile_fd >= 0) {
1566        close(reference_profile_fd);
1567    }
1568    if (image_fd >= 0) {
1569        close(image_fd);
1570    }
1571    return 0;
1572
1573fail:
1574    if (out_fd >= 0) {
1575        close(out_fd);
1576        unlink(out_path);
1577    }
1578    if (input_fd >= 0) {
1579        close(input_fd);
1580    }
1581    if (reference_profile_fd >= 0) {
1582        close(reference_profile_fd);
1583        // We failed to compile. Unlink the reference profile. Current profiles are already unlinked
1584        // when profmoan advises compilation.
1585        clear_reference_profile(pkgname);
1586    }
1587    if (swap_fd >= 0) {
1588        close(swap_fd);
1589    }
1590    if (image_fd >= 0) {
1591        close(image_fd);
1592    }
1593    return -1;
1594}
1595
1596int mark_boot_complete(const char* instruction_set)
1597{
1598  char boot_marker_path[PKG_PATH_MAX];
1599  sprintf(boot_marker_path,
1600          "%s/%s/%s/.booting",
1601          android_data_dir.path,
1602          DALVIK_CACHE,
1603          instruction_set);
1604
1605  ALOGV("mark_boot_complete : %s", boot_marker_path);
1606  if (unlink(boot_marker_path) != 0) {
1607      ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
1608            strerror(errno));
1609      return -1;
1610  }
1611
1612  return 0;
1613}
1614
1615void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1616        struct stat* statbuf)
1617{
1618    while (path[basepos] != 0) {
1619        if (path[basepos] == '/') {
1620            path[basepos] = 0;
1621            if (lstat(path, statbuf) < 0) {
1622                ALOGV("Making directory: %s\n", path);
1623                if (mkdir(path, mode) == 0) {
1624                    chown(path, uid, gid);
1625                } else {
1626                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1627                }
1628            }
1629            path[basepos] = '/';
1630            basepos++;
1631        }
1632        basepos++;
1633    }
1634}
1635
1636int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId)
1637{
1638    struct stat s, libStat;
1639    int rc = 0;
1640
1641    std::string _pkgdir(create_data_user_ce_package_path(uuid, userId, pkgname));
1642    std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
1643
1644    const char* pkgdir = _pkgdir.c_str();
1645    const char* libsymlink = _libsymlink.c_str();
1646
1647    if (stat(pkgdir, &s) < 0) return -1;
1648
1649    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1650        ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1651        return -1;
1652    }
1653
1654    if (chmod(pkgdir, 0700) < 0) {
1655        ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1656        rc = -1;
1657        goto out;
1658    }
1659
1660    if (lstat(libsymlink, &libStat) < 0) {
1661        if (errno != ENOENT) {
1662            ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1663            rc = -1;
1664            goto out;
1665        }
1666    } else {
1667        if (S_ISDIR(libStat.st_mode)) {
1668            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1669                rc = -1;
1670                goto out;
1671            }
1672        } else if (S_ISLNK(libStat.st_mode)) {
1673            if (unlink(libsymlink) < 0) {
1674                ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1675                rc = -1;
1676                goto out;
1677            }
1678        }
1679    }
1680
1681    if (symlink(asecLibDir, libsymlink) < 0) {
1682        ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1683                strerror(errno));
1684        rc = -errno;
1685        goto out;
1686    }
1687
1688out:
1689    if (chmod(pkgdir, s.st_mode) < 0) {
1690        ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1691        rc = -errno;
1692    }
1693
1694    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1695        ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1696        return -errno;
1697    }
1698
1699    return rc;
1700}
1701
1702static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1703{
1704    static const char *IDMAP_BIN = "/system/bin/idmap";
1705    static const size_t MAX_INT_LEN = 32;
1706    char idmap_str[MAX_INT_LEN];
1707
1708    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1709
1710    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1711    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1712}
1713
1714// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1715// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1716static int flatten_path(const char *prefix, const char *suffix,
1717        const char *overlay_path, char *idmap_path, size_t N)
1718{
1719    if (overlay_path == NULL || idmap_path == NULL) {
1720        return -1;
1721    }
1722    const size_t len_overlay_path = strlen(overlay_path);
1723    // will access overlay_path + 1 further below; requires absolute path
1724    if (len_overlay_path < 2 || *overlay_path != '/') {
1725        return -1;
1726    }
1727    const size_t len_idmap_root = strlen(prefix);
1728    const size_t len_suffix = strlen(suffix);
1729    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1730            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1731        // additions below would cause overflow
1732        return -1;
1733    }
1734    if (N < len_idmap_root + len_overlay_path + len_suffix) {
1735        return -1;
1736    }
1737    memset(idmap_path, 0, N);
1738    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1739    char *ch = idmap_path + len_idmap_root;
1740    while (*ch != '\0') {
1741        if (*ch == '/') {
1742            *ch = '@';
1743        }
1744        ++ch;
1745    }
1746    return 0;
1747}
1748
1749int idmap(const char *target_apk, const char *overlay_apk, uid_t uid)
1750{
1751    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1752
1753    int idmap_fd = -1;
1754    char idmap_path[PATH_MAX];
1755
1756    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1757                idmap_path, sizeof(idmap_path)) == -1) {
1758        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1759        goto fail;
1760    }
1761
1762    unlink(idmap_path);
1763    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1764    if (idmap_fd < 0) {
1765        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1766        goto fail;
1767    }
1768    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1769        ALOGE("idmap cannot chown '%s'\n", idmap_path);
1770        goto fail;
1771    }
1772    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1773        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1774        goto fail;
1775    }
1776
1777    pid_t pid;
1778    pid = fork();
1779    if (pid == 0) {
1780        /* child -- drop privileges before continuing */
1781        if (setgid(uid) != 0) {
1782            ALOGE("setgid(%d) failed during idmap\n", uid);
1783            exit(1);
1784        }
1785        if (setuid(uid) != 0) {
1786            ALOGE("setuid(%d) failed during idmap\n", uid);
1787            exit(1);
1788        }
1789        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1790            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1791            exit(1);
1792        }
1793
1794        run_idmap(target_apk, overlay_apk, idmap_fd);
1795        exit(1); /* only if exec call to idmap failed */
1796    } else {
1797        int status = wait_child(pid);
1798        if (status != 0) {
1799            ALOGE("idmap failed, status=0x%04x\n", status);
1800            goto fail;
1801        }
1802    }
1803
1804    close(idmap_fd);
1805    return 0;
1806fail:
1807    if (idmap_fd >= 0) {
1808        close(idmap_fd);
1809        unlink(idmap_path);
1810    }
1811    return -1;
1812}
1813
1814int restorecon_app_data(const char* uuid, const char* pkgName, userid_t userid, int flags,
1815        appid_t appid, const char* seinfo) {
1816    int res = 0;
1817
1818    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1819    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
1820
1821    if (!pkgName || !seinfo) {
1822        ALOGE("Package name or seinfo tag is null when trying to restorecon.");
1823        return -1;
1824    }
1825
1826    uid_t uid = multiuser_get_uid(userid, appid);
1827    if (flags & FLAG_STORAGE_CE) {
1828        auto path = create_data_user_ce_package_path(uuid, userid, pkgName);
1829        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1830            PLOG(ERROR) << "restorecon failed for " << path;
1831            res = -1;
1832        }
1833    }
1834    if (flags & FLAG_STORAGE_DE) {
1835        auto path = create_data_user_de_package_path(uuid, userid, pkgName);
1836        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1837            PLOG(ERROR) << "restorecon failed for " << path;
1838            // TODO: include result once 25796509 is fixed
1839        }
1840    }
1841
1842    return res;
1843}
1844
1845int create_oat_dir(const char* oat_dir, const char* instruction_set)
1846{
1847    char oat_instr_dir[PKG_PATH_MAX];
1848
1849    if (validate_apk_path(oat_dir)) {
1850        ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
1851        return -1;
1852    }
1853    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1854        return -1;
1855    }
1856    if (selinux_android_restorecon(oat_dir, 0)) {
1857        ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
1858        return -1;
1859    }
1860    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
1861    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1862        return -1;
1863    }
1864    return 0;
1865}
1866
1867int rm_package_dir(const char* apk_path)
1868{
1869    if (validate_apk_path(apk_path)) {
1870        ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
1871        return -1;
1872    }
1873    return delete_dir_contents(apk_path, 1 /* also_delete_dir */ , NULL /* exclusion_predicate */);
1874}
1875
1876int link_file(const char* relative_path, const char* from_base, const char* to_base) {
1877    char from_path[PKG_PATH_MAX];
1878    char to_path[PKG_PATH_MAX];
1879    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1880    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1881
1882    if (validate_apk_path_subdirs(from_path)) {
1883        ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
1884        return -1;
1885    }
1886
1887    if (validate_apk_path_subdirs(to_path)) {
1888        ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
1889        return -1;
1890    }
1891
1892    const int ret = link(from_path, to_path);
1893    if (ret < 0) {
1894        ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
1895        return -1;
1896    }
1897
1898    return 0;
1899}
1900
1901// Helper for move_ab, so that we can have common failure-case cleanup.
1902static bool unlink_and_rename(const char* from, const char* to) {
1903    // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1904    // return a failure.
1905    struct stat s;
1906    if (stat(to, &s) == 0) {
1907        if (!S_ISREG(s.st_mode)) {
1908            LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1909            return false;
1910        }
1911        if (unlink(to) != 0) {
1912            LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1913            return false;
1914        }
1915    } else {
1916        // This may be a permission problem. We could investigate the error code, but we'll just
1917        // let the rename failure do the work for us.
1918    }
1919
1920    // Try to rename "to" to "from."
1921    if (rename(from, to) != 0) {
1922        PLOG(ERROR) << "Could not rename " << from << " to " << to;
1923        return false;
1924    }
1925
1926    return true;
1927}
1928
1929int move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1930    if (apk_path == nullptr || instruction_set == nullptr || oat_dir == nullptr) {
1931        LOG(ERROR) << "Cannot move_ab with null input";
1932        return -1;
1933    }
1934    if (validate_apk_path(apk_path) != 0) {
1935        LOG(ERROR) << "invalid apk_path " << apk_path;
1936        return -1;
1937    }
1938    if (validate_apk_path(oat_dir) != 0) {
1939        LOG(ERROR) << "invalid oat_dir " << oat_dir;
1940        return -1;
1941    }
1942
1943    char a_path[PKG_PATH_MAX];
1944    if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1945        return -1;
1946    }
1947
1948    // B path = A path + ".b"
1949    std::string b_path = StringPrintf("%s.b", a_path);
1950
1951    // Check whether B exists.
1952    {
1953        struct stat s;
1954        if (stat(b_path.c_str(), &s) != 0) {
1955            // Silently ignore for now. The service calling this isn't smart enough to understand
1956            // lack of artifacts at the moment.
1957            return -1;
1958        }
1959        if (!S_ISREG(s.st_mode)) {
1960            LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1961            // Try to unlink, but swallow errors.
1962            unlink(b_path.c_str());
1963            return -1;
1964        }
1965    }
1966
1967    // Rename B to A.
1968    if (!unlink_and_rename(b_path.c_str(), a_path)) {
1969        // Delete the b_path so we don't try again (or fail earlier).
1970        if (unlink(b_path.c_str()) != 0) {
1971            PLOG(ERROR) << "Could not unlink " << b_path;
1972        }
1973
1974        return -1;
1975    }
1976
1977    return 0;
1978}
1979
1980}  // namespace installd
1981}  // namespace android
1982