blob: 054c88eb308a5693e0cb357d3c8220d997e463eb [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
Andreas Gampe02d0de52015-11-11 20:43:16 -080021#include <errno.h>
22#include <inttypes.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070025#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070027#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <sys/capability.h>
29#include <sys/file.h>
30#include <sys/resource.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070031#include <sys/quota.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070033#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070034#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000035#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070036#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070038
Andreas Gampeafa58d12016-06-03 16:09:32 -070039#include <android-base/logging.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080040#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070041#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010042#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080043#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070045#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070046#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070047#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070049#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080050#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070051#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070052
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070053#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070054#include "globals.h"
55#include "installd_deps.h"
56#include "otapreopt_utils.h"
57#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070058
Jeff Sharkey88ddd942017-01-17 18:05:54 -070059#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070060#include "MatchExtensionGen.h"
61
Andreas Gampe02d0de52015-11-11 20:43:16 -080062#ifndef LOG_TAG
63#define LOG_TAG "installd"
64#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070065
66using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070067using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070068
Andreas Gampe02d0de52015-11-11 20:43:16 -080069namespace android {
70namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070071
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070072static constexpr const char* kCpPath = "/system/bin/cp";
73static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070074
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070075static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000076
Andreas Gampe0354bd02016-06-27 14:25:30 -070077static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090081static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070082static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
83static constexpr const char* IDMAP_SUFFIX = "@idmap";
84
Andreas Gampe0354bd02016-06-27 14:25:30 -070085// NOTE: keep in sync with Installer
86static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
87static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070088static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070089static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070090static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
91static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -060092static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +000093
Jeff Sharkey0274c972016-12-06 09:32:04 -070094namespace {
95
96constexpr const char* kDump = "android.permission.DUMP";
97
Jeff Sharkey423e7462016-12-09 18:18:43 -070098static binder::Status ok() {
99 return binder::Status::ok();
100}
101
102static binder::Status exception(uint32_t code, const std::string& msg) {
103 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104}
105
106static binder::Status error() {
107 return binder::Status::fromServiceSpecificError(errno);
108}
109
110static binder::Status error(const std::string& msg) {
111 PLOG(ERROR) << msg;
112 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113}
114
115static binder::Status error(uint32_t code, const std::string& msg) {
116 LOG(ERROR) << msg << " (" << code << ")";
117 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
118}
119
Jeff Sharkey0274c972016-12-06 09:32:04 -0700120binder::Status checkPermission(const char* permission) {
121 pid_t pid;
122 uid_t uid;
123
124 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
125 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700126 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700127 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700128 return exception(binder::Status::EX_SECURITY,
129 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700130 }
131}
132
133binder::Status checkUid(uid_t expectedUid) {
134 uid_t uid = IPCThreadState::self()->getCallingUid();
135 if (uid == expectedUid || uid == AID_ROOT) {
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 is not expected UID %d", uid, expectedUid));
140 }
141}
142
143binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
144 if (!uuid || is_valid_filename(*uuid)) {
145 return ok();
146 } else {
147 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
148 StringPrintf("UUID %s is malformed", uuid->c_str()));
149 }
150}
151
152binder::Status checkArgumentPackageName(const std::string& packageName) {
153 if (is_valid_package_name(packageName.c_str())) {
154 return ok();
155 } else {
156 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
157 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700158 }
159}
160
161#define ENFORCE_UID(uid) { \
162 binder::Status status = checkUid((uid)); \
163 if (!status.isOk()) { \
164 return status; \
165 } \
166}
167
Jeff Sharkey423e7462016-12-09 18:18:43 -0700168#define CHECK_ARGUMENT_UUID(uuid) { \
169 binder::Status status = checkArgumentUuid((uuid)); \
170 if (!status.isOk()) { \
171 return status; \
172 } \
173}
174
175#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
176 binder::Status status = \
177 checkArgumentPackageName((packageName)); \
178 if (!status.isOk()) { \
179 return status; \
180 } \
181}
182
Jeff Sharkey0274c972016-12-06 09:32:04 -0700183} // namespace
184
185status_t InstalldNativeService::start() {
186 IPCThreadState::self()->disableBackgroundScheduling(true);
187 status_t ret = BinderService<InstalldNativeService>::publish();
188 if (ret != android::OK) {
189 return ret;
190 }
191 sp<ProcessState> ps(ProcessState::self());
192 ps->startThreadPool();
193 ps->giveThreadPoolName();
194 return android::OK;
195}
196
197status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700198 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700199 const binder::Status dump_permission = checkPermission(kDump);
200 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700201 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700202 return PERMISSION_DENIED;
203 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700204 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700205
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700206 out << "installd is happy!" << endl;
207
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700208 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600209 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
210 out << endl << "Storage mounts:" << endl;
211 for (const auto& n : mStorageMounts) {
212 out << " " << n.first << " = " << n.second << endl;
213 }
214
215 out << endl << "Quota reverse mounts:" << endl;
216 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700217 out << " " << n.first << " = " << n.second << endl;
218 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700219 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700220
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700221 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600222 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700223 out << endl << "Per-UID cache quotas:" << endl;
224 for (const auto& n : mCacheQuotas) {
225 out << " " << n.first << " = " << n.second << endl;
226 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700227 }
228
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700229 out << endl;
230 out.flush();
231
Jeff Sharkey0274c972016-12-06 09:32:04 -0700232 return NO_ERROR;
233}
234
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600235/**
236 * Perform restorecon of the given path, but only perform recursive restorecon
237 * if the label of that top-level file actually changed. This can save us
238 * significant time by avoiding no-op traversals of large filesystem trees.
239 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700240static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
241 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600242 int res = 0;
243 char* before = nullptr;
244 char* after = nullptr;
245
246 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
247 // libselinux. Not needed here.
248
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600249 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600250 PLOG(ERROR) << "Failed before getfilecon for " << path;
251 goto fail;
252 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700253 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600254 PLOG(ERROR) << "Failed top-level restorecon for " << path;
255 goto fail;
256 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600257 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600258 PLOG(ERROR) << "Failed after getfilecon for " << path;
259 goto fail;
260 }
261
262 // If the initial top-level restorecon above changed the label, then go
263 // back and restorecon everything recursively
264 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700265 if (existing) {
266 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
267 << path << "; running recursive restorecon";
268 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700269 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600270 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
271 PLOG(ERROR) << "Failed recursive restorecon for " << path;
272 goto fail;
273 }
274 }
275
276 goto done;
277fail:
278 res = -1;
279done:
280 free(before);
281 free(after);
282 return res;
283}
284
Jeff Sharkey0274c972016-12-06 09:32:04 -0700285static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700286 const std::string& seInfo, uid_t uid, bool existing) {
287 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
288 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600289}
290
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600291static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600292 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
293 PLOG(ERROR) << "Failed to prepare " << path;
294 return -1;
295 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600296 return 0;
297}
298
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600299/**
300 * Ensure that we have a hard-limit quota to protect against abusive apps;
301 * they should never use more than 90% of blocks or 50% of inodes.
302 */
303static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
304 uid_t uid) {
305 if (device.empty()) return 0;
306
307 struct dqblk dq;
308 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
309 reinterpret_cast<char*>(&dq)) != 0) {
310 PLOG(WARNING) << "Failed to find quota for " << uid;
311 return -1;
312 }
313
314 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
315 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
316 struct statvfs stat;
317 if (statvfs(path.c_str(), &stat) != 0) {
318 PLOG(WARNING) << "Failed to statvfs " << path;
319 return -1;
320 }
321
322 dq.dqb_valid = QIF_LIMITS;
Jerry Wonge761ac32017-07-28 15:54:58 -0700323 dq.dqb_bhardlimit =
324 (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600325 dq.dqb_ihardlimit = (stat.f_files / 2);
326 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
327 reinterpret_cast<char*>(&dq)) != 0) {
328 PLOG(WARNING) << "Failed to set hard quota for " << uid;
329 return -1;
330 } else {
331 LOG(DEBUG) << "Applied hard quotas for " << uid;
332 return 0;
333 }
334 } else {
335 // Hard quota already set; assume it's reasonable
336 return 0;
337 }
338}
339
Jeff Sharkey0274c972016-12-06 09:32:04 -0700340binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
341 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700342 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700343 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700344 CHECK_ARGUMENT_UUID(uuid);
345 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700346 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700347
348 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
349 const char* pkgname = packageName.c_str();
350
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700351 // Assume invalid inode unless filled in below
352 if (_aidl_return != nullptr) *_aidl_return = -1;
353
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700354 int32_t uid = multiuser_get_uid(userId, appId);
355 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700356 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
357
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700358 // If UID doesn't have a specific cache GID, use UID value
359 if (cacheGid == -1) {
360 cacheGid = uid;
361 }
362
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700363 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700364 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700365 bool existing = (access(path.c_str(), F_OK) == 0);
366
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700367 if (prepare_app_dir(path, targetMode, uid) ||
368 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
369 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700370 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600371 }
372
373 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700374 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
375 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
376 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700377 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700378 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600379
380 // Remember inode numbers of cache directories so that we can clear
381 // contents while CE storage is locked
382 if (write_path_inode(path, "cache", kXattrInodeCache) ||
383 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700384 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700385 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700386
387 // And return the CE inode of the top-level data directory so we can
388 // clear contents while CE storage is locked
389 if ((_aidl_return != nullptr)
390 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
391 return error("Failed to get_path_inode for " + path);
392 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700393 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700394 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700395 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700396 bool existing = (access(path.c_str(), F_OK) == 0);
397
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700398 if (prepare_app_dir(path, targetMode, uid) ||
399 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
400 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700401 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700402 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000403
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600404 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600405 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
406 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
407 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700408 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600409 }
410
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600411 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
412 return error("Failed to set hard quota " + path);
413 }
414
Jeff Sharkey90aff262016-12-12 14:28:24 -0700415 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800416 const std::string profile_dir =
417 create_primary_current_profile_package_dir_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000418 // read-write-execute only for the app user.
Calin Juravle114f0812017-03-08 19:05:07 -0800419 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
420 return error("Failed to prepare " + profile_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000421 }
Calin Juravle114f0812017-03-08 19:05:07 -0800422 const std::string profile_file = create_current_profile_path(userId, pkgname,
423 /*is_secondary_dex*/false);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100424 // read-write only for the app user.
425 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800426 return error("Failed to prepare " + profile_file);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100427 }
Calin Juravle114f0812017-03-08 19:05:07 -0800428 const std::string ref_profile_path =
429 create_primary_reference_profile_package_dir_path(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000430 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
431 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700432 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700433 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000434 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700435 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000436 }
437 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700438 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700439 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700440}
441
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700442binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
443 const std::string& packageName, int32_t userId, int32_t flags) {
444 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700445 CHECK_ARGUMENT_UUID(uuid);
446 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700447 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700448
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700449 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
450 const char* pkgname = packageName.c_str();
451
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700452 // This method only exists to upgrade system apps that have requested
453 // forceDeviceEncrypted, so their default storage always lives in a
454 // consistent location. This only works on non-FBE devices, since we
455 // never want to risk exposing data on a device with real CE/DE storage.
456
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700457 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
458 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700459
460 // If neither directory is marked as default, assume CE is default
461 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
462 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
463 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700464 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700465 }
466 }
467
468 // Migrate default data location if needed
469 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
470 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
471
472 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
473 LOG(WARNING) << "Requested default storage " << target
474 << " is not active; migrating from " << source;
475 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700476 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700477 }
478 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700479 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700480 }
481 }
482
Jeff Sharkey423e7462016-12-09 18:18:43 -0700483 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700484}
485
Calin Juravle6a1648e2016-02-01 12:12:16 +0000486
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700487binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
488 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700490 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700491
Jeff Sharkey423e7462016-12-09 18:18:43 -0700492 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800493 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700494 res = error("Failed to clear reference profile for " + packageName);
495 }
Calin Juravle114f0812017-03-08 19:05:07 -0800496 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700497 res = error("Failed to clear current profiles for " + packageName);
498 }
499 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000500}
501
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700502binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
503 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
504 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700505 CHECK_ARGUMENT_UUID(uuid);
506 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700507 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700508
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700509 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
510 const char* pkgname = packageName.c_str();
511
Jeff Sharkey423e7462016-12-09 18:18:43 -0700512 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700513 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700514 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600515 if (flags & FLAG_CLEAR_CACHE_ONLY) {
516 path = read_path_inode(path, "cache", kXattrInodeCache);
517 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
518 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
519 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700520 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 if (delete_dir_contents(path) != 0) {
522 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900523 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
524 remove_path_xattr(path, kXattrInodeCache);
525 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700526 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700527 }
528 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700529 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600530 std::string suffix = "";
531 bool only_cache = false;
532 if (flags & FLAG_CLEAR_CACHE_ONLY) {
533 suffix = CACHE_DIR_POSTFIX;
534 only_cache = true;
535 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
536 suffix = CODE_CACHE_DIR_POSTFIX;
537 only_cache = true;
538 }
539
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700540 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700541 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700542 if (delete_dir_contents(path) != 0) {
543 res = error("Failed to delete contents of " + path);
544 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700545 }
Calin Juravleedae6692016-03-23 13:55:31 +0000546 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800547 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700548 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000549 }
550 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700551 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700552 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700553}
554
Calin Juravle76268c52017-03-09 13:19:42 -0800555static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100556 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800557 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100558 /*ignore_if_missing*/ true);
559}
560
Calin Juravle76268c52017-03-09 13:19:42 -0800561static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100562 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800563 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100564 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000565}
566
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700567binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
568 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700569 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700570 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700571
Jeff Sharkey423e7462016-12-09 18:18:43 -0700572 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000573 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
574 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800575 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700576 res = error("Failed to destroy current profiles for " + packageName);
577 }
Calin Juravleedae6692016-03-23 13:55:31 +0000578 }
Calin Juravle76268c52017-03-09 13:19:42 -0800579 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700580 res = error("Failed to destroy reference profile for " + packageName);
581 }
582 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000583}
584
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700585binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
586 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
587 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700588 CHECK_ARGUMENT_UUID(uuid);
589 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700590 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700591
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700592 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
593 const char* pkgname = packageName.c_str();
594
Jeff Sharkey423e7462016-12-09 18:18:43 -0700595 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700596 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700597 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
598 if (delete_dir_contents_and_dir(path) != 0) {
599 res = error("Failed to delete " + path);
600 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700601 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700602 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700603 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
604 if (delete_dir_contents_and_dir(path) != 0) {
605 res = error("Failed to delete " + path);
606 }
Calin Juravle76268c52017-03-09 13:19:42 -0800607 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100608 // TODO(calin): If the package is still installed by other users it's probably
609 // beneficial to keep the reference profile around.
610 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800611 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700612 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700613 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700614}
615
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600616static gid_t get_cache_gid(uid_t uid) {
617 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
618 return (gid != -1) ? gid : uid;
619}
620
621binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
622 int32_t flags) {
623 ENFORCE_UID(AID_SYSTEM);
624 CHECK_ARGUMENT_UUID(uuid);
625 std::lock_guard<std::recursive_mutex> lock(mLock);
626
627 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
628 for (auto user : get_known_users(uuid_)) {
629 ATRACE_BEGIN("fixup user");
630 FTS* fts;
631 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600632 auto ce_path = create_data_user_ce_path(uuid_, user);
633 auto de_path = create_data_user_de_path(uuid_, user);
634 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600635 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
636 return error("Failed to fts_open");
637 }
638 while ((p = fts_read(fts)) != nullptr) {
639 if (p->fts_info == FTS_D && p->fts_level == 1) {
640 // Track down inodes of cache directories
641 uint64_t raw = 0;
642 ino_t inode_cache = 0;
643 ino_t inode_code_cache = 0;
644 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
645 inode_cache = raw;
646 }
647 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
648 inode_code_cache = raw;
649 }
650
651 // Figure out expected GID of each child
652 FTSENT* child = fts_children(fts, 0);
653 while (child != nullptr) {
654 if ((child->fts_statp->st_ino == inode_cache)
655 || (child->fts_statp->st_ino == inode_code_cache)
656 || !strcmp(child->fts_name, "cache")
657 || !strcmp(child->fts_name, "code_cache")) {
658 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
659 } else {
660 child->fts_number = p->fts_statp->st_uid;
661 }
662 child = child->fts_link;
663 }
664 } else if (p->fts_level >= 2) {
665 if (p->fts_level > 2) {
666 // Inherit GID from parent once we're deeper into tree
667 p->fts_number = p->fts_parent->fts_number;
668 }
669
670 uid_t uid = p->fts_parent->fts_statp->st_uid;
671 gid_t cache_gid = get_cache_gid(uid);
672 gid_t expected = p->fts_number;
673 gid_t actual = p->fts_statp->st_gid;
674 if (actual == expected) {
675#if FIXUP_DEBUG
676 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
677#endif
678 if (!(flags & FLAG_FORCE)) {
679 fts_set(fts, p, FTS_SKIP);
680 }
681 } else if ((actual == uid) || (actual == cache_gid)) {
682 // Only consider fixing up when current GID belongs to app
683 if (p->fts_info != FTS_D) {
684 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
685 << " instead of " << expected;
686 }
687 switch (p->fts_info) {
688 case FTS_DP:
689 // If we're moving towards cache GID, we need to set S_ISGID
690 if (expected == cache_gid) {
691 if (chmod(p->fts_path, 02771) != 0) {
692 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
693 }
694 }
695 // Intentional fall through to also set GID
696 case FTS_F:
697 if (chown(p->fts_path, -1, expected) != 0) {
698 PLOG(WARNING) << "Failed to chown " << p->fts_path;
699 }
700 break;
701 case FTS_SL:
702 case FTS_SLNONE:
703 if (lchown(p->fts_path, -1, expected) != 0) {
704 PLOG(WARNING) << "Failed to chown " << p->fts_path;
705 }
706 break;
707 }
708 } else {
709 // Ignore all other GID transitions, since they're kinda shady
710 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
711 << " instead of " << expected;
712 }
713 }
714 }
715 fts_close(fts);
716 ATRACE_END();
717 }
718 return ok();
719}
720
Jeff Sharkey0274c972016-12-06 09:32:04 -0700721binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
722 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
723 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
724 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700725 ENFORCE_UID(AID_SYSTEM);
726 CHECK_ARGUMENT_UUID(fromUuid);
727 CHECK_ARGUMENT_UUID(toUuid);
728 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700729 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700730
731 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
732 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
733 const char* package_name = packageName.c_str();
734 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700735
Jeff Sharkey423e7462016-12-09 18:18:43 -0700736 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700737 std::vector<userid_t> users = get_known_users(from_uuid);
738
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700739 // Copy app
740 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600741 auto from = create_data_app_package_path(from_uuid, data_app_name);
742 auto to = create_data_app_package_path(to_uuid, data_app_name);
743 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700744
745 char *argv[] = {
746 (char*) kCpPath,
747 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
748 (char*) "-p", /* preserve timestamps, ownership, and permissions */
749 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
750 (char*) "-P", /* Do not follow symlinks [default] */
751 (char*) "-d", /* don't dereference symlinks */
752 (char*) from.c_str(),
753 (char*) to_parent.c_str()
754 };
755
756 LOG(DEBUG) << "Copying " << from << " to " << to;
757 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700758 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700759 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700760 goto fail;
761 }
762
763 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700764 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700765 goto fail;
766 }
767 }
768
769 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700770 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700771
772 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600773 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
774 if (access(from_ce.c_str(), F_OK) != 0) {
775 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700776 continue;
777 }
778
Jeff Sharkey0274c972016-12-06 09:32:04 -0700779 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700780 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700781 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700782 goto fail;
783 }
784
785 char *argv[] = {
786 (char*) kCpPath,
787 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
788 (char*) "-p", /* preserve timestamps, ownership, and permissions */
789 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
790 (char*) "-P", /* Do not follow symlinks [default] */
791 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600792 nullptr,
793 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700794 };
795
Jeff Sharkey51c94492016-05-10 17:46:39 -0600796 {
797 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
798 auto to = create_data_user_de_path(to_uuid, user);
799 argv[6] = (char*) from.c_str();
800 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700801
Jeff Sharkey51c94492016-05-10 17:46:39 -0600802 LOG(DEBUG) << "Copying " << from << " to " << to;
803 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
804 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700805 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600806 goto fail;
807 }
808 }
809 {
810 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
811 auto to = create_data_user_ce_path(to_uuid, user);
812 argv[6] = (char*) from.c_str();
813 argv[7] = (char*) to.c_str();
814
815 LOG(DEBUG) << "Copying " << from << " to " << to;
816 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
817 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700818 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600819 goto fail;
820 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700821 }
822
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700823 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
824 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700825 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700826 goto fail;
827 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700828 }
829
Jeff Sharkey31f08982015-07-07 13:31:37 -0700830 // We let the framework scan the new location and persist that before
831 // deleting the data in the old location; this ordering ensures that
832 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700833 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700834
835fail:
836 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700837 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600838 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700839 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
840 LOG(WARNING) << "Failed to rollback " << to;
841 }
842 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700843 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600844 {
845 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
846 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
847 LOG(WARNING) << "Failed to rollback " << to;
848 }
849 }
850 {
851 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
852 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
853 LOG(WARNING) << "Failed to rollback " << to;
854 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700855 }
856 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700857 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700858}
859
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700860binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
861 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
862 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700863 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700864 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700865
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700866 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600867 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700868 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700869 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700870 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700871 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700872 }
873 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600874
875 // Data under /data/media doesn't have an app, but we still want
876 // to limit it to prevent abuse.
877 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
878 multiuser_get_uid(userId, AID_MEDIA_RW))) {
879 return error("Failed to set hard quota for media_rw");
880 }
881
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700882 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700883}
884
885binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
886 int32_t userId, int32_t flags) {
887 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700888 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700889 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700890
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700891 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700892 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700893 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700894 auto path = create_data_user_de_path(uuid_, userId);
895 if (delete_dir_contents_and_dir(path, true) != 0) {
896 res = error("Failed to delete " + path);
897 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700898 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700899 path = create_data_misc_legacy_path(userId);
900 if (delete_dir_contents_and_dir(path, true) != 0) {
901 res = error("Failed to delete " + path);
902 }
Calin Juravle114f0812017-03-08 19:05:07 -0800903 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700904 if (delete_dir_contents_and_dir(path, true) != 0) {
905 res = error("Failed to delete " + path);
906 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700907 }
Robin Lee095c7632014-04-25 15:05:19 +0100908 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600909 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700910 auto path = create_data_user_ce_path(uuid_, userId);
911 if (delete_dir_contents_and_dir(path, true) != 0) {
912 res = error("Failed to delete " + path);
913 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600914 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700915 if (delete_dir_contents_and_dir(path, true) != 0) {
916 res = error("Failed to delete " + path);
917 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600918 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700919 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100920}
921
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700922binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600923 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700924 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700925 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700926 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700927
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700928 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700929 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700930 auto device = findQuotaDeviceForUuid(uuid);
931 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700932
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700933 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700934 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700935 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700936 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700937
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600938 int64_t cleared = 0;
939 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600940 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600941 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600942
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600943 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600944 return ok();
945 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700946
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700947 if (flags & FLAG_FREE_CACHE_V2) {
948 // This new cache strategy fairly removes files from UIDs by deleting
949 // files from the UIDs which are most over their allocated quota
950
951 // 1. Create trackers for every known UID
952 ATRACE_BEGIN("create");
953 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
954 for (auto user : get_known_users(uuid_)) {
955 FTS *fts;
956 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600957 auto ce_path = create_data_user_ce_path(uuid_, user);
958 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600959 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
960 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
961 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700962 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700963 return error("Failed to fts_open");
964 }
965 while ((p = fts_read(fts)) != NULL) {
966 if (p->fts_info == FTS_D && p->fts_level == 1) {
967 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600968 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
969 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
970 + AID_APP_START;
971 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700972 auto search = trackers.find(uid);
973 if (search != trackers.end()) {
974 search->second->addDataPath(p->fts_path);
975 } else {
976 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
977 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
978 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700979 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600980 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700981 tracker->cacheQuota = mCacheQuotas[uid];
982 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700983 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600984#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700985 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600986#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700987 tracker->cacheQuota = 67108864;
988 }
989 trackers[uid] = tracker;
990 }
991 fts_set(fts, p, FTS_SKIP);
992 }
993 }
994 fts_close(fts);
995 }
996 ATRACE_END();
997
998 // 2. Populate tracker stats and insert into priority queue
999 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001000 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001001 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1002 return (left->getCacheRatio() < right->getCacheRatio());
1003 };
1004 std::priority_queue<std::shared_ptr<CacheTracker>,
1005 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1006 for (const auto& it : trackers) {
1007 it.second->loadStats();
1008 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001009 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001010 }
1011 ATRACE_END();
1012
1013 // 3. Bounce across the queue, freeing items from whichever tracker is
1014 // the most over their assigned quota
1015 ATRACE_BEGIN("bounce");
1016 std::shared_ptr<CacheTracker> active;
1017 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001018 // Only look at apps under quota when explicitly requested
1019 if (active && (active->getCacheRatio() < 10000)
1020 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1021 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1022 << " isn't over quota, and defy not requested";
1023 break;
1024 }
1025
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001026 // Only keep clearing when we haven't pushed into reserved area
1027 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1028 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1029 break;
1030 }
1031
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001032 // Find the best tracker to work with; this might involve swapping
1033 // if the active tracker is no longer the most over quota
1034 bool nextBetter = active && !queue.empty()
1035 && active->getCacheRatio() < queue.top()->getCacheRatio();
1036 if (!active || nextBetter) {
1037 if (active) {
1038 // Current tracker still has items, so we'll consider it
1039 // again later once it bubbles up to surface
1040 queue.push(active);
1041 }
1042 active = queue.top(); queue.pop();
1043 active->ensureItems();
1044 continue;
1045 }
1046
1047 // If no items remain, go find another tracker
1048 if (active->items.empty()) {
1049 active = nullptr;
1050 continue;
1051 } else {
1052 auto item = active->items.back();
1053 active->items.pop_back();
1054
1055 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1056 if (!noop) {
1057 item->purge();
1058 }
1059 active->cacheUsed -= item->size;
1060 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001061 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001062 }
1063
1064 // Verify that we're actually done before bailing, since sneaky
1065 // apps might be using hardlinks
1066 if (needed <= 0) {
1067 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001068 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001069 if (needed <= 0) {
1070 break;
1071 } else {
1072 LOG(WARNING) << "Expected to be done but still need " << needed;
1073 }
1074 }
1075 }
1076 ATRACE_END();
1077
1078 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001079 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001080 }
1081
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001082 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001083 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001084 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001085 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001086 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001087 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001088 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001089}
1090
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001091binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1092 const std::string& instructionSet) {
1093 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001094 std::lock_guard<std::recursive_mutex> lock(mLock);
1095
Mike Lockwood94afecf2012-10-24 10:45:23 -07001096 char dex_path[PKG_PATH_MAX];
1097
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001098 const char* path = codePath.c_str();
1099 const char* instruction_set = instructionSet.c_str();
1100
Jeff Sharkey770180a2014-09-08 17:14:26 -07001101 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001102 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001103 }
1104
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001105 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001106 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001107 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001108
1109 ALOGV("unlink %s\n", dex_path);
1110 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001111 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1112 // but could not be unlinked.
1113 if (errno != ENOENT) {
1114 return error(StringPrintf("Failed to unlink %s", dex_path));
1115 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001116 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001117 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001118}
1119
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001120struct stats {
1121 int64_t codeSize;
1122 int64_t dataSize;
1123 int64_t cacheSize;
1124};
1125
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001126#if MEASURE_DEBUG
1127static std::string toString(std::vector<int64_t> values) {
1128 std::stringstream res;
1129 res << "[";
1130 for (size_t i = 0; i < values.size(); i++) {
1131 res << values[i];
1132 if (i < values.size() - 1) {
1133 res << ",";
1134 }
1135 }
1136 res << "]";
1137 return res.str();
1138}
1139#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001140
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001141static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001142 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001143 if (device.empty()) return;
1144
1145 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001146
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001147 if (stats != nullptr) {
1148 uid_t uid = multiuser_get_uid(userId, appId);
1149 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001150 reinterpret_cast<char*>(&dq)) != 0) {
1151 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001152 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001153 }
1154 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001155#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001156 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001157#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001158 stats->dataSize += dq.dqb_curspace;
1159 }
1160
1161 int cacheGid = multiuser_get_cache_gid(userId, appId);
1162 if (cacheGid != -1) {
1163 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1164 reinterpret_cast<char*>(&dq)) != 0) {
1165 if (errno != ESRCH) {
1166 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1167 }
1168 } else {
1169#if MEASURE_DEBUG
1170 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1171#endif
1172 stats->cacheSize += dq.dqb_curspace;
1173 }
1174 }
1175
1176 int sharedGid = multiuser_get_shared_gid(0, appId);
1177 if (sharedGid != -1) {
1178 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1179 reinterpret_cast<char*>(&dq)) != 0) {
1180 if (errno != ESRCH) {
1181 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1182 }
1183 } else {
1184#if MEASURE_DEBUG
1185 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1186#endif
1187 stats->codeSize += dq.dqb_curspace;
1188 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001189 }
1190 }
1191
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001192 if (extStats != nullptr) {
1193 int extGid = multiuser_get_ext_gid(userId, appId);
1194 if (extGid != -1) {
1195 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1196 reinterpret_cast<char*>(&dq)) != 0) {
1197 if (errno != ESRCH) {
1198 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1199 }
1200 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001201#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001202 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001203#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001204 extStats->dataSize += dq.dqb_curspace;
1205 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001206 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001207
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001208 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1209 if (extCacheGid != -1) {
1210 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1211 reinterpret_cast<char*>(&dq)) != 0) {
1212 if (errno != ESRCH) {
1213 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1214 }
1215 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001216#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001217 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001218#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001219 extStats->dataSize += dq.dqb_curspace;
1220 extStats->cacheSize += dq.dqb_curspace;
1221 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001222 }
1223 }
1224}
1225
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001226static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001227 DIR *d;
1228 int dfd;
1229 struct dirent *de;
1230 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001231
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001232 d = opendir(path.c_str());
1233 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001234 if (errno != ENOENT) {
1235 PLOG(WARNING) << "Failed to open " << path;
1236 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001237 return;
1238 }
1239 dfd = dirfd(d);
1240 while ((de = readdir(d))) {
1241 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001242
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001243 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001244 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001245 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001246 }
1247
1248 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001249 if (!strcmp(name, ".")) {
1250 // Don't recurse, but still count node size
1251 } else if (!strcmp(name, "..")) {
1252 // Don't recurse or count node size
1253 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001254 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001255 // Measure all children nodes
1256 size = 0;
1257 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001258 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001259
1260 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1261 stats->cacheSize += size;
1262 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001263 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001264
1265 // Legacy symlink isn't owned by app
1266 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1267 continue;
1268 }
1269
1270 // Everything found inside is considered data
1271 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001272 }
1273 closedir(d);
1274}
1275
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001276static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1277 bool exclude_apps = false) {
1278 DIR *d;
1279 int dfd;
1280 struct dirent *de;
1281 struct stat s;
1282
1283 d = opendir(path.c_str());
1284 if (d == nullptr) {
1285 if (errno != ENOENT) {
1286 PLOG(WARNING) << "Failed to open " << path;
1287 }
1288 return;
1289 }
1290 dfd = dirfd(d);
1291 while ((de = readdir(d))) {
1292 if (de->d_type == DT_DIR) {
1293 const char *name = de->d_name;
1294 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1295 continue;
1296 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001297 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001298 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1299 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001300 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001301 continue;
1302 } else {
1303 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1304 }
1305 }
1306 }
1307 closedir(d);
1308}
1309
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001310static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1311 FTS *fts;
1312 FTSENT *p;
1313 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001314 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001315 PLOG(ERROR) << "Failed to fts_open " << path;
1316 return;
1317 }
1318 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001319 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001320 switch (p->fts_info) {
1321 case FTS_D:
1322 if (p->fts_level == 4
1323 && !strcmp(p->fts_name, "cache")
1324 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1325 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1326 p->fts_number = 1;
1327 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001328 // Fall through to count the directory
1329 case FTS_DEFAULT:
1330 case FTS_F:
1331 case FTS_SL:
1332 case FTS_SLNONE:
1333 int64_t size = (p->fts_statp->st_blocks * 512);
1334 if (p->fts_number == 1) {
1335 stats->cacheSize += size;
1336 }
1337 stats->dataSize += size;
1338 break;
1339 }
1340 }
1341 fts_close(fts);
1342}
1343
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001344binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001345 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1346 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1347 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001348 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001349 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001350 for (auto packageName : packageNames) {
1351 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1352 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001353 // NOTE: Locking is relaxed on this method, since it's limited to
1354 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001355
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001356 // When modifying this logic, always verify using tests:
1357 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1358
1359#if MEASURE_DEBUG
1360 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1361#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001362
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001363 // Here's a summary of the common storage locations across the platform,
1364 // and how they're each tagged:
1365 //
1366 // /data/app/com.example UID system
1367 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001368 // /data/user/0/com.example UID u0_a10 GID u0_a10
1369 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1370 // /data/media/0/foo.txt UID u0_media_rw
1371 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1372 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1373 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1374 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001375
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001376 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001377 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001378 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001379 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001380
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001381 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001382
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001383 auto device = findQuotaDeviceForUuid(uuid);
1384 if (device.empty()) {
1385 flags &= ~FLAG_USE_QUOTA;
1386 }
1387
Jeff Sharkey466459b2017-01-17 15:25:01 -07001388 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001389 for (auto packageName : packageNames) {
1390 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1391 calculate_tree_size(obbCodePath, &extStats.codeSize);
1392 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001393 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001394
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001395 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001396 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001397 for (auto codePath : codePaths) {
1398 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001399 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001400 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001401 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001402
Jeff Sharkey466459b2017-01-17 15:25:01 -07001403 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001404 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001405 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001406 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001407 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001408 for (auto codePath : codePaths) {
1409 calculate_tree_size(codePath, &stats.codeSize);
1410 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001411 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001412
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001413 for (size_t i = 0; i < packageNames.size(); i++) {
1414 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001415
Jeff Sharkey466459b2017-01-17 15:25:01 -07001416 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001417 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1418 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001419 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1420 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001421 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001422
Jeff Sharkey06a61842017-04-15 12:03:31 -06001423 if (!uuid) {
1424 ATRACE_BEGIN("profiles");
1425 calculate_tree_size(
1426 create_primary_current_profile_package_dir_path(userId, pkgname),
1427 &stats.dataSize);
1428 calculate_tree_size(
1429 create_primary_reference_profile_package_dir_path(pkgname),
1430 &stats.codeSize);
1431 ATRACE_END();
1432 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001433
Jeff Sharkey466459b2017-01-17 15:25:01 -07001434 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001435 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001436 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001437 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001438 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001439 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001440 }
1441
Jeff Sharkey06a61842017-04-15 12:03:31 -06001442 if (!uuid) {
1443 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001444 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001445 if (sharedGid != -1) {
1446 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1447 sharedGid, -1);
1448 }
1449 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001450 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001451 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001452
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001453 std::vector<int64_t> ret;
1454 ret.push_back(stats.codeSize);
1455 ret.push_back(stats.dataSize);
1456 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001457 ret.push_back(extStats.codeSize);
1458 ret.push_back(extStats.dataSize);
1459 ret.push_back(extStats.cacheSize);
1460#if MEASURE_DEBUG
1461 LOG(DEBUG) << "Final result " << toString(ret);
1462#endif
1463 *_aidl_return = ret;
1464 return ok();
1465}
1466
1467binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1468 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1469 std::vector<int64_t>* _aidl_return) {
1470 ENFORCE_UID(AID_SYSTEM);
1471 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001472 // NOTE: Locking is relaxed on this method, since it's limited to
1473 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001474
1475 // When modifying this logic, always verify using tests:
1476 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1477
1478#if MEASURE_DEBUG
1479 LOG(INFO) << "Measuring user " << userId;
1480#endif
1481
1482 struct stats stats;
1483 struct stats extStats;
1484 memset(&stats, 0, sizeof(stats));
1485 memset(&extStats, 0, sizeof(extStats));
1486
1487 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1488
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001489 auto device = findQuotaDeviceForUuid(uuid);
1490 if (device.empty()) {
1491 flags &= ~FLAG_USE_QUOTA;
1492 }
1493
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001494 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001495 struct dqblk dq;
1496
1497 ATRACE_BEGIN("obb");
1498 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1499 reinterpret_cast<char*>(&dq)) != 0) {
1500 if (errno != ESRCH) {
1501 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1502 }
1503 } else {
1504#if MEASURE_DEBUG
1505 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1506#endif
1507 extStats.codeSize += dq.dqb_curspace;
1508 }
1509 ATRACE_END();
1510
Jeff Sharkey466459b2017-01-17 15:25:01 -07001511 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001512 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001513 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001514
Jeff Sharkey466459b2017-01-17 15:25:01 -07001515 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001516 auto cePath = create_data_user_ce_path(uuid_, userId);
1517 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001518 auto dePath = create_data_user_de_path(uuid_, userId);
1519 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001520 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001521
Jeff Sharkey06a61842017-04-15 12:03:31 -06001522 if (!uuid) {
1523 ATRACE_BEGIN("profile");
1524 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1525 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1526 auto refProfilePath = create_primary_ref_profile_dir_path();
1527 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1528 ATRACE_END();
1529 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001530
Jeff Sharkey466459b2017-01-17 15:25:01 -07001531 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001532 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1533 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1534 reinterpret_cast<char*>(&dq)) != 0) {
1535 if (errno != ESRCH) {
1536 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1537 }
1538 } else {
1539#if MEASURE_DEBUG
1540 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001541#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001542 extStats.dataSize += dq.dqb_curspace;
1543 }
1544 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001545
Jeff Sharkey06a61842017-04-15 12:03:31 -06001546 if (!uuid) {
1547 ATRACE_BEGIN("dalvik");
1548 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1549 -1, -1, true);
1550 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1551 -1, -1, true);
1552 ATRACE_END();
1553 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001554
Jeff Sharkey466459b2017-01-17 15:25:01 -07001555 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001556 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001557 for (auto appId : appIds) {
1558 if (appId >= AID_APP_START) {
1559 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001560
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001561#if MEASURE_DEBUG
1562 // Sleep to make sure we don't lose logs
1563 usleep(1);
1564#endif
1565 }
1566 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001567 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001568 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001569 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001570 ATRACE_BEGIN("obb");
1571 auto obbPath = create_data_path(uuid_) + "/media/obb";
1572 calculate_tree_size(obbPath, &extStats.codeSize);
1573 ATRACE_END();
1574
Jeff Sharkey466459b2017-01-17 15:25:01 -07001575 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001576 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001577 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001578
Jeff Sharkey466459b2017-01-17 15:25:01 -07001579 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001580 auto cePath = create_data_user_ce_path(uuid_, userId);
1581 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001582 auto dePath = create_data_user_de_path(uuid_, userId);
1583 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001584 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001585
Jeff Sharkey06a61842017-04-15 12:03:31 -06001586 if (!uuid) {
1587 ATRACE_BEGIN("profile");
1588 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1589 calculate_tree_size(userProfilePath, &stats.dataSize);
1590 auto refProfilePath = create_primary_ref_profile_dir_path();
1591 calculate_tree_size(refProfilePath, &stats.codeSize);
1592 ATRACE_END();
1593 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001594
Jeff Sharkey466459b2017-01-17 15:25:01 -07001595 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001596 auto dataMediaPath = create_data_media_path(uuid_, userId);
1597 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1598#if MEASURE_DEBUG
1599 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1600 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001601#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001602 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001603
Jeff Sharkey06a61842017-04-15 12:03:31 -06001604 if (!uuid) {
1605 ATRACE_BEGIN("dalvik");
1606 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1607 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1608 ATRACE_END();
1609 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001610 }
1611
1612 std::vector<int64_t> ret;
1613 ret.push_back(stats.codeSize);
1614 ret.push_back(stats.dataSize);
1615 ret.push_back(stats.cacheSize);
1616 ret.push_back(extStats.codeSize);
1617 ret.push_back(extStats.dataSize);
1618 ret.push_back(extStats.cacheSize);
1619#if MEASURE_DEBUG
1620 LOG(DEBUG) << "Final result " << toString(ret);
1621#endif
1622 *_aidl_return = ret;
1623 return ok();
1624}
1625
1626binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001627 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1628 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001629 ENFORCE_UID(AID_SYSTEM);
1630 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001631 // NOTE: Locking is relaxed on this method, since it's limited to
1632 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001633
1634 // When modifying this logic, always verify using tests:
1635 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1636
1637#if MEASURE_DEBUG
1638 LOG(INFO) << "Measuring external " << userId;
1639#endif
1640
1641 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1642
1643 int64_t totalSize = 0;
1644 int64_t audioSize = 0;
1645 int64_t videoSize = 0;
1646 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001647 int64_t appSize = 0;
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001648 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001649
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001650 auto device = findQuotaDeviceForUuid(uuid);
1651 if (device.empty()) {
1652 flags &= ~FLAG_USE_QUOTA;
1653 }
1654
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001655 if (flags & FLAG_USE_QUOTA) {
1656 struct dqblk dq;
1657
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001658 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001659 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1660 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1661 reinterpret_cast<char*>(&dq)) != 0) {
1662 if (errno != ESRCH) {
1663 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1664 }
1665 } else {
1666#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001667 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001668#endif
1669 totalSize = dq.dqb_curspace;
1670 }
1671
1672 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1673 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1674 reinterpret_cast<char*>(&dq)) == 0) {
1675#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001676 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001677#endif
1678 audioSize = dq.dqb_curspace;
1679 }
1680 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1681 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1682 reinterpret_cast<char*>(&dq)) == 0) {
1683#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001684 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001685#endif
1686 videoSize = dq.dqb_curspace;
1687 }
1688 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1689 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1690 reinterpret_cast<char*>(&dq)) == 0) {
1691#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001692 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001693#endif
1694 imageSize = dq.dqb_curspace;
1695 }
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001696 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1697 reinterpret_cast<char*>(&dq)) == 0) {
1698#if MEASURE_DEBUG
1699 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1700#endif
1701 obbSize = dq.dqb_curspace;
1702 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001703 ATRACE_END();
1704
1705 ATRACE_BEGIN("apps");
1706 struct stats extStats;
1707 memset(&extStats, 0, sizeof(extStats));
1708 for (auto appId : appIds) {
1709 if (appId >= AID_APP_START) {
1710 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1711 }
1712 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001713 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001714 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001715 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001716 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001717 FTS *fts;
1718 FTSENT *p;
1719 auto path = create_data_media_path(uuid_, userId);
1720 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001721 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001722 return error("Failed to fts_open " + path);
1723 }
1724 while ((p = fts_read(fts)) != NULL) {
1725 char* ext;
1726 int64_t size = (p->fts_statp->st_blocks * 512);
1727 switch (p->fts_info) {
1728 case FTS_F:
1729 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001730 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001731 ext = strrchr(p->fts_name, '.');
1732 if (ext != nullptr) {
1733 switch (MatchExtension(++ext)) {
1734 case AID_MEDIA_AUDIO: audioSize += size; break;
1735 case AID_MEDIA_VIDEO: videoSize += size; break;
1736 case AID_MEDIA_IMAGE: imageSize += size; break;
1737 }
1738 }
1739 }
1740 // Fall through to always count against total
1741 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001742 // Ignore data belonging to specific apps
1743 p->fts_number = p->fts_parent->fts_number;
1744 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1745 p->fts_number = 1;
1746 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001747 case FTS_DEFAULT:
1748 case FTS_SL:
1749 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001750 if (p->fts_parent->fts_number == 1) {
1751 appSize += size;
1752 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001753 totalSize += size;
1754 break;
1755 }
1756 }
1757 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001758 ATRACE_END();
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001759
1760 ATRACE_BEGIN("obb");
1761 auto obbPath = create_data_media_obb_path(uuid_, "");
1762 calculate_tree_size(obbPath, &obbSize);
1763 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001764 }
1765
1766 std::vector<int64_t> ret;
1767 ret.push_back(totalSize);
1768 ret.push_back(audioSize);
1769 ret.push_back(videoSize);
1770 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001771 ret.push_back(appSize);
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001772 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001773#if MEASURE_DEBUG
1774 LOG(DEBUG) << "Final result " << toString(ret);
1775#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001776 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001777 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001778}
1779
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001780binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1781 int32_t userId, int32_t appId, int64_t cacheQuota) {
1782 ENFORCE_UID(AID_SYSTEM);
1783 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001784 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001785
1786 int32_t uid = multiuser_get_uid(userId, appId);
1787 mCacheQuotas[uid] = cacheQuota;
1788
1789 return ok();
1790}
1791
David Sehr6727c2d2016-05-17 16:06:22 -07001792// Dumps the contents of a profile file, using pkgname's dex files for pretty
1793// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001794binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1795 const std::string& codePaths, bool* _aidl_return) {
1796 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001797 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001798 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001799
1800 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001801 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001802
Jeff Sharkey90aff262016-12-12 14:28:24 -07001803 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001804 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001805}
1806
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001807// Copy the contents of a system profile over the data profile.
1808binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1809 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1810 ENFORCE_UID(AID_SYSTEM);
1811 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1812 std::lock_guard<std::recursive_mutex> lock(mLock);
1813 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName);
1814 return ok();
1815}
1816
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001817// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001818binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001819 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001820 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001821 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001822 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001823
Calin Juravle114f0812017-03-08 19:05:07 -08001824 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001825 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001826}
1827
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001828binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1829 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1830 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1831 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle52c45822017-07-13 22:50:21 -07001832 const std::unique_ptr<std::string>& classLoaderContext,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001833 const std::unique_ptr<std::string>& seInfo, bool downgrade) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001834 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001835 CHECK_ARGUMENT_UUID(uuid);
1836 if (packageName && *packageName != "*") {
1837 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1838 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001839 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001840
1841 const char* apk_path = apkPath.c_str();
1842 const char* pkgname = packageName ? packageName->c_str() : "*";
1843 const char* instruction_set = instructionSet.c_str();
1844 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1845 const char* compiler_filter = compilerFilter.c_str();
1846 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
Calin Juravle52c45822017-07-13 22:50:21 -07001847 const char* class_loader_context = classLoaderContext ? classLoaderContext->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001848 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001849 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle52c45822017-07-13 22:50:21 -07001850 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001851 downgrade);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001852 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001853}
1854
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001855binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1856 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001857 std::lock_guard<std::recursive_mutex> lock(mLock);
1858
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001859 const char* instruction_set = instructionSet.c_str();
1860
1861 char boot_marker_path[PKG_PATH_MAX];
1862 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001863 "%s/%s/%s/.booting",
1864 android_data_dir.path,
1865 DALVIK_CACHE,
1866 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001867
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001868 ALOGV("mark_boot_complete : %s", boot_marker_path);
1869 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001870 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001871 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001872 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001873}
1874
Mike Lockwood94afecf2012-10-24 10:45:23 -07001875void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1876 struct stat* statbuf)
1877{
1878 while (path[basepos] != 0) {
1879 if (path[basepos] == '/') {
1880 path[basepos] = 0;
1881 if (lstat(path, statbuf) < 0) {
1882 ALOGV("Making directory: %s\n", path);
1883 if (mkdir(path, mode) == 0) {
1884 chown(path, uid, gid);
1885 } else {
1886 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1887 }
1888 }
1889 path[basepos] = '/';
1890 basepos++;
1891 }
1892 basepos++;
1893 }
1894}
1895
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001896binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1897 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1898 const std::string& nativeLibPath32, int32_t userId) {
1899 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001900 CHECK_ARGUMENT_UUID(uuid);
1901 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001902 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001903
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001904 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1905 const char* pkgname = packageName.c_str();
1906 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001907 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001908 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001909
Jeff Sharkey423e7462016-12-09 18:18:43 -07001910 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1911 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001912
1913 const char* pkgdir = _pkgdir.c_str();
1914 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001915
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001916 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001917 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001918 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001919
1920 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001921 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001922 }
1923
1924 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001925 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001926 goto out;
1927 }
1928
1929 if (lstat(libsymlink, &libStat) < 0) {
1930 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001931 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001932 goto out;
1933 }
1934 } else {
1935 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001936 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001937 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001938 goto out;
1939 }
1940 } else if (S_ISLNK(libStat.st_mode)) {
1941 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001942 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001943 goto out;
1944 }
1945 }
1946 }
1947
1948 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001949 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001950 goto out;
1951 }
1952
1953out:
1954 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001955 auto msg = "Failed to cleanup chmod " + _pkgdir;
1956 if (res.isOk()) {
1957 res = error(msg);
1958 } else {
1959 PLOG(ERROR) << msg;
1960 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001961 }
1962
1963 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001964 auto msg = "Failed to cleanup chown " + _pkgdir;
1965 if (res.isOk()) {
1966 res = error(msg);
1967 } else {
1968 PLOG(ERROR) << msg;
1969 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001970 }
1971
Jeff Sharkey423e7462016-12-09 18:18:43 -07001972 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001973}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001974
1975static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1976{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09001977 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
1978 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
1979 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
1980}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001981
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09001982static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1983{
1984 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
1985 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
1986 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
1987}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001988
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09001989static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
1990 const char* idmap_path, int32_t uid) {
1991 int idmap_fd = open(idmap_path, O_RDWR);
1992 if (idmap_fd < 0) {
1993 PLOG(ERROR) << "idmap open failed: " << idmap_path;
1994 unlink(idmap_path);
1995 return true;
1996 }
1997
1998 pid_t pid;
1999 pid = fork();
2000 if (pid == 0) {
2001 /* child -- drop privileges before continuing */
2002 if (setgid(uid) != 0) {
2003 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2004 exit(1);
2005 }
2006 if (setuid(uid) != 0) {
2007 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2008 exit(1);
2009 }
2010 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2011 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2012 exit(1);
2013 }
2014
2015 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2016 exit(1); /* only if exec call to deleting stale idmap failed */
2017 } else {
2018 int status = wait_child(pid);
2019 close(idmap_fd);
2020
2021 if (status != 0) {
2022 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2023 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2024 unlink(idmap_path);
2025 return true;
2026 }
2027 }
2028 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002029}
2030
2031// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2032// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2033static int flatten_path(const char *prefix, const char *suffix,
2034 const char *overlay_path, char *idmap_path, size_t N)
2035{
2036 if (overlay_path == NULL || idmap_path == NULL) {
2037 return -1;
2038 }
2039 const size_t len_overlay_path = strlen(overlay_path);
2040 // will access overlay_path + 1 further below; requires absolute path
2041 if (len_overlay_path < 2 || *overlay_path != '/') {
2042 return -1;
2043 }
2044 const size_t len_idmap_root = strlen(prefix);
2045 const size_t len_suffix = strlen(suffix);
2046 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2047 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2048 // additions below would cause overflow
2049 return -1;
2050 }
2051 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2052 return -1;
2053 }
2054 memset(idmap_path, 0, N);
2055 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2056 char *ch = idmap_path + len_idmap_root;
2057 while (*ch != '\0') {
2058 if (*ch == '/') {
2059 *ch = '@';
2060 }
2061 ++ch;
2062 }
2063 return 0;
2064}
2065
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002066binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2067 const std::string& overlayApkPath, int32_t uid) {
2068 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002069 std::lock_guard<std::recursive_mutex> lock(mLock);
2070
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002071 const char* target_apk = targetApkPath.c_str();
2072 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002073 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2074
2075 int idmap_fd = -1;
2076 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002077 struct stat idmap_stat;
2078 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002079
2080 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2081 idmap_path, sizeof(idmap_path)) == -1) {
2082 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2083 goto fail;
2084 }
2085
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002086 if (stat(idmap_path, &idmap_stat) < 0) {
2087 outdated = true;
2088 } else {
2089 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2090 }
2091
2092 if (outdated) {
2093 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2094 } else {
2095 idmap_fd = open(idmap_path, O_RDWR);
2096 }
2097
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002098 if (idmap_fd < 0) {
2099 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2100 goto fail;
2101 }
2102 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2103 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2104 goto fail;
2105 }
2106 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2107 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2108 goto fail;
2109 }
2110
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002111 if (!outdated) {
2112 close(idmap_fd);
2113 return ok();
2114 }
2115
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002116 pid_t pid;
2117 pid = fork();
2118 if (pid == 0) {
2119 /* child -- drop privileges before continuing */
2120 if (setgid(uid) != 0) {
2121 ALOGE("setgid(%d) failed during idmap\n", uid);
2122 exit(1);
2123 }
2124 if (setuid(uid) != 0) {
2125 ALOGE("setuid(%d) failed during idmap\n", uid);
2126 exit(1);
2127 }
2128 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2129 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2130 exit(1);
2131 }
2132
2133 run_idmap(target_apk, overlay_apk, idmap_fd);
2134 exit(1); /* only if exec call to idmap failed */
2135 } else {
2136 int status = wait_child(pid);
2137 if (status != 0) {
2138 ALOGE("idmap failed, status=0x%04x\n", status);
2139 goto fail;
2140 }
2141 }
2142
2143 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002144 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002145fail:
2146 if (idmap_fd >= 0) {
2147 close(idmap_fd);
2148 unlink(idmap_path);
2149 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002150 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002151}
Robert Craige9887e42014-02-20 10:25:56 -05002152
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002153binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2154 const char* overlay_apk = overlayApkPath.c_str();
2155 char idmap_path[PATH_MAX];
2156
2157 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2158 idmap_path, sizeof(idmap_path)) == -1) {
2159 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2160 return error();
2161 }
2162 if (unlink(idmap_path) < 0) {
2163 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2164 return error();
2165 }
2166 return ok();
2167}
2168
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002169binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2170 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2171 const std::string& seInfo) {
2172 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002173 CHECK_ARGUMENT_UUID(uuid);
2174 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002175 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002176
2177 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002178
Robert Craigda30dc72014-03-27 10:21:12 -04002179 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002180 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002181 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2182 const char* pkgName = packageName.c_str();
2183 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002184
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002185 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002186 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002187 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002188 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002189 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002190 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002191 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002192 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002193 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002194 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002195 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002196 }
Robert Craige9887e42014-02-20 10:25:56 -05002197 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002198 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002199}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002200
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002201binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2202 const std::string& instructionSet) {
2203 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002204 std::lock_guard<std::recursive_mutex> lock(mLock);
2205
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002206 const char* oat_dir = oatDir.c_str();
2207 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002208 char oat_instr_dir[PKG_PATH_MAX];
2209
2210 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002211 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002212 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002213 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002214 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002215 }
2216 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002217 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002218 }
2219 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002220 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002221 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002222 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002223 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002224}
2225
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002226binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2227 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002228 std::lock_guard<std::recursive_mutex> lock(mLock);
2229
Jeff Sharkey423e7462016-12-09 18:18:43 -07002230 if (validate_apk_path(packageDir.c_str())) {
2231 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002232 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002233 if (delete_dir_contents_and_dir(packageDir) != 0) {
2234 return error("Failed to delete " + packageDir);
2235 }
2236 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002237}
2238
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002239binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2240 const std::string& fromBase, const std::string& toBase) {
2241 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002242 std::lock_guard<std::recursive_mutex> lock(mLock);
2243
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002244 const char* relative_path = relativePath.c_str();
2245 const char* from_base = fromBase.c_str();
2246 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002247 char from_path[PKG_PATH_MAX];
2248 char to_path[PKG_PATH_MAX];
2249 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2250 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2251
2252 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002253 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002254 }
2255
2256 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002257 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002258 }
2259
Jeff Sharkey423e7462016-12-09 18:18:43 -07002260 if (link(from_path, to_path) < 0) {
2261 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002262 }
2263
Jeff Sharkey423e7462016-12-09 18:18:43 -07002264 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002265}
2266
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002267binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2268 const std::string& instructionSet, const std::string& outputPath) {
2269 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002270 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002271
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002272 const char* apk_path = apkPath.c_str();
2273 const char* instruction_set = instructionSet.c_str();
2274 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002275
Jeff Sharkey90aff262016-12-12 14:28:24 -07002276 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002277 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002278}
2279
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002280binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002281 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002282 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002283 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002284
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002285 const char* apk_path = apkPath.c_str();
2286 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002287 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002288
Jeff Sharkey90aff262016-12-12 14:28:24 -07002289 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2290 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002291}
2292
Calin Juravlebd968362017-01-25 01:17:17 -08002293binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2294 const std::string& dexPath, const std::string& packageName, int32_t uid,
2295 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2296 int32_t storage_flag, bool* _aidl_return) {
2297 ENFORCE_UID(AID_SYSTEM);
2298 CHECK_ARGUMENT_UUID(volumeUuid);
2299 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2300
2301 std::lock_guard<std::recursive_mutex> lock(mLock);
2302 bool result = android::installd::reconcile_secondary_dex_file(
2303 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2304 return result ? ok() : error();
2305}
2306
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002307binder::Status InstalldNativeService::invalidateMounts() {
2308 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002309 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002310
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002311 mStorageMounts.clear();
2312 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002313
2314 std::ifstream in("/proc/mounts");
2315 if (!in.is_open()) {
2316 return error("Failed to read mounts");
2317 }
2318
2319 std::string source;
2320 std::string target;
2321 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002322 while (!in.eof()) {
2323 std::getline(in, source, ' ');
2324 std::getline(in, target, ' ');
2325 std::getline(in, ignored);
2326
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002327#if !BYPASS_SDCARDFS
2328 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2329 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2330 mStorageMounts[source] = target;
2331 }
2332#endif
2333
2334#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002335 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002336 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002337 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2338 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002339 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2340 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002341
2342 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2343 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2344 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2345 && errno != EBUSY) {
2346 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2347 }
2348 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2349 && errno != EBUSY) {
2350 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2351 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002352 }
2353 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002354#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002355 }
2356 return ok();
2357}
2358
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002359std::string InstalldNativeService::findDataMediaPath(
2360 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2361 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2362 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2363 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2364 auto resolved = mStorageMounts[path];
2365 if (resolved.empty()) {
2366 LOG(WARNING) << "Failed to find storage mount for " << path;
2367 resolved = path;
2368 }
2369 return StringPrintf("%s/%u", resolved.c_str(), userid);
2370}
2371
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002372std::string InstalldNativeService::findQuotaDeviceForUuid(
2373 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002374 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002375 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002376 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002377}
2378
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002379binder::Status InstalldNativeService::isQuotaSupported(
2380 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2381 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2382 return ok();
2383}
2384
Andreas Gampe02d0de52015-11-11 20:43:16 -08002385} // namespace installd
2386} // namespace android