blob: bffbd542d19e7d1160ded5a1af0a3f40a40dd8d5 [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
81static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
82static constexpr const char* IDMAP_SUFFIX = "@idmap";
83
Andreas Gampe0354bd02016-06-27 14:25:30 -070084// NOTE: keep in sync with Installer
85static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
86static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070087static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070088static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070089static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
90static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Calin Juravle6a1648e2016-02-01 12:12:16 +000091
Jeff Sharkey0274c972016-12-06 09:32:04 -070092namespace {
93
94constexpr const char* kDump = "android.permission.DUMP";
95
Jeff Sharkey423e7462016-12-09 18:18:43 -070096static binder::Status ok() {
97 return binder::Status::ok();
98}
99
100static binder::Status exception(uint32_t code, const std::string& msg) {
101 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
102}
103
104static binder::Status error() {
105 return binder::Status::fromServiceSpecificError(errno);
106}
107
108static binder::Status error(const std::string& msg) {
109 PLOG(ERROR) << msg;
110 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
111}
112
113static binder::Status error(uint32_t code, const std::string& msg) {
114 LOG(ERROR) << msg << " (" << code << ")";
115 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
116}
117
Jeff Sharkey0274c972016-12-06 09:32:04 -0700118binder::Status checkPermission(const char* permission) {
119 pid_t pid;
120 uid_t uid;
121
122 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
123 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700124 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700125 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700126 return exception(binder::Status::EX_SECURITY,
127 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700128 }
129}
130
131binder::Status checkUid(uid_t expectedUid) {
132 uid_t uid = IPCThreadState::self()->getCallingUid();
133 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700134 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700135 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return exception(binder::Status::EX_SECURITY,
137 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
138 }
139}
140
141binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
142 if (!uuid || is_valid_filename(*uuid)) {
143 return ok();
144 } else {
145 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
146 StringPrintf("UUID %s is malformed", uuid->c_str()));
147 }
148}
149
150binder::Status checkArgumentPackageName(const std::string& packageName) {
151 if (is_valid_package_name(packageName.c_str())) {
152 return ok();
153 } else {
154 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
155 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700156 }
157}
158
159#define ENFORCE_UID(uid) { \
160 binder::Status status = checkUid((uid)); \
161 if (!status.isOk()) { \
162 return status; \
163 } \
164}
165
Jeff Sharkey423e7462016-12-09 18:18:43 -0700166#define CHECK_ARGUMENT_UUID(uuid) { \
167 binder::Status status = checkArgumentUuid((uuid)); \
168 if (!status.isOk()) { \
169 return status; \
170 } \
171}
172
173#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
174 binder::Status status = \
175 checkArgumentPackageName((packageName)); \
176 if (!status.isOk()) { \
177 return status; \
178 } \
179}
180
Jeff Sharkey0274c972016-12-06 09:32:04 -0700181} // namespace
182
183status_t InstalldNativeService::start() {
184 IPCThreadState::self()->disableBackgroundScheduling(true);
185 status_t ret = BinderService<InstalldNativeService>::publish();
186 if (ret != android::OK) {
187 return ret;
188 }
189 sp<ProcessState> ps(ProcessState::self());
190 ps->startThreadPool();
191 ps->giveThreadPoolName();
192 return android::OK;
193}
194
195status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700196 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700197 const binder::Status dump_permission = checkPermission(kDump);
198 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700199 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700200 return PERMISSION_DENIED;
201 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700202 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700203
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700204 out << "installd is happy!" << endl;
205
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700206 {
207 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
208 out << endl << "Devices with quota support:" << endl;
209 for (const auto& n : mQuotaDevices) {
210 out << " " << n.first << " = " << n.second << endl;
211 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700212 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700213
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700214 {
215 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
216 out << endl << "Per-UID cache quotas:" << endl;
217 for (const auto& n : mCacheQuotas) {
218 out << " " << n.first << " = " << n.second << endl;
219 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700220 }
221
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700222 out << endl;
223 out.flush();
224
Jeff Sharkey0274c972016-12-06 09:32:04 -0700225 return NO_ERROR;
226}
227
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600228/**
229 * Perform restorecon of the given path, but only perform recursive restorecon
230 * if the label of that top-level file actually changed. This can save us
231 * significant time by avoiding no-op traversals of large filesystem trees.
232 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700233static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
234 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600235 int res = 0;
236 char* before = nullptr;
237 char* after = nullptr;
238
239 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
240 // libselinux. Not needed here.
241
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600242 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600243 PLOG(ERROR) << "Failed before getfilecon for " << path;
244 goto fail;
245 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700246 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600247 PLOG(ERROR) << "Failed top-level restorecon for " << path;
248 goto fail;
249 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600250 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600251 PLOG(ERROR) << "Failed after getfilecon for " << path;
252 goto fail;
253 }
254
255 // If the initial top-level restorecon above changed the label, then go
256 // back and restorecon everything recursively
257 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700258 if (existing) {
259 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
260 << path << "; running recursive restorecon";
261 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700262 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600263 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
264 PLOG(ERROR) << "Failed recursive restorecon for " << path;
265 goto fail;
266 }
267 }
268
269 goto done;
270fail:
271 res = -1;
272done:
273 free(before);
274 free(after);
275 return res;
276}
277
Jeff Sharkey0274c972016-12-06 09:32:04 -0700278static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700279 const std::string& seInfo, uid_t uid, bool existing) {
280 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
281 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600282}
283
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600284static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600285 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
286 PLOG(ERROR) << "Failed to prepare " << path;
287 return -1;
288 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600289 return 0;
290}
291
Jeff Sharkey0274c972016-12-06 09:32:04 -0700292binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
293 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700294 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700295 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700296 CHECK_ARGUMENT_UUID(uuid);
297 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700298 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700299
300 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
301 const char* pkgname = packageName.c_str();
302
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700303 // Assume invalid inode unless filled in below
304 if (_aidl_return != nullptr) *_aidl_return = -1;
305
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700306 int32_t uid = multiuser_get_uid(userId, appId);
307 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700308 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
309
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700310 // If UID doesn't have a specific cache GID, use UID value
311 if (cacheGid == -1) {
312 cacheGid = uid;
313 }
314
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700315 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700316 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700317 bool existing = (access(path.c_str(), F_OK) == 0);
318
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700319 if (prepare_app_dir(path, targetMode, uid) ||
320 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
321 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700322 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600323 }
324
325 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700326 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
327 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
328 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700329 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700330 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600331
332 // Remember inode numbers of cache directories so that we can clear
333 // contents while CE storage is locked
334 if (write_path_inode(path, "cache", kXattrInodeCache) ||
335 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700336 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700337 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700338
339 // And return the CE inode of the top-level data directory so we can
340 // clear contents while CE storage is locked
341 if ((_aidl_return != nullptr)
342 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
343 return error("Failed to get_path_inode for " + path);
344 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700345 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700346 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700347 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700348 bool existing = (access(path.c_str(), F_OK) == 0);
349
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700350 if (prepare_app_dir(path, targetMode, uid) ||
351 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
352 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700353 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700354 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000355
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600356 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700357 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700358 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600359 }
360
Jeff Sharkey90aff262016-12-12 14:28:24 -0700361 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700362 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000363 // read-write-execute only for the app user.
364 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700365 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000366 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100367 std::string profile_file = create_primary_profile(profile_path);
368 // read-write only for the app user.
369 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700370 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100371 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000372 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
373 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
374 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700375 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700376 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000377 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700378 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000379 }
380 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700381 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700382 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700383}
384
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700385binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
386 const std::string& packageName, int32_t userId, int32_t flags) {
387 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700388 CHECK_ARGUMENT_UUID(uuid);
389 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700390 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700391
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700392 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
393 const char* pkgname = packageName.c_str();
394
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700395 // This method only exists to upgrade system apps that have requested
396 // forceDeviceEncrypted, so their default storage always lives in a
397 // consistent location. This only works on non-FBE devices, since we
398 // never want to risk exposing data on a device with real CE/DE storage.
399
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700400 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
401 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700402
403 // If neither directory is marked as default, assume CE is default
404 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
405 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
406 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700407 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700408 }
409 }
410
411 // Migrate default data location if needed
412 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
413 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
414
415 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
416 LOG(WARNING) << "Requested default storage " << target
417 << " is not active; migrating from " << source;
418 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700419 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700420 }
421 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700422 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700423 }
424 }
425
Jeff Sharkey423e7462016-12-09 18:18:43 -0700426 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700427}
428
Calin Juravle6a1648e2016-02-01 12:12:16 +0000429
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700430binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
431 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700432 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700433 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700434
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700435 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700436 binder::Status res = ok();
437 if (!clear_reference_profile(pkgname)) {
438 res = error("Failed to clear reference profile for " + packageName);
439 }
440 if (!clear_current_profiles(pkgname)) {
441 res = error("Failed to clear current profiles for " + packageName);
442 }
443 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000444}
445
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700446binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
447 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
448 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700449 CHECK_ARGUMENT_UUID(uuid);
450 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700451 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700452
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700453 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
454 const char* pkgname = packageName.c_str();
455
Jeff Sharkey423e7462016-12-09 18:18:43 -0700456 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700457 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700458 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600459 if (flags & FLAG_CLEAR_CACHE_ONLY) {
460 path = read_path_inode(path, "cache", kXattrInodeCache);
461 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
462 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
463 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700464 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700465 if (delete_dir_contents(path) != 0) {
466 res = error("Failed to delete contents of " + path);
467 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700468 }
469 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700470 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600471 std::string suffix = "";
472 bool only_cache = false;
473 if (flags & FLAG_CLEAR_CACHE_ONLY) {
474 suffix = CACHE_DIR_POSTFIX;
475 only_cache = true;
476 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
477 suffix = CODE_CACHE_DIR_POSTFIX;
478 only_cache = true;
479 }
480
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700481 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700482 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700483 if (delete_dir_contents(path) != 0) {
484 res = error("Failed to delete contents of " + path);
485 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700486 }
Calin Juravleedae6692016-03-23 13:55:31 +0000487 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700488 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000490 }
491 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700492 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700493 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700494}
495
Calin Juravle7535e8e2016-03-29 16:05:40 +0100496static int destroy_app_reference_profile(const char *pkgname) {
497 return delete_dir_contents_and_dir(
498 create_data_ref_profile_package_path(pkgname),
499 /*ignore_if_missing*/ true);
500}
501
Calin Juravleedae6692016-03-23 13:55:31 +0000502static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100503 return delete_dir_contents_and_dir(
504 create_data_user_profile_package_path(userid, pkgname),
505 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000506}
507
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700508binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
509 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700510 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700511 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700512
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700513 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700514 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000515 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
516 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700517 if (destroy_app_current_profiles(pkgname, user) != 0) {
518 res = error("Failed to destroy current profiles for " + packageName);
519 }
Calin Juravleedae6692016-03-23 13:55:31 +0000520 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 if (destroy_app_reference_profile(pkgname) != 0) {
522 res = error("Failed to destroy reference profile for " + packageName);
523 }
524 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000525}
526
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700527binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
528 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
529 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700530 CHECK_ARGUMENT_UUID(uuid);
531 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700532 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700533
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700534 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
535 const char* pkgname = packageName.c_str();
536
Jeff Sharkey423e7462016-12-09 18:18:43 -0700537 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700538 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
540 if (delete_dir_contents_and_dir(path) != 0) {
541 res = error("Failed to delete " + path);
542 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700543 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700544 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700545 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
546 if (delete_dir_contents_and_dir(path) != 0) {
547 res = error("Failed to delete " + path);
548 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700549 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100550 // TODO(calin): If the package is still installed by other users it's probably
551 // beneficial to keep the reference profile around.
552 // Verify if it's ok to do that.
553 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700554 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700555 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700556}
557
Jeff Sharkey0274c972016-12-06 09:32:04 -0700558binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
559 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
560 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
561 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700562 ENFORCE_UID(AID_SYSTEM);
563 CHECK_ARGUMENT_UUID(fromUuid);
564 CHECK_ARGUMENT_UUID(toUuid);
565 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700566 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700567
568 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
569 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
570 const char* package_name = packageName.c_str();
571 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700572
Jeff Sharkey423e7462016-12-09 18:18:43 -0700573 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700574 std::vector<userid_t> users = get_known_users(from_uuid);
575
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700576 // Copy app
577 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600578 auto from = create_data_app_package_path(from_uuid, data_app_name);
579 auto to = create_data_app_package_path(to_uuid, data_app_name);
580 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700581
582 char *argv[] = {
583 (char*) kCpPath,
584 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
585 (char*) "-p", /* preserve timestamps, ownership, and permissions */
586 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
587 (char*) "-P", /* Do not follow symlinks [default] */
588 (char*) "-d", /* don't dereference symlinks */
589 (char*) from.c_str(),
590 (char*) to_parent.c_str()
591 };
592
593 LOG(DEBUG) << "Copying " << from << " to " << to;
594 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700595 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700596 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700597 goto fail;
598 }
599
600 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700601 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700602 goto fail;
603 }
604 }
605
606 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700607 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700608
609 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600610 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
611 if (access(from_ce.c_str(), F_OK) != 0) {
612 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700613 continue;
614 }
615
Jeff Sharkey0274c972016-12-06 09:32:04 -0700616 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700617 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700618 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700619 goto fail;
620 }
621
622 char *argv[] = {
623 (char*) kCpPath,
624 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
625 (char*) "-p", /* preserve timestamps, ownership, and permissions */
626 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
627 (char*) "-P", /* Do not follow symlinks [default] */
628 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600629 nullptr,
630 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700631 };
632
Jeff Sharkey51c94492016-05-10 17:46:39 -0600633 {
634 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
635 auto to = create_data_user_de_path(to_uuid, user);
636 argv[6] = (char*) from.c_str();
637 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700638
Jeff Sharkey51c94492016-05-10 17:46:39 -0600639 LOG(DEBUG) << "Copying " << from << " to " << to;
640 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
641 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700642 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600643 goto fail;
644 }
645 }
646 {
647 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
648 auto to = create_data_user_ce_path(to_uuid, user);
649 argv[6] = (char*) from.c_str();
650 argv[7] = (char*) to.c_str();
651
652 LOG(DEBUG) << "Copying " << from << " to " << to;
653 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
654 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700655 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600656 goto fail;
657 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700658 }
659
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700660 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
661 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700662 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700663 goto fail;
664 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700665 }
666
Jeff Sharkey31f08982015-07-07 13:31:37 -0700667 // We let the framework scan the new location and persist that before
668 // deleting the data in the old location; this ordering ensures that
669 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700670 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700671
672fail:
673 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700674 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600675 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700676 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
677 LOG(WARNING) << "Failed to rollback " << to;
678 }
679 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700680 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600681 {
682 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
683 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
684 LOG(WARNING) << "Failed to rollback " << to;
685 }
686 }
687 {
688 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
689 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
690 LOG(WARNING) << "Failed to rollback " << to;
691 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700692 }
693 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700694 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700695}
696
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700697binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
698 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
699 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700700 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700701 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700702
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700703 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600704 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700705 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700706 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700707 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700708 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700709 }
710 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700711 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700712}
713
714binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
715 int32_t userId, int32_t flags) {
716 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700717 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700718 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700719
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700720 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700721 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700722 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700723 auto path = create_data_user_de_path(uuid_, userId);
724 if (delete_dir_contents_and_dir(path, true) != 0) {
725 res = error("Failed to delete " + path);
726 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700727 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700728 path = create_data_misc_legacy_path(userId);
729 if (delete_dir_contents_and_dir(path, true) != 0) {
730 res = error("Failed to delete " + path);
731 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700732 path = create_data_user_profile_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700733 if (delete_dir_contents_and_dir(path, true) != 0) {
734 res = error("Failed to delete " + path);
735 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700736 }
Robin Lee095c7632014-04-25 15:05:19 +0100737 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600738 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700739 auto path = create_data_user_ce_path(uuid_, userId);
740 if (delete_dir_contents_and_dir(path, true) != 0) {
741 res = error("Failed to delete " + path);
742 }
743 path = create_data_media_path(uuid_, userId);
744 if (delete_dir_contents_and_dir(path, true) != 0) {
745 res = error("Failed to delete " + path);
746 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600747 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100749}
750
Mike Lockwood94afecf2012-10-24 10:45:23 -0700751/* Try to ensure free_size bytes of storage are available.
752 * Returns 0 on success.
753 * This is rather simple-minded because doing a full LRU would
754 * be potentially memory-intensive, and without atime it would
755 * also require that apps constantly modify file metadata even
756 * when just reading from the cache, which is pretty awful.
757 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700758binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700759 int64_t freeStorageSize, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700760 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700761 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700762 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700763
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700764 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700765 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700766 auto device = findQuotaDeviceForUuid(uuid);
767 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700768
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700769 int64_t free = data_disk_free(data_path);
770 int64_t needed = freeStorageSize - free;
771 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700772 return error("Failed to determine free space for " + data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700773 } else if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700774 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700775 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700776
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700777 LOG(DEBUG) << "Found " << data_path << " with " << free << " free; caller requested "
778 << freeStorageSize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700779
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700780 if (flags & FLAG_FREE_CACHE_V2) {
781 // This new cache strategy fairly removes files from UIDs by deleting
782 // files from the UIDs which are most over their allocated quota
783
784 // 1. Create trackers for every known UID
785 ATRACE_BEGIN("create");
786 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
787 for (auto user : get_known_users(uuid_)) {
788 FTS *fts;
789 FTSENT *p;
790 char *argv[] = {
791 (char*) create_data_user_ce_path(uuid_, user).c_str(),
792 (char*) create_data_user_de_path(uuid_, user).c_str(),
793 nullptr
794 };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700795 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700796 return error("Failed to fts_open");
797 }
798 while ((p = fts_read(fts)) != NULL) {
799 if (p->fts_info == FTS_D && p->fts_level == 1) {
800 uid_t uid = p->fts_statp->st_uid;
801 auto search = trackers.find(uid);
802 if (search != trackers.end()) {
803 search->second->addDataPath(p->fts_path);
804 } else {
805 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
806 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
807 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700808 {
809 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
810 tracker->cacheQuota = mCacheQuotas[uid];
811 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700812 if (tracker->cacheQuota == 0) {
813 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
814 tracker->cacheQuota = 67108864;
815 }
816 trackers[uid] = tracker;
817 }
818 fts_set(fts, p, FTS_SKIP);
819 }
820 }
821 fts_close(fts);
822 }
823 ATRACE_END();
824
825 // 2. Populate tracker stats and insert into priority queue
826 ATRACE_BEGIN("populate");
827 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
828 return (left->getCacheRatio() < right->getCacheRatio());
829 };
830 std::priority_queue<std::shared_ptr<CacheTracker>,
831 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
832 for (const auto& it : trackers) {
833 it.second->loadStats();
834 queue.push(it.second);
835 }
836 ATRACE_END();
837
838 // 3. Bounce across the queue, freeing items from whichever tracker is
839 // the most over their assigned quota
840 ATRACE_BEGIN("bounce");
841 std::shared_ptr<CacheTracker> active;
842 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700843 // Only look at apps under quota when explicitly requested
844 if (active && (active->getCacheRatio() < 10000)
845 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
846 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
847 << " isn't over quota, and defy not requested";
848 break;
849 }
850
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700851 // Find the best tracker to work with; this might involve swapping
852 // if the active tracker is no longer the most over quota
853 bool nextBetter = active && !queue.empty()
854 && active->getCacheRatio() < queue.top()->getCacheRatio();
855 if (!active || nextBetter) {
856 if (active) {
857 // Current tracker still has items, so we'll consider it
858 // again later once it bubbles up to surface
859 queue.push(active);
860 }
861 active = queue.top(); queue.pop();
862 active->ensureItems();
863 continue;
864 }
865
866 // If no items remain, go find another tracker
867 if (active->items.empty()) {
868 active = nullptr;
869 continue;
870 } else {
871 auto item = active->items.back();
872 active->items.pop_back();
873
874 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
875 if (!noop) {
876 item->purge();
877 }
878 active->cacheUsed -= item->size;
879 needed -= item->size;
880 }
881
882 // Verify that we're actually done before bailing, since sneaky
883 // apps might be using hardlinks
884 if (needed <= 0) {
885 free = data_disk_free(data_path);
886 needed = freeStorageSize - free;
887 if (needed <= 0) {
888 break;
889 } else {
890 LOG(WARNING) << "Expected to be done but still need " << needed;
891 }
892 }
893 }
894 ATRACE_END();
895
896 } else {
897 ATRACE_BEGIN("start");
898 cache_t* cache = start_cache_collection();
899 ATRACE_END();
900
901 ATRACE_BEGIN("add");
902 for (auto user : get_known_users(uuid_)) {
903 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
904 add_cache_files(cache, create_data_user_de_path(uuid_, user));
905 add_cache_files(cache,
906 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
907 }
Fyodor Kupolovf3124d82016-09-07 13:07:45 -0700908 // Add files from /data/preloads/file_cache
909 if (uuid == nullptr) {
910 add_preloads_file_cache(cache, uuid_);
911 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700912 ATRACE_END();
913
914 ATRACE_BEGIN("clear");
915 clear_cache_files(data_path, cache, freeStorageSize);
916 ATRACE_END();
917
918 ATRACE_BEGIN("finish");
919 finish_cache_collection(cache);
920 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700921 }
922
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700923 free = data_disk_free(data_path);
924 if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700925 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700926 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700927 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700928 freeStorageSize, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700929 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700930}
931
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700932binder::Status InstalldNativeService::rmdex(const std::string& codePath,
933 const std::string& instructionSet) {
934 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700935 std::lock_guard<std::recursive_mutex> lock(mLock);
936
Mike Lockwood94afecf2012-10-24 10:45:23 -0700937 char dex_path[PKG_PATH_MAX];
938
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700939 const char* path = codePath.c_str();
940 const char* instruction_set = instructionSet.c_str();
941
Jeff Sharkey770180a2014-09-08 17:14:26 -0700942 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700943 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700944 }
945
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700946 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700947 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700948 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700949
950 ALOGV("unlink %s\n", dex_path);
951 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700952 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700953 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700954 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700955 }
956}
957
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700958struct stats {
959 int64_t codeSize;
960 int64_t dataSize;
961 int64_t cacheSize;
962};
963
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700964#if MEASURE_DEBUG
965static std::string toString(std::vector<int64_t> values) {
966 std::stringstream res;
967 res << "[";
968 for (size_t i = 0; i < values.size(); i++) {
969 res << values[i];
970 if (i < values.size() - 1) {
971 res << ",";
972 }
973 }
974 res << "]";
975 return res.str();
976}
977#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700978
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700979static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -0700980 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700981 if (device.empty()) return;
982
983 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700984
985 uid_t uid = multiuser_get_uid(userId, appId);
986 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
987 reinterpret_cast<char*>(&dq)) != 0) {
988 if (errno != ESRCH) {
989 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
990 }
991 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700992#if MEASURE_DEBUG
993 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
994#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700995 stats->dataSize += dq.dqb_curspace;
996 }
997
998 int cacheGid = multiuser_get_cache_gid(userId, appId);
999 if (cacheGid != -1) {
1000 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1001 reinterpret_cast<char*>(&dq)) != 0) {
1002 if (errno != ESRCH) {
1003 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1004 }
1005 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001006#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001007 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001008#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001009 stats->cacheSize += dq.dqb_curspace;
1010 }
1011 }
1012
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001013 int extGid = multiuser_get_ext_gid(userId, appId);
1014 if (extGid != -1) {
1015 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1016 reinterpret_cast<char*>(&dq)) != 0) {
1017 if (errno != ESRCH) {
1018 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1019 }
1020 } else {
1021#if MEASURE_DEBUG
1022 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1023#endif
1024 extStats->dataSize += dq.dqb_curspace;
1025 }
1026 }
1027
1028 int sharedGid = multiuser_get_shared_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001029 if (sharedGid != -1) {
1030 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1031 reinterpret_cast<char*>(&dq)) != 0) {
1032 if (errno != ESRCH) {
1033 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1034 }
1035 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001036#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001037 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001038#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001039 stats->codeSize += dq.dqb_curspace;
1040 }
1041 }
1042}
1043
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001044static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001045 DIR *d;
1046 int dfd;
1047 struct dirent *de;
1048 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001049
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001050 d = opendir(path.c_str());
1051 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001052 if (errno != ENOENT) {
1053 PLOG(WARNING) << "Failed to open " << path;
1054 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001055 return;
1056 }
1057 dfd = dirfd(d);
1058 while ((de = readdir(d))) {
1059 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001060
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001061 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001062 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001063 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001064 }
1065
1066 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001067 if (!strcmp(name, ".")) {
1068 // Don't recurse, but still count node size
1069 } else if (!strcmp(name, "..")) {
1070 // Don't recurse or count node size
1071 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001072 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001073 // Measure all children nodes
1074 size = 0;
1075 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001076 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001077
1078 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1079 stats->cacheSize += size;
1080 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001081 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001082
1083 // Legacy symlink isn't owned by app
1084 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1085 continue;
1086 }
1087
1088 // Everything found inside is considered data
1089 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001090 }
1091 closedir(d);
1092}
1093
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001094static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1095 bool exclude_apps = false) {
1096 DIR *d;
1097 int dfd;
1098 struct dirent *de;
1099 struct stat s;
1100
1101 d = opendir(path.c_str());
1102 if (d == nullptr) {
1103 if (errno != ENOENT) {
1104 PLOG(WARNING) << "Failed to open " << path;
1105 }
1106 return;
1107 }
1108 dfd = dirfd(d);
1109 while ((de = readdir(d))) {
1110 if (de->d_type == DT_DIR) {
1111 const char *name = de->d_name;
1112 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1113 continue;
1114 }
1115 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1116 continue;
1117 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1118 continue;
1119 } else {
1120 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1121 }
1122 }
1123 }
1124 closedir(d);
1125}
1126
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001127static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1128 FTS *fts;
1129 FTSENT *p;
1130 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001131 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001132 PLOG(ERROR) << "Failed to fts_open " << path;
1133 return;
1134 }
1135 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001136 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001137 switch (p->fts_info) {
1138 case FTS_D:
1139 if (p->fts_level == 4
1140 && !strcmp(p->fts_name, "cache")
1141 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1142 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1143 p->fts_number = 1;
1144 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001145 // Fall through to count the directory
1146 case FTS_DEFAULT:
1147 case FTS_F:
1148 case FTS_SL:
1149 case FTS_SLNONE:
1150 int64_t size = (p->fts_statp->st_blocks * 512);
1151 if (p->fts_number == 1) {
1152 stats->cacheSize += size;
1153 }
1154 stats->dataSize += size;
1155 break;
1156 }
1157 }
1158 fts_close(fts);
1159}
1160
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001161binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001162 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1163 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1164 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001165 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001166 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001167 for (auto packageName : packageNames) {
1168 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1169 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001170 // NOTE: Locking is relaxed on this method, since it's limited to
1171 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001172
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001173 // When modifying this logic, always verify using tests:
1174 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1175
1176#if MEASURE_DEBUG
1177 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1178#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001179
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001180 // Here's a summary of the common storage locations across the platform,
1181 // and how they're each tagged:
1182 //
1183 // /data/app/com.example UID system
1184 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001185 // /data/user/0/com.example UID u0_a10 GID u0_a10
1186 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1187 // /data/media/0/foo.txt UID u0_media_rw
1188 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1189 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1190 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1191 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001192
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001193 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001194 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001195 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001196 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001197
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001198 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001199
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001200 auto device = findQuotaDeviceForUuid(uuid);
1201 if (device.empty()) {
1202 flags &= ~FLAG_USE_QUOTA;
1203 }
1204
Jeff Sharkey466459b2017-01-17 15:25:01 -07001205 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001206 for (auto packageName : packageNames) {
1207 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1208 calculate_tree_size(obbCodePath, &extStats.codeSize);
1209 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001210 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001211
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001212 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001213 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001214 for (auto codePath : codePaths) {
1215 calculate_tree_size(codePath, &stats.codeSize, -1,
1216 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001217 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001218 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001219
Jeff Sharkey466459b2017-01-17 15:25:01 -07001220 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001221 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001222 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001223
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001224 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001225 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001226 for (auto codePath : codePaths) {
1227 calculate_tree_size(codePath, &stats.codeSize);
1228 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001229 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001230
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001231 for (size_t i = 0; i < packageNames.size(); i++) {
1232 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001233
Jeff Sharkey466459b2017-01-17 15:25:01 -07001234 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001235 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1236 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001237 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1238 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001239 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001240
Jeff Sharkey466459b2017-01-17 15:25:01 -07001241 ATRACE_BEGIN("profiles");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001242 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1243 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001244 auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1245 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001246 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001247
Jeff Sharkey466459b2017-01-17 15:25:01 -07001248 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001249 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001250 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001251 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001252 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001253 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001254 }
1255
Jeff Sharkey466459b2017-01-17 15:25:01 -07001256 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001257 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1258 if (sharedGid != -1) {
1259 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1260 sharedGid, -1);
1261 }
Calin Juravle35c84652017-03-03 17:00:35 -08001262 calculate_tree_size(create_data_user_profile_path(userId), &stats.dataSize,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001263 multiuser_get_uid(userId, appId), -1);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001264 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001265 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001266
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001267 std::vector<int64_t> ret;
1268 ret.push_back(stats.codeSize);
1269 ret.push_back(stats.dataSize);
1270 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001271 ret.push_back(extStats.codeSize);
1272 ret.push_back(extStats.dataSize);
1273 ret.push_back(extStats.cacheSize);
1274#if MEASURE_DEBUG
1275 LOG(DEBUG) << "Final result " << toString(ret);
1276#endif
1277 *_aidl_return = ret;
1278 return ok();
1279}
1280
1281binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1282 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1283 std::vector<int64_t>* _aidl_return) {
1284 ENFORCE_UID(AID_SYSTEM);
1285 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001286 // NOTE: Locking is relaxed on this method, since it's limited to
1287 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001288
1289 // When modifying this logic, always verify using tests:
1290 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1291
1292#if MEASURE_DEBUG
1293 LOG(INFO) << "Measuring user " << userId;
1294#endif
1295
1296 struct stats stats;
1297 struct stats extStats;
1298 memset(&stats, 0, sizeof(stats));
1299 memset(&extStats, 0, sizeof(extStats));
1300
1301 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1302
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001303 auto device = findQuotaDeviceForUuid(uuid);
1304 if (device.empty()) {
1305 flags &= ~FLAG_USE_QUOTA;
1306 }
1307
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001308 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001309 struct dqblk dq;
1310
1311 ATRACE_BEGIN("obb");
1312 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1313 reinterpret_cast<char*>(&dq)) != 0) {
1314 if (errno != ESRCH) {
1315 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1316 }
1317 } else {
1318#if MEASURE_DEBUG
1319 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1320#endif
1321 extStats.codeSize += dq.dqb_curspace;
1322 }
1323 ATRACE_END();
1324
Jeff Sharkey466459b2017-01-17 15:25:01 -07001325 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001326 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001327 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001328
Jeff Sharkey466459b2017-01-17 15:25:01 -07001329 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001330 auto cePath = create_data_user_ce_path(uuid_, userId);
1331 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001332 auto dePath = create_data_user_de_path(uuid_, userId);
1333 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001334 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001335
Jeff Sharkey466459b2017-01-17 15:25:01 -07001336 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001337 auto userProfilePath = create_data_user_profile_path(userId);
1338 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001339 auto refProfilePath = create_data_ref_profile_path();
1340 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001341 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001342
Jeff Sharkey466459b2017-01-17 15:25:01 -07001343 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001344 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1345 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1346 reinterpret_cast<char*>(&dq)) != 0) {
1347 if (errno != ESRCH) {
1348 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1349 }
1350 } else {
1351#if MEASURE_DEBUG
1352 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001353#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001354 extStats.dataSize += dq.dqb_curspace;
1355 }
1356 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001357
Jeff Sharkey466459b2017-01-17 15:25:01 -07001358 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001359 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1360 -1, -1, true);
Calin Juravle35c84652017-03-03 17:00:35 -08001361 calculate_tree_size(create_data_user_profile_path(userId), &stats.dataSize,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001362 -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001363 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001364
Jeff Sharkey466459b2017-01-17 15:25:01 -07001365 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001366 for (auto appId : appIds) {
1367 if (appId >= AID_APP_START) {
1368 collectQuotaStats(device, userId, appId, &stats, &extStats);
1369#if MEASURE_DEBUG
1370 // Sleep to make sure we don't lose logs
1371 usleep(1);
1372#endif
1373 }
1374 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001375 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001376 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001377 ATRACE_BEGIN("obb");
1378 auto obbPath = create_data_path(uuid_) + "/media/obb";
1379 calculate_tree_size(obbPath, &extStats.codeSize);
1380 ATRACE_END();
1381
Jeff Sharkey466459b2017-01-17 15:25:01 -07001382 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001383 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001384 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001385
Jeff Sharkey466459b2017-01-17 15:25:01 -07001386 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001387 auto cePath = create_data_user_ce_path(uuid_, userId);
1388 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001389 auto dePath = create_data_user_de_path(uuid_, userId);
1390 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001391 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001392
Jeff Sharkey466459b2017-01-17 15:25:01 -07001393 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001394 auto userProfilePath = create_data_user_profile_path(userId);
1395 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001396 auto refProfilePath = create_data_ref_profile_path();
1397 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001398 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001399
Jeff Sharkey466459b2017-01-17 15:25:01 -07001400 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001401 auto dataMediaPath = create_data_media_path(uuid_, userId);
1402 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1403#if MEASURE_DEBUG
1404 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1405 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001406#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001407 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001408
Jeff Sharkey466459b2017-01-17 15:25:01 -07001409 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001410 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
Calin Juravle35c84652017-03-03 17:00:35 -08001411 calculate_tree_size(create_data_user_profile_path(userId), &stats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001412 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001413 }
1414
1415 std::vector<int64_t> ret;
1416 ret.push_back(stats.codeSize);
1417 ret.push_back(stats.dataSize);
1418 ret.push_back(stats.cacheSize);
1419 ret.push_back(extStats.codeSize);
1420 ret.push_back(extStats.dataSize);
1421 ret.push_back(extStats.cacheSize);
1422#if MEASURE_DEBUG
1423 LOG(DEBUG) << "Final result " << toString(ret);
1424#endif
1425 *_aidl_return = ret;
1426 return ok();
1427}
1428
1429binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1430 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1431 ENFORCE_UID(AID_SYSTEM);
1432 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001433 // NOTE: Locking is relaxed on this method, since it's limited to
1434 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001435
1436 // When modifying this logic, always verify using tests:
1437 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1438
1439#if MEASURE_DEBUG
1440 LOG(INFO) << "Measuring external " << userId;
1441#endif
1442
1443 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1444
1445 int64_t totalSize = 0;
1446 int64_t audioSize = 0;
1447 int64_t videoSize = 0;
1448 int64_t imageSize = 0;
1449
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001450 auto device = findQuotaDeviceForUuid(uuid);
1451 if (device.empty()) {
1452 flags &= ~FLAG_USE_QUOTA;
1453 }
1454
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001455 if (flags & FLAG_USE_QUOTA) {
1456 struct dqblk dq;
1457
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001458 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1459 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1460 reinterpret_cast<char*>(&dq)) != 0) {
1461 if (errno != ESRCH) {
1462 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1463 }
1464 } else {
1465#if MEASURE_DEBUG
1466 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1467#endif
1468 totalSize = dq.dqb_curspace;
1469 }
1470
1471 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1472 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1473 reinterpret_cast<char*>(&dq)) == 0) {
1474#if MEASURE_DEBUG
1475 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1476#endif
1477 audioSize = dq.dqb_curspace;
1478 }
1479 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1480 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1481 reinterpret_cast<char*>(&dq)) == 0) {
1482#if MEASURE_DEBUG
1483 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1484#endif
1485 videoSize = dq.dqb_curspace;
1486 }
1487 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1488 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1489 reinterpret_cast<char*>(&dq)) == 0) {
1490#if MEASURE_DEBUG
1491 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1492#endif
1493 imageSize = dq.dqb_curspace;
1494 }
1495 } else {
1496 FTS *fts;
1497 FTSENT *p;
1498 auto path = create_data_media_path(uuid_, userId);
1499 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001500 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001501 return error("Failed to fts_open " + path);
1502 }
1503 while ((p = fts_read(fts)) != NULL) {
1504 char* ext;
1505 int64_t size = (p->fts_statp->st_blocks * 512);
1506 switch (p->fts_info) {
1507 case FTS_F:
1508 // Only categorize files not belonging to apps
1509 if (p->fts_statp->st_gid < AID_APP_START) {
1510 ext = strrchr(p->fts_name, '.');
1511 if (ext != nullptr) {
1512 switch (MatchExtension(++ext)) {
1513 case AID_MEDIA_AUDIO: audioSize += size; break;
1514 case AID_MEDIA_VIDEO: videoSize += size; break;
1515 case AID_MEDIA_IMAGE: imageSize += size; break;
1516 }
1517 }
1518 }
1519 // Fall through to always count against total
1520 case FTS_D:
1521 case FTS_DEFAULT:
1522 case FTS_SL:
1523 case FTS_SLNONE:
1524 totalSize += size;
1525 break;
1526 }
1527 }
1528 fts_close(fts);
1529 }
1530
1531 std::vector<int64_t> ret;
1532 ret.push_back(totalSize);
1533 ret.push_back(audioSize);
1534 ret.push_back(videoSize);
1535 ret.push_back(imageSize);
1536#if MEASURE_DEBUG
1537 LOG(DEBUG) << "Final result " << toString(ret);
1538#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001539 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001540 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001541}
1542
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001543binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1544 int32_t userId, int32_t appId, int64_t cacheQuota) {
1545 ENFORCE_UID(AID_SYSTEM);
1546 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001547 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001548
1549 int32_t uid = multiuser_get_uid(userId, appId);
1550 mCacheQuotas[uid] = cacheQuota;
1551
1552 return ok();
1553}
1554
David Sehr6727c2d2016-05-17 16:06:22 -07001555// Dumps the contents of a profile file, using pkgname's dex files for pretty
1556// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001557binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1558 const std::string& codePaths, bool* _aidl_return) {
1559 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001560 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001561 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001562
1563 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001564 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001565
Jeff Sharkey90aff262016-12-12 14:28:24 -07001566 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001567 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001568}
1569
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001570// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001571binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001572 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001573 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001574 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001575 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001576
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001577 const char* pkgname = packageName.c_str();
1578 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001579 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001580}
1581
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001582binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1583 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1584 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1585 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1586 const std::unique_ptr<std::string>& sharedLibraries) {
1587 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001588 CHECK_ARGUMENT_UUID(uuid);
1589 if (packageName && *packageName != "*") {
1590 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1591 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001592 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001593
1594 const char* apk_path = apkPath.c_str();
1595 const char* pkgname = packageName ? packageName->c_str() : "*";
1596 const char* instruction_set = instructionSet.c_str();
1597 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1598 const char* compiler_filter = compilerFilter.c_str();
1599 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1600 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1601
1602 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1603 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001604 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001605}
1606
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001607binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1608 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001609 std::lock_guard<std::recursive_mutex> lock(mLock);
1610
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001611 const char* instruction_set = instructionSet.c_str();
1612
1613 char boot_marker_path[PKG_PATH_MAX];
1614 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001615 "%s/%s/%s/.booting",
1616 android_data_dir.path,
1617 DALVIK_CACHE,
1618 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001619
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001620 ALOGV("mark_boot_complete : %s", boot_marker_path);
1621 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001622 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001623 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001624 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001625}
1626
Mike Lockwood94afecf2012-10-24 10:45:23 -07001627void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1628 struct stat* statbuf)
1629{
1630 while (path[basepos] != 0) {
1631 if (path[basepos] == '/') {
1632 path[basepos] = 0;
1633 if (lstat(path, statbuf) < 0) {
1634 ALOGV("Making directory: %s\n", path);
1635 if (mkdir(path, mode) == 0) {
1636 chown(path, uid, gid);
1637 } else {
1638 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1639 }
1640 }
1641 path[basepos] = '/';
1642 basepos++;
1643 }
1644 basepos++;
1645 }
1646}
1647
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001648binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1649 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1650 const std::string& nativeLibPath32, int32_t userId) {
1651 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001652 CHECK_ARGUMENT_UUID(uuid);
1653 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001654 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001655
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001656 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1657 const char* pkgname = packageName.c_str();
1658 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001659 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001660 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001661
Jeff Sharkey423e7462016-12-09 18:18:43 -07001662 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1663 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001664
1665 const char* pkgdir = _pkgdir.c_str();
1666 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001667
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001668 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001669 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001670 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001671
1672 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001673 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001674 }
1675
1676 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001677 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001678 goto out;
1679 }
1680
1681 if (lstat(libsymlink, &libStat) < 0) {
1682 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001683 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001684 goto out;
1685 }
1686 } else {
1687 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001688 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001689 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001690 goto out;
1691 }
1692 } else if (S_ISLNK(libStat.st_mode)) {
1693 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001694 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001695 goto out;
1696 }
1697 }
1698 }
1699
1700 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001701 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001702 goto out;
1703 }
1704
1705out:
1706 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001707 auto msg = "Failed to cleanup chmod " + _pkgdir;
1708 if (res.isOk()) {
1709 res = error(msg);
1710 } else {
1711 PLOG(ERROR) << msg;
1712 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001713 }
1714
1715 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001716 auto msg = "Failed to cleanup chown " + _pkgdir;
1717 if (res.isOk()) {
1718 res = error(msg);
1719 } else {
1720 PLOG(ERROR) << msg;
1721 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001722 }
1723
Jeff Sharkey423e7462016-12-09 18:18:43 -07001724 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001725}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001726
1727static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1728{
1729 static const char *IDMAP_BIN = "/system/bin/idmap";
1730 static const size_t MAX_INT_LEN = 32;
1731 char idmap_str[MAX_INT_LEN];
1732
1733 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1734
1735 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1736 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1737}
1738
1739// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1740// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1741static int flatten_path(const char *prefix, const char *suffix,
1742 const char *overlay_path, char *idmap_path, size_t N)
1743{
1744 if (overlay_path == NULL || idmap_path == NULL) {
1745 return -1;
1746 }
1747 const size_t len_overlay_path = strlen(overlay_path);
1748 // will access overlay_path + 1 further below; requires absolute path
1749 if (len_overlay_path < 2 || *overlay_path != '/') {
1750 return -1;
1751 }
1752 const size_t len_idmap_root = strlen(prefix);
1753 const size_t len_suffix = strlen(suffix);
1754 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1755 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1756 // additions below would cause overflow
1757 return -1;
1758 }
1759 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1760 return -1;
1761 }
1762 memset(idmap_path, 0, N);
1763 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1764 char *ch = idmap_path + len_idmap_root;
1765 while (*ch != '\0') {
1766 if (*ch == '/') {
1767 *ch = '@';
1768 }
1769 ++ch;
1770 }
1771 return 0;
1772}
1773
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001774binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1775 const std::string& overlayApkPath, int32_t uid) {
1776 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001777 std::lock_guard<std::recursive_mutex> lock(mLock);
1778
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001779 const char* target_apk = targetApkPath.c_str();
1780 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001781 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1782
1783 int idmap_fd = -1;
1784 char idmap_path[PATH_MAX];
1785
1786 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1787 idmap_path, sizeof(idmap_path)) == -1) {
1788 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1789 goto fail;
1790 }
1791
1792 unlink(idmap_path);
1793 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1794 if (idmap_fd < 0) {
1795 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1796 goto fail;
1797 }
1798 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1799 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1800 goto fail;
1801 }
1802 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1803 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1804 goto fail;
1805 }
1806
1807 pid_t pid;
1808 pid = fork();
1809 if (pid == 0) {
1810 /* child -- drop privileges before continuing */
1811 if (setgid(uid) != 0) {
1812 ALOGE("setgid(%d) failed during idmap\n", uid);
1813 exit(1);
1814 }
1815 if (setuid(uid) != 0) {
1816 ALOGE("setuid(%d) failed during idmap\n", uid);
1817 exit(1);
1818 }
1819 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1820 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1821 exit(1);
1822 }
1823
1824 run_idmap(target_apk, overlay_apk, idmap_fd);
1825 exit(1); /* only if exec call to idmap failed */
1826 } else {
1827 int status = wait_child(pid);
1828 if (status != 0) {
1829 ALOGE("idmap failed, status=0x%04x\n", status);
1830 goto fail;
1831 }
1832 }
1833
1834 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001835 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001836fail:
1837 if (idmap_fd >= 0) {
1838 close(idmap_fd);
1839 unlink(idmap_path);
1840 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001841 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001842}
Robert Craige9887e42014-02-20 10:25:56 -05001843
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01001844binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
1845 const char* overlay_apk = overlayApkPath.c_str();
1846 char idmap_path[PATH_MAX];
1847
1848 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1849 idmap_path, sizeof(idmap_path)) == -1) {
1850 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1851 return error();
1852 }
1853 if (unlink(idmap_path) < 0) {
1854 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
1855 return error();
1856 }
1857 return ok();
1858}
1859
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001860binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1861 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1862 const std::string& seInfo) {
1863 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001864 CHECK_ARGUMENT_UUID(uuid);
1865 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001866 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001867
1868 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001869
Robert Craigda30dc72014-03-27 10:21:12 -04001870 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001871 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001872 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1873 const char* pkgName = packageName.c_str();
1874 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001875
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001876 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001877 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001878 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001879 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001880 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001881 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001882 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001883 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001884 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001885 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001886 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001887 }
Robert Craige9887e42014-02-20 10:25:56 -05001888 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001889 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001890}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001891
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001892binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1893 const std::string& instructionSet) {
1894 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001895 std::lock_guard<std::recursive_mutex> lock(mLock);
1896
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001897 const char* oat_dir = oatDir.c_str();
1898 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001899 char oat_instr_dir[PKG_PATH_MAX];
1900
1901 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001902 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001903 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001904 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001905 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001906 }
1907 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001908 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001909 }
1910 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001911 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001912 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001913 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001914 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001915}
1916
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001917binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1918 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001919 std::lock_guard<std::recursive_mutex> lock(mLock);
1920
Jeff Sharkey423e7462016-12-09 18:18:43 -07001921 if (validate_apk_path(packageDir.c_str())) {
1922 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001923 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001924 if (delete_dir_contents_and_dir(packageDir) != 0) {
1925 return error("Failed to delete " + packageDir);
1926 }
1927 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001928}
1929
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001930binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1931 const std::string& fromBase, const std::string& toBase) {
1932 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001933 std::lock_guard<std::recursive_mutex> lock(mLock);
1934
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001935 const char* relative_path = relativePath.c_str();
1936 const char* from_base = fromBase.c_str();
1937 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001938 char from_path[PKG_PATH_MAX];
1939 char to_path[PKG_PATH_MAX];
1940 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1941 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1942
1943 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001944 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001945 }
1946
1947 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001948 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001949 }
1950
Jeff Sharkey423e7462016-12-09 18:18:43 -07001951 if (link(from_path, to_path) < 0) {
1952 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001953 }
1954
Jeff Sharkey423e7462016-12-09 18:18:43 -07001955 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001956}
1957
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001958binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1959 const std::string& instructionSet, const std::string& outputPath) {
1960 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001961 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001962
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001963 const char* apk_path = apkPath.c_str();
1964 const char* instruction_set = instructionSet.c_str();
1965 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07001966
Jeff Sharkey90aff262016-12-12 14:28:24 -07001967 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001968 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08001969}
1970
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001971binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1972 const std::string& instructionSet, const std::string& outputPath) {
1973 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001974 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001975
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001976 const char* apk_path = apkPath.c_str();
1977 const char* instruction_set = instructionSet.c_str();
1978 const char* oat_dir = outputPath.c_str();
1979
Jeff Sharkey90aff262016-12-12 14:28:24 -07001980 bool res = delete_odex(apk_path, instruction_set, oat_dir);
1981 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07001982}
1983
Calin Juravlebd968362017-01-25 01:17:17 -08001984binder::Status InstalldNativeService::reconcileSecondaryDexFile(
1985 const std::string& dexPath, const std::string& packageName, int32_t uid,
1986 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
1987 int32_t storage_flag, bool* _aidl_return) {
1988 ENFORCE_UID(AID_SYSTEM);
1989 CHECK_ARGUMENT_UUID(volumeUuid);
1990 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1991
1992 std::lock_guard<std::recursive_mutex> lock(mLock);
1993 bool result = android::installd::reconcile_secondary_dex_file(
1994 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
1995 return result ? ok() : error();
1996}
1997
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001998binder::Status InstalldNativeService::invalidateMounts() {
1999 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002000 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002001
2002 mQuotaDevices.clear();
2003
2004 std::ifstream in("/proc/mounts");
2005 if (!in.is_open()) {
2006 return error("Failed to read mounts");
2007 }
2008
2009 std::string source;
2010 std::string target;
2011 std::string ignored;
2012 struct dqblk dq;
2013 while (!in.eof()) {
2014 std::getline(in, source, ' ');
2015 std::getline(in, target, ' ');
2016 std::getline(in, ignored);
2017
2018 if (source.compare(0, 11, "/dev/block/") == 0) {
2019 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2020 reinterpret_cast<char*>(&dq)) == 0) {
2021 LOG(DEBUG) << "Found " << source << " with quota";
2022 mQuotaDevices[target] = source;
2023 }
2024 }
2025 }
2026 return ok();
2027}
2028
2029std::string InstalldNativeService::findQuotaDeviceForUuid(
2030 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002031 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002032 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2033 return mQuotaDevices[path];
2034}
2035
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002036binder::Status InstalldNativeService::isQuotaSupported(
2037 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2038 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2039 return ok();
2040}
2041
Andreas Gampe02d0de52015-11-11 20:43:16 -08002042} // namespace installd
2043} // namespace android