InstalldNativeService.cpp revision 475c6f9743e5f6696c38fb22b8b8e9d49a82ab56
194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood/*
294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood** Copyright 2008, The Android Open Source Project
394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood**
4d93707342a61e66bc3eb2145628158452f577f42Dave Allison** Licensed under the Apache License, Version 2.0 (the "License");
5d93707342a61e66bc3eb2145628158452f577f42Dave Allison** you may not use this file except in compliance with the License.
6d93707342a61e66bc3eb2145628158452f577f42Dave Allison** You may obtain a copy of the License at
794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood**
8d93707342a61e66bc3eb2145628158452f577f42Dave Allison**     http://www.apache.org/licenses/LICENSE-2.0
994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood**
10d93707342a61e66bc3eb2145628158452f577f42Dave Allison** Unless required by applicable law or agreed to in writing, software
11d93707342a61e66bc3eb2145628158452f577f42Dave Allison** distributed under the License is distributed on an "AS IS" BASIS,
12d93707342a61e66bc3eb2145628158452f577f42Dave Allison** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13d93707342a61e66bc3eb2145628158452f577f42Dave Allison** See the License for the specific language governing permissions and
1494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood** limitations under the License.
1594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood*/
1694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include "commands.h"
1802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe
1902d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <errno.h>
2002d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <inttypes.h>
21d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe#include <regex>
2202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <stdlib.h>
2302d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <sys/capability.h>
2402d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <sys/file.h>
2502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <sys/resource.h>
2602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <sys/stat.h>
27cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey#include <sys/types.h>
286a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle#include <sys/wait.h>
29cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey#include <sys/xattr.h>
3002d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <unistd.h>
3141ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkey
326fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe#include <android-base/logging.h>
33e4ec9eb7b4c452493589983970ba5ccc501728d1Elliott Hughes#include <android-base/stringprintf.h>
346727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr#include <android-base/strings.h>
3564b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain#include <android-base/unique_fd.h>
3602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <cutils/fs.h>
3702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <cutils/log.h>               // TODO: Move everything to base/logging.
380378aaf257aee92539d30543914a50c4481c6a18Brian Carlstrom#include <cutils/sched_policy.h>
3994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <diskusage/dirsize.h>
40e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey#include <logwrap/logwrap.h>
4102d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <private/android_filesystem_config.h>
42e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey#include <selinux/android.h>
4302d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <system/thread_defs.h>
44e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
4502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <globals.h>
4602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <installd_deps.h>
47fd12edaeab839f3f1f087cc75bd18b4d8af5b192Andreas Gampe#include <otapreopt_utils.h>
4802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#include <utils.h>
4902d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe
5002d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#ifndef LOG_TAG
5102d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#define LOG_TAG "installd"
5202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe#endif
5341ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkey
546fb5a0179d4de9c85351fd016277949804c809edAndreas Gampeusing android::base::EndsWith;
5541ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkeyusing android::base::StringPrintf;
5694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
5702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampenamespace android {
5802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampenamespace installd {
5994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
60cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkeystatic constexpr const char* kCpPath = "/system/bin/cp";
61cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkeystatic constexpr const char* kXattrDefault = "user.default";
62e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
63d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr const char* PKG_LIB_POSTFIX = "/lib";
64d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr const char* CACHE_DIR_POSTFIX = "/cache";
65d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
66d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
67d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
68d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr const char* IDMAP_SUFFIX = "@idmap";
69d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
70d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe// NOTE: keep in sync with StorageManager
71d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr int FLAG_STORAGE_DE = 1 << 0;
72d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr int FLAG_STORAGE_CE = 1 << 1;
73d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
74d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe// NOTE: keep in sync with Installer
75d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
76d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampestatic constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
77d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
78d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe/* dexopt needed flags matching those in dalvik.system.DexFile */
79920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffraystatic constexpr int DEX2OAT_FROM_SCRATCH        = 1;
80920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffraystatic constexpr int DEX2OAT_FOR_BOOT_IMAGE      = 2;
81920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffraystatic constexpr int DEX2OAT_FOR_FILTER          = 3;
82920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffraystatic constexpr int DEX2OAT_FOR_RELOCATION      = 4;
83920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffraystatic constexpr int PATCHOAT_FOR_RELOCATION     = 5;
84d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
85eecb2d205366351af42fd0cd9e1a95de3980764eJanis Danisevskis#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
86eecb2d205366351af42fd0cd9e1a95de3980764eJanis Danisevskis
876a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravletypedef int fd_t;
886a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
890274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeynamespace {
900274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
910274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeyconstexpr const char* kDump = "android.permission.DUMP";
920274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
930274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeybinder::Status checkPermission(const char* permission) {
940274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    pid_t pid;
950274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    uid_t uid;
960274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
970274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
980274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            reinterpret_cast<int32_t*>(&uid))) {
990274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return binder::Status::ok();
1000274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    } else {
1010274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        auto err = StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission);
1020274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
1030274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    }
1040274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}
1050274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1060274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeybinder::Status checkUid(uid_t expectedUid) {
1070274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    uid_t uid = IPCThreadState::self()->getCallingUid();
1080274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (uid == expectedUid || uid == AID_ROOT) {
1090274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return binder::Status::ok();
1100274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    } else {
1110274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        auto err = StringPrintf("UID %d is not expected UID %d", uid, expectedUid);
1120274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
1130274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    }
1140274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}
1150274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1160274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey#define ENFORCE_UID(uid) {                                  \
1170274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    binder::Status status = checkUid((uid));                \
1180274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (!status.isOk()) {                                   \
1190274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return status;                                      \
1200274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    }                                                       \
1210274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}
1220274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1230274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}  // namespace
1240274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1250274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeystatus_t InstalldNativeService::start() {
1260274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    IPCThreadState::self()->disableBackgroundScheduling(true);
1270274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    status_t ret = BinderService<InstalldNativeService>::publish();
1280274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (ret != android::OK) {
1290274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return ret;
1300274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    }
1310274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    sp<ProcessState> ps(ProcessState::self());
1320274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    ps->startThreadPool();
1330274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    ps->giveThreadPoolName();
1340274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return android::OK;
1350274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}
1360274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1370274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeystatus_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
1380274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const binder::Status dump_permission = checkPermission(kDump);
1390274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (!dump_permission.isOk()) {
1400274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const String8 msg(dump_permission.toString8());
1410274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        write(fd, msg.string(), msg.size());
1420274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        return PERMISSION_DENIED;
1430274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    }
1440274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1450274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    std::string msg = "installd is happy\n";
1460274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    write(fd, msg.c_str(), strlen(msg.c_str()));
1470274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return NO_ERROR;
1480274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey}
1490274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
1506a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic bool property_get_bool(const char* property_name, bool default_value = false) {
1516a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    char tmp_property_value[kPropertyValueMax];
1526a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
1536a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (!have_property) {
1546a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return default_value;
1556a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
1566a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return strcmp(tmp_property_value, "true") == 0;
1576a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
1586a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
159bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle// Keep profile paths in sync with ActivityThread.
160bc56e7dcf07e633867e1525435373a1231216b22Calin Juravleconstexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
161bc56e7dcf07e633867e1525435373a1231216b22Calin Juravlestatic std::string create_primary_profile(const std::string& profile_dir) {
162bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle    return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
163bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle}
164bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle
1657db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey/**
1667db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey * Perform restorecon of the given path, but only perform recursive restorecon
1677db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey * if the label of that top-level file actually changed.  This can save us
1687db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey * significant time by avoiding no-op traversals of large filesystem trees.
1697db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey */
1700274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeystatic int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
1717db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    int res = 0;
1727db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    char* before = nullptr;
1737db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    char* after = nullptr;
1747db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
1757db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
1767db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    // libselinux. Not needed here.
1777db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
17895d9ac642f082870fd4d2419f534171a9b82bbcdJeff Sharkey    if (lgetfilecon(path.c_str(), &before) < 0) {
1797db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        PLOG(ERROR) << "Failed before getfilecon for " << path;
1807db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        goto fail;
1817db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    }
1820274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
1837db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        PLOG(ERROR) << "Failed top-level restorecon for " << path;
1847db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        goto fail;
1857db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    }
18695d9ac642f082870fd4d2419f534171a9b82bbcdJeff Sharkey    if (lgetfilecon(path.c_str(), &after) < 0) {
1877db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        PLOG(ERROR) << "Failed after getfilecon for " << path;
1887db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        goto fail;
1897db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    }
1907db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
1917db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    // If the initial top-level restorecon above changed the label, then go
1927db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    // back and restorecon everything recursively
1937db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    if (strcmp(before, after)) {
1947db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
1957db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey                << "; running recursive restorecon";
1960274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
1977db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey                SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
1987db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey            PLOG(ERROR) << "Failed recursive restorecon for " << path;
1997db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey            goto fail;
2007db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        }
2017db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    }
2027db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
2037db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    goto done;
2047db6041d156b750689b32e340d8a0753061262a3Jeff Sharkeyfail:
2057db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    res = -1;
2067db6041d156b750689b32e340d8a0753061262a3Jeff Sharkeydone:
2077db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    free(before);
2087db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    free(after);
2097db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    return res;
2107db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey}
2117db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
2120274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeystatic int restorecon_app_data_lazy(const std::string& parent, const char* name,
2130274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const std::string& seInfo, uid_t uid) {
2140274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
21595d9ac642f082870fd4d2419f534171a9b82bbcdJeff Sharkey}
21695d9ac642f082870fd4d2419f534171a9b82bbcdJeff Sharkey
2177db6041d156b750689b32e340d8a0753061262a3Jeff Sharkeystatic int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
2189a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey    if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
2199a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        PLOG(ERROR) << "Failed to prepare " << path;
2209a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        return -1;
2219a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey    }
2229a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey    return 0;
2239a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey}
2249a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey
2259a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkeystatic int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
2267db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        uid_t uid) {
2277db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey    return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
2289a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey}
2299a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey
2300274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeybinder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
2310274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2320274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const std::string& seInfo, int32_t targetSdkVersion) {
2330274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2340274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
2350274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2360274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* pkgname = packageName.c_str();
2370274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
2380274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    uid_t uid = multiuser_get_uid(userId, appId);
2390274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
240aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
2410274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
2427db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        if (prepare_app_dir(path, target_mode, uid) ||
2437db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey                prepare_app_dir(path, "cache", 0771, uid) ||
2447db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey                prepare_app_dir(path, "code_cache", 0771, uid)) {
2450274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
2467db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        }
2477db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
2487db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        // Consider restorecon over contents if label changed
2490274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        if (restorecon_app_data_lazy(path, seInfo, uid) ||
2500274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
2510274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
2520274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
253c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
2549a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey
2559a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        // Remember inode numbers of cache directories so that we can clear
2569a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        // contents while CE storage is locked
2579a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        if (write_path_inode(path, "cache", kXattrInodeCache) ||
2589a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey                write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
2590274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
260c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
26194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
262aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
2630274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
2647db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        if (prepare_app_dir(path, target_mode, uid)) {
265a03c747ff6e1afb5c1dc86560705bd979cd5c49fJeff Sharkey            // TODO: include result once 25796509 is fixed
2660274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            return binder::Status::ok();
267c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
2686a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
2697db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        // Consider restorecon over contents if label changed
2700274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        if (restorecon_app_data_lazy(path, seInfo, uid)) {
2710274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
2727db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey        }
2737db6041d156b750689b32e340d8a0753061262a3Jeff Sharkey
2746a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        if (property_get_bool("dalvik.vm.usejitprofiles")) {
2750274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey            const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
2766a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            // read-write-execute only for the app user.
2776a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
2786a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                PLOG(ERROR) << "Failed to prepare " << profile_path;
2790274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                return binder::Status::fromServiceSpecificError(-1);
2806a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            }
281bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle            std::string profile_file = create_primary_profile(profile_path);
282bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle            // read-write only for the app user.
283bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
284bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle                PLOG(ERROR) << "Failed to prepare " << profile_path;
2850274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                return binder::Status::fromServiceSpecificError(-1);
286bc56e7dcf07e633867e1525435373a1231216b22Calin Juravle            }
2876a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
2886a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
2896a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            // profiles.
2906a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
2916a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            if (fs_prepare_dir_strict(
2926a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
2936a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
2940274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                return binder::Status::fromServiceSpecificError(-1);
2956a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            }
2966a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
29794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
2980274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return binder::Status::ok();
29994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
30094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
301c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
302c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        const std::string& packageName, int32_t userId, int32_t flags) {
303c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
304c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
305c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* pkgname = packageName.c_str();
306c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey
307cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // This method only exists to upgrade system apps that have requested
308cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // forceDeviceEncrypted, so their default storage always lives in a
309cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // consistent location.  This only works on non-FBE devices, since we
310cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // never want to risk exposing data on a device with real CE/DE storage.
311cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
312c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
313c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
314cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
315cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // If neither directory is marked as default, assume CE is default
316cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
317cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
318cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
319cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey            PLOG(ERROR) << "Failed to mark default storage " << ce_path;
320c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
321cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        }
322cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    }
323cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
324cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    // Migrate default data location if needed
325cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
326cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
327cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
328cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
329cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        LOG(WARNING) << "Requested default storage " << target
330cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey                << " is not active; migrating from " << source;
331cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        if (delete_dir_contents_and_dir(target) != 0) {
332cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey            PLOG(ERROR) << "Failed to delete";
333c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
334cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        }
335cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        if (rename(source.c_str(), target.c_str()) != 0) {
336cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey            PLOG(ERROR) << "Failed to rename";
337c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
338cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey        }
339cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey    }
340cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
341c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return binder::Status::ok();
342cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey}
343cc6281cf8146cddb8ace7cbd58c67321639c1520Jeff Sharkey
344cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravlestatic bool clear_profile(const std::string& profile) {
34564b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain    base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
34664b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain    if (ufd.get() < 0) {
347278edac4b541e0a671d646a0e17bdbea411c8a08Calin Juravle        if (errno != ENOENT) {
348cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle            PLOG(WARNING) << "Could not open profile " << profile;
349d828d6839f6a01e3f0b2b8b2694139dfa801c557David Brazdil            return false;
350cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        } else {
351cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle            // Nothing to clear. That's ok.
352cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle            return true;
353278edac4b541e0a671d646a0e17bdbea411c8a08Calin Juravle        }
3546a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
355cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle
35664b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain    if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
357cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        if (errno != EWOULDBLOCK) {
358cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle            PLOG(WARNING) << "Error locking profile " << profile;
359cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        }
360cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // This implies that the app owning this profile is running
361cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // (and has acquired the lock).
362cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        //
363cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // If we can't acquire the lock bail out since clearing is useless anyway
364cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // (the app will write again to the profile).
365cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        //
366cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // Note:
367cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // This does not impact the this is not an issue for the profiling correctness.
368cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // In case this is needed because of an app upgrade, profiles will still be
369cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // eventually cleared by the app itself due to checksum mismatch.
370cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // If this is needed because profman advised, then keeping the data around
371cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // until the next run is again not an issue.
372cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        //
373cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // If the app attempts to acquire a lock while we've held one here,
374cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        // it will simply skip the current write cycle.
375cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        return false;
376cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    }
377cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle
37864b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain    bool truncated = ftruncate(ufd.get(), 0) == 0;
379cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    if (!truncated) {
380cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        PLOG(WARNING) << "Could not truncate " << profile;
381cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    }
38264b59cc1c89225813295d1b5d6bf4183615da204Roland Levillain    if (flock(ufd.get(), LOCK_UN) != 0) {
383cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        PLOG(WARNING) << "Error unlocking profile " << profile;
384cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    }
385cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    return truncated;
386cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle}
387cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle
388cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravlestatic bool clear_reference_profile(const char* pkgname) {
389cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
390cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    std::string reference_profile = create_primary_profile(reference_profile_dir);
391cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    return clear_profile(reference_profile);
3926a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
3936a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
394cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravlestatic bool clear_current_profile(const char* pkgname, userid_t user) {
395edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
396edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    std::string profile = create_primary_profile(profile_dir);
397cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    return clear_profile(profile);
398edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle}
399edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle
400cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravlestatic bool clear_current_profiles(const char* pkgname) {
401d828d6839f6a01e3f0b2b8b2694139dfa801c557David Brazdil    bool success = true;
4026a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
4036a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    for (auto user : users) {
404cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        success &= clear_current_profile(pkgname, user);
4056a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
406d828d6839f6a01e3f0b2b8b2694139dfa801c557David Brazdil    return success;
4076a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
4086a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
409475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
410475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
411475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* pkgname = packageName.c_str();
412d828d6839f6a01e3f0b2b8b2694139dfa801c557David Brazdil    bool success = true;
413cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    success &= clear_reference_profile(pkgname);
414cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    success &= clear_current_profiles(pkgname);
415475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
4166a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
4176a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
418c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
419c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
420c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
421c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
422c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* pkgname = packageName.c_str();
423c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey
424ebf728fd43ab5c7d11a1f9e5fdc775d6740fae0aJeff Sharkey    int res = 0;
425aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
426c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
4279a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        if (flags & FLAG_CLEAR_CACHE_ONLY) {
4289a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            path = read_path_inode(path, "cache", kXattrInodeCache);
4299a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
4309a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
4319a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        }
432c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        if (access(path.c_str(), F_OK) == 0) {
433c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey            res |= delete_dir_contents(path);
434c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
43594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
436aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
4379a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        std::string suffix = "";
4389a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        bool only_cache = false;
4399a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        if (flags & FLAG_CLEAR_CACHE_ONLY) {
4409a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            suffix = CACHE_DIR_POSTFIX;
4419a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            only_cache = true;
4429a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
4439a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            suffix = CODE_CACHE_DIR_POSTFIX;
4449a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey            only_cache = true;
4459a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey        }
4469a998f4762cb5ad71c786229be748ea0ab9eb7a0Jeff Sharkey
447c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
448c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        if (access(path.c_str(), F_OK) == 0) {
449a03c747ff6e1afb5c1dc86560705bd979cd5c49fJeff Sharkey            // TODO: include result once 25796509 is fixed
450a03c747ff6e1afb5c1dc86560705bd979cd5c49fJeff Sharkey            delete_dir_contents(path);
451c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
452edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle        if (!only_cache) {
453c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            if (!clear_current_profile(pkgname, userId)) {
454edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle                res |= -1;
455edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle            }
456edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle        }
45794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
458c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
459c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey}
46094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
4617535e8e1995398befc866062d63c05d90eb70cccCalin Juravlestatic int destroy_app_reference_profile(const char *pkgname) {
4627535e8e1995398befc866062d63c05d90eb70cccCalin Juravle    return delete_dir_contents_and_dir(
4637535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        create_data_ref_profile_package_path(pkgname),
4647535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        /*ignore_if_missing*/ true);
4657535e8e1995398befc866062d63c05d90eb70cccCalin Juravle}
4667535e8e1995398befc866062d63c05d90eb70cccCalin Juravle
467edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravlestatic int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
468b06f98aabc5381fd6366526d9b31b5d0345481b6Calin Juravle    return delete_dir_contents_and_dir(
469b06f98aabc5381fd6366526d9b31b5d0345481b6Calin Juravle        create_data_user_profile_package_path(userid, pkgname),
470b06f98aabc5381fd6366526d9b31b5d0345481b6Calin Juravle        /*ignore_if_missing*/ true);
471edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle}
472edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle
473475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
474475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
475475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* pkgname = packageName.c_str();
476edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    int result = 0;
477edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
478edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    for (auto user : users) {
479edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle        result |= destroy_app_current_profiles(pkgname, user);
480edae669f18eb99b9316891fdde627e2f385c3c64Calin Juravle    }
4817535e8e1995398befc866062d63c05d90eb70cccCalin Juravle    result |= destroy_app_reference_profile(pkgname);
482475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return result ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
483caa6b809a5ed024a8f3f551c5c109a5ad50ab772Calin Juravle}
484caa6b809a5ed024a8f3f551c5c109a5ad50ab772Calin Juravle
485c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
486c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
487c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
488c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
489c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* pkgname = packageName.c_str();
490c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey
491c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey    int res = 0;
492aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
493c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        res |= delete_dir_contents_and_dir(
494c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey                create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode));
49594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
496aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
497caa6b809a5ed024a8f3f551c5c109a5ad50ab772Calin Juravle        res |= delete_dir_contents_and_dir(
498c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey                create_data_user_de_package_path(uuid_, userId, pkgname));
499c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        destroy_app_current_profiles(pkgname, userId);
5007535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        // TODO(calin): If the package is still installed by other users it's probably
5017535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        // beneficial to keep the reference profile around.
5027535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        // Verify if it's ok to do that.
5037535e8e1995398befc866062d63c05d90eb70cccCalin Juravle        destroy_app_reference_profile(pkgname);
50494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
505c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
50694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
50794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
5080274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkeybinder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
5090274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
5100274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        const std::string& dataAppName, int32_t appId, const std::string& seInfo,
5110274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        int32_t targetSdkVersion) {
5120274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
5130274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
5140274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
5150274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* package_name = packageName.c_str();
5160274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    const char* data_app_name = dataAppName.c_str();
5170274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey
518e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    std::vector<userid_t> users = get_known_users(from_uuid);
519e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
520d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    // Copy app
521d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    {
52251c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        auto from = create_data_app_package_path(from_uuid, data_app_name);
52351c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        auto to = create_data_app_package_path(to_uuid, data_app_name);
52451c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        auto to_parent = create_data_app_path(to_uuid);
525d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
526d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        char *argv[] = {
527d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) kCpPath,
528d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
529d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) "-p", /* preserve timestamps, ownership, and permissions */
530d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
531d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) "-P", /* Do not follow symlinks [default] */
532d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) "-d", /* don't dereference symlinks */
533d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) from.c_str(),
534d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            (char*) to_parent.c_str()
535d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        };
536d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
537d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        LOG(DEBUG) << "Copying " << from << " to " << to;
538d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
539d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
540d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        if (rc != 0) {
541d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            LOG(ERROR) << "Failed copying " << from << " to " << to
542d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey                    << ": status " << rc;
543d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            goto fail;
544d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        }
545d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
546d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
547d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            LOG(ERROR) << "Failed to restorecon " << to;
548d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            goto fail;
549d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        }
550d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    }
551d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
552d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    // Copy private data for all known users
553e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    for (auto user : users) {
554e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
555e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        // Data source may not exist for all users; that's okay
55651c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
55751c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        if (access(from_ce.c_str(), F_OK) != 0) {
55851c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            LOG(INFO) << "Missing source " << from_ce;
559e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            continue;
560e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        }
561e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
5620274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey        if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
5630274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey                seInfo, targetSdkVersion).isOk()) {
56451c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            LOG(ERROR) << "Failed to create package target on " << to_uuid;
565e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            goto fail;
566e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        }
567e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
568e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        char *argv[] = {
569e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) kCpPath,
570e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
571e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) "-p", /* preserve timestamps, ownership, and permissions */
572e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
573e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) "-P", /* Do not follow symlinks [default] */
574e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey            (char*) "-d", /* don't dereference symlinks */
57551c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            nullptr,
57651c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            nullptr
577e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        };
578e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
57951c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        {
58051c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
58151c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto to = create_data_user_de_path(to_uuid, user);
58251c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            argv[6] = (char*) from.c_str();
58351c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            argv[7] = (char*) to.c_str();
58451c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey
58551c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            LOG(DEBUG) << "Copying " << from << " to " << to;
58651c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
58751c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            if (rc != 0) {
58851c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
58951c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                goto fail;
59051c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            }
59151c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        }
59251c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        {
59351c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
59451c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto to = create_data_user_ce_path(to_uuid, user);
59551c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            argv[6] = (char*) from.c_str();
59651c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            argv[7] = (char*) to.c_str();
59751c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey
59851c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            LOG(DEBUG) << "Copying " << from << " to " << to;
59951c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
60051c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            if (rc != 0) {
60151c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
60251c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                goto fail;
60351c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            }
604e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        }
605e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
606c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
607c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey                appId, seInfo).isOk()) {
608c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey            LOG(ERROR) << "Failed to restorecon";
609c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey            goto fail;
610c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        }
611e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    }
612e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
61331f08986f83fa6f2dcf55523b2cf706460aeed7cJeff Sharkey    // We let the framework scan the new location and persist that before
61431f08986f83fa6f2dcf55523b2cf706460aeed7cJeff Sharkey    // deleting the data in the old location; this ordering ensures that
61531f08986f83fa6f2dcf55523b2cf706460aeed7cJeff Sharkey    // we can recover from things like battery pulls.
6160274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return binder::Status::ok();
617e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
618e36372423000a906bafae68844ebc6c42d09335aJeff Sharkeyfail:
619e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    // Nuke everything we might have already copied
620d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    {
62151c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        auto to = create_data_app_package_path(to_uuid, data_app_name);
622d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
623d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey            LOG(WARNING) << "Failed to rollback " << to;
624d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey        }
625d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey    }
626e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    for (auto user : users) {
62751c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        {
62851c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
62951c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
63051c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                LOG(WARNING) << "Failed to rollback " << to;
63151c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            }
63251c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        }
63351c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey        {
63451c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
63551c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
63651c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey                LOG(WARNING) << "Failed to rollback " << to;
63751c94495be151c1da03c8266592ed33f253d4b48Jeff Sharkey            }
638e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey        }
639e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey    }
6400274c977e3b10b52936fd5b2eb464857f0ca6358Jeff Sharkey    return binder::Status::fromServiceSpecificError(-1);
641e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey}
642e36372423000a906bafae68844ebc6c42d09335aJeff Sharkey
643c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
644c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
645c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
646c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
647c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    int res = 0;
648379a12b0072b322c7f86e690a8e8a220e500861cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
649c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        if (uuid_ == nullptr) {
650c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            res = ensure_config_user_dirs(userId);
651379a12b0072b322c7f86e690a8e8a220e500861cJeff Sharkey        }
65294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
653c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
654095c763dd9aa26a206d10ab7c1d7e1c569298fb3Robin Lee}
655095c763dd9aa26a206d10ab7c1d7e1c569298fb3Robin Lee
656c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
657c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        int32_t userId, int32_t flags) {
658c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
659c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
660ebf728fd43ab5c7d11a1f9e5fdc775d6740fae0aJeff Sharkey    int res = 0;
661379a12b0072b322c7f86e690a8e8a220e500861cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
662c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        res |= delete_dir_contents_and_dir(create_data_user_de_path(uuid_, userId), true);
663c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        if (uuid_ == nullptr) {
664c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            res |= delete_dir_contents_and_dir(create_data_misc_legacy_path(userId), true);
665c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey            res |= delete_dir_contents_and_dir(create_data_user_profiles_path(userId), true);
66641ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkey        }
66794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
668379a12b0072b322c7f86e690a8e8a220e500861cJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
669c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        res |= delete_dir_contents_and_dir(create_data_user_ce_path(uuid_, userId), true);
670c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        res |= delete_dir_contents_and_dir(create_data_media_path(uuid_, userId), true);
671379a12b0072b322c7f86e690a8e8a220e500861cJeff Sharkey    }
672c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
67394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
67494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
67594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood/* Try to ensure free_size bytes of storage are available.
67694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * Returns 0 on success.
67794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * This is rather simple-minded because doing a full LRU would
67894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * be potentially memory-intensive, and without atime it would
67994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * also require that apps constantly modify file metadata even
68094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * when just reading from the cache, which is pretty awful.
68194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood */
682475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
683475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        int64_t freeStorageSize) {
684475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
685475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
68694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    cache_t* cache;
68794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int64_t avail;
68894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
689475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    auto data_path = create_data_path(uuid_);
69041ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkey
69141ea424413c0381ef2aa15fc5bd5d4b88abd23c4Jeff Sharkey    avail = data_disk_free(data_path);
692475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (avail < 0) {
693475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
694475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
69594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
696475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
697475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (avail >= freeStorageSize) {
698475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
699475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
70094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
70194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    cache = start_cache_collection();
70294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
703475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    auto users = get_known_users(uuid_);
70454e292e1ea87b504b552393d2e9bc800458bd0c1Jeff Sharkey    for (auto user : users) {
705475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        add_cache_files(cache, create_data_user_ce_path(uuid_, user));
706475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        add_cache_files(cache, create_data_user_de_path(uuid_, user));
70754e292e1ea87b504b552393d2e9bc800458bd0c1Jeff Sharkey        add_cache_files(cache,
708475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey                StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
70994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
71094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
711475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    clear_cache_files(data_path, cache, freeStorageSize);
71294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    finish_cache_collection(cache);
71394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
714475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (data_disk_free(data_path) >= freeStorageSize) {
715475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
716475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    } else {
717475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
718475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
71994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
72094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
721475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::rmdex(const std::string& codePath,
722475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& instructionSet) {
723475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
72494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    char dex_path[PKG_PATH_MAX];
72594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
726475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* path = codePath.c_str();
727475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* instruction_set = instructionSet.c_str();
728475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey
729770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey    if (validate_apk_path(path) && validate_system_app_path(path)) {
730770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey        ALOGE("invalid apk path '%s' (bad prefix)\n", path);
731475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
732770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey    }
733770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey
734475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (!create_cache_path(dex_path, path, instruction_set)) {
735475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
736475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
73794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
73894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGV("unlink %s\n", dex_path);
73994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (unlink(dex_path) < 0) {
740770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey        if (errno != ENOENT) {
741770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey            ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
742770180a4dd86f8bda6af2e6db4676e99a5bb1548Jeff Sharkey        }
743475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
74494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    } else {
745475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
74694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
74794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
74894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7492f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkeystatic void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
7502f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        int64_t *cachesize) {
75194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    DIR *d;
75294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int dfd;
75394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    struct dirent *de;
75494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    struct stat s;
755d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
7562f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    d = opendir(path.c_str());
7572f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    if (d == nullptr) {
7582f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        PLOG(WARNING) << "Failed to open " << path;
7592f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        return;
76094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
7612f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    dfd = dirfd(d);
7622f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    while ((de = readdir(d))) {
7632f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        const char *name = de->d_name;
764d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
7652f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        int64_t statsize = 0;
7662f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
7672f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            statsize = stat_size(&s);
76894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
76994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7702f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        if (de->d_type == DT_DIR) {
7712f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            int subfd;
7722f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            int64_t dirsize = 0;
7732f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            /* always skip "." and ".." */
7742f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            if (name[0] == '.') {
7752f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                if (name[1] == 0) continue;
7762f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                if ((name[1] == '.') && (name[2] == 0)) continue;
7772f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            }
7782f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
7792f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            if (subfd >= 0) {
7802f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                dirsize = calculate_dir_size(subfd);
7812f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                close(subfd);
7822f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            }
7832f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            // TODO: check xattrs!
7842f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
7852f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                *datasize += statsize;
7862f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                *cachesize += dirsize;
7872f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            } else {
7882f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey                *datasize += dirsize + statsize;
7892f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            }
7902f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
7912f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            *codesize += statsize;
7922f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        } else {
7932f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey            *datasize += statsize;
79494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
79594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
7962f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    closedir(d);
7972f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey}
79894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7992f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkeyint get_app_size(const char *uuid, const char *pkgname, int userid, int flags, ino_t ce_data_inode,
8002f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        const char *code_path, int64_t *codesize, int64_t *datasize, int64_t *cachesize,
8012f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        int64_t* asecsize) {
8022f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    DIR *d;
8032f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    int dfd;
80494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8052f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    d = opendir(code_path);
8062f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    if (d != nullptr) {
8072f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        dfd = dirfd(d);
8082f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        *codesize += calculate_dir_size(dfd);
8092f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        closedir(d);
81094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
81194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8122f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
8132f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        auto path = create_data_user_ce_package_path(uuid, userid, pkgname, ce_data_inode);
8142f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        add_app_data_size(path, codesize, datasize, cachesize);
8152f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    }
8162f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
8172f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        auto path = create_data_user_de_package_path(uuid, userid, pkgname);
8182f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey        add_app_data_size(path, codesize, datasize, cachesize);
8192f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    }
82094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8212f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    *asecsize = 0;
822d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
8232f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    return 0;
8242f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey}
825d792118c493806eeb24a8203f508e6e18fe93bd7Jeff Sharkey
826c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
827c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
828c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
829c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
830c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* pkgname = packageName.c_str();
831c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey
832c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    int res = 0;
8332f720f7ec5c9d0b91defc85878e7330b10f8e89aJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
834c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
835c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        res = get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return));
83694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
837c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
83894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
83994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
840b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Roubanstatic int split_count(const char *str)
841b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban{
842b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  char *ctx;
843b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  int count = 0;
84402d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe  char buf[kPropertyValueMax];
845b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
846b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  strncpy(buf, str, sizeof(buf));
847b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  char *pBuf = buf;
848b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
849b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  while(strtok_r(pBuf, " ", &ctx) != NULL) {
850b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    count++;
851b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    pBuf = NULL;
852b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  }
853b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
854b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  return count;
855b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban}
856b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
85714e084d39ac44e9d4d0a0143bf1f111011343d34neo.chaestatic int split(char *buf, const char **argv)
858b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban{
859b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  char *ctx;
860b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  int count = 0;
861b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  char *tok;
862b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  char *pBuf = buf;
863b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
864b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
865b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    argv[count++] = tok;
866b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    pBuf = NULL;
867b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  }
868b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
869b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban  return count;
870b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban}
871b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban
872fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdilstatic void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
873fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const char* input_oat_file_name, const char* input_vdex_file_name,
874fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const char* output_oat_file_name, const char* output_vdex_file_name,
875fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
8767365a10689df23334d245b211ce272502ad20669Alex Light{
8777365a10689df23334d245b211ce272502ad20669Alex Light    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
8788fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
8797365a10689df23334d245b211ce272502ad20669Alex Light
8807365a10689df23334d245b211ce272502ad20669Alex Light    static const char* PATCHOAT_BIN = "/system/bin/patchoat";
8817365a10689df23334d245b211ce272502ad20669Alex Light    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
8827365a10689df23334d245b211ce272502ad20669Alex Light        ALOGE("Instruction set %s longer than max length of %d",
8837365a10689df23334d245b211ce272502ad20669Alex Light              instruction_set, MAX_INSTRUCTION_SET_LEN);
8847365a10689df23334d245b211ce272502ad20669Alex Light        return;
8857365a10689df23334d245b211ce272502ad20669Alex Light    }
8867365a10689df23334d245b211ce272502ad20669Alex Light
8877365a10689df23334d245b211ce272502ad20669Alex Light    /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
8887365a10689df23334d245b211ce272502ad20669Alex Light    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
8897365a10689df23334d245b211ce272502ad20669Alex Light    char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
890fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
891fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
892fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
8937365a10689df23334d245b211ce272502ad20669Alex Light    const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
8947365a10689df23334d245b211ce272502ad20669Alex Light    // The caller has already gotten all the locks we need.
8957365a10689df23334d245b211ce272502ad20669Alex Light    const char* no_lock_arg = "--no-lock-output";
8967365a10689df23334d245b211ce272502ad20669Alex Light    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
897fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
898fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
899fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
900fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
901fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          PATCHOAT_BIN, instruction_set,
902fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          input_oat_fd, input_oat_file_name,
903fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          input_vdex_fd, input_vdex_file_name,
904fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          out_oat_fd, output_oat_file_name,
905fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil          out_vdex_fd, output_vdex_file_name);
9067365a10689df23334d245b211ce272502ad20669Alex Light
9077365a10689df23334d245b211ce272502ad20669Alex Light    /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
908fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    char* argv[9];
9097365a10689df23334d245b211ce272502ad20669Alex Light    argv[0] = (char*) PATCHOAT_BIN;
9107365a10689df23334d245b211ce272502ad20669Alex Light    argv[1] = (char*) patched_image_location_arg;
9117365a10689df23334d245b211ce272502ad20669Alex Light    argv[2] = (char*) no_lock_arg;
9127365a10689df23334d245b211ce272502ad20669Alex Light    argv[3] = instruction_set_arg;
913fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    argv[4] = input_oat_fd_arg;
914fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    argv[5] = input_vdex_fd_arg;
915fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    argv[6] = output_oat_fd_arg;
916fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    argv[7] = output_vdex_fd_arg;
917fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    argv[8] = NULL;
9187365a10689df23334d245b211ce272502ad20669Alex Light
9197365a10689df23334d245b211ce272502ad20669Alex Light    execv(PATCHOAT_BIN, (char* const *)argv);
9207365a10689df23334d245b211ce272502ad20669Alex Light    ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
9217365a10689df23334d245b211ce272502ad20669Alex Light}
9227365a10689df23334d245b211ce272502ad20669Alex Light
92353caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffraystatic void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
924fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        const char* input_file_name, const char* output_file_name, int swap_fd,
925fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
926fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
9278fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
9288fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle
9298fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
9308fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle        ALOGE("Instruction set %s longer than max length of %d",
9318fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle              instruction_set, MAX_INSTRUCTION_SET_LEN);
9328fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle        return;
9338fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    }
9348fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle
93502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_Xms_flag[kPropertyValueMax];
93602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
937e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom
93802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_Xmx_flag[kPropertyValueMax];
93902d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
940e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom
94102d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_threads_buf[kPropertyValueMax];
94202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_dex2oat_threads_flag = get_property(post_bootcomplete
943919461cbeef3e9f35388fc099a5fcdae1cb79cc6Andreas Gampe                                                      ? "dalvik.vm.dex2oat-threads"
944919461cbeef3e9f35388fc099a5fcdae1cb79cc6Andreas Gampe                                                      : "dalvik.vm.boot-dex2oat-threads",
945919461cbeef3e9f35388fc099a5fcdae1cb79cc6Andreas Gampe                                                  dex2oat_threads_buf,
946919461cbeef3e9f35388fc099a5fcdae1cb79cc6Andreas Gampe                                                  NULL) > 0;
94702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_threads_arg[kPropertyValueMax + 2];
9488d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe    if (have_dex2oat_threads_flag) {
9498d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe        sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
9508d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe    }
9518d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe
95202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_isa_features_key[kPropertyKeyMax];
9538fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
95402d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_isa_features[kPropertyValueMax];
95502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
9568fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle                                                  dex2oat_isa_features, NULL) > 0;
9578fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle
95802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_isa_variant_key[kPropertyKeyMax];
95916a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers    sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
96002d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_isa_variant[kPropertyValueMax];
96102d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
96216a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers                                                 dex2oat_isa_variant, NULL) > 0;
96316a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers
96414e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    const char *dex2oat_norelocation = "-Xnorelocate";
96514e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    bool have_dex2oat_relocation_skip_flag = false;
96614e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae
96702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_flags[kPropertyValueMax];
96802d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
969b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban                                 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
9700ae8e39ebcc26836ba55a5ee4481825a0f473a9eBrian Carlstrom    ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
9710ae8e39ebcc26836ba55a5ee4481825a0f473a9eBrian Carlstrom
972538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom    // If we booting without the real /data, don't spend time compiling.
97302d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char vold_decrypt[kPropertyValueMax];
97402d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
975538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom    bool skip_compilation = (have_vold_decrypt &&
976538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom                             (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
977538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom                             (strcmp(vold_decrypt, "1") == 0)));
978538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom
9796a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    bool generate_debug_info = property_get_bool("debug.generate-debug-info");
980d4a7b459f4f383988440c0512513b321ce03fc22Mathieu Chartier
981416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    char app_image_format[kPropertyValueMax];
982416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
983416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    bool have_app_image_format =
98441fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier            image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
985416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    if (have_app_image_format) {
986416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier        sprintf(image_format_arg, "--image-format=%s", app_image_format);
987416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    }
988416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier
989a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    char dex2oat_large_app_threshold[kPropertyValueMax];
990a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    bool have_dex2oat_large_app_threshold =
991a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe            get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
992a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
993a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    if (have_dex2oat_large_app_threshold) {
994a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe        sprintf(dex2oat_large_app_threshold_arg,
995a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe                "--very-large-app-threshold=%s",
996a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe                dex2oat_large_app_threshold);
997a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    }
998a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe
9991705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
100053e0776d967324e2908e3be56b80cddb2c9d9e03Brian Carlstrom
100153e0776d967324e2908e3be56b80cddb2c9d9e03Brian Carlstrom    static const char* RUNTIME_ARG = "--runtime-arg";
100253e0776d967324e2908e3be56b80cddb2c9d9e03Brian Carlstrom
10031705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
10041b4003207750ea8fe8c7b03eb32d80f1df83979eNarayan Kamath
10051705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
10061705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
100753caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
100853caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
10091705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
10107195fcc2185c35b45a8f28c79fde4999b38850e8Brian Carlstrom    char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
10111b4003207750ea8fe8c7b03eb32d80f1df83979eNarayan Kamath    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
101202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
101302d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
101402d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
101502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
101602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
1017e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    bool have_dex2oat_swap_fd = false;
1018e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
1019edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    bool have_dex2oat_image_fd = false;
1020edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
10211705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom
10221705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
10231705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
102453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
102553caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
10261705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
10271705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
10281b4003207750ea8fe8c7b03eb32d80f1df83979eNarayan Kamath    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
102916a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers    sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
10308fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
1031e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    if (swap_fd >= 0) {
1032e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        have_dex2oat_swap_fd = true;
1033e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1034e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    }
1035edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    if (image_fd >= 0) {
1036edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        have_dex2oat_image_fd = true;
1037edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1038edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    }
103957c69c39640a7d6a08b3afb56361d76f7ecf1250Calin Juravle
1040e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    if (have_dex2oat_Xms_flag) {
1041e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom        sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1042e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    }
1043e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    if (have_dex2oat_Xmx_flag) {
1044e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom        sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1045e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    }
10464d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe
10474d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    // Compute compiler filter.
10484d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe
10494d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    bool have_dex2oat_compiler_filter_flag;
1050538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom    if (skip_compilation) {
1051e18987efb5e39ca1bed15527b7b82bde55c99669Brian Carlstrom        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
1052538998f204d1e542e235de9e7ce18ef4dc68c9ccBrian Carlstrom        have_dex2oat_compiler_filter_flag = true;
105314e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae        have_dex2oat_relocation_skip_flag = true;
1054b1efac103523efccbe671e76cc0eaaeab810415bCalin Juravle    } else if (vm_safe_mode) {
1055b1efac103523efccbe671e76cc0eaaeab810415bCalin Juravle        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
105697477d203eaf0c3235bbe2415356f20a0431cadaCalin Juravle        have_dex2oat_compiler_filter_flag = true;
10574d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    } else if (compiler_filter != nullptr &&
10584d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe            strlen(compiler_filter) + strlen("--compiler-filter=") <
10594d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe                    arraysize(dex2oat_compiler_filter_arg)) {
10604d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1061d4a7b459f4f383988440c0512513b321ce03fc22Mathieu Chartier        have_dex2oat_compiler_filter_flag = true;
10624d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    } else {
10634d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        char dex2oat_compiler_filter_flag[kPropertyValueMax];
10644d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
10654d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe                                                         dex2oat_compiler_filter_flag, NULL) > 0;
10664d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        if (have_dex2oat_compiler_filter_flag) {
10674d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe            sprintf(dex2oat_compiler_filter_arg,
10684d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe                    "--compiler-filter=%s",
10694d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe                    dex2oat_compiler_filter_flag);
10704d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        }
1071cf51ba1360ee13459830a0502b0d454d0145544fBrian Carlstrom    }
1072e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom
1073598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe    // Check whether all apps should be compiled debuggable.
1074598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe    if (!debuggable) {
107502d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe        char prop_buf[kPropertyValueMax];
1076598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe        debuggable =
107702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe                (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
1078598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe                (prop_buf[0] == '1');
1079598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe    }
10806a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
10816a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profile_fd != -1) {
10826a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
108360a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
1084598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe
10856a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
10861705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
10874fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle
108853caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    const char* argv[9  // program name, mandatory arguments and the final NULL
108914e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_isa_variant ? 1 : 0)
109014e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_isa_features ? 1 : 0)
109114e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_Xms_flag ? 2 : 0)
109214e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_Xmx_flag ? 2 : 0)
109314e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_compiler_filter_flag ? 1 : 0)
10948d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe                     + (have_dex2oat_threads_flag ? 1 : 0)
109514e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_swap_fd ? 1 : 0)
1096edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier                     + (have_dex2oat_image_fd ? 1 : 0)
109714e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae                     + (have_dex2oat_relocation_skip_flag ? 2 : 0)
1098528c8ddc60df7b3d291b389117e4db878a20ad48David Srbecky                     + (generate_debug_info ? 1 : 0)
1099598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe                     + (debuggable ? 1 : 0)
1100416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier                     + (have_app_image_format ? 1 : 0)
110160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle                     + dex2oat_flags_count
1102b63d91fd2737680351876406277b6c759f4db33cJeff Hao                     + (profile_fd == -1 ? 0 : 1)
1103a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe                     + (shared_libraries != nullptr ? 4 : 0)
1104a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe                     + (have_dex2oat_large_app_threshold ? 1 : 0)];
11054fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    int i = 0;
110614e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    argv[i++] = DEX2OAT_BIN;
11074fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i++] = zip_fd_arg;
11084fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i++] = zip_location_arg;
110953caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    argv[i++] = input_vdex_fd_arg;
111053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    argv[i++] = output_vdex_fd_arg;
11114fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i++] = oat_fd_arg;
11124fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i++] = oat_location_arg;
11134fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i++] = instruction_set_arg;
111416a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers    if (have_dex2oat_isa_variant) {
111516a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers        argv[i++] = instruction_set_variant_arg;
111616a95b267ac6aac75453f65f1bc382ce65c0741eIan Rogers    }
11178fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    if (have_dex2oat_isa_features) {
11188fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle        argv[i++] = instruction_set_features_arg;
11198fc7315a67fdbf9b56cc6fa061f0773be2223a81Calin Juravle    }
1120e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    if (have_dex2oat_Xms_flag) {
112114e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae        argv[i++] = RUNTIME_ARG;
1122e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom        argv[i++] = dex2oat_Xms_arg;
1123e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    }
1124e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    if (have_dex2oat_Xmx_flag) {
112514e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae        argv[i++] = RUNTIME_ARG;
1126e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom        argv[i++] = dex2oat_Xmx_arg;
1127e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    }
1128cf51ba1360ee13459830a0502b0d454d0145544fBrian Carlstrom    if (have_dex2oat_compiler_filter_flag) {
1129cf51ba1360ee13459830a0502b0d454d0145544fBrian Carlstrom        argv[i++] = dex2oat_compiler_filter_arg;
1130cf51ba1360ee13459830a0502b0d454d0145544fBrian Carlstrom    }
11318d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe    if (have_dex2oat_threads_flag) {
11328d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe        argv[i++] = dex2oat_threads_arg;
11338d7af8b2418cc5e7e59746f0cb359a75ed0bdfd1Andreas Gampe    }
1134e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    if (have_dex2oat_swap_fd) {
1135e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        argv[i++] = dex2oat_swap_fd;
1136e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    }
1137edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    if (have_dex2oat_image_fd) {
1138edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        argv[i++] = dex2oat_image_fd;
1139edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    }
1140528c8ddc60df7b3d291b389117e4db878a20ad48David Srbecky    if (generate_debug_info) {
1141528c8ddc60df7b3d291b389117e4db878a20ad48David Srbecky        argv[i++] = "--generate-debug-info";
11423822b8b79cf533ee8573794176838406c32a1c20Andreas Gampe    }
1143598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe    if (debuggable) {
1144598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe        argv[i++] = "--debuggable";
1145598c25e23f7c97470e09a2316513ddf2efdfb670Andreas Gampe    }
1146416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    if (have_app_image_format) {
1147416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier        argv[i++] = image_format_arg;
1148416fa12cd0949c7f12e2067b36ac7ac64ba70b4aMathieu Chartier    }
1149a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    if (have_dex2oat_large_app_threshold) {
1150a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe        argv[i++] = dex2oat_large_app_threshold_arg;
1151a5cc10a8e8d47fd01c117cc51ac1f6765a1735ceAndreas Gampe    }
1152b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    if (dex2oat_flags_count) {
1153b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban        i += split(dex2oat_flags, argv + i);
11544fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    }
115514e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    if (have_dex2oat_relocation_skip_flag) {
115614e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae        argv[i++] = RUNTIME_ARG;
115714e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae        argv[i++] = dex2oat_norelocation;
115814e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    }
11596a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profile_fd != -1) {
11606a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        argv[i++] = profile_arg;
116160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
1162b63d91fd2737680351876406277b6c759f4db33cJeff Hao    if (shared_libraries != nullptr) {
1163b63d91fd2737680351876406277b6c759f4db33cJeff Hao        argv[i++] = RUNTIME_ARG;
1164b63d91fd2737680351876406277b6c759f4db33cJeff Hao        argv[i++] = "-classpath";
1165b63d91fd2737680351876406277b6c759f4db33cJeff Hao        argv[i++] = RUNTIME_ARG;
1166b63d91fd2737680351876406277b6c759f4db33cJeff Hao        argv[i++] = shared_libraries;
1167b63d91fd2737680351876406277b6c759f4db33cJeff Hao    }
1168e46a75a0f6007967cd0d161959af844772cdc330Brian Carlstrom    // Do not add after dex2oat_flags, they should override others for debugging.
11694fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle    argv[i] = NULL;
11704fdff4616699708e58d875273c3c1a85ba4c63bdCalin Juravle
117114e084d39ac44e9d4d0a0143bf1f111011343d34neo.chae    execv(DEX2OAT_BIN, (char * const *)argv);
1172b0d8d00b2916aef7b01ad42f6d441f5b46b7731aYevgeny Rouban    ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
11731705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom}
11741705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom
1175e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe/*
1176c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * Whether dexopt should use a swap file when compiling an APK.
1177c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe *
1178c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1179c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * itself, anyways).
1180c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe *
1181c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1182c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe *
1183c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * Otherwise, return true if this is a low-mem device.
1184c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe *
1185c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe * Otherwise, return default value.
1186e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe */
1187c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampestatic bool kAlwaysProvideSwapFile = false;
1188c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampestatic bool kDefaultProvideSwapFile = true;
1189e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe
1190e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampestatic bool ShouldUseSwapFileForDexopt() {
1191e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    if (kAlwaysProvideSwapFile) {
1192e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        return true;
1193e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    }
1194e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe
1195c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    // Check the "override" property. If it exists, return value == "true".
119602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    char dex2oat_prop_buf[kPropertyValueMax];
119702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe    if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
1198c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe        if (strcmp(dex2oat_prop_buf, "true") == 0) {
1199c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe            return true;
1200c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe        } else {
1201c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe            return false;
1202c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe        }
1203c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    }
1204c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe
1205c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    // Shortcut for default value. This is an implementation optimization for the process sketched
1206c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1207c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    // as low-mem is never returning false. The compiler will optimize this away if it can.
1208c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    if (kDefaultProvideSwapFile) {
1209c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe        return true;
1210c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    }
1211c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe
12126a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    bool is_low_mem = property_get_bool("ro.config.low_ram");
1213c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    if (is_low_mem) {
1214c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe        return true;
1215c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    }
1216c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe
1217c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    // Default value must be false here.
1218c968c0175e967e39e72f557b5e014b9575ba4727Andreas Gampe    return kDefaultProvideSwapFile;
1219e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe}
1220e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe
122194dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampestatic void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
122294dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe    if (set_to_bg) {
122394dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe        if (set_sched_policy(0, SP_BACKGROUND) < 0) {
122494dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe            ALOGE("set_sched_policy failed: %s\n", strerror(errno));
122594dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe            exit(70);
122694dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe        }
122794dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
122894dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe            ALOGE("setpriority failed: %s\n", strerror(errno));
122994dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe            exit(71);
123094dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe        }
123194dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe    }
123294dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe}
123394dd3d3c5be4de57278ee668218a3464585795c0Andreas Gampe
12346a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
123560a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    for (size_t i = 0; i < fds.size(); i++) {
123660a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        if (close(fds[i]) != 0) {
123760a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle            PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
123860a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        }
123960a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
124060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle}
124160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
12426a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic fd_t open_profile_dir(const std::string& profile_dir) {
12436a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
12446a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
12456a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profile_dir_fd < 0) {
12462e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath        // In a multi-user environment, these directories can be created at
12472e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath        // different points and it's possible we'll attempt to open a profile
12482e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath        // dir before it exists.
12492e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath        if (errno != ENOENT) {
12502e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath            PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
12512e063af1651976b50e2da58c4d57564d878ab9c2Narayan Kamath        }
125260a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
12536a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return profile_dir_fd;
125460a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle}
125560a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
12566a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
12576a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    fd_t profile_dir_fd  = open_profile_dir(profile_dir);
12586a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profile_dir_fd < 0) {
12596a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return -1;
12606a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
12616a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
12626a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    fd_t profile_fd = -1;
12636a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::string profile_file = create_primary_profile(profile_dir);
12646a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
12656a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
12666a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profile_fd == -1) {
12676a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // It's not an error if the profile file does not exist.
126860a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        if (errno != ENOENT) {
12696a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
127060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        }
127160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
12726a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // TODO(calin): use AutoCloseFD instead of closing the fd manually.
12736a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (close(profile_dir_fd) != 0) {
12746a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        PLOG(WARNING) << "Could not close profile dir " << profile_dir;
12756a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
12766a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return profile_fd;
12776a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
127860a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
12796a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
12806a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
12816a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
12826a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
12836a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
12846a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
12856a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
12866a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
12876a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
12886a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (fd < 0) {
12896a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return -1;
129060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
12916a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (read_write) {
12926a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // Fix the owner.
12936a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        if (fchown(fd, uid, uid) < 0) {
12946a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            close(fd);
12956a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            return -1;
12966a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
12976a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
12986a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return fd;
12996a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
130060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
13016a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic void open_profile_files(uid_t uid, const char* pkgname,
13026a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
13036a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // Open the reference profile in read-write mode as profman might need to save the merge.
13046a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
130560a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    if (*reference_profile_fd < 0) {
13066a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // We can't access the reference profile file.
130760a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        return;
130860a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
13096a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13106a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
13116a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    for (auto user : users) {
13126a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        fd_t profile_fd = open_primary_profile_file(user, pkgname);
13136a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // Add to the lists only if both fds are valid.
13146a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        if (profile_fd >= 0) {
13156a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            profiles_fd->push_back(profile_fd);
13166a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
13176a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
13186a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
13196a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13206a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic void drop_capabilities(uid_t uid) {
13216a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (setgid(uid) != 0) {
13226a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
13236a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        exit(64);
13246a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
13256a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (setuid(uid) != 0) {
13266a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
13276a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        exit(65);
13286a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
13296a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // drop capabilities
13306a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    struct __user_cap_header_struct capheader;
13316a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    struct __user_cap_data_struct capdata[2];
13326a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    memset(&capheader, 0, sizeof(capheader));
13336a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    memset(&capdata, 0, sizeof(capdata));
13346a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    capheader.version = _LINUX_CAPABILITY_VERSION_3;
13356a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (capset(&capheader, &capdata[0]) < 0) {
13366a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        ALOGE("capset failed: %s\n", strerror(errno));
13376a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        exit(66);
133860a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
133960a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle}
134060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
13416a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
13426a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
13436a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
13446a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
13456a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
13466a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13476727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehrstatic void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
13486a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    static const size_t MAX_INT_LEN = 32;
13496a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    static const char* PROFMAN_BIN = "/system/bin/profman";
13506a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13516a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::vector<std::string> profile_args(profiles_fd.size());
13526a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
13536a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    for (size_t k = 0; k < profiles_fd.size(); k++) {
13546a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
13556a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        profile_args[k].assign(profile_buf);
13566a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
13576a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
13586a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
13596a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13606a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // program name, reference profile fd, the final NULL and the profile fds
13616a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    const char* argv[3 + profiles_fd.size()];
13626a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    int i = 0;
13636a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    argv[i++] = PROFMAN_BIN;
13646a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    argv[i++] = reference_profile_arg;
13656a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    for (size_t k = 0; k < profile_args.size(); k++) {
13666a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        argv[i++] = profile_args[k].c_str();
13676a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
13686a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // Do not add after dex2oat_flags, they should override others for debugging.
13696a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    argv[i] = NULL;
13706a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13716a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    execv(PROFMAN_BIN, (char * const *)argv);
13726a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
13736a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    exit(68);   /* only get here on exec failure */
13746a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
13756a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13766a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle// Decides if profile guided compilation is needed or not based on existing profiles.
13776a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle// Returns true if there is enough information in the current profiles that worth
13786a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle// a re-compilation of the package.
13796a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle// If the return value is true all the current profiles would have been merged into
13806a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle// the reference profiles accessible with open_reference_profile().
13816a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic bool analyse_profiles(uid_t uid, const char* pkgname) {
13826a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    std::vector<fd_t> profiles_fd;
13836a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    fd_t reference_profile_fd = -1;
13846a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
13856a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (profiles_fd.empty() || (reference_profile_fd == -1)) {
13866a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // Skip profile guided compilation because no profiles were found.
13876a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        // Or if the reference profile info couldn't be opened.
13886a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        close_all_fds(profiles_fd, "profiles_fd");
13896a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
13906a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            PLOG(WARNING) << "Failed to close fd for reference profile";
139160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        }
13926a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return false;
13936a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
139460a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
13956727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
13966a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
13976a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    pid_t pid = fork();
13986a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (pid == 0) {
13996a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        /* child -- drop privileges before continuing */
14006a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        drop_capabilities(uid);
14016727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        run_profman_merge(profiles_fd, reference_profile_fd);
14026a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        exit(68);   /* only get here on exec failure */
14036a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
14046a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    /* parent */
14056a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    int return_code = wait_child(pid);
14066a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    bool need_to_compile = false;
1407cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    bool should_clear_current_profiles = false;
1408cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    bool should_clear_reference_profile = false;
14096a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (!WIFEXITED(return_code)) {
14106a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
14116a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    } else {
14126a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return_code = WEXITSTATUS(return_code);
14136a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        switch (return_code) {
14146a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            case PROFMAN_BIN_RETURN_CODE_COMPILE:
14156a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                need_to_compile = true;
1416cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_current_profiles = true;
1417cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_reference_profile = false;
14186a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                break;
14196a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
14206a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                need_to_compile = false;
1421cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_current_profiles = false;
1422cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_reference_profile = false;
14236a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                break;
14246a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
14256a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                LOG(WARNING) << "Bad profiles for package " << pkgname;
14266a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                need_to_compile = false;
1427cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_current_profiles = true;
1428cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_reference_profile = true;
14296a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                break;
14306a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            case PROFMAN_BIN_RETURN_CODE_ERROR_IO:  // fall-through
14316a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
14326a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                // Temporary IO problem (e.g. locking). Ignore but log a warning.
14336a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
14346a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                need_to_compile = false;
1435cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_current_profiles = false;
1436cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_reference_profile = false;
14376a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                break;
14386a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle           default:
14396a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                // Unknown return code or error. Unlink profiles.
14406a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
14416a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                        << ": " << return_code;
14426a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                need_to_compile = false;
1443cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_current_profiles = true;
1444cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle                should_clear_reference_profile = true;
14456a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle                break;
144660a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle        }
144760a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
14486a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    close_all_fds(profiles_fd, "profiles_fd");
14496a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (close(reference_profile_fd) != 0) {
14506a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        PLOG(WARNING) << "Failed to close fd for reference profile";
14516a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
1452cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    if (should_clear_current_profiles) {
1453cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        clear_current_profiles(pkgname);
14546a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
1455cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle    if (should_clear_reference_profile) {
1456cea31418f34680fcfea4ec885dc966ad3d76354fCalin Juravle        clear_reference_profile(pkgname);
14576a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
14586a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return need_to_compile;
145960a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle}
146060a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle
14616727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehrstatic void run_profman_dump(const std::vector<fd_t>& profile_fds,
14626727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr                             fd_t reference_profile_fd,
146340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr                             const std::vector<std::string>& dex_locations,
146440e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr                             const std::vector<fd_t>& apk_fds,
14656727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr                             fd_t output_fd) {
146640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    std::vector<std::string> profman_args;
14676727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    static const char* PROFMAN_BIN = "/system/bin/profman";
146840e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    profman_args.push_back(PROFMAN_BIN);
146940e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    profman_args.push_back("--dump-only");
147040e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
147140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    if (reference_profile_fd != -1) {
147240e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
147340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr                                            reference_profile_fd));
14746727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
14756727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    for (fd_t profile_fd : profile_fds) {
147640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
14776727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
147840e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    for (const std::string& dex_location : dex_locations) {
147940e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
14806727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
148140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    for (fd_t apk_fd : apk_fds) {
148240e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
148340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    }
148440e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    const char **argv = new const char*[profman_args.size() + 1];
148540e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    size_t i = 0;
148640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    for (const std::string& profman_arg : profman_args) {
148740e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        argv[i++] = profman_arg.c_str();
14886727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
14896727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    argv[i] = NULL;
14906727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
14916727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    execv(PROFMAN_BIN, (char * const *)argv);
14926727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
14936727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    exit(68);   /* only get here on exec failure */
14946727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr}
14956727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
149640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehrstatic const char* get_location_from_path(const char* path) {
149740e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    static constexpr char kLocationSeparator = '/';
149840e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    const char *location = strrchr(path, kLocationSeparator);
149940e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    if (location == NULL) {
150040e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        return path;
150140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    } else {
150240e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        // Skip the separator character.
150340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        return location + 1;
150440e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    }
150540e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr}
150640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr
15076727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr// Dumps the contents of a profile file, using pkgname's dex files for pretty
15086727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr// printing the result.
1509475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1510475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& codePaths, bool* _aidl_return) {
1511475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
1512475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey
1513475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* pkgname = packageName.c_str();
1514475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* code_path_string = codePaths.c_str();
1515475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey
15166727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    std::vector<fd_t> profile_fds;
15176727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    fd_t reference_profile_fd = -1;
15186727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
15196727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
15206727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
15216727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
15226727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
15236727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
15246727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    const bool has_reference_profile = (reference_profile_fd != -1);
15256727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    const bool has_profiles = !profile_fds.empty();
15266727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
15276727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    if (!has_reference_profile && !has_profiles) {
15286727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
1529475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        *_aidl_return = false;
1530475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
15316727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
15326727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
153340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
15346727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
15356727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
1536475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        *_aidl_return = false;
1537475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
15386727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
153940e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
154040e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    std::vector<std::string> dex_locations;
154140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    std::vector<fd_t> apk_fds;
154240e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    for (const std::string& code_full_path : code_full_paths) {
154340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        const char* full_path = code_full_path.c_str();
154440e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
154540e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        if (apk_fd == -1) {
154640e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr            ALOGE("installd cannot open '%s'\n", full_path);
1547475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey            *_aidl_return = false;
1548475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey            return binder::Status::ok();
15496727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        }
155040e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        dex_locations.push_back(get_location_from_path(full_path));
155140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        apk_fds.push_back(apk_fd);
15526727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
15536727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
15546727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    pid_t pid = fork();
15556727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    if (pid == 0) {
15566727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        /* child -- drop privileges before continuing */
15576727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        drop_capabilities(uid);
155840e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr        run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
155940e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr                         apk_fds, output_fd);
15606727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        exit(68);   /* only get here on exec failure */
15616727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
15626727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    /* parent */
156340e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr    close_all_fds(apk_fds, "apk_fds");
15646727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    close_all_fds(profile_fds, "profile_fds");
15656727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    if (close(reference_profile_fd) != 0) {
15666727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        PLOG(WARNING) << "Failed to close fd for reference profile";
15676727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
15686727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    int return_code = wait_child(pid);
15696727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    if (!WIFEXITED(return_code)) {
15706727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr        LOG(WARNING) << "profman failed for package " << pkgname << ": "
15716727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr                << return_code;
1572475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        *_aidl_return = false;
1573475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::ok();
15746727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr    }
1575475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    *_aidl_return = true;
1576475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
15776727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr}
15786727c2d0bfc876c62d6ee60d8a05d26bef1d56efDavid Sehr
1579fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdilstatic std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1580fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil  // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
158189b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  if (EndsWith(oat_path, ".dex")) {
1582fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    std::string new_path = oat_path;
1583fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1584fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    CHECK(EndsWith(new_path, new_ext.c_str()));
1585fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    return new_path;
1586edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier  }
158789b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe
158889b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  // An odex entry. Not that this may not be an extension, e.g., in the OTA
158989b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  // case (where the base name will have an extension for the B artifact).
159089b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  size_t odex_pos = oat_path.rfind(".odex");
159189b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  if (odex_pos != std::string::npos) {
1592fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    std::string new_path = oat_path;
1593fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    new_path.replace(odex_pos, strlen(".odex"), new_ext);
1594fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    CHECK_NE(new_path.find(new_ext), std::string::npos);
1595fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    return new_path;
159689b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  }
159789b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe
159889b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  // Don't know how to handle this.
159989b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe  return "";
1600edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier}
1601edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier
1602fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil// Translate the given oat path to an art (app image) path. An empty string
1603fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil// denotes an error.
1604fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdilstatic std::string create_image_filename(const std::string& oat_path) {
1605fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    return replace_file_extension(oat_path, ".art");
1606fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil}
1607fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil
1608fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil// Translate the given oat path to a vdex path. An empty string denotes an error.
1609fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdilstatic std::string create_vdex_filename(const std::string& oat_path) {
1610fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    return replace_file_extension(oat_path, ".vdex");
1611fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil}
1612fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil
161341fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartierstatic bool add_extension_to_file_name(char* file_name, const char* extension) {
161441fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
161541fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier        return false;
1616edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    }
161741fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    strcat(file_name, extension);
161841fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    return true;
161941fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier}
162041fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier
16216fb5a0179d4de9c85351fd016277949804c809edAndreas Gampestatic int open_output_file(const char* file_name, bool recreate, int permissions) {
162241fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    int flags = O_RDWR | O_CREAT;
162341fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    if (recreate) {
16245006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath        if (unlink(file_name) < 0) {
16255006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath            if (errno != ENOENT) {
16265006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath                PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
16275006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath            }
16285006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath        }
162941fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier        flags |= O_EXCL;
163041fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier    }
16315006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath    return open(file_name, flags, permissions);
1632edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier}
1633edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier
1634edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartierstatic bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1635edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    if (fchmod(fd,
1636edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier               S_IRUSR|S_IWUSR|S_IRGRP |
1637edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier               (is_public ? S_IROTH : 0)) < 0) {
1638edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1639edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        return false;
1640edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1641edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        ALOGE("installd cannot chown '%s' during dexopt\n", path);
1642edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier        return false;
1643edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    }
1644edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    return true;
1645edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier}
1646edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier
164753caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffraystatic bool IsOutputDalvikCache(const char* oat_dir) {
164853caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray  // InstallerConnection.java (which invokes installd) transforms Java null arguments
164953caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray  // into '!'. Play it safe by handling it both.
165053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray  // TODO: ensure we never get null.
165153caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray  // TODO: pass a flag instead of inferring if the output is dalvik cache.
165253caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray  return oat_dir == nullptr || oat_dir[0] == '!';
165353caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray}
165453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray
16556a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravlestatic bool create_oat_out_path(const char* apk_path, const char* instruction_set,
1656fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            const char* oat_dir, /*out*/ char* out_oat_path) {
16576a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // Early best-effort check whether we can fit the the path into our buffers.
16586a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
16596a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
16606a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    // extension to the cache path (5 bytes).
16616a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
16626a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        ALOGE("apk_path too long '%s'\n", apk_path);
16636a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return false;
16646a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
16656a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
166653caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    if (!IsOutputDalvikCache(oat_dir)) {
16676a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        if (validate_apk_path(oat_dir)) {
166853caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
16696a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            return false;
16706a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
1671fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
16726a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            return false;
16736a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
16746a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    } else {
1675fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
16766a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle            return false;
16776a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        }
16786a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    }
16796a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle    return true;
16806a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle}
16816a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
16824d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe// TODO: Consider returning error codes.
1683475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1684475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    bool* _aidl_return) {
1685475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
1686475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* pkgname = packageName.c_str();
1687475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    *_aidl_return = analyse_profiles(uid, pkgname);
1688475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
16894d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe}
16904d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe
1691548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampestatic const char* parse_null(const char* arg) {
1692548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe    if (strcmp(arg, "!") == 0) {
1693548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe        return nullptr;
1694548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe    } else {
1695548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe        return arg;
1696548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe    }
1697548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe}
1698548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe
1699d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampeint dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1700548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe    return dexopt(params[0],                    // apk_path
1701548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  atoi(params[1]),              // uid
1702548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  params[2],                    // pkgname
1703548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  params[3],                    // instruction_set
1704548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  atoi(params[4]),              // dexopt_needed
1705548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  params[5],                    // oat_dir
1706548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  atoi(params[6]),              // dexopt_flags
1707548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  params[7],                    // compiler_filter
1708548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  parse_null(params[8]),        // volume_uuid
1709548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe                  parse_null(params[9]));       // shared_libraries
1710548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe    static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1711548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe}
1712548bdb930895d8fe6651eaada0bc5739ee5248c8Andreas Gampe
17136fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
17146fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe// on destruction. It will also run the given cleanup (unless told not to) after closing.
17156fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17166fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe// Usage example:
17176fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17186fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   Dex2oatFileWrapper<std::function<void ()>> file(open(...),
17196fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//                                                   [name]() {
17206fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//                                                       unlink(name.c_str());
17216fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//                                                   });
17226fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
17236fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//            wrapper if captured as a reference.
17246fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17256fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   if (file.get() == -1) {
17266fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//       // Error opening...
17276fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   }
17286fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17296fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   ...
17306fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   if (error) {
17316fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//       // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
17326fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//       // and delete the file (after the fd is closed).
17336fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//       return -1;
17346fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   }
17356fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17366fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   (Success case)
17376fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   file.SetCleanup(false);
17386fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
17396fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//   // (leaving the file around; after the fd is closed).
17406fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe//
17416fb5a0179d4de9c85351fd016277949804c809edAndreas Gampetemplate <typename Cleanup>
17426fb5a0179d4de9c85351fd016277949804c809edAndreas Gampeclass Dex2oatFileWrapper {
17436fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe public:
17446fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
17456fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17466fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17476fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    Dex2oatFileWrapper(int value, Cleanup cleanup)
17486fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
17496fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17506fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    ~Dex2oatFileWrapper() {
17516fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        reset(-1);
17526fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17536fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17546fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    int get() {
17556fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        return value_;
17566fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17576fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17586fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    void SetCleanup(bool cleanup) {
17596fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        do_cleanup_ = cleanup;
17606fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17616fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17626fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    void reset(int new_value) {
17636fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (value_ >= 0) {
17646fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            close(value_);
17656fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
17666fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (do_cleanup_ && cleanup_ != nullptr) {
17676fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            cleanup_();
17686fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
17696fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17706fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        value_ = new_value;
17716fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17726fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17736fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    void reset(int new_value, Cleanup new_cleanup) {
17746fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (value_ >= 0) {
17756fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            close(value_);
17766fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
17776fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (do_cleanup_ && cleanup_ != nullptr) {
17786fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            cleanup_();
17796fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
17806fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17816fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        value_ = new_value;
17826fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        cleanup_ = new_cleanup;
17836fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    }
17846fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
17856fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe private:
17866fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    int value_;
17876fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    Cleanup cleanup_;
17886fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    bool do_cleanup_;
17896fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe};
17906fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe
179160a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravleint dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
17924d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe           int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1793b63d91fd2737680351876406277b6c759f4db33cJeff Hao           const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries)
179494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
1795db0326a56ed8cc1ba2ed5ec2810afe49bcd9a596Calin Juravle    bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
179676e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy    bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
179776e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy    bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
179876e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy    bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
17994d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1800db0326a56ed8cc1ba2ed5ec2810afe49bcd9a596Calin Juravle
18014d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    CHECK(pkgname != nullptr);
18024d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    CHECK(pkgname[0] != 0);
1803db0326a56ed8cc1ba2ed5ec2810afe49bcd9a596Calin Juravle
18044d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    // Public apps should not be compiled with profile information ever. Same goes for the special
18054d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    // package '*' used for the system server.
18066fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
18074d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe    if (!is_public && pkgname[0] != '*') {
18084d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        // Open reference profile in read only mode as dex2oat does not get write permissions.
18096fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        const std::string pkgname_str(pkgname);
18106fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
18116fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                   [pkgname_str]() {
18126fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                       clear_reference_profile(pkgname_str.c_str());
18136fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                   });
18144d0f825dd76a1972a3d081e771cde28513a1c6ffAndreas Gampe        // Note: it's OK to not find a profile here.
181560a794dc845b942907ca035ddc554eb8e0c7ebb6Calin Juravle    }
181676e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy
1817e296e00df65461629a20cd03b5b041a59935d00fTodd Kennedy    if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
181876e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy        LOG_FATAL("dexopt flags contains unknown fields\n");
181976e767ca14bcbb4bc809cd1279ece82a3aabe8a4Todd Kennedy    }
182094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1821fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    char out_oat_path[PKG_PATH_MAX];
1822fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
18236a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        return false;
182494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
182594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
18266fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    const char *input_file;
18276fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    char in_odex_path[PKG_PATH_MAX];
1828920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    int dexopt_action = abs(dexopt_needed);
1829920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    bool is_odex_location = dexopt_needed < 0;
1830920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    switch (dexopt_action) {
1831920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        case DEX2OAT_FROM_SCRATCH:
1832920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        case DEX2OAT_FOR_BOOT_IMAGE:
1833920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        case DEX2OAT_FOR_FILTER:
1834920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        case DEX2OAT_FOR_RELOCATION:
1835c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler            input_file = apk_path;
1836c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler            break;
1837c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler
1838920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        case PATCHOAT_FOR_RELOCATION:
1839920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            if (is_odex_location) {
1840920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1841920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                    return -1;
1842920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                }
1843920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                input_file = in_odex_path;
1844920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            } else {
1845920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                input_file = out_oat_path;
1846c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler            }
1847c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler            break;
1848c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler
1849c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler        default:
1850c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler            ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
18516fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            return 72;
18527365a10689df23334d245b211ce272502ad20669Alex Light    }
18537365a10689df23334d245b211ce272502ad20669Alex Light
18546fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    struct stat input_stat;
18557365a10689df23334d245b211ce272502ad20669Alex Light    memset(&input_stat, 0, sizeof(input_stat));
18567365a10689df23334d245b211ce272502ad20669Alex Light    stat(input_file, &input_stat);
185794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1858fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    // Open the input file. If running dex2oat, `input_file` is the APK. If running
1859fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    // patchoat, it is the OAT file to be relocated.
18606fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
18616fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    if (input_fd.get() < 0) {
18627365a10689df23334d245b211ce272502ad20669Alex Light        ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
186394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return -1;
186494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
186594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1866fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    // Create the output OAT file.
1867fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const std::string out_oat_path_str(out_oat_path);
1868fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1869fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1870fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1871fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (out_oat_fd.get() < 0) {
1872fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
1873fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        return -1;
1874fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    }
1875fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1876fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        return -1;
1877fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    }
1878fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil
187953caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    // Open the existing VDEX. We do this before creating the new output VDEX, which will
188053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    // unlink the old one.
188153caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    base::unique_fd in_vdex_fd;
188253caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    std::string in_vdex_path_str;
1883920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
188453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
188553caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        in_vdex_path_str = create_vdex_filename(input_file);
188653caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        if (in_vdex_path_str.empty()) {
188753caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
188853caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            return -1;
188953caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        }
189053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
189153caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        if (in_vdex_fd.get() < 0) {
189253caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
189353caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray                in_vdex_path_str.c_str(), strerror(errno));
189453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            return -1;
189553caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        }
1896920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
1897920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1898920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        const char* path = nullptr;
1899920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        if (is_odex_location) {
1900920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1901920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                path = in_odex_path;
1902920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            } else {
1903920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
1904920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray                return -1;
1905920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            }
1906920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        } else {
1907920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            path = out_oat_path;
1908920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        }
1909920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        in_vdex_path_str = create_vdex_filename(path);
191053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        if (in_vdex_path_str.empty()) {
1911920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray            ALOGE("installd cannot compute input vdex location for '%s'\n", path);
191253caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray            return -1;
191353caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        }
191453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
191553caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray    }
191653caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray
1917fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    // Infer the name of the output VDEX and create it.
1918fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
1919fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (out_vdex_path_str.empty()) {
1920fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        return -1;
1921fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    }
1922fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
1923fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1924fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1925fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (out_vdex_fd.get() < 0) {
1926fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
19276fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        return -1;
192894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
1929fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
1930fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                uid, out_vdex_path_str.c_str())) {
19316fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        return -1;
193294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
193394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1934e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    // Create a swap file if necessary.
19356fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    base::unique_fd swap_fd;
1936c92fb6247d4c4fbc34c0a5deb26ccf538ca9ec81Richard Uhler    if (ShouldUseSwapFileForDexopt()) {
1937e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        // Make sure there really is enough space.
19386fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        char swap_file_name[PKG_PATH_MAX];
1939fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        strcpy(swap_file_name, out_oat_path);
194041fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier        if (add_extension_to_file_name(swap_file_name, ".swap")) {
19416fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
194241fdcbfa119698122cae9913ea85ea1d2cf9668aMathieu Chartier        }
19436fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (swap_fd.get() < 0) {
1944edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier            // Could not create swap file. Optimistically go on and hope that we can compile
1945edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier            // without it.
1946edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier            ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1947e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        } else {
1948edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier            // Immediately unlink. We don't really want to hit flash.
19495006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath            if (unlink(swap_file_name) < 0) {
19505006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath                PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
19515006f3a6bcfbe73cfae96b3f2659ce42e18bc2eaNarayan Kamath            }
1952e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe        }
1953e1c01353c4dc6058a384eea9853238d2a87040dbAndreas Gampe    }
1954d93707342a61e66bc3eb2145628158452f577f42Dave Allison
1955e80d58db65d29ed4647e631a81aed644fea00913Mathieu Chartier    // Avoid generating an app image for extract only since it will not contain any classes.
19566fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    Dex2oatFileWrapper<std::function<void ()>> image_fd;
1957fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const std::string image_path = create_image_filename(out_oat_path);
1958920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray    if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
19596fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        char app_image_format[kPropertyValueMax];
19606fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        bool have_app_image_format =
19616fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
19626fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        // Use app images only if it is enabled (by a set image format) and we are compiling
19636fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        // profile-guided (so the app image doesn't conservatively contain all classes).
19646fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (profile_guided && have_app_image_format) {
19656fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            // Recreate is true since we do not want to modify a mapped image. If the app is
19666fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            // already running and we modify the image file, it can cause crashes (b/27493510).
196789b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe            image_fd.reset(open_output_file(image_path.c_str(),
19686fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                            true /*recreate*/,
19696fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                            0600 /*permissions*/),
197089b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe                           [image_path]() { unlink(image_path.c_str()); }
19716fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                           );
19726fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            if (image_fd.get() < 0) {
19736fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                // Could not create application image file. Go on since we can compile without
19746fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                // it.
19756fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                LOG(ERROR) << "installd could not create '"
19766fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        << image_path
19776fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        << "' for image file during dexopt";
19786fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            } else if (!set_permissions_and_ownership(image_fd.get(),
19796fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                                      is_public,
19806fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                                                      uid,
198189b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe                                                      image_path.c_str())) {
19826fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                image_fd.reset(-1);
19836fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            }
19846fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
19856fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        // If we have a valid image file path but no image fd, explicitly erase the image file.
19866fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        if (image_fd.get() < 0) {
198789b008dfb59ac827db00a45e7de1bac1c65b9c93Andreas Gampe            if (unlink(image_path.c_str()) < 0) {
19886fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                if (errno != ENOENT) {
19896fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                    PLOG(ERROR) << "Couldn't unlink image file " << image_path;
19906fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                }
19916fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            }
19926fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        }
1993edc8bc48fbf143e35578bf6cccf980dfab076196Mathieu Chartier    }
1994e80d58db65d29ed4647e631a81aed644fea00913Mathieu Chartier
19957365a10689df23334d245b211ce272502ad20669Alex Light    ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
199694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
19976fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    pid_t pid = fork();
199894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (pid == 0) {
199994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        /* child -- drop privileges before continuing */
20006a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle        drop_capabilities(uid);
20016a1648e2f161cb1d7c46aa9d27e8062521a9f314Calin Juravle
200213f141910ba383404145924df64ad6626fe5b42fAndreas Gampe        SetDex2OatAndPatchOatScheduling(boot_complete);
2003fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
2004fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
20056fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            _exit(67);
200694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
200794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2008920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
20096fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            run_patchoat(input_fd.get(),
201053caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray                         in_vdex_fd.get(),
2011fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                         out_oat_fd.get(),
2012fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                         out_vdex_fd.get(),
20136fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                         input_file,
2014fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                         in_vdex_path_str.c_str(),
2015fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                         out_oat_path,
2016fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                         out_vdex_path_str.c_str(),
20176fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                         pkgname,
20186fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                         instruction_set);
2019920c60cdaeb6394eb95aa93c02a2d8f425204074Nicolas Geoffray        } else {
2020aaa1d4e930f653ec21b711eb852194c8abf35143David Brazdil            // Pass dex2oat the relative path to the input file.
202140e566de4b17a0f5f200fbf5014d30367c1992faDavid Sehr            const char *input_file_name = get_location_from_path(input_file);
20226fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            run_dex2oat(input_fd.get(),
2023fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                        out_oat_fd.get(),
202453caf0d20c6831d81a0840ac6056ed4c1c691032Nicolas Geoffray                        in_vdex_fd.get(),
2025fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                        out_vdex_fd.get(),
20266fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        image_fd.get(),
20276fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        input_file_name,
2028fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                        out_oat_path,
20296fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        swap_fd.get(),
20306fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        instruction_set,
20316fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        compiler_filter,
20326fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        vm_safe_mode,
20336fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        debuggable,
20346fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        boot_complete,
20356fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        reference_profile_fd.get(),
20366fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe                        shared_libraries);
20371705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom        }
20386fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        _exit(68);   /* only get here on exec failure */
203994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    } else {
20406fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe        int res = wait_child(pid);
204163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (res == 0) {
20427365a10689df23334d245b211ce272502ad20669Alex Light            ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
204363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        } else {
20447365a10689df23334d245b211ce272502ad20669Alex Light            ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
20456fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe            return -1;
204694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
204794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
204894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
20496fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    struct utimbuf ut;
20507365a10689df23334d245b211ce272502ad20669Alex Light    ut.actime = input_stat.st_atime;
20517365a10689df23334d245b211ce272502ad20669Alex Light    ut.modtime = input_stat.st_mtime;
2052fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    utime(out_oat_path, &ut);
20531705fc44fb85c4232637f9f7189c3bdca98a63d5Brian Carlstrom
20546fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    // We've been successful, don't delete output.
2055fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    out_oat_fd.SetCleanup(false);
2056fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    out_vdex_fd.SetCleanup(false);
20576fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    image_fd.SetCleanup(false);
20586fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    reference_profile_fd.SetCleanup(false);
205994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
20606fb5a0179d4de9c85351fd016277949804c809edAndreas Gampe    return 0;
206194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
206294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2063475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2064475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2065475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* instruction_set = instructionSet.c_str();
2066475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey
2067475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    char boot_marker_path[PKG_PATH_MAX];
2068475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    sprintf(boot_marker_path,
206902d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe          "%s/%s/%s/.booting",
207002d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe          android_data_dir.path,
207102d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe          DALVIK_CACHE,
207202d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe          instruction_set);
2073091ea779d4e575856c04d51d82f45cc8a6155b5eNarayan Kamath
2074475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ALOGV("mark_boot_complete : %s", boot_marker_path);
2075475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (unlink(boot_marker_path) != 0) {
2076475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path, strerror(errno));
2077475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2078475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
2079475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
2080091ea779d4e575856c04d51d82f45cc8a6155b5eNarayan Kamath}
2081091ea779d4e575856c04d51d82f45cc8a6155b5eNarayan Kamath
208294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
208394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        struct stat* statbuf)
208494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
208594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    while (path[basepos] != 0) {
208694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (path[basepos] == '/') {
208794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            path[basepos] = 0;
208894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (lstat(path, statbuf) < 0) {
208994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGV("Making directory: %s\n", path);
209094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                if (mkdir(path, mode) == 0) {
209194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    chown(path, uid, gid);
209294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                } else {
209394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
209494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                }
209594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
209694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            path[basepos] = '/';
209794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            basepos++;
209894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
209994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        basepos++;
210094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
210194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
210294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2103475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::linkNativeLibraryDirectory(
2104475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2105475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& nativeLibPath32, int32_t userId) {
2106475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2107475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2108475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* pkgname = packageName.c_str();
2109475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* asecLibDir = nativeLibPath32.c_str();
211094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    struct stat s, libStat;
211194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int rc = 0;
211294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2113475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    std::string _pkgdir(create_data_user_ce_package_path(uuid_, userId, pkgname));
2114c03de09173f98506e73e7cf7df21fe11795d4b24Jeff Sharkey    std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
2115c03de09173f98506e73e7cf7df21fe11795d4b24Jeff Sharkey
2116c03de09173f98506e73e7cf7df21fe11795d4b24Jeff Sharkey    const char* pkgdir = _pkgdir.c_str();
2117c03de09173f98506e73e7cf7df21fe11795d4b24Jeff Sharkey    const char* libsymlink = _libsymlink.c_str();
211894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2119475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    if (stat(pkgdir, &s) < 0) {
2120475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2121475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    }
212294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
212394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
212494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
2125475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
212694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
212794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
212894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (chmod(pkgdir, 0700) < 0) {
212994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
213094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        rc = -1;
213194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        goto out;
213294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
213394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
213494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (lstat(libsymlink, &libStat) < 0) {
213594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (errno != ENOENT) {
213694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
213794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            rc = -1;
213894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            goto out;
213994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
214094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    } else {
214194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (S_ISDIR(libStat.st_mode)) {
21423aee2c5c749dc2589f001b26fae1ec958ec89524Narayan Kamath            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
214394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                rc = -1;
214494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                goto out;
214594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
214694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        } else if (S_ISLNK(libStat.st_mode)) {
214794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (unlink(libsymlink) < 0) {
214894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
214994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                rc = -1;
215094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                goto out;
215194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
215294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
215394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
215494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
215594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (symlink(asecLibDir, libsymlink) < 0) {
215694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
215794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                strerror(errno));
215894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        rc = -errno;
215994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        goto out;
216094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
216194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
216294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodout:
216394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (chmod(pkgdir, s.st_mode) < 0) {
216494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
216594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        rc = -errno;
216694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
216794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
216894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
216994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
2170475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        rc = -errno;
217194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
217294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2173475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return rc ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
217494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
217563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
217663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstadstatic void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
217763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad{
217863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    static const char *IDMAP_BIN = "/system/bin/idmap";
217963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    static const size_t MAX_INT_LEN = 32;
218063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    char idmap_str[MAX_INT_LEN];
218163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
218263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
218363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
218463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
218563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
218663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad}
218763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
218863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
218963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
219063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstadstatic int flatten_path(const char *prefix, const char *suffix,
219163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        const char *overlay_path, char *idmap_path, size_t N)
219263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad{
219363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (overlay_path == NULL || idmap_path == NULL) {
219463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        return -1;
219563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
219663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    const size_t len_overlay_path = strlen(overlay_path);
219763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    // will access overlay_path + 1 further below; requires absolute path
219863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (len_overlay_path < 2 || *overlay_path != '/') {
219963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        return -1;
220063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
220163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    const size_t len_idmap_root = strlen(prefix);
220263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    const size_t len_suffix = strlen(suffix);
220363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
220463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
220563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        // additions below would cause overflow
220663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        return -1;
220763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
220863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (N < len_idmap_root + len_overlay_path + len_suffix) {
220963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        return -1;
221063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
221163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    memset(idmap_path, 0, N);
221263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
221363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    char *ch = idmap_path + len_idmap_root;
221463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    while (*ch != '\0') {
221563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (*ch == '/') {
221663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            *ch = '@';
221763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        }
221863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        ++ch;
221963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
222063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    return 0;
222163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad}
222263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
2223475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2224475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& overlayApkPath, int32_t uid) {
2225475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2226475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* target_apk = targetApkPath.c_str();
2227475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* overlay_apk = overlayApkPath.c_str();
222863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
222963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
223063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    int idmap_fd = -1;
223163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    char idmap_path[PATH_MAX];
223263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
223363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
223463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad                idmap_path, sizeof(idmap_path)) == -1) {
223563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
223663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        goto fail;
223763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
223863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
223963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    unlink(idmap_path);
224063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
224163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (idmap_fd < 0) {
224263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
224363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        goto fail;
224463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
224563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
224663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        ALOGE("idmap cannot chown '%s'\n", idmap_path);
224763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        goto fail;
224863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
224963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
225063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
225163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        goto fail;
225263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
225363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
225463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    pid_t pid;
225563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    pid = fork();
225663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (pid == 0) {
225763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        /* child -- drop privileges before continuing */
225863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (setgid(uid) != 0) {
225963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            ALOGE("setgid(%d) failed during idmap\n", uid);
226063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            exit(1);
226163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        }
226263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (setuid(uid) != 0) {
226363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            ALOGE("setuid(%d) failed during idmap\n", uid);
226463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            exit(1);
226563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        }
226663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
226763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
226863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            exit(1);
226963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        }
227063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
227163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        run_idmap(target_apk, overlay_apk, idmap_fd);
227263568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        exit(1); /* only if exec call to idmap failed */
227363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    } else {
227463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        int status = wait_child(pid);
227563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        if (status != 0) {
227663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            ALOGE("idmap failed, status=0x%04x\n", status);
227763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad            goto fail;
227863568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        }
227963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
228063568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad
228163568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    close(idmap_fd);
2282475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
228363568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstadfail:
228463568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    if (idmap_fd >= 0) {
228563568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        close(idmap_fd);
228663568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad        unlink(idmap_path);
228763568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad    }
2288475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::fromServiceSpecificError(-1);
228963568b1430d741f40ca008391c854ef1cc880138MÃ¥rten Kongstad}
2290e9887e46cea4a095e4219927eadbe4c57bb1a5eeRobert Craig
2291c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkeybinder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2292c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2293c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        const std::string& seInfo) {
2294c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2295ebf728fd43ab5c7d11a1f9e5fdc775d6740fae0aJeff Sharkey    int res = 0;
2296e9887e46cea4a095e4219927eadbe4c57bb1a5eeRobert Craig
2297da30dc7336f03ca629fe173db1425fdce989119cRobert Craig    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
2298c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
2299c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2300c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* pkgName = packageName.c_str();
2301c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    const char* seinfo = seInfo.c_str();
2302e9887e46cea4a095e4219927eadbe4c57bb1a5eeRobert Craig
2303da30dc7336f03ca629fe173db1425fdce989119cRobert Craig    if (!pkgName || !seinfo) {
2304da30dc7336f03ca629fe173db1425fdce989119cRobert Craig        ALOGE("Package name or seinfo tag is null when trying to restorecon.");
2305c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2306da30dc7336f03ca629fe173db1425fdce989119cRobert Craig    }
2307e9887e46cea4a095e4219927eadbe4c57bb1a5eeRobert Craig
2308c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    uid_t uid = multiuser_get_uid(userId, appId);
2309aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_CE) {
2310c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
2311c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2312c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey            PLOG(ERROR) << "restorecon failed for " << path;
2313ebf728fd43ab5c7d11a1f9e5fdc775d6740fae0aJeff Sharkey            res = -1;
2314da30dc7336f03ca629fe173db1425fdce989119cRobert Craig        }
2315c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey    }
2316aa7ddfd8347fa947618a7668b013521e95722c5cJeff Sharkey    if (flags & FLAG_STORAGE_DE) {
2317c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey        auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
2318c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2319c7d1b2250e8245a7e4e144758bc3ccd33b8d6319Jeff Sharkey            PLOG(ERROR) << "restorecon failed for " << path;
2320ea0e4b19d942f62ea21ca4e70f939f3d4aa14b37Jeff Sharkey            // TODO: include result once 25796509 is fixed
2321da30dc7336f03ca629fe173db1425fdce989119cRobert Craig        }
2322da30dc7336f03ca629fe173db1425fdce989119cRobert Craig    }
2323c1e93e7d746e07791b0667c80ad43a407c515fa8Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
2324e9887e46cea4a095e4219927eadbe4c57bb1a5eeRobert Craig}
23253aee2c5c749dc2589f001b26fae1ec958ec89524Narayan Kamath
2326475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2327475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& instructionSet) {
2328475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2329475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* oat_dir = oatDir.c_str();
2330475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* instruction_set = instructionSet.c_str();
233188ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    char oat_instr_dir[PKG_PATH_MAX];
233288ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov
233388ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    if (validate_apk_path(oat_dir)) {
233488ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov        ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
2335475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
233688ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    }
23378eed7e6a9bb527af7380ec13b390c6e2955eba6aFyodor Kupolov    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2338475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
233988ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    }
234088ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    if (selinux_android_restorecon(oat_dir, 0)) {
234188ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov        ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
2342475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
234388ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    }
234488ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
23458eed7e6a9bb527af7380ec13b390c6e2955eba6aFyodor Kupolov    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2346475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
234788ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    }
2348475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
234988ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov}
235088ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov
2351475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2352475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2353475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* apk_path = packageDir.c_str();
235488ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    if (validate_apk_path(apk_path)) {
235588ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov        ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
2356475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
235788ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov    }
2358475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    int res = delete_dir_contents(apk_path, 1 /* also_delete_dir */,
2359475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey            NULL /* exclusion_predicate */);
2360475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
236188ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov}
236288ce4ff7a95ea2008fa28f12b880ee526e331440Fyodor Kupolov
2363475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2364475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& fromBase, const std::string& toBase) {
2365475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2366475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* relative_path = relativePath.c_str();
2367475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* from_base = fromBase.c_str();
2368475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* to_base = toBase.c_str();
2369d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    char from_path[PKG_PATH_MAX];
2370d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    char to_path[PKG_PATH_MAX];
2371d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2372d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2373d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath
2374d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    if (validate_apk_path_subdirs(from_path)) {
2375d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath        ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
2376475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2377d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    }
2378d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath
2379d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    if (validate_apk_path_subdirs(to_path)) {
2380d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath        ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
2381475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2382d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    }
2383d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath
2384d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    const int ret = link(from_path, to_path);
2385d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    if (ret < 0) {
2386d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath        ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
2387475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2388d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath    }
2389d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath
2390475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return binder::Status::ok();
2391d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath}
2392d845c96128a40ca5802c0840ae190fa0af7d4735Narayan Kamath
2393e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe// Helper for move_ab, so that we can have common failure-case cleanup.
2394e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampestatic bool unlink_and_rename(const char* from, const char* to) {
2395e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2396e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    // return a failure.
2397e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    struct stat s;
2398e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    if (stat(to, &s) == 0) {
2399e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        if (!S_ISREG(s.st_mode)) {
2400e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe            LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2401e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe            return false;
2402e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        }
2403e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        if (unlink(to) != 0) {
2404e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe            LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2405e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe            return false;
2406e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        }
2407e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    } else {
2408e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        // This may be a permission problem. We could investigate the error code, but we'll just
2409e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        // let the rename failure do the work for us.
2410e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2411e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2412e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    // Try to rename "to" to "from."
2413e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    if (rename(from, to) != 0) {
2414e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        PLOG(ERROR) << "Could not rename " << from << " to " << to;
2415e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        return false;
2416e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2417e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    return true;
2418e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe}
2419e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2420ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe// Move/rename a B artifact (from) to an A artifact (to).
2421ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampestatic bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2422ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    // Check whether B exists.
2423ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    {
2424ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        struct stat s;
2425ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        if (stat(b_path.c_str(), &s) != 0) {
2426ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            // Silently ignore for now. The service calling this isn't smart enough to understand
2427ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            // lack of artifacts at the moment.
2428ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            return false;
2429ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        }
2430ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        if (!S_ISREG(s.st_mode)) {
2431ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2432ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            // Try to unlink, but swallow errors.
2433ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            unlink(b_path.c_str());
2434ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            return false;
2435ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        }
2436ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    }
2437ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe
2438ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    // Rename B to A.
2439ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2440ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        // Delete the b_path so we don't try again (or fail earlier).
2441ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        if (unlink(b_path.c_str()) != 0) {
2442ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe            PLOG(ERROR) << "Could not unlink " << b_path;
2443ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        }
2444ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe
2445ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        return false;
2446ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    }
2447ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe
2448ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    return true;
2449ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe}
2450ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe
2451475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey//int move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2452475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2453475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& instructionSet, const std::string& outputPath) {
2454475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2455475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* apk_path = apkPath.c_str();
2456475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* instruction_set = instructionSet.c_str();
2457475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* oat_dir = outputPath.c_str();
2458d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
2459d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    // Get the current slot suffix. No suffix, no A/B.
2460d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    std::string slot_suffix;
2461d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    {
2462d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe        char buf[kPropertyValueMax];
2463d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe        if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2464475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
2465d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe        }
2466d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe        slot_suffix = buf;
2467d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
2468fd12edaeab839f3f1f087cc75bd18b4d8af5b192Andreas Gampe        if (!ValidateTargetSlotSuffix(slot_suffix)) {
2469d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe            LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2470475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey            return binder::Status::fromServiceSpecificError(-1);
2471d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe        }
2472d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    }
2473d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe
2474d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    // Validate other inputs.
2475e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    if (validate_apk_path(apk_path) != 0) {
2476e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        LOG(ERROR) << "invalid apk_path " << apk_path;
2477475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2478e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2479e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    if (validate_apk_path(oat_dir) != 0) {
2480e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        LOG(ERROR) << "invalid oat_dir " << oat_dir;
2481475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2482e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2483e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2484e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    char a_path[PKG_PATH_MAX];
2485e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2486475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2487e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2488fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const std::string a_vdex_path = create_vdex_filename(a_path);
2489ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    const std::string a_image_path = create_image_filename(a_path);
2490e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2491d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    // B path = A path + slot suffix.
2492d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2493fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2494d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe    const std::string b_image_path = StringPrintf("%s.%s",
2495d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe                                                  a_image_path.c_str(),
2496d089ca1703769854356a263ca640d3e07ab8548dAndreas Gampe                                                  slot_suffix.c_str());
2497e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2498fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    bool success = true;
2499fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil    if (move_ab_path(b_path, a_path)) {
2500fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        if (move_ab_path(b_vdex_path, a_vdex_path)) {
2501fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            // Note: we can live without an app image. As such, ignore failure to move the image file.
2502fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            //       If we decide to require the app image, or the app image being moved correctly,
2503fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            //       then change accordingly.
2504fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            constexpr bool kIgnoreAppImageFailure = true;
2505fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil
2506fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            if (!a_image_path.empty()) {
2507fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                if (!move_ab_path(b_image_path, a_image_path)) {
2508c338c7f0b6acd1cd7204e21c0d3408b6946e5024David Brazdil                    unlink(a_image_path.c_str());
2509fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                    if (!kIgnoreAppImageFailure) {
2510fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                        success = false;
2511fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                    }
2512fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil                }
2513fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            }
2514fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        } else {
2515fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            // Cleanup: delete B image, ignore errors.
2516fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            unlink(b_image_path.c_str());
2517fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil            success = false;
2518e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe        }
2519ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe    } else {
2520ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        // Cleanup: delete B image, ignore errors.
2521fc5934e693ca52c89a78297e40ddb08e544e3631David Brazdil        unlink(b_vdex_path.c_str());
2522ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        unlink(b_image_path.c_str());
2523ab15dbfb4a113ce1fa18d3a5f1b91a95f678f272Andreas Gampe        success = false;
2524e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe    }
2525e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2526475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
2527e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe}
2528e65b4faa798269ab6ee0d27dab03b8b5caa6f956Andreas Gampe
2529475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkeybinder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2530475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        const std::string& instructionSet, const std::string& outputPath) {
2531475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    ENFORCE_UID(AID_SYSTEM);
2532475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* apk_path = apkPath.c_str();
2533475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* instruction_set = instructionSet.c_str();
2534475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    const char* oat_dir = outputPath.c_str();
2535475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey
2536b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    // Delete the oat/odex file.
2537b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    char out_path[PKG_PATH_MAX];
2538b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
2539475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey        return binder::Status::fromServiceSpecificError(-1);
2540b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    }
2541b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe
2542b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    // In case of a permission failure report the issue. Otherwise just print a warning.
2543b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    auto unlink_and_check = [](const char* path) -> bool {
2544b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe        int result = unlink(path);
2545b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe        if (result != 0) {
2546b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe            if (errno == EACCES || errno == EPERM) {
2547b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe                PLOG(ERROR) << "Could not unlink " << path;
2548b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe                return false;
2549b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe            }
2550b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe            PLOG(WARNING) << "Could not unlink " << path;
2551b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe        }
2552b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe        return true;
2553b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    };
2554b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe
2555b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    // Delete the oat/odex file.
2556b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    bool return_value_oat = unlink_and_check(out_path);
2557b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe
2558b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    // Derive and delete the app image.
2559b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2560b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe
2561b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe    // Report success.
2562475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    bool success = return_value_oat && return_value_art;
2563475c6f9743e5f6696c38fb22b8b8e9d49a82ab56Jeff Sharkey    return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
2564b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe}
2565b31206b67805617c79fb46ca39ccc5b26cdefd63Andreas Gampe
256602d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe}  // namespace installd
256702d0de56c75347a0cb8d5a8565dc8c4ee7616057Andreas Gampe}  // namespace android
2568