InstalldNativeService.cpp revision 7da5fc78535e3fd1581b3594b694a454a5badfe0
1/*
2** Copyright 2008, The Android Open Source Project
3**
4** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
7**
8**     http://www.apache.org/licenses/LICENSE-2.0
9**
10** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
14** limitations under the License.
15*/
16
17#include "InstalldNativeService.h"
18
19#include <errno.h>
20#include <inttypes.h>
21#include <regex>
22#include <stdlib.h>
23#include <sys/capability.h>
24#include <sys/file.h>
25#include <sys/resource.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <sys/wait.h>
29#include <sys/xattr.h>
30#include <unistd.h>
31
32#include <android-base/logging.h>
33#include <android-base/stringprintf.h>
34#include <android-base/strings.h>
35#include <android-base/unique_fd.h>
36#include <cutils/fs.h>
37#include <cutils/log.h>               // TODO: Move everything to base/logging.
38#include <cutils/sched_policy.h>
39#include <diskusage/dirsize.h>
40#include <logwrap/logwrap.h>
41#include <private/android_filesystem_config.h>
42#include <selinux/android.h>
43#include <system/thread_defs.h>
44
45#include "dexopt.h"
46#include "globals.h"
47#include "installd_deps.h"
48#include "otapreopt_utils.h"
49#include "utils.h"
50
51#ifndef LOG_TAG
52#define LOG_TAG "installd"
53#endif
54
55using android::base::EndsWith;
56using android::base::StringPrintf;
57
58namespace android {
59namespace installd {
60
61static constexpr const char* kCpPath = "/system/bin/cp";
62static constexpr const char* kXattrDefault = "user.default";
63
64static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
65
66static constexpr const char* PKG_LIB_POSTFIX = "/lib";
67static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
68static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
69
70static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
71static constexpr const char* IDMAP_SUFFIX = "@idmap";
72
73// NOTE: keep in sync with StorageManager
74static constexpr int FLAG_STORAGE_DE = 1 << 0;
75static constexpr int FLAG_STORAGE_CE = 1 << 1;
76
77// NOTE: keep in sync with Installer
78static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
79static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
80
81/* dexopt needed flags matching those in dalvik.system.DexFile */
82static constexpr int DEX2OAT_FROM_SCRATCH        = 1;
83static constexpr int DEX2OAT_FOR_BOOT_IMAGE      = 2;
84static constexpr int DEX2OAT_FOR_FILTER          = 3;
85static constexpr int DEX2OAT_FOR_RELOCATION      = 4;
86static constexpr int PATCHOAT_FOR_RELOCATION     = 5;
87
88typedef int fd_t;
89
90namespace {
91
92constexpr const char* kDump = "android.permission.DUMP";
93
94static binder::Status ok() {
95    return binder::Status::ok();
96}
97
98static binder::Status exception(uint32_t code) {
99    return binder::Status::fromExceptionCode(code);
100}
101
102static binder::Status exception(uint32_t code, const std::string& msg) {
103    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104}
105
106static binder::Status error() {
107    return binder::Status::fromServiceSpecificError(errno);
108}
109
110static binder::Status error(const std::string& msg) {
111    PLOG(ERROR) << msg;
112    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113}
114
115static binder::Status error(uint32_t code, const std::string& msg) {
116    LOG(ERROR) << msg << " (" << code << ")";
117    return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
118}
119
120binder::Status checkPermission(const char* permission) {
121    pid_t pid;
122    uid_t uid;
123
124    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
125            reinterpret_cast<int32_t*>(&uid))) {
126        return ok();
127    } else {
128        return exception(binder::Status::EX_SECURITY,
129                StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
130    }
131}
132
133binder::Status checkUid(uid_t expectedUid) {
134    uid_t uid = IPCThreadState::self()->getCallingUid();
135    if (uid == expectedUid || uid == AID_ROOT) {
136        return ok();
137    } else {
138        return exception(binder::Status::EX_SECURITY,
139                StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
140    }
141}
142
143binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
144    if (!uuid || is_valid_filename(*uuid)) {
145        return ok();
146    } else {
147        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
148                StringPrintf("UUID %s is malformed", uuid->c_str()));
149    }
150}
151
152binder::Status checkArgumentPackageName(const std::string& packageName) {
153    if (is_valid_package_name(packageName.c_str())) {
154        return ok();
155    } else {
156        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
157                StringPrintf("Package name %s is malformed", packageName.c_str()));
158    }
159}
160
161#define ENFORCE_UID(uid) {                                  \
162    binder::Status status = checkUid((uid));                \
163    if (!status.isOk()) {                                   \
164        return status;                                      \
165    }                                                       \
166}
167
168#define CHECK_ARGUMENT_UUID(uuid) {                         \
169    binder::Status status = checkArgumentUuid((uuid));      \
170    if (!status.isOk()) {                                   \
171        return status;                                      \
172    }                                                       \
173}
174
175#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
176    binder::Status status =                                 \
177            checkArgumentPackageName((packageName));        \
178    if (!status.isOk()) {                                   \
179        return status;                                      \
180    }                                                       \
181}
182
183}  // namespace
184
185status_t InstalldNativeService::start() {
186    IPCThreadState::self()->disableBackgroundScheduling(true);
187    status_t ret = BinderService<InstalldNativeService>::publish();
188    if (ret != android::OK) {
189        return ret;
190    }
191    sp<ProcessState> ps(ProcessState::self());
192    ps->startThreadPool();
193    ps->giveThreadPoolName();
194    return android::OK;
195}
196
197status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
198    const binder::Status dump_permission = checkPermission(kDump);
199    if (!dump_permission.isOk()) {
200        const String8 msg(dump_permission.toString8());
201        write(fd, msg.string(), msg.size());
202        return PERMISSION_DENIED;
203    }
204
205    std::string msg = "installd is happy\n";
206    write(fd, msg.c_str(), strlen(msg.c_str()));
207    return NO_ERROR;
208}
209
210static bool property_get_bool(const char* property_name, bool default_value = false) {
211    char tmp_property_value[kPropertyValueMax];
212    bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
213    if (!have_property) {
214        return default_value;
215    }
216    return strcmp(tmp_property_value, "true") == 0;
217}
218
219// Keep profile paths in sync with ActivityThread.
220constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
221static std::string create_primary_profile(const std::string& profile_dir) {
222    return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
223}
224
225/**
226 * Perform restorecon of the given path, but only perform recursive restorecon
227 * if the label of that top-level file actually changed.  This can save us
228 * significant time by avoiding no-op traversals of large filesystem trees.
229 */
230static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
231    int res = 0;
232    char* before = nullptr;
233    char* after = nullptr;
234
235    // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
236    // libselinux. Not needed here.
237
238    if (lgetfilecon(path.c_str(), &before) < 0) {
239        PLOG(ERROR) << "Failed before getfilecon for " << path;
240        goto fail;
241    }
242    if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
243        PLOG(ERROR) << "Failed top-level restorecon for " << path;
244        goto fail;
245    }
246    if (lgetfilecon(path.c_str(), &after) < 0) {
247        PLOG(ERROR) << "Failed after getfilecon for " << path;
248        goto fail;
249    }
250
251    // If the initial top-level restorecon above changed the label, then go
252    // back and restorecon everything recursively
253    if (strcmp(before, after)) {
254        LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
255                << "; running recursive restorecon";
256        if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
257                SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
258            PLOG(ERROR) << "Failed recursive restorecon for " << path;
259            goto fail;
260        }
261    }
262
263    goto done;
264fail:
265    res = -1;
266done:
267    free(before);
268    free(after);
269    return res;
270}
271
272static int restorecon_app_data_lazy(const std::string& parent, const char* name,
273        const std::string& seInfo, uid_t uid) {
274    return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
275}
276
277static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
278    if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
279        PLOG(ERROR) << "Failed to prepare " << path;
280        return -1;
281    }
282    return 0;
283}
284
285static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
286        uid_t uid) {
287    return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
288}
289
290binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
291        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
292        const std::string& seInfo, int32_t targetSdkVersion) {
293    ENFORCE_UID(AID_SYSTEM);
294    CHECK_ARGUMENT_UUID(uuid);
295    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
296
297    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
298    const char* pkgname = packageName.c_str();
299
300    uid_t uid = multiuser_get_uid(userId, appId);
301    mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
302    if (flags & FLAG_STORAGE_CE) {
303        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
304        if (prepare_app_dir(path, target_mode, uid) ||
305                prepare_app_dir(path, "cache", 0771, uid) ||
306                prepare_app_dir(path, "code_cache", 0771, uid)) {
307            return error("Failed to prepare " + path);
308        }
309
310        // Consider restorecon over contents if label changed
311        if (restorecon_app_data_lazy(path, seInfo, uid) ||
312                restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
313                restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
314            return error("Failed to restorecon " + path);
315        }
316
317        // Remember inode numbers of cache directories so that we can clear
318        // contents while CE storage is locked
319        if (write_path_inode(path, "cache", kXattrInodeCache) ||
320                write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
321            return error("Failed to write_path_inode for " + path);
322        }
323    }
324    if (flags & FLAG_STORAGE_DE) {
325        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
326        if (prepare_app_dir(path, target_mode, uid)) {
327            return error("Failed to prepare " + path);
328        }
329
330        // Consider restorecon over contents if label changed
331        if (restorecon_app_data_lazy(path, seInfo, uid)) {
332            return error("Failed to restorecon " + path);
333        }
334
335        if (property_get_bool("dalvik.vm.usejitprofiles")) {
336            const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
337            // read-write-execute only for the app user.
338            if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
339                return error("Failed to prepare " + profile_path);
340            }
341            std::string profile_file = create_primary_profile(profile_path);
342            // read-write only for the app user.
343            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
344                return error("Failed to prepare " + profile_path);
345            }
346            const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
347            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
348            // profiles.
349            appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
350            if (fs_prepare_dir_strict(
351                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
352                return error("Failed to prepare " + ref_profile_path);
353            }
354        }
355    }
356    return ok();
357}
358
359binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
360        const std::string& packageName, int32_t userId, int32_t flags) {
361    ENFORCE_UID(AID_SYSTEM);
362    CHECK_ARGUMENT_UUID(uuid);
363    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
364
365    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
366    const char* pkgname = packageName.c_str();
367
368    // This method only exists to upgrade system apps that have requested
369    // forceDeviceEncrypted, so their default storage always lives in a
370    // consistent location.  This only works on non-FBE devices, since we
371    // never want to risk exposing data on a device with real CE/DE storage.
372
373    auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
374    auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
375
376    // If neither directory is marked as default, assume CE is default
377    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
378            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
379        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
380            return error("Failed to mark default storage " + ce_path);
381        }
382    }
383
384    // Migrate default data location if needed
385    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
386    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
387
388    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
389        LOG(WARNING) << "Requested default storage " << target
390                << " is not active; migrating from " << source;
391        if (delete_dir_contents_and_dir(target) != 0) {
392            return error("Failed to delete " + target);
393        }
394        if (rename(source.c_str(), target.c_str()) != 0) {
395            return error("Failed to rename " + source + " to " + target);
396        }
397    }
398
399    return ok();
400}
401
402static bool clear_profile(const std::string& profile) {
403    base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
404    if (ufd.get() < 0) {
405        if (errno != ENOENT) {
406            PLOG(WARNING) << "Could not open profile " << profile;
407            return false;
408        } else {
409            // Nothing to clear. That's ok.
410            return true;
411        }
412    }
413
414    if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
415        if (errno != EWOULDBLOCK) {
416            PLOG(WARNING) << "Error locking profile " << profile;
417        }
418        // This implies that the app owning this profile is running
419        // (and has acquired the lock).
420        //
421        // If we can't acquire the lock bail out since clearing is useless anyway
422        // (the app will write again to the profile).
423        //
424        // Note:
425        // This does not impact the this is not an issue for the profiling correctness.
426        // In case this is needed because of an app upgrade, profiles will still be
427        // eventually cleared by the app itself due to checksum mismatch.
428        // If this is needed because profman advised, then keeping the data around
429        // until the next run is again not an issue.
430        //
431        // If the app attempts to acquire a lock while we've held one here,
432        // it will simply skip the current write cycle.
433        return false;
434    }
435
436    bool truncated = ftruncate(ufd.get(), 0) == 0;
437    if (!truncated) {
438        PLOG(WARNING) << "Could not truncate " << profile;
439    }
440    if (flock(ufd.get(), LOCK_UN) != 0) {
441        PLOG(WARNING) << "Error unlocking profile " << profile;
442    }
443    return truncated;
444}
445
446static bool clear_reference_profile(const char* pkgname) {
447    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
448    std::string reference_profile = create_primary_profile(reference_profile_dir);
449    return clear_profile(reference_profile);
450}
451
452static bool clear_current_profile(const char* pkgname, userid_t user) {
453    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
454    std::string profile = create_primary_profile(profile_dir);
455    return clear_profile(profile);
456}
457
458static bool clear_current_profiles(const char* pkgname) {
459    bool success = true;
460    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
461    for (auto user : users) {
462        success &= clear_current_profile(pkgname, user);
463    }
464    return success;
465}
466
467binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
468    ENFORCE_UID(AID_SYSTEM);
469    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
470
471    const char* pkgname = packageName.c_str();
472    binder::Status res = ok();
473    if (!clear_reference_profile(pkgname)) {
474        res = error("Failed to clear reference profile for " + packageName);
475    }
476    if (!clear_current_profiles(pkgname)) {
477        res = error("Failed to clear current profiles for " + packageName);
478    }
479    return res;
480}
481
482binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
483        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
484    ENFORCE_UID(AID_SYSTEM);
485    CHECK_ARGUMENT_UUID(uuid);
486    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
487
488    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
489    const char* pkgname = packageName.c_str();
490
491    binder::Status res = ok();
492    if (flags & FLAG_STORAGE_CE) {
493        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
494        if (flags & FLAG_CLEAR_CACHE_ONLY) {
495            path = read_path_inode(path, "cache", kXattrInodeCache);
496        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
497            path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
498        }
499        if (access(path.c_str(), F_OK) == 0) {
500            if (delete_dir_contents(path) != 0) {
501                res = error("Failed to delete contents of " + path);
502            }
503        }
504    }
505    if (flags & FLAG_STORAGE_DE) {
506        std::string suffix = "";
507        bool only_cache = false;
508        if (flags & FLAG_CLEAR_CACHE_ONLY) {
509            suffix = CACHE_DIR_POSTFIX;
510            only_cache = true;
511        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
512            suffix = CODE_CACHE_DIR_POSTFIX;
513            only_cache = true;
514        }
515
516        auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
517        if (access(path.c_str(), F_OK) == 0) {
518            if (delete_dir_contents(path) != 0) {
519                res = error("Failed to delete contents of " + path);
520            }
521        }
522        if (!only_cache) {
523            if (!clear_current_profile(pkgname, userId)) {
524                res = error("Failed to clear current profile for " + packageName);
525            }
526        }
527    }
528    return res;
529}
530
531static int destroy_app_reference_profile(const char *pkgname) {
532    return delete_dir_contents_and_dir(
533        create_data_ref_profile_package_path(pkgname),
534        /*ignore_if_missing*/ true);
535}
536
537static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
538    return delete_dir_contents_and_dir(
539        create_data_user_profile_package_path(userid, pkgname),
540        /*ignore_if_missing*/ true);
541}
542
543binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
544    ENFORCE_UID(AID_SYSTEM);
545    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
546
547    const char* pkgname = packageName.c_str();
548    binder::Status res = ok();
549    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
550    for (auto user : users) {
551        if (destroy_app_current_profiles(pkgname, user) != 0) {
552            res = error("Failed to destroy current profiles for " + packageName);
553        }
554    }
555    if (destroy_app_reference_profile(pkgname) != 0) {
556        res = error("Failed to destroy reference profile for " + packageName);
557    }
558    return res;
559}
560
561binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
562        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
563    ENFORCE_UID(AID_SYSTEM);
564    CHECK_ARGUMENT_UUID(uuid);
565    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
566
567    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
568    const char* pkgname = packageName.c_str();
569
570    binder::Status res = ok();
571    if (flags & FLAG_STORAGE_CE) {
572        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
573        if (delete_dir_contents_and_dir(path) != 0) {
574            res = error("Failed to delete " + path);
575        }
576    }
577    if (flags & FLAG_STORAGE_DE) {
578        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
579        if (delete_dir_contents_and_dir(path) != 0) {
580            res = error("Failed to delete " + path);
581        }
582        destroy_app_current_profiles(pkgname, userId);
583        // TODO(calin): If the package is still installed by other users it's probably
584        // beneficial to keep the reference profile around.
585        // Verify if it's ok to do that.
586        destroy_app_reference_profile(pkgname);
587    }
588    return res;
589}
590
591binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
592        const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
593        const std::string& dataAppName, int32_t appId, const std::string& seInfo,
594        int32_t targetSdkVersion) {
595    ENFORCE_UID(AID_SYSTEM);
596    CHECK_ARGUMENT_UUID(fromUuid);
597    CHECK_ARGUMENT_UUID(toUuid);
598    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
599
600    const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
601    const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
602    const char* package_name = packageName.c_str();
603    const char* data_app_name = dataAppName.c_str();
604
605    binder::Status res = ok();
606    std::vector<userid_t> users = get_known_users(from_uuid);
607
608    // Copy app
609    {
610        auto from = create_data_app_package_path(from_uuid, data_app_name);
611        auto to = create_data_app_package_path(to_uuid, data_app_name);
612        auto to_parent = create_data_app_path(to_uuid);
613
614        char *argv[] = {
615            (char*) kCpPath,
616            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
617            (char*) "-p", /* preserve timestamps, ownership, and permissions */
618            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
619            (char*) "-P", /* Do not follow symlinks [default] */
620            (char*) "-d", /* don't dereference symlinks */
621            (char*) from.c_str(),
622            (char*) to_parent.c_str()
623        };
624
625        LOG(DEBUG) << "Copying " << from << " to " << to;
626        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
627        if (rc != 0) {
628            res = error(rc, "Failed copying " + from + " to " + to);
629            goto fail;
630        }
631
632        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
633            res = error("Failed to restorecon " + to);
634            goto fail;
635        }
636    }
637
638    // Copy private data for all known users
639    for (auto user : users) {
640
641        // Data source may not exist for all users; that's okay
642        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
643        if (access(from_ce.c_str(), F_OK) != 0) {
644            LOG(INFO) << "Missing source " << from_ce;
645            continue;
646        }
647
648        if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
649                seInfo, targetSdkVersion).isOk()) {
650            res = error("Failed to create package target");
651            goto fail;
652        }
653
654        char *argv[] = {
655            (char*) kCpPath,
656            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
657            (char*) "-p", /* preserve timestamps, ownership, and permissions */
658            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
659            (char*) "-P", /* Do not follow symlinks [default] */
660            (char*) "-d", /* don't dereference symlinks */
661            nullptr,
662            nullptr
663        };
664
665        {
666            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
667            auto to = create_data_user_de_path(to_uuid, user);
668            argv[6] = (char*) from.c_str();
669            argv[7] = (char*) to.c_str();
670
671            LOG(DEBUG) << "Copying " << from << " to " << to;
672            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
673            if (rc != 0) {
674                res = error(rc, "Failed copying " + from + " to " + to);
675                goto fail;
676            }
677        }
678        {
679            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
680            auto to = create_data_user_ce_path(to_uuid, user);
681            argv[6] = (char*) from.c_str();
682            argv[7] = (char*) to.c_str();
683
684            LOG(DEBUG) << "Copying " << from << " to " << to;
685            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
686            if (rc != 0) {
687                res = error(rc, "Failed copying " + from + " to " + to);
688                goto fail;
689            }
690        }
691
692        if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
693                appId, seInfo).isOk()) {
694            res = error("Failed to restorecon");
695            goto fail;
696        }
697    }
698
699    // We let the framework scan the new location and persist that before
700    // deleting the data in the old location; this ordering ensures that
701    // we can recover from things like battery pulls.
702    return ok();
703
704fail:
705    // Nuke everything we might have already copied
706    {
707        auto to = create_data_app_package_path(to_uuid, data_app_name);
708        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
709            LOG(WARNING) << "Failed to rollback " << to;
710        }
711    }
712    for (auto user : users) {
713        {
714            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
715            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
716                LOG(WARNING) << "Failed to rollback " << to;
717            }
718        }
719        {
720            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
721            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
722                LOG(WARNING) << "Failed to rollback " << to;
723            }
724        }
725    }
726    return res;
727}
728
729binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
730        int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
731    ENFORCE_UID(AID_SYSTEM);
732    CHECK_ARGUMENT_UUID(uuid);
733
734    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
735    if (flags & FLAG_STORAGE_DE) {
736        if (uuid_ == nullptr) {
737            if (ensure_config_user_dirs(userId) != 0) {
738                return error(StringPrintf("Failed to ensure dirs for %d", userId));
739            }
740        }
741    }
742    return ok();
743}
744
745binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
746        int32_t userId, int32_t flags) {
747    ENFORCE_UID(AID_SYSTEM);
748    CHECK_ARGUMENT_UUID(uuid);
749
750    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
751    binder::Status res = ok();
752    if (flags & FLAG_STORAGE_DE) {
753        auto path = create_data_user_de_path(uuid_, userId);
754        if (delete_dir_contents_and_dir(path, true) != 0) {
755            res = error("Failed to delete " + path);
756        }
757        if (uuid_ == nullptr) {
758            path = create_data_misc_legacy_path(userId);
759            if (delete_dir_contents_and_dir(path, true) != 0) {
760                res = error("Failed to delete " + path);
761            }
762            path = create_data_user_profiles_path(userId);
763            if (delete_dir_contents_and_dir(path, true) != 0) {
764                res = error("Failed to delete " + path);
765            }
766        }
767    }
768    if (flags & FLAG_STORAGE_CE) {
769        auto path = create_data_user_ce_path(uuid_, userId);
770        if (delete_dir_contents_and_dir(path, true) != 0) {
771            res = error("Failed to delete " + path);
772        }
773        path = create_data_media_path(uuid_, userId);
774        if (delete_dir_contents_and_dir(path, true) != 0) {
775            res = error("Failed to delete " + path);
776        }
777    }
778    return res;
779}
780
781/* Try to ensure free_size bytes of storage are available.
782 * Returns 0 on success.
783 * This is rather simple-minded because doing a full LRU would
784 * be potentially memory-intensive, and without atime it would
785 * also require that apps constantly modify file metadata even
786 * when just reading from the cache, which is pretty awful.
787 */
788binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
789        int64_t freeStorageSize) {
790    ENFORCE_UID(AID_SYSTEM);
791    CHECK_ARGUMENT_UUID(uuid);
792
793    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
794    cache_t* cache;
795    int64_t avail;
796
797    auto data_path = create_data_path(uuid_);
798
799    avail = data_disk_free(data_path);
800    if (avail < 0) {
801        return error("Failed to determine free space for " + data_path);
802    }
803
804    ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
805    if (avail >= freeStorageSize) {
806        return ok();
807    }
808
809    cache = start_cache_collection();
810
811    auto users = get_known_users(uuid_);
812    for (auto user : users) {
813        add_cache_files(cache, create_data_user_ce_path(uuid_, user));
814        add_cache_files(cache, create_data_user_de_path(uuid_, user));
815        add_cache_files(cache,
816                StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
817    }
818
819    clear_cache_files(data_path, cache, freeStorageSize);
820    finish_cache_collection(cache);
821
822    avail = data_disk_free(data_path);
823    if (avail >= freeStorageSize) {
824        return ok();
825    } else {
826        return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
827                freeStorageSize, data_path.c_str(), avail));
828    }
829}
830
831binder::Status InstalldNativeService::rmdex(const std::string& codePath,
832        const std::string& instructionSet) {
833    ENFORCE_UID(AID_SYSTEM);
834    char dex_path[PKG_PATH_MAX];
835
836    const char* path = codePath.c_str();
837    const char* instruction_set = instructionSet.c_str();
838
839    if (validate_apk_path(path) && validate_system_app_path(path)) {
840        return error("Invalid path " + codePath);
841    }
842
843    if (!create_cache_path(dex_path, path, instruction_set)) {
844        return error("Failed to create cache path for " + codePath);
845    }
846
847    ALOGV("unlink %s\n", dex_path);
848    if (unlink(dex_path) < 0) {
849        return error(StringPrintf("Failed to unlink %s", dex_path));
850    } else {
851        return ok();
852    }
853}
854
855static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
856        int64_t *cachesize) {
857    DIR *d;
858    int dfd;
859    struct dirent *de;
860    struct stat s;
861
862    d = opendir(path.c_str());
863    if (d == nullptr) {
864        PLOG(WARNING) << "Failed to open " << path;
865        return;
866    }
867    dfd = dirfd(d);
868    while ((de = readdir(d))) {
869        const char *name = de->d_name;
870
871        int64_t statsize = 0;
872        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
873            statsize = stat_size(&s);
874        }
875
876        if (de->d_type == DT_DIR) {
877            int subfd;
878            int64_t dirsize = 0;
879            /* always skip "." and ".." */
880            if (name[0] == '.') {
881                if (name[1] == 0) continue;
882                if ((name[1] == '.') && (name[2] == 0)) continue;
883            }
884            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
885            if (subfd >= 0) {
886                dirsize = calculate_dir_size(subfd);
887                close(subfd);
888            }
889            // TODO: check xattrs!
890            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
891                *datasize += statsize;
892                *cachesize += dirsize;
893            } else {
894                *datasize += dirsize + statsize;
895            }
896        } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
897            *codesize += statsize;
898        } else {
899            *datasize += statsize;
900        }
901    }
902    closedir(d);
903}
904
905binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
906        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
907        const std::string& codePath, std::vector<int64_t>* _aidl_return) {
908    ENFORCE_UID(AID_SYSTEM);
909    CHECK_ARGUMENT_UUID(uuid);
910    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
911
912    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
913    const char* pkgname = packageName.c_str();
914    const char* code_path = codePath.c_str();
915
916    DIR *d;
917    int dfd;
918    int64_t codesize = 0;
919    int64_t datasize = 0;
920    int64_t cachesize = 0;
921    int64_t asecsize = 0;
922
923    d = opendir(code_path);
924    if (d != nullptr) {
925        dfd = dirfd(d);
926        codesize += calculate_dir_size(dfd);
927        closedir(d);
928    }
929
930    if (flags & FLAG_STORAGE_CE) {
931        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
932        add_app_data_size(path, &codesize, &datasize, &cachesize);
933    }
934    if (flags & FLAG_STORAGE_DE) {
935        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
936        add_app_data_size(path, &codesize, &datasize, &cachesize);
937    }
938
939    std::vector<int64_t> res;
940    res.push_back(codesize);
941    res.push_back(datasize);
942    res.push_back(cachesize);
943    res.push_back(asecsize);
944    *_aidl_return = res;
945    return ok();
946}
947
948binder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
949        const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
950    ENFORCE_UID(AID_SYSTEM);
951    CHECK_ARGUMENT_UUID(uuid);
952    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
953
954    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
955    const char* pkgname = packageName.c_str();
956
957    if (flags & FLAG_STORAGE_CE) {
958        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
959        if (get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) == 0) {
960            return ok();
961        } else {
962            return error("Failed to get_path_inode for " + path);
963        }
964    }
965    return exception(binder::Status::EX_UNSUPPORTED_OPERATION);
966}
967
968static int split_count(const char *str)
969{
970  char *ctx;
971  int count = 0;
972  char buf[kPropertyValueMax];
973
974  strncpy(buf, str, sizeof(buf));
975  char *pBuf = buf;
976
977  while(strtok_r(pBuf, " ", &ctx) != NULL) {
978    count++;
979    pBuf = NULL;
980  }
981
982  return count;
983}
984
985static int split(char *buf, const char **argv)
986{
987  char *ctx;
988  int count = 0;
989  char *tok;
990  char *pBuf = buf;
991
992  while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
993    argv[count++] = tok;
994    pBuf = NULL;
995  }
996
997  return count;
998}
999
1000static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
1001    const char* input_oat_file_name, const char* input_vdex_file_name,
1002    const char* output_oat_file_name, const char* output_vdex_file_name,
1003    const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
1004{
1005    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
1006    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1007
1008    static const char* PATCHOAT_BIN = "/system/bin/patchoat";
1009    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1010        ALOGE("Instruction set %s longer than max length of %d",
1011              instruction_set, MAX_INSTRUCTION_SET_LEN);
1012        return;
1013    }
1014
1015    /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
1016    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
1017    char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
1018    char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1019    char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
1020    char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
1021    const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
1022    // The caller has already gotten all the locks we need.
1023    const char* no_lock_arg = "--no-lock-output";
1024    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
1025    sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
1026    sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
1027    ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
1028          "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
1029          PATCHOAT_BIN, instruction_set,
1030          input_oat_fd, input_oat_file_name,
1031          input_vdex_fd, input_vdex_file_name,
1032          out_oat_fd, output_oat_file_name,
1033          out_vdex_fd, output_vdex_file_name);
1034
1035    /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
1036    char* argv[9];
1037    argv[0] = (char*) PATCHOAT_BIN;
1038    argv[1] = (char*) patched_image_location_arg;
1039    argv[2] = (char*) no_lock_arg;
1040    argv[3] = instruction_set_arg;
1041    argv[4] = input_oat_fd_arg;
1042    argv[5] = input_vdex_fd_arg;
1043    argv[6] = output_oat_fd_arg;
1044    argv[7] = output_vdex_fd_arg;
1045    argv[8] = NULL;
1046
1047    execv(PATCHOAT_BIN, (char* const *)argv);
1048    ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
1049}
1050
1051static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
1052        const char* input_file_name, const char* output_file_name, int swap_fd,
1053        const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
1054        bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
1055    static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1056
1057    if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1058        ALOGE("Instruction set %s longer than max length of %d",
1059              instruction_set, MAX_INSTRUCTION_SET_LEN);
1060        return;
1061    }
1062
1063    char dex2oat_Xms_flag[kPropertyValueMax];
1064    bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
1065
1066    char dex2oat_Xmx_flag[kPropertyValueMax];
1067    bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
1068
1069    char dex2oat_threads_buf[kPropertyValueMax];
1070    bool have_dex2oat_threads_flag = get_property(post_bootcomplete
1071                                                      ? "dalvik.vm.dex2oat-threads"
1072                                                      : "dalvik.vm.boot-dex2oat-threads",
1073                                                  dex2oat_threads_buf,
1074                                                  NULL) > 0;
1075    char dex2oat_threads_arg[kPropertyValueMax + 2];
1076    if (have_dex2oat_threads_flag) {
1077        sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
1078    }
1079
1080    char dex2oat_isa_features_key[kPropertyKeyMax];
1081    sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
1082    char dex2oat_isa_features[kPropertyValueMax];
1083    bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
1084                                                  dex2oat_isa_features, NULL) > 0;
1085
1086    char dex2oat_isa_variant_key[kPropertyKeyMax];
1087    sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
1088    char dex2oat_isa_variant[kPropertyValueMax];
1089    bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
1090                                                 dex2oat_isa_variant, NULL) > 0;
1091
1092    const char *dex2oat_norelocation = "-Xnorelocate";
1093    bool have_dex2oat_relocation_skip_flag = false;
1094
1095    char dex2oat_flags[kPropertyValueMax];
1096    int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
1097                                 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
1098    ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
1099
1100    // If we booting without the real /data, don't spend time compiling.
1101    char vold_decrypt[kPropertyValueMax];
1102    bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
1103    bool skip_compilation = (have_vold_decrypt &&
1104                             (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
1105                             (strcmp(vold_decrypt, "1") == 0)));
1106
1107    bool generate_debug_info = property_get_bool("debug.generate-debug-info");
1108
1109    char app_image_format[kPropertyValueMax];
1110    char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
1111    bool have_app_image_format =
1112            image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1113    if (have_app_image_format) {
1114        sprintf(image_format_arg, "--image-format=%s", app_image_format);
1115    }
1116
1117    char dex2oat_large_app_threshold[kPropertyValueMax];
1118    bool have_dex2oat_large_app_threshold =
1119            get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
1120    char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
1121    if (have_dex2oat_large_app_threshold) {
1122        sprintf(dex2oat_large_app_threshold_arg,
1123                "--very-large-app-threshold=%s",
1124                dex2oat_large_app_threshold);
1125    }
1126
1127    static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
1128
1129    static const char* RUNTIME_ARG = "--runtime-arg";
1130
1131    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
1132
1133    char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
1134    char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
1135    char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1136    char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
1137    char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
1138    char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
1139    char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
1140    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
1141    char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
1142    char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
1143    char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
1144    char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
1145    bool have_dex2oat_swap_fd = false;
1146    char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
1147    bool have_dex2oat_image_fd = false;
1148    char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
1149
1150    sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
1151    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
1152    sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
1153    sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
1154    sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
1155    sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
1156    sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
1157    sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
1158    sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
1159    if (swap_fd >= 0) {
1160        have_dex2oat_swap_fd = true;
1161        sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1162    }
1163    if (image_fd >= 0) {
1164        have_dex2oat_image_fd = true;
1165        sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1166    }
1167
1168    if (have_dex2oat_Xms_flag) {
1169        sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1170    }
1171    if (have_dex2oat_Xmx_flag) {
1172        sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1173    }
1174
1175    // Compute compiler filter.
1176
1177    bool have_dex2oat_compiler_filter_flag;
1178    if (skip_compilation) {
1179        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
1180        have_dex2oat_compiler_filter_flag = true;
1181        have_dex2oat_relocation_skip_flag = true;
1182    } else if (vm_safe_mode) {
1183        strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
1184        have_dex2oat_compiler_filter_flag = true;
1185    } else if (compiler_filter != nullptr &&
1186            strlen(compiler_filter) + strlen("--compiler-filter=") <
1187                    arraysize(dex2oat_compiler_filter_arg)) {
1188        sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1189        have_dex2oat_compiler_filter_flag = true;
1190    } else {
1191        char dex2oat_compiler_filter_flag[kPropertyValueMax];
1192        have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
1193                                                         dex2oat_compiler_filter_flag, NULL) > 0;
1194        if (have_dex2oat_compiler_filter_flag) {
1195            sprintf(dex2oat_compiler_filter_arg,
1196                    "--compiler-filter=%s",
1197                    dex2oat_compiler_filter_flag);
1198        }
1199    }
1200
1201    // Check whether all apps should be compiled debuggable.
1202    if (!debuggable) {
1203        char prop_buf[kPropertyValueMax];
1204        debuggable =
1205                (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
1206                (prop_buf[0] == '1');
1207    }
1208    char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
1209    if (profile_fd != -1) {
1210        sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
1211    }
1212
1213
1214    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
1215
1216    const char* argv[9  // program name, mandatory arguments and the final NULL
1217                     + (have_dex2oat_isa_variant ? 1 : 0)
1218                     + (have_dex2oat_isa_features ? 1 : 0)
1219                     + (have_dex2oat_Xms_flag ? 2 : 0)
1220                     + (have_dex2oat_Xmx_flag ? 2 : 0)
1221                     + (have_dex2oat_compiler_filter_flag ? 1 : 0)
1222                     + (have_dex2oat_threads_flag ? 1 : 0)
1223                     + (have_dex2oat_swap_fd ? 1 : 0)
1224                     + (have_dex2oat_image_fd ? 1 : 0)
1225                     + (have_dex2oat_relocation_skip_flag ? 2 : 0)
1226                     + (generate_debug_info ? 1 : 0)
1227                     + (debuggable ? 1 : 0)
1228                     + (have_app_image_format ? 1 : 0)
1229                     + dex2oat_flags_count
1230                     + (profile_fd == -1 ? 0 : 1)
1231                     + (shared_libraries != nullptr ? 4 : 0)
1232                     + (have_dex2oat_large_app_threshold ? 1 : 0)];
1233    int i = 0;
1234    argv[i++] = DEX2OAT_BIN;
1235    argv[i++] = zip_fd_arg;
1236    argv[i++] = zip_location_arg;
1237    argv[i++] = input_vdex_fd_arg;
1238    argv[i++] = output_vdex_fd_arg;
1239    argv[i++] = oat_fd_arg;
1240    argv[i++] = oat_location_arg;
1241    argv[i++] = instruction_set_arg;
1242    if (have_dex2oat_isa_variant) {
1243        argv[i++] = instruction_set_variant_arg;
1244    }
1245    if (have_dex2oat_isa_features) {
1246        argv[i++] = instruction_set_features_arg;
1247    }
1248    if (have_dex2oat_Xms_flag) {
1249        argv[i++] = RUNTIME_ARG;
1250        argv[i++] = dex2oat_Xms_arg;
1251    }
1252    if (have_dex2oat_Xmx_flag) {
1253        argv[i++] = RUNTIME_ARG;
1254        argv[i++] = dex2oat_Xmx_arg;
1255    }
1256    if (have_dex2oat_compiler_filter_flag) {
1257        argv[i++] = dex2oat_compiler_filter_arg;
1258    }
1259    if (have_dex2oat_threads_flag) {
1260        argv[i++] = dex2oat_threads_arg;
1261    }
1262    if (have_dex2oat_swap_fd) {
1263        argv[i++] = dex2oat_swap_fd;
1264    }
1265    if (have_dex2oat_image_fd) {
1266        argv[i++] = dex2oat_image_fd;
1267    }
1268    if (generate_debug_info) {
1269        argv[i++] = "--generate-debug-info";
1270    }
1271    if (debuggable) {
1272        argv[i++] = "--debuggable";
1273    }
1274    if (have_app_image_format) {
1275        argv[i++] = image_format_arg;
1276    }
1277    if (have_dex2oat_large_app_threshold) {
1278        argv[i++] = dex2oat_large_app_threshold_arg;
1279    }
1280    if (dex2oat_flags_count) {
1281        i += split(dex2oat_flags, argv + i);
1282    }
1283    if (have_dex2oat_relocation_skip_flag) {
1284        argv[i++] = RUNTIME_ARG;
1285        argv[i++] = dex2oat_norelocation;
1286    }
1287    if (profile_fd != -1) {
1288        argv[i++] = profile_arg;
1289    }
1290    if (shared_libraries != nullptr) {
1291        argv[i++] = RUNTIME_ARG;
1292        argv[i++] = "-classpath";
1293        argv[i++] = RUNTIME_ARG;
1294        argv[i++] = shared_libraries;
1295    }
1296    // Do not add after dex2oat_flags, they should override others for debugging.
1297    argv[i] = NULL;
1298
1299    execv(DEX2OAT_BIN, (char * const *)argv);
1300    ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
1301}
1302
1303/*
1304 * Whether dexopt should use a swap file when compiling an APK.
1305 *
1306 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1307 * itself, anyways).
1308 *
1309 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1310 *
1311 * Otherwise, return true if this is a low-mem device.
1312 *
1313 * Otherwise, return default value.
1314 */
1315static bool kAlwaysProvideSwapFile = false;
1316static bool kDefaultProvideSwapFile = true;
1317
1318static bool ShouldUseSwapFileForDexopt() {
1319    if (kAlwaysProvideSwapFile) {
1320        return true;
1321    }
1322
1323    // Check the "override" property. If it exists, return value == "true".
1324    char dex2oat_prop_buf[kPropertyValueMax];
1325    if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
1326        if (strcmp(dex2oat_prop_buf, "true") == 0) {
1327            return true;
1328        } else {
1329            return false;
1330        }
1331    }
1332
1333    // Shortcut for default value. This is an implementation optimization for the process sketched
1334    // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1335    // as low-mem is never returning false. The compiler will optimize this away if it can.
1336    if (kDefaultProvideSwapFile) {
1337        return true;
1338    }
1339
1340    bool is_low_mem = property_get_bool("ro.config.low_ram");
1341    if (is_low_mem) {
1342        return true;
1343    }
1344
1345    // Default value must be false here.
1346    return kDefaultProvideSwapFile;
1347}
1348
1349static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
1350    if (set_to_bg) {
1351        if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1352            ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1353            exit(70);
1354        }
1355        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1356            ALOGE("setpriority failed: %s\n", strerror(errno));
1357            exit(71);
1358        }
1359    }
1360}
1361
1362static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
1363    for (size_t i = 0; i < fds.size(); i++) {
1364        if (close(fds[i]) != 0) {
1365            PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
1366        }
1367    }
1368}
1369
1370static fd_t open_profile_dir(const std::string& profile_dir) {
1371    fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
1372            O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
1373    if (profile_dir_fd < 0) {
1374        // In a multi-user environment, these directories can be created at
1375        // different points and it's possible we'll attempt to open a profile
1376        // dir before it exists.
1377        if (errno != ENOENT) {
1378            PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
1379        }
1380    }
1381    return profile_dir_fd;
1382}
1383
1384static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1385    fd_t profile_dir_fd  = open_profile_dir(profile_dir);
1386    if (profile_dir_fd < 0) {
1387        return -1;
1388    }
1389
1390    fd_t profile_fd = -1;
1391    std::string profile_file = create_primary_profile(profile_dir);
1392
1393    profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1394    if (profile_fd == -1) {
1395        // It's not an error if the profile file does not exist.
1396        if (errno != ENOENT) {
1397            PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1398        }
1399    }
1400    // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1401    if (close(profile_dir_fd) != 0) {
1402        PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1403    }
1404    return profile_fd;
1405}
1406
1407static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1408    std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1409    return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1410}
1411
1412static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1413    std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1414    int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1415    fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1416    if (fd < 0) {
1417        return -1;
1418    }
1419    if (read_write) {
1420        // Fix the owner.
1421        if (fchown(fd, uid, uid) < 0) {
1422            close(fd);
1423            return -1;
1424        }
1425    }
1426    return fd;
1427}
1428
1429static void open_profile_files(uid_t uid, const char* pkgname,
1430            /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1431    // Open the reference profile in read-write mode as profman might need to save the merge.
1432    *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
1433    if (*reference_profile_fd < 0) {
1434        // We can't access the reference profile file.
1435        return;
1436    }
1437
1438    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1439    for (auto user : users) {
1440        fd_t profile_fd = open_primary_profile_file(user, pkgname);
1441        // Add to the lists only if both fds are valid.
1442        if (profile_fd >= 0) {
1443            profiles_fd->push_back(profile_fd);
1444        }
1445    }
1446}
1447
1448static void drop_capabilities(uid_t uid) {
1449    if (setgid(uid) != 0) {
1450        ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1451        exit(64);
1452    }
1453    if (setuid(uid) != 0) {
1454        ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1455        exit(65);
1456    }
1457    // drop capabilities
1458    struct __user_cap_header_struct capheader;
1459    struct __user_cap_data_struct capdata[2];
1460    memset(&capheader, 0, sizeof(capheader));
1461    memset(&capdata, 0, sizeof(capdata));
1462    capheader.version = _LINUX_CAPABILITY_VERSION_3;
1463    if (capset(&capheader, &capdata[0]) < 0) {
1464        ALOGE("capset failed: %s\n", strerror(errno));
1465        exit(66);
1466    }
1467}
1468
1469static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1470static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1471static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1472static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1473static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1474
1475static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
1476    static const size_t MAX_INT_LEN = 32;
1477    static const char* PROFMAN_BIN = "/system/bin/profman";
1478
1479    std::vector<std::string> profile_args(profiles_fd.size());
1480    char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1481    for (size_t k = 0; k < profiles_fd.size(); k++) {
1482        sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1483        profile_args[k].assign(profile_buf);
1484    }
1485    char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1486    sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1487
1488    // program name, reference profile fd, the final NULL and the profile fds
1489    const char* argv[3 + profiles_fd.size()];
1490    int i = 0;
1491    argv[i++] = PROFMAN_BIN;
1492    argv[i++] = reference_profile_arg;
1493    for (size_t k = 0; k < profile_args.size(); k++) {
1494        argv[i++] = profile_args[k].c_str();
1495    }
1496    // Do not add after dex2oat_flags, they should override others for debugging.
1497    argv[i] = NULL;
1498
1499    execv(PROFMAN_BIN, (char * const *)argv);
1500    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1501    exit(68);   /* only get here on exec failure */
1502}
1503
1504// Decides if profile guided compilation is needed or not based on existing profiles.
1505// Returns true if there is enough information in the current profiles that worth
1506// a re-compilation of the package.
1507// If the return value is true all the current profiles would have been merged into
1508// the reference profiles accessible with open_reference_profile().
1509static bool analyse_profiles(uid_t uid, const char* pkgname) {
1510    std::vector<fd_t> profiles_fd;
1511    fd_t reference_profile_fd = -1;
1512    open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1513    if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1514        // Skip profile guided compilation because no profiles were found.
1515        // Or if the reference profile info couldn't be opened.
1516        close_all_fds(profiles_fd, "profiles_fd");
1517        if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1518            PLOG(WARNING) << "Failed to close fd for reference profile";
1519        }
1520        return false;
1521    }
1522
1523    ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
1524
1525    pid_t pid = fork();
1526    if (pid == 0) {
1527        /* child -- drop privileges before continuing */
1528        drop_capabilities(uid);
1529        run_profman_merge(profiles_fd, reference_profile_fd);
1530        exit(68);   /* only get here on exec failure */
1531    }
1532    /* parent */
1533    int return_code = wait_child(pid);
1534    bool need_to_compile = false;
1535    bool should_clear_current_profiles = false;
1536    bool should_clear_reference_profile = false;
1537    if (!WIFEXITED(return_code)) {
1538        LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1539    } else {
1540        return_code = WEXITSTATUS(return_code);
1541        switch (return_code) {
1542            case PROFMAN_BIN_RETURN_CODE_COMPILE:
1543                need_to_compile = true;
1544                should_clear_current_profiles = true;
1545                should_clear_reference_profile = false;
1546                break;
1547            case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1548                need_to_compile = false;
1549                should_clear_current_profiles = false;
1550                should_clear_reference_profile = false;
1551                break;
1552            case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1553                LOG(WARNING) << "Bad profiles for package " << pkgname;
1554                need_to_compile = false;
1555                should_clear_current_profiles = true;
1556                should_clear_reference_profile = true;
1557                break;
1558            case PROFMAN_BIN_RETURN_CODE_ERROR_IO:  // fall-through
1559            case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1560                // Temporary IO problem (e.g. locking). Ignore but log a warning.
1561                LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1562                need_to_compile = false;
1563                should_clear_current_profiles = false;
1564                should_clear_reference_profile = false;
1565                break;
1566           default:
1567                // Unknown return code or error. Unlink profiles.
1568                LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1569                        << ": " << return_code;
1570                need_to_compile = false;
1571                should_clear_current_profiles = true;
1572                should_clear_reference_profile = true;
1573                break;
1574        }
1575    }
1576    close_all_fds(profiles_fd, "profiles_fd");
1577    if (close(reference_profile_fd) != 0) {
1578        PLOG(WARNING) << "Failed to close fd for reference profile";
1579    }
1580    if (should_clear_current_profiles) {
1581        clear_current_profiles(pkgname);
1582    }
1583    if (should_clear_reference_profile) {
1584        clear_reference_profile(pkgname);
1585    }
1586    return need_to_compile;
1587}
1588
1589static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1590                             fd_t reference_profile_fd,
1591                             const std::vector<std::string>& dex_locations,
1592                             const std::vector<fd_t>& apk_fds,
1593                             fd_t output_fd) {
1594    std::vector<std::string> profman_args;
1595    static const char* PROFMAN_BIN = "/system/bin/profman";
1596    profman_args.push_back(PROFMAN_BIN);
1597    profman_args.push_back("--dump-only");
1598    profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1599    if (reference_profile_fd != -1) {
1600        profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1601                                            reference_profile_fd));
1602    }
1603    for (fd_t profile_fd : profile_fds) {
1604        profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
1605    }
1606    for (const std::string& dex_location : dex_locations) {
1607        profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
1608    }
1609    for (fd_t apk_fd : apk_fds) {
1610        profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1611    }
1612    const char **argv = new const char*[profman_args.size() + 1];
1613    size_t i = 0;
1614    for (const std::string& profman_arg : profman_args) {
1615        argv[i++] = profman_arg.c_str();
1616    }
1617    argv[i] = NULL;
1618
1619    execv(PROFMAN_BIN, (char * const *)argv);
1620    ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1621    exit(68);   /* only get here on exec failure */
1622}
1623
1624static const char* get_location_from_path(const char* path) {
1625    static constexpr char kLocationSeparator = '/';
1626    const char *location = strrchr(path, kLocationSeparator);
1627    if (location == NULL) {
1628        return path;
1629    } else {
1630        // Skip the separator character.
1631        return location + 1;
1632    }
1633}
1634
1635// Dumps the contents of a profile file, using pkgname's dex files for pretty
1636// printing the result.
1637binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1638        const std::string& codePaths, bool* _aidl_return) {
1639    ENFORCE_UID(AID_SYSTEM);
1640    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1641
1642    const char* pkgname = packageName.c_str();
1643    const char* code_path_string = codePaths.c_str();
1644
1645    std::vector<fd_t> profile_fds;
1646    fd_t reference_profile_fd = -1;
1647    std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1648
1649    ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1650
1651    open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1652
1653    const bool has_reference_profile = (reference_profile_fd != -1);
1654    const bool has_profiles = !profile_fds.empty();
1655
1656    if (!has_reference_profile && !has_profiles) {
1657        ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
1658        *_aidl_return = false;
1659        return ok();
1660    }
1661
1662    fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
1663    if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1664        ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
1665        *_aidl_return = false;
1666        return ok();
1667    }
1668    std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1669    std::vector<std::string> dex_locations;
1670    std::vector<fd_t> apk_fds;
1671    for (const std::string& code_full_path : code_full_paths) {
1672        const char* full_path = code_full_path.c_str();
1673        fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1674        if (apk_fd == -1) {
1675            ALOGE("installd cannot open '%s'\n", full_path);
1676            *_aidl_return = false;
1677            return ok();
1678        }
1679        dex_locations.push_back(get_location_from_path(full_path));
1680        apk_fds.push_back(apk_fd);
1681    }
1682
1683    pid_t pid = fork();
1684    if (pid == 0) {
1685        /* child -- drop privileges before continuing */
1686        drop_capabilities(uid);
1687        run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1688                         apk_fds, output_fd);
1689        exit(68);   /* only get here on exec failure */
1690    }
1691    /* parent */
1692    close_all_fds(apk_fds, "apk_fds");
1693    close_all_fds(profile_fds, "profile_fds");
1694    if (close(reference_profile_fd) != 0) {
1695        PLOG(WARNING) << "Failed to close fd for reference profile";
1696    }
1697    int return_code = wait_child(pid);
1698    if (!WIFEXITED(return_code)) {
1699        LOG(WARNING) << "profman failed for package " << pkgname << ": "
1700                << return_code;
1701        *_aidl_return = false;
1702        return ok();
1703    }
1704    *_aidl_return = true;
1705    return ok();
1706}
1707
1708static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1709  // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1710  if (EndsWith(oat_path, ".dex")) {
1711    std::string new_path = oat_path;
1712    new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1713    CHECK(EndsWith(new_path, new_ext.c_str()));
1714    return new_path;
1715  }
1716
1717  // An odex entry. Not that this may not be an extension, e.g., in the OTA
1718  // case (where the base name will have an extension for the B artifact).
1719  size_t odex_pos = oat_path.rfind(".odex");
1720  if (odex_pos != std::string::npos) {
1721    std::string new_path = oat_path;
1722    new_path.replace(odex_pos, strlen(".odex"), new_ext);
1723    CHECK_NE(new_path.find(new_ext), std::string::npos);
1724    return new_path;
1725  }
1726
1727  // Don't know how to handle this.
1728  return "";
1729}
1730
1731// Translate the given oat path to an art (app image) path. An empty string
1732// denotes an error.
1733static std::string create_image_filename(const std::string& oat_path) {
1734    return replace_file_extension(oat_path, ".art");
1735}
1736
1737// Translate the given oat path to a vdex path. An empty string denotes an error.
1738static std::string create_vdex_filename(const std::string& oat_path) {
1739    return replace_file_extension(oat_path, ".vdex");
1740}
1741
1742static bool add_extension_to_file_name(char* file_name, const char* extension) {
1743    if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1744        return false;
1745    }
1746    strcat(file_name, extension);
1747    return true;
1748}
1749
1750static int open_output_file(const char* file_name, bool recreate, int permissions) {
1751    int flags = O_RDWR | O_CREAT;
1752    if (recreate) {
1753        if (unlink(file_name) < 0) {
1754            if (errno != ENOENT) {
1755                PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1756            }
1757        }
1758        flags |= O_EXCL;
1759    }
1760    return open(file_name, flags, permissions);
1761}
1762
1763static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1764    if (fchmod(fd,
1765               S_IRUSR|S_IWUSR|S_IRGRP |
1766               (is_public ? S_IROTH : 0)) < 0) {
1767        ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1768        return false;
1769    } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1770        ALOGE("installd cannot chown '%s' during dexopt\n", path);
1771        return false;
1772    }
1773    return true;
1774}
1775
1776static bool IsOutputDalvikCache(const char* oat_dir) {
1777  // InstallerConnection.java (which invokes installd) transforms Java null arguments
1778  // into '!'. Play it safe by handling it both.
1779  // TODO: ensure we never get null.
1780  // TODO: pass a flag instead of inferring if the output is dalvik cache.
1781  return oat_dir == nullptr || oat_dir[0] == '!';
1782}
1783
1784static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
1785            const char* oat_dir, /*out*/ char* out_oat_path) {
1786    // Early best-effort check whether we can fit the the path into our buffers.
1787    // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1788    // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1789    // extension to the cache path (5 bytes).
1790    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1791        ALOGE("apk_path too long '%s'\n", apk_path);
1792        return false;
1793    }
1794
1795    if (!IsOutputDalvikCache(oat_dir)) {
1796        if (validate_apk_path(oat_dir)) {
1797            ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1798            return false;
1799        }
1800        if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1801            return false;
1802        }
1803    } else {
1804        if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1805            return false;
1806        }
1807    }
1808    return true;
1809}
1810
1811// TODO: Consider returning error codes.
1812binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1813        bool* _aidl_return) {
1814    ENFORCE_UID(AID_SYSTEM);
1815    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1816
1817    const char* pkgname = packageName.c_str();
1818    *_aidl_return = analyse_profiles(uid, pkgname);
1819    return ok();
1820}
1821
1822// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1823// on destruction. It will also run the given cleanup (unless told not to) after closing.
1824//
1825// Usage example:
1826//
1827//   Dex2oatFileWrapper<std::function<void ()>> file(open(...),
1828//                                                   [name]() {
1829//                                                       unlink(name.c_str());
1830//                                                   });
1831//   // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1832//            wrapper if captured as a reference.
1833//
1834//   if (file.get() == -1) {
1835//       // Error opening...
1836//   }
1837//
1838//   ...
1839//   if (error) {
1840//       // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1841//       // and delete the file (after the fd is closed).
1842//       return -1;
1843//   }
1844//
1845//   (Success case)
1846//   file.SetCleanup(false);
1847//   // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1848//   // (leaving the file around; after the fd is closed).
1849//
1850template <typename Cleanup>
1851class Dex2oatFileWrapper {
1852 public:
1853    Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
1854    }
1855
1856    Dex2oatFileWrapper(int value, Cleanup cleanup)
1857            : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
1858
1859    ~Dex2oatFileWrapper() {
1860        reset(-1);
1861    }
1862
1863    int get() {
1864        return value_;
1865    }
1866
1867    void SetCleanup(bool cleanup) {
1868        do_cleanup_ = cleanup;
1869    }
1870
1871    void reset(int new_value) {
1872        if (value_ >= 0) {
1873            close(value_);
1874        }
1875        if (do_cleanup_ && cleanup_ != nullptr) {
1876            cleanup_();
1877        }
1878
1879        value_ = new_value;
1880    }
1881
1882    void reset(int new_value, Cleanup new_cleanup) {
1883        if (value_ >= 0) {
1884            close(value_);
1885        }
1886        if (do_cleanup_ && cleanup_ != nullptr) {
1887            cleanup_();
1888        }
1889
1890        value_ = new_value;
1891        cleanup_ = new_cleanup;
1892    }
1893
1894 private:
1895    int value_;
1896    Cleanup cleanup_;
1897    bool do_cleanup_;
1898};
1899
1900// TODO: eventually move dexopt() implementation into dexopt.cpp
1901int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1902        int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1903        const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
1904    bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1905    bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1906    bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1907    bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1908    bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1909
1910    CHECK(pkgname != nullptr);
1911    CHECK(pkgname[0] != 0);
1912
1913    // Public apps should not be compiled with profile information ever. Same goes for the special
1914    // package '*' used for the system server.
1915    Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
1916    if (!is_public && pkgname[0] != '*') {
1917        // Open reference profile in read only mode as dex2oat does not get write permissions.
1918        const std::string pkgname_str(pkgname);
1919        reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1920                                   [pkgname_str]() {
1921                                       clear_reference_profile(pkgname_str.c_str());
1922                                   });
1923        // Note: it's OK to not find a profile here.
1924    }
1925
1926    if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1927        LOG_FATAL("dexopt flags contains unknown fields\n");
1928    }
1929
1930    char out_oat_path[PKG_PATH_MAX];
1931    if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
1932        return false;
1933    }
1934
1935    const char *input_file;
1936    char in_odex_path[PKG_PATH_MAX];
1937    int dexopt_action = abs(dexopt_needed);
1938    bool is_odex_location = dexopt_needed < 0;
1939    switch (dexopt_action) {
1940        case DEX2OAT_FROM_SCRATCH:
1941        case DEX2OAT_FOR_BOOT_IMAGE:
1942        case DEX2OAT_FOR_FILTER:
1943        case DEX2OAT_FOR_RELOCATION:
1944            input_file = apk_path;
1945            break;
1946
1947        case PATCHOAT_FOR_RELOCATION:
1948            if (is_odex_location) {
1949                if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1950                    return -1;
1951                }
1952                input_file = in_odex_path;
1953            } else {
1954                input_file = out_oat_path;
1955            }
1956            break;
1957
1958        default:
1959            ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1960            return 72;
1961    }
1962
1963    struct stat input_stat;
1964    memset(&input_stat, 0, sizeof(input_stat));
1965    stat(input_file, &input_stat);
1966
1967    // Open the input file. If running dex2oat, `input_file` is the APK. If running
1968    // patchoat, it is the OAT file to be relocated.
1969    base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1970    if (input_fd.get() < 0) {
1971        ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
1972        return -1;
1973    }
1974
1975    // Create the output OAT file.
1976    const std::string out_oat_path_str(out_oat_path);
1977    Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1978            open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1979            [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1980    if (out_oat_fd.get() < 0) {
1981        ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
1982        return -1;
1983    }
1984    if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1985        return -1;
1986    }
1987
1988    // Open the existing VDEX. We do this before creating the new output VDEX, which will
1989    // unlink the old one.
1990    base::unique_fd in_vdex_fd;
1991    std::string in_vdex_path_str;
1992    if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
1993        // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1994        in_vdex_path_str = create_vdex_filename(input_file);
1995        if (in_vdex_path_str.empty()) {
1996            ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1997            return -1;
1998        }
1999        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
2000        if (in_vdex_fd.get() < 0) {
2001            ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
2002                in_vdex_path_str.c_str(), strerror(errno));
2003            return -1;
2004        }
2005    } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
2006        // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
2007        const char* path = nullptr;
2008        if (is_odex_location) {
2009            if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
2010                path = in_odex_path;
2011            } else {
2012                ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
2013                return -1;
2014            }
2015        } else {
2016            path = out_oat_path;
2017        }
2018        in_vdex_path_str = create_vdex_filename(path);
2019        if (in_vdex_path_str.empty()) {
2020            ALOGE("installd cannot compute input vdex location for '%s'\n", path);
2021            return -1;
2022        }
2023        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
2024    }
2025
2026    // Infer the name of the output VDEX and create it.
2027    const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
2028    if (out_vdex_path_str.empty()) {
2029        return -1;
2030    }
2031    Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
2032            open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
2033            [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
2034    if (out_vdex_fd.get() < 0) {
2035        ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
2036        return -1;
2037    }
2038    if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
2039                uid, out_vdex_path_str.c_str())) {
2040        return -1;
2041    }
2042
2043    // Create a swap file if necessary.
2044    base::unique_fd swap_fd;
2045    if (ShouldUseSwapFileForDexopt()) {
2046        // Make sure there really is enough space.
2047        char swap_file_name[PKG_PATH_MAX];
2048        strcpy(swap_file_name, out_oat_path);
2049        if (add_extension_to_file_name(swap_file_name, ".swap")) {
2050            swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
2051        }
2052        if (swap_fd.get() < 0) {
2053            // Could not create swap file. Optimistically go on and hope that we can compile
2054            // without it.
2055            ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
2056        } else {
2057            // Immediately unlink. We don't really want to hit flash.
2058            if (unlink(swap_file_name) < 0) {
2059                PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
2060            }
2061        }
2062    }
2063
2064    // Avoid generating an app image for extract only since it will not contain any classes.
2065    Dex2oatFileWrapper<std::function<void ()>> image_fd;
2066    const std::string image_path = create_image_filename(out_oat_path);
2067    if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
2068        char app_image_format[kPropertyValueMax];
2069        bool have_app_image_format =
2070                get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
2071        // Use app images only if it is enabled (by a set image format) and we are compiling
2072        // profile-guided (so the app image doesn't conservatively contain all classes).
2073        if (profile_guided && have_app_image_format) {
2074            // Recreate is true since we do not want to modify a mapped image. If the app is
2075            // already running and we modify the image file, it can cause crashes (b/27493510).
2076            image_fd.reset(open_output_file(image_path.c_str(),
2077                                            true /*recreate*/,
2078                                            0600 /*permissions*/),
2079                           [image_path]() { unlink(image_path.c_str()); }
2080                           );
2081            if (image_fd.get() < 0) {
2082                // Could not create application image file. Go on since we can compile without
2083                // it.
2084                LOG(ERROR) << "installd could not create '"
2085                        << image_path
2086                        << "' for image file during dexopt";
2087            } else if (!set_permissions_and_ownership(image_fd.get(),
2088                                                      is_public,
2089                                                      uid,
2090                                                      image_path.c_str())) {
2091                image_fd.reset(-1);
2092            }
2093        }
2094        // If we have a valid image file path but no image fd, explicitly erase the image file.
2095        if (image_fd.get() < 0) {
2096            if (unlink(image_path.c_str()) < 0) {
2097                if (errno != ENOENT) {
2098                    PLOG(ERROR) << "Couldn't unlink image file " << image_path;
2099                }
2100            }
2101        }
2102    }
2103
2104    ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
2105
2106    pid_t pid = fork();
2107    if (pid == 0) {
2108        /* child -- drop privileges before continuing */
2109        drop_capabilities(uid);
2110
2111        SetDex2OatAndPatchOatScheduling(boot_complete);
2112        if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
2113            ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
2114            _exit(67);
2115        }
2116
2117        if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
2118            run_patchoat(input_fd.get(),
2119                         in_vdex_fd.get(),
2120                         out_oat_fd.get(),
2121                         out_vdex_fd.get(),
2122                         input_file,
2123                         in_vdex_path_str.c_str(),
2124                         out_oat_path,
2125                         out_vdex_path_str.c_str(),
2126                         pkgname,
2127                         instruction_set);
2128        } else {
2129            // Pass dex2oat the relative path to the input file.
2130            const char *input_file_name = get_location_from_path(input_file);
2131            run_dex2oat(input_fd.get(),
2132                        out_oat_fd.get(),
2133                        in_vdex_fd.get(),
2134                        out_vdex_fd.get(),
2135                        image_fd.get(),
2136                        input_file_name,
2137                        out_oat_path,
2138                        swap_fd.get(),
2139                        instruction_set,
2140                        compiler_filter,
2141                        vm_safe_mode,
2142                        debuggable,
2143                        boot_complete,
2144                        reference_profile_fd.get(),
2145                        shared_libraries);
2146        }
2147        _exit(68);   /* only get here on exec failure */
2148    } else {
2149        int res = wait_child(pid);
2150        if (res == 0) {
2151            ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
2152        } else {
2153            ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
2154            return -1;
2155        }
2156    }
2157
2158    struct utimbuf ut;
2159    ut.actime = input_stat.st_atime;
2160    ut.modtime = input_stat.st_mtime;
2161    utime(out_oat_path, &ut);
2162
2163    // We've been successful, don't delete output.
2164    out_oat_fd.SetCleanup(false);
2165    out_vdex_fd.SetCleanup(false);
2166    image_fd.SetCleanup(false);
2167    reference_profile_fd.SetCleanup(false);
2168
2169    return 0;
2170}
2171
2172binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2173        const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2174        int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2175        const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
2176        const std::unique_ptr<std::string>& sharedLibraries) {
2177    ENFORCE_UID(AID_SYSTEM);
2178    CHECK_ARGUMENT_UUID(uuid);
2179    if (packageName && *packageName != "*") {
2180        CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2181    }
2182
2183    const char* apk_path = apkPath.c_str();
2184    const char* pkgname = packageName ? packageName->c_str() : "*";
2185    const char* instruction_set = instructionSet.c_str();
2186    const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2187    const char* compiler_filter = compilerFilter.c_str();
2188    const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
2189    const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
2190
2191    int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
2192            oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
2193    return res ? error(res, "Failed to dexopt") : ok();
2194}
2195
2196binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2197    ENFORCE_UID(AID_SYSTEM);
2198    const char* instruction_set = instructionSet.c_str();
2199
2200    char boot_marker_path[PKG_PATH_MAX];
2201    sprintf(boot_marker_path,
2202          "%s/%s/%s/.booting",
2203          android_data_dir.path,
2204          DALVIK_CACHE,
2205          instruction_set);
2206
2207    ALOGV("mark_boot_complete : %s", boot_marker_path);
2208    if (unlink(boot_marker_path) != 0) {
2209        return error(StringPrintf("Failed to unlink %s", boot_marker_path));
2210    }
2211    return ok();
2212}
2213
2214void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
2215        struct stat* statbuf)
2216{
2217    while (path[basepos] != 0) {
2218        if (path[basepos] == '/') {
2219            path[basepos] = 0;
2220            if (lstat(path, statbuf) < 0) {
2221                ALOGV("Making directory: %s\n", path);
2222                if (mkdir(path, mode) == 0) {
2223                    chown(path, uid, gid);
2224                } else {
2225                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
2226                }
2227            }
2228            path[basepos] = '/';
2229            basepos++;
2230        }
2231        basepos++;
2232    }
2233}
2234
2235binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2236        const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2237        const std::string& nativeLibPath32, int32_t userId) {
2238    ENFORCE_UID(AID_SYSTEM);
2239    CHECK_ARGUMENT_UUID(uuid);
2240    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2241
2242    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2243    const char* pkgname = packageName.c_str();
2244    const char* asecLibDir = nativeLibPath32.c_str();
2245    struct stat s, libStat;
2246    binder::Status res = ok();
2247
2248    auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2249    auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
2250
2251    const char* pkgdir = _pkgdir.c_str();
2252    const char* libsymlink = _libsymlink.c_str();
2253
2254    if (stat(pkgdir, &s) < 0) {
2255        return error("Failed to stat " + _pkgdir);
2256    }
2257
2258    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
2259        return error("Failed to chown " + _pkgdir);
2260    }
2261
2262    if (chmod(pkgdir, 0700) < 0) {
2263        res = error("Failed to chmod " + _pkgdir);
2264        goto out;
2265    }
2266
2267    if (lstat(libsymlink, &libStat) < 0) {
2268        if (errno != ENOENT) {
2269            res = error("Failed to stat " + _libsymlink);
2270            goto out;
2271        }
2272    } else {
2273        if (S_ISDIR(libStat.st_mode)) {
2274            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
2275                res = error("Failed to delete " + _libsymlink);
2276                goto out;
2277            }
2278        } else if (S_ISLNK(libStat.st_mode)) {
2279            if (unlink(libsymlink) < 0) {
2280                res = error("Failed to unlink " + _libsymlink);
2281                goto out;
2282            }
2283        }
2284    }
2285
2286    if (symlink(asecLibDir, libsymlink) < 0) {
2287        res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
2288        goto out;
2289    }
2290
2291out:
2292    if (chmod(pkgdir, s.st_mode) < 0) {
2293        auto msg = "Failed to cleanup chmod " + _pkgdir;
2294        if (res.isOk()) {
2295            res = error(msg);
2296        } else {
2297            PLOG(ERROR) << msg;
2298        }
2299    }
2300
2301    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
2302        auto msg = "Failed to cleanup chown " + _pkgdir;
2303        if (res.isOk()) {
2304            res = error(msg);
2305        } else {
2306            PLOG(ERROR) << msg;
2307        }
2308    }
2309
2310    return res;
2311}
2312
2313static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2314{
2315    static const char *IDMAP_BIN = "/system/bin/idmap";
2316    static const size_t MAX_INT_LEN = 32;
2317    char idmap_str[MAX_INT_LEN];
2318
2319    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
2320
2321    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
2322    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
2323}
2324
2325// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2326// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2327static int flatten_path(const char *prefix, const char *suffix,
2328        const char *overlay_path, char *idmap_path, size_t N)
2329{
2330    if (overlay_path == NULL || idmap_path == NULL) {
2331        return -1;
2332    }
2333    const size_t len_overlay_path = strlen(overlay_path);
2334    // will access overlay_path + 1 further below; requires absolute path
2335    if (len_overlay_path < 2 || *overlay_path != '/') {
2336        return -1;
2337    }
2338    const size_t len_idmap_root = strlen(prefix);
2339    const size_t len_suffix = strlen(suffix);
2340    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2341            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2342        // additions below would cause overflow
2343        return -1;
2344    }
2345    if (N < len_idmap_root + len_overlay_path + len_suffix) {
2346        return -1;
2347    }
2348    memset(idmap_path, 0, N);
2349    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2350    char *ch = idmap_path + len_idmap_root;
2351    while (*ch != '\0') {
2352        if (*ch == '/') {
2353            *ch = '@';
2354        }
2355        ++ch;
2356    }
2357    return 0;
2358}
2359
2360binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2361        const std::string& overlayApkPath, int32_t uid) {
2362    ENFORCE_UID(AID_SYSTEM);
2363    const char* target_apk = targetApkPath.c_str();
2364    const char* overlay_apk = overlayApkPath.c_str();
2365    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2366
2367    int idmap_fd = -1;
2368    char idmap_path[PATH_MAX];
2369
2370    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2371                idmap_path, sizeof(idmap_path)) == -1) {
2372        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2373        goto fail;
2374    }
2375
2376    unlink(idmap_path);
2377    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2378    if (idmap_fd < 0) {
2379        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2380        goto fail;
2381    }
2382    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2383        ALOGE("idmap cannot chown '%s'\n", idmap_path);
2384        goto fail;
2385    }
2386    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2387        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2388        goto fail;
2389    }
2390
2391    pid_t pid;
2392    pid = fork();
2393    if (pid == 0) {
2394        /* child -- drop privileges before continuing */
2395        if (setgid(uid) != 0) {
2396            ALOGE("setgid(%d) failed during idmap\n", uid);
2397            exit(1);
2398        }
2399        if (setuid(uid) != 0) {
2400            ALOGE("setuid(%d) failed during idmap\n", uid);
2401            exit(1);
2402        }
2403        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2404            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2405            exit(1);
2406        }
2407
2408        run_idmap(target_apk, overlay_apk, idmap_fd);
2409        exit(1); /* only if exec call to idmap failed */
2410    } else {
2411        int status = wait_child(pid);
2412        if (status != 0) {
2413            ALOGE("idmap failed, status=0x%04x\n", status);
2414            goto fail;
2415        }
2416    }
2417
2418    close(idmap_fd);
2419    return ok();
2420fail:
2421    if (idmap_fd >= 0) {
2422        close(idmap_fd);
2423        unlink(idmap_path);
2424    }
2425    return error();
2426}
2427
2428binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2429        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2430        const std::string& seInfo) {
2431    ENFORCE_UID(AID_SYSTEM);
2432    CHECK_ARGUMENT_UUID(uuid);
2433    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2434
2435    binder::Status res = ok();
2436
2437    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
2438    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
2439    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2440    const char* pkgName = packageName.c_str();
2441    const char* seinfo = seInfo.c_str();
2442
2443    uid_t uid = multiuser_get_uid(userId, appId);
2444    if (flags & FLAG_STORAGE_CE) {
2445        auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
2446        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2447            res = error("restorecon failed for " + path);
2448        }
2449    }
2450    if (flags & FLAG_STORAGE_DE) {
2451        auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
2452        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2453            res = error("restorecon failed for " + path);
2454        }
2455    }
2456    return res;
2457}
2458
2459binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2460        const std::string& instructionSet) {
2461    ENFORCE_UID(AID_SYSTEM);
2462    const char* oat_dir = oatDir.c_str();
2463    const char* instruction_set = instructionSet.c_str();
2464    char oat_instr_dir[PKG_PATH_MAX];
2465
2466    if (validate_apk_path(oat_dir)) {
2467        return error("Invalid path " + oatDir);
2468    }
2469    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2470        return error("Failed to prepare " + oatDir);
2471    }
2472    if (selinux_android_restorecon(oat_dir, 0)) {
2473        return error("Failed to restorecon " + oatDir);
2474    }
2475    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
2476    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
2477        return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
2478    }
2479    return ok();
2480}
2481
2482binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2483    ENFORCE_UID(AID_SYSTEM);
2484    if (validate_apk_path(packageDir.c_str())) {
2485        return error("Invalid path " + packageDir);
2486    }
2487    if (delete_dir_contents_and_dir(packageDir) != 0) {
2488        return error("Failed to delete " + packageDir);
2489    }
2490    return ok();
2491}
2492
2493binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2494        const std::string& fromBase, const std::string& toBase) {
2495    ENFORCE_UID(AID_SYSTEM);
2496    const char* relative_path = relativePath.c_str();
2497    const char* from_base = fromBase.c_str();
2498    const char* to_base = toBase.c_str();
2499    char from_path[PKG_PATH_MAX];
2500    char to_path[PKG_PATH_MAX];
2501    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2502    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2503
2504    if (validate_apk_path_subdirs(from_path)) {
2505        return error(StringPrintf("Invalid from path %s", from_path));
2506    }
2507
2508    if (validate_apk_path_subdirs(to_path)) {
2509        return error(StringPrintf("Invalid to path %s", to_path));
2510    }
2511
2512    if (link(from_path, to_path) < 0) {
2513        return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
2514    }
2515
2516    return ok();
2517}
2518
2519// Helper for move_ab, so that we can have common failure-case cleanup.
2520static bool unlink_and_rename(const char* from, const char* to) {
2521    // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2522    // return a failure.
2523    struct stat s;
2524    if (stat(to, &s) == 0) {
2525        if (!S_ISREG(s.st_mode)) {
2526            LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2527            return false;
2528        }
2529        if (unlink(to) != 0) {
2530            LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2531            return false;
2532        }
2533    } else {
2534        // This may be a permission problem. We could investigate the error code, but we'll just
2535        // let the rename failure do the work for us.
2536    }
2537
2538    // Try to rename "to" to "from."
2539    if (rename(from, to) != 0) {
2540        PLOG(ERROR) << "Could not rename " << from << " to " << to;
2541        return false;
2542    }
2543    return true;
2544}
2545
2546// Move/rename a B artifact (from) to an A artifact (to).
2547static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2548    // Check whether B exists.
2549    {
2550        struct stat s;
2551        if (stat(b_path.c_str(), &s) != 0) {
2552            // Silently ignore for now. The service calling this isn't smart enough to understand
2553            // lack of artifacts at the moment.
2554            return false;
2555        }
2556        if (!S_ISREG(s.st_mode)) {
2557            LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2558            // Try to unlink, but swallow errors.
2559            unlink(b_path.c_str());
2560            return false;
2561        }
2562    }
2563
2564    // Rename B to A.
2565    if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2566        // Delete the b_path so we don't try again (or fail earlier).
2567        if (unlink(b_path.c_str()) != 0) {
2568            PLOG(ERROR) << "Could not unlink " << b_path;
2569        }
2570
2571        return false;
2572    }
2573
2574    return true;
2575}
2576
2577binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2578        const std::string& instructionSet, const std::string& outputPath) {
2579    ENFORCE_UID(AID_SYSTEM);
2580    const char* apk_path = apkPath.c_str();
2581    const char* instruction_set = instructionSet.c_str();
2582    const char* oat_dir = outputPath.c_str();
2583
2584    // Get the current slot suffix. No suffix, no A/B.
2585    std::string slot_suffix;
2586    {
2587        char buf[kPropertyValueMax];
2588        if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2589            return error();
2590        }
2591        slot_suffix = buf;
2592
2593        if (!ValidateTargetSlotSuffix(slot_suffix)) {
2594            return error("Target slot suffix not legal: " + slot_suffix);
2595        }
2596    }
2597
2598    // Validate other inputs.
2599    if (validate_apk_path(apk_path) != 0) {
2600        return error("Invalid apkPath: " + apkPath);
2601    }
2602    if (validate_apk_path(oat_dir) != 0) {
2603        return error("Invalid outputPath: " + outputPath);
2604    }
2605
2606    char a_path[PKG_PATH_MAX];
2607    if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2608        return error();
2609    }
2610    const std::string a_vdex_path = create_vdex_filename(a_path);
2611    const std::string a_image_path = create_image_filename(a_path);
2612
2613    // B path = A path + slot suffix.
2614    const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2615    const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2616    const std::string b_image_path = StringPrintf("%s.%s",
2617                                                  a_image_path.c_str(),
2618                                                  slot_suffix.c_str());
2619
2620    bool success = true;
2621    if (move_ab_path(b_path, a_path)) {
2622        if (move_ab_path(b_vdex_path, a_vdex_path)) {
2623            // Note: we can live without an app image. As such, ignore failure to move the image file.
2624            //       If we decide to require the app image, or the app image being moved correctly,
2625            //       then change accordingly.
2626            constexpr bool kIgnoreAppImageFailure = true;
2627
2628            if (!a_image_path.empty()) {
2629                if (!move_ab_path(b_image_path, a_image_path)) {
2630                    unlink(a_image_path.c_str());
2631                    if (!kIgnoreAppImageFailure) {
2632                        success = false;
2633                    }
2634                }
2635            }
2636        } else {
2637            // Cleanup: delete B image, ignore errors.
2638            unlink(b_image_path.c_str());
2639            success = false;
2640        }
2641    } else {
2642        // Cleanup: delete B image, ignore errors.
2643        unlink(b_vdex_path.c_str());
2644        unlink(b_image_path.c_str());
2645        success = false;
2646    }
2647
2648    return success ? ok() : error();
2649}
2650
2651binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2652        const std::string& instructionSet, const std::string& outputPath) {
2653    ENFORCE_UID(AID_SYSTEM);
2654    const char* apk_path = apkPath.c_str();
2655    const char* instruction_set = instructionSet.c_str();
2656    const char* oat_dir = outputPath.c_str();
2657
2658    // Delete the oat/odex file.
2659    char out_path[PKG_PATH_MAX];
2660    if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
2661        return error();
2662    }
2663
2664    // In case of a permission failure report the issue. Otherwise just print a warning.
2665    auto unlink_and_check = [](const char* path) -> bool {
2666        int result = unlink(path);
2667        if (result != 0) {
2668            if (errno == EACCES || errno == EPERM) {
2669                PLOG(ERROR) << "Could not unlink " << path;
2670                return false;
2671            }
2672            PLOG(WARNING) << "Could not unlink " << path;
2673        }
2674        return true;
2675    };
2676
2677    // Delete the oat/odex file.
2678    bool return_value_oat = unlink_and_check(out_path);
2679
2680    // Derive and delete the app image.
2681    bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2682
2683    // Report success.
2684    bool success = return_value_oat && return_value_art;
2685    return success ? ok() : error();
2686}
2687
2688}  // namespace installd
2689}  // namespace android
2690