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