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