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