blob: 5d01368b2ec91e3d0469b997d7b2e1ba7c9a448d [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
94binder::Status checkPermission(const char* permission) {
95 pid_t pid;
96 uid_t uid;
97
98 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
99 reinterpret_cast<int32_t*>(&uid))) {
100 return binder::Status::ok();
101 } else {
102 auto err = StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission);
103 return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
104 }
105}
106
107binder::Status checkUid(uid_t expectedUid) {
108 uid_t uid = IPCThreadState::self()->getCallingUid();
109 if (uid == expectedUid || uid == AID_ROOT) {
110 return binder::Status::ok();
111 } else {
112 auto err = StringPrintf("UID %d is not expected UID %d", uid, expectedUid);
113 return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
114 }
115}
116
117#define ENFORCE_UID(uid) { \
118 binder::Status status = checkUid((uid)); \
119 if (!status.isOk()) { \
120 return status; \
121 } \
122}
123
124} // namespace
125
126status_t InstalldNativeService::start() {
127 IPCThreadState::self()->disableBackgroundScheduling(true);
128 status_t ret = BinderService<InstalldNativeService>::publish();
129 if (ret != android::OK) {
130 return ret;
131 }
132 sp<ProcessState> ps(ProcessState::self());
133 ps->startThreadPool();
134 ps->giveThreadPoolName();
135 return android::OK;
136}
137
138status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
139 const binder::Status dump_permission = checkPermission(kDump);
140 if (!dump_permission.isOk()) {
141 const String8 msg(dump_permission.toString8());
142 write(fd, msg.string(), msg.size());
143 return PERMISSION_DENIED;
144 }
145
146 std::string msg = "installd is happy\n";
147 write(fd, msg.c_str(), strlen(msg.c_str()));
148 return NO_ERROR;
149}
150
Calin Juravle6a1648e2016-02-01 12:12:16 +0000151static bool property_get_bool(const char* property_name, bool default_value = false) {
152 char tmp_property_value[kPropertyValueMax];
153 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
154 if (!have_property) {
155 return default_value;
156 }
157 return strcmp(tmp_property_value, "true") == 0;
158}
159
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100160// Keep profile paths in sync with ActivityThread.
161constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
162static std::string create_primary_profile(const std::string& profile_dir) {
163 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
164}
165
Jeff Sharkey7db60412016-09-20 18:21:42 -0600166/**
167 * Perform restorecon of the given path, but only perform recursive restorecon
168 * if the label of that top-level file actually changed. This can save us
169 * significant time by avoiding no-op traversals of large filesystem trees.
170 */
Jeff Sharkey0274c972016-12-06 09:32:04 -0700171static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600172 int res = 0;
173 char* before = nullptr;
174 char* after = nullptr;
175
176 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
177 // libselinux. Not needed here.
178
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600179 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600180 PLOG(ERROR) << "Failed before getfilecon for " << path;
181 goto fail;
182 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700183 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600184 PLOG(ERROR) << "Failed top-level restorecon for " << path;
185 goto fail;
186 }
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600187 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600188 PLOG(ERROR) << "Failed after getfilecon for " << path;
189 goto fail;
190 }
191
192 // If the initial top-level restorecon above changed the label, then go
193 // back and restorecon everything recursively
194 if (strcmp(before, after)) {
195 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
196 << "; running recursive restorecon";
Jeff Sharkey0274c972016-12-06 09:32:04 -0700197 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600198 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
199 PLOG(ERROR) << "Failed recursive restorecon for " << path;
200 goto fail;
201 }
202 }
203
204 goto done;
205fail:
206 res = -1;
207done:
208 free(before);
209 free(after);
210 return res;
211}
212
Jeff Sharkey0274c972016-12-06 09:32:04 -0700213static int restorecon_app_data_lazy(const std::string& parent, const char* name,
214 const std::string& seInfo, uid_t uid) {
215 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600216}
217
Jeff Sharkey7db60412016-09-20 18:21:42 -0600218static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600219 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
220 PLOG(ERROR) << "Failed to prepare " << path;
221 return -1;
222 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600223 return 0;
224}
225
226static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600227 uid_t uid) {
228 return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600229}
230
Jeff Sharkey0274c972016-12-06 09:32:04 -0700231binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
232 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
233 const std::string& seInfo, int32_t targetSdkVersion) {
234 ENFORCE_UID(AID_SYSTEM);
235
236 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
237 const char* pkgname = packageName.c_str();
238
239 uid_t uid = multiuser_get_uid(userId, appId);
240 mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700241 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700242 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600243 if (prepare_app_dir(path, target_mode, uid) ||
244 prepare_app_dir(path, "cache", 0771, uid) ||
245 prepare_app_dir(path, "code_cache", 0771, uid)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700246 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600247 }
248
249 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700250 if (restorecon_app_data_lazy(path, seInfo, uid) ||
251 restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
252 restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
253 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700254 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600255
256 // Remember inode numbers of cache directories so that we can clear
257 // contents while CE storage is locked
258 if (write_path_inode(path, "cache", kXattrInodeCache) ||
259 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700260 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700261 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700262 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700263 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700264 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600265 if (prepare_app_dir(path, target_mode, uid)) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700266 // TODO: include result once 25796509 is fixed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700267 return binder::Status::ok();
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700268 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000269
Jeff Sharkey7db60412016-09-20 18:21:42 -0600270 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700271 if (restorecon_app_data_lazy(path, seInfo, uid)) {
272 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600273 }
274
Calin Juravle6a1648e2016-02-01 12:12:16 +0000275 if (property_get_bool("dalvik.vm.usejitprofiles")) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700276 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000277 // read-write-execute only for the app user.
278 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
279 PLOG(ERROR) << "Failed to prepare " << profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700280 return binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000281 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100282 std::string profile_file = create_primary_profile(profile_path);
283 // read-write only for the app user.
284 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
285 PLOG(ERROR) << "Failed to prepare " << profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700286 return binder::Status::fromServiceSpecificError(-1);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100287 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000288 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
289 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
290 // profiles.
291 appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
292 if (fs_prepare_dir_strict(
293 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
294 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700295 return binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000296 }
297 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700298 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700299 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700300}
301
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700302binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
303 const std::string& packageName, int32_t userId, int32_t flags) {
304 ENFORCE_UID(AID_SYSTEM);
305 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
306 const char* pkgname = packageName.c_str();
307
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700308 // This method only exists to upgrade system apps that have requested
309 // forceDeviceEncrypted, so their default storage always lives in a
310 // consistent location. This only works on non-FBE devices, since we
311 // never want to risk exposing data on a device with real CE/DE storage.
312
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700313 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
314 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700315
316 // If neither directory is marked as default, assume CE is default
317 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
318 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
319 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
320 PLOG(ERROR) << "Failed to mark default storage " << ce_path;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700321 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700322 }
323 }
324
325 // Migrate default data location if needed
326 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
327 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
328
329 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
330 LOG(WARNING) << "Requested default storage " << target
331 << " is not active; migrating from " << source;
332 if (delete_dir_contents_and_dir(target) != 0) {
333 PLOG(ERROR) << "Failed to delete";
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700334 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700335 }
336 if (rename(source.c_str(), target.c_str()) != 0) {
337 PLOG(ERROR) << "Failed to rename";
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700338 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700339 }
340 }
341
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700342 return binder::Status::ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700343}
344
Calin Juravlecea31412016-03-29 15:36:34 +0100345static bool clear_profile(const std::string& profile) {
Roland Levillain64b59cc2016-04-05 16:41:12 +0100346 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
347 if (ufd.get() < 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100348 if (errno != ENOENT) {
349 PLOG(WARNING) << "Could not open profile " << profile;
350 return false;
351 } else {
352 // Nothing to clear. That's ok.
353 return true;
354 }
355 }
356
Roland Levillain64b59cc2016-04-05 16:41:12 +0100357 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100358 if (errno != EWOULDBLOCK) {
359 PLOG(WARNING) << "Error locking profile " << profile;
360 }
361 // This implies that the app owning this profile is running
362 // (and has acquired the lock).
363 //
364 // If we can't acquire the lock bail out since clearing is useless anyway
365 // (the app will write again to the profile).
366 //
367 // Note:
368 // This does not impact the this is not an issue for the profiling correctness.
369 // In case this is needed because of an app upgrade, profiles will still be
370 // eventually cleared by the app itself due to checksum mismatch.
371 // If this is needed because profman advised, then keeping the data around
372 // until the next run is again not an issue.
373 //
374 // If the app attempts to acquire a lock while we've held one here,
375 // it will simply skip the current write cycle.
376 return false;
377 }
378
Roland Levillain64b59cc2016-04-05 16:41:12 +0100379 bool truncated = ftruncate(ufd.get(), 0) == 0;
Calin Juravlecea31412016-03-29 15:36:34 +0100380 if (!truncated) {
381 PLOG(WARNING) << "Could not truncate " << profile;
382 }
Roland Levillain64b59cc2016-04-05 16:41:12 +0100383 if (flock(ufd.get(), LOCK_UN) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100384 PLOG(WARNING) << "Error unlocking profile " << profile;
385 }
386 return truncated;
387}
388
389static bool clear_reference_profile(const char* pkgname) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000390 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
391 std::string reference_profile = create_primary_profile(reference_profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100392 return clear_profile(reference_profile);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000393}
394
Calin Juravlecea31412016-03-29 15:36:34 +0100395static bool clear_current_profile(const char* pkgname, userid_t user) {
Calin Juravleedae6692016-03-23 13:55:31 +0000396 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
397 std::string profile = create_primary_profile(profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100398 return clear_profile(profile);
Calin Juravleedae6692016-03-23 13:55:31 +0000399}
400
Calin Juravlecea31412016-03-29 15:36:34 +0100401static bool clear_current_profiles(const char* pkgname) {
David Brazdild828d682016-03-08 12:50:20 +0000402 bool success = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000403 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
404 for (auto user : users) {
Calin Juravlecea31412016-03-29 15:36:34 +0100405 success &= clear_current_profile(pkgname, user);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000406 }
David Brazdild828d682016-03-08 12:50:20 +0000407 return success;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000408}
409
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700410binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
411 ENFORCE_UID(AID_SYSTEM);
412 const char* pkgname = packageName.c_str();
David Brazdild828d682016-03-08 12:50:20 +0000413 bool success = true;
Calin Juravlecea31412016-03-29 15:36:34 +0100414 success &= clear_reference_profile(pkgname);
415 success &= clear_current_profiles(pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700416 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000417}
418
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700419binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
420 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
421 ENFORCE_UID(AID_SYSTEM);
422 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
423 const char* pkgname = packageName.c_str();
424
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700425 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700426 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700427 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600428 if (flags & FLAG_CLEAR_CACHE_ONLY) {
429 path = read_path_inode(path, "cache", kXattrInodeCache);
430 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
431 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
432 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700433 if (access(path.c_str(), F_OK) == 0) {
434 res |= delete_dir_contents(path);
435 }
436 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700437 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600438 std::string suffix = "";
439 bool only_cache = false;
440 if (flags & FLAG_CLEAR_CACHE_ONLY) {
441 suffix = CACHE_DIR_POSTFIX;
442 only_cache = true;
443 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
444 suffix = CODE_CACHE_DIR_POSTFIX;
445 only_cache = true;
446 }
447
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700448 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700449 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700450 // TODO: include result once 25796509 is fixed
451 delete_dir_contents(path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700452 }
Calin Juravleedae6692016-03-23 13:55:31 +0000453 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700454 if (!clear_current_profile(pkgname, userId)) {
Calin Juravleedae6692016-03-23 13:55:31 +0000455 res |= -1;
456 }
457 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700458 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700459 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700460}
461
Calin Juravle7535e8e2016-03-29 16:05:40 +0100462static int destroy_app_reference_profile(const char *pkgname) {
463 return delete_dir_contents_and_dir(
464 create_data_ref_profile_package_path(pkgname),
465 /*ignore_if_missing*/ true);
466}
467
Calin Juravleedae6692016-03-23 13:55:31 +0000468static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100469 return delete_dir_contents_and_dir(
470 create_data_user_profile_package_path(userid, pkgname),
471 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000472}
473
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700474binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
475 ENFORCE_UID(AID_SYSTEM);
476 const char* pkgname = packageName.c_str();
Calin Juravleedae6692016-03-23 13:55:31 +0000477 int result = 0;
478 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
479 for (auto user : users) {
480 result |= destroy_app_current_profiles(pkgname, user);
481 }
Calin Juravle7535e8e2016-03-29 16:05:40 +0100482 result |= destroy_app_reference_profile(pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700483 return result ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Calin Juravlecaa6b802016-03-22 14:15:52 +0000484}
485
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700486binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
487 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
488 ENFORCE_UID(AID_SYSTEM);
489 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
490 const char* pkgname = packageName.c_str();
491
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700492 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700493 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700494 res |= delete_dir_contents_and_dir(
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700495 create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700496 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700497 if (flags & FLAG_STORAGE_DE) {
Calin Juravlecaa6b802016-03-22 14:15:52 +0000498 res |= delete_dir_contents_and_dir(
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700499 create_data_user_de_package_path(uuid_, userId, pkgname));
500 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100501 // TODO(calin): If the package is still installed by other users it's probably
502 // beneficial to keep the reference profile around.
503 // Verify if it's ok to do that.
504 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700506 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700507}
508
Jeff Sharkey0274c972016-12-06 09:32:04 -0700509binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
510 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
511 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
512 int32_t targetSdkVersion) {
513
514 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
515 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
516 const char* package_name = packageName.c_str();
517 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700518
Jeff Sharkeye3637242015-04-08 20:56:42 -0700519 std::vector<userid_t> users = get_known_users(from_uuid);
520
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700521 // Copy app
522 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600523 auto from = create_data_app_package_path(from_uuid, data_app_name);
524 auto to = create_data_app_package_path(to_uuid, data_app_name);
525 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700526
527 char *argv[] = {
528 (char*) kCpPath,
529 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
530 (char*) "-p", /* preserve timestamps, ownership, and permissions */
531 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
532 (char*) "-P", /* Do not follow symlinks [default] */
533 (char*) "-d", /* don't dereference symlinks */
534 (char*) from.c_str(),
535 (char*) to_parent.c_str()
536 };
537
538 LOG(DEBUG) << "Copying " << from << " to " << to;
539 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
540
541 if (rc != 0) {
542 LOG(ERROR) << "Failed copying " << from << " to " << to
543 << ": status " << rc;
544 goto fail;
545 }
546
547 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
548 LOG(ERROR) << "Failed to restorecon " << to;
549 goto fail;
550 }
551 }
552
553 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700554 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700555
556 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600557 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
558 if (access(from_ce.c_str(), F_OK) != 0) {
559 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700560 continue;
561 }
562
Jeff Sharkey0274c972016-12-06 09:32:04 -0700563 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
564 seInfo, targetSdkVersion).isOk()) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600565 LOG(ERROR) << "Failed to create package target on " << to_uuid;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700566 goto fail;
567 }
568
569 char *argv[] = {
570 (char*) kCpPath,
571 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
572 (char*) "-p", /* preserve timestamps, ownership, and permissions */
573 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
574 (char*) "-P", /* Do not follow symlinks [default] */
575 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600576 nullptr,
577 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700578 };
579
Jeff Sharkey51c94492016-05-10 17:46:39 -0600580 {
581 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
582 auto to = create_data_user_de_path(to_uuid, user);
583 argv[6] = (char*) from.c_str();
584 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700585
Jeff Sharkey51c94492016-05-10 17:46:39 -0600586 LOG(DEBUG) << "Copying " << from << " to " << to;
587 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
588 if (rc != 0) {
589 LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
590 goto fail;
591 }
592 }
593 {
594 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
595 auto to = create_data_user_ce_path(to_uuid, user);
596 argv[6] = (char*) from.c_str();
597 argv[7] = (char*) to.c_str();
598
599 LOG(DEBUG) << "Copying " << from << " to " << to;
600 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
601 if (rc != 0) {
602 LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
603 goto fail;
604 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700605 }
606
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700607 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
608 appId, seInfo).isOk()) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700609 LOG(ERROR) << "Failed to restorecon";
610 goto fail;
611 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700612 }
613
Jeff Sharkey31f08982015-07-07 13:31:37 -0700614 // We let the framework scan the new location and persist that before
615 // deleting the data in the old location; this ordering ensures that
616 // we can recover from things like battery pulls.
Jeff Sharkey0274c972016-12-06 09:32:04 -0700617 return binder::Status::ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700618
619fail:
620 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700621 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600622 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700623 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
624 LOG(WARNING) << "Failed to rollback " << to;
625 }
626 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700627 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600628 {
629 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
630 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
631 LOG(WARNING) << "Failed to rollback " << to;
632 }
633 }
634 {
635 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
636 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
637 LOG(WARNING) << "Failed to rollback " << to;
638 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700639 }
640 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700641 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeye3637242015-04-08 20:56:42 -0700642}
643
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700644binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
645 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
646 ENFORCE_UID(AID_SYSTEM);
647 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700648 int res = 0;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600649 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700650 if (uuid_ == nullptr) {
651 res = ensure_config_user_dirs(userId);
652 }
653 }
654 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
655}
656
657binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
658 int32_t userId, int32_t flags) {
659 ENFORCE_UID(AID_SYSTEM);
660 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
661 int res = 0;
662 if (flags & FLAG_STORAGE_DE) {
663 res |= delete_dir_contents_and_dir(create_data_user_de_path(uuid_, userId), true);
664 if (uuid_ == nullptr) {
665 res |= delete_dir_contents_and_dir(create_data_misc_legacy_path(userId), true);
666 res |= delete_dir_contents_and_dir(create_data_user_profiles_path(userId), true);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700667 }
Robin Lee095c7632014-04-25 15:05:19 +0100668 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600669 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700670 res |= delete_dir_contents_and_dir(create_data_user_ce_path(uuid_, userId), true);
671 res |= delete_dir_contents_and_dir(create_data_media_path(uuid_, userId), true);
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600672 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700673 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Robin Lee095c7632014-04-25 15:05:19 +0100674}
675
Mike Lockwood94afecf2012-10-24 10:45:23 -0700676/* Try to ensure free_size bytes of storage are available.
677 * Returns 0 on success.
678 * This is rather simple-minded because doing a full LRU would
679 * be potentially memory-intensive, and without atime it would
680 * also require that apps constantly modify file metadata even
681 * when just reading from the cache, which is pretty awful.
682 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700683binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
684 int64_t freeStorageSize) {
685 ENFORCE_UID(AID_SYSTEM);
686 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700687 cache_t* cache;
688 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700689
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700690 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700691
692 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700693 if (avail < 0) {
694 return binder::Status::fromServiceSpecificError(-1);
695 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700696
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700697 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
698 if (avail >= freeStorageSize) {
699 return binder::Status::ok();
700 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700701
702 cache = start_cache_collection();
703
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700704 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600705 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700706 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
707 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600708 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700709 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700710 }
711
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700712 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700713 finish_cache_collection(cache);
714
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700715 if (data_disk_free(data_path) >= freeStorageSize) {
716 return binder::Status::ok();
717 } else {
718 return binder::Status::fromServiceSpecificError(-1);
719 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700720}
721
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700722binder::Status InstalldNativeService::rmdex(const std::string& codePath,
723 const std::string& instructionSet) {
724 ENFORCE_UID(AID_SYSTEM);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700725 char dex_path[PKG_PATH_MAX];
726
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700727 const char* path = codePath.c_str();
728 const char* instruction_set = instructionSet.c_str();
729
Jeff Sharkey770180a2014-09-08 17:14:26 -0700730 if (validate_apk_path(path) && validate_system_app_path(path)) {
731 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700732 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700733 }
734
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700735 if (!create_cache_path(dex_path, path, instruction_set)) {
736 return binder::Status::fromServiceSpecificError(-1);
737 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700738
739 ALOGV("unlink %s\n", dex_path);
740 if (unlink(dex_path) < 0) {
Jeff Sharkey770180a2014-09-08 17:14:26 -0700741 if (errno != ENOENT) {
742 ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
743 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700744 return binder::Status::fromServiceSpecificError(-1);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700745 } else {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700746 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700747 }
748}
749
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600750static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
751 int64_t *cachesize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700752 DIR *d;
753 int dfd;
754 struct dirent *de;
755 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700756
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600757 d = opendir(path.c_str());
758 if (d == nullptr) {
759 PLOG(WARNING) << "Failed to open " << path;
760 return;
761 }
762 dfd = dirfd(d);
763 while ((de = readdir(d))) {
764 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700765
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600766 int64_t statsize = 0;
767 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
768 statsize = stat_size(&s);
769 }
770
771 if (de->d_type == DT_DIR) {
772 int subfd;
773 int64_t dirsize = 0;
774 /* always skip "." and ".." */
775 if (name[0] == '.') {
776 if (name[1] == 0) continue;
777 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700778 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600779 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
780 if (subfd >= 0) {
781 dirsize = calculate_dir_size(subfd);
782 close(subfd);
783 }
784 // TODO: check xattrs!
785 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
786 *datasize += statsize;
787 *cachesize += dirsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700788 } else {
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600789 *datasize += dirsize + statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700790 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600791 } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
792 *codesize += statsize;
793 } else {
794 *datasize += statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700795 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600796 }
797 closedir(d);
798}
799
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700800binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
801 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
802 const std::string& codePath, std::vector<int64_t>* _aidl_return) {
803 ENFORCE_UID(AID_SYSTEM);
804 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
805 const char* pkgname = packageName.c_str();
806 const char* code_path = codePath.c_str();
807
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600808 DIR *d;
809 int dfd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700810 int64_t codesize = 0;
811 int64_t datasize = 0;
812 int64_t cachesize = 0;
813 int64_t asecsize = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600814
815 d = opendir(code_path);
816 if (d != nullptr) {
817 dfd = dirfd(d);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700818 codesize += calculate_dir_size(dfd);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700819 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700820 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600821
822 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700823 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
824 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600825 }
826 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700827 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
828 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600829 }
830
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700831 std::vector<int64_t> res;
832 res.push_back(codesize);
833 res.push_back(datasize);
834 res.push_back(cachesize);
835 res.push_back(asecsize);
836 *_aidl_return = res;
837 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700838}
839
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700840binder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700841 const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700842 ENFORCE_UID(AID_SYSTEM);
843 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
844 const char* pkgname = packageName.c_str();
845
846 int res = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600847 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700848 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
849 res = get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return));
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600850 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700851 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600852}
853
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700854static int split_count(const char *str)
855{
856 char *ctx;
857 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800858 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700859
860 strncpy(buf, str, sizeof(buf));
861 char *pBuf = buf;
862
863 while(strtok_r(pBuf, " ", &ctx) != NULL) {
864 count++;
865 pBuf = NULL;
866 }
867
868 return count;
869}
870
neo.chae14e084d2015-01-07 18:46:13 +0900871static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700872{
873 char *ctx;
874 int count = 0;
875 char *tok;
876 char *pBuf = buf;
877
878 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
879 argv[count++] = tok;
880 pBuf = NULL;
881 }
882
883 return count;
884}
885
David Brazdilfc5934e2016-09-08 11:55:48 +0100886static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
887 const char* input_oat_file_name, const char* input_vdex_file_name,
888 const char* output_oat_file_name, const char* output_vdex_file_name,
889 const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -0700890{
891 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +0100892 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -0700893
894 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
895 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
896 ALOGE("Instruction set %s longer than max length of %d",
897 instruction_set, MAX_INSTRUCTION_SET_LEN);
898 return;
899 }
900
901 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
902 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Alex Light7365a102014-07-21 12:23:48 -0700903 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
David Brazdilfc5934e2016-09-08 11:55:48 +0100904 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
905 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
906 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Alex Light7365a102014-07-21 12:23:48 -0700907 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
908 // The caller has already gotten all the locks we need.
909 const char* no_lock_arg = "--no-lock-output";
910 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
David Brazdilfc5934e2016-09-08 11:55:48 +0100911 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
912 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
913 ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
914 "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
915 PATCHOAT_BIN, instruction_set,
916 input_oat_fd, input_oat_file_name,
917 input_vdex_fd, input_vdex_file_name,
918 out_oat_fd, output_oat_file_name,
919 out_vdex_fd, output_vdex_file_name);
Alex Light7365a102014-07-21 12:23:48 -0700920
921 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
David Brazdilfc5934e2016-09-08 11:55:48 +0100922 char* argv[9];
Alex Light7365a102014-07-21 12:23:48 -0700923 argv[0] = (char*) PATCHOAT_BIN;
924 argv[1] = (char*) patched_image_location_arg;
925 argv[2] = (char*) no_lock_arg;
926 argv[3] = instruction_set_arg;
David Brazdilfc5934e2016-09-08 11:55:48 +0100927 argv[4] = input_oat_fd_arg;
928 argv[5] = input_vdex_fd_arg;
929 argv[6] = output_oat_fd_arg;
930 argv[7] = output_vdex_fd_arg;
931 argv[8] = NULL;
Alex Light7365a102014-07-21 12:23:48 -0700932
933 execv(PATCHOAT_BIN, (char* const *)argv);
934 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
935}
936
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +0000937static 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 +0100938 const char* input_file_name, const char* output_file_name, int swap_fd,
939 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
940 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
Calin Juravle8fc73152014-08-19 18:48:50 +0100941 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
942
943 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
944 ALOGE("Instruction set %s longer than max length of %d",
945 instruction_set, MAX_INSTRUCTION_SET_LEN);
946 return;
947 }
948
Andreas Gampe02d0de52015-11-11 20:43:16 -0800949 char dex2oat_Xms_flag[kPropertyValueMax];
950 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700951
Andreas Gampe02d0de52015-11-11 20:43:16 -0800952 char dex2oat_Xmx_flag[kPropertyValueMax];
953 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700954
Andreas Gampe02d0de52015-11-11 20:43:16 -0800955 char dex2oat_threads_buf[kPropertyValueMax];
956 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -0700957 ? "dalvik.vm.dex2oat-threads"
958 : "dalvik.vm.boot-dex2oat-threads",
959 dex2oat_threads_buf,
960 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800961 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700962 if (have_dex2oat_threads_flag) {
963 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
964 }
965
Andreas Gampe02d0de52015-11-11 20:43:16 -0800966 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +0100967 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800968 char dex2oat_isa_features[kPropertyValueMax];
969 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +0100970 dex2oat_isa_features, NULL) > 0;
971
Andreas Gampe02d0de52015-11-11 20:43:16 -0800972 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -0800973 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800974 char dex2oat_isa_variant[kPropertyValueMax];
975 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -0800976 dex2oat_isa_variant, NULL) > 0;
977
neo.chae14e084d2015-01-07 18:46:13 +0900978 const char *dex2oat_norelocation = "-Xnorelocate";
979 bool have_dex2oat_relocation_skip_flag = false;
980
Andreas Gampe02d0de52015-11-11 20:43:16 -0800981 char dex2oat_flags[kPropertyValueMax];
982 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700983 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -0800984 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
985
Brian Carlstrom538998f2014-07-30 14:37:11 -0700986 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -0800987 char vold_decrypt[kPropertyValueMax];
988 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700989 bool skip_compilation = (have_vold_decrypt &&
990 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
991 (strcmp(vold_decrypt, "1") == 0)));
992
Calin Juravle6a1648e2016-02-01 12:12:16 +0000993 bool generate_debug_info = property_get_bool("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700994
Mathieu Chartier416fa122016-02-03 13:48:16 -0800995 char app_image_format[kPropertyValueMax];
996 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
997 bool have_app_image_format =
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -0800998 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
Mathieu Chartier416fa122016-02-03 13:48:16 -0800999 if (have_app_image_format) {
1000 sprintf(image_format_arg, "--image-format=%s", app_image_format);
1001 }
1002
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001003 char dex2oat_large_app_threshold[kPropertyValueMax];
1004 bool have_dex2oat_large_app_threshold =
1005 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
1006 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
1007 if (have_dex2oat_large_app_threshold) {
1008 sprintf(dex2oat_large_app_threshold_arg,
1009 "--very-large-app-threshold=%s",
1010 dex2oat_large_app_threshold);
1011 }
1012
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001013 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001014
Brian Carlstrom53e07762014-06-27 14:15:19 -07001015 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001016
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001017 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +01001018
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001019 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
1020 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001021 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1022 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001023 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -07001024 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +01001025 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001026 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
1027 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
1028 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
1029 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
1030 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -08001031 bool have_dex2oat_swap_fd = false;
1032 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001033 bool have_dex2oat_image_fd = false;
1034 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001035
1036 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
1037 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001038 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
1039 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001040 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
1041 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +01001042 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -08001043 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +01001044 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -08001045 if (swap_fd >= 0) {
1046 have_dex2oat_swap_fd = true;
1047 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1048 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001049 if (image_fd >= 0) {
1050 have_dex2oat_image_fd = true;
1051 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1052 }
Calin Juravle57c69c32014-06-06 14:42:16 +01001053
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001054 if (have_dex2oat_Xms_flag) {
1055 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1056 }
1057 if (have_dex2oat_Xmx_flag) {
1058 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1059 }
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001060
1061 // Compute compiler filter.
1062
1063 bool have_dex2oat_compiler_filter_flag;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001064 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -07001065 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -07001066 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +09001067 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +01001068 } else if (vm_safe_mode) {
1069 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +01001070 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001071 } else if (compiler_filter != nullptr &&
1072 strlen(compiler_filter) + strlen("--compiler-filter=") <
1073 arraysize(dex2oat_compiler_filter_arg)) {
1074 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001075 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001076 } else {
1077 char dex2oat_compiler_filter_flag[kPropertyValueMax];
1078 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
1079 dex2oat_compiler_filter_flag, NULL) > 0;
1080 if (have_dex2oat_compiler_filter_flag) {
1081 sprintf(dex2oat_compiler_filter_arg,
1082 "--compiler-filter=%s",
1083 dex2oat_compiler_filter_flag);
1084 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001085 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001086
Andreas Gampe598c25e2015-03-03 09:15:06 -08001087 // Check whether all apps should be compiled debuggable.
1088 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001089 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -08001090 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -08001091 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -08001092 (prop_buf[0] == '1');
1093 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001094 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
1095 if (profile_fd != -1) {
1096 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001097 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001098
Calin Juravle6a1648e2016-02-01 12:12:16 +00001099
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001100 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +01001101
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001102 const char* argv[9 // program name, mandatory arguments and the final NULL
neo.chae14e084d2015-01-07 18:46:13 +09001103 + (have_dex2oat_isa_variant ? 1 : 0)
1104 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001105 + (have_dex2oat_Xms_flag ? 2 : 0)
1106 + (have_dex2oat_Xmx_flag ? 2 : 0)
1107 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001108 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001109 + (have_dex2oat_swap_fd ? 1 : 0)
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001110 + (have_dex2oat_image_fd ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001111 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +01001112 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -08001113 + (debuggable ? 1 : 0)
Mathieu Chartier416fa122016-02-03 13:48:16 -08001114 + (have_app_image_format ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +02001115 + dex2oat_flags_count
Jeff Haob63d91f2016-03-16 15:59:25 -07001116 + (profile_fd == -1 ? 0 : 1)
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001117 + (shared_libraries != nullptr ? 4 : 0)
1118 + (have_dex2oat_large_app_threshold ? 1 : 0)];
Calin Juravle4fdff462014-06-06 16:58:43 +01001119 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +09001120 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +01001121 argv[i++] = zip_fd_arg;
1122 argv[i++] = zip_location_arg;
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001123 argv[i++] = input_vdex_fd_arg;
1124 argv[i++] = output_vdex_fd_arg;
Calin Juravle4fdff462014-06-06 16:58:43 +01001125 argv[i++] = oat_fd_arg;
1126 argv[i++] = oat_location_arg;
1127 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -08001128 if (have_dex2oat_isa_variant) {
1129 argv[i++] = instruction_set_variant_arg;
1130 }
Calin Juravle8fc73152014-08-19 18:48:50 +01001131 if (have_dex2oat_isa_features) {
1132 argv[i++] = instruction_set_features_arg;
1133 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001134 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001135 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001136 argv[i++] = dex2oat_Xms_arg;
1137 }
1138 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001139 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001140 argv[i++] = dex2oat_Xmx_arg;
1141 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001142 if (have_dex2oat_compiler_filter_flag) {
1143 argv[i++] = dex2oat_compiler_filter_arg;
1144 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001145 if (have_dex2oat_threads_flag) {
1146 argv[i++] = dex2oat_threads_arg;
1147 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001148 if (have_dex2oat_swap_fd) {
1149 argv[i++] = dex2oat_swap_fd;
1150 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001151 if (have_dex2oat_image_fd) {
1152 argv[i++] = dex2oat_image_fd;
1153 }
David Srbecky528c8dd2015-05-28 16:55:50 +01001154 if (generate_debug_info) {
1155 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -07001156 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001157 if (debuggable) {
1158 argv[i++] = "--debuggable";
1159 }
Mathieu Chartier416fa122016-02-03 13:48:16 -08001160 if (have_app_image_format) {
1161 argv[i++] = image_format_arg;
1162 }
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001163 if (have_dex2oat_large_app_threshold) {
1164 argv[i++] = dex2oat_large_app_threshold_arg;
1165 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001166 if (dex2oat_flags_count) {
1167 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +01001168 }
neo.chae14e084d2015-01-07 18:46:13 +09001169 if (have_dex2oat_relocation_skip_flag) {
1170 argv[i++] = RUNTIME_ARG;
1171 argv[i++] = dex2oat_norelocation;
1172 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001173 if (profile_fd != -1) {
1174 argv[i++] = profile_arg;
Calin Juravle60a794d2015-12-24 12:36:41 +02001175 }
Jeff Haob63d91f2016-03-16 15:59:25 -07001176 if (shared_libraries != nullptr) {
1177 argv[i++] = RUNTIME_ARG;
1178 argv[i++] = "-classpath";
1179 argv[i++] = RUNTIME_ARG;
1180 argv[i++] = shared_libraries;
1181 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001182 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +01001183 argv[i] = NULL;
1184
neo.chae14e084d2015-01-07 18:46:13 +09001185 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001186 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001187}
1188
Andreas Gampee1c01352014-12-10 16:41:11 -08001189/*
Andreas Gampec968c012015-07-16 15:55:41 -07001190 * Whether dexopt should use a swap file when compiling an APK.
1191 *
1192 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1193 * itself, anyways).
1194 *
1195 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1196 *
1197 * Otherwise, return true if this is a low-mem device.
1198 *
1199 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -08001200 */
Andreas Gampec968c012015-07-16 15:55:41 -07001201static bool kAlwaysProvideSwapFile = false;
1202static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -08001203
1204static bool ShouldUseSwapFileForDexopt() {
1205 if (kAlwaysProvideSwapFile) {
1206 return true;
1207 }
1208
Andreas Gampec968c012015-07-16 15:55:41 -07001209 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -08001210 char dex2oat_prop_buf[kPropertyValueMax];
1211 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -07001212 if (strcmp(dex2oat_prop_buf, "true") == 0) {
1213 return true;
1214 } else {
1215 return false;
1216 }
1217 }
1218
1219 // Shortcut for default value. This is an implementation optimization for the process sketched
1220 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1221 // as low-mem is never returning false. The compiler will optimize this away if it can.
1222 if (kDefaultProvideSwapFile) {
1223 return true;
1224 }
1225
Calin Juravle6a1648e2016-02-01 12:12:16 +00001226 bool is_low_mem = property_get_bool("ro.config.low_ram");
Andreas Gampec968c012015-07-16 15:55:41 -07001227 if (is_low_mem) {
1228 return true;
1229 }
1230
1231 // Default value must be false here.
1232 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -08001233}
1234
Andreas Gampe94dd3d32015-09-14 16:33:11 -07001235static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
1236 if (set_to_bg) {
1237 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1238 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1239 exit(70);
1240 }
1241 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1242 ALOGE("setpriority failed: %s\n", strerror(errno));
1243 exit(71);
1244 }
1245 }
1246}
1247
Calin Juravle6a1648e2016-02-01 12:12:16 +00001248static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001249 for (size_t i = 0; i < fds.size(); i++) {
1250 if (close(fds[i]) != 0) {
1251 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
1252 }
1253 }
1254}
1255
Calin Juravle6a1648e2016-02-01 12:12:16 +00001256static fd_t open_profile_dir(const std::string& profile_dir) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001257 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
1258 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
1259 if (profile_dir_fd < 0) {
Narayan Kamath2e063af2016-05-02 09:47:49 +01001260 // In a multi-user environment, these directories can be created at
1261 // different points and it's possible we'll attempt to open a profile
1262 // dir before it exists.
1263 if (errno != ENOENT) {
1264 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
1265 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001266 }
1267 return profile_dir_fd;
1268}
1269
1270static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1271 fd_t profile_dir_fd = open_profile_dir(profile_dir);
1272 if (profile_dir_fd < 0) {
1273 return -1;
1274 }
1275
1276 fd_t profile_fd = -1;
1277 std::string profile_file = create_primary_profile(profile_dir);
1278
1279 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1280 if (profile_fd == -1) {
1281 // It's not an error if the profile file does not exist.
Calin Juravle60a794d2015-12-24 12:36:41 +02001282 if (errno != ENOENT) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001283 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1284 }
1285 }
1286 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1287 if (close(profile_dir_fd) != 0) {
1288 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1289 }
1290 return profile_fd;
1291}
1292
1293static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1294 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1295 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1296}
1297
1298static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1299 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1300 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1301 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1302 if (fd < 0) {
1303 return -1;
1304 }
1305 if (read_write) {
1306 // Fix the owner.
1307 if (fchown(fd, uid, uid) < 0) {
1308 close(fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001309 return -1;
1310 }
1311 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001312 return fd;
Calin Juravle60a794d2015-12-24 12:36:41 +02001313}
1314
Calin Juravle6a1648e2016-02-01 12:12:16 +00001315static void open_profile_files(uid_t uid, const char* pkgname,
1316 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1317 // Open the reference profile in read-write mode as profman might need to save the merge.
1318 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
Calin Juravle60a794d2015-12-24 12:36:41 +02001319 if (*reference_profile_fd < 0) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001320 // We can't access the reference profile file.
Calin Juravle60a794d2015-12-24 12:36:41 +02001321 return;
1322 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001323
1324 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1325 for (auto user : users) {
1326 fd_t profile_fd = open_primary_profile_file(user, pkgname);
1327 // Add to the lists only if both fds are valid.
1328 if (profile_fd >= 0) {
1329 profiles_fd->push_back(profile_fd);
1330 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001331 }
1332}
1333
Calin Juravle6a1648e2016-02-01 12:12:16 +00001334static void drop_capabilities(uid_t uid) {
1335 if (setgid(uid) != 0) {
1336 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1337 exit(64);
1338 }
1339 if (setuid(uid) != 0) {
1340 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1341 exit(65);
1342 }
1343 // drop capabilities
1344 struct __user_cap_header_struct capheader;
1345 struct __user_cap_data_struct capdata[2];
1346 memset(&capheader, 0, sizeof(capheader));
1347 memset(&capdata, 0, sizeof(capdata));
1348 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1349 if (capset(&capheader, &capdata[0]) < 0) {
1350 ALOGE("capset failed: %s\n", strerror(errno));
1351 exit(66);
1352 }
1353}
Calin Juravle60a794d2015-12-24 12:36:41 +02001354
Calin Juravle6a1648e2016-02-01 12:12:16 +00001355static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1356static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1357static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1358static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1359static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1360
David Sehr6727c2d2016-05-17 16:06:22 -07001361static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001362 static const size_t MAX_INT_LEN = 32;
1363 static const char* PROFMAN_BIN = "/system/bin/profman";
1364
1365 std::vector<std::string> profile_args(profiles_fd.size());
1366 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1367 for (size_t k = 0; k < profiles_fd.size(); k++) {
1368 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1369 profile_args[k].assign(profile_buf);
1370 }
1371 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1372 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1373
1374 // program name, reference profile fd, the final NULL and the profile fds
1375 const char* argv[3 + profiles_fd.size()];
1376 int i = 0;
1377 argv[i++] = PROFMAN_BIN;
1378 argv[i++] = reference_profile_arg;
1379 for (size_t k = 0; k < profile_args.size(); k++) {
1380 argv[i++] = profile_args[k].c_str();
1381 }
1382 // Do not add after dex2oat_flags, they should override others for debugging.
1383 argv[i] = NULL;
1384
1385 execv(PROFMAN_BIN, (char * const *)argv);
1386 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1387 exit(68); /* only get here on exec failure */
1388}
1389
1390// Decides if profile guided compilation is needed or not based on existing profiles.
1391// Returns true if there is enough information in the current profiles that worth
1392// a re-compilation of the package.
1393// If the return value is true all the current profiles would have been merged into
1394// the reference profiles accessible with open_reference_profile().
1395static bool analyse_profiles(uid_t uid, const char* pkgname) {
1396 std::vector<fd_t> profiles_fd;
1397 fd_t reference_profile_fd = -1;
1398 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1399 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1400 // Skip profile guided compilation because no profiles were found.
1401 // Or if the reference profile info couldn't be opened.
1402 close_all_fds(profiles_fd, "profiles_fd");
1403 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1404 PLOG(WARNING) << "Failed to close fd for reference profile";
1405 }
1406 return false;
1407 }
1408
David Sehr6727c2d2016-05-17 16:06:22 -07001409 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001410
1411 pid_t pid = fork();
1412 if (pid == 0) {
1413 /* child -- drop privileges before continuing */
1414 drop_capabilities(uid);
David Sehr6727c2d2016-05-17 16:06:22 -07001415 run_profman_merge(profiles_fd, reference_profile_fd);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001416 exit(68); /* only get here on exec failure */
1417 }
1418 /* parent */
1419 int return_code = wait_child(pid);
1420 bool need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001421 bool should_clear_current_profiles = false;
1422 bool should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001423 if (!WIFEXITED(return_code)) {
1424 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1425 } else {
1426 return_code = WEXITSTATUS(return_code);
1427 switch (return_code) {
1428 case PROFMAN_BIN_RETURN_CODE_COMPILE:
1429 need_to_compile = true;
Calin Juravlecea31412016-03-29 15:36:34 +01001430 should_clear_current_profiles = true;
1431 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001432 break;
1433 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1434 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001435 should_clear_current_profiles = false;
1436 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001437 break;
1438 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1439 LOG(WARNING) << "Bad profiles for package " << pkgname;
1440 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001441 should_clear_current_profiles = true;
1442 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001443 break;
1444 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
1445 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1446 // Temporary IO problem (e.g. locking). Ignore but log a warning.
1447 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1448 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001449 should_clear_current_profiles = false;
1450 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001451 break;
1452 default:
1453 // Unknown return code or error. Unlink profiles.
1454 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1455 << ": " << return_code;
1456 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001457 should_clear_current_profiles = true;
1458 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001459 break;
Calin Juravle60a794d2015-12-24 12:36:41 +02001460 }
1461 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001462 close_all_fds(profiles_fd, "profiles_fd");
1463 if (close(reference_profile_fd) != 0) {
1464 PLOG(WARNING) << "Failed to close fd for reference profile";
1465 }
Calin Juravlecea31412016-03-29 15:36:34 +01001466 if (should_clear_current_profiles) {
1467 clear_current_profiles(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001468 }
Calin Juravlecea31412016-03-29 15:36:34 +01001469 if (should_clear_reference_profile) {
1470 clear_reference_profile(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001471 }
1472 return need_to_compile;
Calin Juravle60a794d2015-12-24 12:36:41 +02001473}
1474
David Sehr6727c2d2016-05-17 16:06:22 -07001475static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1476 fd_t reference_profile_fd,
David Sehr40e566d2016-06-02 10:42:12 -07001477 const std::vector<std::string>& dex_locations,
1478 const std::vector<fd_t>& apk_fds,
David Sehr6727c2d2016-05-17 16:06:22 -07001479 fd_t output_fd) {
David Sehr40e566d2016-06-02 10:42:12 -07001480 std::vector<std::string> profman_args;
David Sehr6727c2d2016-05-17 16:06:22 -07001481 static const char* PROFMAN_BIN = "/system/bin/profman";
David Sehr40e566d2016-06-02 10:42:12 -07001482 profman_args.push_back(PROFMAN_BIN);
1483 profman_args.push_back("--dump-only");
1484 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1485 if (reference_profile_fd != -1) {
1486 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1487 reference_profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001488 }
1489 for (fd_t profile_fd : profile_fds) {
David Sehr40e566d2016-06-02 10:42:12 -07001490 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001491 }
David Sehr40e566d2016-06-02 10:42:12 -07001492 for (const std::string& dex_location : dex_locations) {
1493 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
David Sehr6727c2d2016-05-17 16:06:22 -07001494 }
David Sehr40e566d2016-06-02 10:42:12 -07001495 for (fd_t apk_fd : apk_fds) {
1496 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1497 }
1498 const char **argv = new const char*[profman_args.size() + 1];
1499 size_t i = 0;
1500 for (const std::string& profman_arg : profman_args) {
1501 argv[i++] = profman_arg.c_str();
David Sehr6727c2d2016-05-17 16:06:22 -07001502 }
1503 argv[i] = NULL;
David Sehr6727c2d2016-05-17 16:06:22 -07001504
1505 execv(PROFMAN_BIN, (char * const *)argv);
1506 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1507 exit(68); /* only get here on exec failure */
1508}
1509
David Sehr40e566d2016-06-02 10:42:12 -07001510static const char* get_location_from_path(const char* path) {
1511 static constexpr char kLocationSeparator = '/';
1512 const char *location = strrchr(path, kLocationSeparator);
1513 if (location == NULL) {
1514 return path;
1515 } else {
1516 // Skip the separator character.
1517 return location + 1;
1518 }
1519}
1520
David Sehr6727c2d2016-05-17 16:06:22 -07001521// Dumps the contents of a profile file, using pkgname's dex files for pretty
1522// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001523binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1524 const std::string& codePaths, bool* _aidl_return) {
1525 ENFORCE_UID(AID_SYSTEM);
1526
1527 const char* pkgname = packageName.c_str();
1528 const char* code_path_string = codePaths.c_str();
1529
David Sehr6727c2d2016-05-17 16:06:22 -07001530 std::vector<fd_t> profile_fds;
1531 fd_t reference_profile_fd = -1;
1532 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1533
1534 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1535
1536 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1537
1538 const bool has_reference_profile = (reference_profile_fd != -1);
1539 const bool has_profiles = !profile_fds.empty();
1540
1541 if (!has_reference_profile && !has_profiles) {
1542 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001543 *_aidl_return = false;
1544 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001545 }
1546
David Sehr40e566d2016-06-02 10:42:12 -07001547 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 -07001548 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1549 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001550 *_aidl_return = false;
1551 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001552 }
David Sehr40e566d2016-06-02 10:42:12 -07001553 std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1554 std::vector<std::string> dex_locations;
1555 std::vector<fd_t> apk_fds;
1556 for (const std::string& code_full_path : code_full_paths) {
1557 const char* full_path = code_full_path.c_str();
1558 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1559 if (apk_fd == -1) {
1560 ALOGE("installd cannot open '%s'\n", full_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001561 *_aidl_return = false;
1562 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001563 }
David Sehr40e566d2016-06-02 10:42:12 -07001564 dex_locations.push_back(get_location_from_path(full_path));
1565 apk_fds.push_back(apk_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001566 }
1567
1568 pid_t pid = fork();
1569 if (pid == 0) {
1570 /* child -- drop privileges before continuing */
1571 drop_capabilities(uid);
David Sehr40e566d2016-06-02 10:42:12 -07001572 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1573 apk_fds, output_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001574 exit(68); /* only get here on exec failure */
1575 }
1576 /* parent */
David Sehr40e566d2016-06-02 10:42:12 -07001577 close_all_fds(apk_fds, "apk_fds");
David Sehr6727c2d2016-05-17 16:06:22 -07001578 close_all_fds(profile_fds, "profile_fds");
1579 if (close(reference_profile_fd) != 0) {
1580 PLOG(WARNING) << "Failed to close fd for reference profile";
1581 }
1582 int return_code = wait_child(pid);
1583 if (!WIFEXITED(return_code)) {
1584 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1585 << return_code;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001586 *_aidl_return = false;
1587 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001588 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001589 *_aidl_return = true;
1590 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001591}
1592
David Brazdilfc5934e2016-09-08 11:55:48 +01001593static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1594 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
Andreas Gampe89b008d2016-06-03 21:13:50 -07001595 if (EndsWith(oat_path, ".dex")) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001596 std::string new_path = oat_path;
1597 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1598 CHECK(EndsWith(new_path, new_ext.c_str()));
1599 return new_path;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001600 }
Andreas Gampe89b008d2016-06-03 21:13:50 -07001601
1602 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1603 // case (where the base name will have an extension for the B artifact).
1604 size_t odex_pos = oat_path.rfind(".odex");
1605 if (odex_pos != std::string::npos) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001606 std::string new_path = oat_path;
1607 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1608 CHECK_NE(new_path.find(new_ext), std::string::npos);
1609 return new_path;
Andreas Gampe89b008d2016-06-03 21:13:50 -07001610 }
1611
1612 // Don't know how to handle this.
1613 return "";
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001614}
1615
David Brazdilfc5934e2016-09-08 11:55:48 +01001616// Translate the given oat path to an art (app image) path. An empty string
1617// denotes an error.
1618static std::string create_image_filename(const std::string& oat_path) {
1619 return replace_file_extension(oat_path, ".art");
1620}
1621
1622// Translate the given oat path to a vdex path. An empty string denotes an error.
1623static std::string create_vdex_filename(const std::string& oat_path) {
1624 return replace_file_extension(oat_path, ".vdex");
1625}
1626
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001627static bool add_extension_to_file_name(char* file_name, const char* extension) {
1628 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1629 return false;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001630 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001631 strcat(file_name, extension);
1632 return true;
1633}
1634
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001635static int open_output_file(const char* file_name, bool recreate, int permissions) {
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001636 int flags = O_RDWR | O_CREAT;
1637 if (recreate) {
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001638 if (unlink(file_name) < 0) {
1639 if (errno != ENOENT) {
1640 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1641 }
1642 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001643 flags |= O_EXCL;
1644 }
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001645 return open(file_name, flags, permissions);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001646}
1647
1648static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1649 if (fchmod(fd,
1650 S_IRUSR|S_IWUSR|S_IRGRP |
1651 (is_public ? S_IROTH : 0)) < 0) {
1652 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1653 return false;
1654 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1655 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1656 return false;
1657 }
1658 return true;
1659}
1660
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001661static bool IsOutputDalvikCache(const char* oat_dir) {
1662 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1663 // into '!'. Play it safe by handling it both.
1664 // TODO: ensure we never get null.
1665 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1666 return oat_dir == nullptr || oat_dir[0] == '!';
1667}
1668
Calin Juravle6a1648e2016-02-01 12:12:16 +00001669static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
David Brazdilfc5934e2016-09-08 11:55:48 +01001670 const char* oat_dir, /*out*/ char* out_oat_path) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001671 // Early best-effort check whether we can fit the the path into our buffers.
1672 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1673 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1674 // extension to the cache path (5 bytes).
1675 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1676 ALOGE("apk_path too long '%s'\n", apk_path);
1677 return false;
1678 }
1679
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001680 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001681 if (validate_apk_path(oat_dir)) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001682 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001683 return false;
1684 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001685 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001686 return false;
1687 }
1688 } else {
David Brazdilfc5934e2016-09-08 11:55:48 +01001689 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001690 return false;
1691 }
1692 }
1693 return true;
1694}
1695
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001696// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001697binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1698 bool* _aidl_return) {
1699 ENFORCE_UID(AID_SYSTEM);
1700 const char* pkgname = packageName.c_str();
1701 *_aidl_return = analyse_profiles(uid, pkgname);
1702 return binder::Status::ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001703}
1704
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001705// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1706// on destruction. It will also run the given cleanup (unless told not to) after closing.
1707//
1708// Usage example:
1709//
1710// Dex2oatFileWrapper<std::function<void ()>> file(open(...),
1711// [name]() {
1712// unlink(name.c_str());
1713// });
1714// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1715// wrapper if captured as a reference.
1716//
1717// if (file.get() == -1) {
1718// // Error opening...
1719// }
1720//
1721// ...
1722// if (error) {
1723// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1724// // and delete the file (after the fd is closed).
1725// return -1;
1726// }
1727//
1728// (Success case)
1729// file.SetCleanup(false);
1730// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1731// // (leaving the file around; after the fd is closed).
1732//
1733template <typename Cleanup>
1734class Dex2oatFileWrapper {
1735 public:
1736 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
1737 }
1738
1739 Dex2oatFileWrapper(int value, Cleanup cleanup)
1740 : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
1741
1742 ~Dex2oatFileWrapper() {
1743 reset(-1);
1744 }
1745
1746 int get() {
1747 return value_;
1748 }
1749
1750 void SetCleanup(bool cleanup) {
1751 do_cleanup_ = cleanup;
1752 }
1753
1754 void reset(int new_value) {
1755 if (value_ >= 0) {
1756 close(value_);
1757 }
1758 if (do_cleanup_ && cleanup_ != nullptr) {
1759 cleanup_();
1760 }
1761
1762 value_ = new_value;
1763 }
1764
1765 void reset(int new_value, Cleanup new_cleanup) {
1766 if (value_ >= 0) {
1767 close(value_);
1768 }
1769 if (do_cleanup_ && cleanup_ != nullptr) {
1770 cleanup_();
1771 }
1772
1773 value_ = new_value;
1774 cleanup_ = new_cleanup;
1775 }
1776
1777 private:
1778 int value_;
1779 Cleanup cleanup_;
1780 bool do_cleanup_;
1781};
1782
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001783// TODO: eventually move dexopt() implementation into dexopt.cpp
Calin Juravle60a794d2015-12-24 12:36:41 +02001784int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001785 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1786 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
Calin Juravledb0326a2016-02-23 19:06:45 +00001787 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
Todd Kennedy76e767c2015-09-25 07:47:47 -07001788 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1789 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1790 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001791 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1792
1793 CHECK(pkgname != nullptr);
1794 CHECK(pkgname[0] != 0);
1795
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001796 // Public apps should not be compiled with profile information ever. Same goes for the special
1797 // package '*' used for the system server.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001798 Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001799 if (!is_public && pkgname[0] != '*') {
1800 // Open reference profile in read only mode as dex2oat does not get write permissions.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001801 const std::string pkgname_str(pkgname);
1802 reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1803 [pkgname_str]() {
1804 clear_reference_profile(pkgname_str.c_str());
1805 });
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001806 // Note: it's OK to not find a profile here.
Calin Juravle60a794d2015-12-24 12:36:41 +02001807 }
Todd Kennedy76e767c2015-09-25 07:47:47 -07001808
Todd Kennedye296e002015-11-16 14:41:36 -08001809 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -07001810 LOG_FATAL("dexopt flags contains unknown fields\n");
1811 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001812
David Brazdilfc5934e2016-09-08 11:55:48 +01001813 char out_oat_path[PKG_PATH_MAX];
1814 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001815 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001816 }
1817
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001818 const char *input_file;
1819 char in_odex_path[PKG_PATH_MAX];
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001820 int dexopt_action = abs(dexopt_needed);
1821 bool is_odex_location = dexopt_needed < 0;
1822 switch (dexopt_action) {
1823 case DEX2OAT_FROM_SCRATCH:
1824 case DEX2OAT_FOR_BOOT_IMAGE:
1825 case DEX2OAT_FOR_FILTER:
1826 case DEX2OAT_FOR_RELOCATION:
Richard Uhlerc92fb622015-03-26 15:47:38 -07001827 input_file = apk_path;
1828 break;
1829
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001830 case PATCHOAT_FOR_RELOCATION:
1831 if (is_odex_location) {
1832 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1833 return -1;
1834 }
1835 input_file = in_odex_path;
1836 } else {
1837 input_file = out_oat_path;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001838 }
Richard Uhlerc92fb622015-03-26 15:47:38 -07001839 break;
1840
1841 default:
1842 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001843 return 72;
Alex Light7365a102014-07-21 12:23:48 -07001844 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001845
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001846 struct stat input_stat;
Alex Light7365a102014-07-21 12:23:48 -07001847 memset(&input_stat, 0, sizeof(input_stat));
1848 stat(input_file, &input_stat);
1849
David Brazdilfc5934e2016-09-08 11:55:48 +01001850 // Open the input file. If running dex2oat, `input_file` is the APK. If running
1851 // patchoat, it is the OAT file to be relocated.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001852 base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1853 if (input_fd.get() < 0) {
Alex Light7365a102014-07-21 12:23:48 -07001854 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001855 return -1;
1856 }
1857
David Brazdilfc5934e2016-09-08 11:55:48 +01001858 // Create the output OAT file.
1859 const std::string out_oat_path_str(out_oat_path);
1860 Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1861 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1862 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1863 if (out_oat_fd.get() < 0) {
1864 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001865 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001866 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001867 if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1868 return -1;
1869 }
1870
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001871 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1872 // unlink the old one.
1873 base::unique_fd in_vdex_fd;
1874 std::string in_vdex_path_str;
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001875 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001876 // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1877 in_vdex_path_str = create_vdex_filename(input_file);
1878 if (in_vdex_path_str.empty()) {
1879 ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1880 return -1;
1881 }
1882 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1883 if (in_vdex_fd.get() < 0) {
1884 ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
1885 in_vdex_path_str.c_str(), strerror(errno));
1886 return -1;
1887 }
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001888 } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
1889 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1890 const char* path = nullptr;
1891 if (is_odex_location) {
1892 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1893 path = in_odex_path;
1894 } else {
1895 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
1896 return -1;
1897 }
1898 } else {
1899 path = out_oat_path;
1900 }
1901 in_vdex_path_str = create_vdex_filename(path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001902 if (in_vdex_path_str.empty()) {
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001903 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001904 return -1;
1905 }
1906 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001907 }
1908
David Brazdilfc5934e2016-09-08 11:55:48 +01001909 // Infer the name of the output VDEX and create it.
1910 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
1911 if (out_vdex_path_str.empty()) {
1912 return -1;
1913 }
1914 Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
1915 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1916 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1917 if (out_vdex_fd.get() < 0) {
1918 ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
1919 return -1;
1920 }
1921 if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
1922 uid, out_vdex_path_str.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001923 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001924 }
1925
Andreas Gampee1c01352014-12-10 16:41:11 -08001926 // Create a swap file if necessary.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001927 base::unique_fd swap_fd;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001928 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001929 // Make sure there really is enough space.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001930 char swap_file_name[PKG_PATH_MAX];
David Brazdilfc5934e2016-09-08 11:55:48 +01001931 strcpy(swap_file_name, out_oat_path);
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001932 if (add_extension_to_file_name(swap_file_name, ".swap")) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001933 swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001934 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001935 if (swap_fd.get() < 0) {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001936 // Could not create swap file. Optimistically go on and hope that we can compile
1937 // without it.
1938 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08001939 } else {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001940 // Immediately unlink. We don't really want to hit flash.
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001941 if (unlink(swap_file_name) < 0) {
1942 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1943 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001944 }
1945 }
Dave Allisond9370732014-01-30 14:19:23 -08001946
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001947 // Avoid generating an app image for extract only since it will not contain any classes.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001948 Dex2oatFileWrapper<std::function<void ()>> image_fd;
David Brazdilfc5934e2016-09-08 11:55:48 +01001949 const std::string image_path = create_image_filename(out_oat_path);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001950 if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001951 char app_image_format[kPropertyValueMax];
1952 bool have_app_image_format =
1953 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1954 // Use app images only if it is enabled (by a set image format) and we are compiling
1955 // profile-guided (so the app image doesn't conservatively contain all classes).
1956 if (profile_guided && have_app_image_format) {
1957 // Recreate is true since we do not want to modify a mapped image. If the app is
1958 // already running and we modify the image file, it can cause crashes (b/27493510).
Andreas Gampe89b008d2016-06-03 21:13:50 -07001959 image_fd.reset(open_output_file(image_path.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001960 true /*recreate*/,
1961 0600 /*permissions*/),
Andreas Gampe89b008d2016-06-03 21:13:50 -07001962 [image_path]() { unlink(image_path.c_str()); }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001963 );
1964 if (image_fd.get() < 0) {
1965 // Could not create application image file. Go on since we can compile without
1966 // it.
1967 LOG(ERROR) << "installd could not create '"
1968 << image_path
1969 << "' for image file during dexopt";
1970 } else if (!set_permissions_and_ownership(image_fd.get(),
1971 is_public,
1972 uid,
Andreas Gampe89b008d2016-06-03 21:13:50 -07001973 image_path.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001974 image_fd.reset(-1);
1975 }
1976 }
1977 // If we have a valid image file path but no image fd, explicitly erase the image file.
1978 if (image_fd.get() < 0) {
Andreas Gampe89b008d2016-06-03 21:13:50 -07001979 if (unlink(image_path.c_str()) < 0) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001980 if (errno != ENOENT) {
1981 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1982 }
1983 }
1984 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001985 }
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001986
Alex Light7365a102014-07-21 12:23:48 -07001987 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001988
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001989 pid_t pid = fork();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001990 if (pid == 0) {
1991 /* child -- drop privileges before continuing */
Calin Juravle6a1648e2016-02-01 12:12:16 +00001992 drop_capabilities(uid);
1993
Andreas Gampe13f14192015-09-21 13:21:30 -07001994 SetDex2OatAndPatchOatScheduling(boot_complete);
David Brazdilfc5934e2016-09-08 11:55:48 +01001995 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1996 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001997 _exit(67);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001998 }
1999
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002000 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002001 run_patchoat(input_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002002 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002003 out_oat_fd.get(),
2004 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002005 input_file,
David Brazdilfc5934e2016-09-08 11:55:48 +01002006 in_vdex_path_str.c_str(),
2007 out_oat_path,
2008 out_vdex_path_str.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002009 pkgname,
2010 instruction_set);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002011 } else {
David Brazdilaaa1d4e2016-02-05 15:42:01 +00002012 // Pass dex2oat the relative path to the input file.
David Sehr40e566d2016-06-02 10:42:12 -07002013 const char *input_file_name = get_location_from_path(input_file);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002014 run_dex2oat(input_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002015 out_oat_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002016 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002017 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002018 image_fd.get(),
2019 input_file_name,
David Brazdilfc5934e2016-09-08 11:55:48 +01002020 out_oat_path,
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002021 swap_fd.get(),
2022 instruction_set,
2023 compiler_filter,
2024 vm_safe_mode,
2025 debuggable,
2026 boot_complete,
2027 reference_profile_fd.get(),
2028 shared_libraries);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002029 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002030 _exit(68); /* only get here on exec failure */
Mike Lockwood94afecf2012-10-24 10:45:23 -07002031 } else {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002032 int res = wait_child(pid);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002033 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07002034 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002035 } else {
Alex Light7365a102014-07-21 12:23:48 -07002036 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002037 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002038 }
2039 }
2040
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002041 struct utimbuf ut;
Alex Light7365a102014-07-21 12:23:48 -07002042 ut.actime = input_stat.st_atime;
2043 ut.modtime = input_stat.st_mtime;
David Brazdilfc5934e2016-09-08 11:55:48 +01002044 utime(out_oat_path, &ut);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002045
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002046 // We've been successful, don't delete output.
David Brazdilfc5934e2016-09-08 11:55:48 +01002047 out_oat_fd.SetCleanup(false);
2048 out_vdex_fd.SetCleanup(false);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002049 image_fd.SetCleanup(false);
2050 reference_profile_fd.SetCleanup(false);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002051
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002052 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002053}
2054
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002055binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2056 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2057 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2058 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
2059 const std::unique_ptr<std::string>& sharedLibraries) {
2060 ENFORCE_UID(AID_SYSTEM);
2061
2062 const char* apk_path = apkPath.c_str();
2063 const char* pkgname = packageName ? packageName->c_str() : "*";
2064 const char* instruction_set = instructionSet.c_str();
2065 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2066 const char* compiler_filter = compilerFilter.c_str();
2067 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
2068 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
2069
2070 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
2071 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
2072 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
2073}
2074
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002075binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2076 ENFORCE_UID(AID_SYSTEM);
2077 const char* instruction_set = instructionSet.c_str();
2078
2079 char boot_marker_path[PKG_PATH_MAX];
2080 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002081 "%s/%s/%s/.booting",
2082 android_data_dir.path,
2083 DALVIK_CACHE,
2084 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002085
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002086 ALOGV("mark_boot_complete : %s", boot_marker_path);
2087 if (unlink(boot_marker_path) != 0) {
2088 ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path, strerror(errno));
2089 return binder::Status::fromServiceSpecificError(-1);
2090 }
2091 return binder::Status::ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002092}
2093
Mike Lockwood94afecf2012-10-24 10:45:23 -07002094void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
2095 struct stat* statbuf)
2096{
2097 while (path[basepos] != 0) {
2098 if (path[basepos] == '/') {
2099 path[basepos] = 0;
2100 if (lstat(path, statbuf) < 0) {
2101 ALOGV("Making directory: %s\n", path);
2102 if (mkdir(path, mode) == 0) {
2103 chown(path, uid, gid);
2104 } else {
2105 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
2106 }
2107 }
2108 path[basepos] = '/';
2109 basepos++;
2110 }
2111 basepos++;
2112 }
2113}
2114
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002115binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2116 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2117 const std::string& nativeLibPath32, int32_t userId) {
2118 ENFORCE_UID(AID_SYSTEM);
2119 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2120 const char* pkgname = packageName.c_str();
2121 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002122 struct stat s, libStat;
2123 int rc = 0;
2124
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002125 std::string _pkgdir(create_data_user_ce_package_path(uuid_, userId, pkgname));
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002126 std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
2127
2128 const char* pkgdir = _pkgdir.c_str();
2129 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002130
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002131 if (stat(pkgdir, &s) < 0) {
2132 return binder::Status::fromServiceSpecificError(-1);
2133 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002134
2135 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
2136 ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002137 return binder::Status::fromServiceSpecificError(-1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002138 }
2139
2140 if (chmod(pkgdir, 0700) < 0) {
2141 ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
2142 rc = -1;
2143 goto out;
2144 }
2145
2146 if (lstat(libsymlink, &libStat) < 0) {
2147 if (errno != ENOENT) {
2148 ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
2149 rc = -1;
2150 goto out;
2151 }
2152 } else {
2153 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002154 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002155 rc = -1;
2156 goto out;
2157 }
2158 } else if (S_ISLNK(libStat.st_mode)) {
2159 if (unlink(libsymlink) < 0) {
2160 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
2161 rc = -1;
2162 goto out;
2163 }
2164 }
2165 }
2166
2167 if (symlink(asecLibDir, libsymlink) < 0) {
2168 ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
2169 strerror(errno));
2170 rc = -errno;
2171 goto out;
2172 }
2173
2174out:
2175 if (chmod(pkgdir, s.st_mode) < 0) {
2176 ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
2177 rc = -errno;
2178 }
2179
2180 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
2181 ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002182 rc = -errno;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002183 }
2184
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002185 return rc ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002186}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002187
2188static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2189{
2190 static const char *IDMAP_BIN = "/system/bin/idmap";
2191 static const size_t MAX_INT_LEN = 32;
2192 char idmap_str[MAX_INT_LEN];
2193
2194 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
2195
2196 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
2197 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
2198}
2199
2200// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2201// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2202static int flatten_path(const char *prefix, const char *suffix,
2203 const char *overlay_path, char *idmap_path, size_t N)
2204{
2205 if (overlay_path == NULL || idmap_path == NULL) {
2206 return -1;
2207 }
2208 const size_t len_overlay_path = strlen(overlay_path);
2209 // will access overlay_path + 1 further below; requires absolute path
2210 if (len_overlay_path < 2 || *overlay_path != '/') {
2211 return -1;
2212 }
2213 const size_t len_idmap_root = strlen(prefix);
2214 const size_t len_suffix = strlen(suffix);
2215 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2216 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2217 // additions below would cause overflow
2218 return -1;
2219 }
2220 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2221 return -1;
2222 }
2223 memset(idmap_path, 0, N);
2224 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2225 char *ch = idmap_path + len_idmap_root;
2226 while (*ch != '\0') {
2227 if (*ch == '/') {
2228 *ch = '@';
2229 }
2230 ++ch;
2231 }
2232 return 0;
2233}
2234
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002235binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2236 const std::string& overlayApkPath, int32_t uid) {
2237 ENFORCE_UID(AID_SYSTEM);
2238 const char* target_apk = targetApkPath.c_str();
2239 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002240 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2241
2242 int idmap_fd = -1;
2243 char idmap_path[PATH_MAX];
2244
2245 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2246 idmap_path, sizeof(idmap_path)) == -1) {
2247 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2248 goto fail;
2249 }
2250
2251 unlink(idmap_path);
2252 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2253 if (idmap_fd < 0) {
2254 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2255 goto fail;
2256 }
2257 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2258 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2259 goto fail;
2260 }
2261 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2262 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2263 goto fail;
2264 }
2265
2266 pid_t pid;
2267 pid = fork();
2268 if (pid == 0) {
2269 /* child -- drop privileges before continuing */
2270 if (setgid(uid) != 0) {
2271 ALOGE("setgid(%d) failed during idmap\n", uid);
2272 exit(1);
2273 }
2274 if (setuid(uid) != 0) {
2275 ALOGE("setuid(%d) failed during idmap\n", uid);
2276 exit(1);
2277 }
2278 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2279 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2280 exit(1);
2281 }
2282
2283 run_idmap(target_apk, overlay_apk, idmap_fd);
2284 exit(1); /* only if exec call to idmap failed */
2285 } else {
2286 int status = wait_child(pid);
2287 if (status != 0) {
2288 ALOGE("idmap failed, status=0x%04x\n", status);
2289 goto fail;
2290 }
2291 }
2292
2293 close(idmap_fd);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002294 return binder::Status::ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002295fail:
2296 if (idmap_fd >= 0) {
2297 close(idmap_fd);
2298 unlink(idmap_path);
2299 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002300 return binder::Status::fromServiceSpecificError(-1);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002301}
Robert Craige9887e42014-02-20 10:25:56 -05002302
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002303binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2304 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2305 const std::string& seInfo) {
2306 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002307 int res = 0;
Robert Craige9887e42014-02-20 10:25:56 -05002308
Robert Craigda30dc72014-03-27 10:21:12 -04002309 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002310 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002311 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2312 const char* pkgName = packageName.c_str();
2313 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002314
2315 if (!pkgName || !seinfo) {
2316 ALOGE("Package name or seinfo tag is null when trying to restorecon.");
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002317 return binder::Status::fromServiceSpecificError(-1);
Robert Craige9887e42014-02-20 10:25:56 -05002318 }
2319
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002320 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002321 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002322 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002323 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2324 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002325 res = -1;
2326 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002327 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002328 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002329 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002330 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2331 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyea0e4b12015-11-19 15:35:27 -07002332 // TODO: include result once 25796509 is fixed
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002333 }
Robert Craige9887e42014-02-20 10:25:56 -05002334 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002335 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Robert Craige9887e42014-02-20 10:25:56 -05002336}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002337
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002338binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2339 const std::string& instructionSet) {
2340 ENFORCE_UID(AID_SYSTEM);
2341 const char* oat_dir = oatDir.c_str();
2342 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002343 char oat_instr_dir[PKG_PATH_MAX];
2344
2345 if (validate_apk_path(oat_dir)) {
2346 ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002347 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002348 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002349 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002350 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002351 }
2352 if (selinux_android_restorecon(oat_dir, 0)) {
2353 ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002354 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002355 }
2356 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002357 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002358 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002359 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002360 return binder::Status::ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002361}
2362
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002363binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2364 ENFORCE_UID(AID_SYSTEM);
2365 const char* apk_path = packageDir.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002366 if (validate_apk_path(apk_path)) {
2367 ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002368 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002369 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002370 int res = delete_dir_contents(apk_path, 1 /* also_delete_dir */,
2371 NULL /* exclusion_predicate */);
2372 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002373}
2374
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002375binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2376 const std::string& fromBase, const std::string& toBase) {
2377 ENFORCE_UID(AID_SYSTEM);
2378 const char* relative_path = relativePath.c_str();
2379 const char* from_base = fromBase.c_str();
2380 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002381 char from_path[PKG_PATH_MAX];
2382 char to_path[PKG_PATH_MAX];
2383 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2384 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2385
2386 if (validate_apk_path_subdirs(from_path)) {
2387 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002388 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002389 }
2390
2391 if (validate_apk_path_subdirs(to_path)) {
2392 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002393 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002394 }
2395
2396 const int ret = link(from_path, to_path);
2397 if (ret < 0) {
2398 ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002399 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002400 }
2401
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002402 return binder::Status::ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002403}
2404
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002405// Helper for move_ab, so that we can have common failure-case cleanup.
2406static bool unlink_and_rename(const char* from, const char* to) {
2407 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2408 // return a failure.
2409 struct stat s;
2410 if (stat(to, &s) == 0) {
2411 if (!S_ISREG(s.st_mode)) {
2412 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2413 return false;
2414 }
2415 if (unlink(to) != 0) {
2416 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2417 return false;
2418 }
2419 } else {
2420 // This may be a permission problem. We could investigate the error code, but we'll just
2421 // let the rename failure do the work for us.
2422 }
2423
2424 // Try to rename "to" to "from."
2425 if (rename(from, to) != 0) {
2426 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2427 return false;
2428 }
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002429 return true;
2430}
2431
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002432// Move/rename a B artifact (from) to an A artifact (to).
2433static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2434 // Check whether B exists.
2435 {
2436 struct stat s;
2437 if (stat(b_path.c_str(), &s) != 0) {
2438 // Silently ignore for now. The service calling this isn't smart enough to understand
2439 // lack of artifacts at the moment.
2440 return false;
2441 }
2442 if (!S_ISREG(s.st_mode)) {
2443 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2444 // Try to unlink, but swallow errors.
2445 unlink(b_path.c_str());
2446 return false;
2447 }
2448 }
2449
2450 // Rename B to A.
2451 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2452 // Delete the b_path so we don't try again (or fail earlier).
2453 if (unlink(b_path.c_str()) != 0) {
2454 PLOG(ERROR) << "Could not unlink " << b_path;
2455 }
2456
2457 return false;
2458 }
2459
2460 return true;
2461}
2462
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002463binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2464 const std::string& instructionSet, const std::string& outputPath) {
2465 ENFORCE_UID(AID_SYSTEM);
2466 const char* apk_path = apkPath.c_str();
2467 const char* instruction_set = instructionSet.c_str();
2468 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07002469
2470 // Get the current slot suffix. No suffix, no A/B.
2471 std::string slot_suffix;
2472 {
2473 char buf[kPropertyValueMax];
2474 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002475 return binder::Status::fromServiceSpecificError(-1);
Andreas Gamped089ca12016-06-27 14:25:30 -07002476 }
2477 slot_suffix = buf;
2478
Andreas Gampefd12eda2016-07-12 09:47:17 -07002479 if (!ValidateTargetSlotSuffix(slot_suffix)) {
Andreas Gamped089ca12016-06-27 14:25:30 -07002480 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002481 return binder::Status::fromServiceSpecificError(-1);
Andreas Gamped089ca12016-06-27 14:25:30 -07002482 }
2483 }
2484
2485 // Validate other inputs.
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002486 if (validate_apk_path(apk_path) != 0) {
2487 LOG(ERROR) << "invalid apk_path " << apk_path;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002488 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002489 }
2490 if (validate_apk_path(oat_dir) != 0) {
2491 LOG(ERROR) << "invalid oat_dir " << oat_dir;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002492 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002493 }
2494
2495 char a_path[PKG_PATH_MAX];
2496 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002497 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002498 }
David Brazdilfc5934e2016-09-08 11:55:48 +01002499 const std::string a_vdex_path = create_vdex_filename(a_path);
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002500 const std::string a_image_path = create_image_filename(a_path);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002501
Andreas Gamped089ca12016-06-27 14:25:30 -07002502 // B path = A path + slot suffix.
2503 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002504 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 -07002505 const std::string b_image_path = StringPrintf("%s.%s",
2506 a_image_path.c_str(),
2507 slot_suffix.c_str());
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002508
David Brazdilfc5934e2016-09-08 11:55:48 +01002509 bool success = true;
2510 if (move_ab_path(b_path, a_path)) {
2511 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2512 // Note: we can live without an app image. As such, ignore failure to move the image file.
2513 // If we decide to require the app image, or the app image being moved correctly,
2514 // then change accordingly.
2515 constexpr bool kIgnoreAppImageFailure = true;
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002516
David Brazdilfc5934e2016-09-08 11:55:48 +01002517 if (!a_image_path.empty()) {
2518 if (!move_ab_path(b_image_path, a_image_path)) {
David Brazdilc338c7f2016-09-12 16:26:40 +01002519 unlink(a_image_path.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002520 if (!kIgnoreAppImageFailure) {
2521 success = false;
2522 }
2523 }
2524 }
2525 } else {
2526 // Cleanup: delete B image, ignore errors.
2527 unlink(b_image_path.c_str());
2528 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002529 }
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002530 } else {
2531 // Cleanup: delete B image, ignore errors.
David Brazdilfc5934e2016-09-08 11:55:48 +01002532 unlink(b_vdex_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002533 unlink(b_image_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002534 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002535 }
2536
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002537 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002538}
2539
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002540binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2541 const std::string& instructionSet, const std::string& outputPath) {
2542 ENFORCE_UID(AID_SYSTEM);
2543 const char* apk_path = apkPath.c_str();
2544 const char* instruction_set = instructionSet.c_str();
2545 const char* oat_dir = outputPath.c_str();
2546
Andreas Gampeb31206b2016-09-09 17:07:04 -07002547 // Delete the oat/odex file.
2548 char out_path[PKG_PATH_MAX];
2549 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002550 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampeb31206b2016-09-09 17:07:04 -07002551 }
2552
2553 // In case of a permission failure report the issue. Otherwise just print a warning.
2554 auto unlink_and_check = [](const char* path) -> bool {
2555 int result = unlink(path);
2556 if (result != 0) {
2557 if (errno == EACCES || errno == EPERM) {
2558 PLOG(ERROR) << "Could not unlink " << path;
2559 return false;
2560 }
2561 PLOG(WARNING) << "Could not unlink " << path;
2562 }
2563 return true;
2564 };
2565
2566 // Delete the oat/odex file.
2567 bool return_value_oat = unlink_and_check(out_path);
2568
2569 // Derive and delete the app image.
2570 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2571
2572 // Report success.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002573 bool success = return_value_oat && return_value_art;
2574 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Andreas Gampeb31206b2016-09-09 17:07:04 -07002575}
2576
Andreas Gampe02d0de52015-11-11 20:43:16 -08002577} // namespace installd
2578} // namespace android