InstalldNativeService.cpp revision d712f0ccc120357e1267a04ac6de9dd732b27e76
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 return error(StringPrintf("Failed to unlink %s", dex_path)); 1104 } else { 1105 return ok(); 1106 } 1107} 1108 1109struct stats { 1110 int64_t codeSize; 1111 int64_t dataSize; 1112 int64_t cacheSize; 1113}; 1114 1115#if MEASURE_DEBUG 1116static std::string toString(std::vector<int64_t> values) { 1117 std::stringstream res; 1118 res << "["; 1119 for (size_t i = 0; i < values.size(); i++) { 1120 res << values[i]; 1121 if (i < values.size() - 1) { 1122 res << ","; 1123 } 1124 } 1125 res << "]"; 1126 return res.str(); 1127} 1128#endif 1129 1130static void collectQuotaStats(const std::string& device, int32_t userId, 1131 int32_t appId, struct stats* stats, struct stats* extStats) { 1132 if (device.empty()) return; 1133 1134 struct dqblk dq; 1135 1136 if (stats != nullptr) { 1137 uid_t uid = multiuser_get_uid(userId, appId); 1138 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid, 1139 reinterpret_cast<char*>(&dq)) != 0) { 1140 if (errno != ESRCH) { 1141 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid; 1142 } 1143 } else { 1144#if MEASURE_DEBUG 1145 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace; 1146#endif 1147 stats->dataSize += dq.dqb_curspace; 1148 } 1149 1150 int cacheGid = multiuser_get_cache_gid(userId, appId); 1151 if (cacheGid != -1) { 1152 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid, 1153 reinterpret_cast<char*>(&dq)) != 0) { 1154 if (errno != ESRCH) { 1155 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid; 1156 } 1157 } else { 1158#if MEASURE_DEBUG 1159 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace; 1160#endif 1161 stats->cacheSize += dq.dqb_curspace; 1162 } 1163 } 1164 1165 int sharedGid = multiuser_get_shared_gid(0, appId); 1166 if (sharedGid != -1) { 1167 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid, 1168 reinterpret_cast<char*>(&dq)) != 0) { 1169 if (errno != ESRCH) { 1170 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid; 1171 } 1172 } else { 1173#if MEASURE_DEBUG 1174 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace; 1175#endif 1176 stats->codeSize += dq.dqb_curspace; 1177 } 1178 } 1179 } 1180 1181 if (extStats != nullptr) { 1182 int extGid = multiuser_get_ext_gid(userId, appId); 1183 if (extGid != -1) { 1184 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid, 1185 reinterpret_cast<char*>(&dq)) != 0) { 1186 if (errno != ESRCH) { 1187 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid; 1188 } 1189 } else { 1190#if MEASURE_DEBUG 1191 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace; 1192#endif 1193 extStats->dataSize += dq.dqb_curspace; 1194 } 1195 } 1196 1197 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId); 1198 if (extCacheGid != -1) { 1199 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid, 1200 reinterpret_cast<char*>(&dq)) != 0) { 1201 if (errno != ESRCH) { 1202 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid; 1203 } 1204 } else { 1205#if MEASURE_DEBUG 1206 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace; 1207#endif 1208 extStats->dataSize += dq.dqb_curspace; 1209 extStats->cacheSize += dq.dqb_curspace; 1210 } 1211 } 1212 } 1213} 1214 1215static void collectManualStats(const std::string& path, struct stats* stats) { 1216 DIR *d; 1217 int dfd; 1218 struct dirent *de; 1219 struct stat s; 1220 1221 d = opendir(path.c_str()); 1222 if (d == nullptr) { 1223 if (errno != ENOENT) { 1224 PLOG(WARNING) << "Failed to open " << path; 1225 } 1226 return; 1227 } 1228 dfd = dirfd(d); 1229 while ((de = readdir(d))) { 1230 const char *name = de->d_name; 1231 1232 int64_t size = 0; 1233 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) { 1234 size = s.st_blocks * 512; 1235 } 1236 1237 if (de->d_type == DT_DIR) { 1238 if (!strcmp(name, ".")) { 1239 // Don't recurse, but still count node size 1240 } else if (!strcmp(name, "..")) { 1241 // Don't recurse or count node size 1242 continue; 1243 } else { 1244 // Measure all children nodes 1245 size = 0; 1246 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size); 1247 } 1248 1249 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) { 1250 stats->cacheSize += size; 1251 } 1252 } 1253 1254 // Legacy symlink isn't owned by app 1255 if (de->d_type == DT_LNK && !strcmp(name, "lib")) { 1256 continue; 1257 } 1258 1259 // Everything found inside is considered data 1260 stats->dataSize += size; 1261 } 1262 closedir(d); 1263} 1264 1265static void collectManualStatsForUser(const std::string& path, struct stats* stats, 1266 bool exclude_apps = false) { 1267 DIR *d; 1268 int dfd; 1269 struct dirent *de; 1270 struct stat s; 1271 1272 d = opendir(path.c_str()); 1273 if (d == nullptr) { 1274 if (errno != ENOENT) { 1275 PLOG(WARNING) << "Failed to open " << path; 1276 } 1277 return; 1278 } 1279 dfd = dirfd(d); 1280 while ((de = readdir(d))) { 1281 if (de->d_type == DT_DIR) { 1282 const char *name = de->d_name; 1283 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) { 1284 continue; 1285 } 1286 int32_t user_uid = multiuser_get_app_id(s.st_uid); 1287 if (!strcmp(name, ".") || !strcmp(name, "..")) { 1288 continue; 1289 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) { 1290 continue; 1291 } else { 1292 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats); 1293 } 1294 } 1295 } 1296 closedir(d); 1297} 1298 1299static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) { 1300 FTS *fts; 1301 FTSENT *p; 1302 char *argv[] = { (char*) path.c_str(), nullptr }; 1303 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) { 1304 PLOG(ERROR) << "Failed to fts_open " << path; 1305 return; 1306 } 1307 while ((p = fts_read(fts)) != NULL) { 1308 p->fts_number = p->fts_parent->fts_number; 1309 switch (p->fts_info) { 1310 case FTS_D: 1311 if (p->fts_level == 4 1312 && !strcmp(p->fts_name, "cache") 1313 && !strcmp(p->fts_parent->fts_parent->fts_name, "data") 1314 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) { 1315 p->fts_number = 1; 1316 } 1317 // Fall through to count the directory 1318 case FTS_DEFAULT: 1319 case FTS_F: 1320 case FTS_SL: 1321 case FTS_SLNONE: 1322 int64_t size = (p->fts_statp->st_blocks * 512); 1323 if (p->fts_number == 1) { 1324 stats->cacheSize += size; 1325 } 1326 stats->dataSize += size; 1327 break; 1328 } 1329 } 1330 fts_close(fts); 1331} 1332 1333binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid, 1334 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags, 1335 int32_t appId, const std::vector<int64_t>& ceDataInodes, 1336 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) { 1337 ENFORCE_UID(AID_SYSTEM); 1338 CHECK_ARGUMENT_UUID(uuid); 1339 for (auto packageName : packageNames) { 1340 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1341 } 1342 // NOTE: Locking is relaxed on this method, since it's limited to 1343 // read-only measurements without mutation. 1344 1345 // When modifying this logic, always verify using tests: 1346 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize 1347 1348#if MEASURE_DEBUG 1349 LOG(INFO) << "Measuring user " << userId << " app " << appId; 1350#endif 1351 1352 // Here's a summary of the common storage locations across the platform, 1353 // and how they're each tagged: 1354 // 1355 // /data/app/com.example UID system 1356 // /data/app/com.example/oat UID system 1357 // /data/user/0/com.example UID u0_a10 GID u0_a10 1358 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache 1359 // /data/media/0/foo.txt UID u0_media_rw 1360 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image 1361 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext 1362 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache 1363 // /data/media/obb/com.example UID system 1364 1365 struct stats stats; 1366 struct stats extStats; 1367 memset(&stats, 0, sizeof(stats)); 1368 memset(&extStats, 0, sizeof(extStats)); 1369 1370 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1371 1372 auto device = findQuotaDeviceForUuid(uuid); 1373 if (device.empty()) { 1374 flags &= ~FLAG_USE_QUOTA; 1375 } 1376 1377 ATRACE_BEGIN("obb"); 1378 for (auto packageName : packageNames) { 1379 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str()); 1380 calculate_tree_size(obbCodePath, &extStats.codeSize); 1381 } 1382 ATRACE_END(); 1383 1384 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) { 1385 ATRACE_BEGIN("code"); 1386 for (auto codePath : codePaths) { 1387 calculate_tree_size(codePath, &stats.codeSize, -1, 1388 multiuser_get_shared_gid(0, appId)); 1389 } 1390 ATRACE_END(); 1391 1392 ATRACE_BEGIN("quota"); 1393 collectQuotaStats(device, userId, appId, &stats, &extStats); 1394 ATRACE_END(); 1395 } else { 1396 ATRACE_BEGIN("code"); 1397 for (auto codePath : codePaths) { 1398 calculate_tree_size(codePath, &stats.codeSize); 1399 } 1400 ATRACE_END(); 1401 1402 for (size_t i = 0; i < packageNames.size(); i++) { 1403 const char* pkgname = packageNames[i].c_str(); 1404 1405 ATRACE_BEGIN("data"); 1406 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]); 1407 collectManualStats(cePath, &stats); 1408 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname); 1409 collectManualStats(dePath, &stats); 1410 ATRACE_END(); 1411 1412 if (!uuid) { 1413 ATRACE_BEGIN("profiles"); 1414 calculate_tree_size( 1415 create_primary_current_profile_package_dir_path(userId, pkgname), 1416 &stats.dataSize); 1417 calculate_tree_size( 1418 create_primary_reference_profile_package_dir_path(pkgname), 1419 &stats.codeSize); 1420 ATRACE_END(); 1421 } 1422 1423 ATRACE_BEGIN("external"); 1424 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname); 1425 collectManualStats(extPath, &extStats); 1426 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname); 1427 calculate_tree_size(mediaPath, &extStats.dataSize); 1428 ATRACE_END(); 1429 } 1430 1431 if (!uuid) { 1432 ATRACE_BEGIN("dalvik"); 1433 int32_t sharedGid = multiuser_get_shared_gid(0, appId); 1434 if (sharedGid != -1) { 1435 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize, 1436 sharedGid, -1); 1437 } 1438 ATRACE_END(); 1439 } 1440 } 1441 1442 std::vector<int64_t> ret; 1443 ret.push_back(stats.codeSize); 1444 ret.push_back(stats.dataSize); 1445 ret.push_back(stats.cacheSize); 1446 ret.push_back(extStats.codeSize); 1447 ret.push_back(extStats.dataSize); 1448 ret.push_back(extStats.cacheSize); 1449#if MEASURE_DEBUG 1450 LOG(DEBUG) << "Final result " << toString(ret); 1451#endif 1452 *_aidl_return = ret; 1453 return ok(); 1454} 1455 1456binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid, 1457 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds, 1458 std::vector<int64_t>* _aidl_return) { 1459 ENFORCE_UID(AID_SYSTEM); 1460 CHECK_ARGUMENT_UUID(uuid); 1461 // NOTE: Locking is relaxed on this method, since it's limited to 1462 // read-only measurements without mutation. 1463 1464 // When modifying this logic, always verify using tests: 1465 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize 1466 1467#if MEASURE_DEBUG 1468 LOG(INFO) << "Measuring user " << userId; 1469#endif 1470 1471 struct stats stats; 1472 struct stats extStats; 1473 memset(&stats, 0, sizeof(stats)); 1474 memset(&extStats, 0, sizeof(extStats)); 1475 1476 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1477 1478 auto device = findQuotaDeviceForUuid(uuid); 1479 if (device.empty()) { 1480 flags &= ~FLAG_USE_QUOTA; 1481 } 1482 1483 if (flags & FLAG_USE_QUOTA) { 1484 struct dqblk dq; 1485 1486 ATRACE_BEGIN("obb"); 1487 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB, 1488 reinterpret_cast<char*>(&dq)) != 0) { 1489 if (errno != ESRCH) { 1490 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB; 1491 } 1492 } else { 1493#if MEASURE_DEBUG 1494 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace; 1495#endif 1496 extStats.codeSize += dq.dqb_curspace; 1497 } 1498 ATRACE_END(); 1499 1500 ATRACE_BEGIN("code"); 1501 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true); 1502 ATRACE_END(); 1503 1504 ATRACE_BEGIN("data"); 1505 auto cePath = create_data_user_ce_path(uuid_, userId); 1506 collectManualStatsForUser(cePath, &stats, true); 1507 auto dePath = create_data_user_de_path(uuid_, userId); 1508 collectManualStatsForUser(dePath, &stats, true); 1509 ATRACE_END(); 1510 1511 if (!uuid) { 1512 ATRACE_BEGIN("profile"); 1513 auto userProfilePath = create_primary_cur_profile_dir_path(userId); 1514 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true); 1515 auto refProfilePath = create_primary_ref_profile_dir_path(); 1516 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true); 1517 ATRACE_END(); 1518 } 1519 1520 ATRACE_BEGIN("external"); 1521 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW); 1522 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid, 1523 reinterpret_cast<char*>(&dq)) != 0) { 1524 if (errno != ESRCH) { 1525 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid; 1526 } 1527 } else { 1528#if MEASURE_DEBUG 1529 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace; 1530#endif 1531 extStats.dataSize += dq.dqb_curspace; 1532 } 1533 ATRACE_END(); 1534 1535 if (!uuid) { 1536 ATRACE_BEGIN("dalvik"); 1537 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize, 1538 -1, -1, true); 1539 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize, 1540 -1, -1, true); 1541 ATRACE_END(); 1542 } 1543 1544 ATRACE_BEGIN("quota"); 1545 int64_t dataSize = extStats.dataSize; 1546 for (auto appId : appIds) { 1547 if (appId >= AID_APP_START) { 1548 collectQuotaStats(device, userId, appId, &stats, &extStats); 1549 1550#if MEASURE_DEBUG 1551 // Sleep to make sure we don't lose logs 1552 usleep(1); 1553#endif 1554 } 1555 } 1556 extStats.dataSize = dataSize; 1557 ATRACE_END(); 1558 } else { 1559 ATRACE_BEGIN("obb"); 1560 auto obbPath = create_data_path(uuid_) + "/media/obb"; 1561 calculate_tree_size(obbPath, &extStats.codeSize); 1562 ATRACE_END(); 1563 1564 ATRACE_BEGIN("code"); 1565 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize); 1566 ATRACE_END(); 1567 1568 ATRACE_BEGIN("data"); 1569 auto cePath = create_data_user_ce_path(uuid_, userId); 1570 collectManualStatsForUser(cePath, &stats); 1571 auto dePath = create_data_user_de_path(uuid_, userId); 1572 collectManualStatsForUser(dePath, &stats); 1573 ATRACE_END(); 1574 1575 if (!uuid) { 1576 ATRACE_BEGIN("profile"); 1577 auto userProfilePath = create_primary_cur_profile_dir_path(userId); 1578 calculate_tree_size(userProfilePath, &stats.dataSize); 1579 auto refProfilePath = create_primary_ref_profile_dir_path(); 1580 calculate_tree_size(refProfilePath, &stats.codeSize); 1581 ATRACE_END(); 1582 } 1583 1584 ATRACE_BEGIN("external"); 1585 auto dataMediaPath = create_data_media_path(uuid_, userId); 1586 collectManualExternalStatsForUser(dataMediaPath, &extStats); 1587#if MEASURE_DEBUG 1588 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache " 1589 << extStats.cacheSize; 1590#endif 1591 ATRACE_END(); 1592 1593 if (!uuid) { 1594 ATRACE_BEGIN("dalvik"); 1595 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize); 1596 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize); 1597 ATRACE_END(); 1598 } 1599 } 1600 1601 std::vector<int64_t> ret; 1602 ret.push_back(stats.codeSize); 1603 ret.push_back(stats.dataSize); 1604 ret.push_back(stats.cacheSize); 1605 ret.push_back(extStats.codeSize); 1606 ret.push_back(extStats.dataSize); 1607 ret.push_back(extStats.cacheSize); 1608#if MEASURE_DEBUG 1609 LOG(DEBUG) << "Final result " << toString(ret); 1610#endif 1611 *_aidl_return = ret; 1612 return ok(); 1613} 1614 1615binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid, 1616 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds, 1617 std::vector<int64_t>* _aidl_return) { 1618 ENFORCE_UID(AID_SYSTEM); 1619 CHECK_ARGUMENT_UUID(uuid); 1620 // NOTE: Locking is relaxed on this method, since it's limited to 1621 // read-only measurements without mutation. 1622 1623 // When modifying this logic, always verify using tests: 1624 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize 1625 1626#if MEASURE_DEBUG 1627 LOG(INFO) << "Measuring external " << userId; 1628#endif 1629 1630 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1631 1632 int64_t totalSize = 0; 1633 int64_t audioSize = 0; 1634 int64_t videoSize = 0; 1635 int64_t imageSize = 0; 1636 int64_t appSize = 0; 1637 1638 auto device = findQuotaDeviceForUuid(uuid); 1639 if (device.empty()) { 1640 flags &= ~FLAG_USE_QUOTA; 1641 } 1642 1643 if (flags & FLAG_USE_QUOTA) { 1644 struct dqblk dq; 1645 1646 ATRACE_BEGIN("quota"); 1647 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW); 1648 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid, 1649 reinterpret_cast<char*>(&dq)) != 0) { 1650 if (errno != ESRCH) { 1651 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid; 1652 } 1653 } else { 1654#if MEASURE_DEBUG 1655 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace; 1656#endif 1657 totalSize = dq.dqb_curspace; 1658 } 1659 1660 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO); 1661 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid, 1662 reinterpret_cast<char*>(&dq)) == 0) { 1663#if MEASURE_DEBUG 1664 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace; 1665#endif 1666 audioSize = dq.dqb_curspace; 1667 } 1668 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO); 1669 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid, 1670 reinterpret_cast<char*>(&dq)) == 0) { 1671#if MEASURE_DEBUG 1672 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace; 1673#endif 1674 videoSize = dq.dqb_curspace; 1675 } 1676 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE); 1677 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid, 1678 reinterpret_cast<char*>(&dq)) == 0) { 1679#if MEASURE_DEBUG 1680 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace; 1681#endif 1682 imageSize = dq.dqb_curspace; 1683 } 1684 ATRACE_END(); 1685 1686 ATRACE_BEGIN("apps"); 1687 struct stats extStats; 1688 memset(&extStats, 0, sizeof(extStats)); 1689 for (auto appId : appIds) { 1690 if (appId >= AID_APP_START) { 1691 collectQuotaStats(device, userId, appId, nullptr, &extStats); 1692 } 1693 } 1694 appSize = extStats.dataSize + extStats.cacheSize; 1695 ATRACE_END(); 1696 } else { 1697 ATRACE_BEGIN("manual"); 1698 FTS *fts; 1699 FTSENT *p; 1700 auto path = create_data_media_path(uuid_, userId); 1701 char *argv[] = { (char*) path.c_str(), nullptr }; 1702 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) { 1703 return error("Failed to fts_open " + path); 1704 } 1705 while ((p = fts_read(fts)) != NULL) { 1706 char* ext; 1707 int64_t size = (p->fts_statp->st_blocks * 512); 1708 switch (p->fts_info) { 1709 case FTS_F: 1710 // Only categorize files not belonging to apps 1711 if (p->fts_parent->fts_number == 0) { 1712 ext = strrchr(p->fts_name, '.'); 1713 if (ext != nullptr) { 1714 switch (MatchExtension(++ext)) { 1715 case AID_MEDIA_AUDIO: audioSize += size; break; 1716 case AID_MEDIA_VIDEO: videoSize += size; break; 1717 case AID_MEDIA_IMAGE: imageSize += size; break; 1718 } 1719 } 1720 } 1721 // Fall through to always count against total 1722 case FTS_D: 1723 // Ignore data belonging to specific apps 1724 p->fts_number = p->fts_parent->fts_number; 1725 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) { 1726 p->fts_number = 1; 1727 } 1728 case FTS_DEFAULT: 1729 case FTS_SL: 1730 case FTS_SLNONE: 1731 if (p->fts_parent->fts_number == 1) { 1732 appSize += size; 1733 } 1734 totalSize += size; 1735 break; 1736 } 1737 } 1738 fts_close(fts); 1739 ATRACE_END(); 1740 } 1741 1742 std::vector<int64_t> ret; 1743 ret.push_back(totalSize); 1744 ret.push_back(audioSize); 1745 ret.push_back(videoSize); 1746 ret.push_back(imageSize); 1747 ret.push_back(appSize); 1748#if MEASURE_DEBUG 1749 LOG(DEBUG) << "Final result " << toString(ret); 1750#endif 1751 *_aidl_return = ret; 1752 return ok(); 1753} 1754 1755binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid, 1756 int32_t userId, int32_t appId, int64_t cacheQuota) { 1757 ENFORCE_UID(AID_SYSTEM); 1758 CHECK_ARGUMENT_UUID(uuid); 1759 std::lock_guard<std::recursive_mutex> lock(mQuotasLock); 1760 1761 int32_t uid = multiuser_get_uid(userId, appId); 1762 mCacheQuotas[uid] = cacheQuota; 1763 1764 return ok(); 1765} 1766 1767// Dumps the contents of a profile file, using pkgname's dex files for pretty 1768// printing the result. 1769binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName, 1770 const std::string& codePaths, bool* _aidl_return) { 1771 ENFORCE_UID(AID_SYSTEM); 1772 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1773 std::lock_guard<std::recursive_mutex> lock(mLock); 1774 1775 const char* pkgname = packageName.c_str(); 1776 const char* code_paths = codePaths.c_str(); 1777 1778 *_aidl_return = dump_profiles(uid, pkgname, code_paths); 1779 return ok(); 1780} 1781 1782// TODO: Consider returning error codes. 1783binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName, 1784 bool* _aidl_return) { 1785 ENFORCE_UID(AID_SYSTEM); 1786 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1787 std::lock_guard<std::recursive_mutex> lock(mLock); 1788 1789 *_aidl_return = analyze_primary_profiles(uid, packageName); 1790 return ok(); 1791} 1792 1793binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid, 1794 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet, 1795 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags, 1796 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid, 1797 const std::unique_ptr<std::string>& sharedLibraries, 1798 const std::unique_ptr<std::string>& seInfo) { 1799 ENFORCE_UID(AID_SYSTEM); 1800 CHECK_ARGUMENT_UUID(uuid); 1801 if (packageName && *packageName != "*") { 1802 CHECK_ARGUMENT_PACKAGE_NAME(*packageName); 1803 } 1804 std::lock_guard<std::recursive_mutex> lock(mLock); 1805 1806 const char* apk_path = apkPath.c_str(); 1807 const char* pkgname = packageName ? packageName->c_str() : "*"; 1808 const char* instruction_set = instructionSet.c_str(); 1809 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr; 1810 const char* compiler_filter = compilerFilter.c_str(); 1811 const char* volume_uuid = uuid ? uuid->c_str() : nullptr; 1812 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr; 1813 const char* se_info = seInfo ? seInfo->c_str() : nullptr; 1814 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded, 1815 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries, se_info); 1816 return res ? error(res, "Failed to dexopt") : ok(); 1817} 1818 1819binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) { 1820 ENFORCE_UID(AID_SYSTEM); 1821 std::lock_guard<std::recursive_mutex> lock(mLock); 1822 1823 const char* instruction_set = instructionSet.c_str(); 1824 1825 char boot_marker_path[PKG_PATH_MAX]; 1826 sprintf(boot_marker_path, 1827 "%s/%s/%s/.booting", 1828 android_data_dir.path, 1829 DALVIK_CACHE, 1830 instruction_set); 1831 1832 ALOGV("mark_boot_complete : %s", boot_marker_path); 1833 if (unlink(boot_marker_path) != 0) { 1834 return error(StringPrintf("Failed to unlink %s", boot_marker_path)); 1835 } 1836 return ok(); 1837} 1838 1839void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid, 1840 struct stat* statbuf) 1841{ 1842 while (path[basepos] != 0) { 1843 if (path[basepos] == '/') { 1844 path[basepos] = 0; 1845 if (lstat(path, statbuf) < 0) { 1846 ALOGV("Making directory: %s\n", path); 1847 if (mkdir(path, mode) == 0) { 1848 chown(path, uid, gid); 1849 } else { 1850 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno)); 1851 } 1852 } 1853 path[basepos] = '/'; 1854 basepos++; 1855 } 1856 basepos++; 1857 } 1858} 1859 1860binder::Status InstalldNativeService::linkNativeLibraryDirectory( 1861 const std::unique_ptr<std::string>& uuid, const std::string& packageName, 1862 const std::string& nativeLibPath32, int32_t userId) { 1863 ENFORCE_UID(AID_SYSTEM); 1864 CHECK_ARGUMENT_UUID(uuid); 1865 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 1866 std::lock_guard<std::recursive_mutex> lock(mLock); 1867 1868 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 1869 const char* pkgname = packageName.c_str(); 1870 const char* asecLibDir = nativeLibPath32.c_str(); 1871 struct stat s, libStat; 1872 binder::Status res = ok(); 1873 1874 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname); 1875 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX; 1876 1877 const char* pkgdir = _pkgdir.c_str(); 1878 const char* libsymlink = _libsymlink.c_str(); 1879 1880 if (stat(pkgdir, &s) < 0) { 1881 return error("Failed to stat " + _pkgdir); 1882 } 1883 1884 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) { 1885 return error("Failed to chown " + _pkgdir); 1886 } 1887 1888 if (chmod(pkgdir, 0700) < 0) { 1889 res = error("Failed to chmod " + _pkgdir); 1890 goto out; 1891 } 1892 1893 if (lstat(libsymlink, &libStat) < 0) { 1894 if (errno != ENOENT) { 1895 res = error("Failed to stat " + _libsymlink); 1896 goto out; 1897 } 1898 } else { 1899 if (S_ISDIR(libStat.st_mode)) { 1900 if (delete_dir_contents(libsymlink, 1, NULL) < 0) { 1901 res = error("Failed to delete " + _libsymlink); 1902 goto out; 1903 } 1904 } else if (S_ISLNK(libStat.st_mode)) { 1905 if (unlink(libsymlink) < 0) { 1906 res = error("Failed to unlink " + _libsymlink); 1907 goto out; 1908 } 1909 } 1910 } 1911 1912 if (symlink(asecLibDir, libsymlink) < 0) { 1913 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32); 1914 goto out; 1915 } 1916 1917out: 1918 if (chmod(pkgdir, s.st_mode) < 0) { 1919 auto msg = "Failed to cleanup chmod " + _pkgdir; 1920 if (res.isOk()) { 1921 res = error(msg); 1922 } else { 1923 PLOG(ERROR) << msg; 1924 } 1925 } 1926 1927 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) { 1928 auto msg = "Failed to cleanup chown " + _pkgdir; 1929 if (res.isOk()) { 1930 res = error(msg); 1931 } else { 1932 PLOG(ERROR) << msg; 1933 } 1934 } 1935 1936 return res; 1937} 1938 1939static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd) 1940{ 1941 static const char *IDMAP_BIN = "/system/bin/idmap"; 1942 static const size_t MAX_INT_LEN = 32; 1943 char idmap_str[MAX_INT_LEN]; 1944 1945 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd); 1946 1947 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL); 1948 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno)); 1949} 1950 1951// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix) 1952// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap 1953static int flatten_path(const char *prefix, const char *suffix, 1954 const char *overlay_path, char *idmap_path, size_t N) 1955{ 1956 if (overlay_path == NULL || idmap_path == NULL) { 1957 return -1; 1958 } 1959 const size_t len_overlay_path = strlen(overlay_path); 1960 // will access overlay_path + 1 further below; requires absolute path 1961 if (len_overlay_path < 2 || *overlay_path != '/') { 1962 return -1; 1963 } 1964 const size_t len_idmap_root = strlen(prefix); 1965 const size_t len_suffix = strlen(suffix); 1966 if (SIZE_MAX - len_idmap_root < len_overlay_path || 1967 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) { 1968 // additions below would cause overflow 1969 return -1; 1970 } 1971 if (N < len_idmap_root + len_overlay_path + len_suffix) { 1972 return -1; 1973 } 1974 memset(idmap_path, 0, N); 1975 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix); 1976 char *ch = idmap_path + len_idmap_root; 1977 while (*ch != '\0') { 1978 if (*ch == '/') { 1979 *ch = '@'; 1980 } 1981 ++ch; 1982 } 1983 return 0; 1984} 1985 1986binder::Status InstalldNativeService::idmap(const std::string& targetApkPath, 1987 const std::string& overlayApkPath, int32_t uid) { 1988 ENFORCE_UID(AID_SYSTEM); 1989 std::lock_guard<std::recursive_mutex> lock(mLock); 1990 1991 const char* target_apk = targetApkPath.c_str(); 1992 const char* overlay_apk = overlayApkPath.c_str(); 1993 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid); 1994 1995 int idmap_fd = -1; 1996 char idmap_path[PATH_MAX]; 1997 struct stat target_apk_stat, overlay_apk_stat, idmap_stat; 1998 bool outdated = false; 1999 2000 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk, 2001 idmap_path, sizeof(idmap_path)) == -1) { 2002 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk); 2003 goto fail; 2004 } 2005 2006 if (stat(idmap_path, &idmap_stat) < 0 || 2007 stat(target_apk, &target_apk_stat) < 0 || 2008 stat(overlay_apk, &overlay_apk_stat) < 0) { 2009 outdated = true; 2010 } else if (idmap_stat.st_mtime < target_apk_stat.st_mtime || 2011 idmap_stat.st_mtime < overlay_apk_stat.st_mtime) { 2012 outdated = true; 2013 } 2014 2015 if (outdated) { 2016 unlink(idmap_path); 2017 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644); 2018 } else { 2019 idmap_fd = open(idmap_path, O_RDWR); 2020 } 2021 2022 if (idmap_fd < 0) { 2023 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno)); 2024 goto fail; 2025 } 2026 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) { 2027 ALOGE("idmap cannot chown '%s'\n", idmap_path); 2028 goto fail; 2029 } 2030 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) { 2031 ALOGE("idmap cannot chmod '%s'\n", idmap_path); 2032 goto fail; 2033 } 2034 2035 if (!outdated) { 2036 close(idmap_fd); 2037 return ok(); 2038 } 2039 2040 pid_t pid; 2041 pid = fork(); 2042 if (pid == 0) { 2043 /* child -- drop privileges before continuing */ 2044 if (setgid(uid) != 0) { 2045 ALOGE("setgid(%d) failed during idmap\n", uid); 2046 exit(1); 2047 } 2048 if (setuid(uid) != 0) { 2049 ALOGE("setuid(%d) failed during idmap\n", uid); 2050 exit(1); 2051 } 2052 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) { 2053 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno)); 2054 exit(1); 2055 } 2056 2057 run_idmap(target_apk, overlay_apk, idmap_fd); 2058 exit(1); /* only if exec call to idmap failed */ 2059 } else { 2060 int status = wait_child(pid); 2061 if (status != 0) { 2062 ALOGE("idmap failed, status=0x%04x\n", status); 2063 goto fail; 2064 } 2065 } 2066 2067 close(idmap_fd); 2068 return ok(); 2069fail: 2070 if (idmap_fd >= 0) { 2071 close(idmap_fd); 2072 unlink(idmap_path); 2073 } 2074 return error(); 2075} 2076 2077binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) { 2078 const char* overlay_apk = overlayApkPath.c_str(); 2079 char idmap_path[PATH_MAX]; 2080 2081 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk, 2082 idmap_path, sizeof(idmap_path)) == -1) { 2083 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk); 2084 return error(); 2085 } 2086 if (unlink(idmap_path) < 0) { 2087 ALOGE("couldn't unlink idmap file %s\n", idmap_path); 2088 return error(); 2089 } 2090 return ok(); 2091} 2092 2093binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid, 2094 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId, 2095 const std::string& seInfo) { 2096 ENFORCE_UID(AID_SYSTEM); 2097 CHECK_ARGUMENT_UUID(uuid); 2098 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 2099 std::lock_guard<std::recursive_mutex> lock(mLock); 2100 2101 binder::Status res = ok(); 2102 2103 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here. 2104 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE; 2105 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 2106 const char* pkgName = packageName.c_str(); 2107 const char* seinfo = seInfo.c_str(); 2108 2109 uid_t uid = multiuser_get_uid(userId, appId); 2110 if (flags & FLAG_STORAGE_CE) { 2111 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName); 2112 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) { 2113 res = error("restorecon failed for " + path); 2114 } 2115 } 2116 if (flags & FLAG_STORAGE_DE) { 2117 auto path = create_data_user_de_package_path(uuid_, userId, pkgName); 2118 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) { 2119 res = error("restorecon failed for " + path); 2120 } 2121 } 2122 return res; 2123} 2124 2125binder::Status InstalldNativeService::createOatDir(const std::string& oatDir, 2126 const std::string& instructionSet) { 2127 ENFORCE_UID(AID_SYSTEM); 2128 std::lock_guard<std::recursive_mutex> lock(mLock); 2129 2130 const char* oat_dir = oatDir.c_str(); 2131 const char* instruction_set = instructionSet.c_str(); 2132 char oat_instr_dir[PKG_PATH_MAX]; 2133 2134 if (validate_apk_path(oat_dir)) { 2135 return error("Invalid path " + oatDir); 2136 } 2137 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) { 2138 return error("Failed to prepare " + oatDir); 2139 } 2140 if (selinux_android_restorecon(oat_dir, 0)) { 2141 return error("Failed to restorecon " + oatDir); 2142 } 2143 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set); 2144 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) { 2145 return error(StringPrintf("Failed to prepare %s", oat_instr_dir)); 2146 } 2147 return ok(); 2148} 2149 2150binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) { 2151 ENFORCE_UID(AID_SYSTEM); 2152 std::lock_guard<std::recursive_mutex> lock(mLock); 2153 2154 if (validate_apk_path(packageDir.c_str())) { 2155 return error("Invalid path " + packageDir); 2156 } 2157 if (delete_dir_contents_and_dir(packageDir) != 0) { 2158 return error("Failed to delete " + packageDir); 2159 } 2160 return ok(); 2161} 2162 2163binder::Status InstalldNativeService::linkFile(const std::string& relativePath, 2164 const std::string& fromBase, const std::string& toBase) { 2165 ENFORCE_UID(AID_SYSTEM); 2166 std::lock_guard<std::recursive_mutex> lock(mLock); 2167 2168 const char* relative_path = relativePath.c_str(); 2169 const char* from_base = fromBase.c_str(); 2170 const char* to_base = toBase.c_str(); 2171 char from_path[PKG_PATH_MAX]; 2172 char to_path[PKG_PATH_MAX]; 2173 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path); 2174 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path); 2175 2176 if (validate_apk_path_subdirs(from_path)) { 2177 return error(StringPrintf("Invalid from path %s", from_path)); 2178 } 2179 2180 if (validate_apk_path_subdirs(to_path)) { 2181 return error(StringPrintf("Invalid to path %s", to_path)); 2182 } 2183 2184 if (link(from_path, to_path) < 0) { 2185 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path)); 2186 } 2187 2188 return ok(); 2189} 2190 2191binder::Status InstalldNativeService::moveAb(const std::string& apkPath, 2192 const std::string& instructionSet, const std::string& outputPath) { 2193 ENFORCE_UID(AID_SYSTEM); 2194 std::lock_guard<std::recursive_mutex> lock(mLock); 2195 2196 const char* apk_path = apkPath.c_str(); 2197 const char* instruction_set = instructionSet.c_str(); 2198 const char* oat_dir = outputPath.c_str(); 2199 2200 bool success = move_ab(apk_path, instruction_set, oat_dir); 2201 return success ? ok() : error(); 2202} 2203 2204binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath, 2205 const std::string& instructionSet, const std::string& outputPath) { 2206 ENFORCE_UID(AID_SYSTEM); 2207 std::lock_guard<std::recursive_mutex> lock(mLock); 2208 2209 const char* apk_path = apkPath.c_str(); 2210 const char* instruction_set = instructionSet.c_str(); 2211 const char* oat_dir = outputPath.c_str(); 2212 2213 bool res = delete_odex(apk_path, instruction_set, oat_dir); 2214 return res ? ok() : error(); 2215} 2216 2217binder::Status InstalldNativeService::reconcileSecondaryDexFile( 2218 const std::string& dexPath, const std::string& packageName, int32_t uid, 2219 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid, 2220 int32_t storage_flag, bool* _aidl_return) { 2221 ENFORCE_UID(AID_SYSTEM); 2222 CHECK_ARGUMENT_UUID(volumeUuid); 2223 CHECK_ARGUMENT_PACKAGE_NAME(packageName); 2224 2225 std::lock_guard<std::recursive_mutex> lock(mLock); 2226 bool result = android::installd::reconcile_secondary_dex_file( 2227 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return); 2228 return result ? ok() : error(); 2229} 2230 2231binder::Status InstalldNativeService::invalidateMounts() { 2232 ENFORCE_UID(AID_SYSTEM); 2233 std::lock_guard<std::recursive_mutex> lock(mMountsLock); 2234 2235 mStorageMounts.clear(); 2236 mQuotaReverseMounts.clear(); 2237 2238 std::ifstream in("/proc/mounts"); 2239 if (!in.is_open()) { 2240 return error("Failed to read mounts"); 2241 } 2242 2243 std::string source; 2244 std::string target; 2245 std::string ignored; 2246 while (!in.eof()) { 2247 std::getline(in, source, ' '); 2248 std::getline(in, target, ' '); 2249 std::getline(in, ignored); 2250 2251#if !BYPASS_SDCARDFS 2252 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) { 2253 LOG(DEBUG) << "Found storage mount " << source << " at " << target; 2254 mStorageMounts[source] = target; 2255 } 2256#endif 2257 2258#if !BYPASS_QUOTA 2259 if (source.compare(0, 11, "/dev/block/") == 0) { 2260 struct dqblk dq; 2261 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0, 2262 reinterpret_cast<char*>(&dq)) == 0) { 2263 LOG(DEBUG) << "Found quota mount " << source << " at " << target; 2264 mQuotaReverseMounts[target] = source; 2265 2266 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we 2267 // need to kick it again to enable DQUOT_LIMITS_ENABLED. 2268 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0 2269 && errno != EBUSY) { 2270 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source; 2271 } 2272 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0 2273 && errno != EBUSY) { 2274 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source; 2275 } 2276 } 2277 } 2278#endif 2279 } 2280 return ok(); 2281} 2282 2283std::string InstalldNativeService::findDataMediaPath( 2284 const std::unique_ptr<std::string>& uuid, userid_t userid) { 2285 std::lock_guard<std::recursive_mutex> lock(mMountsLock); 2286 const char* uuid_ = uuid ? uuid->c_str() : nullptr; 2287 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str()); 2288 auto resolved = mStorageMounts[path]; 2289 if (resolved.empty()) { 2290 LOG(WARNING) << "Failed to find storage mount for " << path; 2291 resolved = path; 2292 } 2293 return StringPrintf("%s/%u", resolved.c_str(), userid); 2294} 2295 2296std::string InstalldNativeService::findQuotaDeviceForUuid( 2297 const std::unique_ptr<std::string>& uuid) { 2298 std::lock_guard<std::recursive_mutex> lock(mMountsLock); 2299 auto path = create_data_path(uuid ? uuid->c_str() : nullptr); 2300 return mQuotaReverseMounts[path]; 2301} 2302 2303binder::Status InstalldNativeService::isQuotaSupported( 2304 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) { 2305 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty(); 2306 return ok(); 2307} 2308 2309} // namespace installd 2310} // namespace android 2311