blob: 5acad942d65765d5fc987c8be7c7d346e39ca715 [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
19#include <errno.h>
20#include <inttypes.h>
Andreas Gamped089ca12016-06-27 14:25:30 -070021#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <stdlib.h>
23#include <sys/capability.h>
24#include <sys/file.h>
25#include <sys/resource.h>
26#include <sys/stat.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070027#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000028#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070029#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070031
Andreas Gampe6fb5a012016-06-03 16:09:32 -070032#include <android-base/logging.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080033#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070034#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010035#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080036#include <cutils/fs.h>
37#include <cutils/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070038#include <cutils/sched_policy.h>
39#include <diskusage/dirsize.h>
40#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080041#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070042#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080043#include <system/thread_defs.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070044
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070045#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070046#include "globals.h"
47#include "installd_deps.h"
48#include "otapreopt_utils.h"
49#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
Andreas Gampe02d0de52015-11-11 20:43:16 -080051#ifndef LOG_TAG
52#define LOG_TAG "installd"
53#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070054
Andreas Gampe6fb5a012016-06-03 16:09:32 -070055using android::base::EndsWith;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070056using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070057
Andreas Gampe02d0de52015-11-11 20:43:16 -080058namespace android {
59namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070060
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070061static constexpr const char* kCpPath = "/system/bin/cp";
62static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070063
Andreas Gamped089ca12016-06-27 14:25:30 -070064static constexpr const char* PKG_LIB_POSTFIX = "/lib";
65static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
66static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
67
68static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
69static constexpr const char* IDMAP_SUFFIX = "@idmap";
70
71// NOTE: keep in sync with StorageManager
72static constexpr int FLAG_STORAGE_DE = 1 << 0;
73static constexpr int FLAG_STORAGE_CE = 1 << 1;
74
75// NOTE: keep in sync with Installer
76static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
77static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
78
79/* dexopt needed flags matching those in dalvik.system.DexFile */
Nicolas Geoffray920c60c2016-11-25 11:33:31 +000080static constexpr int DEX2OAT_FROM_SCRATCH = 1;
81static constexpr int DEX2OAT_FOR_BOOT_IMAGE = 2;
82static constexpr int DEX2OAT_FOR_FILTER = 3;
83static constexpr int DEX2OAT_FOR_RELOCATION = 4;
84static constexpr int PATCHOAT_FOR_RELOCATION = 5;
Andreas Gamped089ca12016-06-27 14:25:30 -070085
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000086#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
87
Calin Juravle6a1648e2016-02-01 12:12:16 +000088typedef int fd_t;
89
Jeff Sharkey0274c972016-12-06 09:32:04 -070090namespace {
91
92constexpr const char* kDump = "android.permission.DUMP";
93
Jeff Sharkey423e7462016-12-09 18:18:43 -070094static binder::Status ok() {
95 return binder::Status::ok();
96}
97
Jeff Sharkey7be5ead2016-12-12 13:18:46 -070098static binder::Status exception(uint32_t code) {
99 return binder::Status::fromExceptionCode(code);
100}
101
Jeff Sharkey423e7462016-12-09 18:18:43 -0700102static binder::Status exception(uint32_t code, const std::string& msg) {
103 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104}
105
106static binder::Status error() {
107 return binder::Status::fromServiceSpecificError(errno);
108}
109
110static binder::Status error(const std::string& msg) {
111 PLOG(ERROR) << msg;
112 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113}
114
115static binder::Status error(uint32_t code, const std::string& msg) {
116 LOG(ERROR) << msg << " (" << code << ")";
117 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
118}
119
Jeff Sharkey0274c972016-12-06 09:32:04 -0700120binder::Status checkPermission(const char* permission) {
121 pid_t pid;
122 uid_t uid;
123
124 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
125 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700126 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700127 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700128 return exception(binder::Status::EX_SECURITY,
129 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700130 }
131}
132
133binder::Status checkUid(uid_t expectedUid) {
134 uid_t uid = IPCThreadState::self()->getCallingUid();
135 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700137 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700138 return exception(binder::Status::EX_SECURITY,
139 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
140 }
141}
142
143binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
144 if (!uuid || is_valid_filename(*uuid)) {
145 return ok();
146 } else {
147 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
148 StringPrintf("UUID %s is malformed", uuid->c_str()));
149 }
150}
151
152binder::Status checkArgumentPackageName(const std::string& packageName) {
153 if (is_valid_package_name(packageName.c_str())) {
154 return ok();
155 } else {
156 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
157 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700158 }
159}
160
161#define ENFORCE_UID(uid) { \
162 binder::Status status = checkUid((uid)); \
163 if (!status.isOk()) { \
164 return status; \
165 } \
166}
167
Jeff Sharkey423e7462016-12-09 18:18:43 -0700168#define CHECK_ARGUMENT_UUID(uuid) { \
169 binder::Status status = checkArgumentUuid((uuid)); \
170 if (!status.isOk()) { \
171 return status; \
172 } \
173}
174
175#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
176 binder::Status status = \
177 checkArgumentPackageName((packageName)); \
178 if (!status.isOk()) { \
179 return status; \
180 } \
181}
182
Jeff Sharkey0274c972016-12-06 09:32:04 -0700183} // namespace
184
185status_t InstalldNativeService::start() {
186 IPCThreadState::self()->disableBackgroundScheduling(true);
187 status_t ret = BinderService<InstalldNativeService>::publish();
188 if (ret != android::OK) {
189 return ret;
190 }
191 sp<ProcessState> ps(ProcessState::self());
192 ps->startThreadPool();
193 ps->giveThreadPoolName();
194 return android::OK;
195}
196
197status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
198 const binder::Status dump_permission = checkPermission(kDump);
199 if (!dump_permission.isOk()) {
200 const String8 msg(dump_permission.toString8());
201 write(fd, msg.string(), msg.size());
202 return PERMISSION_DENIED;
203 }
204
205 std::string msg = "installd is happy\n";
206 write(fd, msg.c_str(), strlen(msg.c_str()));
207 return NO_ERROR;
208}
209
Calin Juravle6a1648e2016-02-01 12:12:16 +0000210static bool property_get_bool(const char* property_name, bool default_value = false) {
211 char tmp_property_value[kPropertyValueMax];
212 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
213 if (!have_property) {
214 return default_value;
215 }
216 return strcmp(tmp_property_value, "true") == 0;
217}
218
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100219// Keep profile paths in sync with ActivityThread.
220constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
221static std::string create_primary_profile(const std::string& profile_dir) {
222 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
223}
224
Jeff Sharkey7db60412016-09-20 18:21:42 -0600225/**
226 * Perform restorecon of the given path, but only perform recursive restorecon
227 * if the label of that top-level file actually changed. This can save us
228 * significant time by avoiding no-op traversals of large filesystem trees.
229 */
Jeff Sharkey0274c972016-12-06 09:32:04 -0700230static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600231 int res = 0;
232 char* before = nullptr;
233 char* after = nullptr;
234
235 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
236 // libselinux. Not needed here.
237
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600238 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600239 PLOG(ERROR) << "Failed before getfilecon for " << path;
240 goto fail;
241 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700242 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600243 PLOG(ERROR) << "Failed top-level restorecon for " << path;
244 goto fail;
245 }
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600246 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600247 PLOG(ERROR) << "Failed after getfilecon for " << path;
248 goto fail;
249 }
250
251 // If the initial top-level restorecon above changed the label, then go
252 // back and restorecon everything recursively
253 if (strcmp(before, after)) {
254 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
255 << "; running recursive restorecon";
Jeff Sharkey0274c972016-12-06 09:32:04 -0700256 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600257 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
258 PLOG(ERROR) << "Failed recursive restorecon for " << path;
259 goto fail;
260 }
261 }
262
263 goto done;
264fail:
265 res = -1;
266done:
267 free(before);
268 free(after);
269 return res;
270}
271
Jeff Sharkey0274c972016-12-06 09:32:04 -0700272static int restorecon_app_data_lazy(const std::string& parent, const char* name,
273 const std::string& seInfo, uid_t uid) {
274 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600275}
276
Jeff Sharkey7db60412016-09-20 18:21:42 -0600277static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600278 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
279 PLOG(ERROR) << "Failed to prepare " << path;
280 return -1;
281 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600282 return 0;
283}
284
285static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600286 uid_t uid) {
287 return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600288}
289
Jeff Sharkey0274c972016-12-06 09:32:04 -0700290binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
291 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
292 const std::string& seInfo, int32_t targetSdkVersion) {
293 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700294 CHECK_ARGUMENT_UUID(uuid);
295 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700296
297 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
298 const char* pkgname = packageName.c_str();
299
300 uid_t uid = multiuser_get_uid(userId, appId);
301 mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700302 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700303 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600304 if (prepare_app_dir(path, target_mode, uid) ||
305 prepare_app_dir(path, "cache", 0771, uid) ||
306 prepare_app_dir(path, "code_cache", 0771, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700307 return error("Failed to prepare " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600308 }
309
310 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700311 if (restorecon_app_data_lazy(path, seInfo, uid) ||
312 restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
313 restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700314 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700315 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600316
317 // Remember inode numbers of cache directories so that we can clear
318 // contents while CE storage is locked
319 if (write_path_inode(path, "cache", kXattrInodeCache) ||
320 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700321 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700322 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700323 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700324 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700325 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600326 if (prepare_app_dir(path, target_mode, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700327 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700328 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000329
Jeff Sharkey7db60412016-09-20 18:21:42 -0600330 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700331 if (restorecon_app_data_lazy(path, seInfo, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700332 return error("Failed to restorecon " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600333 }
334
Calin Juravle6a1648e2016-02-01 12:12:16 +0000335 if (property_get_bool("dalvik.vm.usejitprofiles")) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700336 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000337 // read-write-execute only for the app user.
338 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700339 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000340 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100341 std::string profile_file = create_primary_profile(profile_path);
342 // read-write only for the app user.
343 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700344 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100345 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000346 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
347 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
348 // profiles.
349 appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
350 if (fs_prepare_dir_strict(
351 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700352 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000353 }
354 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700355 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700356 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700357}
358
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700359binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
360 const std::string& packageName, int32_t userId, int32_t flags) {
361 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700362 CHECK_ARGUMENT_UUID(uuid);
363 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
364
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700365 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
366 const char* pkgname = packageName.c_str();
367
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700368 // This method only exists to upgrade system apps that have requested
369 // forceDeviceEncrypted, so their default storage always lives in a
370 // consistent location. This only works on non-FBE devices, since we
371 // never want to risk exposing data on a device with real CE/DE storage.
372
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700373 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
374 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700375
376 // If neither directory is marked as default, assume CE is default
377 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
378 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
379 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700380 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700381 }
382 }
383
384 // Migrate default data location if needed
385 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
386 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
387
388 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
389 LOG(WARNING) << "Requested default storage " << target
390 << " is not active; migrating from " << source;
391 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700392 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700393 }
394 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700395 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700396 }
397 }
398
Jeff Sharkey423e7462016-12-09 18:18:43 -0700399 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700400}
401
Calin Juravlecea31412016-03-29 15:36:34 +0100402static bool clear_profile(const std::string& profile) {
Roland Levillain64b59cc2016-04-05 16:41:12 +0100403 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
404 if (ufd.get() < 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100405 if (errno != ENOENT) {
406 PLOG(WARNING) << "Could not open profile " << profile;
407 return false;
408 } else {
409 // Nothing to clear. That's ok.
410 return true;
411 }
412 }
413
Roland Levillain64b59cc2016-04-05 16:41:12 +0100414 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100415 if (errno != EWOULDBLOCK) {
416 PLOG(WARNING) << "Error locking profile " << profile;
417 }
418 // This implies that the app owning this profile is running
419 // (and has acquired the lock).
420 //
421 // If we can't acquire the lock bail out since clearing is useless anyway
422 // (the app will write again to the profile).
423 //
424 // Note:
425 // This does not impact the this is not an issue for the profiling correctness.
426 // In case this is needed because of an app upgrade, profiles will still be
427 // eventually cleared by the app itself due to checksum mismatch.
428 // If this is needed because profman advised, then keeping the data around
429 // until the next run is again not an issue.
430 //
431 // If the app attempts to acquire a lock while we've held one here,
432 // it will simply skip the current write cycle.
433 return false;
434 }
435
Roland Levillain64b59cc2016-04-05 16:41:12 +0100436 bool truncated = ftruncate(ufd.get(), 0) == 0;
Calin Juravlecea31412016-03-29 15:36:34 +0100437 if (!truncated) {
438 PLOG(WARNING) << "Could not truncate " << profile;
439 }
Roland Levillain64b59cc2016-04-05 16:41:12 +0100440 if (flock(ufd.get(), LOCK_UN) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100441 PLOG(WARNING) << "Error unlocking profile " << profile;
442 }
443 return truncated;
444}
445
446static bool clear_reference_profile(const char* pkgname) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000447 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
448 std::string reference_profile = create_primary_profile(reference_profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100449 return clear_profile(reference_profile);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000450}
451
Calin Juravlecea31412016-03-29 15:36:34 +0100452static bool clear_current_profile(const char* pkgname, userid_t user) {
Calin Juravleedae6692016-03-23 13:55:31 +0000453 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
454 std::string profile = create_primary_profile(profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100455 return clear_profile(profile);
Calin Juravleedae6692016-03-23 13:55:31 +0000456}
457
Calin Juravlecea31412016-03-29 15:36:34 +0100458static bool clear_current_profiles(const char* pkgname) {
David Brazdild828d682016-03-08 12:50:20 +0000459 bool success = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000460 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
461 for (auto user : users) {
Calin Juravlecea31412016-03-29 15:36:34 +0100462 success &= clear_current_profile(pkgname, user);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000463 }
David Brazdild828d682016-03-08 12:50:20 +0000464 return success;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000465}
466
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700467binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
468 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700469 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
470
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700471 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700472 binder::Status res = ok();
473 if (!clear_reference_profile(pkgname)) {
474 res = error("Failed to clear reference profile for " + packageName);
475 }
476 if (!clear_current_profiles(pkgname)) {
477 res = error("Failed to clear current profiles for " + packageName);
478 }
479 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000480}
481
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700482binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
483 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
484 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700485 CHECK_ARGUMENT_UUID(uuid);
486 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
487
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700488 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
489 const char* pkgname = packageName.c_str();
490
Jeff Sharkey423e7462016-12-09 18:18:43 -0700491 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700492 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700493 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600494 if (flags & FLAG_CLEAR_CACHE_ONLY) {
495 path = read_path_inode(path, "cache", kXattrInodeCache);
496 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
497 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
498 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700499 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700500 if (delete_dir_contents(path) != 0) {
501 res = error("Failed to delete contents of " + path);
502 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700503 }
504 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700505 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600506 std::string suffix = "";
507 bool only_cache = false;
508 if (flags & FLAG_CLEAR_CACHE_ONLY) {
509 suffix = CACHE_DIR_POSTFIX;
510 only_cache = true;
511 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
512 suffix = CODE_CACHE_DIR_POSTFIX;
513 only_cache = true;
514 }
515
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700516 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700517 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700518 if (delete_dir_contents(path) != 0) {
519 res = error("Failed to delete contents of " + path);
520 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700521 }
Calin Juravleedae6692016-03-23 13:55:31 +0000522 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700523 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700524 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000525 }
526 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700527 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700528 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700529}
530
Calin Juravle7535e8e2016-03-29 16:05:40 +0100531static int destroy_app_reference_profile(const char *pkgname) {
532 return delete_dir_contents_and_dir(
533 create_data_ref_profile_package_path(pkgname),
534 /*ignore_if_missing*/ true);
535}
536
Calin Juravleedae6692016-03-23 13:55:31 +0000537static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100538 return delete_dir_contents_and_dir(
539 create_data_user_profile_package_path(userid, pkgname),
540 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000541}
542
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700543binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
544 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700545 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
546
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700547 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700548 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000549 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
550 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700551 if (destroy_app_current_profiles(pkgname, user) != 0) {
552 res = error("Failed to destroy current profiles for " + packageName);
553 }
Calin Juravleedae6692016-03-23 13:55:31 +0000554 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700555 if (destroy_app_reference_profile(pkgname) != 0) {
556 res = error("Failed to destroy reference profile for " + packageName);
557 }
558 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000559}
560
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700561binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
562 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
563 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564 CHECK_ARGUMENT_UUID(uuid);
565 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
566
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700567 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
568 const char* pkgname = packageName.c_str();
569
Jeff Sharkey423e7462016-12-09 18:18:43 -0700570 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700571 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700572 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
573 if (delete_dir_contents_and_dir(path) != 0) {
574 res = error("Failed to delete " + path);
575 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700576 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700577 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700578 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
579 if (delete_dir_contents_and_dir(path) != 0) {
580 res = error("Failed to delete " + path);
581 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700582 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100583 // TODO(calin): If the package is still installed by other users it's probably
584 // beneficial to keep the reference profile around.
585 // Verify if it's ok to do that.
586 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700587 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700588 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700589}
590
Jeff Sharkey0274c972016-12-06 09:32:04 -0700591binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
592 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
593 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
594 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700595 ENFORCE_UID(AID_SYSTEM);
596 CHECK_ARGUMENT_UUID(fromUuid);
597 CHECK_ARGUMENT_UUID(toUuid);
598 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700599
600 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
601 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
602 const char* package_name = packageName.c_str();
603 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700604
Jeff Sharkey423e7462016-12-09 18:18:43 -0700605 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700606 std::vector<userid_t> users = get_known_users(from_uuid);
607
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700608 // Copy app
609 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600610 auto from = create_data_app_package_path(from_uuid, data_app_name);
611 auto to = create_data_app_package_path(to_uuid, data_app_name);
612 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700613
614 char *argv[] = {
615 (char*) kCpPath,
616 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
617 (char*) "-p", /* preserve timestamps, ownership, and permissions */
618 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
619 (char*) "-P", /* Do not follow symlinks [default] */
620 (char*) "-d", /* don't dereference symlinks */
621 (char*) from.c_str(),
622 (char*) to_parent.c_str()
623 };
624
625 LOG(DEBUG) << "Copying " << from << " to " << to;
626 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700627 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700628 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700629 goto fail;
630 }
631
632 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700633 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700634 goto fail;
635 }
636 }
637
638 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700639 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700640
641 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600642 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
643 if (access(from_ce.c_str(), F_OK) != 0) {
644 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700645 continue;
646 }
647
Jeff Sharkey0274c972016-12-06 09:32:04 -0700648 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
649 seInfo, targetSdkVersion).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700650 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700651 goto fail;
652 }
653
654 char *argv[] = {
655 (char*) kCpPath,
656 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
657 (char*) "-p", /* preserve timestamps, ownership, and permissions */
658 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
659 (char*) "-P", /* Do not follow symlinks [default] */
660 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600661 nullptr,
662 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700663 };
664
Jeff Sharkey51c94492016-05-10 17:46:39 -0600665 {
666 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
667 auto to = create_data_user_de_path(to_uuid, user);
668 argv[6] = (char*) from.c_str();
669 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700670
Jeff Sharkey51c94492016-05-10 17:46:39 -0600671 LOG(DEBUG) << "Copying " << from << " to " << to;
672 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
673 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700674 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600675 goto fail;
676 }
677 }
678 {
679 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
680 auto to = create_data_user_ce_path(to_uuid, user);
681 argv[6] = (char*) from.c_str();
682 argv[7] = (char*) to.c_str();
683
684 LOG(DEBUG) << "Copying " << from << " to " << to;
685 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
686 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700687 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600688 goto fail;
689 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700690 }
691
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700692 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
693 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700694 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700695 goto fail;
696 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700697 }
698
Jeff Sharkey31f08982015-07-07 13:31:37 -0700699 // We let the framework scan the new location and persist that before
700 // deleting the data in the old location; this ordering ensures that
701 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700702 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700703
704fail:
705 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700706 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600707 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700708 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
709 LOG(WARNING) << "Failed to rollback " << to;
710 }
711 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700712 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600713 {
714 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
715 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
716 LOG(WARNING) << "Failed to rollback " << to;
717 }
718 }
719 {
720 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
721 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
722 LOG(WARNING) << "Failed to rollback " << to;
723 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700724 }
725 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700726 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700727}
728
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700729binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
730 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
731 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700732 CHECK_ARGUMENT_UUID(uuid);
733
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700734 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600735 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700736 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700737 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700738 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700739 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700740 }
741 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700742 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700743}
744
745binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
746 int32_t userId, int32_t flags) {
747 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 CHECK_ARGUMENT_UUID(uuid);
749
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700750 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700751 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700752 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700753 auto path = create_data_user_de_path(uuid_, userId);
754 if (delete_dir_contents_and_dir(path, true) != 0) {
755 res = error("Failed to delete " + path);
756 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700757 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700758 path = create_data_misc_legacy_path(userId);
759 if (delete_dir_contents_and_dir(path, true) != 0) {
760 res = error("Failed to delete " + path);
761 }
762 path = create_data_user_profiles_path(userId);
763 if (delete_dir_contents_and_dir(path, true) != 0) {
764 res = error("Failed to delete " + path);
765 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700766 }
Robin Lee095c7632014-04-25 15:05:19 +0100767 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600768 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700769 auto path = create_data_user_ce_path(uuid_, userId);
770 if (delete_dir_contents_and_dir(path, true) != 0) {
771 res = error("Failed to delete " + path);
772 }
773 path = create_data_media_path(uuid_, userId);
774 if (delete_dir_contents_and_dir(path, true) != 0) {
775 res = error("Failed to delete " + path);
776 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600777 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700778 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100779}
780
Mike Lockwood94afecf2012-10-24 10:45:23 -0700781/* Try to ensure free_size bytes of storage are available.
782 * Returns 0 on success.
783 * This is rather simple-minded because doing a full LRU would
784 * be potentially memory-intensive, and without atime it would
785 * also require that apps constantly modify file metadata even
786 * when just reading from the cache, which is pretty awful.
787 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700788binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
789 int64_t freeStorageSize) {
790 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700791 CHECK_ARGUMENT_UUID(uuid);
792
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700793 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700794 cache_t* cache;
795 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700796
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700797 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700798
799 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700800 if (avail < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700801 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700802 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700803
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700804 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
805 if (avail >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700806 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700807 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700808
809 cache = start_cache_collection();
810
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700811 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600812 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700813 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
814 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600815 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700816 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700817 }
818
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700819 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700820 finish_cache_collection(cache);
821
Jeff Sharkey423e7462016-12-09 18:18:43 -0700822 avail = data_disk_free(data_path);
823 if (avail >= freeStorageSize) {
824 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700825 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700826 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
827 freeStorageSize, data_path.c_str(), avail));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700828 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700829}
830
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700831binder::Status InstalldNativeService::rmdex(const std::string& codePath,
832 const std::string& instructionSet) {
833 ENFORCE_UID(AID_SYSTEM);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700834 char dex_path[PKG_PATH_MAX];
835
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700836 const char* path = codePath.c_str();
837 const char* instruction_set = instructionSet.c_str();
838
Jeff Sharkey770180a2014-09-08 17:14:26 -0700839 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700840 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700841 }
842
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700843 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700844 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700845 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700846
847 ALOGV("unlink %s\n", dex_path);
848 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700849 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700850 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700851 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700852 }
853}
854
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600855static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
856 int64_t *cachesize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700857 DIR *d;
858 int dfd;
859 struct dirent *de;
860 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700861
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600862 d = opendir(path.c_str());
863 if (d == nullptr) {
864 PLOG(WARNING) << "Failed to open " << path;
865 return;
866 }
867 dfd = dirfd(d);
868 while ((de = readdir(d))) {
869 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700870
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600871 int64_t statsize = 0;
872 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
873 statsize = stat_size(&s);
874 }
875
876 if (de->d_type == DT_DIR) {
877 int subfd;
878 int64_t dirsize = 0;
879 /* always skip "." and ".." */
880 if (name[0] == '.') {
881 if (name[1] == 0) continue;
882 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700883 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600884 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
885 if (subfd >= 0) {
886 dirsize = calculate_dir_size(subfd);
887 close(subfd);
888 }
889 // TODO: check xattrs!
890 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
891 *datasize += statsize;
892 *cachesize += dirsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700893 } else {
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600894 *datasize += dirsize + statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700895 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600896 } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
897 *codesize += statsize;
898 } else {
899 *datasize += statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700900 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600901 }
902 closedir(d);
903}
904
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700905binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey423e7462016-12-09 18:18:43 -0700906 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
907 const std::string& codePath, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700908 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700909 CHECK_ARGUMENT_UUID(uuid);
910 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
911
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700912 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
913 const char* pkgname = packageName.c_str();
914 const char* code_path = codePath.c_str();
915
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600916 DIR *d;
917 int dfd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700918 int64_t codesize = 0;
919 int64_t datasize = 0;
920 int64_t cachesize = 0;
921 int64_t asecsize = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600922
923 d = opendir(code_path);
924 if (d != nullptr) {
925 dfd = dirfd(d);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700926 codesize += calculate_dir_size(dfd);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700927 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700928 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600929
930 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700931 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
932 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600933 }
934 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700935 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
936 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600937 }
938
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700939 std::vector<int64_t> res;
940 res.push_back(codesize);
941 res.push_back(datasize);
942 res.push_back(cachesize);
943 res.push_back(asecsize);
944 *_aidl_return = res;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700945 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700946}
947
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700948binder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700949 const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700950 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700951 CHECK_ARGUMENT_UUID(uuid);
952 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
953
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700954 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
955 const char* pkgname = packageName.c_str();
956
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600957 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700958 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700959 if (get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) == 0) {
960 return ok();
961 } else {
962 return error("Failed to get_path_inode for " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700963 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600964 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700965 return exception(binder::Status::EX_UNSUPPORTED_OPERATION);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600966}
967
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700968static int split_count(const char *str)
969{
970 char *ctx;
971 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800972 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700973
974 strncpy(buf, str, sizeof(buf));
975 char *pBuf = buf;
976
977 while(strtok_r(pBuf, " ", &ctx) != NULL) {
978 count++;
979 pBuf = NULL;
980 }
981
982 return count;
983}
984
neo.chae14e084d2015-01-07 18:46:13 +0900985static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700986{
987 char *ctx;
988 int count = 0;
989 char *tok;
990 char *pBuf = buf;
991
992 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
993 argv[count++] = tok;
994 pBuf = NULL;
995 }
996
997 return count;
998}
999
David Brazdilfc5934e2016-09-08 11:55:48 +01001000static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
1001 const char* input_oat_file_name, const char* input_vdex_file_name,
1002 const char* output_oat_file_name, const char* output_vdex_file_name,
1003 const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -07001004{
1005 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +01001006 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -07001007
1008 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
1009 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1010 ALOGE("Instruction set %s longer than max length of %d",
1011 instruction_set, MAX_INSTRUCTION_SET_LEN);
1012 return;
1013 }
1014
1015 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
1016 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Alex Light7365a102014-07-21 12:23:48 -07001017 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
David Brazdilfc5934e2016-09-08 11:55:48 +01001018 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1019 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
1020 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Alex Light7365a102014-07-21 12:23:48 -07001021 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
1022 // The caller has already gotten all the locks we need.
1023 const char* no_lock_arg = "--no-lock-output";
1024 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
David Brazdilfc5934e2016-09-08 11:55:48 +01001025 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
1026 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
1027 ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
1028 "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
1029 PATCHOAT_BIN, instruction_set,
1030 input_oat_fd, input_oat_file_name,
1031 input_vdex_fd, input_vdex_file_name,
1032 out_oat_fd, output_oat_file_name,
1033 out_vdex_fd, output_vdex_file_name);
Alex Light7365a102014-07-21 12:23:48 -07001034
1035 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
David Brazdilfc5934e2016-09-08 11:55:48 +01001036 char* argv[9];
Alex Light7365a102014-07-21 12:23:48 -07001037 argv[0] = (char*) PATCHOAT_BIN;
1038 argv[1] = (char*) patched_image_location_arg;
1039 argv[2] = (char*) no_lock_arg;
1040 argv[3] = instruction_set_arg;
David Brazdilfc5934e2016-09-08 11:55:48 +01001041 argv[4] = input_oat_fd_arg;
1042 argv[5] = input_vdex_fd_arg;
1043 argv[6] = output_oat_fd_arg;
1044 argv[7] = output_vdex_fd_arg;
1045 argv[8] = NULL;
Alex Light7365a102014-07-21 12:23:48 -07001046
1047 execv(PATCHOAT_BIN, (char* const *)argv);
1048 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
1049}
1050
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001051static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
David Brazdilfc5934e2016-09-08 11:55:48 +01001052 const char* input_file_name, const char* output_file_name, int swap_fd,
1053 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
1054 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
Calin Juravle8fc73152014-08-19 18:48:50 +01001055 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1056
1057 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1058 ALOGE("Instruction set %s longer than max length of %d",
1059 instruction_set, MAX_INSTRUCTION_SET_LEN);
1060 return;
1061 }
1062
Andreas Gampe02d0de52015-11-11 20:43:16 -08001063 char dex2oat_Xms_flag[kPropertyValueMax];
1064 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001065
Andreas Gampe02d0de52015-11-11 20:43:16 -08001066 char dex2oat_Xmx_flag[kPropertyValueMax];
1067 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001068
Andreas Gampe02d0de52015-11-11 20:43:16 -08001069 char dex2oat_threads_buf[kPropertyValueMax];
1070 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -07001071 ? "dalvik.vm.dex2oat-threads"
1072 : "dalvik.vm.boot-dex2oat-threads",
1073 dex2oat_threads_buf,
1074 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -08001075 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001076 if (have_dex2oat_threads_flag) {
1077 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
1078 }
1079
Andreas Gampe02d0de52015-11-11 20:43:16 -08001080 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +01001081 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001082 char dex2oat_isa_features[kPropertyValueMax];
1083 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +01001084 dex2oat_isa_features, NULL) > 0;
1085
Andreas Gampe02d0de52015-11-11 20:43:16 -08001086 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -08001087 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001088 char dex2oat_isa_variant[kPropertyValueMax];
1089 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -08001090 dex2oat_isa_variant, NULL) > 0;
1091
neo.chae14e084d2015-01-07 18:46:13 +09001092 const char *dex2oat_norelocation = "-Xnorelocate";
1093 bool have_dex2oat_relocation_skip_flag = false;
1094
Andreas Gampe02d0de52015-11-11 20:43:16 -08001095 char dex2oat_flags[kPropertyValueMax];
1096 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001097 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -08001098 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
1099
Brian Carlstrom538998f2014-07-30 14:37:11 -07001100 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -08001101 char vold_decrypt[kPropertyValueMax];
1102 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001103 bool skip_compilation = (have_vold_decrypt &&
1104 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
1105 (strcmp(vold_decrypt, "1") == 0)));
1106
Calin Juravle6a1648e2016-02-01 12:12:16 +00001107 bool generate_debug_info = property_get_bool("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001108
Mathieu Chartier416fa122016-02-03 13:48:16 -08001109 char app_image_format[kPropertyValueMax];
1110 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
1111 bool have_app_image_format =
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001112 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
Mathieu Chartier416fa122016-02-03 13:48:16 -08001113 if (have_app_image_format) {
1114 sprintf(image_format_arg, "--image-format=%s", app_image_format);
1115 }
1116
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001117 char dex2oat_large_app_threshold[kPropertyValueMax];
1118 bool have_dex2oat_large_app_threshold =
1119 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
1120 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
1121 if (have_dex2oat_large_app_threshold) {
1122 sprintf(dex2oat_large_app_threshold_arg,
1123 "--very-large-app-threshold=%s",
1124 dex2oat_large_app_threshold);
1125 }
1126
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001127 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001128
Brian Carlstrom53e07762014-06-27 14:15:19 -07001129 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001130
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001131 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +01001132
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001133 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
1134 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001135 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1136 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001137 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -07001138 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +01001139 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001140 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
1141 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
1142 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
1143 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
1144 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -08001145 bool have_dex2oat_swap_fd = false;
1146 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001147 bool have_dex2oat_image_fd = false;
1148 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001149
1150 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
1151 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001152 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
1153 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001154 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
1155 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +01001156 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -08001157 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +01001158 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -08001159 if (swap_fd >= 0) {
1160 have_dex2oat_swap_fd = true;
1161 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1162 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001163 if (image_fd >= 0) {
1164 have_dex2oat_image_fd = true;
1165 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1166 }
Calin Juravle57c69c32014-06-06 14:42:16 +01001167
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001168 if (have_dex2oat_Xms_flag) {
1169 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1170 }
1171 if (have_dex2oat_Xmx_flag) {
1172 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1173 }
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001174
1175 // Compute compiler filter.
1176
1177 bool have_dex2oat_compiler_filter_flag;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001178 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -07001179 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -07001180 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +09001181 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +01001182 } else if (vm_safe_mode) {
1183 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +01001184 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001185 } else if (compiler_filter != nullptr &&
1186 strlen(compiler_filter) + strlen("--compiler-filter=") <
1187 arraysize(dex2oat_compiler_filter_arg)) {
1188 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001189 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001190 } else {
1191 char dex2oat_compiler_filter_flag[kPropertyValueMax];
1192 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
1193 dex2oat_compiler_filter_flag, NULL) > 0;
1194 if (have_dex2oat_compiler_filter_flag) {
1195 sprintf(dex2oat_compiler_filter_arg,
1196 "--compiler-filter=%s",
1197 dex2oat_compiler_filter_flag);
1198 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001199 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001200
Andreas Gampe598c25e2015-03-03 09:15:06 -08001201 // Check whether all apps should be compiled debuggable.
1202 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001203 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -08001204 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -08001205 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -08001206 (prop_buf[0] == '1');
1207 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001208 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
1209 if (profile_fd != -1) {
1210 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001211 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001212
Calin Juravle6a1648e2016-02-01 12:12:16 +00001213
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001214 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +01001215
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001216 const char* argv[9 // program name, mandatory arguments and the final NULL
neo.chae14e084d2015-01-07 18:46:13 +09001217 + (have_dex2oat_isa_variant ? 1 : 0)
1218 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001219 + (have_dex2oat_Xms_flag ? 2 : 0)
1220 + (have_dex2oat_Xmx_flag ? 2 : 0)
1221 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001222 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001223 + (have_dex2oat_swap_fd ? 1 : 0)
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001224 + (have_dex2oat_image_fd ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001225 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +01001226 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -08001227 + (debuggable ? 1 : 0)
Mathieu Chartier416fa122016-02-03 13:48:16 -08001228 + (have_app_image_format ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +02001229 + dex2oat_flags_count
Jeff Haob63d91f2016-03-16 15:59:25 -07001230 + (profile_fd == -1 ? 0 : 1)
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001231 + (shared_libraries != nullptr ? 4 : 0)
1232 + (have_dex2oat_large_app_threshold ? 1 : 0)];
Calin Juravle4fdff462014-06-06 16:58:43 +01001233 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +09001234 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +01001235 argv[i++] = zip_fd_arg;
1236 argv[i++] = zip_location_arg;
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001237 argv[i++] = input_vdex_fd_arg;
1238 argv[i++] = output_vdex_fd_arg;
Calin Juravle4fdff462014-06-06 16:58:43 +01001239 argv[i++] = oat_fd_arg;
1240 argv[i++] = oat_location_arg;
1241 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -08001242 if (have_dex2oat_isa_variant) {
1243 argv[i++] = instruction_set_variant_arg;
1244 }
Calin Juravle8fc73152014-08-19 18:48:50 +01001245 if (have_dex2oat_isa_features) {
1246 argv[i++] = instruction_set_features_arg;
1247 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001248 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001249 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001250 argv[i++] = dex2oat_Xms_arg;
1251 }
1252 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001253 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001254 argv[i++] = dex2oat_Xmx_arg;
1255 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001256 if (have_dex2oat_compiler_filter_flag) {
1257 argv[i++] = dex2oat_compiler_filter_arg;
1258 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001259 if (have_dex2oat_threads_flag) {
1260 argv[i++] = dex2oat_threads_arg;
1261 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001262 if (have_dex2oat_swap_fd) {
1263 argv[i++] = dex2oat_swap_fd;
1264 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001265 if (have_dex2oat_image_fd) {
1266 argv[i++] = dex2oat_image_fd;
1267 }
David Srbecky528c8dd2015-05-28 16:55:50 +01001268 if (generate_debug_info) {
1269 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -07001270 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001271 if (debuggable) {
1272 argv[i++] = "--debuggable";
1273 }
Mathieu Chartier416fa122016-02-03 13:48:16 -08001274 if (have_app_image_format) {
1275 argv[i++] = image_format_arg;
1276 }
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001277 if (have_dex2oat_large_app_threshold) {
1278 argv[i++] = dex2oat_large_app_threshold_arg;
1279 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001280 if (dex2oat_flags_count) {
1281 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +01001282 }
neo.chae14e084d2015-01-07 18:46:13 +09001283 if (have_dex2oat_relocation_skip_flag) {
1284 argv[i++] = RUNTIME_ARG;
1285 argv[i++] = dex2oat_norelocation;
1286 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001287 if (profile_fd != -1) {
1288 argv[i++] = profile_arg;
Calin Juravle60a794d2015-12-24 12:36:41 +02001289 }
Jeff Haob63d91f2016-03-16 15:59:25 -07001290 if (shared_libraries != nullptr) {
1291 argv[i++] = RUNTIME_ARG;
1292 argv[i++] = "-classpath";
1293 argv[i++] = RUNTIME_ARG;
1294 argv[i++] = shared_libraries;
1295 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001296 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +01001297 argv[i] = NULL;
1298
neo.chae14e084d2015-01-07 18:46:13 +09001299 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001300 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001301}
1302
Andreas Gampee1c01352014-12-10 16:41:11 -08001303/*
Andreas Gampec968c012015-07-16 15:55:41 -07001304 * Whether dexopt should use a swap file when compiling an APK.
1305 *
1306 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1307 * itself, anyways).
1308 *
1309 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1310 *
1311 * Otherwise, return true if this is a low-mem device.
1312 *
1313 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -08001314 */
Andreas Gampec968c012015-07-16 15:55:41 -07001315static bool kAlwaysProvideSwapFile = false;
1316static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -08001317
1318static bool ShouldUseSwapFileForDexopt() {
1319 if (kAlwaysProvideSwapFile) {
1320 return true;
1321 }
1322
Andreas Gampec968c012015-07-16 15:55:41 -07001323 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -08001324 char dex2oat_prop_buf[kPropertyValueMax];
1325 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -07001326 if (strcmp(dex2oat_prop_buf, "true") == 0) {
1327 return true;
1328 } else {
1329 return false;
1330 }
1331 }
1332
1333 // Shortcut for default value. This is an implementation optimization for the process sketched
1334 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1335 // as low-mem is never returning false. The compiler will optimize this away if it can.
1336 if (kDefaultProvideSwapFile) {
1337 return true;
1338 }
1339
Calin Juravle6a1648e2016-02-01 12:12:16 +00001340 bool is_low_mem = property_get_bool("ro.config.low_ram");
Andreas Gampec968c012015-07-16 15:55:41 -07001341 if (is_low_mem) {
1342 return true;
1343 }
1344
1345 // Default value must be false here.
1346 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -08001347}
1348
Andreas Gampe94dd3d32015-09-14 16:33:11 -07001349static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
1350 if (set_to_bg) {
1351 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1352 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1353 exit(70);
1354 }
1355 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1356 ALOGE("setpriority failed: %s\n", strerror(errno));
1357 exit(71);
1358 }
1359 }
1360}
1361
Calin Juravle6a1648e2016-02-01 12:12:16 +00001362static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001363 for (size_t i = 0; i < fds.size(); i++) {
1364 if (close(fds[i]) != 0) {
1365 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
1366 }
1367 }
1368}
1369
Calin Juravle6a1648e2016-02-01 12:12:16 +00001370static fd_t open_profile_dir(const std::string& profile_dir) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001371 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
1372 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
1373 if (profile_dir_fd < 0) {
Narayan Kamath2e063af2016-05-02 09:47:49 +01001374 // In a multi-user environment, these directories can be created at
1375 // different points and it's possible we'll attempt to open a profile
1376 // dir before it exists.
1377 if (errno != ENOENT) {
1378 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
1379 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001380 }
1381 return profile_dir_fd;
1382}
1383
1384static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1385 fd_t profile_dir_fd = open_profile_dir(profile_dir);
1386 if (profile_dir_fd < 0) {
1387 return -1;
1388 }
1389
1390 fd_t profile_fd = -1;
1391 std::string profile_file = create_primary_profile(profile_dir);
1392
1393 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1394 if (profile_fd == -1) {
1395 // It's not an error if the profile file does not exist.
Calin Juravle60a794d2015-12-24 12:36:41 +02001396 if (errno != ENOENT) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001397 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1398 }
1399 }
1400 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1401 if (close(profile_dir_fd) != 0) {
1402 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1403 }
1404 return profile_fd;
1405}
1406
1407static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1408 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1409 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1410}
1411
1412static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1413 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1414 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1415 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1416 if (fd < 0) {
1417 return -1;
1418 }
1419 if (read_write) {
1420 // Fix the owner.
1421 if (fchown(fd, uid, uid) < 0) {
1422 close(fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001423 return -1;
1424 }
1425 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001426 return fd;
Calin Juravle60a794d2015-12-24 12:36:41 +02001427}
1428
Calin Juravle6a1648e2016-02-01 12:12:16 +00001429static void open_profile_files(uid_t uid, const char* pkgname,
1430 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1431 // Open the reference profile in read-write mode as profman might need to save the merge.
1432 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
Calin Juravle60a794d2015-12-24 12:36:41 +02001433 if (*reference_profile_fd < 0) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001434 // We can't access the reference profile file.
Calin Juravle60a794d2015-12-24 12:36:41 +02001435 return;
1436 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001437
1438 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1439 for (auto user : users) {
1440 fd_t profile_fd = open_primary_profile_file(user, pkgname);
1441 // Add to the lists only if both fds are valid.
1442 if (profile_fd >= 0) {
1443 profiles_fd->push_back(profile_fd);
1444 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001445 }
1446}
1447
Calin Juravle6a1648e2016-02-01 12:12:16 +00001448static void drop_capabilities(uid_t uid) {
1449 if (setgid(uid) != 0) {
1450 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1451 exit(64);
1452 }
1453 if (setuid(uid) != 0) {
1454 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1455 exit(65);
1456 }
1457 // drop capabilities
1458 struct __user_cap_header_struct capheader;
1459 struct __user_cap_data_struct capdata[2];
1460 memset(&capheader, 0, sizeof(capheader));
1461 memset(&capdata, 0, sizeof(capdata));
1462 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1463 if (capset(&capheader, &capdata[0]) < 0) {
1464 ALOGE("capset failed: %s\n", strerror(errno));
1465 exit(66);
1466 }
1467}
Calin Juravle60a794d2015-12-24 12:36:41 +02001468
Calin Juravle6a1648e2016-02-01 12:12:16 +00001469static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1470static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1471static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1472static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1473static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1474
David Sehr6727c2d2016-05-17 16:06:22 -07001475static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001476 static const size_t MAX_INT_LEN = 32;
1477 static const char* PROFMAN_BIN = "/system/bin/profman";
1478
1479 std::vector<std::string> profile_args(profiles_fd.size());
1480 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1481 for (size_t k = 0; k < profiles_fd.size(); k++) {
1482 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1483 profile_args[k].assign(profile_buf);
1484 }
1485 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1486 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1487
1488 // program name, reference profile fd, the final NULL and the profile fds
1489 const char* argv[3 + profiles_fd.size()];
1490 int i = 0;
1491 argv[i++] = PROFMAN_BIN;
1492 argv[i++] = reference_profile_arg;
1493 for (size_t k = 0; k < profile_args.size(); k++) {
1494 argv[i++] = profile_args[k].c_str();
1495 }
1496 // Do not add after dex2oat_flags, they should override others for debugging.
1497 argv[i] = NULL;
1498
1499 execv(PROFMAN_BIN, (char * const *)argv);
1500 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1501 exit(68); /* only get here on exec failure */
1502}
1503
1504// Decides if profile guided compilation is needed or not based on existing profiles.
1505// Returns true if there is enough information in the current profiles that worth
1506// a re-compilation of the package.
1507// If the return value is true all the current profiles would have been merged into
1508// the reference profiles accessible with open_reference_profile().
1509static bool analyse_profiles(uid_t uid, const char* pkgname) {
1510 std::vector<fd_t> profiles_fd;
1511 fd_t reference_profile_fd = -1;
1512 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1513 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1514 // Skip profile guided compilation because no profiles were found.
1515 // Or if the reference profile info couldn't be opened.
1516 close_all_fds(profiles_fd, "profiles_fd");
1517 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1518 PLOG(WARNING) << "Failed to close fd for reference profile";
1519 }
1520 return false;
1521 }
1522
David Sehr6727c2d2016-05-17 16:06:22 -07001523 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001524
1525 pid_t pid = fork();
1526 if (pid == 0) {
1527 /* child -- drop privileges before continuing */
1528 drop_capabilities(uid);
David Sehr6727c2d2016-05-17 16:06:22 -07001529 run_profman_merge(profiles_fd, reference_profile_fd);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001530 exit(68); /* only get here on exec failure */
1531 }
1532 /* parent */
1533 int return_code = wait_child(pid);
1534 bool need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001535 bool should_clear_current_profiles = false;
1536 bool should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001537 if (!WIFEXITED(return_code)) {
1538 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1539 } else {
1540 return_code = WEXITSTATUS(return_code);
1541 switch (return_code) {
1542 case PROFMAN_BIN_RETURN_CODE_COMPILE:
1543 need_to_compile = true;
Calin Juravlecea31412016-03-29 15:36:34 +01001544 should_clear_current_profiles = true;
1545 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001546 break;
1547 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1548 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001549 should_clear_current_profiles = false;
1550 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001551 break;
1552 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1553 LOG(WARNING) << "Bad profiles for package " << pkgname;
1554 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001555 should_clear_current_profiles = true;
1556 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001557 break;
1558 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
1559 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1560 // Temporary IO problem (e.g. locking). Ignore but log a warning.
1561 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1562 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001563 should_clear_current_profiles = false;
1564 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001565 break;
1566 default:
1567 // Unknown return code or error. Unlink profiles.
1568 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1569 << ": " << return_code;
1570 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001571 should_clear_current_profiles = true;
1572 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001573 break;
Calin Juravle60a794d2015-12-24 12:36:41 +02001574 }
1575 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001576 close_all_fds(profiles_fd, "profiles_fd");
1577 if (close(reference_profile_fd) != 0) {
1578 PLOG(WARNING) << "Failed to close fd for reference profile";
1579 }
Calin Juravlecea31412016-03-29 15:36:34 +01001580 if (should_clear_current_profiles) {
1581 clear_current_profiles(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001582 }
Calin Juravlecea31412016-03-29 15:36:34 +01001583 if (should_clear_reference_profile) {
1584 clear_reference_profile(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001585 }
1586 return need_to_compile;
Calin Juravle60a794d2015-12-24 12:36:41 +02001587}
1588
David Sehr6727c2d2016-05-17 16:06:22 -07001589static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1590 fd_t reference_profile_fd,
David Sehr40e566d2016-06-02 10:42:12 -07001591 const std::vector<std::string>& dex_locations,
1592 const std::vector<fd_t>& apk_fds,
David Sehr6727c2d2016-05-17 16:06:22 -07001593 fd_t output_fd) {
David Sehr40e566d2016-06-02 10:42:12 -07001594 std::vector<std::string> profman_args;
David Sehr6727c2d2016-05-17 16:06:22 -07001595 static const char* PROFMAN_BIN = "/system/bin/profman";
David Sehr40e566d2016-06-02 10:42:12 -07001596 profman_args.push_back(PROFMAN_BIN);
1597 profman_args.push_back("--dump-only");
1598 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1599 if (reference_profile_fd != -1) {
1600 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1601 reference_profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001602 }
1603 for (fd_t profile_fd : profile_fds) {
David Sehr40e566d2016-06-02 10:42:12 -07001604 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001605 }
David Sehr40e566d2016-06-02 10:42:12 -07001606 for (const std::string& dex_location : dex_locations) {
1607 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
David Sehr6727c2d2016-05-17 16:06:22 -07001608 }
David Sehr40e566d2016-06-02 10:42:12 -07001609 for (fd_t apk_fd : apk_fds) {
1610 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1611 }
1612 const char **argv = new const char*[profman_args.size() + 1];
1613 size_t i = 0;
1614 for (const std::string& profman_arg : profman_args) {
1615 argv[i++] = profman_arg.c_str();
David Sehr6727c2d2016-05-17 16:06:22 -07001616 }
1617 argv[i] = NULL;
David Sehr6727c2d2016-05-17 16:06:22 -07001618
1619 execv(PROFMAN_BIN, (char * const *)argv);
1620 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1621 exit(68); /* only get here on exec failure */
1622}
1623
David Sehr40e566d2016-06-02 10:42:12 -07001624static const char* get_location_from_path(const char* path) {
1625 static constexpr char kLocationSeparator = '/';
1626 const char *location = strrchr(path, kLocationSeparator);
1627 if (location == NULL) {
1628 return path;
1629 } else {
1630 // Skip the separator character.
1631 return location + 1;
1632 }
1633}
1634
David Sehr6727c2d2016-05-17 16:06:22 -07001635// Dumps the contents of a profile file, using pkgname's dex files for pretty
1636// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001637binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1638 const std::string& codePaths, bool* _aidl_return) {
1639 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001640 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001641
1642 const char* pkgname = packageName.c_str();
1643 const char* code_path_string = codePaths.c_str();
1644
David Sehr6727c2d2016-05-17 16:06:22 -07001645 std::vector<fd_t> profile_fds;
1646 fd_t reference_profile_fd = -1;
1647 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1648
1649 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1650
1651 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1652
1653 const bool has_reference_profile = (reference_profile_fd != -1);
1654 const bool has_profiles = !profile_fds.empty();
1655
1656 if (!has_reference_profile && !has_profiles) {
1657 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001658 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001659 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001660 }
1661
David Sehr40e566d2016-06-02 10:42:12 -07001662 fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
David Sehr6727c2d2016-05-17 16:06:22 -07001663 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1664 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001665 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001666 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001667 }
David Sehr40e566d2016-06-02 10:42:12 -07001668 std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1669 std::vector<std::string> dex_locations;
1670 std::vector<fd_t> apk_fds;
1671 for (const std::string& code_full_path : code_full_paths) {
1672 const char* full_path = code_full_path.c_str();
1673 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1674 if (apk_fd == -1) {
1675 ALOGE("installd cannot open '%s'\n", full_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001676 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001677 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001678 }
David Sehr40e566d2016-06-02 10:42:12 -07001679 dex_locations.push_back(get_location_from_path(full_path));
1680 apk_fds.push_back(apk_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001681 }
1682
1683 pid_t pid = fork();
1684 if (pid == 0) {
1685 /* child -- drop privileges before continuing */
1686 drop_capabilities(uid);
David Sehr40e566d2016-06-02 10:42:12 -07001687 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1688 apk_fds, output_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001689 exit(68); /* only get here on exec failure */
1690 }
1691 /* parent */
David Sehr40e566d2016-06-02 10:42:12 -07001692 close_all_fds(apk_fds, "apk_fds");
David Sehr6727c2d2016-05-17 16:06:22 -07001693 close_all_fds(profile_fds, "profile_fds");
1694 if (close(reference_profile_fd) != 0) {
1695 PLOG(WARNING) << "Failed to close fd for reference profile";
1696 }
1697 int return_code = wait_child(pid);
1698 if (!WIFEXITED(return_code)) {
1699 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1700 << return_code;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001701 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001702 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001703 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001704 *_aidl_return = true;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001705 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001706}
1707
David Brazdilfc5934e2016-09-08 11:55:48 +01001708static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1709 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
Andreas Gampe89b008d2016-06-03 21:13:50 -07001710 if (EndsWith(oat_path, ".dex")) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001711 std::string new_path = oat_path;
1712 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1713 CHECK(EndsWith(new_path, new_ext.c_str()));
1714 return new_path;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001715 }
Andreas Gampe89b008d2016-06-03 21:13:50 -07001716
1717 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1718 // case (where the base name will have an extension for the B artifact).
1719 size_t odex_pos = oat_path.rfind(".odex");
1720 if (odex_pos != std::string::npos) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001721 std::string new_path = oat_path;
1722 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1723 CHECK_NE(new_path.find(new_ext), std::string::npos);
1724 return new_path;
Andreas Gampe89b008d2016-06-03 21:13:50 -07001725 }
1726
1727 // Don't know how to handle this.
1728 return "";
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001729}
1730
David Brazdilfc5934e2016-09-08 11:55:48 +01001731// Translate the given oat path to an art (app image) path. An empty string
1732// denotes an error.
1733static std::string create_image_filename(const std::string& oat_path) {
1734 return replace_file_extension(oat_path, ".art");
1735}
1736
1737// Translate the given oat path to a vdex path. An empty string denotes an error.
1738static std::string create_vdex_filename(const std::string& oat_path) {
1739 return replace_file_extension(oat_path, ".vdex");
1740}
1741
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001742static bool add_extension_to_file_name(char* file_name, const char* extension) {
1743 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1744 return false;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001745 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001746 strcat(file_name, extension);
1747 return true;
1748}
1749
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001750static int open_output_file(const char* file_name, bool recreate, int permissions) {
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001751 int flags = O_RDWR | O_CREAT;
1752 if (recreate) {
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001753 if (unlink(file_name) < 0) {
1754 if (errno != ENOENT) {
1755 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1756 }
1757 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001758 flags |= O_EXCL;
1759 }
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001760 return open(file_name, flags, permissions);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001761}
1762
1763static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1764 if (fchmod(fd,
1765 S_IRUSR|S_IWUSR|S_IRGRP |
1766 (is_public ? S_IROTH : 0)) < 0) {
1767 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1768 return false;
1769 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1770 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1771 return false;
1772 }
1773 return true;
1774}
1775
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001776static bool IsOutputDalvikCache(const char* oat_dir) {
1777 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1778 // into '!'. Play it safe by handling it both.
1779 // TODO: ensure we never get null.
1780 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1781 return oat_dir == nullptr || oat_dir[0] == '!';
1782}
1783
Calin Juravle6a1648e2016-02-01 12:12:16 +00001784static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
David Brazdilfc5934e2016-09-08 11:55:48 +01001785 const char* oat_dir, /*out*/ char* out_oat_path) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001786 // Early best-effort check whether we can fit the the path into our buffers.
1787 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1788 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1789 // extension to the cache path (5 bytes).
1790 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1791 ALOGE("apk_path too long '%s'\n", apk_path);
1792 return false;
1793 }
1794
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001795 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001796 if (validate_apk_path(oat_dir)) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001797 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001798 return false;
1799 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001800 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001801 return false;
1802 }
1803 } else {
David Brazdilfc5934e2016-09-08 11:55:48 +01001804 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001805 return false;
1806 }
1807 }
1808 return true;
1809}
1810
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001811// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001812binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001813 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001814 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001815 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1816
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001817 const char* pkgname = packageName.c_str();
1818 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001819 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001820}
1821
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001822// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1823// on destruction. It will also run the given cleanup (unless told not to) after closing.
1824//
1825// Usage example:
1826//
1827// Dex2oatFileWrapper<std::function<void ()>> file(open(...),
1828// [name]() {
1829// unlink(name.c_str());
1830// });
1831// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1832// wrapper if captured as a reference.
1833//
1834// if (file.get() == -1) {
1835// // Error opening...
1836// }
1837//
1838// ...
1839// if (error) {
1840// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1841// // and delete the file (after the fd is closed).
1842// return -1;
1843// }
1844//
1845// (Success case)
1846// file.SetCleanup(false);
1847// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1848// // (leaving the file around; after the fd is closed).
1849//
1850template <typename Cleanup>
1851class Dex2oatFileWrapper {
1852 public:
1853 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
1854 }
1855
1856 Dex2oatFileWrapper(int value, Cleanup cleanup)
1857 : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
1858
1859 ~Dex2oatFileWrapper() {
1860 reset(-1);
1861 }
1862
1863 int get() {
1864 return value_;
1865 }
1866
1867 void SetCleanup(bool cleanup) {
1868 do_cleanup_ = cleanup;
1869 }
1870
1871 void reset(int new_value) {
1872 if (value_ >= 0) {
1873 close(value_);
1874 }
1875 if (do_cleanup_ && cleanup_ != nullptr) {
1876 cleanup_();
1877 }
1878
1879 value_ = new_value;
1880 }
1881
1882 void reset(int new_value, Cleanup new_cleanup) {
1883 if (value_ >= 0) {
1884 close(value_);
1885 }
1886 if (do_cleanup_ && cleanup_ != nullptr) {
1887 cleanup_();
1888 }
1889
1890 value_ = new_value;
1891 cleanup_ = new_cleanup;
1892 }
1893
1894 private:
1895 int value_;
1896 Cleanup cleanup_;
1897 bool do_cleanup_;
1898};
1899
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001900// TODO: eventually move dexopt() implementation into dexopt.cpp
Calin Juravle60a794d2015-12-24 12:36:41 +02001901int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001902 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1903 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
Calin Juravledb0326a2016-02-23 19:06:45 +00001904 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
Todd Kennedy76e767c2015-09-25 07:47:47 -07001905 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1906 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1907 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001908 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1909
1910 CHECK(pkgname != nullptr);
1911 CHECK(pkgname[0] != 0);
1912
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001913 // Public apps should not be compiled with profile information ever. Same goes for the special
1914 // package '*' used for the system server.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001915 Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001916 if (!is_public && pkgname[0] != '*') {
1917 // Open reference profile in read only mode as dex2oat does not get write permissions.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001918 const std::string pkgname_str(pkgname);
1919 reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1920 [pkgname_str]() {
1921 clear_reference_profile(pkgname_str.c_str());
1922 });
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001923 // Note: it's OK to not find a profile here.
Calin Juravle60a794d2015-12-24 12:36:41 +02001924 }
Todd Kennedy76e767c2015-09-25 07:47:47 -07001925
Todd Kennedye296e002015-11-16 14:41:36 -08001926 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -07001927 LOG_FATAL("dexopt flags contains unknown fields\n");
1928 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001929
David Brazdilfc5934e2016-09-08 11:55:48 +01001930 char out_oat_path[PKG_PATH_MAX];
1931 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001932 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001933 }
1934
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001935 const char *input_file;
1936 char in_odex_path[PKG_PATH_MAX];
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001937 int dexopt_action = abs(dexopt_needed);
1938 bool is_odex_location = dexopt_needed < 0;
1939 switch (dexopt_action) {
1940 case DEX2OAT_FROM_SCRATCH:
1941 case DEX2OAT_FOR_BOOT_IMAGE:
1942 case DEX2OAT_FOR_FILTER:
1943 case DEX2OAT_FOR_RELOCATION:
Richard Uhlerc92fb622015-03-26 15:47:38 -07001944 input_file = apk_path;
1945 break;
1946
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001947 case PATCHOAT_FOR_RELOCATION:
1948 if (is_odex_location) {
1949 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1950 return -1;
1951 }
1952 input_file = in_odex_path;
1953 } else {
1954 input_file = out_oat_path;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001955 }
Richard Uhlerc92fb622015-03-26 15:47:38 -07001956 break;
1957
1958 default:
1959 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001960 return 72;
Alex Light7365a102014-07-21 12:23:48 -07001961 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001962
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001963 struct stat input_stat;
Alex Light7365a102014-07-21 12:23:48 -07001964 memset(&input_stat, 0, sizeof(input_stat));
1965 stat(input_file, &input_stat);
1966
David Brazdilfc5934e2016-09-08 11:55:48 +01001967 // Open the input file. If running dex2oat, `input_file` is the APK. If running
1968 // patchoat, it is the OAT file to be relocated.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001969 base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1970 if (input_fd.get() < 0) {
Alex Light7365a102014-07-21 12:23:48 -07001971 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001972 return -1;
1973 }
1974
David Brazdilfc5934e2016-09-08 11:55:48 +01001975 // Create the output OAT file.
1976 const std::string out_oat_path_str(out_oat_path);
1977 Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1978 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1979 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1980 if (out_oat_fd.get() < 0) {
1981 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001982 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001983 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001984 if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1985 return -1;
1986 }
1987
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001988 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1989 // unlink the old one.
1990 base::unique_fd in_vdex_fd;
1991 std::string in_vdex_path_str;
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001992 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001993 // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1994 in_vdex_path_str = create_vdex_filename(input_file);
1995 if (in_vdex_path_str.empty()) {
1996 ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1997 return -1;
1998 }
1999 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
2000 if (in_vdex_fd.get() < 0) {
2001 ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
2002 in_vdex_path_str.c_str(), strerror(errno));
2003 return -1;
2004 }
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002005 } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
2006 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
2007 const char* path = nullptr;
2008 if (is_odex_location) {
2009 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
2010 path = in_odex_path;
2011 } else {
2012 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
2013 return -1;
2014 }
2015 } else {
2016 path = out_oat_path;
2017 }
2018 in_vdex_path_str = create_vdex_filename(path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002019 if (in_vdex_path_str.empty()) {
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002020 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002021 return -1;
2022 }
2023 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002024 }
2025
David Brazdilfc5934e2016-09-08 11:55:48 +01002026 // Infer the name of the output VDEX and create it.
2027 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
2028 if (out_vdex_path_str.empty()) {
2029 return -1;
2030 }
2031 Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
2032 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
2033 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
2034 if (out_vdex_fd.get() < 0) {
2035 ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
2036 return -1;
2037 }
2038 if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
2039 uid, out_vdex_path_str.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002040 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002041 }
2042
Andreas Gampee1c01352014-12-10 16:41:11 -08002043 // Create a swap file if necessary.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002044 base::unique_fd swap_fd;
Richard Uhlerc92fb622015-03-26 15:47:38 -07002045 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08002046 // Make sure there really is enough space.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002047 char swap_file_name[PKG_PATH_MAX];
David Brazdilfc5934e2016-09-08 11:55:48 +01002048 strcpy(swap_file_name, out_oat_path);
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08002049 if (add_extension_to_file_name(swap_file_name, ".swap")) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002050 swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08002051 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002052 if (swap_fd.get() < 0) {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002053 // Could not create swap file. Optimistically go on and hope that we can compile
2054 // without it.
2055 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08002056 } else {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002057 // Immediately unlink. We don't really want to hit flash.
Narayan Kamath5006f3a2016-04-07 10:42:41 +01002058 if (unlink(swap_file_name) < 0) {
2059 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
2060 }
Andreas Gampee1c01352014-12-10 16:41:11 -08002061 }
2062 }
Dave Allisond9370732014-01-30 14:19:23 -08002063
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08002064 // Avoid generating an app image for extract only since it will not contain any classes.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002065 Dex2oatFileWrapper<std::function<void ()>> image_fd;
David Brazdilfc5934e2016-09-08 11:55:48 +01002066 const std::string image_path = create_image_filename(out_oat_path);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002067 if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002068 char app_image_format[kPropertyValueMax];
2069 bool have_app_image_format =
2070 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
2071 // Use app images only if it is enabled (by a set image format) and we are compiling
2072 // profile-guided (so the app image doesn't conservatively contain all classes).
2073 if (profile_guided && have_app_image_format) {
2074 // Recreate is true since we do not want to modify a mapped image. If the app is
2075 // already running and we modify the image file, it can cause crashes (b/27493510).
Andreas Gampe89b008d2016-06-03 21:13:50 -07002076 image_fd.reset(open_output_file(image_path.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002077 true /*recreate*/,
2078 0600 /*permissions*/),
Andreas Gampe89b008d2016-06-03 21:13:50 -07002079 [image_path]() { unlink(image_path.c_str()); }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002080 );
2081 if (image_fd.get() < 0) {
2082 // Could not create application image file. Go on since we can compile without
2083 // it.
2084 LOG(ERROR) << "installd could not create '"
2085 << image_path
2086 << "' for image file during dexopt";
2087 } else if (!set_permissions_and_ownership(image_fd.get(),
2088 is_public,
2089 uid,
Andreas Gampe89b008d2016-06-03 21:13:50 -07002090 image_path.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002091 image_fd.reset(-1);
2092 }
2093 }
2094 // If we have a valid image file path but no image fd, explicitly erase the image file.
2095 if (image_fd.get() < 0) {
Andreas Gampe89b008d2016-06-03 21:13:50 -07002096 if (unlink(image_path.c_str()) < 0) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002097 if (errno != ENOENT) {
2098 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
2099 }
2100 }
2101 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002102 }
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08002103
Alex Light7365a102014-07-21 12:23:48 -07002104 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002105
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002106 pid_t pid = fork();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002107 if (pid == 0) {
2108 /* child -- drop privileges before continuing */
Calin Juravle6a1648e2016-02-01 12:12:16 +00002109 drop_capabilities(uid);
2110
Andreas Gampe13f14192015-09-21 13:21:30 -07002111 SetDex2OatAndPatchOatScheduling(boot_complete);
David Brazdilfc5934e2016-09-08 11:55:48 +01002112 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
2113 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002114 _exit(67);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002115 }
2116
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002117 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002118 run_patchoat(input_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002119 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002120 out_oat_fd.get(),
2121 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002122 input_file,
David Brazdilfc5934e2016-09-08 11:55:48 +01002123 in_vdex_path_str.c_str(),
2124 out_oat_path,
2125 out_vdex_path_str.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002126 pkgname,
2127 instruction_set);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002128 } else {
David Brazdilaaa1d4e2016-02-05 15:42:01 +00002129 // Pass dex2oat the relative path to the input file.
David Sehr40e566d2016-06-02 10:42:12 -07002130 const char *input_file_name = get_location_from_path(input_file);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002131 run_dex2oat(input_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002132 out_oat_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002133 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002134 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002135 image_fd.get(),
2136 input_file_name,
David Brazdilfc5934e2016-09-08 11:55:48 +01002137 out_oat_path,
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002138 swap_fd.get(),
2139 instruction_set,
2140 compiler_filter,
2141 vm_safe_mode,
2142 debuggable,
2143 boot_complete,
2144 reference_profile_fd.get(),
2145 shared_libraries);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002146 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002147 _exit(68); /* only get here on exec failure */
Mike Lockwood94afecf2012-10-24 10:45:23 -07002148 } else {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002149 int res = wait_child(pid);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002150 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07002151 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002152 } else {
Alex Light7365a102014-07-21 12:23:48 -07002153 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002154 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002155 }
2156 }
2157
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002158 struct utimbuf ut;
Alex Light7365a102014-07-21 12:23:48 -07002159 ut.actime = input_stat.st_atime;
2160 ut.modtime = input_stat.st_mtime;
David Brazdilfc5934e2016-09-08 11:55:48 +01002161 utime(out_oat_path, &ut);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002162
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002163 // We've been successful, don't delete output.
David Brazdilfc5934e2016-09-08 11:55:48 +01002164 out_oat_fd.SetCleanup(false);
2165 out_vdex_fd.SetCleanup(false);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002166 image_fd.SetCleanup(false);
2167 reference_profile_fd.SetCleanup(false);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002168
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002169 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002170}
2171
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002172binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2173 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2174 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2175 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
2176 const std::unique_ptr<std::string>& sharedLibraries) {
2177 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002178 CHECK_ARGUMENT_UUID(uuid);
2179 if (packageName && *packageName != "*") {
2180 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2181 }
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002182
2183 const char* apk_path = apkPath.c_str();
2184 const char* pkgname = packageName ? packageName->c_str() : "*";
2185 const char* instruction_set = instructionSet.c_str();
2186 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2187 const char* compiler_filter = compilerFilter.c_str();
2188 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
2189 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
2190
2191 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
2192 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002193 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002194}
2195
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002196binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2197 ENFORCE_UID(AID_SYSTEM);
2198 const char* instruction_set = instructionSet.c_str();
2199
2200 char boot_marker_path[PKG_PATH_MAX];
2201 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002202 "%s/%s/%s/.booting",
2203 android_data_dir.path,
2204 DALVIK_CACHE,
2205 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002206
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002207 ALOGV("mark_boot_complete : %s", boot_marker_path);
2208 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002209 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002210 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002211 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002212}
2213
Mike Lockwood94afecf2012-10-24 10:45:23 -07002214void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
2215 struct stat* statbuf)
2216{
2217 while (path[basepos] != 0) {
2218 if (path[basepos] == '/') {
2219 path[basepos] = 0;
2220 if (lstat(path, statbuf) < 0) {
2221 ALOGV("Making directory: %s\n", path);
2222 if (mkdir(path, mode) == 0) {
2223 chown(path, uid, gid);
2224 } else {
2225 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
2226 }
2227 }
2228 path[basepos] = '/';
2229 basepos++;
2230 }
2231 basepos++;
2232 }
2233}
2234
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002235binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2236 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2237 const std::string& nativeLibPath32, int32_t userId) {
2238 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002239 CHECK_ARGUMENT_UUID(uuid);
2240 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2241
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002242 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2243 const char* pkgname = packageName.c_str();
2244 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002245 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002246 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002247
Jeff Sharkey423e7462016-12-09 18:18:43 -07002248 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2249 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002250
2251 const char* pkgdir = _pkgdir.c_str();
2252 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002253
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002254 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002255 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002256 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002257
2258 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002259 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002260 }
2261
2262 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002263 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002264 goto out;
2265 }
2266
2267 if (lstat(libsymlink, &libStat) < 0) {
2268 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002269 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002270 goto out;
2271 }
2272 } else {
2273 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002274 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002275 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002276 goto out;
2277 }
2278 } else if (S_ISLNK(libStat.st_mode)) {
2279 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002280 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002281 goto out;
2282 }
2283 }
2284 }
2285
2286 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002287 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002288 goto out;
2289 }
2290
2291out:
2292 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002293 auto msg = "Failed to cleanup chmod " + _pkgdir;
2294 if (res.isOk()) {
2295 res = error(msg);
2296 } else {
2297 PLOG(ERROR) << msg;
2298 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002299 }
2300
2301 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002302 auto msg = "Failed to cleanup chown " + _pkgdir;
2303 if (res.isOk()) {
2304 res = error(msg);
2305 } else {
2306 PLOG(ERROR) << msg;
2307 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002308 }
2309
Jeff Sharkey423e7462016-12-09 18:18:43 -07002310 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002311}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002312
2313static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2314{
2315 static const char *IDMAP_BIN = "/system/bin/idmap";
2316 static const size_t MAX_INT_LEN = 32;
2317 char idmap_str[MAX_INT_LEN];
2318
2319 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
2320
2321 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
2322 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
2323}
2324
2325// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2326// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2327static int flatten_path(const char *prefix, const char *suffix,
2328 const char *overlay_path, char *idmap_path, size_t N)
2329{
2330 if (overlay_path == NULL || idmap_path == NULL) {
2331 return -1;
2332 }
2333 const size_t len_overlay_path = strlen(overlay_path);
2334 // will access overlay_path + 1 further below; requires absolute path
2335 if (len_overlay_path < 2 || *overlay_path != '/') {
2336 return -1;
2337 }
2338 const size_t len_idmap_root = strlen(prefix);
2339 const size_t len_suffix = strlen(suffix);
2340 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2341 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2342 // additions below would cause overflow
2343 return -1;
2344 }
2345 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2346 return -1;
2347 }
2348 memset(idmap_path, 0, N);
2349 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2350 char *ch = idmap_path + len_idmap_root;
2351 while (*ch != '\0') {
2352 if (*ch == '/') {
2353 *ch = '@';
2354 }
2355 ++ch;
2356 }
2357 return 0;
2358}
2359
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002360binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2361 const std::string& overlayApkPath, int32_t uid) {
2362 ENFORCE_UID(AID_SYSTEM);
2363 const char* target_apk = targetApkPath.c_str();
2364 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002365 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2366
2367 int idmap_fd = -1;
2368 char idmap_path[PATH_MAX];
2369
2370 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2371 idmap_path, sizeof(idmap_path)) == -1) {
2372 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2373 goto fail;
2374 }
2375
2376 unlink(idmap_path);
2377 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2378 if (idmap_fd < 0) {
2379 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2380 goto fail;
2381 }
2382 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2383 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2384 goto fail;
2385 }
2386 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2387 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2388 goto fail;
2389 }
2390
2391 pid_t pid;
2392 pid = fork();
2393 if (pid == 0) {
2394 /* child -- drop privileges before continuing */
2395 if (setgid(uid) != 0) {
2396 ALOGE("setgid(%d) failed during idmap\n", uid);
2397 exit(1);
2398 }
2399 if (setuid(uid) != 0) {
2400 ALOGE("setuid(%d) failed during idmap\n", uid);
2401 exit(1);
2402 }
2403 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2404 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2405 exit(1);
2406 }
2407
2408 run_idmap(target_apk, overlay_apk, idmap_fd);
2409 exit(1); /* only if exec call to idmap failed */
2410 } else {
2411 int status = wait_child(pid);
2412 if (status != 0) {
2413 ALOGE("idmap failed, status=0x%04x\n", status);
2414 goto fail;
2415 }
2416 }
2417
2418 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002419 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002420fail:
2421 if (idmap_fd >= 0) {
2422 close(idmap_fd);
2423 unlink(idmap_path);
2424 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002425 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002426}
Robert Craige9887e42014-02-20 10:25:56 -05002427
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002428binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2429 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2430 const std::string& seInfo) {
2431 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002432 CHECK_ARGUMENT_UUID(uuid);
2433 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2434
2435 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002436
Robert Craigda30dc72014-03-27 10:21:12 -04002437 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002438 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002439 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2440 const char* pkgName = packageName.c_str();
2441 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002442
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002443 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002444 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002445 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002446 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002447 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002448 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002449 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002450 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002451 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002452 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002453 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002454 }
Robert Craige9887e42014-02-20 10:25:56 -05002455 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002456 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002457}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002458
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002459binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2460 const std::string& instructionSet) {
2461 ENFORCE_UID(AID_SYSTEM);
2462 const char* oat_dir = oatDir.c_str();
2463 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002464 char oat_instr_dir[PKG_PATH_MAX];
2465
2466 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002467 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002468 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002469 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002470 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002471 }
2472 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002473 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002474 }
2475 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002476 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002477 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002478 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002479 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002480}
2481
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002482binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2483 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002484 if (validate_apk_path(packageDir.c_str())) {
2485 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002486 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002487 if (delete_dir_contents_and_dir(packageDir) != 0) {
2488 return error("Failed to delete " + packageDir);
2489 }
2490 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002491}
2492
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002493binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2494 const std::string& fromBase, const std::string& toBase) {
2495 ENFORCE_UID(AID_SYSTEM);
2496 const char* relative_path = relativePath.c_str();
2497 const char* from_base = fromBase.c_str();
2498 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002499 char from_path[PKG_PATH_MAX];
2500 char to_path[PKG_PATH_MAX];
2501 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2502 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2503
2504 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002505 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002506 }
2507
2508 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002509 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002510 }
2511
Jeff Sharkey423e7462016-12-09 18:18:43 -07002512 if (link(from_path, to_path) < 0) {
2513 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002514 }
2515
Jeff Sharkey423e7462016-12-09 18:18:43 -07002516 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002517}
2518
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002519// Helper for move_ab, so that we can have common failure-case cleanup.
2520static bool unlink_and_rename(const char* from, const char* to) {
2521 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2522 // return a failure.
2523 struct stat s;
2524 if (stat(to, &s) == 0) {
2525 if (!S_ISREG(s.st_mode)) {
2526 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2527 return false;
2528 }
2529 if (unlink(to) != 0) {
2530 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2531 return false;
2532 }
2533 } else {
2534 // This may be a permission problem. We could investigate the error code, but we'll just
2535 // let the rename failure do the work for us.
2536 }
2537
2538 // Try to rename "to" to "from."
2539 if (rename(from, to) != 0) {
2540 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2541 return false;
2542 }
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002543 return true;
2544}
2545
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002546// Move/rename a B artifact (from) to an A artifact (to).
2547static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2548 // Check whether B exists.
2549 {
2550 struct stat s;
2551 if (stat(b_path.c_str(), &s) != 0) {
2552 // Silently ignore for now. The service calling this isn't smart enough to understand
2553 // lack of artifacts at the moment.
2554 return false;
2555 }
2556 if (!S_ISREG(s.st_mode)) {
2557 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2558 // Try to unlink, but swallow errors.
2559 unlink(b_path.c_str());
2560 return false;
2561 }
2562 }
2563
2564 // Rename B to A.
2565 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2566 // Delete the b_path so we don't try again (or fail earlier).
2567 if (unlink(b_path.c_str()) != 0) {
2568 PLOG(ERROR) << "Could not unlink " << b_path;
2569 }
2570
2571 return false;
2572 }
2573
2574 return true;
2575}
2576
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002577binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2578 const std::string& instructionSet, const std::string& outputPath) {
2579 ENFORCE_UID(AID_SYSTEM);
2580 const char* apk_path = apkPath.c_str();
2581 const char* instruction_set = instructionSet.c_str();
2582 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07002583
2584 // Get the current slot suffix. No suffix, no A/B.
2585 std::string slot_suffix;
2586 {
2587 char buf[kPropertyValueMax];
2588 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002589 return error();
Andreas Gamped089ca12016-06-27 14:25:30 -07002590 }
2591 slot_suffix = buf;
2592
Andreas Gampefd12eda2016-07-12 09:47:17 -07002593 if (!ValidateTargetSlotSuffix(slot_suffix)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002594 return error("Target slot suffix not legal: " + slot_suffix);
Andreas Gamped089ca12016-06-27 14:25:30 -07002595 }
2596 }
2597
2598 // Validate other inputs.
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002599 if (validate_apk_path(apk_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002600 return error("Invalid apkPath: " + apkPath);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002601 }
2602 if (validate_apk_path(oat_dir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002603 return error("Invalid outputPath: " + outputPath);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002604 }
2605
2606 char a_path[PKG_PATH_MAX];
2607 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002608 return error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002609 }
David Brazdilfc5934e2016-09-08 11:55:48 +01002610 const std::string a_vdex_path = create_vdex_filename(a_path);
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002611 const std::string a_image_path = create_image_filename(a_path);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002612
Andreas Gamped089ca12016-06-27 14:25:30 -07002613 // B path = A path + slot suffix.
2614 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002615 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -07002616 const std::string b_image_path = StringPrintf("%s.%s",
2617 a_image_path.c_str(),
2618 slot_suffix.c_str());
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002619
David Brazdilfc5934e2016-09-08 11:55:48 +01002620 bool success = true;
2621 if (move_ab_path(b_path, a_path)) {
2622 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2623 // Note: we can live without an app image. As such, ignore failure to move the image file.
2624 // If we decide to require the app image, or the app image being moved correctly,
2625 // then change accordingly.
2626 constexpr bool kIgnoreAppImageFailure = true;
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002627
David Brazdilfc5934e2016-09-08 11:55:48 +01002628 if (!a_image_path.empty()) {
2629 if (!move_ab_path(b_image_path, a_image_path)) {
David Brazdilc338c7f2016-09-12 16:26:40 +01002630 unlink(a_image_path.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002631 if (!kIgnoreAppImageFailure) {
2632 success = false;
2633 }
2634 }
2635 }
2636 } else {
2637 // Cleanup: delete B image, ignore errors.
2638 unlink(b_image_path.c_str());
2639 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002640 }
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002641 } else {
2642 // Cleanup: delete B image, ignore errors.
David Brazdilfc5934e2016-09-08 11:55:48 +01002643 unlink(b_vdex_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002644 unlink(b_image_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002645 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002646 }
2647
Jeff Sharkey423e7462016-12-09 18:18:43 -07002648 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002649}
2650
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002651binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2652 const std::string& instructionSet, const std::string& outputPath) {
2653 ENFORCE_UID(AID_SYSTEM);
2654 const char* apk_path = apkPath.c_str();
2655 const char* instruction_set = instructionSet.c_str();
2656 const char* oat_dir = outputPath.c_str();
2657
Andreas Gampeb31206b2016-09-09 17:07:04 -07002658 // Delete the oat/odex file.
2659 char out_path[PKG_PATH_MAX];
2660 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002661 return error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07002662 }
2663
2664 // In case of a permission failure report the issue. Otherwise just print a warning.
2665 auto unlink_and_check = [](const char* path) -> bool {
2666 int result = unlink(path);
2667 if (result != 0) {
2668 if (errno == EACCES || errno == EPERM) {
2669 PLOG(ERROR) << "Could not unlink " << path;
2670 return false;
2671 }
2672 PLOG(WARNING) << "Could not unlink " << path;
2673 }
2674 return true;
2675 };
2676
2677 // Delete the oat/odex file.
2678 bool return_value_oat = unlink_and_check(out_path);
2679
2680 // Derive and delete the app image.
2681 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2682
2683 // Report success.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002684 bool success = return_value_oat && return_value_art;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002685 return success ? ok() : error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07002686}
2687
Andreas Gampe02d0de52015-11-11 20:43:16 -08002688} // namespace installd
2689} // namespace android