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