InstalldNativeService.cpp revision 64f07c5fdccbe59468f318512591a316d8eec909
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#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
21#include <errno.h>
22#include <inttypes.h>
23#include <fstream>
24#include <fts.h>
25#include <regex>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/capability.h>
29#include <sys/file.h>
30#include <sys/resource.h>
31#include <sys/quota.h>
32#include <sys/stat.h>
33#include <sys/statvfs.h>
34#include <sys/types.h>
35#include <sys/wait.h>
36#include <sys/xattr.h>
37#include <unistd.h>
38
39#include <android-base/logging.h>
40#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
43#include <cutils/fs.h>
44#include <cutils/properties.h>
45#include <cutils/sched_policy.h>
46#include <log/log.h>               // TODO: Move everything to base/logging.
47#include <logwrap/logwrap.h>
48#include <private/android_filesystem_config.h>
49#include <selinux/android.h>
50#include <system/thread_defs.h>
51#include <utils/Trace.h>
52
53#include "dexopt.h"
54#include "globals.h"
55#include "installd_deps.h"
56#include "otapreopt_utils.h"
57#include "utils.h"
58
59#include "CacheTracker.h"
60#include "MatchExtensionGen.h"
61
62#ifndef LOG_TAG
63#define LOG_TAG "installd"
64#endif
65
66using android::base::StringPrintf;
67using std::endl;
68
69namespace android {
70namespace installd {
71
72static constexpr const char* kCpPath = "/system/bin/cp";
73static constexpr const char* kXattrDefault = "user.default";
74
75static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
76
77static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
81static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
82static constexpr const char* IDMAP_SUFFIX = "@idmap";
83
84// NOTE: keep in sync with StorageManager
85static constexpr int FLAG_STORAGE_DE = 1 << 0;
86static constexpr int FLAG_STORAGE_CE = 1 << 1;
87
88// NOTE: keep in sync with Installer
89static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
90static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
91static constexpr int FLAG_USE_QUOTA = 1 << 12;
92static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
93static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 14;
94
95namespace {
96
97constexpr const char* kDump = "android.permission.DUMP";
98
99static binder::Status ok() {
100    return binder::Status::ok();
101}
102
103static binder::Status exception(uint32_t code, const std::string& msg) {
104    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
105}
106
107static binder::Status error() {
108    return binder::Status::fromServiceSpecificError(errno);
109}
110
111static binder::Status error(const std::string& msg) {
112    PLOG(ERROR) << msg;
113    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
114}
115
116static binder::Status error(uint32_t code, const std::string& msg) {
117    LOG(ERROR) << msg << " (" << code << ")";
118    return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
119}
120
121binder::Status checkPermission(const char* permission) {
122    pid_t pid;
123    uid_t uid;
124
125    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
126            reinterpret_cast<int32_t*>(&uid))) {
127        return ok();
128    } else {
129        return exception(binder::Status::EX_SECURITY,
130                StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
131    }
132}
133
134binder::Status checkUid(uid_t expectedUid) {
135    uid_t uid = IPCThreadState::self()->getCallingUid();
136    if (uid == expectedUid || uid == AID_ROOT) {
137        return ok();
138    } else {
139        return exception(binder::Status::EX_SECURITY,
140                StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
141    }
142}
143
144binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
145    if (!uuid || is_valid_filename(*uuid)) {
146        return ok();
147    } else {
148        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
149                StringPrintf("UUID %s is malformed", uuid->c_str()));
150    }
151}
152
153binder::Status checkArgumentPackageName(const std::string& packageName) {
154    if (is_valid_package_name(packageName.c_str())) {
155        return ok();
156    } else {
157        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
158                StringPrintf("Package name %s is malformed", packageName.c_str()));
159    }
160}
161
162#define ENFORCE_UID(uid) {                                  \
163    binder::Status status = checkUid((uid));                \
164    if (!status.isOk()) {                                   \
165        return status;                                      \
166    }                                                       \
167}
168
169#define CHECK_ARGUMENT_UUID(uuid) {                         \
170    binder::Status status = checkArgumentUuid((uuid));      \
171    if (!status.isOk()) {                                   \
172        return status;                                      \
173    }                                                       \
174}
175
176#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
177    binder::Status status =                                 \
178            checkArgumentPackageName((packageName));        \
179    if (!status.isOk()) {                                   \
180        return status;                                      \
181    }                                                       \
182}
183
184}  // namespace
185
186status_t InstalldNativeService::start() {
187    IPCThreadState::self()->disableBackgroundScheduling(true);
188    status_t ret = BinderService<InstalldNativeService>::publish();
189    if (ret != android::OK) {
190        return ret;
191    }
192    sp<ProcessState> ps(ProcessState::self());
193    ps->startThreadPool();
194    ps->giveThreadPoolName();
195    return android::OK;
196}
197
198status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
199    auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
200    const binder::Status dump_permission = checkPermission(kDump);
201    if (!dump_permission.isOk()) {
202        out << dump_permission.toString8() << endl;
203        return PERMISSION_DENIED;
204    }
205    std::lock_guard<std::recursive_mutex> lock(mLock);
206
207    out << "installd is happy!" << endl;
208
209    out << endl << "Devices with quota support:" << endl;
210    for (const auto& n : mQuotaDevices) {
211        out << "    " << n.first << " = " << n.second << endl;
212    }
213
214    out << endl << "Per-UID cache quotas:" << endl;
215    for (const auto& n : mCacheQuotas) {
216        out << "    " << n.first << " = " << n.second << endl;
217    }
218
219    out << endl;
220    out.flush();
221
222    return NO_ERROR;
223}
224
225/**
226 * Perform restorecon of the given path, but only perform recursive restorecon
227 * if the label of that top-level file actually changed.  This can save us
228 * significant time by avoiding no-op traversals of large filesystem trees.
229 */
230static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
231        bool existing) {
232    int res = 0;
233    char* before = nullptr;
234    char* after = nullptr;
235
236    // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
237    // libselinux. Not needed here.
238
239    if (lgetfilecon(path.c_str(), &before) < 0) {
240        PLOG(ERROR) << "Failed before getfilecon for " << path;
241        goto fail;
242    }
243    if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
244        PLOG(ERROR) << "Failed top-level restorecon for " << path;
245        goto fail;
246    }
247    if (lgetfilecon(path.c_str(), &after) < 0) {
248        PLOG(ERROR) << "Failed after getfilecon for " << path;
249        goto fail;
250    }
251
252    // If the initial top-level restorecon above changed the label, then go
253    // back and restorecon everything recursively
254    if (strcmp(before, after)) {
255        if (existing) {
256            LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
257                    << path << "; running recursive restorecon";
258        }
259        if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
260                SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
261            PLOG(ERROR) << "Failed recursive restorecon for " << path;
262            goto fail;
263        }
264    }
265
266    goto done;
267fail:
268    res = -1;
269done:
270    free(before);
271    free(after);
272    return res;
273}
274
275static int restorecon_app_data_lazy(const std::string& parent, const char* name,
276        const std::string& seInfo, uid_t uid, bool existing) {
277    return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
278            existing);
279}
280
281static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
282    if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
283        PLOG(ERROR) << "Failed to prepare " << path;
284        return -1;
285    }
286    return 0;
287}
288
289/**
290 * Prepare an app cache directory, which offers to fix-up the GID and
291 * directory mode flags during a platform upgrade.
292 */
293static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
294        uid_t uid, gid_t gid) {
295    auto path = StringPrintf("%s/%s", parent.c_str(), name);
296    struct stat st;
297    if (stat(path.c_str(), &st) != 0) {
298        if (errno == ENOENT) {
299            // This is fine, just create it
300            if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
301                PLOG(ERROR) << "Failed to prepare " << path;
302                return -1;
303            } else {
304                return 0;
305            }
306        } else {
307            PLOG(ERROR) << "Failed to stat " << path;
308            return -1;
309        }
310    }
311
312    mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
313    if (st.st_uid != uid) {
314        // Mismatched UID is real trouble; we can't recover
315        LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
316                << " but expected " << uid;
317        return -1;
318    } else if (st.st_gid == gid && actual_mode == target_mode) {
319        // Everything looks good!
320        return 0;
321    }
322
323    // Directory is owned correctly, but GID or mode mismatch means it's
324    // probably a platform upgrade so we need to fix them
325    FTS *fts;
326    FTSENT *p;
327    char *argv[] = { (char*) path.c_str(), nullptr };
328    if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
329        PLOG(ERROR) << "Failed to fts_open " << path;
330        return -1;
331    }
332    while ((p = fts_read(fts)) != NULL) {
333        switch (p->fts_info) {
334        case FTS_DP:
335            if (chmod(p->fts_accpath, target_mode) != 0) {
336                PLOG(WARNING) << "Failed to chmod " << p->fts_path;
337            }
338            // Intentional fall through to also set GID
339        case FTS_F:
340            if (chown(p->fts_accpath, -1, gid) != 0) {
341                PLOG(WARNING) << "Failed to chown " << p->fts_path;
342            }
343            break;
344        case FTS_SL:
345        case FTS_SLNONE:
346            if (lchown(p->fts_accpath, -1, gid) != 0) {
347                PLOG(WARNING) << "Failed to chown " << p->fts_path;
348            }
349            break;
350        }
351    }
352    fts_close(fts);
353    return 0;
354}
355
356binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
357        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
358        const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
359    ENFORCE_UID(AID_SYSTEM);
360    CHECK_ARGUMENT_UUID(uuid);
361    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
362    std::lock_guard<std::recursive_mutex> lock(mLock);
363
364    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
365    const char* pkgname = packageName.c_str();
366
367    // Assume invalid inode unless filled in below
368    if (_aidl_return != nullptr) *_aidl_return = -1;
369
370    int32_t uid = multiuser_get_uid(userId, appId);
371    int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
372    mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
373
374    // If UID doesn't have a specific cache GID, use UID value
375    if (cacheGid == -1) {
376        cacheGid = uid;
377    }
378
379    if (flags & FLAG_STORAGE_CE) {
380        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
381        bool existing = (access(path.c_str(), F_OK) == 0);
382
383        if (prepare_app_dir(path, targetMode, uid) ||
384                prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
385                prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
386            return error("Failed to prepare " + path);
387        }
388
389        // Consider restorecon over contents if label changed
390        if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
391                restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
392                restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
393            return error("Failed to restorecon " + path);
394        }
395
396        // Remember inode numbers of cache directories so that we can clear
397        // contents while CE storage is locked
398        if (write_path_inode(path, "cache", kXattrInodeCache) ||
399                write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
400            return error("Failed to write_path_inode for " + path);
401        }
402
403        // And return the CE inode of the top-level data directory so we can
404        // clear contents while CE storage is locked
405        if ((_aidl_return != nullptr)
406                && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
407            return error("Failed to get_path_inode for " + path);
408        }
409    }
410    if (flags & FLAG_STORAGE_DE) {
411        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
412        bool existing = (access(path.c_str(), F_OK) == 0);
413
414        if (prepare_app_dir(path, targetMode, uid) ||
415                prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
416                prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
417            return error("Failed to prepare " + path);
418        }
419
420        // Consider restorecon over contents if label changed
421        if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
422            return error("Failed to restorecon " + path);
423        }
424
425        if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
426            const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
427            // read-write-execute only for the app user.
428            if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
429                return error("Failed to prepare " + profile_path);
430            }
431            std::string profile_file = create_primary_profile(profile_path);
432            // read-write only for the app user.
433            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
434                return error("Failed to prepare " + profile_path);
435            }
436            const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
437            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
438            // profiles.
439            int shared_app_gid = multiuser_get_shared_gid(0, appId);
440            if ((shared_app_gid != -1) && fs_prepare_dir_strict(
441                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
442                return error("Failed to prepare " + ref_profile_path);
443            }
444        }
445    }
446    return ok();
447}
448
449binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
450        const std::string& packageName, int32_t userId, int32_t flags) {
451    ENFORCE_UID(AID_SYSTEM);
452    CHECK_ARGUMENT_UUID(uuid);
453    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
454    std::lock_guard<std::recursive_mutex> lock(mLock);
455
456    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
457    const char* pkgname = packageName.c_str();
458
459    // This method only exists to upgrade system apps that have requested
460    // forceDeviceEncrypted, so their default storage always lives in a
461    // consistent location.  This only works on non-FBE devices, since we
462    // never want to risk exposing data on a device with real CE/DE storage.
463
464    auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
465    auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
466
467    // If neither directory is marked as default, assume CE is default
468    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
469            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
470        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
471            return error("Failed to mark default storage " + ce_path);
472        }
473    }
474
475    // Migrate default data location if needed
476    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
477    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
478
479    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
480        LOG(WARNING) << "Requested default storage " << target
481                << " is not active; migrating from " << source;
482        if (delete_dir_contents_and_dir(target) != 0) {
483            return error("Failed to delete " + target);
484        }
485        if (rename(source.c_str(), target.c_str()) != 0) {
486            return error("Failed to rename " + source + " to " + target);
487        }
488    }
489
490    return ok();
491}
492
493
494binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
495    ENFORCE_UID(AID_SYSTEM);
496    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
497    std::lock_guard<std::recursive_mutex> lock(mLock);
498
499    const char* pkgname = packageName.c_str();
500    binder::Status res = ok();
501    if (!clear_reference_profile(pkgname)) {
502        res = error("Failed to clear reference profile for " + packageName);
503    }
504    if (!clear_current_profiles(pkgname)) {
505        res = error("Failed to clear current profiles for " + packageName);
506    }
507    return res;
508}
509
510binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
511        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
512    ENFORCE_UID(AID_SYSTEM);
513    CHECK_ARGUMENT_UUID(uuid);
514    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
515    std::lock_guard<std::recursive_mutex> lock(mLock);
516
517    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
518    const char* pkgname = packageName.c_str();
519
520    binder::Status res = ok();
521    if (flags & FLAG_STORAGE_CE) {
522        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
523        if (flags & FLAG_CLEAR_CACHE_ONLY) {
524            path = read_path_inode(path, "cache", kXattrInodeCache);
525        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
526            path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
527        }
528        if (access(path.c_str(), F_OK) == 0) {
529            if (delete_dir_contents(path) != 0) {
530                res = error("Failed to delete contents of " + path);
531            }
532        }
533    }
534    if (flags & FLAG_STORAGE_DE) {
535        std::string suffix = "";
536        bool only_cache = false;
537        if (flags & FLAG_CLEAR_CACHE_ONLY) {
538            suffix = CACHE_DIR_POSTFIX;
539            only_cache = true;
540        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
541            suffix = CODE_CACHE_DIR_POSTFIX;
542            only_cache = true;
543        }
544
545        auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
546        if (access(path.c_str(), F_OK) == 0) {
547            if (delete_dir_contents(path) != 0) {
548                res = error("Failed to delete contents of " + path);
549            }
550        }
551        if (!only_cache) {
552            if (!clear_current_profile(pkgname, userId)) {
553                res = error("Failed to clear current profile for " + packageName);
554            }
555        }
556    }
557    return res;
558}
559
560static int destroy_app_reference_profile(const char *pkgname) {
561    return delete_dir_contents_and_dir(
562        create_data_ref_profile_package_path(pkgname),
563        /*ignore_if_missing*/ true);
564}
565
566static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
567    return delete_dir_contents_and_dir(
568        create_data_user_profile_package_path(userid, pkgname),
569        /*ignore_if_missing*/ true);
570}
571
572binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
573    ENFORCE_UID(AID_SYSTEM);
574    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
575    std::lock_guard<std::recursive_mutex> lock(mLock);
576
577    const char* pkgname = packageName.c_str();
578    binder::Status res = ok();
579    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
580    for (auto user : users) {
581        if (destroy_app_current_profiles(pkgname, user) != 0) {
582            res = error("Failed to destroy current profiles for " + packageName);
583        }
584    }
585    if (destroy_app_reference_profile(pkgname) != 0) {
586        res = error("Failed to destroy reference profile for " + packageName);
587    }
588    return res;
589}
590
591binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
592        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
593    ENFORCE_UID(AID_SYSTEM);
594    CHECK_ARGUMENT_UUID(uuid);
595    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
596    std::lock_guard<std::recursive_mutex> lock(mLock);
597
598    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
599    const char* pkgname = packageName.c_str();
600
601    binder::Status res = ok();
602    if (flags & FLAG_STORAGE_CE) {
603        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
604        if (delete_dir_contents_and_dir(path) != 0) {
605            res = error("Failed to delete " + path);
606        }
607    }
608    if (flags & FLAG_STORAGE_DE) {
609        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
610        if (delete_dir_contents_and_dir(path) != 0) {
611            res = error("Failed to delete " + path);
612        }
613        destroy_app_current_profiles(pkgname, userId);
614        // TODO(calin): If the package is still installed by other users it's probably
615        // beneficial to keep the reference profile around.
616        // Verify if it's ok to do that.
617        destroy_app_reference_profile(pkgname);
618    }
619    return res;
620}
621
622binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
623        const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
624        const std::string& dataAppName, int32_t appId, const std::string& seInfo,
625        int32_t targetSdkVersion) {
626    ENFORCE_UID(AID_SYSTEM);
627    CHECK_ARGUMENT_UUID(fromUuid);
628    CHECK_ARGUMENT_UUID(toUuid);
629    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
630    std::lock_guard<std::recursive_mutex> lock(mLock);
631
632    const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
633    const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
634    const char* package_name = packageName.c_str();
635    const char* data_app_name = dataAppName.c_str();
636
637    binder::Status res = ok();
638    std::vector<userid_t> users = get_known_users(from_uuid);
639
640    // Copy app
641    {
642        auto from = create_data_app_package_path(from_uuid, data_app_name);
643        auto to = create_data_app_package_path(to_uuid, data_app_name);
644        auto to_parent = create_data_app_path(to_uuid);
645
646        char *argv[] = {
647            (char*) kCpPath,
648            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
649            (char*) "-p", /* preserve timestamps, ownership, and permissions */
650            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
651            (char*) "-P", /* Do not follow symlinks [default] */
652            (char*) "-d", /* don't dereference symlinks */
653            (char*) from.c_str(),
654            (char*) to_parent.c_str()
655        };
656
657        LOG(DEBUG) << "Copying " << from << " to " << to;
658        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
659        if (rc != 0) {
660            res = error(rc, "Failed copying " + from + " to " + to);
661            goto fail;
662        }
663
664        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
665            res = error("Failed to restorecon " + to);
666            goto fail;
667        }
668    }
669
670    // Copy private data for all known users
671    for (auto user : users) {
672
673        // Data source may not exist for all users; that's okay
674        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
675        if (access(from_ce.c_str(), F_OK) != 0) {
676            LOG(INFO) << "Missing source " << from_ce;
677            continue;
678        }
679
680        if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
681                seInfo, targetSdkVersion, nullptr).isOk()) {
682            res = error("Failed to create package target");
683            goto fail;
684        }
685
686        char *argv[] = {
687            (char*) kCpPath,
688            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
689            (char*) "-p", /* preserve timestamps, ownership, and permissions */
690            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
691            (char*) "-P", /* Do not follow symlinks [default] */
692            (char*) "-d", /* don't dereference symlinks */
693            nullptr,
694            nullptr
695        };
696
697        {
698            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
699            auto to = create_data_user_de_path(to_uuid, user);
700            argv[6] = (char*) from.c_str();
701            argv[7] = (char*) to.c_str();
702
703            LOG(DEBUG) << "Copying " << from << " to " << to;
704            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
705            if (rc != 0) {
706                res = error(rc, "Failed copying " + from + " to " + to);
707                goto fail;
708            }
709        }
710        {
711            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
712            auto to = create_data_user_ce_path(to_uuid, user);
713            argv[6] = (char*) from.c_str();
714            argv[7] = (char*) to.c_str();
715
716            LOG(DEBUG) << "Copying " << from << " to " << to;
717            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
718            if (rc != 0) {
719                res = error(rc, "Failed copying " + from + " to " + to);
720                goto fail;
721            }
722        }
723
724        if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
725                appId, seInfo).isOk()) {
726            res = error("Failed to restorecon");
727            goto fail;
728        }
729    }
730
731    // We let the framework scan the new location and persist that before
732    // deleting the data in the old location; this ordering ensures that
733    // we can recover from things like battery pulls.
734    return ok();
735
736fail:
737    // Nuke everything we might have already copied
738    {
739        auto to = create_data_app_package_path(to_uuid, data_app_name);
740        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
741            LOG(WARNING) << "Failed to rollback " << to;
742        }
743    }
744    for (auto user : users) {
745        {
746            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
747            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
748                LOG(WARNING) << "Failed to rollback " << to;
749            }
750        }
751        {
752            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
753            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
754                LOG(WARNING) << "Failed to rollback " << to;
755            }
756        }
757    }
758    return res;
759}
760
761binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
762        int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
763    ENFORCE_UID(AID_SYSTEM);
764    CHECK_ARGUMENT_UUID(uuid);
765    std::lock_guard<std::recursive_mutex> lock(mLock);
766
767    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
768    if (flags & FLAG_STORAGE_DE) {
769        if (uuid_ == nullptr) {
770            if (ensure_config_user_dirs(userId) != 0) {
771                return error(StringPrintf("Failed to ensure dirs for %d", userId));
772            }
773        }
774    }
775    return ok();
776}
777
778binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
779        int32_t userId, int32_t flags) {
780    ENFORCE_UID(AID_SYSTEM);
781    CHECK_ARGUMENT_UUID(uuid);
782    std::lock_guard<std::recursive_mutex> lock(mLock);
783
784    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
785    binder::Status res = ok();
786    if (flags & FLAG_STORAGE_DE) {
787        auto path = create_data_user_de_path(uuid_, userId);
788        if (delete_dir_contents_and_dir(path, true) != 0) {
789            res = error("Failed to delete " + path);
790        }
791        if (uuid_ == nullptr) {
792            path = create_data_misc_legacy_path(userId);
793            if (delete_dir_contents_and_dir(path, true) != 0) {
794                res = error("Failed to delete " + path);
795            }
796            path = create_data_user_profile_path(userId);
797            if (delete_dir_contents_and_dir(path, true) != 0) {
798                res = error("Failed to delete " + path);
799            }
800        }
801    }
802    if (flags & FLAG_STORAGE_CE) {
803        auto path = create_data_user_ce_path(uuid_, userId);
804        if (delete_dir_contents_and_dir(path, true) != 0) {
805            res = error("Failed to delete " + path);
806        }
807        path = create_data_media_path(uuid_, userId);
808        if (delete_dir_contents_and_dir(path, true) != 0) {
809            res = error("Failed to delete " + path);
810        }
811    }
812    return res;
813}
814
815/* Try to ensure free_size bytes of storage are available.
816 * Returns 0 on success.
817 * This is rather simple-minded because doing a full LRU would
818 * be potentially memory-intensive, and without atime it would
819 * also require that apps constantly modify file metadata even
820 * when just reading from the cache, which is pretty awful.
821 */
822binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
823        int64_t freeStorageSize, int32_t flags) {
824    ENFORCE_UID(AID_SYSTEM);
825    CHECK_ARGUMENT_UUID(uuid);
826    std::lock_guard<std::recursive_mutex> lock(mLock);
827
828    // TODO: remove this once framework is more robust
829    invalidateMounts();
830
831    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
832    auto data_path = create_data_path(uuid_);
833    auto device = findQuotaDeviceForUuid(uuid);
834    auto noop = (flags & FLAG_FREE_CACHE_NOOP);
835
836    int64_t free = data_disk_free(data_path);
837    int64_t needed = freeStorageSize - free;
838    if (free < 0) {
839        return error("Failed to determine free space for " + data_path);
840    } else if (free >= freeStorageSize) {
841        return ok();
842    }
843
844    LOG(DEBUG) << "Found " << data_path << " with " << free << " free; caller requested "
845            << freeStorageSize;
846
847    if (flags & FLAG_FREE_CACHE_V2) {
848        // This new cache strategy fairly removes files from UIDs by deleting
849        // files from the UIDs which are most over their allocated quota
850
851        // 1. Create trackers for every known UID
852        ATRACE_BEGIN("create");
853        std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
854        for (auto user : get_known_users(uuid_)) {
855            FTS *fts;
856            FTSENT *p;
857            char *argv[] = {
858                    (char*) create_data_user_ce_path(uuid_, user).c_str(),
859                    (char*) create_data_user_de_path(uuid_, user).c_str(),
860                    nullptr
861            };
862            if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
863                return error("Failed to fts_open");
864            }
865            while ((p = fts_read(fts)) != NULL) {
866                if (p->fts_info == FTS_D && p->fts_level == 1) {
867                    uid_t uid = p->fts_statp->st_uid;
868                    auto search = trackers.find(uid);
869                    if (search != trackers.end()) {
870                        search->second->addDataPath(p->fts_path);
871                    } else {
872                        auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
873                                multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
874                        tracker->addDataPath(p->fts_path);
875                        tracker->cacheQuota = mCacheQuotas[uid];
876                        if (tracker->cacheQuota == 0) {
877                            LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
878                            tracker->cacheQuota = 67108864;
879                        }
880                        trackers[uid] = tracker;
881                    }
882                    fts_set(fts, p, FTS_SKIP);
883                }
884            }
885            fts_close(fts);
886        }
887        ATRACE_END();
888
889        // 2. Populate tracker stats and insert into priority queue
890        ATRACE_BEGIN("populate");
891        auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
892            return (left->getCacheRatio() < right->getCacheRatio());
893        };
894        std::priority_queue<std::shared_ptr<CacheTracker>,
895                std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
896        for (const auto& it : trackers) {
897            it.second->loadStats();
898            queue.push(it.second);
899        }
900        ATRACE_END();
901
902        // 3. Bounce across the queue, freeing items from whichever tracker is
903        // the most over their assigned quota
904        ATRACE_BEGIN("bounce");
905        std::shared_ptr<CacheTracker> active;
906        while (active || !queue.empty()) {
907            // Find the best tracker to work with; this might involve swapping
908            // if the active tracker is no longer the most over quota
909            bool nextBetter = active && !queue.empty()
910                    && active->getCacheRatio() < queue.top()->getCacheRatio();
911            if (!active || nextBetter) {
912                if (active) {
913                    // Current tracker still has items, so we'll consider it
914                    // again later once it bubbles up to surface
915                    queue.push(active);
916                }
917                active = queue.top(); queue.pop();
918                active->ensureItems();
919                continue;
920            }
921
922            // If no items remain, go find another tracker
923            if (active->items.empty()) {
924                active = nullptr;
925                continue;
926            } else {
927                auto item = active->items.back();
928                active->items.pop_back();
929
930                LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
931                if (!noop) {
932                    item->purge();
933                }
934                active->cacheUsed -= item->size;
935                needed -= item->size;
936            }
937
938            // Verify that we're actually done before bailing, since sneaky
939            // apps might be using hardlinks
940            if (needed <= 0) {
941                free = data_disk_free(data_path);
942                needed = freeStorageSize - free;
943                if (needed <= 0) {
944                    break;
945                } else {
946                    LOG(WARNING) << "Expected to be done but still need " << needed;
947                }
948            }
949        }
950        ATRACE_END();
951
952    } else {
953        ATRACE_BEGIN("start");
954        cache_t* cache = start_cache_collection();
955        ATRACE_END();
956
957        ATRACE_BEGIN("add");
958        for (auto user : get_known_users(uuid_)) {
959            add_cache_files(cache, create_data_user_ce_path(uuid_, user));
960            add_cache_files(cache, create_data_user_de_path(uuid_, user));
961            add_cache_files(cache,
962                    StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
963        }
964        // Add files from /data/preloads/file_cache
965        if (uuid == nullptr) {
966            add_preloads_file_cache(cache, uuid_);
967        }
968        ATRACE_END();
969
970        ATRACE_BEGIN("clear");
971        clear_cache_files(data_path, cache, freeStorageSize);
972        ATRACE_END();
973
974        ATRACE_BEGIN("finish");
975        finish_cache_collection(cache);
976        ATRACE_END();
977    }
978
979    free = data_disk_free(data_path);
980    if (free >= freeStorageSize) {
981        return ok();
982    } else {
983        return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
984                freeStorageSize, data_path.c_str(), free));
985    }
986}
987
988binder::Status InstalldNativeService::rmdex(const std::string& codePath,
989        const std::string& instructionSet) {
990    ENFORCE_UID(AID_SYSTEM);
991    std::lock_guard<std::recursive_mutex> lock(mLock);
992
993    char dex_path[PKG_PATH_MAX];
994
995    const char* path = codePath.c_str();
996    const char* instruction_set = instructionSet.c_str();
997
998    if (validate_apk_path(path) && validate_system_app_path(path)) {
999        return error("Invalid path " + codePath);
1000    }
1001
1002    if (!create_cache_path(dex_path, path, instruction_set)) {
1003        return error("Failed to create cache path for " + codePath);
1004    }
1005
1006    ALOGV("unlink %s\n", dex_path);
1007    if (unlink(dex_path) < 0) {
1008        return error(StringPrintf("Failed to unlink %s", dex_path));
1009    } else {
1010        return ok();
1011    }
1012}
1013
1014struct stats {
1015    int64_t codeSize;
1016    int64_t dataSize;
1017    int64_t cacheSize;
1018};
1019
1020#if MEASURE_DEBUG
1021static std::string toString(std::vector<int64_t> values) {
1022    std::stringstream res;
1023    res << "[";
1024    for (size_t i = 0; i < values.size(); i++) {
1025        res << values[i];
1026        if (i < values.size() - 1) {
1027            res << ",";
1028        }
1029    }
1030    res << "]";
1031    return res.str();
1032}
1033#endif
1034
1035static void collectQuotaStats(const std::string& device, int32_t userId,
1036        int32_t appId, struct stats* stats, struct stats* extStats) {
1037    if (device.empty()) return;
1038
1039    struct dqblk dq;
1040
1041    uid_t uid = multiuser_get_uid(userId, appId);
1042    if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1043            reinterpret_cast<char*>(&dq)) != 0) {
1044        if (errno != ESRCH) {
1045            PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1046        }
1047    } else {
1048#if MEASURE_DEBUG
1049        LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1050#endif
1051        stats->dataSize += dq.dqb_curspace;
1052    }
1053
1054    int cacheGid = multiuser_get_cache_gid(userId, appId);
1055    if (cacheGid != -1) {
1056        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1057                reinterpret_cast<char*>(&dq)) != 0) {
1058            if (errno != ESRCH) {
1059                PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1060            }
1061        } else {
1062#if MEASURE_DEBUG
1063            LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1064#endif
1065            stats->cacheSize += dq.dqb_curspace;
1066        }
1067    }
1068
1069    int extGid = multiuser_get_ext_gid(userId, appId);
1070    if (extGid != -1) {
1071        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1072                reinterpret_cast<char*>(&dq)) != 0) {
1073            if (errno != ESRCH) {
1074                PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1075            }
1076        } else {
1077#if MEASURE_DEBUG
1078            LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1079#endif
1080            extStats->dataSize += dq.dqb_curspace;
1081        }
1082    }
1083
1084    int sharedGid = multiuser_get_shared_gid(userId, appId);
1085    if (sharedGid != -1) {
1086        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1087                reinterpret_cast<char*>(&dq)) != 0) {
1088            if (errno != ESRCH) {
1089                PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1090            }
1091        } else {
1092#if MEASURE_DEBUG
1093            LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1094#endif
1095            stats->codeSize += dq.dqb_curspace;
1096        }
1097    }
1098}
1099
1100static void collectManualStats(const std::string& path, struct stats* stats) {
1101    DIR *d;
1102    int dfd;
1103    struct dirent *de;
1104    struct stat s;
1105
1106    d = opendir(path.c_str());
1107    if (d == nullptr) {
1108        if (errno != ENOENT) {
1109            PLOG(WARNING) << "Failed to open " << path;
1110        }
1111        return;
1112    }
1113    dfd = dirfd(d);
1114    while ((de = readdir(d))) {
1115        const char *name = de->d_name;
1116
1117        int64_t size = 0;
1118        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1119            size = s.st_blocks * 512;
1120        }
1121
1122        if (de->d_type == DT_DIR) {
1123            if (!strcmp(name, ".")) {
1124                // Don't recurse, but still count node size
1125            } else if (!strcmp(name, "..")) {
1126                // Don't recurse or count node size
1127                continue;
1128            } else {
1129                // Measure all children nodes
1130                size = 0;
1131                calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
1132            }
1133
1134            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1135                stats->cacheSize += size;
1136            }
1137        }
1138
1139        // Legacy symlink isn't owned by app
1140        if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1141            continue;
1142        }
1143
1144        // Everything found inside is considered data
1145        stats->dataSize += size;
1146    }
1147    closedir(d);
1148}
1149
1150static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1151        bool exclude_apps = false) {
1152    DIR *d;
1153    int dfd;
1154    struct dirent *de;
1155    struct stat s;
1156
1157    d = opendir(path.c_str());
1158    if (d == nullptr) {
1159        if (errno != ENOENT) {
1160            PLOG(WARNING) << "Failed to open " << path;
1161        }
1162        return;
1163    }
1164    dfd = dirfd(d);
1165    while ((de = readdir(d))) {
1166        if (de->d_type == DT_DIR) {
1167            const char *name = de->d_name;
1168            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1169                continue;
1170            }
1171            if (!strcmp(name, ".") || !strcmp(name, "..")) {
1172                continue;
1173            } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1174                continue;
1175            } else {
1176                collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1177            }
1178        }
1179    }
1180    closedir(d);
1181}
1182
1183static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1184    FTS *fts;
1185    FTSENT *p;
1186    char *argv[] = { (char*) path.c_str(), nullptr };
1187    if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1188        PLOG(ERROR) << "Failed to fts_open " << path;
1189        return;
1190    }
1191    while ((p = fts_read(fts)) != NULL) {
1192        switch (p->fts_info) {
1193        case FTS_D:
1194            if (p->fts_level == 4
1195                    && !strcmp(p->fts_name, "cache")
1196                    && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1197                    && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1198                p->fts_number = 1;
1199            }
1200            p->fts_number = p->fts_parent->fts_number;
1201            // Fall through to count the directory
1202        case FTS_DEFAULT:
1203        case FTS_F:
1204        case FTS_SL:
1205        case FTS_SLNONE:
1206            int64_t size = (p->fts_statp->st_blocks * 512);
1207            if (p->fts_number == 1) {
1208                stats->cacheSize += size;
1209            }
1210            stats->dataSize += size;
1211            break;
1212        }
1213    }
1214    fts_close(fts);
1215}
1216
1217binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
1218        const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1219        int32_t appId, const std::vector<int64_t>& ceDataInodes,
1220        const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
1221    ENFORCE_UID(AID_SYSTEM);
1222    CHECK_ARGUMENT_UUID(uuid);
1223    for (auto packageName : packageNames) {
1224        CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1225    }
1226    std::lock_guard<std::recursive_mutex> lock(mLock);
1227
1228    // When modifying this logic, always verify using tests:
1229    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1230
1231#if MEASURE_DEBUG
1232    LOG(INFO) << "Measuring user " << userId << " app " << appId;
1233#endif
1234
1235    // Here's a summary of the common storage locations across the platform,
1236    // and how they're each tagged:
1237    //
1238    // /data/app/com.example                           UID system
1239    // /data/app/com.example/oat                       UID system
1240    // /data/user/0/com.example                        UID u0_a10      GID u0_a10
1241    // /data/user/0/com.example/cache                  UID u0_a10      GID u0_a10_cache
1242    // /data/media/0/foo.txt                           UID u0_media_rw
1243    // /data/media/0/bar.jpg                           UID u0_media_rw GID u0_media_image
1244    // /data/media/0/Android/data/com.example          UID u0_media_rw GID u0_a10_ext
1245    // /data/media/0/Android/data/com.example/cache    UID u0_media_rw GID u0_a10_ext_cache
1246    // /data/media/obb/com.example                     UID system
1247
1248    struct stats stats;
1249    struct stats extStats;
1250    memset(&stats, 0, sizeof(stats));
1251    memset(&extStats, 0, sizeof(extStats));
1252
1253    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1254
1255    auto device = findQuotaDeviceForUuid(uuid);
1256    if (device.empty()) {
1257        flags &= ~FLAG_USE_QUOTA;
1258    }
1259
1260    ATRACE_BEGIN("obb");
1261    for (auto packageName : packageNames) {
1262        auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1263        calculate_tree_size(obbCodePath, &extStats.codeSize);
1264    }
1265    ATRACE_END();
1266
1267    if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1268        ATRACE_BEGIN("code");
1269        for (auto codePath : codePaths) {
1270            calculate_tree_size(codePath, &stats.codeSize, -1,
1271                    multiuser_get_shared_gid(userId, appId));
1272        }
1273        ATRACE_END();
1274
1275        ATRACE_BEGIN("quota");
1276        collectQuotaStats(device, userId, appId, &stats, &extStats);
1277        ATRACE_END();
1278
1279    } else {
1280        ATRACE_BEGIN("code");
1281        for (auto codePath : codePaths) {
1282            calculate_tree_size(codePath, &stats.codeSize);
1283        }
1284        ATRACE_END();
1285
1286        for (size_t i = 0; i < packageNames.size(); i++) {
1287            const char* pkgname = packageNames[i].c_str();
1288
1289            ATRACE_BEGIN("data");
1290            auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1291            collectManualStats(cePath, &stats);
1292            auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1293            collectManualStats(dePath, &stats);
1294            ATRACE_END();
1295
1296            ATRACE_BEGIN("profiles");
1297            auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1298            calculate_tree_size(userProfilePath, &stats.dataSize);
1299            auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1300            calculate_tree_size(refProfilePath, &stats.codeSize);
1301            ATRACE_END();
1302
1303            ATRACE_BEGIN("external");
1304            auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data");
1305            collectManualStats(extPath, &extStats);
1306            auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media");
1307            calculate_tree_size(mediaPath, &extStats.dataSize);
1308            ATRACE_END();
1309        }
1310
1311        ATRACE_BEGIN("dalvik");
1312        int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1313        if (sharedGid != -1) {
1314            calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1315                    sharedGid, -1);
1316        }
1317        calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1318                multiuser_get_uid(userId, appId), -1);
1319        ATRACE_END();
1320    }
1321
1322    std::vector<int64_t> ret;
1323    ret.push_back(stats.codeSize);
1324    ret.push_back(stats.dataSize);
1325    ret.push_back(stats.cacheSize);
1326    ret.push_back(extStats.codeSize);
1327    ret.push_back(extStats.dataSize);
1328    ret.push_back(extStats.cacheSize);
1329#if MEASURE_DEBUG
1330    LOG(DEBUG) << "Final result " << toString(ret);
1331#endif
1332    *_aidl_return = ret;
1333    return ok();
1334}
1335
1336binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1337        int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1338        std::vector<int64_t>* _aidl_return) {
1339    ENFORCE_UID(AID_SYSTEM);
1340    CHECK_ARGUMENT_UUID(uuid);
1341    std::lock_guard<std::recursive_mutex> lock(mLock);
1342
1343    // When modifying this logic, always verify using tests:
1344    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1345
1346#if MEASURE_DEBUG
1347    LOG(INFO) << "Measuring user " << userId;
1348#endif
1349
1350    struct stats stats;
1351    struct stats extStats;
1352    memset(&stats, 0, sizeof(stats));
1353    memset(&extStats, 0, sizeof(extStats));
1354
1355    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1356
1357    auto device = findQuotaDeviceForUuid(uuid);
1358    if (device.empty()) {
1359        flags &= ~FLAG_USE_QUOTA;
1360    }
1361
1362    if (flags & FLAG_USE_QUOTA) {
1363        struct dqblk dq;
1364
1365        ATRACE_BEGIN("obb");
1366        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1367                reinterpret_cast<char*>(&dq)) != 0) {
1368            if (errno != ESRCH) {
1369                PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1370            }
1371        } else {
1372#if MEASURE_DEBUG
1373            LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1374#endif
1375            extStats.codeSize += dq.dqb_curspace;
1376        }
1377        ATRACE_END();
1378
1379        ATRACE_BEGIN("code");
1380        calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1381        ATRACE_END();
1382
1383        ATRACE_BEGIN("data");
1384        auto cePath = create_data_user_ce_path(uuid_, userId);
1385        collectManualStatsForUser(cePath, &stats, true);
1386        auto dePath = create_data_user_de_path(uuid_, userId);
1387        collectManualStatsForUser(dePath, &stats, true);
1388        ATRACE_END();
1389
1390        ATRACE_BEGIN("profile");
1391        auto userProfilePath = create_data_user_profile_path(userId);
1392        calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1393        auto refProfilePath = create_data_ref_profile_path();
1394        calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1395        ATRACE_END();
1396
1397        ATRACE_BEGIN("external");
1398        uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1399        if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1400                reinterpret_cast<char*>(&dq)) != 0) {
1401            if (errno != ESRCH) {
1402                PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1403            }
1404        } else {
1405#if MEASURE_DEBUG
1406            LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1407#endif
1408            extStats.dataSize += dq.dqb_curspace;
1409        }
1410        ATRACE_END();
1411
1412        ATRACE_BEGIN("dalvik");
1413        calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1414                -1, -1, true);
1415        calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1416                -1, -1, true);
1417        ATRACE_END();
1418
1419        ATRACE_BEGIN("quota");
1420        for (auto appId : appIds) {
1421            if (appId >= AID_APP_START) {
1422                collectQuotaStats(device, userId, appId, &stats, &extStats);
1423#if MEASURE_DEBUG
1424                // Sleep to make sure we don't lose logs
1425                usleep(1);
1426#endif
1427            }
1428        }
1429        ATRACE_END();
1430    } else {
1431        ATRACE_BEGIN("obb");
1432        auto obbPath = create_data_path(uuid_) + "/media/obb";
1433        calculate_tree_size(obbPath, &extStats.codeSize);
1434        ATRACE_END();
1435
1436        ATRACE_BEGIN("code");
1437        calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1438        ATRACE_END();
1439
1440        ATRACE_BEGIN("data");
1441        auto cePath = create_data_user_ce_path(uuid_, userId);
1442        collectManualStatsForUser(cePath, &stats);
1443        auto dePath = create_data_user_de_path(uuid_, userId);
1444        collectManualStatsForUser(dePath, &stats);
1445        ATRACE_END();
1446
1447        ATRACE_BEGIN("profile");
1448        auto userProfilePath = create_data_user_profile_path(userId);
1449        calculate_tree_size(userProfilePath, &stats.dataSize);
1450        auto refProfilePath = create_data_ref_profile_path();
1451        calculate_tree_size(refProfilePath, &stats.codeSize);
1452        ATRACE_END();
1453
1454        ATRACE_BEGIN("external");
1455        auto dataMediaPath = create_data_media_path(uuid_, userId);
1456        collectManualExternalStatsForUser(dataMediaPath, &extStats);
1457#if MEASURE_DEBUG
1458        LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1459                << extStats.cacheSize;
1460#endif
1461        ATRACE_END();
1462
1463        ATRACE_BEGIN("dalvik");
1464        calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1465        calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize);
1466        ATRACE_END();
1467    }
1468
1469    std::vector<int64_t> ret;
1470    ret.push_back(stats.codeSize);
1471    ret.push_back(stats.dataSize);
1472    ret.push_back(stats.cacheSize);
1473    ret.push_back(extStats.codeSize);
1474    ret.push_back(extStats.dataSize);
1475    ret.push_back(extStats.cacheSize);
1476#if MEASURE_DEBUG
1477    LOG(DEBUG) << "Final result " << toString(ret);
1478#endif
1479    *_aidl_return = ret;
1480    return ok();
1481}
1482
1483binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1484        int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1485    ENFORCE_UID(AID_SYSTEM);
1486    CHECK_ARGUMENT_UUID(uuid);
1487    std::lock_guard<std::recursive_mutex> lock(mLock);
1488
1489    // When modifying this logic, always verify using tests:
1490    // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1491
1492#if MEASURE_DEBUG
1493    LOG(INFO) << "Measuring external " << userId;
1494#endif
1495
1496    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1497
1498    int64_t totalSize = 0;
1499    int64_t audioSize = 0;
1500    int64_t videoSize = 0;
1501    int64_t imageSize = 0;
1502
1503    auto device = findQuotaDeviceForUuid(uuid);
1504    if (device.empty()) {
1505        flags &= ~FLAG_USE_QUOTA;
1506    }
1507
1508    if (flags & FLAG_USE_QUOTA) {
1509        struct dqblk dq;
1510
1511        uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1512        if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1513                reinterpret_cast<char*>(&dq)) != 0) {
1514            if (errno != ESRCH) {
1515                PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1516            }
1517        } else {
1518#if MEASURE_DEBUG
1519        LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1520#endif
1521            totalSize = dq.dqb_curspace;
1522        }
1523
1524        gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1525        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1526                reinterpret_cast<char*>(&dq)) == 0) {
1527#if MEASURE_DEBUG
1528        LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1529#endif
1530            audioSize = dq.dqb_curspace;
1531        }
1532        gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1533        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1534                reinterpret_cast<char*>(&dq)) == 0) {
1535#if MEASURE_DEBUG
1536        LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1537#endif
1538            videoSize = dq.dqb_curspace;
1539        }
1540        gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1541        if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1542                reinterpret_cast<char*>(&dq)) == 0) {
1543#if MEASURE_DEBUG
1544        LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1545#endif
1546            imageSize = dq.dqb_curspace;
1547        }
1548    } else {
1549        FTS *fts;
1550        FTSENT *p;
1551        auto path = create_data_media_path(uuid_, userId);
1552        char *argv[] = { (char*) path.c_str(), nullptr };
1553        if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1554            return error("Failed to fts_open " + path);
1555        }
1556        while ((p = fts_read(fts)) != NULL) {
1557            char* ext;
1558            int64_t size = (p->fts_statp->st_blocks * 512);
1559            switch (p->fts_info) {
1560            case FTS_F:
1561                // Only categorize files not belonging to apps
1562                if (p->fts_statp->st_gid < AID_APP_START) {
1563                    ext = strrchr(p->fts_name, '.');
1564                    if (ext != nullptr) {
1565                        switch (MatchExtension(++ext)) {
1566                        case AID_MEDIA_AUDIO: audioSize += size; break;
1567                        case AID_MEDIA_VIDEO: videoSize += size; break;
1568                        case AID_MEDIA_IMAGE: imageSize += size; break;
1569                        }
1570                    }
1571                }
1572                // Fall through to always count against total
1573            case FTS_D:
1574            case FTS_DEFAULT:
1575            case FTS_SL:
1576            case FTS_SLNONE:
1577                totalSize += size;
1578                break;
1579            }
1580        }
1581        fts_close(fts);
1582    }
1583
1584    std::vector<int64_t> ret;
1585    ret.push_back(totalSize);
1586    ret.push_back(audioSize);
1587    ret.push_back(videoSize);
1588    ret.push_back(imageSize);
1589#if MEASURE_DEBUG
1590    LOG(DEBUG) << "Final result " << toString(ret);
1591#endif
1592    *_aidl_return = ret;
1593    return ok();
1594}
1595
1596binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1597        int32_t userId, int32_t appId, int64_t cacheQuota) {
1598    ENFORCE_UID(AID_SYSTEM);
1599    CHECK_ARGUMENT_UUID(uuid);
1600    std::lock_guard<std::recursive_mutex> lock(mLock);
1601
1602    int32_t uid = multiuser_get_uid(userId, appId);
1603    mCacheQuotas[uid] = cacheQuota;
1604
1605    return ok();
1606}
1607
1608// Dumps the contents of a profile file, using pkgname's dex files for pretty
1609// printing the result.
1610binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1611        const std::string& codePaths, bool* _aidl_return) {
1612    ENFORCE_UID(AID_SYSTEM);
1613    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1614    std::lock_guard<std::recursive_mutex> lock(mLock);
1615
1616    const char* pkgname = packageName.c_str();
1617    const char* code_paths = codePaths.c_str();
1618
1619    *_aidl_return = dump_profiles(uid, pkgname, code_paths);
1620    return ok();
1621}
1622
1623// TODO: Consider returning error codes.
1624binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1625        bool* _aidl_return) {
1626    ENFORCE_UID(AID_SYSTEM);
1627    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1628    std::lock_guard<std::recursive_mutex> lock(mLock);
1629
1630    const char* pkgname = packageName.c_str();
1631    *_aidl_return = analyse_profiles(uid, pkgname);
1632    return ok();
1633}
1634
1635binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1636        const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1637        int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1638        const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1639        const std::unique_ptr<std::string>& sharedLibraries) {
1640    ENFORCE_UID(AID_SYSTEM);
1641    CHECK_ARGUMENT_UUID(uuid);
1642    if (packageName && *packageName != "*") {
1643        CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1644    }
1645    std::lock_guard<std::recursive_mutex> lock(mLock);
1646
1647    const char* apk_path = apkPath.c_str();
1648    const char* pkgname = packageName ? packageName->c_str() : "*";
1649    const char* instruction_set = instructionSet.c_str();
1650    const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1651    const char* compiler_filter = compilerFilter.c_str();
1652    const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1653    const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1654
1655    int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1656            oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
1657    return res ? error(res, "Failed to dexopt") : ok();
1658}
1659
1660binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1661    ENFORCE_UID(AID_SYSTEM);
1662    std::lock_guard<std::recursive_mutex> lock(mLock);
1663
1664    const char* instruction_set = instructionSet.c_str();
1665
1666    char boot_marker_path[PKG_PATH_MAX];
1667    sprintf(boot_marker_path,
1668          "%s/%s/%s/.booting",
1669          android_data_dir.path,
1670          DALVIK_CACHE,
1671          instruction_set);
1672
1673    ALOGV("mark_boot_complete : %s", boot_marker_path);
1674    if (unlink(boot_marker_path) != 0) {
1675        return error(StringPrintf("Failed to unlink %s", boot_marker_path));
1676    }
1677    return ok();
1678}
1679
1680void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1681        struct stat* statbuf)
1682{
1683    while (path[basepos] != 0) {
1684        if (path[basepos] == '/') {
1685            path[basepos] = 0;
1686            if (lstat(path, statbuf) < 0) {
1687                ALOGV("Making directory: %s\n", path);
1688                if (mkdir(path, mode) == 0) {
1689                    chown(path, uid, gid);
1690                } else {
1691                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1692                }
1693            }
1694            path[basepos] = '/';
1695            basepos++;
1696        }
1697        basepos++;
1698    }
1699}
1700
1701binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1702        const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1703        const std::string& nativeLibPath32, int32_t userId) {
1704    ENFORCE_UID(AID_SYSTEM);
1705    CHECK_ARGUMENT_UUID(uuid);
1706    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1707    std::lock_guard<std::recursive_mutex> lock(mLock);
1708
1709    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1710    const char* pkgname = packageName.c_str();
1711    const char* asecLibDir = nativeLibPath32.c_str();
1712    struct stat s, libStat;
1713    binder::Status res = ok();
1714
1715    auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1716    auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
1717
1718    const char* pkgdir = _pkgdir.c_str();
1719    const char* libsymlink = _libsymlink.c_str();
1720
1721    if (stat(pkgdir, &s) < 0) {
1722        return error("Failed to stat " + _pkgdir);
1723    }
1724
1725    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1726        return error("Failed to chown " + _pkgdir);
1727    }
1728
1729    if (chmod(pkgdir, 0700) < 0) {
1730        res = error("Failed to chmod " + _pkgdir);
1731        goto out;
1732    }
1733
1734    if (lstat(libsymlink, &libStat) < 0) {
1735        if (errno != ENOENT) {
1736            res = error("Failed to stat " + _libsymlink);
1737            goto out;
1738        }
1739    } else {
1740        if (S_ISDIR(libStat.st_mode)) {
1741            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1742                res = error("Failed to delete " + _libsymlink);
1743                goto out;
1744            }
1745        } else if (S_ISLNK(libStat.st_mode)) {
1746            if (unlink(libsymlink) < 0) {
1747                res = error("Failed to unlink " + _libsymlink);
1748                goto out;
1749            }
1750        }
1751    }
1752
1753    if (symlink(asecLibDir, libsymlink) < 0) {
1754        res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
1755        goto out;
1756    }
1757
1758out:
1759    if (chmod(pkgdir, s.st_mode) < 0) {
1760        auto msg = "Failed to cleanup chmod " + _pkgdir;
1761        if (res.isOk()) {
1762            res = error(msg);
1763        } else {
1764            PLOG(ERROR) << msg;
1765        }
1766    }
1767
1768    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1769        auto msg = "Failed to cleanup chown " + _pkgdir;
1770        if (res.isOk()) {
1771            res = error(msg);
1772        } else {
1773            PLOG(ERROR) << msg;
1774        }
1775    }
1776
1777    return res;
1778}
1779
1780static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1781{
1782    static const char *IDMAP_BIN = "/system/bin/idmap";
1783    static const size_t MAX_INT_LEN = 32;
1784    char idmap_str[MAX_INT_LEN];
1785
1786    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1787
1788    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1789    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1790}
1791
1792// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1793// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1794static int flatten_path(const char *prefix, const char *suffix,
1795        const char *overlay_path, char *idmap_path, size_t N)
1796{
1797    if (overlay_path == NULL || idmap_path == NULL) {
1798        return -1;
1799    }
1800    const size_t len_overlay_path = strlen(overlay_path);
1801    // will access overlay_path + 1 further below; requires absolute path
1802    if (len_overlay_path < 2 || *overlay_path != '/') {
1803        return -1;
1804    }
1805    const size_t len_idmap_root = strlen(prefix);
1806    const size_t len_suffix = strlen(suffix);
1807    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1808            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1809        // additions below would cause overflow
1810        return -1;
1811    }
1812    if (N < len_idmap_root + len_overlay_path + len_suffix) {
1813        return -1;
1814    }
1815    memset(idmap_path, 0, N);
1816    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1817    char *ch = idmap_path + len_idmap_root;
1818    while (*ch != '\0') {
1819        if (*ch == '/') {
1820            *ch = '@';
1821        }
1822        ++ch;
1823    }
1824    return 0;
1825}
1826
1827binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1828        const std::string& overlayApkPath, int32_t uid) {
1829    ENFORCE_UID(AID_SYSTEM);
1830    std::lock_guard<std::recursive_mutex> lock(mLock);
1831
1832    const char* target_apk = targetApkPath.c_str();
1833    const char* overlay_apk = overlayApkPath.c_str();
1834    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1835
1836    int idmap_fd = -1;
1837    char idmap_path[PATH_MAX];
1838
1839    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1840                idmap_path, sizeof(idmap_path)) == -1) {
1841        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1842        goto fail;
1843    }
1844
1845    unlink(idmap_path);
1846    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1847    if (idmap_fd < 0) {
1848        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1849        goto fail;
1850    }
1851    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1852        ALOGE("idmap cannot chown '%s'\n", idmap_path);
1853        goto fail;
1854    }
1855    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1856        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1857        goto fail;
1858    }
1859
1860    pid_t pid;
1861    pid = fork();
1862    if (pid == 0) {
1863        /* child -- drop privileges before continuing */
1864        if (setgid(uid) != 0) {
1865            ALOGE("setgid(%d) failed during idmap\n", uid);
1866            exit(1);
1867        }
1868        if (setuid(uid) != 0) {
1869            ALOGE("setuid(%d) failed during idmap\n", uid);
1870            exit(1);
1871        }
1872        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1873            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1874            exit(1);
1875        }
1876
1877        run_idmap(target_apk, overlay_apk, idmap_fd);
1878        exit(1); /* only if exec call to idmap failed */
1879    } else {
1880        int status = wait_child(pid);
1881        if (status != 0) {
1882            ALOGE("idmap failed, status=0x%04x\n", status);
1883            goto fail;
1884        }
1885    }
1886
1887    close(idmap_fd);
1888    return ok();
1889fail:
1890    if (idmap_fd >= 0) {
1891        close(idmap_fd);
1892        unlink(idmap_path);
1893    }
1894    return error();
1895}
1896
1897binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
1898    const char* overlay_apk = overlayApkPath.c_str();
1899    char idmap_path[PATH_MAX];
1900
1901    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1902                idmap_path, sizeof(idmap_path)) == -1) {
1903        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1904        return error();
1905    }
1906    if (unlink(idmap_path) < 0) {
1907        ALOGE("couldn't unlink idmap file %s\n", idmap_path);
1908        return error();
1909    }
1910    return ok();
1911}
1912
1913binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1914        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1915        const std::string& seInfo) {
1916    ENFORCE_UID(AID_SYSTEM);
1917    CHECK_ARGUMENT_UUID(uuid);
1918    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1919    std::lock_guard<std::recursive_mutex> lock(mLock);
1920
1921    binder::Status res = ok();
1922
1923    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1924    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
1925    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1926    const char* pkgName = packageName.c_str();
1927    const char* seinfo = seInfo.c_str();
1928
1929    uid_t uid = multiuser_get_uid(userId, appId);
1930    if (flags & FLAG_STORAGE_CE) {
1931        auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
1932        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1933            res = error("restorecon failed for " + path);
1934        }
1935    }
1936    if (flags & FLAG_STORAGE_DE) {
1937        auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
1938        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1939            res = error("restorecon failed for " + path);
1940        }
1941    }
1942    return res;
1943}
1944
1945binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1946        const std::string& instructionSet) {
1947    ENFORCE_UID(AID_SYSTEM);
1948    std::lock_guard<std::recursive_mutex> lock(mLock);
1949
1950    const char* oat_dir = oatDir.c_str();
1951    const char* instruction_set = instructionSet.c_str();
1952    char oat_instr_dir[PKG_PATH_MAX];
1953
1954    if (validate_apk_path(oat_dir)) {
1955        return error("Invalid path " + oatDir);
1956    }
1957    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1958        return error("Failed to prepare " + oatDir);
1959    }
1960    if (selinux_android_restorecon(oat_dir, 0)) {
1961        return error("Failed to restorecon " + oatDir);
1962    }
1963    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
1964    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1965        return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
1966    }
1967    return ok();
1968}
1969
1970binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1971    ENFORCE_UID(AID_SYSTEM);
1972    std::lock_guard<std::recursive_mutex> lock(mLock);
1973
1974    if (validate_apk_path(packageDir.c_str())) {
1975        return error("Invalid path " + packageDir);
1976    }
1977    if (delete_dir_contents_and_dir(packageDir) != 0) {
1978        return error("Failed to delete " + packageDir);
1979    }
1980    return ok();
1981}
1982
1983binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1984        const std::string& fromBase, const std::string& toBase) {
1985    ENFORCE_UID(AID_SYSTEM);
1986    std::lock_guard<std::recursive_mutex> lock(mLock);
1987
1988    const char* relative_path = relativePath.c_str();
1989    const char* from_base = fromBase.c_str();
1990    const char* to_base = toBase.c_str();
1991    char from_path[PKG_PATH_MAX];
1992    char to_path[PKG_PATH_MAX];
1993    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1994    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1995
1996    if (validate_apk_path_subdirs(from_path)) {
1997        return error(StringPrintf("Invalid from path %s", from_path));
1998    }
1999
2000    if (validate_apk_path_subdirs(to_path)) {
2001        return error(StringPrintf("Invalid to path %s", to_path));
2002    }
2003
2004    if (link(from_path, to_path) < 0) {
2005        return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
2006    }
2007
2008    return ok();
2009}
2010
2011binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2012        const std::string& instructionSet, const std::string& outputPath) {
2013    ENFORCE_UID(AID_SYSTEM);
2014    std::lock_guard<std::recursive_mutex> lock(mLock);
2015
2016    const char* apk_path = apkPath.c_str();
2017    const char* instruction_set = instructionSet.c_str();
2018    const char* oat_dir = outputPath.c_str();
2019
2020    bool success = move_ab(apk_path, instruction_set, oat_dir);
2021    return success ? ok() : error();
2022}
2023
2024binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2025        const std::string& instructionSet, const std::string& outputPath) {
2026    ENFORCE_UID(AID_SYSTEM);
2027    std::lock_guard<std::recursive_mutex> lock(mLock);
2028
2029    const char* apk_path = apkPath.c_str();
2030    const char* instruction_set = instructionSet.c_str();
2031    const char* oat_dir = outputPath.c_str();
2032
2033    bool res = delete_odex(apk_path, instruction_set, oat_dir);
2034    return res ? ok() : error();
2035}
2036
2037binder::Status InstalldNativeService::invalidateMounts() {
2038    ENFORCE_UID(AID_SYSTEM);
2039    std::lock_guard<std::recursive_mutex> lock(mLock);
2040
2041    mQuotaDevices.clear();
2042
2043    std::ifstream in("/proc/mounts");
2044    if (!in.is_open()) {
2045        return error("Failed to read mounts");
2046    }
2047
2048    std::string source;
2049    std::string target;
2050    std::string ignored;
2051    struct dqblk dq;
2052    while (!in.eof()) {
2053        std::getline(in, source, ' ');
2054        std::getline(in, target, ' ');
2055        std::getline(in, ignored);
2056
2057        if (source.compare(0, 11, "/dev/block/") == 0) {
2058            if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2059                    reinterpret_cast<char*>(&dq)) == 0) {
2060                LOG(DEBUG) << "Found " << source << " with quota";
2061                mQuotaDevices[target] = source;
2062            }
2063        }
2064    }
2065    return ok();
2066}
2067
2068std::string InstalldNativeService::findQuotaDeviceForUuid(
2069        const std::unique_ptr<std::string>& uuid) {
2070    auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2071    return mQuotaDevices[path];
2072}
2073
2074}  // namespace installd
2075}  // namespace android
2076