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