blob: 9e3520dd60ad54cda3f525853ab8593edc7f2bce [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** 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
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** 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
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070017#include "InstalldNativeService.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080018
Jeff Sharkey466459b2017-01-17 15:25:01 -070019#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
Victor Hsiehc6d738a2018-01-20 15:06:39 -080021#include <algorithm>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <errno.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Victor Hsieh18ac0272018-03-12 16:03:02 -070025#include <functional>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080026#include <inttypes.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070027#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070029#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <sys/capability.h>
31#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080032#include <sys/ioctl.h>
33#include <sys/mman.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080034#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070036#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070037#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000038#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070039#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080040#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070041
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000042#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070043#include <android-base/logging.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070044#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000045#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080046#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070047#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010048#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080049#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080050#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070051#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070052#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070053#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070054#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080055#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070056#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080057#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070058#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070059
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070060#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070061#include "globals.h"
62#include "installd_deps.h"
63#include "otapreopt_utils.h"
64#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080065#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066
Jeff Sharkey88ddd942017-01-17 18:05:54 -070067#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080068#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070069#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060070#include "QuotaUtils.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070071
Andreas Gampe02d0de52015-11-11 20:43:16 -080072#ifndef LOG_TAG
73#define LOG_TAG "installd"
74#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070075
76using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070077using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070078
Andreas Gampe02d0de52015-11-11 20:43:16 -080079namespace android {
80namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070081
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000082// An uuid used in unit tests.
83static constexpr const char* kTestUuid = "TEST";
84
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000085static constexpr const mode_t kRollbackFolderMode = 0700;
86
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070087static constexpr const char* kCpPath = "/system/bin/cp";
88static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070089
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070090static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000091
Andreas Gampe0354bd02016-06-27 14:25:30 -070092static constexpr const char* PKG_LIB_POSTFIX = "/lib";
93static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
94static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
95
Victor Hsieh3f16dd62018-01-13 13:43:11 -080096// fsverity assumes the page size is always 4096. If not, the feature can not be
97// enabled.
98static constexpr int kVerityPageSize = 4096;
Victor Hsiehc6d738a2018-01-20 15:06:39 -080099static constexpr size_t kSha256Size = 32;
Victor Hsieh99de5162017-10-06 14:44:14 -0700100static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
Zim0ce832d2019-12-03 17:03:58 +0000101static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700102
Jeff Sharkey0274c972016-12-06 09:32:04 -0700103namespace {
104
105constexpr const char* kDump = "android.permission.DUMP";
106
Jeff Sharkey423e7462016-12-09 18:18:43 -0700107static binder::Status ok() {
108 return binder::Status::ok();
109}
110
111static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700112 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700113 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
114}
115
116static binder::Status error() {
117 return binder::Status::fromServiceSpecificError(errno);
118}
119
120static binder::Status error(const std::string& msg) {
121 PLOG(ERROR) << msg;
122 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
123}
124
125static binder::Status error(uint32_t code, const std::string& msg) {
126 LOG(ERROR) << msg << " (" << code << ")";
127 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
128}
129
Jeff Sharkey0274c972016-12-06 09:32:04 -0700130binder::Status checkPermission(const char* permission) {
131 pid_t pid;
132 uid_t uid;
133
134 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
135 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700137 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700138 return exception(binder::Status::EX_SECURITY,
139 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700140 }
141}
142
143binder::Status checkUid(uid_t expectedUid) {
144 uid_t uid = IPCThreadState::self()->getCallingUid();
145 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700146 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700147 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700148 return exception(binder::Status::EX_SECURITY,
149 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
150 }
151}
152
153binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
154 if (!uuid || is_valid_filename(*uuid)) {
155 return ok();
156 } else {
157 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
158 StringPrintf("UUID %s is malformed", uuid->c_str()));
159 }
160}
161
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000162binder::Status checkArgumentUuidTestOrNull(const std::unique_ptr<std::string>& uuid) {
163 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
164 return ok();
165 } else {
166 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
167 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
168 }
169}
170
Jeff Sharkey423e7462016-12-09 18:18:43 -0700171binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700172 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700173 return ok();
174 } else {
175 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
176 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700177 }
178}
179
Jeff Sharkey53594302018-02-24 18:59:39 -0700180binder::Status checkArgumentPath(const std::string& path) {
181 if (path.empty()) {
182 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
183 }
184 if (path[0] != '/') {
185 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
186 StringPrintf("Path %s is relative", path.c_str()));
187 }
188 if ((path + '/').find("/../") != std::string::npos) {
189 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
190 StringPrintf("Path %s is shady", path.c_str()));
191 }
192 for (const char& c : path) {
193 if (c == '\0' || c == '\n') {
194 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
195 StringPrintf("Path %s is malformed", path.c_str()));
196 }
197 }
198 return ok();
199}
200
201binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
202 if (path) {
203 return checkArgumentPath(*path);
204 } else {
205 return ok();
206 }
207}
208
Jeff Sharkey0274c972016-12-06 09:32:04 -0700209#define ENFORCE_UID(uid) { \
210 binder::Status status = checkUid((uid)); \
211 if (!status.isOk()) { \
212 return status; \
213 } \
214}
215
Jeff Sharkey423e7462016-12-09 18:18:43 -0700216#define CHECK_ARGUMENT_UUID(uuid) { \
217 binder::Status status = checkArgumentUuid((uuid)); \
218 if (!status.isOk()) { \
219 return status; \
220 } \
221}
222
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000223#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
224 auto status = checkArgumentUuidTestOrNull(uuid); \
225 if (!status.isOk()) { \
226 return status; \
227 } \
228} \
229
Jeff Sharkey423e7462016-12-09 18:18:43 -0700230#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
231 binder::Status status = \
232 checkArgumentPackageName((packageName)); \
233 if (!status.isOk()) { \
234 return status; \
235 } \
236}
237
Jeff Sharkey53594302018-02-24 18:59:39 -0700238#define CHECK_ARGUMENT_PATH(path) { \
239 binder::Status status = checkArgumentPath((path)); \
240 if (!status.isOk()) { \
241 return status; \
242 } \
243}
244
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800245#define ASSERT_PAGE_SIZE_4K() { \
246 if (getpagesize() != kVerityPageSize) { \
Victor Hsieh7ebd5132018-01-23 07:52:17 -0800247 return error("FSVerity only supports 4K pages"); \
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800248 } \
249}
250
Jeff Sharkey0274c972016-12-06 09:32:04 -0700251} // namespace
252
253status_t InstalldNativeService::start() {
254 IPCThreadState::self()->disableBackgroundScheduling(true);
255 status_t ret = BinderService<InstalldNativeService>::publish();
256 if (ret != android::OK) {
257 return ret;
258 }
259 sp<ProcessState> ps(ProcessState::self());
260 ps->startThreadPool();
261 ps->giveThreadPoolName();
262 return android::OK;
263}
264
265status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700266 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700267 const binder::Status dump_permission = checkPermission(kDump);
268 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700269 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700270 return PERMISSION_DENIED;
271 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700272 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700273
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700274 out << "installd is happy!" << endl;
275
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700276 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600277 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
278 out << endl << "Storage mounts:" << endl;
279 for (const auto& n : mStorageMounts) {
280 out << " " << n.first << " = " << n.second << endl;
281 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700282 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700283
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700284 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600285 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700286 out << endl << "Per-UID cache quotas:" << endl;
287 for (const auto& n : mCacheQuotas) {
288 out << " " << n.first << " = " << n.second << endl;
289 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700290 }
291
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700292 out << endl;
293 out.flush();
294
Jeff Sharkey0274c972016-12-06 09:32:04 -0700295 return NO_ERROR;
296}
297
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600298/**
299 * Perform restorecon of the given path, but only perform recursive restorecon
300 * if the label of that top-level file actually changed. This can save us
301 * significant time by avoiding no-op traversals of large filesystem trees.
302 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700303static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
304 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600305 int res = 0;
306 char* before = nullptr;
307 char* after = nullptr;
308
309 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
310 // libselinux. Not needed here.
311
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600312 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600313 PLOG(ERROR) << "Failed before getfilecon for " << path;
314 goto fail;
315 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700316 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600317 PLOG(ERROR) << "Failed top-level restorecon for " << path;
318 goto fail;
319 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600320 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600321 PLOG(ERROR) << "Failed after getfilecon for " << path;
322 goto fail;
323 }
324
325 // If the initial top-level restorecon above changed the label, then go
326 // back and restorecon everything recursively
327 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700328 if (existing) {
329 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
330 << path << "; running recursive restorecon";
331 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700332 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600333 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
334 PLOG(ERROR) << "Failed recursive restorecon for " << path;
335 goto fail;
336 }
337 }
338
339 goto done;
340fail:
341 res = -1;
342done:
343 free(before);
344 free(after);
345 return res;
346}
347
Jeff Sharkey0274c972016-12-06 09:32:04 -0700348static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700349 const std::string& seInfo, uid_t uid, bool existing) {
350 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
351 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600352}
353
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600354static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600355 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
356 PLOG(ERROR) << "Failed to prepare " << path;
357 return -1;
358 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600359 return 0;
360}
361
Calin Juravled2affb82017-11-28 17:41:43 -0800362static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
363 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
364 return true;
365 }
366
367 int32_t uid = multiuser_get_uid(userId, appId);
368 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
369 if (shared_app_gid == -1) {
370 // TODO(calin): this should no longer be possible but do not continue if we don't get
371 // a valid shared gid.
372 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
373 return true;
374 }
375
376 const std::string profile_dir =
377 create_primary_current_profile_package_dir_path(userId, packageName);
378 // read-write-execute only for the app user.
379 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
380 PLOG(ERROR) << "Failed to prepare " << profile_dir;
381 return false;
382 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800383
Calin Juravled2affb82017-11-28 17:41:43 -0800384 const std::string ref_profile_path =
385 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800386
387 // Prepare the reference profile directory. Note that we use the non strict version of
388 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
389 // This is particularly important given that in O there were some fixes for how the
390 // shared_app_gid is computed.
391 //
392 // Note that by the time we get here we know that we are using a correct uid (otherwise
393 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
394 // are sure that the gid being used belongs to the owning app and not someone else.
395 //
396 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
397 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800398 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
399 return false;
400 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800401
Calin Juravled2affb82017-11-28 17:41:43 -0800402 return true;
403}
404
Jeff Sharkey0274c972016-12-06 09:32:04 -0700405binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
406 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700407 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700408 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700409 CHECK_ARGUMENT_UUID(uuid);
410 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700411 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700412
413 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
414 const char* pkgname = packageName.c_str();
415
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700416 // Assume invalid inode unless filled in below
417 if (_aidl_return != nullptr) *_aidl_return = -1;
418
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700419 int32_t uid = multiuser_get_uid(userId, appId);
420 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700421 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
422
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700423 // If UID doesn't have a specific cache GID, use UID value
424 if (cacheGid == -1) {
425 cacheGid = uid;
426 }
427
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700428 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700429 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700430 bool existing = (access(path.c_str(), F_OK) == 0);
431
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700432 if (prepare_app_dir(path, targetMode, uid) ||
433 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
434 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700435 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600436 }
437
438 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700439 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
440 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
441 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700442 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700443 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600444
445 // Remember inode numbers of cache directories so that we can clear
446 // contents while CE storage is locked
447 if (write_path_inode(path, "cache", kXattrInodeCache) ||
448 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700449 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700450 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700451
452 // And return the CE inode of the top-level data directory so we can
453 // clear contents while CE storage is locked
454 if ((_aidl_return != nullptr)
455 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
456 return error("Failed to get_path_inode for " + path);
457 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700458 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700459 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700460 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700461 bool existing = (access(path.c_str(), F_OK) == 0);
462
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700463 if (prepare_app_dir(path, targetMode, uid) ||
464 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
465 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700466 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700467 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000468
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600469 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600470 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
471 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
472 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700473 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600474 }
475
Calin Juravled2affb82017-11-28 17:41:43 -0800476 if (!prepare_app_profile_dir(packageName, appId, userId)) {
477 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000478 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700479 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700480 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700481}
482
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700483binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
484 const std::string& packageName, int32_t userId, int32_t flags) {
485 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700486 CHECK_ARGUMENT_UUID(uuid);
487 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700488 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700490 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
491 const char* pkgname = packageName.c_str();
492
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700493 // This method only exists to upgrade system apps that have requested
494 // forceDeviceEncrypted, so their default storage always lives in a
495 // consistent location. This only works on non-FBE devices, since we
496 // never want to risk exposing data on a device with real CE/DE storage.
497
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700498 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
499 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700500
501 // If neither directory is marked as default, assume CE is default
502 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
503 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
504 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700505 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700506 }
507 }
508
509 // Migrate default data location if needed
510 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
511 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
512
513 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
514 LOG(WARNING) << "Requested default storage " << target
515 << " is not active; migrating from " << source;
516 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700517 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700518 }
519 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700521 }
522 }
523
Jeff Sharkey423e7462016-12-09 18:18:43 -0700524 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700525}
526
Calin Juravle6a1648e2016-02-01 12:12:16 +0000527
Calin Juravle562de812018-01-20 23:34:18 -0800528binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
529 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700530 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700531 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700532 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700533
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -0800535 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700536 res = error("Failed to clear reference profile for " + packageName);
537 }
Calin Juravle562de812018-01-20 23:34:18 -0800538 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 res = error("Failed to clear current profiles for " + packageName);
540 }
541 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000542}
543
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700544binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
545 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
546 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 CHECK_ARGUMENT_UUID(uuid);
548 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700549 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700550
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700551 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
552 const char* pkgname = packageName.c_str();
553
Jeff Sharkey423e7462016-12-09 18:18:43 -0700554 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700555 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700556 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600557 if (flags & FLAG_CLEAR_CACHE_ONLY) {
558 path = read_path_inode(path, "cache", kXattrInodeCache);
559 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
560 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
561 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700562 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700563 if (delete_dir_contents(path) != 0) {
564 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900565 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
566 remove_path_xattr(path, kXattrInodeCache);
567 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700569 }
570 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700571 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600572 std::string suffix = "";
573 bool only_cache = false;
574 if (flags & FLAG_CLEAR_CACHE_ONLY) {
575 suffix = CACHE_DIR_POSTFIX;
576 only_cache = true;
577 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
578 suffix = CODE_CACHE_DIR_POSTFIX;
579 only_cache = true;
580 }
581
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700582 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700583 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 if (delete_dir_contents(path) != 0) {
585 res = error("Failed to delete contents of " + path);
586 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700587 }
588 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600589 if (flags & FLAG_STORAGE_EXTERNAL) {
590 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
591 for (const auto& n : mStorageMounts) {
592 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000593
594 if (android::base::GetBoolProperty(kFuseProp, false)) {
595 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
596 if (std::regex_match(extPath, re)) {
597 extPath += "/" + std::to_string(userId);
598 }
599 } else {
600 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
601 extPath += StringPrintf("/%d", userId);
602 } else if (userId != 0) {
603 // TODO: support devices mounted under secondary users
604 continue;
605 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600606 }
Zim0ce832d2019-12-03 17:03:58 +0000607
Jeff Sharkey6e175692019-05-14 14:55:33 -0600608 if (flags & FLAG_CLEAR_CACHE_ONLY) {
609 // Clear only cached data from shared storage
610 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
611 if (delete_dir_contents(path, true) != 0) {
612 res = error("Failed to delete contents of " + path);
613 }
614 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
615 // No code cache on shared storage
616 } else {
617 // Clear everything on shared storage
618 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
619 if (delete_dir_contents(path, true) != 0) {
620 res = error("Failed to delete contents of " + path);
621 }
622 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
623 if (delete_dir_contents(path, true) != 0) {
624 res = error("Failed to delete contents of " + path);
625 }
626 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
627 if (delete_dir_contents(path, true) != 0) {
628 res = error("Failed to delete contents of " + path);
629 }
630 }
631 }
632 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700633 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700634}
635
Calin Juravle76268c52017-03-09 13:19:42 -0800636static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100637 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800638 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100639 /*ignore_if_missing*/ true);
640}
641
Calin Juravle76268c52017-03-09 13:19:42 -0800642static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100643 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800644 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100645 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000646}
647
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700648binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
649 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700650 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700651 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700652
Jeff Sharkey423e7462016-12-09 18:18:43 -0700653 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000654 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
655 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800656 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700657 res = error("Failed to destroy current profiles for " + packageName);
658 }
Calin Juravleedae6692016-03-23 13:55:31 +0000659 }
Calin Juravle76268c52017-03-09 13:19:42 -0800660 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700661 res = error("Failed to destroy reference profile for " + packageName);
662 }
663 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000664}
665
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700666binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
667 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
668 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700669 CHECK_ARGUMENT_UUID(uuid);
670 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700671 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700672
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700673 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
674 const char* pkgname = packageName.c_str();
675
Jeff Sharkey423e7462016-12-09 18:18:43 -0700676 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700677 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700678 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
679 if (delete_dir_contents_and_dir(path) != 0) {
680 res = error("Failed to delete " + path);
681 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700682 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700683 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700684 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
685 if (delete_dir_contents_and_dir(path) != 0) {
686 res = error("Failed to delete " + path);
687 }
Calin Juravle76268c52017-03-09 13:19:42 -0800688 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100689 // TODO(calin): If the package is still installed by other users it's probably
690 // beneficial to keep the reference profile around.
691 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800692 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700693 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600694 if (flags & FLAG_STORAGE_EXTERNAL) {
695 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
696 for (const auto& n : mStorageMounts) {
697 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000698
699 if (android::base::GetBoolProperty(kFuseProp, false)) {
700 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
701 if (std::regex_match(extPath, re)) {
702 extPath += "/" + std::to_string(userId);
703 }
704 } else {
705 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
706 extPath += StringPrintf("/%d", userId);
707 } else if (userId != 0) {
708 // TODO: support devices mounted under secondary users
709 continue;
710 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600711 }
Zim0ce832d2019-12-03 17:03:58 +0000712
Jeff Sharkey6e175692019-05-14 14:55:33 -0600713 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
714 if (delete_dir_contents_and_dir(path, true) != 0) {
715 res = error("Failed to delete contents of " + path);
716 }
Zim0ce832d2019-12-03 17:03:58 +0000717
Jeff Sharkey6e175692019-05-14 14:55:33 -0600718 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
719 if (delete_dir_contents_and_dir(path, true) != 0) {
720 res = error("Failed to delete contents of " + path);
721 }
722 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
723 if (delete_dir_contents_and_dir(path, true) != 0) {
724 res = error("Failed to delete contents of " + path);
725 }
726 }
727 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700728 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700729}
730
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600731static gid_t get_cache_gid(uid_t uid) {
732 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
733 return (gid != -1) ? gid : uid;
734}
735
736binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
737 int32_t flags) {
738 ENFORCE_UID(AID_SYSTEM);
739 CHECK_ARGUMENT_UUID(uuid);
740 std::lock_guard<std::recursive_mutex> lock(mLock);
741
742 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
743 for (auto user : get_known_users(uuid_)) {
744 ATRACE_BEGIN("fixup user");
745 FTS* fts;
746 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600747 auto ce_path = create_data_user_ce_path(uuid_, user);
748 auto de_path = create_data_user_de_path(uuid_, user);
749 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -0700750 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600751 return error("Failed to fts_open");
752 }
753 while ((p = fts_read(fts)) != nullptr) {
754 if (p->fts_info == FTS_D && p->fts_level == 1) {
755 // Track down inodes of cache directories
756 uint64_t raw = 0;
757 ino_t inode_cache = 0;
758 ino_t inode_code_cache = 0;
759 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
760 inode_cache = raw;
761 }
762 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
763 inode_code_cache = raw;
764 }
765
766 // Figure out expected GID of each child
767 FTSENT* child = fts_children(fts, 0);
768 while (child != nullptr) {
769 if ((child->fts_statp->st_ino == inode_cache)
770 || (child->fts_statp->st_ino == inode_code_cache)
771 || !strcmp(child->fts_name, "cache")
772 || !strcmp(child->fts_name, "code_cache")) {
773 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
774 } else {
775 child->fts_number = p->fts_statp->st_uid;
776 }
777 child = child->fts_link;
778 }
779 } else if (p->fts_level >= 2) {
780 if (p->fts_level > 2) {
781 // Inherit GID from parent once we're deeper into tree
782 p->fts_number = p->fts_parent->fts_number;
783 }
784
785 uid_t uid = p->fts_parent->fts_statp->st_uid;
786 gid_t cache_gid = get_cache_gid(uid);
787 gid_t expected = p->fts_number;
788 gid_t actual = p->fts_statp->st_gid;
789 if (actual == expected) {
790#if FIXUP_DEBUG
791 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
792#endif
793 if (!(flags & FLAG_FORCE)) {
794 fts_set(fts, p, FTS_SKIP);
795 }
796 } else if ((actual == uid) || (actual == cache_gid)) {
797 // Only consider fixing up when current GID belongs to app
798 if (p->fts_info != FTS_D) {
799 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
800 << " instead of " << expected;
801 }
802 switch (p->fts_info) {
803 case FTS_DP:
804 // If we're moving towards cache GID, we need to set S_ISGID
805 if (expected == cache_gid) {
806 if (chmod(p->fts_path, 02771) != 0) {
807 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
808 }
809 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700810 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600811 case FTS_F:
812 if (chown(p->fts_path, -1, expected) != 0) {
813 PLOG(WARNING) << "Failed to chown " << p->fts_path;
814 }
815 break;
816 case FTS_SL:
817 case FTS_SLNONE:
818 if (lchown(p->fts_path, -1, expected) != 0) {
819 PLOG(WARNING) << "Failed to chown " << p->fts_path;
820 }
821 break;
822 }
823 } else {
824 // Ignore all other GID transitions, since they're kinda shady
825 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
826 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600827 if (!(flags & FLAG_FORCE)) {
828 fts_set(fts, p, FTS_SKIP);
829 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600830 }
831 }
832 }
833 fts_close(fts);
834 ATRACE_END();
835 }
836 return ok();
837}
838
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000839static int32_t copy_directory_recursive(const char* from, const char* to) {
840 char *argv[] = {
841 (char*) kCpPath,
842 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
843 (char*) "-p", /* preserve timestamps, ownership, and permissions */
844 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
845 (char*) "-P", /* Do not follow symlinks [default] */
846 (char*) "-d", /* don't dereference symlinks */
847 (char*) from,
848 (char*) to
849 };
850
851 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -0700852 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000853}
854
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000855binder::Status InstalldNativeService::snapshotAppData(
856 const std::unique_ptr<std::string>& volumeUuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000857 const std::string& packageName, int32_t user, int32_t snapshotId,
858 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000859 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000860 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000861 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
862 std::lock_guard<std::recursive_mutex> lock(mLock);
863
864 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
865 const char* package_name = packageName.c_str();
866
867 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000868 // Default result to 0, it will be populated with inode of ce data snapshot
869 // if FLAG_STORAGE_CE has been passed.
870 if (_aidl_return != nullptr) *_aidl_return = 0;
871
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000872 bool clear_ce_on_exit = false;
873 bool clear_de_on_exit = false;
874
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000875 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &user, &package_name,
876 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000877 if (clear_de_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000878 auto to = create_data_misc_de_rollback_package_path(volume_uuid, user, snapshotId,
879 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000880 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
881 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
882 }
883 }
884
885 if (clear_ce_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000886 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshotId,
887 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000888 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
889 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
890 }
891 }
892 };
893
894 auto scope_guard = android::base::make_scope_guard(deleter);
895
896 // The app may not have any data at all, in which case it's OK to skip here.
897 auto from_ce = create_data_user_ce_package_path(volume_uuid, user, package_name);
898 if (access(from_ce.c_str(), F_OK) != 0) {
899 LOG(INFO) << "Missing source " << from_ce;
900 return ok();
901 }
902
Nikita Ioffe900b3c22019-01-23 14:32:48 +0000903 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
904 binder::Status clear_cache_result = clearAppData(volumeUuid, packageName, user,
905 storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
906 if (!clear_cache_result.isOk()) {
907 // It should be fine to continue snapshot if we for some reason failed
908 // to clear cache.
909 LOG(WARNING) << "Failed to clear cache of app " << packageName;
910 }
911
912 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
913 binder::Status clear_code_cache_result = clearAppData(volumeUuid, packageName, user,
914 storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY, 0);
915 if (!clear_code_cache_result.isOk()) {
916 // It should be fine to continue snapshot if we for some reason failed
917 // to clear code_cache.
918 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
919 }
920
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000921 if (storageFlags & FLAG_STORAGE_DE) {
922 auto from = create_data_user_de_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000923 auto to = create_data_misc_de_rollback_path(volume_uuid, user, snapshotId);
924 auto rollback_package_path = create_data_misc_de_rollback_package_path(volume_uuid, user,
925 snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000926
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000927 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
928 if (rc != 0) {
929 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000930 }
931
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000932 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
933 if (rc != 0) {
934 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
935 }
936
937 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000938 if (rc != 0) {
939 res = error(rc, "Failed copying " + from + " to " + to);
940 clear_de_on_exit = true;
941 return res;
942 }
943 }
944
945 if (storageFlags & FLAG_STORAGE_CE) {
946 auto from = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000947 auto to = create_data_misc_ce_rollback_path(volume_uuid, user, snapshotId);
948 auto rollback_package_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
949 snapshotId, package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000950
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000951 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
952 if (rc != 0) {
953 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000954 }
955
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000956 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
957 if (rc != 0) {
958 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
959 }
960
961 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000962 if (rc != 0) {
963 res = error(rc, "Failed copying " + from + " to " + to);
964 clear_ce_on_exit = true;
965 return res;
966 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000967 if (_aidl_return != nullptr) {
968 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000969 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000970 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
971 if (rc != 0) {
972 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
973 clear_ce_on_exit = true;
974 return res;
975 }
976 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000977 }
978
979 return res;
980}
981
982binder::Status InstalldNativeService::restoreAppDataSnapshot(
983 const std::unique_ptr<std::string>& volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000984 const int32_t appId, const std::string& seInfo, const int32_t user,
985 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000986 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000987 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000988 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
989 std::lock_guard<std::recursive_mutex> lock(mLock);
990
991 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
992 const char* package_name = packageName.c_str();
993
994 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000995 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000996 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000997 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000998
999 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1000 (access(from_ce.c_str(), F_OK) == 0);
1001 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1002 (access(from_de.c_str(), F_OK) == 0);
1003
1004 if (!needs_ce_rollback && !needs_de_rollback) {
1005 return ok();
1006 }
1007
1008 // We know we're going to rollback one of the CE or DE data, so we clear
1009 // application data first. Note that it's possible that we're asked to
1010 // restore both CE & DE data but that one of the restores fail. Leaving the
1011 // app with no data in those cases is arguably better than leaving the app
1012 // with mismatched / stale data.
1013 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001014 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1015 // can only be called when user unlocks the phone, meaning that CE user data
1016 // is decrypted.
1017 binder::Status res = clearAppData(volumeUuid, packageName, user, storageFlags,
1018 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001019 if (!res.isOk()) {
1020 return res;
1021 }
1022
1023 if (needs_ce_rollback) {
1024 auto to_ce = create_data_user_ce_path(volume_uuid, user);
1025 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1026 if (rc != 0) {
1027 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1028 return res;
1029 }
1030 }
1031
1032 if (needs_de_rollback) {
1033 auto to_de = create_data_user_de_path(volume_uuid, user);
1034 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1035 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001036 if (needs_ce_rollback) {
1037 auto ce_data = create_data_user_ce_package_path(volume_uuid, user, package_name);
1038 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1039 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1040 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1041 }
1042 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001043 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1044 return res;
1045 }
1046 }
1047
1048 // Finally, restore the SELinux label on the app data.
1049 return restoreconAppData(volumeUuid, packageName, user, storageFlags, appId, seInfo);
1050}
1051
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001052binder::Status InstalldNativeService::destroyAppDataSnapshot(
1053 const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001054 const int32_t user, const int64_t ceSnapshotInode, const int32_t snapshotId,
1055 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001056 ENFORCE_UID(AID_SYSTEM);
1057 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1058 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1059 std::lock_guard<std::recursive_mutex> lock(mLock);
1060
1061 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1062 const char* package_name = packageName.c_str();
1063
1064 if (storageFlags & FLAG_STORAGE_DE) {
1065 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001066 user, snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001067
1068 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1069 if (res != 0) {
1070 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1071 }
1072 }
1073
1074 if (storageFlags & FLAG_STORAGE_CE) {
1075 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001076 user, snapshotId, package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001077 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1078 if (res != 0) {
1079 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1080 }
1081 }
1082 return ok();
1083}
1084
1085
Jeff Sharkey0274c972016-12-06 09:32:04 -07001086binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
1087 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
1088 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
1089 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001090 ENFORCE_UID(AID_SYSTEM);
1091 CHECK_ARGUMENT_UUID(fromUuid);
1092 CHECK_ARGUMENT_UUID(toUuid);
1093 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001094 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -07001095
1096 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1097 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1098 const char* package_name = packageName.c_str();
1099 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001100
Jeff Sharkey423e7462016-12-09 18:18:43 -07001101 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001102 std::vector<userid_t> users = get_known_users(from_uuid);
1103
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001104 // Copy app
1105 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001106 auto from = create_data_app_package_path(from_uuid, data_app_name);
1107 auto to = create_data_app_package_path(to_uuid, data_app_name);
1108 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001109
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001110 int rc = copy_directory_recursive(from.c_str(), to_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001111 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001112 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001113 goto fail;
1114 }
1115
1116 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001117 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001118 goto fail;
1119 }
1120 }
1121
1122 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -07001123 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -07001124
1125 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -06001126 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
1127 if (access(from_ce.c_str(), F_OK) != 0) {
1128 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001129 continue;
1130 }
1131
Jeff Sharkey0274c972016-12-06 09:32:04 -07001132 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -07001133 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001134 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001135 goto fail;
1136 }
1137
Jeff Sharkey51c94492016-05-10 17:46:39 -06001138 {
1139 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
1140 auto to = create_data_user_de_path(to_uuid, user);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001141
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001142 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001143 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001144 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001145 goto fail;
1146 }
1147 }
1148 {
1149 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
1150 auto to = create_data_user_ce_path(to_uuid, user);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001151
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001152 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001153 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001154 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001155 goto fail;
1156 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001157 }
1158
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001159 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1160 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001161 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001162 goto fail;
1163 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001164 }
1165
Jeff Sharkey31f08982015-07-07 13:31:37 -07001166 // We let the framework scan the new location and persist that before
1167 // deleting the data in the old location; this ordering ensures that
1168 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001169 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001170
1171fail:
1172 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001173 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001174 auto to = create_data_app_package_path(to_uuid, data_app_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001175 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001176 LOG(WARNING) << "Failed to rollback " << to;
1177 }
1178 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001179 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001180 {
1181 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001182 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001183 LOG(WARNING) << "Failed to rollback " << to;
1184 }
1185 }
1186 {
1187 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001188 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001189 LOG(WARNING) << "Failed to rollback " << to;
1190 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001191 }
1192 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001193 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001194}
1195
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001196binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
1197 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1198 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001199 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001200 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001201
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001202 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001203 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001204 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001205 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001206 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001207 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001208 }
1209 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001210
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001211 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001212}
1213
1214binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
1215 int32_t userId, int32_t flags) {
1216 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001217 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001218 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001219
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001220 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001221 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001222 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001223 auto path = create_data_user_de_path(uuid_, userId);
1224 if (delete_dir_contents_and_dir(path, true) != 0) {
1225 res = error("Failed to delete " + path);
1226 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001227 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001228 path = create_data_misc_legacy_path(userId);
1229 if (delete_dir_contents_and_dir(path, true) != 0) {
1230 res = error("Failed to delete " + path);
1231 }
Calin Juravle114f0812017-03-08 19:05:07 -08001232 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001233 if (delete_dir_contents_and_dir(path, true) != 0) {
1234 res = error("Failed to delete " + path);
1235 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001236 }
Robin Lee095c7632014-04-25 15:05:19 +01001237 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001238 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001239 auto path = create_data_user_ce_path(uuid_, userId);
1240 if (delete_dir_contents_and_dir(path, true) != 0) {
1241 res = error("Failed to delete " + path);
1242 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001243 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001244 if (delete_dir_contents_and_dir(path, true) != 0) {
1245 res = error("Failed to delete " + path);
1246 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001247 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001248 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001249}
1250
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001251binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001252 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001253 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001254 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001255 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001256
Risan5f308262018-10-26 12:06:58 -06001257 auto uuidString = uuid ? *uuid : "";
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001258 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001259 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001260 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001261
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001262 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001263 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001264 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001265 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001266
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001267 int64_t cleared = 0;
1268 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001269 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001270 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001271
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001272 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001273 return ok();
1274 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001275
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001276 if (flags & FLAG_FREE_CACHE_V2) {
1277 // This new cache strategy fairly removes files from UIDs by deleting
1278 // files from the UIDs which are most over their allocated quota
1279
1280 // 1. Create trackers for every known UID
1281 ATRACE_BEGIN("create");
1282 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1283 for (auto user : get_known_users(uuid_)) {
1284 FTS *fts;
1285 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001286 auto ce_path = create_data_user_ce_path(uuid_, user);
1287 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001288 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1289 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1290 (char*) media_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001291 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001292 return error("Failed to fts_open");
1293 }
Yi Konge7bf3772018-07-17 16:16:24 -07001294 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001295 if (p->fts_info == FTS_D && p->fts_level == 1) {
1296 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001297 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1298 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1299 + AID_APP_START;
1300 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001301 auto search = trackers.find(uid);
1302 if (search != trackers.end()) {
1303 search->second->addDataPath(p->fts_path);
1304 } else {
1305 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06001306 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001307 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001308 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001309 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001310 tracker->cacheQuota = mCacheQuotas[uid];
1311 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001312 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001313#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001314 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001315#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001316 tracker->cacheQuota = 67108864;
1317 }
1318 trackers[uid] = tracker;
1319 }
1320 fts_set(fts, p, FTS_SKIP);
1321 }
1322 }
1323 fts_close(fts);
1324 }
1325 ATRACE_END();
1326
1327 // 2. Populate tracker stats and insert into priority queue
1328 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001329 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001330 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1331 return (left->getCacheRatio() < right->getCacheRatio());
1332 };
1333 std::priority_queue<std::shared_ptr<CacheTracker>,
1334 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1335 for (const auto& it : trackers) {
1336 it.second->loadStats();
1337 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001338 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001339 }
1340 ATRACE_END();
1341
1342 // 3. Bounce across the queue, freeing items from whichever tracker is
1343 // the most over their assigned quota
1344 ATRACE_BEGIN("bounce");
1345 std::shared_ptr<CacheTracker> active;
1346 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001347 // Only look at apps under quota when explicitly requested
1348 if (active && (active->getCacheRatio() < 10000)
1349 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1350 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1351 << " isn't over quota, and defy not requested";
1352 break;
1353 }
1354
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001355 // Only keep clearing when we haven't pushed into reserved area
1356 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1357 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1358 break;
1359 }
1360
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001361 // Find the best tracker to work with; this might involve swapping
1362 // if the active tracker is no longer the most over quota
1363 bool nextBetter = active && !queue.empty()
1364 && active->getCacheRatio() < queue.top()->getCacheRatio();
1365 if (!active || nextBetter) {
1366 if (active) {
1367 // Current tracker still has items, so we'll consider it
1368 // again later once it bubbles up to surface
1369 queue.push(active);
1370 }
1371 active = queue.top(); queue.pop();
1372 active->ensureItems();
1373 continue;
1374 }
1375
1376 // If no items remain, go find another tracker
1377 if (active->items.empty()) {
1378 active = nullptr;
1379 continue;
1380 } else {
1381 auto item = active->items.back();
1382 active->items.pop_back();
1383
1384 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1385 if (!noop) {
1386 item->purge();
1387 }
1388 active->cacheUsed -= item->size;
1389 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001390 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001391 }
1392
1393 // Verify that we're actually done before bailing, since sneaky
1394 // apps might be using hardlinks
1395 if (needed <= 0) {
1396 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001397 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001398 if (needed <= 0) {
1399 break;
1400 } else {
1401 LOG(WARNING) << "Expected to be done but still need " << needed;
1402 }
1403 }
1404 }
1405 ATRACE_END();
1406
1407 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001408 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001409 }
1410
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001411 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001412 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001413 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001414 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001415 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001416 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001417 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001418}
1419
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001420binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1421 const std::string& instructionSet) {
1422 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07001423 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001424 std::lock_guard<std::recursive_mutex> lock(mLock);
1425
Mike Lockwood94afecf2012-10-24 10:45:23 -07001426 char dex_path[PKG_PATH_MAX];
1427
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001428 const char* path = codePath.c_str();
1429 const char* instruction_set = instructionSet.c_str();
1430
Jeff Sharkey770180a2014-09-08 17:14:26 -07001431 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001432 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001433 }
1434
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001435 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001436 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001437 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001438
1439 ALOGV("unlink %s\n", dex_path);
1440 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001441 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1442 // but could not be unlinked.
1443 if (errno != ENOENT) {
1444 return error(StringPrintf("Failed to unlink %s", dex_path));
1445 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001446 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001447 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001448}
1449
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001450struct stats {
1451 int64_t codeSize;
1452 int64_t dataSize;
1453 int64_t cacheSize;
1454};
1455
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001456#if MEASURE_DEBUG
1457static std::string toString(std::vector<int64_t> values) {
1458 std::stringstream res;
1459 res << "[";
1460 for (size_t i = 0; i < values.size(); i++) {
1461 res << values[i];
1462 if (i < values.size() - 1) {
1463 res << ",";
1464 }
1465 }
1466 res << "]";
1467 return res.str();
1468}
1469#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001470
Risan5f308262018-10-26 12:06:58 -06001471static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001472 int32_t appId, struct stats* stats, struct stats* extStats) {
Risan5f308262018-10-26 12:06:58 -06001473 int64_t space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001474 if (stats != nullptr) {
1475 uid_t uid = multiuser_get_uid(userId, appId);
Risan5f308262018-10-26 12:06:58 -06001476 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
1477 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001478 }
1479
1480 int cacheGid = multiuser_get_cache_gid(userId, appId);
1481 if (cacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001482 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
1483 stats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001484 }
1485 }
1486
1487 int sharedGid = multiuser_get_shared_gid(0, appId);
1488 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001489 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
1490 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001491 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001492 }
1493 }
1494
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001495 if (extStats != nullptr) {
1496 int extGid = multiuser_get_ext_gid(userId, appId);
1497 if (extGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001498 if ((space = GetOccupiedSpaceForGid(uuid, extGid)) != -1) {
1499 extStats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001500 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001501 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001502
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001503 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1504 if (extCacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001505 if ((space = GetOccupiedSpaceForGid(uuid, extCacheGid)) != -1) {
1506 extStats->dataSize += space;
1507 extStats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001508 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001509 }
1510 }
1511}
1512
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001513static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001514 DIR *d;
1515 int dfd;
1516 struct dirent *de;
1517 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001518
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001519 d = opendir(path.c_str());
1520 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001521 if (errno != ENOENT) {
1522 PLOG(WARNING) << "Failed to open " << path;
1523 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001524 return;
1525 }
1526 dfd = dirfd(d);
1527 while ((de = readdir(d))) {
1528 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001529
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001530 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001531 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001532 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001533 }
1534
1535 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001536 if (!strcmp(name, ".")) {
1537 // Don't recurse, but still count node size
1538 } else if (!strcmp(name, "..")) {
1539 // Don't recurse or count node size
1540 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001541 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001542 // Measure all children nodes
1543 size = 0;
1544 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001545 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001546
1547 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1548 stats->cacheSize += size;
1549 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001550 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001551
1552 // Legacy symlink isn't owned by app
1553 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1554 continue;
1555 }
1556
1557 // Everything found inside is considered data
1558 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001559 }
1560 closedir(d);
1561}
1562
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001563static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1564 bool exclude_apps = false) {
1565 DIR *d;
1566 int dfd;
1567 struct dirent *de;
1568 struct stat s;
1569
1570 d = opendir(path.c_str());
1571 if (d == nullptr) {
1572 if (errno != ENOENT) {
1573 PLOG(WARNING) << "Failed to open " << path;
1574 }
1575 return;
1576 }
1577 dfd = dirfd(d);
1578 while ((de = readdir(d))) {
1579 if (de->d_type == DT_DIR) {
1580 const char *name = de->d_name;
1581 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1582 continue;
1583 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001584 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001585 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1586 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001587 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001588 continue;
1589 } else {
1590 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1591 }
1592 }
1593 }
1594 closedir(d);
1595}
1596
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001597static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1598 FTS *fts;
1599 FTSENT *p;
1600 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001601 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001602 PLOG(ERROR) << "Failed to fts_open " << path;
1603 return;
1604 }
Yi Konge7bf3772018-07-17 16:16:24 -07001605 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001606 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001607 switch (p->fts_info) {
1608 case FTS_D:
1609 if (p->fts_level == 4
1610 && !strcmp(p->fts_name, "cache")
1611 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1612 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1613 p->fts_number = 1;
1614 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001615 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001616 case FTS_DEFAULT:
1617 case FTS_F:
1618 case FTS_SL:
1619 case FTS_SLNONE:
1620 int64_t size = (p->fts_statp->st_blocks * 512);
1621 if (p->fts_number == 1) {
1622 stats->cacheSize += size;
1623 }
1624 stats->dataSize += size;
1625 break;
1626 }
1627 }
1628 fts_close(fts);
1629}
1630
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001631binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001632 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1633 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1634 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001635 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001636 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001637 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001638 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1639 }
Jeff Sharkey53594302018-02-24 18:59:39 -07001640 for (const auto& codePath : codePaths) {
1641 CHECK_ARGUMENT_PATH(codePath);
1642 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001643 // NOTE: Locking is relaxed on this method, since it's limited to
1644 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001645
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001646 // When modifying this logic, always verify using tests:
1647 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1648
1649#if MEASURE_DEBUG
1650 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1651#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001652
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001653 // Here's a summary of the common storage locations across the platform,
1654 // and how they're each tagged:
1655 //
1656 // /data/app/com.example UID system
1657 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001658 // /data/user/0/com.example UID u0_a10 GID u0_a10
1659 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1660 // /data/media/0/foo.txt UID u0_media_rw
1661 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1662 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1663 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1664 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001665
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001666 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001667 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001668 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001669 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001670
Risan5f308262018-10-26 12:06:58 -06001671 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001672 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001673
Risan5f308262018-10-26 12:06:58 -06001674 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001675 flags &= ~FLAG_USE_QUOTA;
1676 }
1677
Jeff Sharkey466459b2017-01-17 15:25:01 -07001678 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001679 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06001680 auto obbCodePath = create_data_media_package_path(uuid_, userId,
1681 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001682 calculate_tree_size(obbCodePath, &extStats.codeSize);
1683 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001684 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001685
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001686 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001687 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001688 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001689 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001690 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001691 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001692 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001693
Jeff Sharkey466459b2017-01-17 15:25:01 -07001694 ATRACE_BEGIN("quota");
Risan5f308262018-10-26 12:06:58 -06001695 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001696 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001697 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001698 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001699 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001700 calculate_tree_size(codePath, &stats.codeSize);
1701 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001702 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001703
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001704 for (size_t i = 0; i < packageNames.size(); i++) {
1705 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001706
Jeff Sharkey466459b2017-01-17 15:25:01 -07001707 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001708 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1709 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001710 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1711 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001712 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001713
Jeff Sharkey06a61842017-04-15 12:03:31 -06001714 if (!uuid) {
1715 ATRACE_BEGIN("profiles");
1716 calculate_tree_size(
1717 create_primary_current_profile_package_dir_path(userId, pkgname),
1718 &stats.dataSize);
1719 calculate_tree_size(
1720 create_primary_reference_profile_package_dir_path(pkgname),
1721 &stats.codeSize);
1722 ATRACE_END();
1723 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001724
Jeff Sharkey466459b2017-01-17 15:25:01 -07001725 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001726 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001727 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001728 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001729 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001730 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001731 }
1732
Jeff Sharkey06a61842017-04-15 12:03:31 -06001733 if (!uuid) {
1734 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001735 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001736 if (sharedGid != -1) {
1737 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1738 sharedGid, -1);
1739 }
1740 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001741 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001742 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001743
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001744 std::vector<int64_t> ret;
1745 ret.push_back(stats.codeSize);
1746 ret.push_back(stats.dataSize);
1747 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001748 ret.push_back(extStats.codeSize);
1749 ret.push_back(extStats.dataSize);
1750 ret.push_back(extStats.cacheSize);
1751#if MEASURE_DEBUG
1752 LOG(DEBUG) << "Final result " << toString(ret);
1753#endif
1754 *_aidl_return = ret;
1755 return ok();
1756}
1757
1758binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1759 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1760 std::vector<int64_t>* _aidl_return) {
1761 ENFORCE_UID(AID_SYSTEM);
1762 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001763 // NOTE: Locking is relaxed on this method, since it's limited to
1764 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001765
1766 // When modifying this logic, always verify using tests:
1767 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1768
1769#if MEASURE_DEBUG
1770 LOG(INFO) << "Measuring user " << userId;
1771#endif
1772
1773 struct stats stats;
1774 struct stats extStats;
1775 memset(&stats, 0, sizeof(stats));
1776 memset(&extStats, 0, sizeof(extStats));
1777
Risan5f308262018-10-26 12:06:58 -06001778 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001779 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1780
Risan5f308262018-10-26 12:06:58 -06001781 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001782 flags &= ~FLAG_USE_QUOTA;
1783 }
1784
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001785 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001786 int64_t space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001787
1788 ATRACE_BEGIN("obb");
Risan5f308262018-10-26 12:06:58 -06001789 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1790 extStats.codeSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001791 }
1792 ATRACE_END();
1793
Jeff Sharkey466459b2017-01-17 15:25:01 -07001794 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001795 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001796 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001797
Jeff Sharkey466459b2017-01-17 15:25:01 -07001798 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001799 auto cePath = create_data_user_ce_path(uuid_, userId);
1800 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001801 auto dePath = create_data_user_de_path(uuid_, userId);
1802 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001803 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001804
Jeff Sharkey06a61842017-04-15 12:03:31 -06001805 if (!uuid) {
1806 ATRACE_BEGIN("profile");
1807 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1808 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1809 auto refProfilePath = create_primary_ref_profile_dir_path();
1810 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1811 ATRACE_END();
1812 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001813
Jeff Sharkey466459b2017-01-17 15:25:01 -07001814 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001815 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001816 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1817 extStats.dataSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001818 }
1819 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001820
Jeff Sharkey06a61842017-04-15 12:03:31 -06001821 if (!uuid) {
1822 ATRACE_BEGIN("dalvik");
1823 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1824 -1, -1, true);
1825 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1826 -1, -1, true);
1827 ATRACE_END();
1828 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001829
Jeff Sharkey466459b2017-01-17 15:25:01 -07001830 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001831 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001832 for (auto appId : appIds) {
1833 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001834 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001835
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001836#if MEASURE_DEBUG
1837 // Sleep to make sure we don't lose logs
1838 usleep(1);
1839#endif
1840 }
1841 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001842 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001843 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001844 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001845 ATRACE_BEGIN("obb");
1846 auto obbPath = create_data_path(uuid_) + "/media/obb";
1847 calculate_tree_size(obbPath, &extStats.codeSize);
1848 ATRACE_END();
1849
Jeff Sharkey466459b2017-01-17 15:25:01 -07001850 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001851 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001852 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001853
Jeff Sharkey466459b2017-01-17 15:25:01 -07001854 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001855 auto cePath = create_data_user_ce_path(uuid_, userId);
1856 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001857 auto dePath = create_data_user_de_path(uuid_, userId);
1858 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001859 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001860
Jeff Sharkey06a61842017-04-15 12:03:31 -06001861 if (!uuid) {
1862 ATRACE_BEGIN("profile");
1863 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1864 calculate_tree_size(userProfilePath, &stats.dataSize);
1865 auto refProfilePath = create_primary_ref_profile_dir_path();
1866 calculate_tree_size(refProfilePath, &stats.codeSize);
1867 ATRACE_END();
1868 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001869
Jeff Sharkey466459b2017-01-17 15:25:01 -07001870 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001871 auto dataMediaPath = create_data_media_path(uuid_, userId);
1872 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1873#if MEASURE_DEBUG
1874 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1875 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001876#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001877 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001878
Jeff Sharkey06a61842017-04-15 12:03:31 -06001879 if (!uuid) {
1880 ATRACE_BEGIN("dalvik");
1881 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1882 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1883 ATRACE_END();
1884 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001885 }
1886
1887 std::vector<int64_t> ret;
1888 ret.push_back(stats.codeSize);
1889 ret.push_back(stats.dataSize);
1890 ret.push_back(stats.cacheSize);
1891 ret.push_back(extStats.codeSize);
1892 ret.push_back(extStats.dataSize);
1893 ret.push_back(extStats.cacheSize);
1894#if MEASURE_DEBUG
1895 LOG(DEBUG) << "Final result " << toString(ret);
1896#endif
1897 *_aidl_return = ret;
1898 return ok();
1899}
1900
1901binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001902 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1903 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001904 ENFORCE_UID(AID_SYSTEM);
1905 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001906 // NOTE: Locking is relaxed on this method, since it's limited to
1907 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001908
1909 // When modifying this logic, always verify using tests:
1910 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1911
1912#if MEASURE_DEBUG
1913 LOG(INFO) << "Measuring external " << userId;
1914#endif
1915
Risan5f308262018-10-26 12:06:58 -06001916 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001917 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1918
1919 int64_t totalSize = 0;
1920 int64_t audioSize = 0;
1921 int64_t videoSize = 0;
1922 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001923 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001924 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001925
Risan5f308262018-10-26 12:06:58 -06001926 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001927 flags &= ~FLAG_USE_QUOTA;
1928 }
1929
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001930 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001931 int64_t space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001932
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001933 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001934 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001935 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1936 totalSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001937 }
1938
1939 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
Risan5f308262018-10-26 12:06:58 -06001940 if ((space = GetOccupiedSpaceForGid(uuidString, audioGid)) != -1) {
1941 audioSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001942 }
1943 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
Risan5f308262018-10-26 12:06:58 -06001944 if ((space = GetOccupiedSpaceForGid(uuidString, videoGid)) != -1) {
1945 videoSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001946 }
1947 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
Risan5f308262018-10-26 12:06:58 -06001948 if ((space = GetOccupiedSpaceForGid(uuidString, imageGid)) != -1) {
1949 imageSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001950 }
Risan5f308262018-10-26 12:06:58 -06001951 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1952 obbSize = space;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001953 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001954 ATRACE_END();
1955
1956 ATRACE_BEGIN("apps");
1957 struct stats extStats;
1958 memset(&extStats, 0, sizeof(extStats));
1959 for (auto appId : appIds) {
1960 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001961 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001962 }
1963 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001964 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001965 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001966 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001967 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001968 FTS *fts;
1969 FTSENT *p;
1970 auto path = create_data_media_path(uuid_, userId);
1971 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001972 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001973 return error("Failed to fts_open " + path);
1974 }
Yi Konge7bf3772018-07-17 16:16:24 -07001975 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001976 char* ext;
1977 int64_t size = (p->fts_statp->st_blocks * 512);
1978 switch (p->fts_info) {
1979 case FTS_F:
1980 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001981 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001982 ext = strrchr(p->fts_name, '.');
1983 if (ext != nullptr) {
1984 switch (MatchExtension(++ext)) {
1985 case AID_MEDIA_AUDIO: audioSize += size; break;
1986 case AID_MEDIA_VIDEO: videoSize += size; break;
1987 case AID_MEDIA_IMAGE: imageSize += size; break;
1988 }
1989 }
1990 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001991 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001992 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001993 // Ignore data belonging to specific apps
1994 p->fts_number = p->fts_parent->fts_number;
1995 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1996 p->fts_number = 1;
1997 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001998 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001999 case FTS_DEFAULT:
2000 case FTS_SL:
2001 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002002 if (p->fts_parent->fts_number == 1) {
2003 appSize += size;
2004 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002005 totalSize += size;
2006 break;
2007 }
2008 }
2009 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002010 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06002011
2012 ATRACE_BEGIN("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002013 auto obbPath = StringPrintf("%s/Android/obb",
2014 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06002015 calculate_tree_size(obbPath, &obbSize);
2016 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002017 }
2018
2019 std::vector<int64_t> ret;
2020 ret.push_back(totalSize);
2021 ret.push_back(audioSize);
2022 ret.push_back(videoSize);
2023 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002024 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06002025 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002026#if MEASURE_DEBUG
2027 LOG(DEBUG) << "Final result " << toString(ret);
2028#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002029 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002030 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002031}
2032
Felka Chang2a0a2462019-11-20 14:20:40 +08002033binder::Status InstalldNativeService::getAppCrates(
2034 const std::unique_ptr<std::string>& uuid,
2035 const std::vector<std::string>& packageNames, int32_t userId,
2036 std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
2037 ENFORCE_UID(AID_SYSTEM);
2038 CHECK_ARGUMENT_UUID(uuid);
2039 for (const auto& packageName : packageNames) {
2040 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2041 }
2042 std::lock_guard<std::recursive_mutex> lock(mLock);
2043
2044 auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
2045 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2046
2047 std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
2048 [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
2049 if (cratedFolder == nullptr) {
2050 return;
2051 }
2052 retVector->push_back(std::move(crateMetadata));
2053 };
2054
2055 for (const auto& packageName : packageNames) {
2056#if CRATE_DEBUG
2057 LOG(DEBUG) << "packageName = " << packageName;
2058#endif
2059 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
2060 crateManager->traverseAllCrates(onCreateCrate);
2061 }
2062
2063#if CRATE_DEBUG
2064 LOG(WARNING) << "retVector->size() =" << retVector->size();
2065 for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
2066 CrateManager::dump(*iter);
2067 }
2068#endif
2069
2070 *_aidl_return = std::move(retVector);
2071 return ok();
2072}
2073
2074binder::Status InstalldNativeService::getUserCrates(
2075 const std::unique_ptr<std::string>& uuid, int32_t userId,
2076 std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
2077 ENFORCE_UID(AID_SYSTEM);
2078 CHECK_ARGUMENT_UUID(uuid);
2079 std::lock_guard<std::recursive_mutex> lock(mLock);
2080
2081 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2082 auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
2083
2084 std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
2085 [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
2086 if (cratedFolder == nullptr) {
2087 return;
2088 }
2089 retVector->push_back(std::move(crateMetadata));
2090 };
2091
2092 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
2093 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
2094 crateManager->traverseAllCrates(onCreateCrate);
2095 };
2096 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
2097
2098#if CRATE_DEBUG
2099 LOG(DEBUG) << "retVector->size() =" << retVector->size();
2100 for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
2101 CrateManager::dump(*iter);
2102 }
2103#endif
2104
2105 *_aidl_return = std::move(retVector);
2106 return ok();
2107}
2108
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002109binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
2110 int32_t userId, int32_t appId, int64_t cacheQuota) {
2111 ENFORCE_UID(AID_SYSTEM);
2112 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002113 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002114
2115 int32_t uid = multiuser_get_uid(userId, appId);
2116 mCacheQuotas[uid] = cacheQuota;
2117
2118 return ok();
2119}
2120
David Sehr6727c2d2016-05-17 16:06:22 -07002121// Dumps the contents of a profile file, using pkgname's dex files for pretty
2122// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002123binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002124 const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002125 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002126 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002127 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002128 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002129
Calin Juravle562de812018-01-20 23:34:18 -08002130 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002131 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07002132}
2133
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002134// Copy the contents of a system profile over the data profile.
2135binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08002136 int32_t packageUid, const std::string& packageName, const std::string& profileName,
2137 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002138 ENFORCE_UID(AID_SYSTEM);
2139 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2140 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle562de812018-01-20 23:34:18 -08002141 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002142 return ok();
2143}
2144
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002145// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002146binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002147 const std::string& profileName, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002148 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002149 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002150 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002151
Calin Juravle562de812018-01-20 23:34:18 -08002152 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002153 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002154}
2155
Calin Juravlec41dac22017-12-05 12:29:15 -08002156binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08002157 const std::string& packageName, const std::string& profileName,
2158 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08002159 ENFORCE_UID(AID_SYSTEM);
2160 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2161 std::lock_guard<std::recursive_mutex> lock(mLock);
2162
Calin Juravlee61189e2018-01-23 19:54:11 -08002163 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08002164 return ok();
2165}
2166
2167binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002168 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08002169 ENFORCE_UID(AID_SYSTEM);
2170 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2171 std::lock_guard<std::recursive_mutex> lock(mLock);
2172
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002173 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002174 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002175 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002176 }
2177 return ok();
2178}
2179
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002180static const char* getCStr(const std::unique_ptr<std::string>& data,
2181 const char* default_value = nullptr) {
2182 return data == nullptr ? default_value : data->c_str();
2183}
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002184binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2185 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2186 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2187 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07002188 const std::unique_ptr<std::string>& classLoaderContext,
Calin Juravle562de812018-01-20 23:34:18 -08002189 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002190 const std::unique_ptr<std::string>& profileName,
Calin Juravledcccd832018-02-13 18:31:32 -08002191 const std::unique_ptr<std::string>& dexMetadataPath,
2192 const std::unique_ptr<std::string>& compilationReason) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002193 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002194 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07002195 CHECK_ARGUMENT_PATH(apkPath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002196 if (packageName && *packageName != "*") {
2197 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2198 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002199 CHECK_ARGUMENT_PATH(outputPath);
2200 CHECK_ARGUMENT_PATH(dexMetadataPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002201 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002202
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07002203 const char* oat_dir = getCStr(outputPath);
2204 const char* instruction_set = instructionSet.c_str();
2205 if (oat_dir != nullptr && !createOatDir(oat_dir, instruction_set).isOk()) {
2206 // Can't create oat dir - let dexopt use cache dir.
2207 oat_dir = nullptr;
2208 }
2209
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002210 const char* apk_path = apkPath.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002211 const char* pkgname = getCStr(packageName, "*");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002212 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002213 const char* volume_uuid = getCStr(uuid);
2214 const char* class_loader_context = getCStr(classLoaderContext);
2215 const char* se_info = getCStr(seInfo);
2216 const char* profile_name = getCStr(profileName);
2217 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08002218 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08002219 std::string error_msg;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002220 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07002221 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Andreas Gampe023b2242018-02-28 16:03:25 -08002222 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg);
2223 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002224}
2225
Eric Holk0ebbe0f2019-01-09 18:17:27 -08002226binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
2227 const std::string& packageName,
2228 const std ::string& outDexFile, int uid,
2229 bool* _aidl_return) {
2230 const char* apk_path = apkPath.c_str();
2231 const char* package_name = packageName.c_str();
2232 const char* out_dex_file = outDexFile.c_str();
2233 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
2234 return *_aidl_return ? ok() : error("viewcompiler failed");
2235}
2236
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002237binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2238 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002239 std::lock_guard<std::recursive_mutex> lock(mLock);
2240
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002241 const char* instruction_set = instructionSet.c_str();
2242
2243 char boot_marker_path[PKG_PATH_MAX];
2244 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002245 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06002246 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08002247 DALVIK_CACHE,
2248 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002249
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002250 ALOGV("mark_boot_complete : %s", boot_marker_path);
2251 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002252 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002253 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002254 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002255}
2256
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002257binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2258 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2259 const std::string& nativeLibPath32, int32_t userId) {
2260 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002261 CHECK_ARGUMENT_UUID(uuid);
2262 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002263 CHECK_ARGUMENT_PATH(nativeLibPath32);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002264 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002265
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002266 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2267 const char* pkgname = packageName.c_str();
2268 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002269 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002270 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002271
Jeff Sharkey423e7462016-12-09 18:18:43 -07002272 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2273 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002274
2275 const char* pkgdir = _pkgdir.c_str();
2276 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002277
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002278 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002279 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002280 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002281
Nick Kralevich85958b62019-01-30 12:32:21 -08002282 char *con = nullptr;
2283 if (lgetfilecon(pkgdir, &con) < 0) {
2284 return error("Failed to lgetfilecon " + _pkgdir);
2285 }
2286
Mike Lockwood94afecf2012-10-24 10:45:23 -07002287 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08002288 res = error("Failed to chown " + _pkgdir);
2289 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002290 }
2291
2292 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002293 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002294 goto out;
2295 }
2296
2297 if (lstat(libsymlink, &libStat) < 0) {
2298 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002299 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002300 goto out;
2301 }
2302 } else {
2303 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07002304 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002305 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002306 goto out;
2307 }
2308 } else if (S_ISLNK(libStat.st_mode)) {
2309 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002310 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002311 goto out;
2312 }
2313 }
2314 }
2315
2316 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002317 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002318 goto out;
2319 }
2320
Nick Kralevich85958b62019-01-30 12:32:21 -08002321 if (lsetfilecon(libsymlink, con) < 0) {
2322 res = error("Failed to lsetfilecon " + _libsymlink);
2323 goto out;
2324 }
2325
Mike Lockwood94afecf2012-10-24 10:45:23 -07002326out:
Nick Kralevich85958b62019-01-30 12:32:21 -08002327 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002328 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002329 auto msg = "Failed to cleanup chmod " + _pkgdir;
2330 if (res.isOk()) {
2331 res = error(msg);
2332 } else {
2333 PLOG(ERROR) << msg;
2334 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002335 }
2336
2337 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002338 auto msg = "Failed to cleanup chown " + _pkgdir;
2339 if (res.isOk()) {
2340 res = error(msg);
2341 } else {
2342 PLOG(ERROR) << msg;
2343 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002344 }
2345
Jeff Sharkey423e7462016-12-09 18:18:43 -07002346 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002347}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002348
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002349binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2350 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2351 const std::string& seInfo) {
2352 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002353 CHECK_ARGUMENT_UUID(uuid);
2354 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002355 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002356
2357 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002358
Robert Craigda30dc72014-03-27 10:21:12 -04002359 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002360 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002361 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2362 const char* pkgName = packageName.c_str();
2363 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002364
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002365 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002366 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002367 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002368 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002369 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002370 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002371 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002372 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002373 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002374 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002375 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002376 }
Robert Craige9887e42014-02-20 10:25:56 -05002377 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002378 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002379}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002380
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002381binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2382 const std::string& instructionSet) {
2383 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002384 CHECK_ARGUMENT_PATH(oatDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002385 std::lock_guard<std::recursive_mutex> lock(mLock);
2386
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002387 const char* oat_dir = oatDir.c_str();
2388 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002389 char oat_instr_dir[PKG_PATH_MAX];
2390
2391 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002392 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002393 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002394 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002395 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002396 }
2397 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002398 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002399 }
2400 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002401 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002402 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002403 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002404 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002405}
2406
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002407binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2408 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002409 CHECK_ARGUMENT_PATH(packageDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002410 std::lock_guard<std::recursive_mutex> lock(mLock);
2411
Jeff Sharkey423e7462016-12-09 18:18:43 -07002412 if (validate_apk_path(packageDir.c_str())) {
2413 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002414 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01002415 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002416 return error("Failed to delete " + packageDir);
2417 }
2418 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002419}
2420
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002421binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2422 const std::string& fromBase, const std::string& toBase) {
2423 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002424 CHECK_ARGUMENT_PATH(fromBase);
2425 CHECK_ARGUMENT_PATH(toBase);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002426 std::lock_guard<std::recursive_mutex> lock(mLock);
2427
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002428 const char* relative_path = relativePath.c_str();
2429 const char* from_base = fromBase.c_str();
2430 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002431 char from_path[PKG_PATH_MAX];
2432 char to_path[PKG_PATH_MAX];
2433 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2434 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2435
2436 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002437 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002438 }
2439
2440 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002441 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002442 }
2443
Jeff Sharkey423e7462016-12-09 18:18:43 -07002444 if (link(from_path, to_path) < 0) {
2445 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002446 }
2447
Jeff Sharkey423e7462016-12-09 18:18:43 -07002448 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002449}
2450
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002451binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2452 const std::string& instructionSet, const std::string& outputPath) {
2453 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002454 CHECK_ARGUMENT_PATH(apkPath);
2455 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002456 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002457
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002458 const char* apk_path = apkPath.c_str();
2459 const char* instruction_set = instructionSet.c_str();
2460 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002461
Jeff Sharkey90aff262016-12-12 14:28:24 -07002462 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002463 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002464}
2465
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002466binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002467 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002468 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002469 CHECK_ARGUMENT_PATH(apkPath);
2470 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002471 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002472
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002473 const char* apk_path = apkPath.c_str();
2474 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002475 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002476
Jeff Sharkey90aff262016-12-12 14:28:24 -07002477 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2478 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002479}
2480
Victor Hsieh7ebd5132018-01-23 07:52:17 -08002481// This kernel feature is experimental.
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002482// TODO: remove local definition once upstreamed
Victor Hsieh18ac0272018-03-12 16:03:02 -07002483#ifndef FS_IOC_ENABLE_VERITY
2484
2485#define FS_IOC_ENABLE_VERITY _IO('f', 133)
2486#define FS_IOC_SET_VERITY_MEASUREMENT _IOW('f', 134, struct fsverity_measurement)
2487
2488#define FS_VERITY_ALG_SHA256 1
2489
2490struct fsverity_measurement {
2491 __u16 digest_algorithm;
2492 __u16 digest_size;
2493 __u32 reserved1;
2494 __u64 reserved2[3];
2495 __u8 digest[];
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002496};
2497
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002498#endif
2499
2500binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
Jiyong Park3b25ae12019-11-25 11:06:16 +09002501 android::base::unique_fd verityInputAshmem, int32_t contentSize) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002502 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002503 CHECK_ARGUMENT_PATH(filePath);
2504 std::lock_guard<std::recursive_mutex> lock(mLock);
2505
Victor Hsieh99de5162017-10-06 14:44:14 -07002506 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2507 return ok();
2508 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002509#ifndef NDEBUG
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002510 ASSERT_PAGE_SIZE_4K();
2511#endif
2512 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2513 // TODO: change ashmem to some temporary file to support huge apk.
2514 if (!ashmem_valid(verityInputAshmem.get())) {
2515 return error("FD is not an ashmem");
2516 }
2517
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002518 // 1. Seek to the next page boundary beyond the end of the file.
Victor Hsieh93a98052018-01-24 14:56:32 -08002519 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002520 if (wfd.get() < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002521 return error("Failed to open " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002522 }
2523 struct stat st;
2524 if (fstat(wfd.get(), &st) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002525 return error("Failed to stat " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002526 }
2527 // fsverity starts from the block boundary.
Victor Hsieh93a98052018-01-24 14:56:32 -08002528 off_t padding = kVerityPageSize - st.st_size % kVerityPageSize;
2529 if (padding == kVerityPageSize) {
2530 padding = 0;
2531 }
2532 if (lseek(wfd.get(), st.st_size + padding, SEEK_SET) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002533 return error("Failed to lseek " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002534 }
2535
Victor Hsieh18ac0272018-03-12 16:03:02 -07002536 // 2. Write everything in the ashmem to the file. Note that allocated
2537 // ashmem size is multiple of page size, which is different from the
2538 // actual content size.
2539 int shmSize = ashmem_get_size_region(verityInputAshmem.get());
2540 if (shmSize < 0) {
2541 return error("Failed to get ashmem size: " + std::to_string(shmSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002542 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002543 if (contentSize < 0) {
2544 return error("Invalid content size: " + std::to_string(contentSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002545 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002546 if (contentSize > shmSize) {
2547 return error("Content size overflow: " + std::to_string(contentSize) + " > " +
2548 std::to_string(shmSize));
2549 }
2550 auto data = std::unique_ptr<void, std::function<void (void *)>>(
Yi Konge7bf3772018-07-17 16:16:24 -07002551 mmap(nullptr, contentSize, PROT_READ, MAP_SHARED, verityInputAshmem.get(), 0),
Victor Hsieh18ac0272018-03-12 16:03:02 -07002552 [contentSize] (void* ptr) {
2553 if (ptr != MAP_FAILED) {
2554 munmap(ptr, contentSize);
2555 }
2556 });
2557
2558 if (data.get() == MAP_FAILED) {
2559 return error("Failed to mmap the ashmem");
2560 }
2561 char* cursor = reinterpret_cast<char*>(data.get());
2562 int remaining = contentSize;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002563 while (remaining > 0) {
Victor Hsieh93a98052018-01-24 14:56:32 -08002564 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), cursor, remaining));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002565 if (ret < 0) {
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002566 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
Victor Hsieh18ac0272018-03-12 16:03:02 -07002567 + "/" + std::to_string(contentSize) + ")");
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002568 }
Victor Hsieh93a98052018-01-24 14:56:32 -08002569 cursor += ret;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002570 remaining -= ret;
2571 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002572 wfd.reset();
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002573
Victor Hsieh18ac0272018-03-12 16:03:02 -07002574 // 3. Enable fsverity (needs readonly fd. Once it's done, the file becomes immutable.
2575 ::android::base::unique_fd rfd(open(filePath.c_str(), O_RDONLY));
2576 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, nullptr) < 0) {
2577 return error("Failed to enable fsverity on " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002578 }
2579 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002580}
2581
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002582binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2583 const std::vector<uint8_t>& expectedHash) {
2584 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002585 CHECK_ARGUMENT_PATH(filePath);
2586 std::lock_guard<std::recursive_mutex> lock(mLock);
2587
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002588 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2589 return ok();
2590 }
2591 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2592 if (expectedHash.size() != kSha256Size) {
2593 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2594 std::to_string(expectedHash.size()));
2595 }
2596
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002597 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2598 if (fd.get() < 0) {
2599 return error("Failed to open " + filePath + ": " + strerror(errno));
2600 }
2601
Victor Hsieh18ac0272018-03-12 16:03:02 -07002602 unsigned int buffer_size = sizeof(fsverity_measurement) + kSha256Size;
2603 std::vector<char> buffer(buffer_size, 0);
2604
2605 fsverity_measurement* config = reinterpret_cast<fsverity_measurement*>(buffer.data());
2606 config->digest_algorithm = FS_VERITY_ALG_SHA256;
2607 config->digest_size = kSha256Size;
2608 memcpy(config->digest, expectedHash.data(), kSha256Size);
2609 if (ioctl(fd.get(), FS_IOC_SET_VERITY_MEASUREMENT, config) < 0) {
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002610 // This includes an expected failure case with no FSVerity setup. It normally happens when
2611 // the apk does not contains the Merkle tree root hash.
2612 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2613 }
2614 return ok(); // hashes match
2615}
2616
Calin Juravlebd968362017-01-25 01:17:17 -08002617binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2618 const std::string& dexPath, const std::string& packageName, int32_t uid,
2619 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2620 int32_t storage_flag, bool* _aidl_return) {
2621 ENFORCE_UID(AID_SYSTEM);
2622 CHECK_ARGUMENT_UUID(volumeUuid);
2623 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002624 CHECK_ARGUMENT_PATH(dexPath);
Calin Juravlebd968362017-01-25 01:17:17 -08002625 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey53594302018-02-24 18:59:39 -07002626
Calin Juravlebd968362017-01-25 01:17:17 -08002627 bool result = android::installd::reconcile_secondary_dex_file(
2628 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2629 return result ? ok() : error();
2630}
2631
Alan Stokes753dc712017-10-16 10:56:00 +01002632binder::Status InstalldNativeService::hashSecondaryDexFile(
2633 const std::string& dexPath, const std::string& packageName, int32_t uid,
2634 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2635 std::vector<uint8_t>* _aidl_return) {
2636 ENFORCE_UID(AID_SYSTEM);
2637 CHECK_ARGUMENT_UUID(volumeUuid);
2638 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002639 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01002640
2641 // mLock is not taken here since we will never modify the file system.
2642 // If a file is modified just as we are reading it this may result in an
2643 // anomalous hash, but that's ok.
2644 bool result = android::installd::hash_secondary_dex_file(
2645 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2646 return result ? ok() : error();
2647}
2648
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002649binder::Status InstalldNativeService::invalidateMounts() {
2650 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002651 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002652
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002653 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06002654
2655#if !BYPASS_QUOTA
2656 if (!InvalidateQuotaMounts()) {
2657 return error("Failed to read mounts");
2658 }
2659#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002660
2661 std::ifstream in("/proc/mounts");
2662 if (!in.is_open()) {
2663 return error("Failed to read mounts");
2664 }
2665
2666 std::string source;
2667 std::string target;
2668 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002669 while (!in.eof()) {
2670 std::getline(in, source, ' ');
2671 std::getline(in, target, ' ');
2672 std::getline(in, ignored);
2673
Zim0ce832d2019-12-03 17:03:58 +00002674 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zimd4de6362019-12-12 16:22:27 +00002675 // TODO(b/146139106): Use sdcardfs mounts on devices running sdcardfs so we don't bypass
2676 // it's VFS cache
Zim0ce832d2019-12-03 17:03:58 +00002677 if (target.compare(0, 17, "/mnt/pass_through") == 0) {
2678 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2679 mStorageMounts[source] = target;
2680 }
2681 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002682#if !BYPASS_SDCARDFS
Zim0ce832d2019-12-03 17:03:58 +00002683 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2684 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2685 mStorageMounts[source] = target;
2686 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002687#endif
Zim0ce832d2019-12-03 17:03:58 +00002688 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002689 }
2690 return ok();
2691}
2692
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002693std::string InstalldNativeService::findDataMediaPath(
2694 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2695 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2696 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2697 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
Zimd4de6362019-12-12 16:22:27 +00002698 if (android::base::GetBoolProperty(kFuseProp, false)) {
2699 // TODO(b/146139106): This is only safe on devices not running sdcardfs where there is no
2700 // risk of bypassing the sdcardfs VFS cache
2701
2702 // Always use the lower filesystem path on FUSE enabled devices not running sdcardfs
2703 // The upper filesystem path, /mnt/pass_through/<userid>/<vol>/ which was a bind mount
2704 // to the lower filesytem may have been unmounted already when a user is
2705 // removed and the path will now be pointing to a tmpfs without content
2706 return StringPrintf("%s/%u", path.c_str(), userid);
2707 }
2708
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002709 auto resolved = mStorageMounts[path];
2710 if (resolved.empty()) {
2711 LOG(WARNING) << "Failed to find storage mount for " << path;
2712 resolved = path;
2713 }
2714 return StringPrintf("%s/%u", resolved.c_str(), userid);
2715}
2716
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002717binder::Status InstalldNativeService::isQuotaSupported(
Risan5f308262018-10-26 12:06:58 -06002718 const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
2719 auto uuidString = uuid ? *uuid : "";
2720 *_aidl_return = IsQuotaSupported(uuidString);
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002721 return ok();
2722}
2723
Calin Juravlebc5ab872018-01-18 22:32:58 -08002724binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
2725 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
2726 const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
2727 ENFORCE_UID(AID_SYSTEM);
2728 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002729 CHECK_ARGUMENT_PATH(codePath);
Calin Juravlebc5ab872018-01-18 22:32:58 -08002730 std::lock_guard<std::recursive_mutex> lock(mLock);
2731
2732 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
2733 dexMetadata);
2734 return ok();
2735}
2736
Narayan Kamath28ab93b2019-05-15 18:29:44 +01002737binder::Status InstalldNativeService::migrateLegacyObbData() {
2738 ENFORCE_UID(AID_SYSTEM);
2739 // NOTE: The lint warning doesn't apply to the use of system(3) with
2740 // absolute parse and no command line arguments.
2741 if (system("/system/bin/migrate_legacy_obb_data.sh") != 0) { // NOLINT(cert-env33-c)
2742 LOG(ERROR) << "Unable to migrate legacy obb data";
2743 }
2744
2745 return ok();
2746}
2747
Andreas Gampe02d0de52015-11-11 20:43:16 -08002748} // namespace installd
2749} // namespace android