blob: 987e8da2e5a09cd05fa9e00af339446ab66ad91a [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 Sharkeydf2d7542017-01-07 09:19:35 -070059#include "MatchExtensionGen.h"
60
Andreas Gampe02d0de52015-11-11 20:43:16 -080061#ifndef LOG_TAG
62#define LOG_TAG "installd"
63#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070064
65using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070066using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070067
Andreas Gampe02d0de52015-11-11 20:43:16 -080068namespace android {
69namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070070
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070071static constexpr const char* kCpPath = "/system/bin/cp";
72static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070073
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070074static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000075
Andreas Gampe0354bd02016-06-27 14:25:30 -070076static constexpr const char* PKG_LIB_POSTFIX = "/lib";
77static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
78static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
79
80static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
81static constexpr const char* IDMAP_SUFFIX = "@idmap";
82
83// NOTE: keep in sync with StorageManager
84static constexpr int FLAG_STORAGE_DE = 1 << 0;
85static constexpr int FLAG_STORAGE_CE = 1 << 1;
86
87// NOTE: keep in sync with Installer
88static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
89static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070090static constexpr int FLAG_USE_QUOTA = 1 << 12;
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 Sharkey66b1a122017-01-16 20:57:45 -0700204 out << "installd is happy!" << endl << endl;
205 out << "Devices with quota support:" << endl;
206 for (const auto& n : mQuotaDevices) {
207 out << " " << n.first << " = " << n.second << endl;
208 }
209 out << endl;
210 out.flush();
211
Jeff Sharkey0274c972016-12-06 09:32:04 -0700212 return NO_ERROR;
213}
214
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600215/**
216 * Perform restorecon of the given path, but only perform recursive restorecon
217 * if the label of that top-level file actually changed. This can save us
218 * significant time by avoiding no-op traversals of large filesystem trees.
219 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700220static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
221 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600222 int res = 0;
223 char* before = nullptr;
224 char* after = nullptr;
225
226 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
227 // libselinux. Not needed here.
228
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600229 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600230 PLOG(ERROR) << "Failed before getfilecon for " << path;
231 goto fail;
232 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700233 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600234 PLOG(ERROR) << "Failed top-level restorecon for " << path;
235 goto fail;
236 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600237 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600238 PLOG(ERROR) << "Failed after getfilecon for " << path;
239 goto fail;
240 }
241
242 // If the initial top-level restorecon above changed the label, then go
243 // back and restorecon everything recursively
244 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700245 if (existing) {
246 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
247 << path << "; running recursive restorecon";
248 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700249 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600250 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
251 PLOG(ERROR) << "Failed recursive restorecon for " << path;
252 goto fail;
253 }
254 }
255
256 goto done;
257fail:
258 res = -1;
259done:
260 free(before);
261 free(after);
262 return res;
263}
264
Jeff Sharkey0274c972016-12-06 09:32:04 -0700265static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700266 const std::string& seInfo, uid_t uid, bool existing) {
267 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
268 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600269}
270
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600271static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600272 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
273 PLOG(ERROR) << "Failed to prepare " << path;
274 return -1;
275 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600276 return 0;
277}
278
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700279/**
280 * Prepare an app cache directory, which offers to fix-up the GID and
281 * directory mode flags during a platform upgrade.
282 */
283static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
284 uid_t uid, gid_t gid) {
285 auto path = StringPrintf("%s/%s", parent.c_str(), name);
286 struct stat st;
287 if (stat(path.c_str(), &st) != 0) {
288 if (errno == ENOENT) {
289 // This is fine, just create it
290 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
291 PLOG(ERROR) << "Failed to prepare " << path;
292 return -1;
293 } else {
294 return 0;
295 }
296 } else {
297 PLOG(ERROR) << "Failed to stat " << path;
298 return -1;
299 }
300 }
301
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700302 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700303 if (st.st_uid != uid) {
304 // Mismatched UID is real trouble; we can't recover
305 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
306 << " but expected " << uid;
307 return -1;
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700308 } else if (st.st_gid == gid && actual_mode == target_mode) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700309 // Everything looks good!
310 return 0;
311 }
312
313 // Directory is owned correctly, but GID or mode mismatch means it's
314 // probably a platform upgrade so we need to fix them
315 FTS *fts;
316 FTSENT *p;
317 char *argv[] = { (char*) path.c_str(), nullptr };
318 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
319 PLOG(ERROR) << "Failed to fts_open " << path;
320 return -1;
321 }
322 while ((p = fts_read(fts)) != NULL) {
323 switch (p->fts_info) {
324 case FTS_DP:
325 if (chmod(p->fts_accpath, target_mode) != 0) {
326 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
327 }
328 // Intentional fall through to also set GID
329 case FTS_F:
330 if (chown(p->fts_accpath, -1, gid) != 0) {
331 PLOG(WARNING) << "Failed to chown " << p->fts_path;
332 }
333 break;
334 case FTS_SL:
335 case FTS_SLNONE:
336 if (lchown(p->fts_accpath, -1, gid) != 0) {
337 PLOG(WARNING) << "Failed to chown " << p->fts_path;
338 }
339 break;
340 }
341 }
342 fts_close(fts);
343 return 0;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600344}
345
Jeff Sharkey0274c972016-12-06 09:32:04 -0700346binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
347 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700348 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700349 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700350 CHECK_ARGUMENT_UUID(uuid);
351 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700352 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700353
354 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
355 const char* pkgname = packageName.c_str();
356
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700357 // Assume invalid inode unless filled in below
358 if (_aidl_return != nullptr) *_aidl_return = -1;
359
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700360 int32_t uid = multiuser_get_uid(userId, appId);
361 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700362 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
363
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700364 // If UID doesn't have a specific cache GID, use UID value
365 if (cacheGid == -1) {
366 cacheGid = uid;
367 }
368
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700369 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700370 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700371 bool existing = (access(path.c_str(), F_OK) == 0);
372
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700373 if (prepare_app_dir(path, targetMode, uid) ||
374 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
375 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700376 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600377 }
378
379 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700380 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
381 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
382 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700383 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700384 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600385
386 // Remember inode numbers of cache directories so that we can clear
387 // contents while CE storage is locked
388 if (write_path_inode(path, "cache", kXattrInodeCache) ||
389 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700390 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700391 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700392
393 // And return the CE inode of the top-level data directory so we can
394 // clear contents while CE storage is locked
395 if ((_aidl_return != nullptr)
396 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
397 return error("Failed to get_path_inode for " + path);
398 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700399 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700400 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700401 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700402 bool existing = (access(path.c_str(), F_OK) == 0);
403
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700404 if (prepare_app_dir(path, targetMode, uid) ||
405 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
406 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700407 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700408 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000409
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600410 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700411 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700412 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600413 }
414
Jeff Sharkey90aff262016-12-12 14:28:24 -0700415 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700416 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000417 // read-write-execute only for the app user.
418 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700419 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000420 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100421 std::string profile_file = create_primary_profile(profile_path);
422 // read-write only for the app user.
423 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700424 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100425 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000426 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
427 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
428 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700429 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700430 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000431 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700432 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000433 }
434 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700435 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700436 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700437}
438
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700439binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
440 const std::string& packageName, int32_t userId, int32_t flags) {
441 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700442 CHECK_ARGUMENT_UUID(uuid);
443 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700444 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700445
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700446 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
447 const char* pkgname = packageName.c_str();
448
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700449 // This method only exists to upgrade system apps that have requested
450 // forceDeviceEncrypted, so their default storage always lives in a
451 // consistent location. This only works on non-FBE devices, since we
452 // never want to risk exposing data on a device with real CE/DE storage.
453
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700454 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
455 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700456
457 // If neither directory is marked as default, assume CE is default
458 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
459 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
460 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700461 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700462 }
463 }
464
465 // Migrate default data location if needed
466 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
467 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
468
469 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
470 LOG(WARNING) << "Requested default storage " << target
471 << " is not active; migrating from " << source;
472 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700473 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700474 }
475 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700476 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700477 }
478 }
479
Jeff Sharkey423e7462016-12-09 18:18:43 -0700480 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700481}
482
Calin Juravle6a1648e2016-02-01 12:12:16 +0000483
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700484binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
485 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700486 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700487 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700488
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700489 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700490 binder::Status res = ok();
491 if (!clear_reference_profile(pkgname)) {
492 res = error("Failed to clear reference profile for " + packageName);
493 }
494 if (!clear_current_profiles(pkgname)) {
495 res = error("Failed to clear current profiles for " + packageName);
496 }
497 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000498}
499
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
501 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
502 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700503 CHECK_ARGUMENT_UUID(uuid);
504 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700505 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700506
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700507 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
508 const char* pkgname = packageName.c_str();
509
Jeff Sharkey423e7462016-12-09 18:18:43 -0700510 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700511 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700512 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600513 if (flags & FLAG_CLEAR_CACHE_ONLY) {
514 path = read_path_inode(path, "cache", kXattrInodeCache);
515 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
516 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
517 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700518 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700519 if (delete_dir_contents(path) != 0) {
520 res = error("Failed to delete contents of " + path);
521 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700522 }
523 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700524 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600525 std::string suffix = "";
526 bool only_cache = false;
527 if (flags & FLAG_CLEAR_CACHE_ONLY) {
528 suffix = CACHE_DIR_POSTFIX;
529 only_cache = true;
530 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
531 suffix = CODE_CACHE_DIR_POSTFIX;
532 only_cache = true;
533 }
534
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700535 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700536 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700537 if (delete_dir_contents(path) != 0) {
538 res = error("Failed to delete contents of " + path);
539 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700540 }
Calin Juravleedae6692016-03-23 13:55:31 +0000541 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700542 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700543 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000544 }
545 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700546 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700548}
549
Calin Juravle7535e8e2016-03-29 16:05:40 +0100550static int destroy_app_reference_profile(const char *pkgname) {
551 return delete_dir_contents_and_dir(
552 create_data_ref_profile_package_path(pkgname),
553 /*ignore_if_missing*/ true);
554}
555
Calin Juravleedae6692016-03-23 13:55:31 +0000556static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100557 return delete_dir_contents_and_dir(
558 create_data_user_profile_package_path(userid, pkgname),
559 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000560}
561
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700562binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
563 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700565 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700566
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700567 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000569 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
570 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700571 if (destroy_app_current_profiles(pkgname, user) != 0) {
572 res = error("Failed to destroy current profiles for " + packageName);
573 }
Calin Juravleedae6692016-03-23 13:55:31 +0000574 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700575 if (destroy_app_reference_profile(pkgname) != 0) {
576 res = error("Failed to destroy reference profile for " + packageName);
577 }
578 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000579}
580
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700581binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
582 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
583 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 CHECK_ARGUMENT_UUID(uuid);
585 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700586 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700587
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700588 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
589 const char* pkgname = packageName.c_str();
590
Jeff Sharkey423e7462016-12-09 18:18:43 -0700591 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700592 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700593 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
594 if (delete_dir_contents_and_dir(path) != 0) {
595 res = error("Failed to delete " + path);
596 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700597 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700598 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700599 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
600 if (delete_dir_contents_and_dir(path) != 0) {
601 res = error("Failed to delete " + path);
602 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700603 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100604 // TODO(calin): If the package is still installed by other users it's probably
605 // beneficial to keep the reference profile around.
606 // Verify if it's ok to do that.
607 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700608 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700609 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700610}
611
Jeff Sharkey0274c972016-12-06 09:32:04 -0700612binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
613 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
614 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
615 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700616 ENFORCE_UID(AID_SYSTEM);
617 CHECK_ARGUMENT_UUID(fromUuid);
618 CHECK_ARGUMENT_UUID(toUuid);
619 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700620 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700621
622 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
623 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
624 const char* package_name = packageName.c_str();
625 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700626
Jeff Sharkey423e7462016-12-09 18:18:43 -0700627 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700628 std::vector<userid_t> users = get_known_users(from_uuid);
629
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700630 // Copy app
631 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600632 auto from = create_data_app_package_path(from_uuid, data_app_name);
633 auto to = create_data_app_package_path(to_uuid, data_app_name);
634 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700635
636 char *argv[] = {
637 (char*) kCpPath,
638 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
639 (char*) "-p", /* preserve timestamps, ownership, and permissions */
640 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
641 (char*) "-P", /* Do not follow symlinks [default] */
642 (char*) "-d", /* don't dereference symlinks */
643 (char*) from.c_str(),
644 (char*) to_parent.c_str()
645 };
646
647 LOG(DEBUG) << "Copying " << from << " to " << to;
648 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700649 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700650 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700651 goto fail;
652 }
653
654 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700655 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700656 goto fail;
657 }
658 }
659
660 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700661 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700662
663 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600664 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
665 if (access(from_ce.c_str(), F_OK) != 0) {
666 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700667 continue;
668 }
669
Jeff Sharkey0274c972016-12-06 09:32:04 -0700670 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700671 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700672 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700673 goto fail;
674 }
675
676 char *argv[] = {
677 (char*) kCpPath,
678 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
679 (char*) "-p", /* preserve timestamps, ownership, and permissions */
680 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
681 (char*) "-P", /* Do not follow symlinks [default] */
682 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600683 nullptr,
684 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700685 };
686
Jeff Sharkey51c94492016-05-10 17:46:39 -0600687 {
688 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
689 auto to = create_data_user_de_path(to_uuid, user);
690 argv[6] = (char*) from.c_str();
691 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700692
Jeff Sharkey51c94492016-05-10 17:46:39 -0600693 LOG(DEBUG) << "Copying " << from << " to " << to;
694 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
695 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700696 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600697 goto fail;
698 }
699 }
700 {
701 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
702 auto to = create_data_user_ce_path(to_uuid, user);
703 argv[6] = (char*) from.c_str();
704 argv[7] = (char*) to.c_str();
705
706 LOG(DEBUG) << "Copying " << from << " to " << to;
707 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
708 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700709 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600710 goto fail;
711 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700712 }
713
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700714 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
715 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700716 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700717 goto fail;
718 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700719 }
720
Jeff Sharkey31f08982015-07-07 13:31:37 -0700721 // We let the framework scan the new location and persist that before
722 // deleting the data in the old location; this ordering ensures that
723 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700724 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700725
726fail:
727 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700728 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600729 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700730 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
731 LOG(WARNING) << "Failed to rollback " << to;
732 }
733 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700734 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600735 {
736 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
737 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
738 LOG(WARNING) << "Failed to rollback " << to;
739 }
740 }
741 {
742 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
743 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
744 LOG(WARNING) << "Failed to rollback " << to;
745 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700746 }
747 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700749}
750
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700751binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
752 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
753 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700754 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700755 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700756
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700757 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600758 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700759 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700760 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700761 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700762 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700763 }
764 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700765 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700766}
767
768binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
769 int32_t userId, int32_t flags) {
770 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700771 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700772 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700773
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700774 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700775 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700776 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700777 auto path = create_data_user_de_path(uuid_, userId);
778 if (delete_dir_contents_and_dir(path, true) != 0) {
779 res = error("Failed to delete " + path);
780 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700781 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700782 path = create_data_misc_legacy_path(userId);
783 if (delete_dir_contents_and_dir(path, true) != 0) {
784 res = error("Failed to delete " + path);
785 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700786 path = create_data_user_profile_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700787 if (delete_dir_contents_and_dir(path, true) != 0) {
788 res = error("Failed to delete " + path);
789 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700790 }
Robin Lee095c7632014-04-25 15:05:19 +0100791 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600792 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700793 auto path = create_data_user_ce_path(uuid_, userId);
794 if (delete_dir_contents_and_dir(path, true) != 0) {
795 res = error("Failed to delete " + path);
796 }
797 path = create_data_media_path(uuid_, userId);
798 if (delete_dir_contents_and_dir(path, true) != 0) {
799 res = error("Failed to delete " + path);
800 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600801 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700802 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100803}
804
Mike Lockwood94afecf2012-10-24 10:45:23 -0700805/* Try to ensure free_size bytes of storage are available.
806 * Returns 0 on success.
807 * This is rather simple-minded because doing a full LRU would
808 * be potentially memory-intensive, and without atime it would
809 * also require that apps constantly modify file metadata even
810 * when just reading from the cache, which is pretty awful.
811 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700812binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
813 int64_t freeStorageSize) {
814 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700815 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700816 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700817
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700818 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700819 cache_t* cache;
820 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700821
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700822 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700823
824 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700825 if (avail < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700826 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700827 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700828
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700829 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
830 if (avail >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700831 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700832 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700833
834 cache = start_cache_collection();
835
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700836 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600837 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700838 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
839 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600840 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700841 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700842 }
843
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700844 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700845 finish_cache_collection(cache);
846
Jeff Sharkey423e7462016-12-09 18:18:43 -0700847 avail = data_disk_free(data_path);
848 if (avail >= freeStorageSize) {
849 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700850 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700851 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
852 freeStorageSize, data_path.c_str(), avail));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700853 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700854}
855
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700856binder::Status InstalldNativeService::rmdex(const std::string& codePath,
857 const std::string& instructionSet) {
858 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700859 std::lock_guard<std::recursive_mutex> lock(mLock);
860
Mike Lockwood94afecf2012-10-24 10:45:23 -0700861 char dex_path[PKG_PATH_MAX];
862
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700863 const char* path = codePath.c_str();
864 const char* instruction_set = instructionSet.c_str();
865
Jeff Sharkey770180a2014-09-08 17:14:26 -0700866 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700867 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700868 }
869
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700870 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700871 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700872 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700873
874 ALOGV("unlink %s\n", dex_path);
875 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700876 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700877 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700878 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700879 }
880}
881
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700882struct stats {
883 int64_t codeSize;
884 int64_t dataSize;
885 int64_t cacheSize;
886};
887
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700888#if MEASURE_DEBUG
889static std::string toString(std::vector<int64_t> values) {
890 std::stringstream res;
891 res << "[";
892 for (size_t i = 0; i < values.size(); i++) {
893 res << values[i];
894 if (i < values.size() - 1) {
895 res << ",";
896 }
897 }
898 res << "]";
899 return res.str();
900}
901#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700902
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700903static void collectQuotaStats(const std::string& device, int32_t userId,
904 int32_t appId, struct stats* stats, struct stats* extStats ATTRIBUTE_UNUSED) {
905 if (device.empty()) return;
906
907 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700908
909 uid_t uid = multiuser_get_uid(userId, appId);
910 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
911 reinterpret_cast<char*>(&dq)) != 0) {
912 if (errno != ESRCH) {
913 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
914 }
915 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700916#if MEASURE_DEBUG
917 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
918#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700919 stats->dataSize += dq.dqb_curspace;
920 }
921
922 int cacheGid = multiuser_get_cache_gid(userId, appId);
923 if (cacheGid != -1) {
924 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
925 reinterpret_cast<char*>(&dq)) != 0) {
926 if (errno != ESRCH) {
927 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
928 }
929 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700930#if MEASURE_DEBUG
931 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
932#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700933 stats->cacheSize += dq.dqb_curspace;
934 }
935 }
936
937 int sharedGid = multiuser_get_shared_app_gid(uid);
938 if (sharedGid != -1) {
939 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
940 reinterpret_cast<char*>(&dq)) != 0) {
941 if (errno != ESRCH) {
942 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
943 }
944 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700945#if MEASURE_DEBUG
946 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
947#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700948 stats->codeSize += dq.dqb_curspace;
949 }
950 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700951
952#if MEASURE_EXTERNAL
953 // TODO: measure using external GIDs
954#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700955}
956
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700957static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700958 DIR *d;
959 int dfd;
960 struct dirent *de;
961 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700962
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600963 d = opendir(path.c_str());
964 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700965 if (errno != ENOENT) {
966 PLOG(WARNING) << "Failed to open " << path;
967 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600968 return;
969 }
970 dfd = dirfd(d);
971 while ((de = readdir(d))) {
972 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700973
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700974 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600975 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700976 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600977 }
978
979 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700980 if (!strcmp(name, ".")) {
981 // Don't recurse, but still count node size
982 } else if (!strcmp(name, "..")) {
983 // Don't recurse or count node size
984 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700985 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700986 // Measure all children nodes
987 size = 0;
988 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700989 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700990
991 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
992 stats->cacheSize += size;
993 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700994 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700995
996 // Legacy symlink isn't owned by app
997 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
998 continue;
999 }
1000
1001 // Everything found inside is considered data
1002 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001003 }
1004 closedir(d);
1005}
1006
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001007static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1008 bool exclude_apps = false) {
1009 DIR *d;
1010 int dfd;
1011 struct dirent *de;
1012 struct stat s;
1013
1014 d = opendir(path.c_str());
1015 if (d == nullptr) {
1016 if (errno != ENOENT) {
1017 PLOG(WARNING) << "Failed to open " << path;
1018 }
1019 return;
1020 }
1021 dfd = dirfd(d);
1022 while ((de = readdir(d))) {
1023 if (de->d_type == DT_DIR) {
1024 const char *name = de->d_name;
1025 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1026 continue;
1027 }
1028 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1029 continue;
1030 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1031 continue;
1032 } else {
1033 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1034 }
1035 }
1036 }
1037 closedir(d);
1038}
1039
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001040binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001041 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1042 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1043 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001044 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001045 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001046 for (auto packageName : packageNames) {
1047 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1048 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001049 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001050
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001051 // When modifying this logic, always verify using tests:
1052 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1053
1054#if MEASURE_DEBUG
1055 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1056#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001057
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001058 // Here's a summary of the common storage locations across the platform,
1059 // and how they're each tagged:
1060 //
1061 // /data/app/com.example UID system
1062 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001063 // /data/user/0/com.example UID u0_a10 GID u0_a10
1064 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1065 // /data/media/0/foo.txt UID u0_media_rw
1066 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1067 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1068 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1069 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001070
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001071 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001072 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001073 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001074 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001075
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001076 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001077
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001078 auto device = findQuotaDeviceForUuid(uuid);
1079 if (device.empty()) {
1080 flags &= ~FLAG_USE_QUOTA;
1081 }
1082
Jeff Sharkey466459b2017-01-17 15:25:01 -07001083 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001084 for (auto packageName : packageNames) {
1085 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1086 calculate_tree_size(obbCodePath, &extStats.codeSize);
1087 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001088 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001089
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001090 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001091 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001092 for (auto codePath : codePaths) {
1093 calculate_tree_size(codePath, &stats.codeSize, -1,
1094 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001095 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001096 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001097
Jeff Sharkey466459b2017-01-17 15:25:01 -07001098 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001099 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001100 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001101
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001102 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001103 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001104 for (auto codePath : codePaths) {
1105 calculate_tree_size(codePath, &stats.codeSize);
1106 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001107 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001108
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001109 for (size_t i = 0; i < packageNames.size(); i++) {
1110 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001111
Jeff Sharkey466459b2017-01-17 15:25:01 -07001112 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001113 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1114 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001115 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1116 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001117 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001118
Jeff Sharkey466459b2017-01-17 15:25:01 -07001119 ATRACE_BEGIN("profiles");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001120 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1121 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001122 auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1123 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001124 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001125
1126#if MEASURE_EXTERNAL
Jeff Sharkey466459b2017-01-17 15:25:01 -07001127 ATRACE_BEGIN("external");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001128 auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data");
1129 collectManualStats(extPath, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001130 auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media");
1131 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001132 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001133#endif
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001134 }
1135
Jeff Sharkey466459b2017-01-17 15:25:01 -07001136 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001137 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1138 if (sharedGid != -1) {
1139 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1140 sharedGid, -1);
1141 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001142 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1143 multiuser_get_uid(userId, appId), -1);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001144 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001145 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001146
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001147 std::vector<int64_t> ret;
1148 ret.push_back(stats.codeSize);
1149 ret.push_back(stats.dataSize);
1150 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001151 ret.push_back(extStats.codeSize);
1152 ret.push_back(extStats.dataSize);
1153 ret.push_back(extStats.cacheSize);
1154#if MEASURE_DEBUG
1155 LOG(DEBUG) << "Final result " << toString(ret);
1156#endif
1157 *_aidl_return = ret;
1158 return ok();
1159}
1160
1161binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1162 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1163 std::vector<int64_t>* _aidl_return) {
1164 ENFORCE_UID(AID_SYSTEM);
1165 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001166 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001167
1168 // When modifying this logic, always verify using tests:
1169 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1170
1171#if MEASURE_DEBUG
1172 LOG(INFO) << "Measuring user " << userId;
1173#endif
1174
1175 struct stats stats;
1176 struct stats extStats;
1177 memset(&stats, 0, sizeof(stats));
1178 memset(&extStats, 0, sizeof(extStats));
1179
1180 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1181
Jeff Sharkey466459b2017-01-17 15:25:01 -07001182 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001183 auto obbPath = create_data_path(uuid_) + "/media/obb";
1184 calculate_tree_size(obbPath, &extStats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001185 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001186
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001187 auto device = findQuotaDeviceForUuid(uuid);
1188 if (device.empty()) {
1189 flags &= ~FLAG_USE_QUOTA;
1190 }
1191
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001192 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001193 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001194 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001195 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001196
Jeff Sharkey466459b2017-01-17 15:25:01 -07001197 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001198 auto cePath = create_data_user_ce_path(uuid_, userId);
1199 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001200 auto dePath = create_data_user_de_path(uuid_, userId);
1201 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001202 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001203
Jeff Sharkey466459b2017-01-17 15:25:01 -07001204 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001205 auto userProfilePath = create_data_user_profile_path(userId);
1206 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001207 auto refProfilePath = create_data_ref_profile_path();
1208 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001209 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001210
1211#if MEASURE_EXTERNAL
Jeff Sharkey466459b2017-01-17 15:25:01 -07001212 ATRACE_BEGIN("external");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001213 // TODO: measure external storage paths
Jeff Sharkey466459b2017-01-17 15:25:01 -07001214 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001215#endif
1216
Jeff Sharkey466459b2017-01-17 15:25:01 -07001217 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001218 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1219 -1, -1, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001220 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1221 -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001222 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001223
Jeff Sharkey466459b2017-01-17 15:25:01 -07001224 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001225 for (auto appId : appIds) {
1226 if (appId >= AID_APP_START) {
1227 collectQuotaStats(device, userId, appId, &stats, &extStats);
1228#if MEASURE_DEBUG
1229 // Sleep to make sure we don't lose logs
1230 usleep(1);
1231#endif
1232 }
1233 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001234 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001235 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001236 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001237 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001238 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001239
Jeff Sharkey466459b2017-01-17 15:25:01 -07001240 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001241 auto cePath = create_data_user_ce_path(uuid_, userId);
1242 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001243 auto dePath = create_data_user_de_path(uuid_, userId);
1244 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001245 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001246
Jeff Sharkey466459b2017-01-17 15:25:01 -07001247 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001248 auto userProfilePath = create_data_user_profile_path(userId);
1249 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001250 auto refProfilePath = create_data_ref_profile_path();
1251 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001252 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001253
1254#if MEASURE_EXTERNAL
Jeff Sharkey466459b2017-01-17 15:25:01 -07001255 ATRACE_BEGIN("external");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001256 // TODO: measure external storage paths
Jeff Sharkey466459b2017-01-17 15:25:01 -07001257 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001258#endif
1259
Jeff Sharkey466459b2017-01-17 15:25:01 -07001260 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001261 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001262 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001263 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001264 }
1265
1266 std::vector<int64_t> ret;
1267 ret.push_back(stats.codeSize);
1268 ret.push_back(stats.dataSize);
1269 ret.push_back(stats.cacheSize);
1270 ret.push_back(extStats.codeSize);
1271 ret.push_back(extStats.dataSize);
1272 ret.push_back(extStats.cacheSize);
1273#if MEASURE_DEBUG
1274 LOG(DEBUG) << "Final result " << toString(ret);
1275#endif
1276 *_aidl_return = ret;
1277 return ok();
1278}
1279
1280binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1281 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1282 ENFORCE_UID(AID_SYSTEM);
1283 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001284 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001285
1286 // When modifying this logic, always verify using tests:
1287 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1288
1289#if MEASURE_DEBUG
1290 LOG(INFO) << "Measuring external " << userId;
1291#endif
1292
1293 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1294
1295 int64_t totalSize = 0;
1296 int64_t audioSize = 0;
1297 int64_t videoSize = 0;
1298 int64_t imageSize = 0;
1299
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001300 auto device = findQuotaDeviceForUuid(uuid);
1301 if (device.empty()) {
1302 flags &= ~FLAG_USE_QUOTA;
1303 }
1304
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001305 if (flags & FLAG_USE_QUOTA) {
1306 struct dqblk dq;
1307
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001308 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1309 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1310 reinterpret_cast<char*>(&dq)) != 0) {
1311 if (errno != ESRCH) {
1312 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1313 }
1314 } else {
1315#if MEASURE_DEBUG
1316 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1317#endif
1318 totalSize = dq.dqb_curspace;
1319 }
1320
1321 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1322 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1323 reinterpret_cast<char*>(&dq)) == 0) {
1324#if MEASURE_DEBUG
1325 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1326#endif
1327 audioSize = dq.dqb_curspace;
1328 }
1329 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1330 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1331 reinterpret_cast<char*>(&dq)) == 0) {
1332#if MEASURE_DEBUG
1333 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1334#endif
1335 videoSize = dq.dqb_curspace;
1336 }
1337 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1338 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1339 reinterpret_cast<char*>(&dq)) == 0) {
1340#if MEASURE_DEBUG
1341 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1342#endif
1343 imageSize = dq.dqb_curspace;
1344 }
1345 } else {
1346 FTS *fts;
1347 FTSENT *p;
1348 auto path = create_data_media_path(uuid_, userId);
1349 char *argv[] = { (char*) path.c_str(), nullptr };
1350 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1351 return error("Failed to fts_open " + path);
1352 }
1353 while ((p = fts_read(fts)) != NULL) {
1354 char* ext;
1355 int64_t size = (p->fts_statp->st_blocks * 512);
1356 switch (p->fts_info) {
1357 case FTS_F:
1358 // Only categorize files not belonging to apps
1359 if (p->fts_statp->st_gid < AID_APP_START) {
1360 ext = strrchr(p->fts_name, '.');
1361 if (ext != nullptr) {
1362 switch (MatchExtension(++ext)) {
1363 case AID_MEDIA_AUDIO: audioSize += size; break;
1364 case AID_MEDIA_VIDEO: videoSize += size; break;
1365 case AID_MEDIA_IMAGE: imageSize += size; break;
1366 }
1367 }
1368 }
1369 // Fall through to always count against total
1370 case FTS_D:
1371 case FTS_DEFAULT:
1372 case FTS_SL:
1373 case FTS_SLNONE:
1374 totalSize += size;
1375 break;
1376 }
1377 }
1378 fts_close(fts);
1379 }
1380
1381 std::vector<int64_t> ret;
1382 ret.push_back(totalSize);
1383 ret.push_back(audioSize);
1384 ret.push_back(videoSize);
1385 ret.push_back(imageSize);
1386#if MEASURE_DEBUG
1387 LOG(DEBUG) << "Final result " << toString(ret);
1388#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001389 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001390 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001391}
1392
David Sehr6727c2d2016-05-17 16:06:22 -07001393// Dumps the contents of a profile file, using pkgname's dex files for pretty
1394// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001395binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1396 const std::string& codePaths, bool* _aidl_return) {
1397 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001398 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001399 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001400
1401 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001402 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001403
Jeff Sharkey90aff262016-12-12 14:28:24 -07001404 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001405 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001406}
1407
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001408// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001409binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001410 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001411 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001412 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001413 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001414
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001415 const char* pkgname = packageName.c_str();
1416 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001417 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001418}
1419
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001420binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1421 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1422 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1423 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1424 const std::unique_ptr<std::string>& sharedLibraries) {
1425 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001426 CHECK_ARGUMENT_UUID(uuid);
1427 if (packageName && *packageName != "*") {
1428 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1429 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001430 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001431
1432 const char* apk_path = apkPath.c_str();
1433 const char* pkgname = packageName ? packageName->c_str() : "*";
1434 const char* instruction_set = instructionSet.c_str();
1435 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1436 const char* compiler_filter = compilerFilter.c_str();
1437 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1438 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1439
1440 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1441 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001442 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001443}
1444
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001445binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1446 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001447 std::lock_guard<std::recursive_mutex> lock(mLock);
1448
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001449 const char* instruction_set = instructionSet.c_str();
1450
1451 char boot_marker_path[PKG_PATH_MAX];
1452 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001453 "%s/%s/%s/.booting",
1454 android_data_dir.path,
1455 DALVIK_CACHE,
1456 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001457
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001458 ALOGV("mark_boot_complete : %s", boot_marker_path);
1459 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001460 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001461 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001462 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001463}
1464
Mike Lockwood94afecf2012-10-24 10:45:23 -07001465void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1466 struct stat* statbuf)
1467{
1468 while (path[basepos] != 0) {
1469 if (path[basepos] == '/') {
1470 path[basepos] = 0;
1471 if (lstat(path, statbuf) < 0) {
1472 ALOGV("Making directory: %s\n", path);
1473 if (mkdir(path, mode) == 0) {
1474 chown(path, uid, gid);
1475 } else {
1476 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1477 }
1478 }
1479 path[basepos] = '/';
1480 basepos++;
1481 }
1482 basepos++;
1483 }
1484}
1485
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001486binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1487 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1488 const std::string& nativeLibPath32, int32_t userId) {
1489 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001490 CHECK_ARGUMENT_UUID(uuid);
1491 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001492 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001493
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001494 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1495 const char* pkgname = packageName.c_str();
1496 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001497 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001498 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001499
Jeff Sharkey423e7462016-12-09 18:18:43 -07001500 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1501 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001502
1503 const char* pkgdir = _pkgdir.c_str();
1504 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001505
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001506 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001507 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001508 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001509
1510 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001511 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001512 }
1513
1514 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001515 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001516 goto out;
1517 }
1518
1519 if (lstat(libsymlink, &libStat) < 0) {
1520 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001521 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001522 goto out;
1523 }
1524 } else {
1525 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001526 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001527 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001528 goto out;
1529 }
1530 } else if (S_ISLNK(libStat.st_mode)) {
1531 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001532 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001533 goto out;
1534 }
1535 }
1536 }
1537
1538 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001539 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001540 goto out;
1541 }
1542
1543out:
1544 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001545 auto msg = "Failed to cleanup chmod " + _pkgdir;
1546 if (res.isOk()) {
1547 res = error(msg);
1548 } else {
1549 PLOG(ERROR) << msg;
1550 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001551 }
1552
1553 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001554 auto msg = "Failed to cleanup chown " + _pkgdir;
1555 if (res.isOk()) {
1556 res = error(msg);
1557 } else {
1558 PLOG(ERROR) << msg;
1559 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001560 }
1561
Jeff Sharkey423e7462016-12-09 18:18:43 -07001562 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001563}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001564
1565static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1566{
1567 static const char *IDMAP_BIN = "/system/bin/idmap";
1568 static const size_t MAX_INT_LEN = 32;
1569 char idmap_str[MAX_INT_LEN];
1570
1571 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1572
1573 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1574 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1575}
1576
1577// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1578// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1579static int flatten_path(const char *prefix, const char *suffix,
1580 const char *overlay_path, char *idmap_path, size_t N)
1581{
1582 if (overlay_path == NULL || idmap_path == NULL) {
1583 return -1;
1584 }
1585 const size_t len_overlay_path = strlen(overlay_path);
1586 // will access overlay_path + 1 further below; requires absolute path
1587 if (len_overlay_path < 2 || *overlay_path != '/') {
1588 return -1;
1589 }
1590 const size_t len_idmap_root = strlen(prefix);
1591 const size_t len_suffix = strlen(suffix);
1592 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1593 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1594 // additions below would cause overflow
1595 return -1;
1596 }
1597 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1598 return -1;
1599 }
1600 memset(idmap_path, 0, N);
1601 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1602 char *ch = idmap_path + len_idmap_root;
1603 while (*ch != '\0') {
1604 if (*ch == '/') {
1605 *ch = '@';
1606 }
1607 ++ch;
1608 }
1609 return 0;
1610}
1611
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001612binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1613 const std::string& overlayApkPath, int32_t uid) {
1614 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001615 std::lock_guard<std::recursive_mutex> lock(mLock);
1616
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001617 const char* target_apk = targetApkPath.c_str();
1618 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001619 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1620
1621 int idmap_fd = -1;
1622 char idmap_path[PATH_MAX];
1623
1624 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1625 idmap_path, sizeof(idmap_path)) == -1) {
1626 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1627 goto fail;
1628 }
1629
1630 unlink(idmap_path);
1631 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1632 if (idmap_fd < 0) {
1633 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1634 goto fail;
1635 }
1636 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1637 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1638 goto fail;
1639 }
1640 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1641 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1642 goto fail;
1643 }
1644
1645 pid_t pid;
1646 pid = fork();
1647 if (pid == 0) {
1648 /* child -- drop privileges before continuing */
1649 if (setgid(uid) != 0) {
1650 ALOGE("setgid(%d) failed during idmap\n", uid);
1651 exit(1);
1652 }
1653 if (setuid(uid) != 0) {
1654 ALOGE("setuid(%d) failed during idmap\n", uid);
1655 exit(1);
1656 }
1657 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1658 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1659 exit(1);
1660 }
1661
1662 run_idmap(target_apk, overlay_apk, idmap_fd);
1663 exit(1); /* only if exec call to idmap failed */
1664 } else {
1665 int status = wait_child(pid);
1666 if (status != 0) {
1667 ALOGE("idmap failed, status=0x%04x\n", status);
1668 goto fail;
1669 }
1670 }
1671
1672 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001673 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001674fail:
1675 if (idmap_fd >= 0) {
1676 close(idmap_fd);
1677 unlink(idmap_path);
1678 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001679 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001680}
Robert Craige9887e42014-02-20 10:25:56 -05001681
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001682binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1683 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1684 const std::string& seInfo) {
1685 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001686 CHECK_ARGUMENT_UUID(uuid);
1687 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001688 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001689
1690 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001691
Robert Craigda30dc72014-03-27 10:21:12 -04001692 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001693 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001694 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1695 const char* pkgName = packageName.c_str();
1696 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001697
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001698 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001699 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001700 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001701 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001702 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001703 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001704 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001705 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001706 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001707 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001708 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001709 }
Robert Craige9887e42014-02-20 10:25:56 -05001710 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001711 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001712}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001713
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001714binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1715 const std::string& instructionSet) {
1716 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001717 std::lock_guard<std::recursive_mutex> lock(mLock);
1718
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001719 const char* oat_dir = oatDir.c_str();
1720 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001721 char oat_instr_dir[PKG_PATH_MAX];
1722
1723 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001724 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001725 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001726 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001727 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001728 }
1729 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001730 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001731 }
1732 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001733 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001734 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001735 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001736 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001737}
1738
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001739binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1740 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001741 std::lock_guard<std::recursive_mutex> lock(mLock);
1742
Jeff Sharkey423e7462016-12-09 18:18:43 -07001743 if (validate_apk_path(packageDir.c_str())) {
1744 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001745 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001746 if (delete_dir_contents_and_dir(packageDir) != 0) {
1747 return error("Failed to delete " + packageDir);
1748 }
1749 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001750}
1751
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001752binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1753 const std::string& fromBase, const std::string& toBase) {
1754 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001755 std::lock_guard<std::recursive_mutex> lock(mLock);
1756
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001757 const char* relative_path = relativePath.c_str();
1758 const char* from_base = fromBase.c_str();
1759 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001760 char from_path[PKG_PATH_MAX];
1761 char to_path[PKG_PATH_MAX];
1762 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1763 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1764
1765 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001766 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001767 }
1768
1769 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001770 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001771 }
1772
Jeff Sharkey423e7462016-12-09 18:18:43 -07001773 if (link(from_path, to_path) < 0) {
1774 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001775 }
1776
Jeff Sharkey423e7462016-12-09 18:18:43 -07001777 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001778}
1779
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001780binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1781 const std::string& instructionSet, const std::string& outputPath) {
1782 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001783 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001784
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001785 const char* apk_path = apkPath.c_str();
1786 const char* instruction_set = instructionSet.c_str();
1787 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07001788
Jeff Sharkey90aff262016-12-12 14:28:24 -07001789 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001790 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08001791}
1792
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001793binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1794 const std::string& instructionSet, const std::string& outputPath) {
1795 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001796 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001797
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001798 const char* apk_path = apkPath.c_str();
1799 const char* instruction_set = instructionSet.c_str();
1800 const char* oat_dir = outputPath.c_str();
1801
Jeff Sharkey90aff262016-12-12 14:28:24 -07001802 bool res = delete_odex(apk_path, instruction_set, oat_dir);
1803 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07001804}
1805
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001806binder::Status InstalldNativeService::invalidateMounts() {
1807 ENFORCE_UID(AID_SYSTEM);
1808 std::lock_guard<std::recursive_mutex> lock(mLock);
1809
1810 mQuotaDevices.clear();
1811
1812 std::ifstream in("/proc/mounts");
1813 if (!in.is_open()) {
1814 return error("Failed to read mounts");
1815 }
1816
1817 std::string source;
1818 std::string target;
1819 std::string ignored;
1820 struct dqblk dq;
1821 while (!in.eof()) {
1822 std::getline(in, source, ' ');
1823 std::getline(in, target, ' ');
1824 std::getline(in, ignored);
1825
1826 if (source.compare(0, 11, "/dev/block/") == 0) {
1827 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
1828 reinterpret_cast<char*>(&dq)) == 0) {
1829 LOG(DEBUG) << "Found " << source << " with quota";
1830 mQuotaDevices[target] = source;
1831 }
1832 }
1833 }
1834 return ok();
1835}
1836
1837std::string InstalldNativeService::findQuotaDeviceForUuid(
1838 const std::unique_ptr<std::string>& uuid) {
1839 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
1840 return mQuotaDevices[path];
1841}
1842
Andreas Gampe02d0de52015-11-11 20:43:16 -08001843} // namespace installd
1844} // namespace android