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