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