2 ** Copyright 2008, The Android Open Source Project
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
8 ** http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "InstalldNativeService.h"
19 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
28 #include <sys/capability.h>
30 #include <sys/resource.h>
31 #include <sys/quota.h>
33 #include <sys/statvfs.h>
34 #include <sys/types.h>
36 #include <sys/xattr.h>
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>
55 #include "installd_deps.h"
56 #include "otapreopt_utils.h"
59 #include "CacheTracker.h"
60 #include "MatchExtensionGen.h"
63 #define LOG_TAG "installd"
66 using android::base::StringPrintf;
72 static constexpr const char* kCpPath = "/system/bin/cp";
73 static constexpr const char* kXattrDefault = "user.default";
75 static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
77 static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78 static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79 static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
81 static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
82 static constexpr const char* IDMAP_SUFFIX = "@idmap";
84 // NOTE: keep in sync with Installer
85 static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
86 static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
87 static constexpr int FLAG_USE_QUOTA = 1 << 12;
88 static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
89 static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
90 static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
94 constexpr const char* kDump = "android.permission.DUMP";
96 static binder::Status ok() {
97 return binder::Status::ok();
100 static binder::Status exception(uint32_t code, const std::string& msg) {
101 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104 static binder::Status error() {
105 return binder::Status::fromServiceSpecificError(errno);
108 static binder::Status error(const std::string& msg) {
110 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113 static 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()));
118 binder::Status checkPermission(const char* permission) {
122 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
123 reinterpret_cast<int32_t*>(&uid))) {
126 return exception(binder::Status::EX_SECURITY,
127 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
131 binder::Status checkUid(uid_t expectedUid) {
132 uid_t uid = IPCThreadState::self()->getCallingUid();
133 if (uid == expectedUid || uid == AID_ROOT) {
136 return exception(binder::Status::EX_SECURITY,
137 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
141 binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
142 if (!uuid || is_valid_filename(*uuid)) {
145 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
146 StringPrintf("UUID %s is malformed", uuid->c_str()));
150 binder::Status checkArgumentPackageName(const std::string& packageName) {
151 if (is_valid_package_name(packageName.c_str())) {
154 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
155 StringPrintf("Package name %s is malformed", packageName.c_str()));
159 #define ENFORCE_UID(uid) { \
160 binder::Status status = checkUid((uid)); \
161 if (!status.isOk()) { \
166 #define CHECK_ARGUMENT_UUID(uuid) { \
167 binder::Status status = checkArgumentUuid((uuid)); \
168 if (!status.isOk()) { \
173 #define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
174 binder::Status status = \
175 checkArgumentPackageName((packageName)); \
176 if (!status.isOk()) { \
183 status_t InstalldNativeService::start() {
184 IPCThreadState::self()->disableBackgroundScheduling(true);
185 status_t ret = BinderService<InstalldNativeService>::publish();
186 if (ret != android::OK) {
189 sp<ProcessState> ps(ProcessState::self());
190 ps->startThreadPool();
191 ps->giveThreadPoolName();
195 status_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;
202 std::lock_guard<std::recursive_mutex> lock(mLock);
204 out << "installd is happy!" << endl;
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;
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;
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.
233 static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
236 char* before = nullptr;
237 char* after = nullptr;
239 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
240 // libselinux. Not needed here.
242 if (lgetfilecon(path.c_str(), &before) < 0) {
243 PLOG(ERROR) << "Failed before getfilecon for " << path;
246 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
247 PLOG(ERROR) << "Failed top-level restorecon for " << path;
250 if (lgetfilecon(path.c_str(), &after) < 0) {
251 PLOG(ERROR) << "Failed after getfilecon for " << path;
255 // If the initial top-level restorecon above changed the label, then go
256 // back and restorecon everything recursively
257 if (strcmp(before, after)) {
259 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
260 << path << "; running recursive restorecon";
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;
278 static 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,
284 static 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;
292 binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
293 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
294 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
295 ENFORCE_UID(AID_SYSTEM);
296 CHECK_ARGUMENT_UUID(uuid);
297 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
298 std::lock_guard<std::recursive_mutex> lock(mLock);
300 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
301 const char* pkgname = packageName.c_str();
303 // Assume invalid inode unless filled in below
304 if (_aidl_return != nullptr) *_aidl_return = -1;
306 int32_t uid = multiuser_get_uid(userId, appId);
307 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
308 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
310 // If UID doesn't have a specific cache GID, use UID value
311 if (cacheGid == -1) {
315 if (flags & FLAG_STORAGE_CE) {
316 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
317 bool existing = (access(path.c_str(), F_OK) == 0);
319 if (prepare_app_dir(path, targetMode, uid) ||
320 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
321 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
322 return error("Failed to prepare " + path);
325 // Consider restorecon over contents if label changed
326 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
327 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
328 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
329 return error("Failed to restorecon " + path);
332 // Remember inode numbers of cache directories so that we can clear
333 // contents while CE storage is locked
334 if (write_path_inode(path, "cache", kXattrInodeCache) ||
335 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
336 return error("Failed to write_path_inode for " + path);
339 // And return the CE inode of the top-level data directory so we can
340 // clear contents while CE storage is locked
341 if ((_aidl_return != nullptr)
342 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
343 return error("Failed to get_path_inode for " + path);
346 if (flags & FLAG_STORAGE_DE) {
347 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
348 bool existing = (access(path.c_str(), F_OK) == 0);
350 if (prepare_app_dir(path, targetMode, uid) ||
351 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
352 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
353 return error("Failed to prepare " + path);
356 // Consider restorecon over contents if label changed
357 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
358 return error("Failed to restorecon " + path);
361 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
362 const std::string profile_dir =
363 create_primary_current_profile_package_dir_path(userId, pkgname);
364 // read-write-execute only for the app user.
365 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
366 return error("Failed to prepare " + profile_dir);
368 const std::string profile_file = create_current_profile_path(userId, pkgname,
369 /*is_secondary_dex*/false);
370 // read-write only for the app user.
371 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
372 return error("Failed to prepare " + profile_file);
374 const std::string ref_profile_path =
375 create_primary_reference_profile_package_dir_path(pkgname);
376 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
378 int shared_app_gid = multiuser_get_shared_gid(0, appId);
379 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
380 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
381 return error("Failed to prepare " + ref_profile_path);
388 binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
389 const std::string& packageName, int32_t userId, int32_t flags) {
390 ENFORCE_UID(AID_SYSTEM);
391 CHECK_ARGUMENT_UUID(uuid);
392 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
393 std::lock_guard<std::recursive_mutex> lock(mLock);
395 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
396 const char* pkgname = packageName.c_str();
398 // This method only exists to upgrade system apps that have requested
399 // forceDeviceEncrypted, so their default storage always lives in a
400 // consistent location. This only works on non-FBE devices, since we
401 // never want to risk exposing data on a device with real CE/DE storage.
403 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
404 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
406 // If neither directory is marked as default, assume CE is default
407 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
408 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
409 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
410 return error("Failed to mark default storage " + ce_path);
414 // Migrate default data location if needed
415 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
416 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
418 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
419 LOG(WARNING) << "Requested default storage " << target
420 << " is not active; migrating from " << source;
421 if (delete_dir_contents_and_dir(target) != 0) {
422 return error("Failed to delete " + target);
424 if (rename(source.c_str(), target.c_str()) != 0) {
425 return error("Failed to rename " + source + " to " + target);
433 binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
434 ENFORCE_UID(AID_SYSTEM);
435 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
436 std::lock_guard<std::recursive_mutex> lock(mLock);
438 binder::Status res = ok();
439 if (!clear_primary_reference_profile(packageName)) {
440 res = error("Failed to clear reference profile for " + packageName);
442 if (!clear_primary_current_profiles(packageName)) {
443 res = error("Failed to clear current profiles for " + packageName);
448 binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
449 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
450 ENFORCE_UID(AID_SYSTEM);
451 CHECK_ARGUMENT_UUID(uuid);
452 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
453 std::lock_guard<std::recursive_mutex> lock(mLock);
455 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
456 const char* pkgname = packageName.c_str();
458 binder::Status res = ok();
459 if (flags & FLAG_STORAGE_CE) {
460 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
461 if (flags & FLAG_CLEAR_CACHE_ONLY) {
462 path = read_path_inode(path, "cache", kXattrInodeCache);
463 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
464 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
466 if (access(path.c_str(), F_OK) == 0) {
467 if (delete_dir_contents(path) != 0) {
468 res = error("Failed to delete contents of " + path);
472 if (flags & FLAG_STORAGE_DE) {
473 std::string suffix = "";
474 bool only_cache = false;
475 if (flags & FLAG_CLEAR_CACHE_ONLY) {
476 suffix = CACHE_DIR_POSTFIX;
478 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
479 suffix = CODE_CACHE_DIR_POSTFIX;
483 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
484 if (access(path.c_str(), F_OK) == 0) {
485 if (delete_dir_contents(path) != 0) {
486 res = error("Failed to delete contents of " + path);
490 if (!clear_primary_current_profile(packageName, userId)) {
491 res = error("Failed to clear current profile for " + packageName);
498 static int destroy_app_reference_profile(const std::string& pkgname) {
499 return delete_dir_contents_and_dir(
500 create_primary_reference_profile_package_dir_path(pkgname),
501 /*ignore_if_missing*/ true);
504 static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
505 return delete_dir_contents_and_dir(
506 create_primary_current_profile_package_dir_path(userid, pkgname),
507 /*ignore_if_missing*/ true);
510 binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
511 ENFORCE_UID(AID_SYSTEM);
512 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
513 std::lock_guard<std::recursive_mutex> lock(mLock);
515 binder::Status res = ok();
516 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
517 for (auto user : users) {
518 if (destroy_app_current_profiles(packageName, user) != 0) {
519 res = error("Failed to destroy current profiles for " + packageName);
522 if (destroy_app_reference_profile(packageName) != 0) {
523 res = error("Failed to destroy reference profile for " + packageName);
528 binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
529 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
530 ENFORCE_UID(AID_SYSTEM);
531 CHECK_ARGUMENT_UUID(uuid);
532 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
533 std::lock_guard<std::recursive_mutex> lock(mLock);
535 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
536 const char* pkgname = packageName.c_str();
538 binder::Status res = ok();
539 if (flags & FLAG_STORAGE_CE) {
540 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
541 if (delete_dir_contents_and_dir(path) != 0) {
542 res = error("Failed to delete " + path);
545 if (flags & FLAG_STORAGE_DE) {
546 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
547 if (delete_dir_contents_and_dir(path) != 0) {
548 res = error("Failed to delete " + path);
550 destroy_app_current_profiles(packageName, userId);
551 // TODO(calin): If the package is still installed by other users it's probably
552 // beneficial to keep the reference profile around.
553 // Verify if it's ok to do that.
554 destroy_app_reference_profile(packageName);
559 binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
560 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
561 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
562 int32_t targetSdkVersion) {
563 ENFORCE_UID(AID_SYSTEM);
564 CHECK_ARGUMENT_UUID(fromUuid);
565 CHECK_ARGUMENT_UUID(toUuid);
566 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
567 std::lock_guard<std::recursive_mutex> lock(mLock);
569 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
570 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
571 const char* package_name = packageName.c_str();
572 const char* data_app_name = dataAppName.c_str();
574 binder::Status res = ok();
575 std::vector<userid_t> users = get_known_users(from_uuid);
579 auto from = create_data_app_package_path(from_uuid, data_app_name);
580 auto to = create_data_app_package_path(to_uuid, data_app_name);
581 auto to_parent = create_data_app_path(to_uuid);
585 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
586 (char*) "-p", /* preserve timestamps, ownership, and permissions */
587 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
588 (char*) "-P", /* Do not follow symlinks [default] */
589 (char*) "-d", /* don't dereference symlinks */
590 (char*) from.c_str(),
591 (char*) to_parent.c_str()
594 LOG(DEBUG) << "Copying " << from << " to " << to;
595 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
597 res = error(rc, "Failed copying " + from + " to " + to);
601 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
602 res = error("Failed to restorecon " + to);
607 // Copy private data for all known users
608 for (auto user : users) {
610 // Data source may not exist for all users; that's okay
611 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
612 if (access(from_ce.c_str(), F_OK) != 0) {
613 LOG(INFO) << "Missing source " << from_ce;
617 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
618 seInfo, targetSdkVersion, nullptr).isOk()) {
619 res = error("Failed to create package target");
625 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
626 (char*) "-p", /* preserve timestamps, ownership, and permissions */
627 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
628 (char*) "-P", /* Do not follow symlinks [default] */
629 (char*) "-d", /* don't dereference symlinks */
635 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
636 auto to = create_data_user_de_path(to_uuid, user);
637 argv[6] = (char*) from.c_str();
638 argv[7] = (char*) to.c_str();
640 LOG(DEBUG) << "Copying " << from << " to " << to;
641 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
643 res = error(rc, "Failed copying " + from + " to " + to);
648 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
649 auto to = create_data_user_ce_path(to_uuid, user);
650 argv[6] = (char*) from.c_str();
651 argv[7] = (char*) to.c_str();
653 LOG(DEBUG) << "Copying " << from << " to " << to;
654 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
656 res = error(rc, "Failed copying " + from + " to " + to);
661 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
662 appId, seInfo).isOk()) {
663 res = error("Failed to restorecon");
668 // We let the framework scan the new location and persist that before
669 // deleting the data in the old location; this ordering ensures that
670 // we can recover from things like battery pulls.
674 // Nuke everything we might have already copied
676 auto to = create_data_app_package_path(to_uuid, data_app_name);
677 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
678 LOG(WARNING) << "Failed to rollback " << to;
681 for (auto user : users) {
683 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
684 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
685 LOG(WARNING) << "Failed to rollback " << to;
689 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
690 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
691 LOG(WARNING) << "Failed to rollback " << to;
698 binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
699 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
700 ENFORCE_UID(AID_SYSTEM);
701 CHECK_ARGUMENT_UUID(uuid);
702 std::lock_guard<std::recursive_mutex> lock(mLock);
704 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
705 if (flags & FLAG_STORAGE_DE) {
706 if (uuid_ == nullptr) {
707 if (ensure_config_user_dirs(userId) != 0) {
708 return error(StringPrintf("Failed to ensure dirs for %d", userId));
715 binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
716 int32_t userId, int32_t flags) {
717 ENFORCE_UID(AID_SYSTEM);
718 CHECK_ARGUMENT_UUID(uuid);
719 std::lock_guard<std::recursive_mutex> lock(mLock);
721 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
722 binder::Status res = ok();
723 if (flags & FLAG_STORAGE_DE) {
724 auto path = create_data_user_de_path(uuid_, userId);
725 if (delete_dir_contents_and_dir(path, true) != 0) {
726 res = error("Failed to delete " + path);
728 if (uuid_ == nullptr) {
729 path = create_data_misc_legacy_path(userId);
730 if (delete_dir_contents_and_dir(path, true) != 0) {
731 res = error("Failed to delete " + path);
733 path = create_primary_cur_profile_dir_path(userId);
734 if (delete_dir_contents_and_dir(path, true) != 0) {
735 res = error("Failed to delete " + path);
739 if (flags & FLAG_STORAGE_CE) {
740 auto path = create_data_user_ce_path(uuid_, userId);
741 if (delete_dir_contents_and_dir(path, true) != 0) {
742 res = error("Failed to delete " + path);
744 path = create_data_media_path(uuid_, userId);
745 if (delete_dir_contents_and_dir(path, true) != 0) {
746 res = error("Failed to delete " + path);
752 /* Try to ensure free_size bytes of storage are available.
753 * Returns 0 on success.
754 * This is rather simple-minded because doing a full LRU would
755 * be potentially memory-intensive, and without atime it would
756 * also require that apps constantly modify file metadata even
757 * when just reading from the cache, which is pretty awful.
759 binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
760 int64_t freeStorageSize, int32_t flags) {
761 ENFORCE_UID(AID_SYSTEM);
762 CHECK_ARGUMENT_UUID(uuid);
763 std::lock_guard<std::recursive_mutex> lock(mLock);
765 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
766 auto data_path = create_data_path(uuid_);
767 auto device = findQuotaDeviceForUuid(uuid);
768 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
770 int64_t free = data_disk_free(data_path);
771 int64_t needed = freeStorageSize - free;
773 return error("Failed to determine free space for " + data_path);
774 } else if (free >= freeStorageSize) {
778 LOG(DEBUG) << "Found " << data_path << " with " << free << " free; caller requested "
781 if (flags & FLAG_FREE_CACHE_V2) {
782 // This new cache strategy fairly removes files from UIDs by deleting
783 // files from the UIDs which are most over their allocated quota
785 // 1. Create trackers for every known UID
786 ATRACE_BEGIN("create");
787 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
788 for (auto user : get_known_users(uuid_)) {
792 (char*) create_data_user_ce_path(uuid_, user).c_str(),
793 (char*) create_data_user_de_path(uuid_, user).c_str(),
796 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
797 return error("Failed to fts_open");
799 while ((p = fts_read(fts)) != NULL) {
800 if (p->fts_info == FTS_D && p->fts_level == 1) {
801 uid_t uid = p->fts_statp->st_uid;
802 auto search = trackers.find(uid);
803 if (search != trackers.end()) {
804 search->second->addDataPath(p->fts_path);
806 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
807 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
808 tracker->addDataPath(p->fts_path);
810 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
811 tracker->cacheQuota = mCacheQuotas[uid];
813 if (tracker->cacheQuota == 0) {
814 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
815 tracker->cacheQuota = 67108864;
817 trackers[uid] = tracker;
819 fts_set(fts, p, FTS_SKIP);
826 // 2. Populate tracker stats and insert into priority queue
827 ATRACE_BEGIN("populate");
828 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
829 return (left->getCacheRatio() < right->getCacheRatio());
831 std::priority_queue<std::shared_ptr<CacheTracker>,
832 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
833 for (const auto& it : trackers) {
834 it.second->loadStats();
835 queue.push(it.second);
839 // 3. Bounce across the queue, freeing items from whichever tracker is
840 // the most over their assigned quota
841 ATRACE_BEGIN("bounce");
842 std::shared_ptr<CacheTracker> active;
843 while (active || !queue.empty()) {
844 // Only look at apps under quota when explicitly requested
845 if (active && (active->getCacheRatio() < 10000)
846 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
847 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
848 << " isn't over quota, and defy not requested";
852 // Find the best tracker to work with; this might involve swapping
853 // if the active tracker is no longer the most over quota
854 bool nextBetter = active && !queue.empty()
855 && active->getCacheRatio() < queue.top()->getCacheRatio();
856 if (!active || nextBetter) {
858 // Current tracker still has items, so we'll consider it
859 // again later once it bubbles up to surface
862 active = queue.top(); queue.pop();
863 active->ensureItems();
867 // If no items remain, go find another tracker
868 if (active->items.empty()) {
872 auto item = active->items.back();
873 active->items.pop_back();
875 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
879 active->cacheUsed -= item->size;
880 needed -= item->size;
883 // Verify that we're actually done before bailing, since sneaky
884 // apps might be using hardlinks
886 free = data_disk_free(data_path);
887 needed = freeStorageSize - free;
891 LOG(WARNING) << "Expected to be done but still need " << needed;
898 ATRACE_BEGIN("start");
899 cache_t* cache = start_cache_collection();
903 for (auto user : get_known_users(uuid_)) {
904 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
905 add_cache_files(cache, create_data_user_de_path(uuid_, user));
906 add_cache_files(cache,
907 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
909 // Add files from /data/preloads/file_cache
910 if (uuid == nullptr) {
911 add_preloads_file_cache(cache, uuid_);
915 ATRACE_BEGIN("clear");
916 clear_cache_files(data_path, cache, freeStorageSize);
919 ATRACE_BEGIN("finish");
920 finish_cache_collection(cache);
924 free = data_disk_free(data_path);
925 if (free >= freeStorageSize) {
928 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
929 freeStorageSize, data_path.c_str(), free));
933 binder::Status InstalldNativeService::rmdex(const std::string& codePath,
934 const std::string& instructionSet) {
935 ENFORCE_UID(AID_SYSTEM);
936 std::lock_guard<std::recursive_mutex> lock(mLock);
938 char dex_path[PKG_PATH_MAX];
940 const char* path = codePath.c_str();
941 const char* instruction_set = instructionSet.c_str();
943 if (validate_apk_path(path) && validate_system_app_path(path)) {
944 return error("Invalid path " + codePath);
947 if (!create_cache_path(dex_path, path, instruction_set)) {
948 return error("Failed to create cache path for " + codePath);
951 ALOGV("unlink %s\n", dex_path);
952 if (unlink(dex_path) < 0) {
953 return error(StringPrintf("Failed to unlink %s", dex_path));
966 static std::string toString(std::vector<int64_t> values) {
967 std::stringstream res;
969 for (size_t i = 0; i < values.size(); i++) {
971 if (i < values.size() - 1) {
980 static void collectQuotaStats(const std::string& device, int32_t userId,
981 int32_t appId, struct stats* stats, struct stats* extStats) {
982 if (device.empty()) return;
986 uid_t uid = multiuser_get_uid(userId, appId);
987 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
988 reinterpret_cast<char*>(&dq)) != 0) {
989 if (errno != ESRCH) {
990 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
994 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
996 stats->dataSize += dq.dqb_curspace;
999 int cacheGid = multiuser_get_cache_gid(userId, appId);
1000 if (cacheGid != -1) {
1001 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1002 reinterpret_cast<char*>(&dq)) != 0) {
1003 if (errno != ESRCH) {
1004 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1008 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1010 stats->cacheSize += dq.dqb_curspace;
1014 int extGid = multiuser_get_ext_gid(userId, appId);
1016 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1017 reinterpret_cast<char*>(&dq)) != 0) {
1018 if (errno != ESRCH) {
1019 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1023 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1025 extStats->dataSize += dq.dqb_curspace;
1029 int sharedGid = multiuser_get_shared_gid(userId, appId);
1030 if (sharedGid != -1) {
1031 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1032 reinterpret_cast<char*>(&dq)) != 0) {
1033 if (errno != ESRCH) {
1034 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1038 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1040 stats->codeSize += dq.dqb_curspace;
1045 static void collectManualStats(const std::string& path, struct stats* stats) {
1051 d = opendir(path.c_str());
1053 if (errno != ENOENT) {
1054 PLOG(WARNING) << "Failed to open " << path;
1059 while ((de = readdir(d))) {
1060 const char *name = de->d_name;
1063 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1064 size = s.st_blocks * 512;
1067 if (de->d_type == DT_DIR) {
1068 if (!strcmp(name, ".")) {
1069 // Don't recurse, but still count node size
1070 } else if (!strcmp(name, "..")) {
1071 // Don't recurse or count node size
1074 // Measure all children nodes
1076 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
1079 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1080 stats->cacheSize += size;
1084 // Legacy symlink isn't owned by app
1085 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1089 // Everything found inside is considered data
1090 stats->dataSize += size;
1095 static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1096 bool exclude_apps = false) {
1102 d = opendir(path.c_str());
1104 if (errno != ENOENT) {
1105 PLOG(WARNING) << "Failed to open " << path;
1110 while ((de = readdir(d))) {
1111 if (de->d_type == DT_DIR) {
1112 const char *name = de->d_name;
1113 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1116 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1118 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1121 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1128 static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1131 char *argv[] = { (char*) path.c_str(), nullptr };
1132 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1133 PLOG(ERROR) << "Failed to fts_open " << path;
1136 while ((p = fts_read(fts)) != NULL) {
1137 p->fts_number = p->fts_parent->fts_number;
1138 switch (p->fts_info) {
1140 if (p->fts_level == 4
1141 && !strcmp(p->fts_name, "cache")
1142 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1143 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1146 // Fall through to count the directory
1151 int64_t size = (p->fts_statp->st_blocks * 512);
1152 if (p->fts_number == 1) {
1153 stats->cacheSize += size;
1155 stats->dataSize += size;
1162 binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
1163 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1164 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1165 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
1166 ENFORCE_UID(AID_SYSTEM);
1167 CHECK_ARGUMENT_UUID(uuid);
1168 for (auto packageName : packageNames) {
1169 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1171 // NOTE: Locking is relaxed on this method, since it's limited to
1172 // read-only measurements without mutation.
1174 // When modifying this logic, always verify using tests:
1175 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1178 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1181 // Here's a summary of the common storage locations across the platform,
1182 // and how they're each tagged:
1184 // /data/app/com.example UID system
1185 // /data/app/com.example/oat UID system
1186 // /data/user/0/com.example UID u0_a10 GID u0_a10
1187 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1188 // /data/media/0/foo.txt UID u0_media_rw
1189 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1190 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1191 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1192 // /data/media/obb/com.example UID system
1195 struct stats extStats;
1196 memset(&stats, 0, sizeof(stats));
1197 memset(&extStats, 0, sizeof(extStats));
1199 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1201 auto device = findQuotaDeviceForUuid(uuid);
1202 if (device.empty()) {
1203 flags &= ~FLAG_USE_QUOTA;
1206 ATRACE_BEGIN("obb");
1207 for (auto packageName : packageNames) {
1208 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1209 calculate_tree_size(obbCodePath, &extStats.codeSize);
1213 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1214 ATRACE_BEGIN("code");
1215 for (auto codePath : codePaths) {
1216 calculate_tree_size(codePath, &stats.codeSize, -1,
1217 multiuser_get_shared_gid(userId, appId));
1221 ATRACE_BEGIN("quota");
1222 collectQuotaStats(device, userId, appId, &stats, &extStats);
1226 ATRACE_BEGIN("code");
1227 for (auto codePath : codePaths) {
1228 calculate_tree_size(codePath, &stats.codeSize);
1232 for (size_t i = 0; i < packageNames.size(); i++) {
1233 const char* pkgname = packageNames[i].c_str();
1235 ATRACE_BEGIN("data");
1236 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1237 collectManualStats(cePath, &stats);
1238 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1239 collectManualStats(dePath, &stats);
1242 ATRACE_BEGIN("profiles");
1243 auto userProfilePath = create_primary_current_profile_package_dir_path(userId, pkgname);
1244 calculate_tree_size(userProfilePath, &stats.dataSize);
1245 auto refProfilePath = create_primary_reference_profile_package_dir_path(pkgname);
1246 calculate_tree_size(refProfilePath, &stats.codeSize);
1249 ATRACE_BEGIN("external");
1250 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
1251 collectManualStats(extPath, &extStats);
1252 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
1253 calculate_tree_size(mediaPath, &extStats.dataSize);
1257 ATRACE_BEGIN("dalvik");
1258 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1259 if (sharedGid != -1) {
1260 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1263 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1264 multiuser_get_uid(userId, appId), -1);
1268 std::vector<int64_t> ret;
1269 ret.push_back(stats.codeSize);
1270 ret.push_back(stats.dataSize);
1271 ret.push_back(stats.cacheSize);
1272 ret.push_back(extStats.codeSize);
1273 ret.push_back(extStats.dataSize);
1274 ret.push_back(extStats.cacheSize);
1276 LOG(DEBUG) << "Final result " << toString(ret);
1278 *_aidl_return = ret;
1282 binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1283 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1284 std::vector<int64_t>* _aidl_return) {
1285 ENFORCE_UID(AID_SYSTEM);
1286 CHECK_ARGUMENT_UUID(uuid);
1287 // NOTE: Locking is relaxed on this method, since it's limited to
1288 // read-only measurements without mutation.
1290 // When modifying this logic, always verify using tests:
1291 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1294 LOG(INFO) << "Measuring user " << userId;
1298 struct stats extStats;
1299 memset(&stats, 0, sizeof(stats));
1300 memset(&extStats, 0, sizeof(extStats));
1302 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1304 auto device = findQuotaDeviceForUuid(uuid);
1305 if (device.empty()) {
1306 flags &= ~FLAG_USE_QUOTA;
1309 if (flags & FLAG_USE_QUOTA) {
1312 ATRACE_BEGIN("obb");
1313 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1314 reinterpret_cast<char*>(&dq)) != 0) {
1315 if (errno != ESRCH) {
1316 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1320 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1322 extStats.codeSize += dq.dqb_curspace;
1326 ATRACE_BEGIN("code");
1327 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1330 ATRACE_BEGIN("data");
1331 auto cePath = create_data_user_ce_path(uuid_, userId);
1332 collectManualStatsForUser(cePath, &stats, true);
1333 auto dePath = create_data_user_de_path(uuid_, userId);
1334 collectManualStatsForUser(dePath, &stats, true);
1337 ATRACE_BEGIN("profile");
1338 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1339 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1340 auto refProfilePath = create_primary_ref_profile_dir_path();
1341 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1344 ATRACE_BEGIN("external");
1345 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1346 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1347 reinterpret_cast<char*>(&dq)) != 0) {
1348 if (errno != ESRCH) {
1349 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1353 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1355 extStats.dataSize += dq.dqb_curspace;
1359 ATRACE_BEGIN("dalvik");
1360 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1362 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1366 ATRACE_BEGIN("quota");
1367 for (auto appId : appIds) {
1368 if (appId >= AID_APP_START) {
1369 collectQuotaStats(device, userId, appId, &stats, &extStats);
1371 // Sleep to make sure we don't lose logs
1378 ATRACE_BEGIN("obb");
1379 auto obbPath = create_data_path(uuid_) + "/media/obb";
1380 calculate_tree_size(obbPath, &extStats.codeSize);
1383 ATRACE_BEGIN("code");
1384 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1387 ATRACE_BEGIN("data");
1388 auto cePath = create_data_user_ce_path(uuid_, userId);
1389 collectManualStatsForUser(cePath, &stats);
1390 auto dePath = create_data_user_de_path(uuid_, userId);
1391 collectManualStatsForUser(dePath, &stats);
1394 ATRACE_BEGIN("profile");
1395 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1396 calculate_tree_size(userProfilePath, &stats.dataSize);
1397 auto refProfilePath = create_primary_ref_profile_dir_path();
1398 calculate_tree_size(refProfilePath, &stats.codeSize);
1401 ATRACE_BEGIN("external");
1402 auto dataMediaPath = create_data_media_path(uuid_, userId);
1403 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1405 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1406 << extStats.cacheSize;
1410 ATRACE_BEGIN("dalvik");
1411 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1412 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1416 std::vector<int64_t> ret;
1417 ret.push_back(stats.codeSize);
1418 ret.push_back(stats.dataSize);
1419 ret.push_back(stats.cacheSize);
1420 ret.push_back(extStats.codeSize);
1421 ret.push_back(extStats.dataSize);
1422 ret.push_back(extStats.cacheSize);
1424 LOG(DEBUG) << "Final result " << toString(ret);
1426 *_aidl_return = ret;
1430 binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1431 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1432 ENFORCE_UID(AID_SYSTEM);
1433 CHECK_ARGUMENT_UUID(uuid);
1434 // NOTE: Locking is relaxed on this method, since it's limited to
1435 // read-only measurements without mutation.
1437 // When modifying this logic, always verify using tests:
1438 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1441 LOG(INFO) << "Measuring external " << userId;
1444 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1446 int64_t totalSize = 0;
1447 int64_t audioSize = 0;
1448 int64_t videoSize = 0;
1449 int64_t imageSize = 0;
1451 auto device = findQuotaDeviceForUuid(uuid);
1452 if (device.empty()) {
1453 flags &= ~FLAG_USE_QUOTA;
1456 if (flags & FLAG_USE_QUOTA) {
1459 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1460 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1461 reinterpret_cast<char*>(&dq)) != 0) {
1462 if (errno != ESRCH) {
1463 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1467 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1469 totalSize = dq.dqb_curspace;
1472 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1473 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1474 reinterpret_cast<char*>(&dq)) == 0) {
1476 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1478 audioSize = dq.dqb_curspace;
1480 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1481 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1482 reinterpret_cast<char*>(&dq)) == 0) {
1484 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1486 videoSize = dq.dqb_curspace;
1488 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1489 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1490 reinterpret_cast<char*>(&dq)) == 0) {
1492 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1494 imageSize = dq.dqb_curspace;
1499 auto path = create_data_media_path(uuid_, userId);
1500 char *argv[] = { (char*) path.c_str(), nullptr };
1501 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1502 return error("Failed to fts_open " + path);
1504 while ((p = fts_read(fts)) != NULL) {
1506 int64_t size = (p->fts_statp->st_blocks * 512);
1507 switch (p->fts_info) {
1509 // Only categorize files not belonging to apps
1510 if (p->fts_parent->fts_number == 0) {
1511 ext = strrchr(p->fts_name, '.');
1512 if (ext != nullptr) {
1513 switch (MatchExtension(++ext)) {
1514 case AID_MEDIA_AUDIO: audioSize += size; break;
1515 case AID_MEDIA_VIDEO: videoSize += size; break;
1516 case AID_MEDIA_IMAGE: imageSize += size; break;
1520 // Fall through to always count against total
1522 // Ignore data belonging to specific apps
1523 p->fts_number = p->fts_parent->fts_number;
1524 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1537 std::vector<int64_t> ret;
1538 ret.push_back(totalSize);
1539 ret.push_back(audioSize);
1540 ret.push_back(videoSize);
1541 ret.push_back(imageSize);
1543 LOG(DEBUG) << "Final result " << toString(ret);
1545 *_aidl_return = ret;
1549 binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1550 int32_t userId, int32_t appId, int64_t cacheQuota) {
1551 ENFORCE_UID(AID_SYSTEM);
1552 CHECK_ARGUMENT_UUID(uuid);
1553 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
1555 int32_t uid = multiuser_get_uid(userId, appId);
1556 mCacheQuotas[uid] = cacheQuota;
1561 // Dumps the contents of a profile file, using pkgname's dex files for pretty
1562 // printing the result.
1563 binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1564 const std::string& codePaths, bool* _aidl_return) {
1565 ENFORCE_UID(AID_SYSTEM);
1566 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1567 std::lock_guard<std::recursive_mutex> lock(mLock);
1569 const char* pkgname = packageName.c_str();
1570 const char* code_paths = codePaths.c_str();
1572 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
1576 // TODO: Consider returning error codes.
1577 binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1578 bool* _aidl_return) {
1579 ENFORCE_UID(AID_SYSTEM);
1580 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1581 std::lock_guard<std::recursive_mutex> lock(mLock);
1583 *_aidl_return = analyze_primary_profiles(uid, packageName);
1587 binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1588 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1589 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1590 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1591 const std::unique_ptr<std::string>& sharedLibraries) {
1592 ENFORCE_UID(AID_SYSTEM);
1593 CHECK_ARGUMENT_UUID(uuid);
1594 if (packageName && *packageName != "*") {
1595 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1597 std::lock_guard<std::recursive_mutex> lock(mLock);
1599 const char* apk_path = apkPath.c_str();
1600 const char* pkgname = packageName ? packageName->c_str() : "*";
1601 const char* instruction_set = instructionSet.c_str();
1602 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1603 const char* compiler_filter = compilerFilter.c_str();
1604 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1605 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1607 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1608 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
1609 return res ? error(res, "Failed to dexopt") : ok();
1612 binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1613 ENFORCE_UID(AID_SYSTEM);
1614 std::lock_guard<std::recursive_mutex> lock(mLock);
1616 const char* instruction_set = instructionSet.c_str();
1618 char boot_marker_path[PKG_PATH_MAX];
1619 sprintf(boot_marker_path,
1620 "%s/%s/%s/.booting",
1621 android_data_dir.path,
1625 ALOGV("mark_boot_complete : %s", boot_marker_path);
1626 if (unlink(boot_marker_path) != 0) {
1627 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
1632 void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1633 struct stat* statbuf)
1635 while (path[basepos] != 0) {
1636 if (path[basepos] == '/') {
1638 if (lstat(path, statbuf) < 0) {
1639 ALOGV("Making directory: %s\n", path);
1640 if (mkdir(path, mode) == 0) {
1641 chown(path, uid, gid);
1643 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1646 path[basepos] = '/';
1653 binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1654 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1655 const std::string& nativeLibPath32, int32_t userId) {
1656 ENFORCE_UID(AID_SYSTEM);
1657 CHECK_ARGUMENT_UUID(uuid);
1658 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1659 std::lock_guard<std::recursive_mutex> lock(mLock);
1661 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1662 const char* pkgname = packageName.c_str();
1663 const char* asecLibDir = nativeLibPath32.c_str();
1664 struct stat s, libStat;
1665 binder::Status res = ok();
1667 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1668 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
1670 const char* pkgdir = _pkgdir.c_str();
1671 const char* libsymlink = _libsymlink.c_str();
1673 if (stat(pkgdir, &s) < 0) {
1674 return error("Failed to stat " + _pkgdir);
1677 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1678 return error("Failed to chown " + _pkgdir);
1681 if (chmod(pkgdir, 0700) < 0) {
1682 res = error("Failed to chmod " + _pkgdir);
1686 if (lstat(libsymlink, &libStat) < 0) {
1687 if (errno != ENOENT) {
1688 res = error("Failed to stat " + _libsymlink);
1692 if (S_ISDIR(libStat.st_mode)) {
1693 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1694 res = error("Failed to delete " + _libsymlink);
1697 } else if (S_ISLNK(libStat.st_mode)) {
1698 if (unlink(libsymlink) < 0) {
1699 res = error("Failed to unlink " + _libsymlink);
1705 if (symlink(asecLibDir, libsymlink) < 0) {
1706 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
1711 if (chmod(pkgdir, s.st_mode) < 0) {
1712 auto msg = "Failed to cleanup chmod " + _pkgdir;
1720 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1721 auto msg = "Failed to cleanup chown " + _pkgdir;
1732 static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1734 static const char *IDMAP_BIN = "/system/bin/idmap";
1735 static const size_t MAX_INT_LEN = 32;
1736 char idmap_str[MAX_INT_LEN];
1738 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1740 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1741 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1744 // Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1745 // eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1746 static int flatten_path(const char *prefix, const char *suffix,
1747 const char *overlay_path, char *idmap_path, size_t N)
1749 if (overlay_path == NULL || idmap_path == NULL) {
1752 const size_t len_overlay_path = strlen(overlay_path);
1753 // will access overlay_path + 1 further below; requires absolute path
1754 if (len_overlay_path < 2 || *overlay_path != '/') {
1757 const size_t len_idmap_root = strlen(prefix);
1758 const size_t len_suffix = strlen(suffix);
1759 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1760 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1761 // additions below would cause overflow
1764 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1767 memset(idmap_path, 0, N);
1768 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1769 char *ch = idmap_path + len_idmap_root;
1770 while (*ch != '\0') {
1779 binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1780 const std::string& overlayApkPath, int32_t uid) {
1781 ENFORCE_UID(AID_SYSTEM);
1782 std::lock_guard<std::recursive_mutex> lock(mLock);
1784 const char* target_apk = targetApkPath.c_str();
1785 const char* overlay_apk = overlayApkPath.c_str();
1786 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1789 char idmap_path[PATH_MAX];
1791 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1792 idmap_path, sizeof(idmap_path)) == -1) {
1793 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1798 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1800 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1803 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1804 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1807 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1808 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1815 /* child -- drop privileges before continuing */
1816 if (setgid(uid) != 0) {
1817 ALOGE("setgid(%d) failed during idmap\n", uid);
1820 if (setuid(uid) != 0) {
1821 ALOGE("setuid(%d) failed during idmap\n", uid);
1824 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1825 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1829 run_idmap(target_apk, overlay_apk, idmap_fd);
1830 exit(1); /* only if exec call to idmap failed */
1832 int status = wait_child(pid);
1834 ALOGE("idmap failed, status=0x%04x\n", status);
1842 if (idmap_fd >= 0) {
1849 binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
1850 const char* overlay_apk = overlayApkPath.c_str();
1851 char idmap_path[PATH_MAX];
1853 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1854 idmap_path, sizeof(idmap_path)) == -1) {
1855 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1858 if (unlink(idmap_path) < 0) {
1859 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
1865 binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1866 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1867 const std::string& seInfo) {
1868 ENFORCE_UID(AID_SYSTEM);
1869 CHECK_ARGUMENT_UUID(uuid);
1870 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1871 std::lock_guard<std::recursive_mutex> lock(mLock);
1873 binder::Status res = ok();
1875 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1876 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
1877 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1878 const char* pkgName = packageName.c_str();
1879 const char* seinfo = seInfo.c_str();
1881 uid_t uid = multiuser_get_uid(userId, appId);
1882 if (flags & FLAG_STORAGE_CE) {
1883 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
1884 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1885 res = error("restorecon failed for " + path);
1888 if (flags & FLAG_STORAGE_DE) {
1889 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
1890 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1891 res = error("restorecon failed for " + path);
1897 binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1898 const std::string& instructionSet) {
1899 ENFORCE_UID(AID_SYSTEM);
1900 std::lock_guard<std::recursive_mutex> lock(mLock);
1902 const char* oat_dir = oatDir.c_str();
1903 const char* instruction_set = instructionSet.c_str();
1904 char oat_instr_dir[PKG_PATH_MAX];
1906 if (validate_apk_path(oat_dir)) {
1907 return error("Invalid path " + oatDir);
1909 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1910 return error("Failed to prepare " + oatDir);
1912 if (selinux_android_restorecon(oat_dir, 0)) {
1913 return error("Failed to restorecon " + oatDir);
1915 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
1916 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1917 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
1922 binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1923 ENFORCE_UID(AID_SYSTEM);
1924 std::lock_guard<std::recursive_mutex> lock(mLock);
1926 if (validate_apk_path(packageDir.c_str())) {
1927 return error("Invalid path " + packageDir);
1929 if (delete_dir_contents_and_dir(packageDir) != 0) {
1930 return error("Failed to delete " + packageDir);
1935 binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1936 const std::string& fromBase, const std::string& toBase) {
1937 ENFORCE_UID(AID_SYSTEM);
1938 std::lock_guard<std::recursive_mutex> lock(mLock);
1940 const char* relative_path = relativePath.c_str();
1941 const char* from_base = fromBase.c_str();
1942 const char* to_base = toBase.c_str();
1943 char from_path[PKG_PATH_MAX];
1944 char to_path[PKG_PATH_MAX];
1945 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1946 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1948 if (validate_apk_path_subdirs(from_path)) {
1949 return error(StringPrintf("Invalid from path %s", from_path));
1952 if (validate_apk_path_subdirs(to_path)) {
1953 return error(StringPrintf("Invalid to path %s", to_path));
1956 if (link(from_path, to_path) < 0) {
1957 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
1963 binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1964 const std::string& instructionSet, const std::string& outputPath) {
1965 ENFORCE_UID(AID_SYSTEM);
1966 std::lock_guard<std::recursive_mutex> lock(mLock);
1968 const char* apk_path = apkPath.c_str();
1969 const char* instruction_set = instructionSet.c_str();
1970 const char* oat_dir = outputPath.c_str();
1972 bool success = move_ab(apk_path, instruction_set, oat_dir);
1973 return success ? ok() : error();
1976 binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1977 const std::string& instructionSet, const std::string& outputPath) {
1978 ENFORCE_UID(AID_SYSTEM);
1979 std::lock_guard<std::recursive_mutex> lock(mLock);
1981 const char* apk_path = apkPath.c_str();
1982 const char* instruction_set = instructionSet.c_str();
1983 const char* oat_dir = outputPath.c_str();
1985 bool res = delete_odex(apk_path, instruction_set, oat_dir);
1986 return res ? ok() : error();
1989 binder::Status InstalldNativeService::reconcileSecondaryDexFile(
1990 const std::string& dexPath, const std::string& packageName, int32_t uid,
1991 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
1992 int32_t storage_flag, bool* _aidl_return) {
1993 ENFORCE_UID(AID_SYSTEM);
1994 CHECK_ARGUMENT_UUID(volumeUuid);
1995 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1997 std::lock_guard<std::recursive_mutex> lock(mLock);
1998 bool result = android::installd::reconcile_secondary_dex_file(
1999 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2000 return result ? ok() : error();
2003 binder::Status InstalldNativeService::invalidateMounts() {
2004 ENFORCE_UID(AID_SYSTEM);
2005 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
2007 mQuotaDevices.clear();
2009 std::ifstream in("/proc/mounts");
2010 if (!in.is_open()) {
2011 return error("Failed to read mounts");
2016 std::string ignored;
2019 std::getline(in, source, ' ');
2020 std::getline(in, target, ' ');
2021 std::getline(in, ignored);
2023 if (source.compare(0, 11, "/dev/block/") == 0) {
2024 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2025 reinterpret_cast<char*>(&dq)) == 0) {
2026 LOG(DEBUG) << "Found " << source << " with quota";
2027 mQuotaDevices[target] = source;
2034 std::string InstalldNativeService::findQuotaDeviceForUuid(
2035 const std::unique_ptr<std::string>& uuid) {
2036 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
2037 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2038 return mQuotaDevices[path];
2041 binder::Status InstalldNativeService::isQuotaSupported(
2042 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2043 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2047 } // namespace installd
2048 } // namespace android