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