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