blob: 9033013f074a675a31fbd9476bbfec4877811698 [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
98static binder::Status exception(uint32_t code, const std::string& msg) {
99 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
100}
101
102static binder::Status error() {
103 return binder::Status::fromServiceSpecificError(errno);
104}
105
106static binder::Status error(const std::string& msg) {
107 PLOG(ERROR) << msg;
108 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
109}
110
111static binder::Status error(uint32_t code, const std::string& msg) {
112 LOG(ERROR) << msg << " (" << code << ")";
113 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
114}
115
Jeff Sharkey0274c972016-12-06 09:32:04 -0700116binder::Status checkPermission(const char* permission) {
117 pid_t pid;
118 uid_t uid;
119
120 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
121 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700122 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700123 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700124 return exception(binder::Status::EX_SECURITY,
125 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700126 }
127}
128
129binder::Status checkUid(uid_t expectedUid) {
130 uid_t uid = IPCThreadState::self()->getCallingUid();
131 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700132 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700133 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700134 return exception(binder::Status::EX_SECURITY,
135 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
136 }
137}
138
139binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
140 if (!uuid || is_valid_filename(*uuid)) {
141 return ok();
142 } else {
143 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
144 StringPrintf("UUID %s is malformed", uuid->c_str()));
145 }
146}
147
148binder::Status checkArgumentPackageName(const std::string& packageName) {
149 if (is_valid_package_name(packageName.c_str())) {
150 return ok();
151 } else {
152 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
153 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700154 }
155}
156
157#define ENFORCE_UID(uid) { \
158 binder::Status status = checkUid((uid)); \
159 if (!status.isOk()) { \
160 return status; \
161 } \
162}
163
Jeff Sharkey423e7462016-12-09 18:18:43 -0700164#define CHECK_ARGUMENT_UUID(uuid) { \
165 binder::Status status = checkArgumentUuid((uuid)); \
166 if (!status.isOk()) { \
167 return status; \
168 } \
169}
170
171#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
172 binder::Status status = \
173 checkArgumentPackageName((packageName)); \
174 if (!status.isOk()) { \
175 return status; \
176 } \
177}
178
Jeff Sharkey0274c972016-12-06 09:32:04 -0700179} // namespace
180
181status_t InstalldNativeService::start() {
182 IPCThreadState::self()->disableBackgroundScheduling(true);
183 status_t ret = BinderService<InstalldNativeService>::publish();
184 if (ret != android::OK) {
185 return ret;
186 }
187 sp<ProcessState> ps(ProcessState::self());
188 ps->startThreadPool();
189 ps->giveThreadPoolName();
190 return android::OK;
191}
192
193status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
194 const binder::Status dump_permission = checkPermission(kDump);
195 if (!dump_permission.isOk()) {
196 const String8 msg(dump_permission.toString8());
197 write(fd, msg.string(), msg.size());
198 return PERMISSION_DENIED;
199 }
200
201 std::string msg = "installd is happy\n";
202 write(fd, msg.c_str(), strlen(msg.c_str()));
203 return NO_ERROR;
204}
205
Calin Juravle6a1648e2016-02-01 12:12:16 +0000206static bool property_get_bool(const char* property_name, bool default_value = false) {
207 char tmp_property_value[kPropertyValueMax];
208 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
209 if (!have_property) {
210 return default_value;
211 }
212 return strcmp(tmp_property_value, "true") == 0;
213}
214
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100215// Keep profile paths in sync with ActivityThread.
216constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
217static std::string create_primary_profile(const std::string& profile_dir) {
218 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
219}
220
Jeff Sharkey7db60412016-09-20 18:21:42 -0600221/**
222 * Perform restorecon of the given path, but only perform recursive restorecon
223 * if the label of that top-level file actually changed. This can save us
224 * significant time by avoiding no-op traversals of large filesystem trees.
225 */
Jeff Sharkey0274c972016-12-06 09:32:04 -0700226static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600227 int res = 0;
228 char* before = nullptr;
229 char* after = nullptr;
230
231 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
232 // libselinux. Not needed here.
233
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600234 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600235 PLOG(ERROR) << "Failed before getfilecon for " << path;
236 goto fail;
237 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700238 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600239 PLOG(ERROR) << "Failed top-level restorecon for " << path;
240 goto fail;
241 }
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600242 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600243 PLOG(ERROR) << "Failed after getfilecon for " << path;
244 goto fail;
245 }
246
247 // If the initial top-level restorecon above changed the label, then go
248 // back and restorecon everything recursively
249 if (strcmp(before, after)) {
250 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
251 << "; running recursive restorecon";
Jeff Sharkey0274c972016-12-06 09:32:04 -0700252 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600253 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
254 PLOG(ERROR) << "Failed recursive restorecon for " << path;
255 goto fail;
256 }
257 }
258
259 goto done;
260fail:
261 res = -1;
262done:
263 free(before);
264 free(after);
265 return res;
266}
267
Jeff Sharkey0274c972016-12-06 09:32:04 -0700268static int restorecon_app_data_lazy(const std::string& parent, const char* name,
269 const std::string& seInfo, uid_t uid) {
270 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600271}
272
Jeff Sharkey7db60412016-09-20 18:21:42 -0600273static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600274 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
275 PLOG(ERROR) << "Failed to prepare " << path;
276 return -1;
277 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600278 return 0;
279}
280
281static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600282 uid_t uid) {
283 return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600284}
285
Jeff Sharkey0274c972016-12-06 09:32:04 -0700286binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
287 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
288 const std::string& seInfo, int32_t targetSdkVersion) {
289 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700290 CHECK_ARGUMENT_UUID(uuid);
291 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700292
293 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
294 const char* pkgname = packageName.c_str();
295
296 uid_t uid = multiuser_get_uid(userId, appId);
297 mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700298 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700299 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600300 if (prepare_app_dir(path, target_mode, uid) ||
301 prepare_app_dir(path, "cache", 0771, uid) ||
302 prepare_app_dir(path, "code_cache", 0771, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700303 return error("Failed to prepare " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600304 }
305
306 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700307 if (restorecon_app_data_lazy(path, seInfo, uid) ||
308 restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
309 restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700310 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700311 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600312
313 // Remember inode numbers of cache directories so that we can clear
314 // contents while CE storage is locked
315 if (write_path_inode(path, "cache", kXattrInodeCache) ||
316 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700317 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700318 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700319 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700320 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700321 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600322 if (prepare_app_dir(path, target_mode, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700323 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700324 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000325
Jeff Sharkey7db60412016-09-20 18:21:42 -0600326 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700327 if (restorecon_app_data_lazy(path, seInfo, uid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700328 return error("Failed to restorecon " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600329 }
330
Calin Juravle6a1648e2016-02-01 12:12:16 +0000331 if (property_get_bool("dalvik.vm.usejitprofiles")) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700332 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000333 // read-write-execute only for the app user.
334 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700335 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000336 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100337 std::string profile_file = create_primary_profile(profile_path);
338 // read-write only for the app user.
339 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700340 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100341 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000342 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
343 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
344 // profiles.
345 appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
346 if (fs_prepare_dir_strict(
347 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700348 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000349 }
350 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700351 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700352 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700353}
354
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700355binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
356 const std::string& packageName, int32_t userId, int32_t flags) {
357 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700358 CHECK_ARGUMENT_UUID(uuid);
359 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
360
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700361 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
362 const char* pkgname = packageName.c_str();
363
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700364 // This method only exists to upgrade system apps that have requested
365 // forceDeviceEncrypted, so their default storage always lives in a
366 // consistent location. This only works on non-FBE devices, since we
367 // never want to risk exposing data on a device with real CE/DE storage.
368
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700369 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
370 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700371
372 // If neither directory is marked as default, assume CE is default
373 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
374 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
375 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700376 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700377 }
378 }
379
380 // Migrate default data location if needed
381 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
382 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
383
384 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
385 LOG(WARNING) << "Requested default storage " << target
386 << " is not active; migrating from " << source;
387 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700388 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700389 }
390 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700391 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700392 }
393 }
394
Jeff Sharkey423e7462016-12-09 18:18:43 -0700395 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700396}
397
Calin Juravlecea31412016-03-29 15:36:34 +0100398static bool clear_profile(const std::string& profile) {
Roland Levillain64b59cc2016-04-05 16:41:12 +0100399 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
400 if (ufd.get() < 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100401 if (errno != ENOENT) {
402 PLOG(WARNING) << "Could not open profile " << profile;
403 return false;
404 } else {
405 // Nothing to clear. That's ok.
406 return true;
407 }
408 }
409
Roland Levillain64b59cc2016-04-05 16:41:12 +0100410 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100411 if (errno != EWOULDBLOCK) {
412 PLOG(WARNING) << "Error locking profile " << profile;
413 }
414 // This implies that the app owning this profile is running
415 // (and has acquired the lock).
416 //
417 // If we can't acquire the lock bail out since clearing is useless anyway
418 // (the app will write again to the profile).
419 //
420 // Note:
421 // This does not impact the this is not an issue for the profiling correctness.
422 // In case this is needed because of an app upgrade, profiles will still be
423 // eventually cleared by the app itself due to checksum mismatch.
424 // If this is needed because profman advised, then keeping the data around
425 // until the next run is again not an issue.
426 //
427 // If the app attempts to acquire a lock while we've held one here,
428 // it will simply skip the current write cycle.
429 return false;
430 }
431
Roland Levillain64b59cc2016-04-05 16:41:12 +0100432 bool truncated = ftruncate(ufd.get(), 0) == 0;
Calin Juravlecea31412016-03-29 15:36:34 +0100433 if (!truncated) {
434 PLOG(WARNING) << "Could not truncate " << profile;
435 }
Roland Levillain64b59cc2016-04-05 16:41:12 +0100436 if (flock(ufd.get(), LOCK_UN) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100437 PLOG(WARNING) << "Error unlocking profile " << profile;
438 }
439 return truncated;
440}
441
442static bool clear_reference_profile(const char* pkgname) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000443 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
444 std::string reference_profile = create_primary_profile(reference_profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100445 return clear_profile(reference_profile);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000446}
447
Calin Juravlecea31412016-03-29 15:36:34 +0100448static bool clear_current_profile(const char* pkgname, userid_t user) {
Calin Juravleedae6692016-03-23 13:55:31 +0000449 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
450 std::string profile = create_primary_profile(profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100451 return clear_profile(profile);
Calin Juravleedae6692016-03-23 13:55:31 +0000452}
453
Calin Juravlecea31412016-03-29 15:36:34 +0100454static bool clear_current_profiles(const char* pkgname) {
David Brazdild828d682016-03-08 12:50:20 +0000455 bool success = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000456 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
457 for (auto user : users) {
Calin Juravlecea31412016-03-29 15:36:34 +0100458 success &= clear_current_profile(pkgname, user);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000459 }
David Brazdild828d682016-03-08 12:50:20 +0000460 return success;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000461}
462
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700463binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
464 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700465 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
466
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700467 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700468 binder::Status res = ok();
469 if (!clear_reference_profile(pkgname)) {
470 res = error("Failed to clear reference profile for " + packageName);
471 }
472 if (!clear_current_profiles(pkgname)) {
473 res = error("Failed to clear current profiles for " + packageName);
474 }
475 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000476}
477
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700478binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
479 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
480 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481 CHECK_ARGUMENT_UUID(uuid);
482 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
483
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700484 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
485 const char* pkgname = packageName.c_str();
486
Jeff Sharkey423e7462016-12-09 18:18:43 -0700487 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700488 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700489 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600490 if (flags & FLAG_CLEAR_CACHE_ONLY) {
491 path = read_path_inode(path, "cache", kXattrInodeCache);
492 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
493 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
494 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700495 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700496 if (delete_dir_contents(path) != 0) {
497 res = error("Failed to delete contents of " + path);
498 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700499 }
500 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700501 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600502 std::string suffix = "";
503 bool only_cache = false;
504 if (flags & FLAG_CLEAR_CACHE_ONLY) {
505 suffix = CACHE_DIR_POSTFIX;
506 only_cache = true;
507 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
508 suffix = CODE_CACHE_DIR_POSTFIX;
509 only_cache = true;
510 }
511
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700512 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700513 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700514 if (delete_dir_contents(path) != 0) {
515 res = error("Failed to delete contents of " + path);
516 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700517 }
Calin Juravleedae6692016-03-23 13:55:31 +0000518 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700519 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000521 }
522 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700523 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700524 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700525}
526
Calin Juravle7535e8e2016-03-29 16:05:40 +0100527static int destroy_app_reference_profile(const char *pkgname) {
528 return delete_dir_contents_and_dir(
529 create_data_ref_profile_package_path(pkgname),
530 /*ignore_if_missing*/ true);
531}
532
Calin Juravleedae6692016-03-23 13:55:31 +0000533static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100534 return delete_dir_contents_and_dir(
535 create_data_user_profile_package_path(userid, pkgname),
536 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000537}
538
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700539binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
540 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700541 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
542
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700543 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700544 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000545 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
546 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 if (destroy_app_current_profiles(pkgname, user) != 0) {
548 res = error("Failed to destroy current profiles for " + packageName);
549 }
Calin Juravleedae6692016-03-23 13:55:31 +0000550 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700551 if (destroy_app_reference_profile(pkgname) != 0) {
552 res = error("Failed to destroy reference profile for " + packageName);
553 }
554 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000555}
556
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700557binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
558 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
559 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700560 CHECK_ARGUMENT_UUID(uuid);
561 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
562
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700563 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
564 const char* pkgname = packageName.c_str();
565
Jeff Sharkey423e7462016-12-09 18:18:43 -0700566 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700567 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
569 if (delete_dir_contents_and_dir(path) != 0) {
570 res = error("Failed to delete " + path);
571 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700572 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700573 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700574 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
575 if (delete_dir_contents_and_dir(path) != 0) {
576 res = error("Failed to delete " + path);
577 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700578 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100579 // TODO(calin): If the package is still installed by other users it's probably
580 // beneficial to keep the reference profile around.
581 // Verify if it's ok to do that.
582 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700583 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700585}
586
Jeff Sharkey0274c972016-12-06 09:32:04 -0700587binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
588 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
589 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
590 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700591 ENFORCE_UID(AID_SYSTEM);
592 CHECK_ARGUMENT_UUID(fromUuid);
593 CHECK_ARGUMENT_UUID(toUuid);
594 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700595
596 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
597 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
598 const char* package_name = packageName.c_str();
599 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700600
Jeff Sharkey423e7462016-12-09 18:18:43 -0700601 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700602 std::vector<userid_t> users = get_known_users(from_uuid);
603
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700604 // Copy app
605 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600606 auto from = create_data_app_package_path(from_uuid, data_app_name);
607 auto to = create_data_app_package_path(to_uuid, data_app_name);
608 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700609
610 char *argv[] = {
611 (char*) kCpPath,
612 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
613 (char*) "-p", /* preserve timestamps, ownership, and permissions */
614 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
615 (char*) "-P", /* Do not follow symlinks [default] */
616 (char*) "-d", /* don't dereference symlinks */
617 (char*) from.c_str(),
618 (char*) to_parent.c_str()
619 };
620
621 LOG(DEBUG) << "Copying " << from << " to " << to;
622 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700623 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700624 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700625 goto fail;
626 }
627
628 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700629 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700630 goto fail;
631 }
632 }
633
634 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700635 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700636
637 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600638 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
639 if (access(from_ce.c_str(), F_OK) != 0) {
640 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700641 continue;
642 }
643
Jeff Sharkey0274c972016-12-06 09:32:04 -0700644 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
645 seInfo, targetSdkVersion).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700646 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700647 goto fail;
648 }
649
650 char *argv[] = {
651 (char*) kCpPath,
652 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
653 (char*) "-p", /* preserve timestamps, ownership, and permissions */
654 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
655 (char*) "-P", /* Do not follow symlinks [default] */
656 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600657 nullptr,
658 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700659 };
660
Jeff Sharkey51c94492016-05-10 17:46:39 -0600661 {
662 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
663 auto to = create_data_user_de_path(to_uuid, user);
664 argv[6] = (char*) from.c_str();
665 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700666
Jeff Sharkey51c94492016-05-10 17:46:39 -0600667 LOG(DEBUG) << "Copying " << from << " to " << to;
668 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
669 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700670 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600671 goto fail;
672 }
673 }
674 {
675 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
676 auto to = create_data_user_ce_path(to_uuid, user);
677 argv[6] = (char*) from.c_str();
678 argv[7] = (char*) to.c_str();
679
680 LOG(DEBUG) << "Copying " << from << " to " << to;
681 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
682 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700683 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600684 goto fail;
685 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700686 }
687
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700688 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
689 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700690 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700691 goto fail;
692 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700693 }
694
Jeff Sharkey31f08982015-07-07 13:31:37 -0700695 // We let the framework scan the new location and persist that before
696 // deleting the data in the old location; this ordering ensures that
697 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700698 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700699
700fail:
701 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700702 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600703 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700704 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
705 LOG(WARNING) << "Failed to rollback " << to;
706 }
707 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700708 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600709 {
710 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
711 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
712 LOG(WARNING) << "Failed to rollback " << to;
713 }
714 }
715 {
716 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
717 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
718 LOG(WARNING) << "Failed to rollback " << to;
719 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700720 }
721 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700722 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700723}
724
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700725binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
726 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
727 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700728 CHECK_ARGUMENT_UUID(uuid);
729
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700730 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700731 binder::Status res = ok();
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600732 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700733 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700734 if (ensure_config_user_dirs(userId) != 0) {
735 res = error(StringPrintf("Failed to ensure dirs for %d", userId));
736 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700737 }
738 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700739 return res;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700740}
741
742binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
743 int32_t userId, int32_t flags) {
744 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700745 CHECK_ARGUMENT_UUID(uuid);
746
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700747 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700749 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700750 auto path = create_data_user_de_path(uuid_, userId);
751 if (delete_dir_contents_and_dir(path, true) != 0) {
752 res = error("Failed to delete " + path);
753 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700754 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700755 path = create_data_misc_legacy_path(userId);
756 if (delete_dir_contents_and_dir(path, true) != 0) {
757 res = error("Failed to delete " + path);
758 }
759 path = create_data_user_profiles_path(userId);
760 if (delete_dir_contents_and_dir(path, true) != 0) {
761 res = error("Failed to delete " + path);
762 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700763 }
Robin Lee095c7632014-04-25 15:05:19 +0100764 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600765 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700766 auto path = create_data_user_ce_path(uuid_, userId);
767 if (delete_dir_contents_and_dir(path, true) != 0) {
768 res = error("Failed to delete " + path);
769 }
770 path = create_data_media_path(uuid_, userId);
771 if (delete_dir_contents_and_dir(path, true) != 0) {
772 res = error("Failed to delete " + path);
773 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600774 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700775 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100776}
777
Mike Lockwood94afecf2012-10-24 10:45:23 -0700778/* Try to ensure free_size bytes of storage are available.
779 * Returns 0 on success.
780 * This is rather simple-minded because doing a full LRU would
781 * be potentially memory-intensive, and without atime it would
782 * also require that apps constantly modify file metadata even
783 * when just reading from the cache, which is pretty awful.
784 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700785binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
786 int64_t freeStorageSize) {
787 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700788 CHECK_ARGUMENT_UUID(uuid);
789
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700790 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700791 cache_t* cache;
792 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700793
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700794 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700795
796 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700797 if (avail < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700798 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700799 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700800
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700801 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
802 if (avail >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700803 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700804 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700805
806 cache = start_cache_collection();
807
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700808 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600809 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700810 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
811 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600812 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700813 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700814 }
815
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700816 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700817 finish_cache_collection(cache);
818
Jeff Sharkey423e7462016-12-09 18:18:43 -0700819 avail = data_disk_free(data_path);
820 if (avail >= freeStorageSize) {
821 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700822 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700823 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
824 freeStorageSize, data_path.c_str(), avail));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700825 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700826}
827
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700828binder::Status InstalldNativeService::rmdex(const std::string& codePath,
829 const std::string& instructionSet) {
830 ENFORCE_UID(AID_SYSTEM);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700831 char dex_path[PKG_PATH_MAX];
832
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700833 const char* path = codePath.c_str();
834 const char* instruction_set = instructionSet.c_str();
835
Jeff Sharkey770180a2014-09-08 17:14:26 -0700836 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700837 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700838 }
839
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700840 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700841 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700842 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700843
844 ALOGV("unlink %s\n", dex_path);
845 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700846 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700847 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700848 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700849 }
850}
851
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600852static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
853 int64_t *cachesize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700854 DIR *d;
855 int dfd;
856 struct dirent *de;
857 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700858
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600859 d = opendir(path.c_str());
860 if (d == nullptr) {
861 PLOG(WARNING) << "Failed to open " << path;
862 return;
863 }
864 dfd = dirfd(d);
865 while ((de = readdir(d))) {
866 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700867
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600868 int64_t statsize = 0;
869 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
870 statsize = stat_size(&s);
871 }
872
873 if (de->d_type == DT_DIR) {
874 int subfd;
875 int64_t dirsize = 0;
876 /* always skip "." and ".." */
877 if (name[0] == '.') {
878 if (name[1] == 0) continue;
879 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700880 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600881 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
882 if (subfd >= 0) {
883 dirsize = calculate_dir_size(subfd);
884 close(subfd);
885 }
886 // TODO: check xattrs!
887 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
888 *datasize += statsize;
889 *cachesize += dirsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700890 } else {
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600891 *datasize += dirsize + statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700892 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600893 } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
894 *codesize += statsize;
895 } else {
896 *datasize += statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700897 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600898 }
899 closedir(d);
900}
901
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700902binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey423e7462016-12-09 18:18:43 -0700903 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
904 const std::string& codePath, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700905 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700906 CHECK_ARGUMENT_UUID(uuid);
907 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
908
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700909 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
910 const char* pkgname = packageName.c_str();
911 const char* code_path = codePath.c_str();
912
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600913 DIR *d;
914 int dfd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700915 int64_t codesize = 0;
916 int64_t datasize = 0;
917 int64_t cachesize = 0;
918 int64_t asecsize = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600919
920 d = opendir(code_path);
921 if (d != nullptr) {
922 dfd = dirfd(d);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700923 codesize += calculate_dir_size(dfd);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700924 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700925 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600926
927 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700928 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
929 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600930 }
931 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700932 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
933 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600934 }
935
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700936 std::vector<int64_t> res;
937 res.push_back(codesize);
938 res.push_back(datasize);
939 res.push_back(cachesize);
940 res.push_back(asecsize);
941 *_aidl_return = res;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700942 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700943}
944
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700945binder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700946 const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700947 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700948 CHECK_ARGUMENT_UUID(uuid);
949 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
950
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700951 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
952 const char* pkgname = packageName.c_str();
953
Jeff Sharkey423e7462016-12-09 18:18:43 -0700954 binder::Status res = ok();
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600955 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700956 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700957 if (get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
958 res = error("Failed to get_path_inode for " + path);
959 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600960 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700961 return res;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600962}
963
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700964static int split_count(const char *str)
965{
966 char *ctx;
967 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800968 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700969
970 strncpy(buf, str, sizeof(buf));
971 char *pBuf = buf;
972
973 while(strtok_r(pBuf, " ", &ctx) != NULL) {
974 count++;
975 pBuf = NULL;
976 }
977
978 return count;
979}
980
neo.chae14e084d2015-01-07 18:46:13 +0900981static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700982{
983 char *ctx;
984 int count = 0;
985 char *tok;
986 char *pBuf = buf;
987
988 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
989 argv[count++] = tok;
990 pBuf = NULL;
991 }
992
993 return count;
994}
995
David Brazdilfc5934e2016-09-08 11:55:48 +0100996static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
997 const char* input_oat_file_name, const char* input_vdex_file_name,
998 const char* output_oat_file_name, const char* output_vdex_file_name,
999 const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -07001000{
1001 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +01001002 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -07001003
1004 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
1005 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1006 ALOGE("Instruction set %s longer than max length of %d",
1007 instruction_set, MAX_INSTRUCTION_SET_LEN);
1008 return;
1009 }
1010
1011 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
1012 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Alex Light7365a102014-07-21 12:23:48 -07001013 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
David Brazdilfc5934e2016-09-08 11:55:48 +01001014 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1015 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
1016 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Alex Light7365a102014-07-21 12:23:48 -07001017 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
1018 // The caller has already gotten all the locks we need.
1019 const char* no_lock_arg = "--no-lock-output";
1020 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
David Brazdilfc5934e2016-09-08 11:55:48 +01001021 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
1022 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
1023 ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
1024 "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
1025 PATCHOAT_BIN, instruction_set,
1026 input_oat_fd, input_oat_file_name,
1027 input_vdex_fd, input_vdex_file_name,
1028 out_oat_fd, output_oat_file_name,
1029 out_vdex_fd, output_vdex_file_name);
Alex Light7365a102014-07-21 12:23:48 -07001030
1031 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
David Brazdilfc5934e2016-09-08 11:55:48 +01001032 char* argv[9];
Alex Light7365a102014-07-21 12:23:48 -07001033 argv[0] = (char*) PATCHOAT_BIN;
1034 argv[1] = (char*) patched_image_location_arg;
1035 argv[2] = (char*) no_lock_arg;
1036 argv[3] = instruction_set_arg;
David Brazdilfc5934e2016-09-08 11:55:48 +01001037 argv[4] = input_oat_fd_arg;
1038 argv[5] = input_vdex_fd_arg;
1039 argv[6] = output_oat_fd_arg;
1040 argv[7] = output_vdex_fd_arg;
1041 argv[8] = NULL;
Alex Light7365a102014-07-21 12:23:48 -07001042
1043 execv(PATCHOAT_BIN, (char* const *)argv);
1044 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
1045}
1046
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001047static 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 +01001048 const char* input_file_name, const char* output_file_name, int swap_fd,
1049 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
1050 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
Calin Juravle8fc73152014-08-19 18:48:50 +01001051 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1052
1053 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1054 ALOGE("Instruction set %s longer than max length of %d",
1055 instruction_set, MAX_INSTRUCTION_SET_LEN);
1056 return;
1057 }
1058
Andreas Gampe02d0de52015-11-11 20:43:16 -08001059 char dex2oat_Xms_flag[kPropertyValueMax];
1060 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001061
Andreas Gampe02d0de52015-11-11 20:43:16 -08001062 char dex2oat_Xmx_flag[kPropertyValueMax];
1063 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001064
Andreas Gampe02d0de52015-11-11 20:43:16 -08001065 char dex2oat_threads_buf[kPropertyValueMax];
1066 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -07001067 ? "dalvik.vm.dex2oat-threads"
1068 : "dalvik.vm.boot-dex2oat-threads",
1069 dex2oat_threads_buf,
1070 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -08001071 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001072 if (have_dex2oat_threads_flag) {
1073 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
1074 }
1075
Andreas Gampe02d0de52015-11-11 20:43:16 -08001076 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +01001077 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001078 char dex2oat_isa_features[kPropertyValueMax];
1079 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +01001080 dex2oat_isa_features, NULL) > 0;
1081
Andreas Gampe02d0de52015-11-11 20:43:16 -08001082 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -08001083 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001084 char dex2oat_isa_variant[kPropertyValueMax];
1085 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -08001086 dex2oat_isa_variant, NULL) > 0;
1087
neo.chae14e084d2015-01-07 18:46:13 +09001088 const char *dex2oat_norelocation = "-Xnorelocate";
1089 bool have_dex2oat_relocation_skip_flag = false;
1090
Andreas Gampe02d0de52015-11-11 20:43:16 -08001091 char dex2oat_flags[kPropertyValueMax];
1092 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001093 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -08001094 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
1095
Brian Carlstrom538998f2014-07-30 14:37:11 -07001096 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -08001097 char vold_decrypt[kPropertyValueMax];
1098 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001099 bool skip_compilation = (have_vold_decrypt &&
1100 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
1101 (strcmp(vold_decrypt, "1") == 0)));
1102
Calin Juravle6a1648e2016-02-01 12:12:16 +00001103 bool generate_debug_info = property_get_bool("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001104
Mathieu Chartier416fa122016-02-03 13:48:16 -08001105 char app_image_format[kPropertyValueMax];
1106 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
1107 bool have_app_image_format =
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001108 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
Mathieu Chartier416fa122016-02-03 13:48:16 -08001109 if (have_app_image_format) {
1110 sprintf(image_format_arg, "--image-format=%s", app_image_format);
1111 }
1112
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001113 char dex2oat_large_app_threshold[kPropertyValueMax];
1114 bool have_dex2oat_large_app_threshold =
1115 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
1116 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
1117 if (have_dex2oat_large_app_threshold) {
1118 sprintf(dex2oat_large_app_threshold_arg,
1119 "--very-large-app-threshold=%s",
1120 dex2oat_large_app_threshold);
1121 }
1122
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001123 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001124
Brian Carlstrom53e07762014-06-27 14:15:19 -07001125 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001126
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001127 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +01001128
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001129 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
1130 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001131 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1132 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001133 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -07001134 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +01001135 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001136 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
1137 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
1138 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
1139 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
1140 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -08001141 bool have_dex2oat_swap_fd = false;
1142 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001143 bool have_dex2oat_image_fd = false;
1144 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001145
1146 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
1147 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001148 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
1149 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001150 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
1151 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +01001152 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -08001153 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +01001154 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -08001155 if (swap_fd >= 0) {
1156 have_dex2oat_swap_fd = true;
1157 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1158 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001159 if (image_fd >= 0) {
1160 have_dex2oat_image_fd = true;
1161 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1162 }
Calin Juravle57c69c32014-06-06 14:42:16 +01001163
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001164 if (have_dex2oat_Xms_flag) {
1165 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1166 }
1167 if (have_dex2oat_Xmx_flag) {
1168 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1169 }
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001170
1171 // Compute compiler filter.
1172
1173 bool have_dex2oat_compiler_filter_flag;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001174 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -07001175 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -07001176 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +09001177 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +01001178 } else if (vm_safe_mode) {
1179 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +01001180 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001181 } else if (compiler_filter != nullptr &&
1182 strlen(compiler_filter) + strlen("--compiler-filter=") <
1183 arraysize(dex2oat_compiler_filter_arg)) {
1184 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001185 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001186 } else {
1187 char dex2oat_compiler_filter_flag[kPropertyValueMax];
1188 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
1189 dex2oat_compiler_filter_flag, NULL) > 0;
1190 if (have_dex2oat_compiler_filter_flag) {
1191 sprintf(dex2oat_compiler_filter_arg,
1192 "--compiler-filter=%s",
1193 dex2oat_compiler_filter_flag);
1194 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001195 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001196
Andreas Gampe598c25e2015-03-03 09:15:06 -08001197 // Check whether all apps should be compiled debuggable.
1198 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001199 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -08001200 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -08001201 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -08001202 (prop_buf[0] == '1');
1203 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001204 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
1205 if (profile_fd != -1) {
1206 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001207 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001208
Calin Juravle6a1648e2016-02-01 12:12:16 +00001209
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001210 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +01001211
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001212 const char* argv[9 // program name, mandatory arguments and the final NULL
neo.chae14e084d2015-01-07 18:46:13 +09001213 + (have_dex2oat_isa_variant ? 1 : 0)
1214 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001215 + (have_dex2oat_Xms_flag ? 2 : 0)
1216 + (have_dex2oat_Xmx_flag ? 2 : 0)
1217 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001218 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001219 + (have_dex2oat_swap_fd ? 1 : 0)
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001220 + (have_dex2oat_image_fd ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001221 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +01001222 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -08001223 + (debuggable ? 1 : 0)
Mathieu Chartier416fa122016-02-03 13:48:16 -08001224 + (have_app_image_format ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +02001225 + dex2oat_flags_count
Jeff Haob63d91f2016-03-16 15:59:25 -07001226 + (profile_fd == -1 ? 0 : 1)
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001227 + (shared_libraries != nullptr ? 4 : 0)
1228 + (have_dex2oat_large_app_threshold ? 1 : 0)];
Calin Juravle4fdff462014-06-06 16:58:43 +01001229 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +09001230 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +01001231 argv[i++] = zip_fd_arg;
1232 argv[i++] = zip_location_arg;
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001233 argv[i++] = input_vdex_fd_arg;
1234 argv[i++] = output_vdex_fd_arg;
Calin Juravle4fdff462014-06-06 16:58:43 +01001235 argv[i++] = oat_fd_arg;
1236 argv[i++] = oat_location_arg;
1237 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -08001238 if (have_dex2oat_isa_variant) {
1239 argv[i++] = instruction_set_variant_arg;
1240 }
Calin Juravle8fc73152014-08-19 18:48:50 +01001241 if (have_dex2oat_isa_features) {
1242 argv[i++] = instruction_set_features_arg;
1243 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001244 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001245 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001246 argv[i++] = dex2oat_Xms_arg;
1247 }
1248 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001249 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001250 argv[i++] = dex2oat_Xmx_arg;
1251 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001252 if (have_dex2oat_compiler_filter_flag) {
1253 argv[i++] = dex2oat_compiler_filter_arg;
1254 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001255 if (have_dex2oat_threads_flag) {
1256 argv[i++] = dex2oat_threads_arg;
1257 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001258 if (have_dex2oat_swap_fd) {
1259 argv[i++] = dex2oat_swap_fd;
1260 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001261 if (have_dex2oat_image_fd) {
1262 argv[i++] = dex2oat_image_fd;
1263 }
David Srbecky528c8dd2015-05-28 16:55:50 +01001264 if (generate_debug_info) {
1265 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -07001266 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001267 if (debuggable) {
1268 argv[i++] = "--debuggable";
1269 }
Mathieu Chartier416fa122016-02-03 13:48:16 -08001270 if (have_app_image_format) {
1271 argv[i++] = image_format_arg;
1272 }
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001273 if (have_dex2oat_large_app_threshold) {
1274 argv[i++] = dex2oat_large_app_threshold_arg;
1275 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001276 if (dex2oat_flags_count) {
1277 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +01001278 }
neo.chae14e084d2015-01-07 18:46:13 +09001279 if (have_dex2oat_relocation_skip_flag) {
1280 argv[i++] = RUNTIME_ARG;
1281 argv[i++] = dex2oat_norelocation;
1282 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001283 if (profile_fd != -1) {
1284 argv[i++] = profile_arg;
Calin Juravle60a794d2015-12-24 12:36:41 +02001285 }
Jeff Haob63d91f2016-03-16 15:59:25 -07001286 if (shared_libraries != nullptr) {
1287 argv[i++] = RUNTIME_ARG;
1288 argv[i++] = "-classpath";
1289 argv[i++] = RUNTIME_ARG;
1290 argv[i++] = shared_libraries;
1291 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001292 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +01001293 argv[i] = NULL;
1294
neo.chae14e084d2015-01-07 18:46:13 +09001295 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001296 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001297}
1298
Andreas Gampee1c01352014-12-10 16:41:11 -08001299/*
Andreas Gampec968c012015-07-16 15:55:41 -07001300 * Whether dexopt should use a swap file when compiling an APK.
1301 *
1302 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1303 * itself, anyways).
1304 *
1305 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1306 *
1307 * Otherwise, return true if this is a low-mem device.
1308 *
1309 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -08001310 */
Andreas Gampec968c012015-07-16 15:55:41 -07001311static bool kAlwaysProvideSwapFile = false;
1312static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -08001313
1314static bool ShouldUseSwapFileForDexopt() {
1315 if (kAlwaysProvideSwapFile) {
1316 return true;
1317 }
1318
Andreas Gampec968c012015-07-16 15:55:41 -07001319 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -08001320 char dex2oat_prop_buf[kPropertyValueMax];
1321 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -07001322 if (strcmp(dex2oat_prop_buf, "true") == 0) {
1323 return true;
1324 } else {
1325 return false;
1326 }
1327 }
1328
1329 // Shortcut for default value. This is an implementation optimization for the process sketched
1330 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1331 // as low-mem is never returning false. The compiler will optimize this away if it can.
1332 if (kDefaultProvideSwapFile) {
1333 return true;
1334 }
1335
Calin Juravle6a1648e2016-02-01 12:12:16 +00001336 bool is_low_mem = property_get_bool("ro.config.low_ram");
Andreas Gampec968c012015-07-16 15:55:41 -07001337 if (is_low_mem) {
1338 return true;
1339 }
1340
1341 // Default value must be false here.
1342 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -08001343}
1344
Andreas Gampe94dd3d32015-09-14 16:33:11 -07001345static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
1346 if (set_to_bg) {
1347 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1348 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1349 exit(70);
1350 }
1351 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1352 ALOGE("setpriority failed: %s\n", strerror(errno));
1353 exit(71);
1354 }
1355 }
1356}
1357
Calin Juravle6a1648e2016-02-01 12:12:16 +00001358static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001359 for (size_t i = 0; i < fds.size(); i++) {
1360 if (close(fds[i]) != 0) {
1361 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
1362 }
1363 }
1364}
1365
Calin Juravle6a1648e2016-02-01 12:12:16 +00001366static fd_t open_profile_dir(const std::string& profile_dir) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001367 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
1368 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
1369 if (profile_dir_fd < 0) {
Narayan Kamath2e063af2016-05-02 09:47:49 +01001370 // In a multi-user environment, these directories can be created at
1371 // different points and it's possible we'll attempt to open a profile
1372 // dir before it exists.
1373 if (errno != ENOENT) {
1374 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
1375 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001376 }
1377 return profile_dir_fd;
1378}
1379
1380static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1381 fd_t profile_dir_fd = open_profile_dir(profile_dir);
1382 if (profile_dir_fd < 0) {
1383 return -1;
1384 }
1385
1386 fd_t profile_fd = -1;
1387 std::string profile_file = create_primary_profile(profile_dir);
1388
1389 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1390 if (profile_fd == -1) {
1391 // It's not an error if the profile file does not exist.
Calin Juravle60a794d2015-12-24 12:36:41 +02001392 if (errno != ENOENT) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001393 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1394 }
1395 }
1396 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1397 if (close(profile_dir_fd) != 0) {
1398 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1399 }
1400 return profile_fd;
1401}
1402
1403static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1404 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1405 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1406}
1407
1408static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1409 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1410 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1411 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1412 if (fd < 0) {
1413 return -1;
1414 }
1415 if (read_write) {
1416 // Fix the owner.
1417 if (fchown(fd, uid, uid) < 0) {
1418 close(fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001419 return -1;
1420 }
1421 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001422 return fd;
Calin Juravle60a794d2015-12-24 12:36:41 +02001423}
1424
Calin Juravle6a1648e2016-02-01 12:12:16 +00001425static void open_profile_files(uid_t uid, const char* pkgname,
1426 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1427 // Open the reference profile in read-write mode as profman might need to save the merge.
1428 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
Calin Juravle60a794d2015-12-24 12:36:41 +02001429 if (*reference_profile_fd < 0) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001430 // We can't access the reference profile file.
Calin Juravle60a794d2015-12-24 12:36:41 +02001431 return;
1432 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001433
1434 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1435 for (auto user : users) {
1436 fd_t profile_fd = open_primary_profile_file(user, pkgname);
1437 // Add to the lists only if both fds are valid.
1438 if (profile_fd >= 0) {
1439 profiles_fd->push_back(profile_fd);
1440 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001441 }
1442}
1443
Calin Juravle6a1648e2016-02-01 12:12:16 +00001444static void drop_capabilities(uid_t uid) {
1445 if (setgid(uid) != 0) {
1446 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1447 exit(64);
1448 }
1449 if (setuid(uid) != 0) {
1450 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1451 exit(65);
1452 }
1453 // drop capabilities
1454 struct __user_cap_header_struct capheader;
1455 struct __user_cap_data_struct capdata[2];
1456 memset(&capheader, 0, sizeof(capheader));
1457 memset(&capdata, 0, sizeof(capdata));
1458 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1459 if (capset(&capheader, &capdata[0]) < 0) {
1460 ALOGE("capset failed: %s\n", strerror(errno));
1461 exit(66);
1462 }
1463}
Calin Juravle60a794d2015-12-24 12:36:41 +02001464
Calin Juravle6a1648e2016-02-01 12:12:16 +00001465static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1466static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1467static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1468static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1469static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1470
David Sehr6727c2d2016-05-17 16:06:22 -07001471static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001472 static const size_t MAX_INT_LEN = 32;
1473 static const char* PROFMAN_BIN = "/system/bin/profman";
1474
1475 std::vector<std::string> profile_args(profiles_fd.size());
1476 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1477 for (size_t k = 0; k < profiles_fd.size(); k++) {
1478 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1479 profile_args[k].assign(profile_buf);
1480 }
1481 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1482 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1483
1484 // program name, reference profile fd, the final NULL and the profile fds
1485 const char* argv[3 + profiles_fd.size()];
1486 int i = 0;
1487 argv[i++] = PROFMAN_BIN;
1488 argv[i++] = reference_profile_arg;
1489 for (size_t k = 0; k < profile_args.size(); k++) {
1490 argv[i++] = profile_args[k].c_str();
1491 }
1492 // Do not add after dex2oat_flags, they should override others for debugging.
1493 argv[i] = NULL;
1494
1495 execv(PROFMAN_BIN, (char * const *)argv);
1496 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1497 exit(68); /* only get here on exec failure */
1498}
1499
1500// Decides if profile guided compilation is needed or not based on existing profiles.
1501// Returns true if there is enough information in the current profiles that worth
1502// a re-compilation of the package.
1503// If the return value is true all the current profiles would have been merged into
1504// the reference profiles accessible with open_reference_profile().
1505static bool analyse_profiles(uid_t uid, const char* pkgname) {
1506 std::vector<fd_t> profiles_fd;
1507 fd_t reference_profile_fd = -1;
1508 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1509 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1510 // Skip profile guided compilation because no profiles were found.
1511 // Or if the reference profile info couldn't be opened.
1512 close_all_fds(profiles_fd, "profiles_fd");
1513 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1514 PLOG(WARNING) << "Failed to close fd for reference profile";
1515 }
1516 return false;
1517 }
1518
David Sehr6727c2d2016-05-17 16:06:22 -07001519 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001520
1521 pid_t pid = fork();
1522 if (pid == 0) {
1523 /* child -- drop privileges before continuing */
1524 drop_capabilities(uid);
David Sehr6727c2d2016-05-17 16:06:22 -07001525 run_profman_merge(profiles_fd, reference_profile_fd);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001526 exit(68); /* only get here on exec failure */
1527 }
1528 /* parent */
1529 int return_code = wait_child(pid);
1530 bool need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001531 bool should_clear_current_profiles = false;
1532 bool should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001533 if (!WIFEXITED(return_code)) {
1534 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1535 } else {
1536 return_code = WEXITSTATUS(return_code);
1537 switch (return_code) {
1538 case PROFMAN_BIN_RETURN_CODE_COMPILE:
1539 need_to_compile = true;
Calin Juravlecea31412016-03-29 15:36:34 +01001540 should_clear_current_profiles = true;
1541 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001542 break;
1543 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1544 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001545 should_clear_current_profiles = false;
1546 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001547 break;
1548 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1549 LOG(WARNING) << "Bad profiles for package " << pkgname;
1550 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001551 should_clear_current_profiles = true;
1552 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001553 break;
1554 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
1555 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1556 // Temporary IO problem (e.g. locking). Ignore but log a warning.
1557 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1558 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001559 should_clear_current_profiles = false;
1560 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001561 break;
1562 default:
1563 // Unknown return code or error. Unlink profiles.
1564 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1565 << ": " << return_code;
1566 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001567 should_clear_current_profiles = true;
1568 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001569 break;
Calin Juravle60a794d2015-12-24 12:36:41 +02001570 }
1571 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001572 close_all_fds(profiles_fd, "profiles_fd");
1573 if (close(reference_profile_fd) != 0) {
1574 PLOG(WARNING) << "Failed to close fd for reference profile";
1575 }
Calin Juravlecea31412016-03-29 15:36:34 +01001576 if (should_clear_current_profiles) {
1577 clear_current_profiles(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001578 }
Calin Juravlecea31412016-03-29 15:36:34 +01001579 if (should_clear_reference_profile) {
1580 clear_reference_profile(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001581 }
1582 return need_to_compile;
Calin Juravle60a794d2015-12-24 12:36:41 +02001583}
1584
David Sehr6727c2d2016-05-17 16:06:22 -07001585static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1586 fd_t reference_profile_fd,
David Sehr40e566d2016-06-02 10:42:12 -07001587 const std::vector<std::string>& dex_locations,
1588 const std::vector<fd_t>& apk_fds,
David Sehr6727c2d2016-05-17 16:06:22 -07001589 fd_t output_fd) {
David Sehr40e566d2016-06-02 10:42:12 -07001590 std::vector<std::string> profman_args;
David Sehr6727c2d2016-05-17 16:06:22 -07001591 static const char* PROFMAN_BIN = "/system/bin/profman";
David Sehr40e566d2016-06-02 10:42:12 -07001592 profman_args.push_back(PROFMAN_BIN);
1593 profman_args.push_back("--dump-only");
1594 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1595 if (reference_profile_fd != -1) {
1596 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1597 reference_profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001598 }
1599 for (fd_t profile_fd : profile_fds) {
David Sehr40e566d2016-06-02 10:42:12 -07001600 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001601 }
David Sehr40e566d2016-06-02 10:42:12 -07001602 for (const std::string& dex_location : dex_locations) {
1603 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
David Sehr6727c2d2016-05-17 16:06:22 -07001604 }
David Sehr40e566d2016-06-02 10:42:12 -07001605 for (fd_t apk_fd : apk_fds) {
1606 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1607 }
1608 const char **argv = new const char*[profman_args.size() + 1];
1609 size_t i = 0;
1610 for (const std::string& profman_arg : profman_args) {
1611 argv[i++] = profman_arg.c_str();
David Sehr6727c2d2016-05-17 16:06:22 -07001612 }
1613 argv[i] = NULL;
David Sehr6727c2d2016-05-17 16:06:22 -07001614
1615 execv(PROFMAN_BIN, (char * const *)argv);
1616 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1617 exit(68); /* only get here on exec failure */
1618}
1619
David Sehr40e566d2016-06-02 10:42:12 -07001620static const char* get_location_from_path(const char* path) {
1621 static constexpr char kLocationSeparator = '/';
1622 const char *location = strrchr(path, kLocationSeparator);
1623 if (location == NULL) {
1624 return path;
1625 } else {
1626 // Skip the separator character.
1627 return location + 1;
1628 }
1629}
1630
David Sehr6727c2d2016-05-17 16:06:22 -07001631// Dumps the contents of a profile file, using pkgname's dex files for pretty
1632// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001633binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1634 const std::string& codePaths, bool* _aidl_return) {
1635 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001636 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001637
1638 const char* pkgname = packageName.c_str();
1639 const char* code_path_string = codePaths.c_str();
1640
David Sehr6727c2d2016-05-17 16:06:22 -07001641 std::vector<fd_t> profile_fds;
1642 fd_t reference_profile_fd = -1;
1643 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1644
1645 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1646
1647 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1648
1649 const bool has_reference_profile = (reference_profile_fd != -1);
1650 const bool has_profiles = !profile_fds.empty();
1651
1652 if (!has_reference_profile && !has_profiles) {
1653 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001654 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001655 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001656 }
1657
David Sehr40e566d2016-06-02 10:42:12 -07001658 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 -07001659 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1660 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001661 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001662 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001663 }
David Sehr40e566d2016-06-02 10:42:12 -07001664 std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1665 std::vector<std::string> dex_locations;
1666 std::vector<fd_t> apk_fds;
1667 for (const std::string& code_full_path : code_full_paths) {
1668 const char* full_path = code_full_path.c_str();
1669 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1670 if (apk_fd == -1) {
1671 ALOGE("installd cannot open '%s'\n", full_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001672 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001673 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001674 }
David Sehr40e566d2016-06-02 10:42:12 -07001675 dex_locations.push_back(get_location_from_path(full_path));
1676 apk_fds.push_back(apk_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001677 }
1678
1679 pid_t pid = fork();
1680 if (pid == 0) {
1681 /* child -- drop privileges before continuing */
1682 drop_capabilities(uid);
David Sehr40e566d2016-06-02 10:42:12 -07001683 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1684 apk_fds, output_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001685 exit(68); /* only get here on exec failure */
1686 }
1687 /* parent */
David Sehr40e566d2016-06-02 10:42:12 -07001688 close_all_fds(apk_fds, "apk_fds");
David Sehr6727c2d2016-05-17 16:06:22 -07001689 close_all_fds(profile_fds, "profile_fds");
1690 if (close(reference_profile_fd) != 0) {
1691 PLOG(WARNING) << "Failed to close fd for reference profile";
1692 }
1693 int return_code = wait_child(pid);
1694 if (!WIFEXITED(return_code)) {
1695 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1696 << return_code;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001697 *_aidl_return = false;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001698 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001699 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001700 *_aidl_return = true;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001701 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001702}
1703
David Brazdilfc5934e2016-09-08 11:55:48 +01001704static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1705 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
Andreas Gampe89b008d2016-06-03 21:13:50 -07001706 if (EndsWith(oat_path, ".dex")) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001707 std::string new_path = oat_path;
1708 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1709 CHECK(EndsWith(new_path, new_ext.c_str()));
1710 return new_path;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001711 }
Andreas Gampe89b008d2016-06-03 21:13:50 -07001712
1713 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1714 // case (where the base name will have an extension for the B artifact).
1715 size_t odex_pos = oat_path.rfind(".odex");
1716 if (odex_pos != std::string::npos) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001717 std::string new_path = oat_path;
1718 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1719 CHECK_NE(new_path.find(new_ext), std::string::npos);
1720 return new_path;
Andreas Gampe89b008d2016-06-03 21:13:50 -07001721 }
1722
1723 // Don't know how to handle this.
1724 return "";
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001725}
1726
David Brazdilfc5934e2016-09-08 11:55:48 +01001727// Translate the given oat path to an art (app image) path. An empty string
1728// denotes an error.
1729static std::string create_image_filename(const std::string& oat_path) {
1730 return replace_file_extension(oat_path, ".art");
1731}
1732
1733// Translate the given oat path to a vdex path. An empty string denotes an error.
1734static std::string create_vdex_filename(const std::string& oat_path) {
1735 return replace_file_extension(oat_path, ".vdex");
1736}
1737
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001738static bool add_extension_to_file_name(char* file_name, const char* extension) {
1739 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1740 return false;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001741 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001742 strcat(file_name, extension);
1743 return true;
1744}
1745
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001746static int open_output_file(const char* file_name, bool recreate, int permissions) {
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001747 int flags = O_RDWR | O_CREAT;
1748 if (recreate) {
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001749 if (unlink(file_name) < 0) {
1750 if (errno != ENOENT) {
1751 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1752 }
1753 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001754 flags |= O_EXCL;
1755 }
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001756 return open(file_name, flags, permissions);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001757}
1758
1759static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1760 if (fchmod(fd,
1761 S_IRUSR|S_IWUSR|S_IRGRP |
1762 (is_public ? S_IROTH : 0)) < 0) {
1763 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1764 return false;
1765 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1766 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1767 return false;
1768 }
1769 return true;
1770}
1771
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001772static bool IsOutputDalvikCache(const char* oat_dir) {
1773 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1774 // into '!'. Play it safe by handling it both.
1775 // TODO: ensure we never get null.
1776 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1777 return oat_dir == nullptr || oat_dir[0] == '!';
1778}
1779
Calin Juravle6a1648e2016-02-01 12:12:16 +00001780static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
David Brazdilfc5934e2016-09-08 11:55:48 +01001781 const char* oat_dir, /*out*/ char* out_oat_path) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001782 // Early best-effort check whether we can fit the the path into our buffers.
1783 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1784 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1785 // extension to the cache path (5 bytes).
1786 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1787 ALOGE("apk_path too long '%s'\n", apk_path);
1788 return false;
1789 }
1790
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001791 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001792 if (validate_apk_path(oat_dir)) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001793 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001794 return false;
1795 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001796 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001797 return false;
1798 }
1799 } else {
David Brazdilfc5934e2016-09-08 11:55:48 +01001800 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001801 return false;
1802 }
1803 }
1804 return true;
1805}
1806
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001807// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001808binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001809 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001810 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001811 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1812
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001813 const char* pkgname = packageName.c_str();
1814 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001815 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001816}
1817
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001818// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1819// on destruction. It will also run the given cleanup (unless told not to) after closing.
1820//
1821// Usage example:
1822//
1823// Dex2oatFileWrapper<std::function<void ()>> file(open(...),
1824// [name]() {
1825// unlink(name.c_str());
1826// });
1827// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1828// wrapper if captured as a reference.
1829//
1830// if (file.get() == -1) {
1831// // Error opening...
1832// }
1833//
1834// ...
1835// if (error) {
1836// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1837// // and delete the file (after the fd is closed).
1838// return -1;
1839// }
1840//
1841// (Success case)
1842// file.SetCleanup(false);
1843// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1844// // (leaving the file around; after the fd is closed).
1845//
1846template <typename Cleanup>
1847class Dex2oatFileWrapper {
1848 public:
1849 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
1850 }
1851
1852 Dex2oatFileWrapper(int value, Cleanup cleanup)
1853 : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
1854
1855 ~Dex2oatFileWrapper() {
1856 reset(-1);
1857 }
1858
1859 int get() {
1860 return value_;
1861 }
1862
1863 void SetCleanup(bool cleanup) {
1864 do_cleanup_ = cleanup;
1865 }
1866
1867 void reset(int new_value) {
1868 if (value_ >= 0) {
1869 close(value_);
1870 }
1871 if (do_cleanup_ && cleanup_ != nullptr) {
1872 cleanup_();
1873 }
1874
1875 value_ = new_value;
1876 }
1877
1878 void reset(int new_value, Cleanup new_cleanup) {
1879 if (value_ >= 0) {
1880 close(value_);
1881 }
1882 if (do_cleanup_ && cleanup_ != nullptr) {
1883 cleanup_();
1884 }
1885
1886 value_ = new_value;
1887 cleanup_ = new_cleanup;
1888 }
1889
1890 private:
1891 int value_;
1892 Cleanup cleanup_;
1893 bool do_cleanup_;
1894};
1895
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001896// TODO: eventually move dexopt() implementation into dexopt.cpp
Calin Juravle60a794d2015-12-24 12:36:41 +02001897int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001898 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1899 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
Calin Juravledb0326a2016-02-23 19:06:45 +00001900 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
Todd Kennedy76e767c2015-09-25 07:47:47 -07001901 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1902 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1903 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001904 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1905
1906 CHECK(pkgname != nullptr);
1907 CHECK(pkgname[0] != 0);
1908
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001909 // Public apps should not be compiled with profile information ever. Same goes for the special
1910 // package '*' used for the system server.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001911 Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001912 if (!is_public && pkgname[0] != '*') {
1913 // Open reference profile in read only mode as dex2oat does not get write permissions.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001914 const std::string pkgname_str(pkgname);
1915 reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1916 [pkgname_str]() {
1917 clear_reference_profile(pkgname_str.c_str());
1918 });
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001919 // Note: it's OK to not find a profile here.
Calin Juravle60a794d2015-12-24 12:36:41 +02001920 }
Todd Kennedy76e767c2015-09-25 07:47:47 -07001921
Todd Kennedye296e002015-11-16 14:41:36 -08001922 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -07001923 LOG_FATAL("dexopt flags contains unknown fields\n");
1924 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001925
David Brazdilfc5934e2016-09-08 11:55:48 +01001926 char out_oat_path[PKG_PATH_MAX];
1927 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001928 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001929 }
1930
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001931 const char *input_file;
1932 char in_odex_path[PKG_PATH_MAX];
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001933 int dexopt_action = abs(dexopt_needed);
1934 bool is_odex_location = dexopt_needed < 0;
1935 switch (dexopt_action) {
1936 case DEX2OAT_FROM_SCRATCH:
1937 case DEX2OAT_FOR_BOOT_IMAGE:
1938 case DEX2OAT_FOR_FILTER:
1939 case DEX2OAT_FOR_RELOCATION:
Richard Uhlerc92fb622015-03-26 15:47:38 -07001940 input_file = apk_path;
1941 break;
1942
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001943 case PATCHOAT_FOR_RELOCATION:
1944 if (is_odex_location) {
1945 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1946 return -1;
1947 }
1948 input_file = in_odex_path;
1949 } else {
1950 input_file = out_oat_path;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001951 }
Richard Uhlerc92fb622015-03-26 15:47:38 -07001952 break;
1953
1954 default:
1955 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001956 return 72;
Alex Light7365a102014-07-21 12:23:48 -07001957 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001958
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001959 struct stat input_stat;
Alex Light7365a102014-07-21 12:23:48 -07001960 memset(&input_stat, 0, sizeof(input_stat));
1961 stat(input_file, &input_stat);
1962
David Brazdilfc5934e2016-09-08 11:55:48 +01001963 // Open the input file. If running dex2oat, `input_file` is the APK. If running
1964 // patchoat, it is the OAT file to be relocated.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001965 base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1966 if (input_fd.get() < 0) {
Alex Light7365a102014-07-21 12:23:48 -07001967 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001968 return -1;
1969 }
1970
David Brazdilfc5934e2016-09-08 11:55:48 +01001971 // Create the output OAT file.
1972 const std::string out_oat_path_str(out_oat_path);
1973 Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1974 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1975 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1976 if (out_oat_fd.get() < 0) {
1977 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001978 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001979 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001980 if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1981 return -1;
1982 }
1983
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001984 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1985 // unlink the old one.
1986 base::unique_fd in_vdex_fd;
1987 std::string in_vdex_path_str;
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001988 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001989 // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1990 in_vdex_path_str = create_vdex_filename(input_file);
1991 if (in_vdex_path_str.empty()) {
1992 ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1993 return -1;
1994 }
1995 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1996 if (in_vdex_fd.get() < 0) {
1997 ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
1998 in_vdex_path_str.c_str(), strerror(errno));
1999 return -1;
2000 }
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002001 } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
2002 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
2003 const char* path = nullptr;
2004 if (is_odex_location) {
2005 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
2006 path = in_odex_path;
2007 } else {
2008 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
2009 return -1;
2010 }
2011 } else {
2012 path = out_oat_path;
2013 }
2014 in_vdex_path_str = create_vdex_filename(path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002015 if (in_vdex_path_str.empty()) {
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002016 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002017 return -1;
2018 }
2019 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002020 }
2021
David Brazdilfc5934e2016-09-08 11:55:48 +01002022 // Infer the name of the output VDEX and create it.
2023 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
2024 if (out_vdex_path_str.empty()) {
2025 return -1;
2026 }
2027 Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
2028 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
2029 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
2030 if (out_vdex_fd.get() < 0) {
2031 ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
2032 return -1;
2033 }
2034 if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
2035 uid, out_vdex_path_str.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002036 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002037 }
2038
Andreas Gampee1c01352014-12-10 16:41:11 -08002039 // Create a swap file if necessary.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002040 base::unique_fd swap_fd;
Richard Uhlerc92fb622015-03-26 15:47:38 -07002041 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08002042 // Make sure there really is enough space.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002043 char swap_file_name[PKG_PATH_MAX];
David Brazdilfc5934e2016-09-08 11:55:48 +01002044 strcpy(swap_file_name, out_oat_path);
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08002045 if (add_extension_to_file_name(swap_file_name, ".swap")) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002046 swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08002047 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002048 if (swap_fd.get() < 0) {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002049 // Could not create swap file. Optimistically go on and hope that we can compile
2050 // without it.
2051 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08002052 } else {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002053 // Immediately unlink. We don't really want to hit flash.
Narayan Kamath5006f3a2016-04-07 10:42:41 +01002054 if (unlink(swap_file_name) < 0) {
2055 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
2056 }
Andreas Gampee1c01352014-12-10 16:41:11 -08002057 }
2058 }
Dave Allisond9370732014-01-30 14:19:23 -08002059
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08002060 // Avoid generating an app image for extract only since it will not contain any classes.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002061 Dex2oatFileWrapper<std::function<void ()>> image_fd;
David Brazdilfc5934e2016-09-08 11:55:48 +01002062 const std::string image_path = create_image_filename(out_oat_path);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002063 if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002064 char app_image_format[kPropertyValueMax];
2065 bool have_app_image_format =
2066 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
2067 // Use app images only if it is enabled (by a set image format) and we are compiling
2068 // profile-guided (so the app image doesn't conservatively contain all classes).
2069 if (profile_guided && have_app_image_format) {
2070 // Recreate is true since we do not want to modify a mapped image. If the app is
2071 // already running and we modify the image file, it can cause crashes (b/27493510).
Andreas Gampe89b008d2016-06-03 21:13:50 -07002072 image_fd.reset(open_output_file(image_path.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002073 true /*recreate*/,
2074 0600 /*permissions*/),
Andreas Gampe89b008d2016-06-03 21:13:50 -07002075 [image_path]() { unlink(image_path.c_str()); }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002076 );
2077 if (image_fd.get() < 0) {
2078 // Could not create application image file. Go on since we can compile without
2079 // it.
2080 LOG(ERROR) << "installd could not create '"
2081 << image_path
2082 << "' for image file during dexopt";
2083 } else if (!set_permissions_and_ownership(image_fd.get(),
2084 is_public,
2085 uid,
Andreas Gampe89b008d2016-06-03 21:13:50 -07002086 image_path.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002087 image_fd.reset(-1);
2088 }
2089 }
2090 // If we have a valid image file path but no image fd, explicitly erase the image file.
2091 if (image_fd.get() < 0) {
Andreas Gampe89b008d2016-06-03 21:13:50 -07002092 if (unlink(image_path.c_str()) < 0) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002093 if (errno != ENOENT) {
2094 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
2095 }
2096 }
2097 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07002098 }
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08002099
Alex Light7365a102014-07-21 12:23:48 -07002100 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002101
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002102 pid_t pid = fork();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002103 if (pid == 0) {
2104 /* child -- drop privileges before continuing */
Calin Juravle6a1648e2016-02-01 12:12:16 +00002105 drop_capabilities(uid);
2106
Andreas Gampe13f14192015-09-21 13:21:30 -07002107 SetDex2OatAndPatchOatScheduling(boot_complete);
David Brazdilfc5934e2016-09-08 11:55:48 +01002108 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
2109 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002110 _exit(67);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002111 }
2112
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002113 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002114 run_patchoat(input_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002115 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002116 out_oat_fd.get(),
2117 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002118 input_file,
David Brazdilfc5934e2016-09-08 11:55:48 +01002119 in_vdex_path_str.c_str(),
2120 out_oat_path,
2121 out_vdex_path_str.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002122 pkgname,
2123 instruction_set);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002124 } else {
David Brazdilaaa1d4e2016-02-05 15:42:01 +00002125 // Pass dex2oat the relative path to the input file.
David Sehr40e566d2016-06-02 10:42:12 -07002126 const char *input_file_name = get_location_from_path(input_file);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002127 run_dex2oat(input_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002128 out_oat_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002129 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002130 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002131 image_fd.get(),
2132 input_file_name,
David Brazdilfc5934e2016-09-08 11:55:48 +01002133 out_oat_path,
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002134 swap_fd.get(),
2135 instruction_set,
2136 compiler_filter,
2137 vm_safe_mode,
2138 debuggable,
2139 boot_complete,
2140 reference_profile_fd.get(),
2141 shared_libraries);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002142 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002143 _exit(68); /* only get here on exec failure */
Mike Lockwood94afecf2012-10-24 10:45:23 -07002144 } else {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002145 int res = wait_child(pid);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002146 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07002147 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002148 } else {
Alex Light7365a102014-07-21 12:23:48 -07002149 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002150 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002151 }
2152 }
2153
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002154 struct utimbuf ut;
Alex Light7365a102014-07-21 12:23:48 -07002155 ut.actime = input_stat.st_atime;
2156 ut.modtime = input_stat.st_mtime;
David Brazdilfc5934e2016-09-08 11:55:48 +01002157 utime(out_oat_path, &ut);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002158
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002159 // We've been successful, don't delete output.
David Brazdilfc5934e2016-09-08 11:55:48 +01002160 out_oat_fd.SetCleanup(false);
2161 out_vdex_fd.SetCleanup(false);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002162 image_fd.SetCleanup(false);
2163 reference_profile_fd.SetCleanup(false);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002164
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002165 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002166}
2167
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002168binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2169 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2170 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2171 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
2172 const std::unique_ptr<std::string>& sharedLibraries) {
2173 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002174 CHECK_ARGUMENT_UUID(uuid);
2175 if (packageName && *packageName != "*") {
2176 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2177 }
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002178
2179 const char* apk_path = apkPath.c_str();
2180 const char* pkgname = packageName ? packageName->c_str() : "*";
2181 const char* instruction_set = instructionSet.c_str();
2182 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2183 const char* compiler_filter = compilerFilter.c_str();
2184 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
2185 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
2186
2187 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
2188 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002189 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002190}
2191
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002192binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2193 ENFORCE_UID(AID_SYSTEM);
2194 const char* instruction_set = instructionSet.c_str();
2195
2196 char boot_marker_path[PKG_PATH_MAX];
2197 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002198 "%s/%s/%s/.booting",
2199 android_data_dir.path,
2200 DALVIK_CACHE,
2201 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002202
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002203 ALOGV("mark_boot_complete : %s", boot_marker_path);
2204 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002205 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002206 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002207 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002208}
2209
Mike Lockwood94afecf2012-10-24 10:45:23 -07002210void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
2211 struct stat* statbuf)
2212{
2213 while (path[basepos] != 0) {
2214 if (path[basepos] == '/') {
2215 path[basepos] = 0;
2216 if (lstat(path, statbuf) < 0) {
2217 ALOGV("Making directory: %s\n", path);
2218 if (mkdir(path, mode) == 0) {
2219 chown(path, uid, gid);
2220 } else {
2221 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
2222 }
2223 }
2224 path[basepos] = '/';
2225 basepos++;
2226 }
2227 basepos++;
2228 }
2229}
2230
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002231binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2232 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2233 const std::string& nativeLibPath32, int32_t userId) {
2234 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002235 CHECK_ARGUMENT_UUID(uuid);
2236 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2237
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002238 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2239 const char* pkgname = packageName.c_str();
2240 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002241 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002242 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002243
Jeff Sharkey423e7462016-12-09 18:18:43 -07002244 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2245 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002246
2247 const char* pkgdir = _pkgdir.c_str();
2248 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002249
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002250 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002251 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002252 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002253
2254 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002255 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002256 }
2257
2258 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002259 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002260 goto out;
2261 }
2262
2263 if (lstat(libsymlink, &libStat) < 0) {
2264 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002265 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002266 goto out;
2267 }
2268 } else {
2269 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002270 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002271 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002272 goto out;
2273 }
2274 } else if (S_ISLNK(libStat.st_mode)) {
2275 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002276 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002277 goto out;
2278 }
2279 }
2280 }
2281
2282 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002283 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002284 goto out;
2285 }
2286
2287out:
2288 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002289 auto msg = "Failed to cleanup chmod " + _pkgdir;
2290 if (res.isOk()) {
2291 res = error(msg);
2292 } else {
2293 PLOG(ERROR) << msg;
2294 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002295 }
2296
2297 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002298 auto msg = "Failed to cleanup chown " + _pkgdir;
2299 if (res.isOk()) {
2300 res = error(msg);
2301 } else {
2302 PLOG(ERROR) << msg;
2303 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002304 }
2305
Jeff Sharkey423e7462016-12-09 18:18:43 -07002306 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002307}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002308
2309static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2310{
2311 static const char *IDMAP_BIN = "/system/bin/idmap";
2312 static const size_t MAX_INT_LEN = 32;
2313 char idmap_str[MAX_INT_LEN];
2314
2315 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
2316
2317 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
2318 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
2319}
2320
2321// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2322// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2323static int flatten_path(const char *prefix, const char *suffix,
2324 const char *overlay_path, char *idmap_path, size_t N)
2325{
2326 if (overlay_path == NULL || idmap_path == NULL) {
2327 return -1;
2328 }
2329 const size_t len_overlay_path = strlen(overlay_path);
2330 // will access overlay_path + 1 further below; requires absolute path
2331 if (len_overlay_path < 2 || *overlay_path != '/') {
2332 return -1;
2333 }
2334 const size_t len_idmap_root = strlen(prefix);
2335 const size_t len_suffix = strlen(suffix);
2336 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2337 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2338 // additions below would cause overflow
2339 return -1;
2340 }
2341 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2342 return -1;
2343 }
2344 memset(idmap_path, 0, N);
2345 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2346 char *ch = idmap_path + len_idmap_root;
2347 while (*ch != '\0') {
2348 if (*ch == '/') {
2349 *ch = '@';
2350 }
2351 ++ch;
2352 }
2353 return 0;
2354}
2355
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002356binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2357 const std::string& overlayApkPath, int32_t uid) {
2358 ENFORCE_UID(AID_SYSTEM);
2359 const char* target_apk = targetApkPath.c_str();
2360 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002361 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2362
2363 int idmap_fd = -1;
2364 char idmap_path[PATH_MAX];
2365
2366 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2367 idmap_path, sizeof(idmap_path)) == -1) {
2368 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2369 goto fail;
2370 }
2371
2372 unlink(idmap_path);
2373 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2374 if (idmap_fd < 0) {
2375 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2376 goto fail;
2377 }
2378 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2379 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2380 goto fail;
2381 }
2382 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2383 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2384 goto fail;
2385 }
2386
2387 pid_t pid;
2388 pid = fork();
2389 if (pid == 0) {
2390 /* child -- drop privileges before continuing */
2391 if (setgid(uid) != 0) {
2392 ALOGE("setgid(%d) failed during idmap\n", uid);
2393 exit(1);
2394 }
2395 if (setuid(uid) != 0) {
2396 ALOGE("setuid(%d) failed during idmap\n", uid);
2397 exit(1);
2398 }
2399 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2400 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2401 exit(1);
2402 }
2403
2404 run_idmap(target_apk, overlay_apk, idmap_fd);
2405 exit(1); /* only if exec call to idmap failed */
2406 } else {
2407 int status = wait_child(pid);
2408 if (status != 0) {
2409 ALOGE("idmap failed, status=0x%04x\n", status);
2410 goto fail;
2411 }
2412 }
2413
2414 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002415 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002416fail:
2417 if (idmap_fd >= 0) {
2418 close(idmap_fd);
2419 unlink(idmap_path);
2420 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002421 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002422}
Robert Craige9887e42014-02-20 10:25:56 -05002423
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002424binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2425 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2426 const std::string& seInfo) {
2427 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002428 CHECK_ARGUMENT_UUID(uuid);
2429 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2430
2431 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002432
Robert Craigda30dc72014-03-27 10:21:12 -04002433 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002434 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002435 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2436 const char* pkgName = packageName.c_str();
2437 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002438
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002439 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002440 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002441 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002442 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002443 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002444 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002445 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002446 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002447 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002448 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002449 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002450 }
Robert Craige9887e42014-02-20 10:25:56 -05002451 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002452 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002453}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002454
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002455binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2456 const std::string& instructionSet) {
2457 ENFORCE_UID(AID_SYSTEM);
2458 const char* oat_dir = oatDir.c_str();
2459 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002460 char oat_instr_dir[PKG_PATH_MAX];
2461
2462 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002463 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002464 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002465 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002466 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002467 }
2468 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002469 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002470 }
2471 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002472 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002473 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002474 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002475 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002476}
2477
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002478binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2479 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002480 if (validate_apk_path(packageDir.c_str())) {
2481 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002482 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002483 if (delete_dir_contents_and_dir(packageDir) != 0) {
2484 return error("Failed to delete " + packageDir);
2485 }
2486 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002487}
2488
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002489binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2490 const std::string& fromBase, const std::string& toBase) {
2491 ENFORCE_UID(AID_SYSTEM);
2492 const char* relative_path = relativePath.c_str();
2493 const char* from_base = fromBase.c_str();
2494 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002495 char from_path[PKG_PATH_MAX];
2496 char to_path[PKG_PATH_MAX];
2497 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2498 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2499
2500 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002501 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002502 }
2503
2504 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002505 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002506 }
2507
Jeff Sharkey423e7462016-12-09 18:18:43 -07002508 if (link(from_path, to_path) < 0) {
2509 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002510 }
2511
Jeff Sharkey423e7462016-12-09 18:18:43 -07002512 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002513}
2514
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002515// Helper for move_ab, so that we can have common failure-case cleanup.
2516static bool unlink_and_rename(const char* from, const char* to) {
2517 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2518 // return a failure.
2519 struct stat s;
2520 if (stat(to, &s) == 0) {
2521 if (!S_ISREG(s.st_mode)) {
2522 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2523 return false;
2524 }
2525 if (unlink(to) != 0) {
2526 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2527 return false;
2528 }
2529 } else {
2530 // This may be a permission problem. We could investigate the error code, but we'll just
2531 // let the rename failure do the work for us.
2532 }
2533
2534 // Try to rename "to" to "from."
2535 if (rename(from, to) != 0) {
2536 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2537 return false;
2538 }
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002539 return true;
2540}
2541
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002542// Move/rename a B artifact (from) to an A artifact (to).
2543static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2544 // Check whether B exists.
2545 {
2546 struct stat s;
2547 if (stat(b_path.c_str(), &s) != 0) {
2548 // Silently ignore for now. The service calling this isn't smart enough to understand
2549 // lack of artifacts at the moment.
2550 return false;
2551 }
2552 if (!S_ISREG(s.st_mode)) {
2553 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2554 // Try to unlink, but swallow errors.
2555 unlink(b_path.c_str());
2556 return false;
2557 }
2558 }
2559
2560 // Rename B to A.
2561 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2562 // Delete the b_path so we don't try again (or fail earlier).
2563 if (unlink(b_path.c_str()) != 0) {
2564 PLOG(ERROR) << "Could not unlink " << b_path;
2565 }
2566
2567 return false;
2568 }
2569
2570 return true;
2571}
2572
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002573binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2574 const std::string& instructionSet, const std::string& outputPath) {
2575 ENFORCE_UID(AID_SYSTEM);
2576 const char* apk_path = apkPath.c_str();
2577 const char* instruction_set = instructionSet.c_str();
2578 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07002579
2580 // Get the current slot suffix. No suffix, no A/B.
2581 std::string slot_suffix;
2582 {
2583 char buf[kPropertyValueMax];
2584 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002585 return error();
Andreas Gamped089ca12016-06-27 14:25:30 -07002586 }
2587 slot_suffix = buf;
2588
Andreas Gampefd12eda2016-07-12 09:47:17 -07002589 if (!ValidateTargetSlotSuffix(slot_suffix)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002590 return error("Target slot suffix not legal: " + slot_suffix);
Andreas Gamped089ca12016-06-27 14:25:30 -07002591 }
2592 }
2593
2594 // Validate other inputs.
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002595 if (validate_apk_path(apk_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002596 return error("Invalid apkPath: " + apkPath);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002597 }
2598 if (validate_apk_path(oat_dir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002599 return error("Invalid outputPath: " + outputPath);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002600 }
2601
2602 char a_path[PKG_PATH_MAX];
2603 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002604 return error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002605 }
David Brazdilfc5934e2016-09-08 11:55:48 +01002606 const std::string a_vdex_path = create_vdex_filename(a_path);
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002607 const std::string a_image_path = create_image_filename(a_path);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002608
Andreas Gamped089ca12016-06-27 14:25:30 -07002609 // B path = A path + slot suffix.
2610 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002611 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 -07002612 const std::string b_image_path = StringPrintf("%s.%s",
2613 a_image_path.c_str(),
2614 slot_suffix.c_str());
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002615
David Brazdilfc5934e2016-09-08 11:55:48 +01002616 bool success = true;
2617 if (move_ab_path(b_path, a_path)) {
2618 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2619 // Note: we can live without an app image. As such, ignore failure to move the image file.
2620 // If we decide to require the app image, or the app image being moved correctly,
2621 // then change accordingly.
2622 constexpr bool kIgnoreAppImageFailure = true;
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002623
David Brazdilfc5934e2016-09-08 11:55:48 +01002624 if (!a_image_path.empty()) {
2625 if (!move_ab_path(b_image_path, a_image_path)) {
David Brazdilc338c7f2016-09-12 16:26:40 +01002626 unlink(a_image_path.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002627 if (!kIgnoreAppImageFailure) {
2628 success = false;
2629 }
2630 }
2631 }
2632 } else {
2633 // Cleanup: delete B image, ignore errors.
2634 unlink(b_image_path.c_str());
2635 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002636 }
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002637 } else {
2638 // Cleanup: delete B image, ignore errors.
David Brazdilfc5934e2016-09-08 11:55:48 +01002639 unlink(b_vdex_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002640 unlink(b_image_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002641 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002642 }
2643
Jeff Sharkey423e7462016-12-09 18:18:43 -07002644 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002645}
2646
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002647binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2648 const std::string& instructionSet, const std::string& outputPath) {
2649 ENFORCE_UID(AID_SYSTEM);
2650 const char* apk_path = apkPath.c_str();
2651 const char* instruction_set = instructionSet.c_str();
2652 const char* oat_dir = outputPath.c_str();
2653
Andreas Gampeb31206b2016-09-09 17:07:04 -07002654 // Delete the oat/odex file.
2655 char out_path[PKG_PATH_MAX];
2656 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002657 return error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07002658 }
2659
2660 // In case of a permission failure report the issue. Otherwise just print a warning.
2661 auto unlink_and_check = [](const char* path) -> bool {
2662 int result = unlink(path);
2663 if (result != 0) {
2664 if (errno == EACCES || errno == EPERM) {
2665 PLOG(ERROR) << "Could not unlink " << path;
2666 return false;
2667 }
2668 PLOG(WARNING) << "Could not unlink " << path;
2669 }
2670 return true;
2671 };
2672
2673 // Delete the oat/odex file.
2674 bool return_value_oat = unlink_and_check(out_path);
2675
2676 // Derive and delete the app image.
2677 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2678
2679 // Report success.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002680 bool success = return_value_oat && return_value_art;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002681 return success ? ok() : error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07002682}
2683
Andreas Gampe02d0de52015-11-11 20:43:16 -08002684} // namespace installd
2685} // namespace android