blob: facf7a4c62601cb53001ac58ffdc1b11b5a2906d [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
Andreas Gampe02d0de52015-11-11 20:43:16 -080017#include "commands.h"
18
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
Andreas Gampe02d0de52015-11-11 20:43:16 -080045#include <globals.h>
46#include <installd_deps.h>
Andreas Gampefd12eda2016-07-12 09:47:17 -070047#include <otapreopt_utils.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <utils.h>
49
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050#include "dexopt.h"
51
Andreas Gampe02d0de52015-11-11 20:43:16 -080052#ifndef LOG_TAG
53#define LOG_TAG "installd"
54#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070055
Andreas Gampe6fb5a012016-06-03 16:09:32 -070056using android::base::EndsWith;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070057using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070058
Andreas Gampe02d0de52015-11-11 20:43:16 -080059namespace android {
60namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070061
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070062static constexpr const char* kCpPath = "/system/bin/cp";
63static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070064
Andreas Gamped089ca12016-06-27 14:25:30 -070065static constexpr const char* PKG_LIB_POSTFIX = "/lib";
66static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
67static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
68
69static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
70static constexpr const char* IDMAP_SUFFIX = "@idmap";
71
72// NOTE: keep in sync with StorageManager
73static constexpr int FLAG_STORAGE_DE = 1 << 0;
74static constexpr int FLAG_STORAGE_CE = 1 << 1;
75
76// NOTE: keep in sync with Installer
77static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
78static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
79
80/* dexopt needed flags matching those in dalvik.system.DexFile */
Nicolas Geoffray920c60c2016-11-25 11:33:31 +000081static constexpr int DEX2OAT_FROM_SCRATCH = 1;
82static constexpr int DEX2OAT_FOR_BOOT_IMAGE = 2;
83static constexpr int DEX2OAT_FOR_FILTER = 3;
84static constexpr int DEX2OAT_FOR_RELOCATION = 4;
85static constexpr int PATCHOAT_FOR_RELOCATION = 5;
Andreas Gamped089ca12016-06-27 14:25:30 -070086
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000087#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
88
Calin Juravle6a1648e2016-02-01 12:12:16 +000089typedef int fd_t;
90
Jeff Sharkey0274c972016-12-06 09:32:04 -070091namespace {
92
93constexpr const char* kDump = "android.permission.DUMP";
94
95binder::Status checkPermission(const char* permission) {
96 pid_t pid;
97 uid_t uid;
98
99 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
100 reinterpret_cast<int32_t*>(&uid))) {
101 return binder::Status::ok();
102 } else {
103 auto err = StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission);
104 return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
105 }
106}
107
108binder::Status checkUid(uid_t expectedUid) {
109 uid_t uid = IPCThreadState::self()->getCallingUid();
110 if (uid == expectedUid || uid == AID_ROOT) {
111 return binder::Status::ok();
112 } else {
113 auto err = StringPrintf("UID %d is not expected UID %d", uid, expectedUid);
114 return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(err.c_str()));
115 }
116}
117
118#define ENFORCE_UID(uid) { \
119 binder::Status status = checkUid((uid)); \
120 if (!status.isOk()) { \
121 return status; \
122 } \
123}
124
125} // namespace
126
127status_t InstalldNativeService::start() {
128 IPCThreadState::self()->disableBackgroundScheduling(true);
129 status_t ret = BinderService<InstalldNativeService>::publish();
130 if (ret != android::OK) {
131 return ret;
132 }
133 sp<ProcessState> ps(ProcessState::self());
134 ps->startThreadPool();
135 ps->giveThreadPoolName();
136 return android::OK;
137}
138
139status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
140 const binder::Status dump_permission = checkPermission(kDump);
141 if (!dump_permission.isOk()) {
142 const String8 msg(dump_permission.toString8());
143 write(fd, msg.string(), msg.size());
144 return PERMISSION_DENIED;
145 }
146
147 std::string msg = "installd is happy\n";
148 write(fd, msg.c_str(), strlen(msg.c_str()));
149 return NO_ERROR;
150}
151
Calin Juravle6a1648e2016-02-01 12:12:16 +0000152static bool property_get_bool(const char* property_name, bool default_value = false) {
153 char tmp_property_value[kPropertyValueMax];
154 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
155 if (!have_property) {
156 return default_value;
157 }
158 return strcmp(tmp_property_value, "true") == 0;
159}
160
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100161// Keep profile paths in sync with ActivityThread.
162constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
163static std::string create_primary_profile(const std::string& profile_dir) {
164 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
165}
166
Jeff Sharkey7db60412016-09-20 18:21:42 -0600167/**
168 * Perform restorecon of the given path, but only perform recursive restorecon
169 * if the label of that top-level file actually changed. This can save us
170 * significant time by avoiding no-op traversals of large filesystem trees.
171 */
Jeff Sharkey0274c972016-12-06 09:32:04 -0700172static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600173 int res = 0;
174 char* before = nullptr;
175 char* after = nullptr;
176
177 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
178 // libselinux. Not needed here.
179
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600180 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600181 PLOG(ERROR) << "Failed before getfilecon for " << path;
182 goto fail;
183 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700184 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600185 PLOG(ERROR) << "Failed top-level restorecon for " << path;
186 goto fail;
187 }
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600188 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600189 PLOG(ERROR) << "Failed after getfilecon for " << path;
190 goto fail;
191 }
192
193 // If the initial top-level restorecon above changed the label, then go
194 // back and restorecon everything recursively
195 if (strcmp(before, after)) {
196 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at " << path
197 << "; running recursive restorecon";
Jeff Sharkey0274c972016-12-06 09:32:04 -0700198 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600199 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
200 PLOG(ERROR) << "Failed recursive restorecon for " << path;
201 goto fail;
202 }
203 }
204
205 goto done;
206fail:
207 res = -1;
208done:
209 free(before);
210 free(after);
211 return res;
212}
213
Jeff Sharkey0274c972016-12-06 09:32:04 -0700214static int restorecon_app_data_lazy(const std::string& parent, const char* name,
215 const std::string& seInfo, uid_t uid) {
216 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid);
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600217}
218
Jeff Sharkey7db60412016-09-20 18:21:42 -0600219static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600220 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
221 PLOG(ERROR) << "Failed to prepare " << path;
222 return -1;
223 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600224 return 0;
225}
226
227static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600228 uid_t uid) {
229 return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600230}
231
Jeff Sharkey0274c972016-12-06 09:32:04 -0700232binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
233 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
234 const std::string& seInfo, int32_t targetSdkVersion) {
235 ENFORCE_UID(AID_SYSTEM);
236
237 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
238 const char* pkgname = packageName.c_str();
239
240 uid_t uid = multiuser_get_uid(userId, appId);
241 mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700242 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700243 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600244 if (prepare_app_dir(path, target_mode, uid) ||
245 prepare_app_dir(path, "cache", 0771, uid) ||
246 prepare_app_dir(path, "code_cache", 0771, uid)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700247 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600248 }
249
250 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700251 if (restorecon_app_data_lazy(path, seInfo, uid) ||
252 restorecon_app_data_lazy(path, "cache", seInfo, uid) ||
253 restorecon_app_data_lazy(path, "code_cache", seInfo, uid)) {
254 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700255 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600256
257 // Remember inode numbers of cache directories so that we can clear
258 // contents while CE storage is locked
259 if (write_path_inode(path, "cache", kXattrInodeCache) ||
260 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700261 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700262 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700263 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700264 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700265 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600266 if (prepare_app_dir(path, target_mode, uid)) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700267 // TODO: include result once 25796509 is fixed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700268 return binder::Status::ok();
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700269 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000270
Jeff Sharkey7db60412016-09-20 18:21:42 -0600271 // Consider restorecon over contents if label changed
Jeff Sharkey0274c972016-12-06 09:32:04 -0700272 if (restorecon_app_data_lazy(path, seInfo, uid)) {
273 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600274 }
275
Calin Juravle6a1648e2016-02-01 12:12:16 +0000276 if (property_get_bool("dalvik.vm.usejitprofiles")) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700277 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000278 // read-write-execute only for the app user.
279 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
280 PLOG(ERROR) << "Failed to prepare " << profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700281 return binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000282 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100283 std::string profile_file = create_primary_profile(profile_path);
284 // read-write only for the app user.
285 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
286 PLOG(ERROR) << "Failed to prepare " << profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700287 return binder::Status::fromServiceSpecificError(-1);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100288 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000289 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
290 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
291 // profiles.
292 appid_t shared_app_gid = multiuser_get_shared_app_gid(uid);
293 if (fs_prepare_dir_strict(
294 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
295 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700296 return binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000297 }
298 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700299 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700300 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700301}
302
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700303binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
304 const std::string& packageName, int32_t userId, int32_t flags) {
305 ENFORCE_UID(AID_SYSTEM);
306 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
307 const char* pkgname = packageName.c_str();
308
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700309 // This method only exists to upgrade system apps that have requested
310 // forceDeviceEncrypted, so their default storage always lives in a
311 // consistent location. This only works on non-FBE devices, since we
312 // never want to risk exposing data on a device with real CE/DE storage.
313
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700314 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
315 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700316
317 // If neither directory is marked as default, assume CE is default
318 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
319 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
320 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
321 PLOG(ERROR) << "Failed to mark default storage " << ce_path;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700322 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700323 }
324 }
325
326 // Migrate default data location if needed
327 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
328 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
329
330 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
331 LOG(WARNING) << "Requested default storage " << target
332 << " is not active; migrating from " << source;
333 if (delete_dir_contents_and_dir(target) != 0) {
334 PLOG(ERROR) << "Failed to delete";
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700335 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700336 }
337 if (rename(source.c_str(), target.c_str()) != 0) {
338 PLOG(ERROR) << "Failed to rename";
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700339 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700340 }
341 }
342
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700343 return binder::Status::ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700344}
345
Calin Juravlecea31412016-03-29 15:36:34 +0100346static bool clear_profile(const std::string& profile) {
Roland Levillain64b59cc2016-04-05 16:41:12 +0100347 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
348 if (ufd.get() < 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100349 if (errno != ENOENT) {
350 PLOG(WARNING) << "Could not open profile " << profile;
351 return false;
352 } else {
353 // Nothing to clear. That's ok.
354 return true;
355 }
356 }
357
Roland Levillain64b59cc2016-04-05 16:41:12 +0100358 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100359 if (errno != EWOULDBLOCK) {
360 PLOG(WARNING) << "Error locking profile " << profile;
361 }
362 // This implies that the app owning this profile is running
363 // (and has acquired the lock).
364 //
365 // If we can't acquire the lock bail out since clearing is useless anyway
366 // (the app will write again to the profile).
367 //
368 // Note:
369 // This does not impact the this is not an issue for the profiling correctness.
370 // In case this is needed because of an app upgrade, profiles will still be
371 // eventually cleared by the app itself due to checksum mismatch.
372 // If this is needed because profman advised, then keeping the data around
373 // until the next run is again not an issue.
374 //
375 // If the app attempts to acquire a lock while we've held one here,
376 // it will simply skip the current write cycle.
377 return false;
378 }
379
Roland Levillain64b59cc2016-04-05 16:41:12 +0100380 bool truncated = ftruncate(ufd.get(), 0) == 0;
Calin Juravlecea31412016-03-29 15:36:34 +0100381 if (!truncated) {
382 PLOG(WARNING) << "Could not truncate " << profile;
383 }
Roland Levillain64b59cc2016-04-05 16:41:12 +0100384 if (flock(ufd.get(), LOCK_UN) != 0) {
Calin Juravlecea31412016-03-29 15:36:34 +0100385 PLOG(WARNING) << "Error unlocking profile " << profile;
386 }
387 return truncated;
388}
389
390static bool clear_reference_profile(const char* pkgname) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000391 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
392 std::string reference_profile = create_primary_profile(reference_profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100393 return clear_profile(reference_profile);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000394}
395
Calin Juravlecea31412016-03-29 15:36:34 +0100396static bool clear_current_profile(const char* pkgname, userid_t user) {
Calin Juravleedae6692016-03-23 13:55:31 +0000397 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
398 std::string profile = create_primary_profile(profile_dir);
Calin Juravlecea31412016-03-29 15:36:34 +0100399 return clear_profile(profile);
Calin Juravleedae6692016-03-23 13:55:31 +0000400}
401
Calin Juravlecea31412016-03-29 15:36:34 +0100402static bool clear_current_profiles(const char* pkgname) {
David Brazdild828d682016-03-08 12:50:20 +0000403 bool success = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000404 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
405 for (auto user : users) {
Calin Juravlecea31412016-03-29 15:36:34 +0100406 success &= clear_current_profile(pkgname, user);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000407 }
David Brazdild828d682016-03-08 12:50:20 +0000408 return success;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000409}
410
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700411binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
412 ENFORCE_UID(AID_SYSTEM);
413 const char* pkgname = packageName.c_str();
David Brazdild828d682016-03-08 12:50:20 +0000414 bool success = true;
Calin Juravlecea31412016-03-29 15:36:34 +0100415 success &= clear_reference_profile(pkgname);
416 success &= clear_current_profiles(pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700417 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000418}
419
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700420binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
421 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
422 ENFORCE_UID(AID_SYSTEM);
423 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
424 const char* pkgname = packageName.c_str();
425
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700426 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700427 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700428 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600429 if (flags & FLAG_CLEAR_CACHE_ONLY) {
430 path = read_path_inode(path, "cache", kXattrInodeCache);
431 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
432 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
433 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700434 if (access(path.c_str(), F_OK) == 0) {
435 res |= delete_dir_contents(path);
436 }
437 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700438 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600439 std::string suffix = "";
440 bool only_cache = false;
441 if (flags & FLAG_CLEAR_CACHE_ONLY) {
442 suffix = CACHE_DIR_POSTFIX;
443 only_cache = true;
444 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
445 suffix = CODE_CACHE_DIR_POSTFIX;
446 only_cache = true;
447 }
448
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700449 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700450 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700451 // TODO: include result once 25796509 is fixed
452 delete_dir_contents(path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700453 }
Calin Juravleedae6692016-03-23 13:55:31 +0000454 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700455 if (!clear_current_profile(pkgname, userId)) {
Calin Juravleedae6692016-03-23 13:55:31 +0000456 res |= -1;
457 }
458 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700459 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700460 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700461}
462
Calin Juravle7535e8e2016-03-29 16:05:40 +0100463static int destroy_app_reference_profile(const char *pkgname) {
464 return delete_dir_contents_and_dir(
465 create_data_ref_profile_package_path(pkgname),
466 /*ignore_if_missing*/ true);
467}
468
Calin Juravleedae6692016-03-23 13:55:31 +0000469static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100470 return delete_dir_contents_and_dir(
471 create_data_user_profile_package_path(userid, pkgname),
472 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000473}
474
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700475binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
476 ENFORCE_UID(AID_SYSTEM);
477 const char* pkgname = packageName.c_str();
Calin Juravleedae6692016-03-23 13:55:31 +0000478 int result = 0;
479 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
480 for (auto user : users) {
481 result |= destroy_app_current_profiles(pkgname, user);
482 }
Calin Juravle7535e8e2016-03-29 16:05:40 +0100483 result |= destroy_app_reference_profile(pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700484 return result ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Calin Juravlecaa6b802016-03-22 14:15:52 +0000485}
486
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700487binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
488 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
489 ENFORCE_UID(AID_SYSTEM);
490 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
491 const char* pkgname = packageName.c_str();
492
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700493 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700494 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700495 res |= delete_dir_contents_and_dir(
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700496 create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700497 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700498 if (flags & FLAG_STORAGE_DE) {
Calin Juravlecaa6b802016-03-22 14:15:52 +0000499 res |= delete_dir_contents_and_dir(
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500 create_data_user_de_package_path(uuid_, userId, pkgname));
501 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100502 // TODO(calin): If the package is still installed by other users it's probably
503 // beneficial to keep the reference profile around.
504 // Verify if it's ok to do that.
505 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700506 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700507 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700508}
509
Jeff Sharkey0274c972016-12-06 09:32:04 -0700510binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
511 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
512 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
513 int32_t targetSdkVersion) {
514
515 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
516 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
517 const char* package_name = packageName.c_str();
518 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700519
Jeff Sharkeye3637242015-04-08 20:56:42 -0700520 std::vector<userid_t> users = get_known_users(from_uuid);
521
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700522 // Copy app
523 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600524 auto from = create_data_app_package_path(from_uuid, data_app_name);
525 auto to = create_data_app_package_path(to_uuid, data_app_name);
526 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700527
528 char *argv[] = {
529 (char*) kCpPath,
530 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
531 (char*) "-p", /* preserve timestamps, ownership, and permissions */
532 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
533 (char*) "-P", /* Do not follow symlinks [default] */
534 (char*) "-d", /* don't dereference symlinks */
535 (char*) from.c_str(),
536 (char*) to_parent.c_str()
537 };
538
539 LOG(DEBUG) << "Copying " << from << " to " << to;
540 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
541
542 if (rc != 0) {
543 LOG(ERROR) << "Failed copying " << from << " to " << to
544 << ": status " << rc;
545 goto fail;
546 }
547
548 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
549 LOG(ERROR) << "Failed to restorecon " << to;
550 goto fail;
551 }
552 }
553
554 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700555 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700556
557 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600558 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
559 if (access(from_ce.c_str(), F_OK) != 0) {
560 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700561 continue;
562 }
563
Jeff Sharkey0274c972016-12-06 09:32:04 -0700564 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
565 seInfo, targetSdkVersion).isOk()) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600566 LOG(ERROR) << "Failed to create package target on " << to_uuid;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700567 goto fail;
568 }
569
570 char *argv[] = {
571 (char*) kCpPath,
572 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
573 (char*) "-p", /* preserve timestamps, ownership, and permissions */
574 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
575 (char*) "-P", /* Do not follow symlinks [default] */
576 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600577 nullptr,
578 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700579 };
580
Jeff Sharkey51c94492016-05-10 17:46:39 -0600581 {
582 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
583 auto to = create_data_user_de_path(to_uuid, user);
584 argv[6] = (char*) from.c_str();
585 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700586
Jeff Sharkey51c94492016-05-10 17:46:39 -0600587 LOG(DEBUG) << "Copying " << from << " to " << to;
588 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
589 if (rc != 0) {
590 LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
591 goto fail;
592 }
593 }
594 {
595 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
596 auto to = create_data_user_ce_path(to_uuid, user);
597 argv[6] = (char*) from.c_str();
598 argv[7] = (char*) to.c_str();
599
600 LOG(DEBUG) << "Copying " << from << " to " << to;
601 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
602 if (rc != 0) {
603 LOG(ERROR) << "Failed copying " << from << " to " << to << " with status " << rc;
604 goto fail;
605 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700606 }
607
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700608 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
609 appId, seInfo).isOk()) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700610 LOG(ERROR) << "Failed to restorecon";
611 goto fail;
612 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700613 }
614
Jeff Sharkey31f08982015-07-07 13:31:37 -0700615 // We let the framework scan the new location and persist that before
616 // deleting the data in the old location; this ordering ensures that
617 // we can recover from things like battery pulls.
Jeff Sharkey0274c972016-12-06 09:32:04 -0700618 return binder::Status::ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700619
620fail:
621 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700622 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600623 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700624 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
625 LOG(WARNING) << "Failed to rollback " << to;
626 }
627 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700628 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600629 {
630 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
631 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
632 LOG(WARNING) << "Failed to rollback " << to;
633 }
634 }
635 {
636 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
637 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
638 LOG(WARNING) << "Failed to rollback " << to;
639 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700640 }
641 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700642 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkeye3637242015-04-08 20:56:42 -0700643}
644
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700645binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
646 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
647 ENFORCE_UID(AID_SYSTEM);
648 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700649 int res = 0;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600650 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700651 if (uuid_ == nullptr) {
652 res = ensure_config_user_dirs(userId);
653 }
654 }
655 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
656}
657
658binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
659 int32_t userId, int32_t flags) {
660 ENFORCE_UID(AID_SYSTEM);
661 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
662 int res = 0;
663 if (flags & FLAG_STORAGE_DE) {
664 res |= delete_dir_contents_and_dir(create_data_user_de_path(uuid_, userId), true);
665 if (uuid_ == nullptr) {
666 res |= delete_dir_contents_and_dir(create_data_misc_legacy_path(userId), true);
667 res |= delete_dir_contents_and_dir(create_data_user_profiles_path(userId), true);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700668 }
Robin Lee095c7632014-04-25 15:05:19 +0100669 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600670 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700671 res |= delete_dir_contents_and_dir(create_data_user_ce_path(uuid_, userId), true);
672 res |= delete_dir_contents_and_dir(create_data_media_path(uuid_, userId), true);
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600673 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700674 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Robin Lee095c7632014-04-25 15:05:19 +0100675}
676
Mike Lockwood94afecf2012-10-24 10:45:23 -0700677/* Try to ensure free_size bytes of storage are available.
678 * Returns 0 on success.
679 * This is rather simple-minded because doing a full LRU would
680 * be potentially memory-intensive, and without atime it would
681 * also require that apps constantly modify file metadata even
682 * when just reading from the cache, which is pretty awful.
683 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700684binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
685 int64_t freeStorageSize) {
686 ENFORCE_UID(AID_SYSTEM);
687 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700688 cache_t* cache;
689 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700690
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700691 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700692
693 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700694 if (avail < 0) {
695 return binder::Status::fromServiceSpecificError(-1);
696 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700697
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700698 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
699 if (avail >= freeStorageSize) {
700 return binder::Status::ok();
701 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700702
703 cache = start_cache_collection();
704
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700705 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600706 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700707 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
708 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600709 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700710 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700711 }
712
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700713 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700714 finish_cache_collection(cache);
715
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700716 if (data_disk_free(data_path) >= freeStorageSize) {
717 return binder::Status::ok();
718 } else {
719 return binder::Status::fromServiceSpecificError(-1);
720 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700721}
722
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700723binder::Status InstalldNativeService::rmdex(const std::string& codePath,
724 const std::string& instructionSet) {
725 ENFORCE_UID(AID_SYSTEM);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700726 char dex_path[PKG_PATH_MAX];
727
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700728 const char* path = codePath.c_str();
729 const char* instruction_set = instructionSet.c_str();
730
Jeff Sharkey770180a2014-09-08 17:14:26 -0700731 if (validate_apk_path(path) && validate_system_app_path(path)) {
732 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700733 return binder::Status::fromServiceSpecificError(-1);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700734 }
735
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700736 if (!create_cache_path(dex_path, path, instruction_set)) {
737 return binder::Status::fromServiceSpecificError(-1);
738 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700739
740 ALOGV("unlink %s\n", dex_path);
741 if (unlink(dex_path) < 0) {
Jeff Sharkey770180a2014-09-08 17:14:26 -0700742 if (errno != ENOENT) {
743 ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
744 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700745 return binder::Status::fromServiceSpecificError(-1);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700746 } else {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700747 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700748 }
749}
750
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600751static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
752 int64_t *cachesize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700753 DIR *d;
754 int dfd;
755 struct dirent *de;
756 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700757
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600758 d = opendir(path.c_str());
759 if (d == nullptr) {
760 PLOG(WARNING) << "Failed to open " << path;
761 return;
762 }
763 dfd = dirfd(d);
764 while ((de = readdir(d))) {
765 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700766
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600767 int64_t statsize = 0;
768 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
769 statsize = stat_size(&s);
770 }
771
772 if (de->d_type == DT_DIR) {
773 int subfd;
774 int64_t dirsize = 0;
775 /* always skip "." and ".." */
776 if (name[0] == '.') {
777 if (name[1] == 0) continue;
778 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700779 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600780 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
781 if (subfd >= 0) {
782 dirsize = calculate_dir_size(subfd);
783 close(subfd);
784 }
785 // TODO: check xattrs!
786 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
787 *datasize += statsize;
788 *cachesize += dirsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700789 } else {
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600790 *datasize += dirsize + statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700791 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600792 } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
793 *codesize += statsize;
794 } else {
795 *datasize += statsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700796 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600797 }
798 closedir(d);
799}
800
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700801binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
802 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
803 const std::string& codePath, std::vector<int64_t>* _aidl_return) {
804 ENFORCE_UID(AID_SYSTEM);
805 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
806 const char* pkgname = packageName.c_str();
807 const char* code_path = codePath.c_str();
808
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600809 DIR *d;
810 int dfd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700811 int64_t codesize = 0;
812 int64_t datasize = 0;
813 int64_t cachesize = 0;
814 int64_t asecsize = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600815
816 d = opendir(code_path);
817 if (d != nullptr) {
818 dfd = dirfd(d);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700819 codesize += calculate_dir_size(dfd);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700820 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700821 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600822
823 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700824 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
825 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600826 }
827 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700828 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
829 add_app_data_size(path, &codesize, &datasize, &cachesize);
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600830 }
831
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700832 std::vector<int64_t> res;
833 res.push_back(codesize);
834 res.push_back(datasize);
835 res.push_back(cachesize);
836 res.push_back(asecsize);
837 *_aidl_return = res;
838 return binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700839}
840
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700841binder::Status InstalldNativeService::getAppDataInode(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700842 const std::string& packageName, int32_t userId, int32_t flags, int64_t* _aidl_return) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700843 ENFORCE_UID(AID_SYSTEM);
844 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
845 const char* pkgname = packageName.c_str();
846
847 int res = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600848 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700849 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
850 res = get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return));
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600851 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700852 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600853}
854
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700855static int split_count(const char *str)
856{
857 char *ctx;
858 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800859 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700860
861 strncpy(buf, str, sizeof(buf));
862 char *pBuf = buf;
863
864 while(strtok_r(pBuf, " ", &ctx) != NULL) {
865 count++;
866 pBuf = NULL;
867 }
868
869 return count;
870}
871
neo.chae14e084d2015-01-07 18:46:13 +0900872static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700873{
874 char *ctx;
875 int count = 0;
876 char *tok;
877 char *pBuf = buf;
878
879 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
880 argv[count++] = tok;
881 pBuf = NULL;
882 }
883
884 return count;
885}
886
David Brazdilfc5934e2016-09-08 11:55:48 +0100887static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
888 const char* input_oat_file_name, const char* input_vdex_file_name,
889 const char* output_oat_file_name, const char* output_vdex_file_name,
890 const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -0700891{
892 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +0100893 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -0700894
895 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
896 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
897 ALOGE("Instruction set %s longer than max length of %d",
898 instruction_set, MAX_INSTRUCTION_SET_LEN);
899 return;
900 }
901
902 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
903 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Alex Light7365a102014-07-21 12:23:48 -0700904 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
David Brazdilfc5934e2016-09-08 11:55:48 +0100905 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
906 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
907 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Alex Light7365a102014-07-21 12:23:48 -0700908 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
909 // The caller has already gotten all the locks we need.
910 const char* no_lock_arg = "--no-lock-output";
911 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
David Brazdilfc5934e2016-09-08 11:55:48 +0100912 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
913 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
914 ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
915 "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
916 PATCHOAT_BIN, instruction_set,
917 input_oat_fd, input_oat_file_name,
918 input_vdex_fd, input_vdex_file_name,
919 out_oat_fd, output_oat_file_name,
920 out_vdex_fd, output_vdex_file_name);
Alex Light7365a102014-07-21 12:23:48 -0700921
922 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
David Brazdilfc5934e2016-09-08 11:55:48 +0100923 char* argv[9];
Alex Light7365a102014-07-21 12:23:48 -0700924 argv[0] = (char*) PATCHOAT_BIN;
925 argv[1] = (char*) patched_image_location_arg;
926 argv[2] = (char*) no_lock_arg;
927 argv[3] = instruction_set_arg;
David Brazdilfc5934e2016-09-08 11:55:48 +0100928 argv[4] = input_oat_fd_arg;
929 argv[5] = input_vdex_fd_arg;
930 argv[6] = output_oat_fd_arg;
931 argv[7] = output_vdex_fd_arg;
932 argv[8] = NULL;
Alex Light7365a102014-07-21 12:23:48 -0700933
934 execv(PATCHOAT_BIN, (char* const *)argv);
935 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
936}
937
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +0000938static 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 +0100939 const char* input_file_name, const char* output_file_name, int swap_fd,
940 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
941 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
Calin Juravle8fc73152014-08-19 18:48:50 +0100942 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
943
944 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
945 ALOGE("Instruction set %s longer than max length of %d",
946 instruction_set, MAX_INSTRUCTION_SET_LEN);
947 return;
948 }
949
Andreas Gampe02d0de52015-11-11 20:43:16 -0800950 char dex2oat_Xms_flag[kPropertyValueMax];
951 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700952
Andreas Gampe02d0de52015-11-11 20:43:16 -0800953 char dex2oat_Xmx_flag[kPropertyValueMax];
954 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700955
Andreas Gampe02d0de52015-11-11 20:43:16 -0800956 char dex2oat_threads_buf[kPropertyValueMax];
957 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -0700958 ? "dalvik.vm.dex2oat-threads"
959 : "dalvik.vm.boot-dex2oat-threads",
960 dex2oat_threads_buf,
961 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800962 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700963 if (have_dex2oat_threads_flag) {
964 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
965 }
966
Andreas Gampe02d0de52015-11-11 20:43:16 -0800967 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +0100968 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800969 char dex2oat_isa_features[kPropertyValueMax];
970 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +0100971 dex2oat_isa_features, NULL) > 0;
972
Andreas Gampe02d0de52015-11-11 20:43:16 -0800973 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -0800974 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800975 char dex2oat_isa_variant[kPropertyValueMax];
976 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -0800977 dex2oat_isa_variant, NULL) > 0;
978
neo.chae14e084d2015-01-07 18:46:13 +0900979 const char *dex2oat_norelocation = "-Xnorelocate";
980 bool have_dex2oat_relocation_skip_flag = false;
981
Andreas Gampe02d0de52015-11-11 20:43:16 -0800982 char dex2oat_flags[kPropertyValueMax];
983 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700984 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -0800985 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
986
Brian Carlstrom538998f2014-07-30 14:37:11 -0700987 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -0800988 char vold_decrypt[kPropertyValueMax];
989 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700990 bool skip_compilation = (have_vold_decrypt &&
991 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
992 (strcmp(vold_decrypt, "1") == 0)));
993
Calin Juravle6a1648e2016-02-01 12:12:16 +0000994 bool generate_debug_info = property_get_bool("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700995
Mathieu Chartier416fa122016-02-03 13:48:16 -0800996 char app_image_format[kPropertyValueMax];
997 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
998 bool have_app_image_format =
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -0800999 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
Mathieu Chartier416fa122016-02-03 13:48:16 -08001000 if (have_app_image_format) {
1001 sprintf(image_format_arg, "--image-format=%s", app_image_format);
1002 }
1003
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001004 char dex2oat_large_app_threshold[kPropertyValueMax];
1005 bool have_dex2oat_large_app_threshold =
1006 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
1007 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
1008 if (have_dex2oat_large_app_threshold) {
1009 sprintf(dex2oat_large_app_threshold_arg,
1010 "--very-large-app-threshold=%s",
1011 dex2oat_large_app_threshold);
1012 }
1013
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001014 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001015
Brian Carlstrom53e07762014-06-27 14:15:19 -07001016 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -07001017
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001018 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +01001019
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001020 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
1021 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001022 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
1023 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001024 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -07001025 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +01001026 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001027 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
1028 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
1029 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
1030 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
1031 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -08001032 bool have_dex2oat_swap_fd = false;
1033 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001034 bool have_dex2oat_image_fd = false;
1035 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001036
1037 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
1038 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001039 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
1040 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001041 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
1042 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +01001043 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -08001044 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +01001045 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -08001046 if (swap_fd >= 0) {
1047 have_dex2oat_swap_fd = true;
1048 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
1049 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001050 if (image_fd >= 0) {
1051 have_dex2oat_image_fd = true;
1052 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
1053 }
Calin Juravle57c69c32014-06-06 14:42:16 +01001054
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001055 if (have_dex2oat_Xms_flag) {
1056 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
1057 }
1058 if (have_dex2oat_Xmx_flag) {
1059 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
1060 }
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001061
1062 // Compute compiler filter.
1063
1064 bool have_dex2oat_compiler_filter_flag;
Brian Carlstrom538998f2014-07-30 14:37:11 -07001065 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -07001066 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -07001067 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +09001068 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +01001069 } else if (vm_safe_mode) {
1070 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +01001071 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001072 } else if (compiler_filter != nullptr &&
1073 strlen(compiler_filter) + strlen("--compiler-filter=") <
1074 arraysize(dex2oat_compiler_filter_arg)) {
1075 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
Mathieu Chartierd4a7b452015-03-20 15:39:47 -07001076 have_dex2oat_compiler_filter_flag = true;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001077 } else {
1078 char dex2oat_compiler_filter_flag[kPropertyValueMax];
1079 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
1080 dex2oat_compiler_filter_flag, NULL) > 0;
1081 if (have_dex2oat_compiler_filter_flag) {
1082 sprintf(dex2oat_compiler_filter_arg,
1083 "--compiler-filter=%s",
1084 dex2oat_compiler_filter_flag);
1085 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001086 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001087
Andreas Gampe598c25e2015-03-03 09:15:06 -08001088 // Check whether all apps should be compiled debuggable.
1089 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001090 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -08001091 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -08001092 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -08001093 (prop_buf[0] == '1');
1094 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001095 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
1096 if (profile_fd != -1) {
1097 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001098 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001099
Calin Juravle6a1648e2016-02-01 12:12:16 +00001100
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001101 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +01001102
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001103 const char* argv[9 // program name, mandatory arguments and the final NULL
neo.chae14e084d2015-01-07 18:46:13 +09001104 + (have_dex2oat_isa_variant ? 1 : 0)
1105 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001106 + (have_dex2oat_Xms_flag ? 2 : 0)
1107 + (have_dex2oat_Xmx_flag ? 2 : 0)
1108 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001109 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001110 + (have_dex2oat_swap_fd ? 1 : 0)
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001111 + (have_dex2oat_image_fd ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +09001112 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +01001113 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -08001114 + (debuggable ? 1 : 0)
Mathieu Chartier416fa122016-02-03 13:48:16 -08001115 + (have_app_image_format ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +02001116 + dex2oat_flags_count
Jeff Haob63d91f2016-03-16 15:59:25 -07001117 + (profile_fd == -1 ? 0 : 1)
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001118 + (shared_libraries != nullptr ? 4 : 0)
1119 + (have_dex2oat_large_app_threshold ? 1 : 0)];
Calin Juravle4fdff462014-06-06 16:58:43 +01001120 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +09001121 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +01001122 argv[i++] = zip_fd_arg;
1123 argv[i++] = zip_location_arg;
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001124 argv[i++] = input_vdex_fd_arg;
1125 argv[i++] = output_vdex_fd_arg;
Calin Juravle4fdff462014-06-06 16:58:43 +01001126 argv[i++] = oat_fd_arg;
1127 argv[i++] = oat_location_arg;
1128 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -08001129 if (have_dex2oat_isa_variant) {
1130 argv[i++] = instruction_set_variant_arg;
1131 }
Calin Juravle8fc73152014-08-19 18:48:50 +01001132 if (have_dex2oat_isa_features) {
1133 argv[i++] = instruction_set_features_arg;
1134 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001135 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001136 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001137 argv[i++] = dex2oat_Xms_arg;
1138 }
1139 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +09001140 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001141 argv[i++] = dex2oat_Xmx_arg;
1142 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -07001143 if (have_dex2oat_compiler_filter_flag) {
1144 argv[i++] = dex2oat_compiler_filter_arg;
1145 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -07001146 if (have_dex2oat_threads_flag) {
1147 argv[i++] = dex2oat_threads_arg;
1148 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001149 if (have_dex2oat_swap_fd) {
1150 argv[i++] = dex2oat_swap_fd;
1151 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001152 if (have_dex2oat_image_fd) {
1153 argv[i++] = dex2oat_image_fd;
1154 }
David Srbecky528c8dd2015-05-28 16:55:50 +01001155 if (generate_debug_info) {
1156 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -07001157 }
Andreas Gampe598c25e2015-03-03 09:15:06 -08001158 if (debuggable) {
1159 argv[i++] = "--debuggable";
1160 }
Mathieu Chartier416fa122016-02-03 13:48:16 -08001161 if (have_app_image_format) {
1162 argv[i++] = image_format_arg;
1163 }
Andreas Gampea5cc10a2016-07-11 15:19:31 -07001164 if (have_dex2oat_large_app_threshold) {
1165 argv[i++] = dex2oat_large_app_threshold_arg;
1166 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001167 if (dex2oat_flags_count) {
1168 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +01001169 }
neo.chae14e084d2015-01-07 18:46:13 +09001170 if (have_dex2oat_relocation_skip_flag) {
1171 argv[i++] = RUNTIME_ARG;
1172 argv[i++] = dex2oat_norelocation;
1173 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001174 if (profile_fd != -1) {
1175 argv[i++] = profile_arg;
Calin Juravle60a794d2015-12-24 12:36:41 +02001176 }
Jeff Haob63d91f2016-03-16 15:59:25 -07001177 if (shared_libraries != nullptr) {
1178 argv[i++] = RUNTIME_ARG;
1179 argv[i++] = "-classpath";
1180 argv[i++] = RUNTIME_ARG;
1181 argv[i++] = shared_libraries;
1182 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -07001183 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +01001184 argv[i] = NULL;
1185
neo.chae14e084d2015-01-07 18:46:13 +09001186 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +07001187 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001188}
1189
Andreas Gampee1c01352014-12-10 16:41:11 -08001190/*
Andreas Gampec968c012015-07-16 15:55:41 -07001191 * Whether dexopt should use a swap file when compiling an APK.
1192 *
1193 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
1194 * itself, anyways).
1195 *
1196 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
1197 *
1198 * Otherwise, return true if this is a low-mem device.
1199 *
1200 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -08001201 */
Andreas Gampec968c012015-07-16 15:55:41 -07001202static bool kAlwaysProvideSwapFile = false;
1203static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -08001204
1205static bool ShouldUseSwapFileForDexopt() {
1206 if (kAlwaysProvideSwapFile) {
1207 return true;
1208 }
1209
Andreas Gampec968c012015-07-16 15:55:41 -07001210 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -08001211 char dex2oat_prop_buf[kPropertyValueMax];
1212 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -07001213 if (strcmp(dex2oat_prop_buf, "true") == 0) {
1214 return true;
1215 } else {
1216 return false;
1217 }
1218 }
1219
1220 // Shortcut for default value. This is an implementation optimization for the process sketched
1221 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
1222 // as low-mem is never returning false. The compiler will optimize this away if it can.
1223 if (kDefaultProvideSwapFile) {
1224 return true;
1225 }
1226
Calin Juravle6a1648e2016-02-01 12:12:16 +00001227 bool is_low_mem = property_get_bool("ro.config.low_ram");
Andreas Gampec968c012015-07-16 15:55:41 -07001228 if (is_low_mem) {
1229 return true;
1230 }
1231
1232 // Default value must be false here.
1233 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -08001234}
1235
Andreas Gampe94dd3d32015-09-14 16:33:11 -07001236static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
1237 if (set_to_bg) {
1238 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
1239 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
1240 exit(70);
1241 }
1242 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
1243 ALOGE("setpriority failed: %s\n", strerror(errno));
1244 exit(71);
1245 }
1246 }
1247}
1248
Calin Juravle6a1648e2016-02-01 12:12:16 +00001249static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001250 for (size_t i = 0; i < fds.size(); i++) {
1251 if (close(fds[i]) != 0) {
1252 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
1253 }
1254 }
1255}
1256
Calin Juravle6a1648e2016-02-01 12:12:16 +00001257static fd_t open_profile_dir(const std::string& profile_dir) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001258 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
1259 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
1260 if (profile_dir_fd < 0) {
Narayan Kamath2e063af2016-05-02 09:47:49 +01001261 // In a multi-user environment, these directories can be created at
1262 // different points and it's possible we'll attempt to open a profile
1263 // dir before it exists.
1264 if (errno != ENOENT) {
1265 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
1266 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001267 }
1268 return profile_dir_fd;
1269}
1270
1271static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
1272 fd_t profile_dir_fd = open_profile_dir(profile_dir);
1273 if (profile_dir_fd < 0) {
1274 return -1;
1275 }
1276
1277 fd_t profile_fd = -1;
1278 std::string profile_file = create_primary_profile(profile_dir);
1279
1280 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
1281 if (profile_fd == -1) {
1282 // It's not an error if the profile file does not exist.
Calin Juravle60a794d2015-12-24 12:36:41 +02001283 if (errno != ENOENT) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001284 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
1285 }
1286 }
1287 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
1288 if (close(profile_dir_fd) != 0) {
1289 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
1290 }
1291 return profile_fd;
1292}
1293
1294static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
1295 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
1296 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
1297}
1298
1299static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
1300 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
1301 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
1302 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
1303 if (fd < 0) {
1304 return -1;
1305 }
1306 if (read_write) {
1307 // Fix the owner.
1308 if (fchown(fd, uid, uid) < 0) {
1309 close(fd);
Calin Juravle60a794d2015-12-24 12:36:41 +02001310 return -1;
1311 }
1312 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001313 return fd;
Calin Juravle60a794d2015-12-24 12:36:41 +02001314}
1315
Calin Juravle6a1648e2016-02-01 12:12:16 +00001316static void open_profile_files(uid_t uid, const char* pkgname,
1317 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
1318 // Open the reference profile in read-write mode as profman might need to save the merge.
1319 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
Calin Juravle60a794d2015-12-24 12:36:41 +02001320 if (*reference_profile_fd < 0) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001321 // We can't access the reference profile file.
Calin Juravle60a794d2015-12-24 12:36:41 +02001322 return;
1323 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001324
1325 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1326 for (auto user : users) {
1327 fd_t profile_fd = open_primary_profile_file(user, pkgname);
1328 // Add to the lists only if both fds are valid.
1329 if (profile_fd >= 0) {
1330 profiles_fd->push_back(profile_fd);
1331 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001332 }
1333}
1334
Calin Juravle6a1648e2016-02-01 12:12:16 +00001335static void drop_capabilities(uid_t uid) {
1336 if (setgid(uid) != 0) {
1337 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
1338 exit(64);
1339 }
1340 if (setuid(uid) != 0) {
1341 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
1342 exit(65);
1343 }
1344 // drop capabilities
1345 struct __user_cap_header_struct capheader;
1346 struct __user_cap_data_struct capdata[2];
1347 memset(&capheader, 0, sizeof(capheader));
1348 memset(&capdata, 0, sizeof(capdata));
1349 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1350 if (capset(&capheader, &capdata[0]) < 0) {
1351 ALOGE("capset failed: %s\n", strerror(errno));
1352 exit(66);
1353 }
1354}
Calin Juravle60a794d2015-12-24 12:36:41 +02001355
Calin Juravle6a1648e2016-02-01 12:12:16 +00001356static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
1357static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
1358static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
1359static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
1360static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
1361
David Sehr6727c2d2016-05-17 16:06:22 -07001362static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001363 static const size_t MAX_INT_LEN = 32;
1364 static const char* PROFMAN_BIN = "/system/bin/profman";
1365
1366 std::vector<std::string> profile_args(profiles_fd.size());
1367 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
1368 for (size_t k = 0; k < profiles_fd.size(); k++) {
1369 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
1370 profile_args[k].assign(profile_buf);
1371 }
1372 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
1373 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
1374
1375 // program name, reference profile fd, the final NULL and the profile fds
1376 const char* argv[3 + profiles_fd.size()];
1377 int i = 0;
1378 argv[i++] = PROFMAN_BIN;
1379 argv[i++] = reference_profile_arg;
1380 for (size_t k = 0; k < profile_args.size(); k++) {
1381 argv[i++] = profile_args[k].c_str();
1382 }
1383 // Do not add after dex2oat_flags, they should override others for debugging.
1384 argv[i] = NULL;
1385
1386 execv(PROFMAN_BIN, (char * const *)argv);
1387 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1388 exit(68); /* only get here on exec failure */
1389}
1390
1391// Decides if profile guided compilation is needed or not based on existing profiles.
1392// Returns true if there is enough information in the current profiles that worth
1393// a re-compilation of the package.
1394// If the return value is true all the current profiles would have been merged into
1395// the reference profiles accessible with open_reference_profile().
1396static bool analyse_profiles(uid_t uid, const char* pkgname) {
1397 std::vector<fd_t> profiles_fd;
1398 fd_t reference_profile_fd = -1;
1399 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
1400 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
1401 // Skip profile guided compilation because no profiles were found.
1402 // Or if the reference profile info couldn't be opened.
1403 close_all_fds(profiles_fd, "profiles_fd");
1404 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
1405 PLOG(WARNING) << "Failed to close fd for reference profile";
1406 }
1407 return false;
1408 }
1409
David Sehr6727c2d2016-05-17 16:06:22 -07001410 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001411
1412 pid_t pid = fork();
1413 if (pid == 0) {
1414 /* child -- drop privileges before continuing */
1415 drop_capabilities(uid);
David Sehr6727c2d2016-05-17 16:06:22 -07001416 run_profman_merge(profiles_fd, reference_profile_fd);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001417 exit(68); /* only get here on exec failure */
1418 }
1419 /* parent */
1420 int return_code = wait_child(pid);
1421 bool need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001422 bool should_clear_current_profiles = false;
1423 bool should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001424 if (!WIFEXITED(return_code)) {
1425 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
1426 } else {
1427 return_code = WEXITSTATUS(return_code);
1428 switch (return_code) {
1429 case PROFMAN_BIN_RETURN_CODE_COMPILE:
1430 need_to_compile = true;
Calin Juravlecea31412016-03-29 15:36:34 +01001431 should_clear_current_profiles = true;
1432 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001433 break;
1434 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
1435 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001436 should_clear_current_profiles = false;
1437 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001438 break;
1439 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
1440 LOG(WARNING) << "Bad profiles for package " << pkgname;
1441 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001442 should_clear_current_profiles = true;
1443 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001444 break;
1445 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
1446 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
1447 // Temporary IO problem (e.g. locking). Ignore but log a warning.
1448 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
1449 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001450 should_clear_current_profiles = false;
1451 should_clear_reference_profile = false;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001452 break;
1453 default:
1454 // Unknown return code or error. Unlink profiles.
1455 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
1456 << ": " << return_code;
1457 need_to_compile = false;
Calin Juravlecea31412016-03-29 15:36:34 +01001458 should_clear_current_profiles = true;
1459 should_clear_reference_profile = true;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001460 break;
Calin Juravle60a794d2015-12-24 12:36:41 +02001461 }
1462 }
Calin Juravle6a1648e2016-02-01 12:12:16 +00001463 close_all_fds(profiles_fd, "profiles_fd");
1464 if (close(reference_profile_fd) != 0) {
1465 PLOG(WARNING) << "Failed to close fd for reference profile";
1466 }
Calin Juravlecea31412016-03-29 15:36:34 +01001467 if (should_clear_current_profiles) {
1468 clear_current_profiles(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001469 }
Calin Juravlecea31412016-03-29 15:36:34 +01001470 if (should_clear_reference_profile) {
1471 clear_reference_profile(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001472 }
1473 return need_to_compile;
Calin Juravle60a794d2015-12-24 12:36:41 +02001474}
1475
David Sehr6727c2d2016-05-17 16:06:22 -07001476static void run_profman_dump(const std::vector<fd_t>& profile_fds,
1477 fd_t reference_profile_fd,
David Sehr40e566d2016-06-02 10:42:12 -07001478 const std::vector<std::string>& dex_locations,
1479 const std::vector<fd_t>& apk_fds,
David Sehr6727c2d2016-05-17 16:06:22 -07001480 fd_t output_fd) {
David Sehr40e566d2016-06-02 10:42:12 -07001481 std::vector<std::string> profman_args;
David Sehr6727c2d2016-05-17 16:06:22 -07001482 static const char* PROFMAN_BIN = "/system/bin/profman";
David Sehr40e566d2016-06-02 10:42:12 -07001483 profman_args.push_back(PROFMAN_BIN);
1484 profman_args.push_back("--dump-only");
1485 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
1486 if (reference_profile_fd != -1) {
1487 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
1488 reference_profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001489 }
1490 for (fd_t profile_fd : profile_fds) {
David Sehr40e566d2016-06-02 10:42:12 -07001491 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
David Sehr6727c2d2016-05-17 16:06:22 -07001492 }
David Sehr40e566d2016-06-02 10:42:12 -07001493 for (const std::string& dex_location : dex_locations) {
1494 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
David Sehr6727c2d2016-05-17 16:06:22 -07001495 }
David Sehr40e566d2016-06-02 10:42:12 -07001496 for (fd_t apk_fd : apk_fds) {
1497 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
1498 }
1499 const char **argv = new const char*[profman_args.size() + 1];
1500 size_t i = 0;
1501 for (const std::string& profman_arg : profman_args) {
1502 argv[i++] = profman_arg.c_str();
David Sehr6727c2d2016-05-17 16:06:22 -07001503 }
1504 argv[i] = NULL;
David Sehr6727c2d2016-05-17 16:06:22 -07001505
1506 execv(PROFMAN_BIN, (char * const *)argv);
1507 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
1508 exit(68); /* only get here on exec failure */
1509}
1510
David Sehr40e566d2016-06-02 10:42:12 -07001511static const char* get_location_from_path(const char* path) {
1512 static constexpr char kLocationSeparator = '/';
1513 const char *location = strrchr(path, kLocationSeparator);
1514 if (location == NULL) {
1515 return path;
1516 } else {
1517 // Skip the separator character.
1518 return location + 1;
1519 }
1520}
1521
David Sehr6727c2d2016-05-17 16:06:22 -07001522// Dumps the contents of a profile file, using pkgname's dex files for pretty
1523// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001524binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1525 const std::string& codePaths, bool* _aidl_return) {
1526 ENFORCE_UID(AID_SYSTEM);
1527
1528 const char* pkgname = packageName.c_str();
1529 const char* code_path_string = codePaths.c_str();
1530
David Sehr6727c2d2016-05-17 16:06:22 -07001531 std::vector<fd_t> profile_fds;
1532 fd_t reference_profile_fd = -1;
1533 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
1534
1535 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
1536
1537 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
1538
1539 const bool has_reference_profile = (reference_profile_fd != -1);
1540 const bool has_profiles = !profile_fds.empty();
1541
1542 if (!has_reference_profile && !has_profiles) {
1543 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001544 *_aidl_return = false;
1545 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001546 }
1547
David Sehr40e566d2016-06-02 10:42:12 -07001548 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 -07001549 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
1550 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001551 *_aidl_return = false;
1552 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001553 }
David Sehr40e566d2016-06-02 10:42:12 -07001554 std::vector<std::string> code_full_paths = base::Split(code_path_string, ";");
1555 std::vector<std::string> dex_locations;
1556 std::vector<fd_t> apk_fds;
1557 for (const std::string& code_full_path : code_full_paths) {
1558 const char* full_path = code_full_path.c_str();
1559 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
1560 if (apk_fd == -1) {
1561 ALOGE("installd cannot open '%s'\n", full_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001562 *_aidl_return = false;
1563 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001564 }
David Sehr40e566d2016-06-02 10:42:12 -07001565 dex_locations.push_back(get_location_from_path(full_path));
1566 apk_fds.push_back(apk_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001567 }
1568
1569 pid_t pid = fork();
1570 if (pid == 0) {
1571 /* child -- drop privileges before continuing */
1572 drop_capabilities(uid);
David Sehr40e566d2016-06-02 10:42:12 -07001573 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
1574 apk_fds, output_fd);
David Sehr6727c2d2016-05-17 16:06:22 -07001575 exit(68); /* only get here on exec failure */
1576 }
1577 /* parent */
David Sehr40e566d2016-06-02 10:42:12 -07001578 close_all_fds(apk_fds, "apk_fds");
David Sehr6727c2d2016-05-17 16:06:22 -07001579 close_all_fds(profile_fds, "profile_fds");
1580 if (close(reference_profile_fd) != 0) {
1581 PLOG(WARNING) << "Failed to close fd for reference profile";
1582 }
1583 int return_code = wait_child(pid);
1584 if (!WIFEXITED(return_code)) {
1585 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1586 << return_code;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001587 *_aidl_return = false;
1588 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001589 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001590 *_aidl_return = true;
1591 return binder::Status::ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001592}
1593
David Brazdilfc5934e2016-09-08 11:55:48 +01001594static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1595 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
Andreas Gampe89b008d2016-06-03 21:13:50 -07001596 if (EndsWith(oat_path, ".dex")) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001597 std::string new_path = oat_path;
1598 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
1599 CHECK(EndsWith(new_path, new_ext.c_str()));
1600 return new_path;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001601 }
Andreas Gampe89b008d2016-06-03 21:13:50 -07001602
1603 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1604 // case (where the base name will have an extension for the B artifact).
1605 size_t odex_pos = oat_path.rfind(".odex");
1606 if (odex_pos != std::string::npos) {
David Brazdilfc5934e2016-09-08 11:55:48 +01001607 std::string new_path = oat_path;
1608 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1609 CHECK_NE(new_path.find(new_ext), std::string::npos);
1610 return new_path;
Andreas Gampe89b008d2016-06-03 21:13:50 -07001611 }
1612
1613 // Don't know how to handle this.
1614 return "";
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001615}
1616
David Brazdilfc5934e2016-09-08 11:55:48 +01001617// Translate the given oat path to an art (app image) path. An empty string
1618// denotes an error.
1619static std::string create_image_filename(const std::string& oat_path) {
1620 return replace_file_extension(oat_path, ".art");
1621}
1622
1623// Translate the given oat path to a vdex path. An empty string denotes an error.
1624static std::string create_vdex_filename(const std::string& oat_path) {
1625 return replace_file_extension(oat_path, ".vdex");
1626}
1627
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001628static bool add_extension_to_file_name(char* file_name, const char* extension) {
1629 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1630 return false;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001631 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001632 strcat(file_name, extension);
1633 return true;
1634}
1635
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001636static int open_output_file(const char* file_name, bool recreate, int permissions) {
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001637 int flags = O_RDWR | O_CREAT;
1638 if (recreate) {
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001639 if (unlink(file_name) < 0) {
1640 if (errno != ENOENT) {
1641 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1642 }
1643 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001644 flags |= O_EXCL;
1645 }
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001646 return open(file_name, flags, permissions);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001647}
1648
1649static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1650 if (fchmod(fd,
1651 S_IRUSR|S_IWUSR|S_IRGRP |
1652 (is_public ? S_IROTH : 0)) < 0) {
1653 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1654 return false;
1655 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1656 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1657 return false;
1658 }
1659 return true;
1660}
1661
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001662static bool IsOutputDalvikCache(const char* oat_dir) {
1663 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1664 // into '!'. Play it safe by handling it both.
1665 // TODO: ensure we never get null.
1666 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1667 return oat_dir == nullptr || oat_dir[0] == '!';
1668}
1669
Calin Juravle6a1648e2016-02-01 12:12:16 +00001670static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
David Brazdilfc5934e2016-09-08 11:55:48 +01001671 const char* oat_dir, /*out*/ char* out_oat_path) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001672 // Early best-effort check whether we can fit the the path into our buffers.
1673 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1674 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1675 // extension to the cache path (5 bytes).
1676 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
1677 ALOGE("apk_path too long '%s'\n", apk_path);
1678 return false;
1679 }
1680
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001681 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001682 if (validate_apk_path(oat_dir)) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001683 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +00001684 return false;
1685 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001686 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001687 return false;
1688 }
1689 } else {
David Brazdilfc5934e2016-09-08 11:55:48 +01001690 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001691 return false;
1692 }
1693 }
1694 return true;
1695}
1696
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001697// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001698binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1699 bool* _aidl_return) {
1700 ENFORCE_UID(AID_SYSTEM);
1701 const char* pkgname = packageName.c_str();
1702 *_aidl_return = analyse_profiles(uid, pkgname);
1703 return binder::Status::ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001704}
1705
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001706// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1707// on destruction. It will also run the given cleanup (unless told not to) after closing.
1708//
1709// Usage example:
1710//
1711// Dex2oatFileWrapper<std::function<void ()>> file(open(...),
1712// [name]() {
1713// unlink(name.c_str());
1714// });
1715// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1716// wrapper if captured as a reference.
1717//
1718// if (file.get() == -1) {
1719// // Error opening...
1720// }
1721//
1722// ...
1723// if (error) {
1724// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1725// // and delete the file (after the fd is closed).
1726// return -1;
1727// }
1728//
1729// (Success case)
1730// file.SetCleanup(false);
1731// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1732// // (leaving the file around; after the fd is closed).
1733//
1734template <typename Cleanup>
1735class Dex2oatFileWrapper {
1736 public:
1737 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
1738 }
1739
1740 Dex2oatFileWrapper(int value, Cleanup cleanup)
1741 : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
1742
1743 ~Dex2oatFileWrapper() {
1744 reset(-1);
1745 }
1746
1747 int get() {
1748 return value_;
1749 }
1750
1751 void SetCleanup(bool cleanup) {
1752 do_cleanup_ = cleanup;
1753 }
1754
1755 void reset(int new_value) {
1756 if (value_ >= 0) {
1757 close(value_);
1758 }
1759 if (do_cleanup_ && cleanup_ != nullptr) {
1760 cleanup_();
1761 }
1762
1763 value_ = new_value;
1764 }
1765
1766 void reset(int new_value, Cleanup new_cleanup) {
1767 if (value_ >= 0) {
1768 close(value_);
1769 }
1770 if (do_cleanup_ && cleanup_ != nullptr) {
1771 cleanup_();
1772 }
1773
1774 value_ = new_value;
1775 cleanup_ = new_cleanup;
1776 }
1777
1778 private:
1779 int value_;
1780 Cleanup cleanup_;
1781 bool do_cleanup_;
1782};
1783
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001784// TODO: eventually move dexopt() implementation into dexopt.cpp
Calin Juravle60a794d2015-12-24 12:36:41 +02001785int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001786 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1787 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
Calin Juravledb0326a2016-02-23 19:06:45 +00001788 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
Todd Kennedy76e767c2015-09-25 07:47:47 -07001789 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1790 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1791 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001792 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1793
1794 CHECK(pkgname != nullptr);
1795 CHECK(pkgname[0] != 0);
1796
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001797 // Public apps should not be compiled with profile information ever. Same goes for the special
1798 // package '*' used for the system server.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001799 Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001800 if (!is_public && pkgname[0] != '*') {
1801 // Open reference profile in read only mode as dex2oat does not get write permissions.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001802 const std::string pkgname_str(pkgname);
1803 reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1804 [pkgname_str]() {
1805 clear_reference_profile(pkgname_str.c_str());
1806 });
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001807 // Note: it's OK to not find a profile here.
Calin Juravle60a794d2015-12-24 12:36:41 +02001808 }
Todd Kennedy76e767c2015-09-25 07:47:47 -07001809
Todd Kennedye296e002015-11-16 14:41:36 -08001810 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -07001811 LOG_FATAL("dexopt flags contains unknown fields\n");
1812 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001813
David Brazdilfc5934e2016-09-08 11:55:48 +01001814 char out_oat_path[PKG_PATH_MAX];
1815 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
Calin Juravle6a1648e2016-02-01 12:12:16 +00001816 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001817 }
1818
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001819 const char *input_file;
1820 char in_odex_path[PKG_PATH_MAX];
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001821 int dexopt_action = abs(dexopt_needed);
1822 bool is_odex_location = dexopt_needed < 0;
1823 switch (dexopt_action) {
1824 case DEX2OAT_FROM_SCRATCH:
1825 case DEX2OAT_FOR_BOOT_IMAGE:
1826 case DEX2OAT_FOR_FILTER:
1827 case DEX2OAT_FOR_RELOCATION:
Richard Uhlerc92fb622015-03-26 15:47:38 -07001828 input_file = apk_path;
1829 break;
1830
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001831 case PATCHOAT_FOR_RELOCATION:
1832 if (is_odex_location) {
1833 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1834 return -1;
1835 }
1836 input_file = in_odex_path;
1837 } else {
1838 input_file = out_oat_path;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001839 }
Richard Uhlerc92fb622015-03-26 15:47:38 -07001840 break;
1841
1842 default:
1843 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001844 return 72;
Alex Light7365a102014-07-21 12:23:48 -07001845 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001846
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001847 struct stat input_stat;
Alex Light7365a102014-07-21 12:23:48 -07001848 memset(&input_stat, 0, sizeof(input_stat));
1849 stat(input_file, &input_stat);
1850
David Brazdilfc5934e2016-09-08 11:55:48 +01001851 // Open the input file. If running dex2oat, `input_file` is the APK. If running
1852 // patchoat, it is the OAT file to be relocated.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001853 base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1854 if (input_fd.get() < 0) {
Alex Light7365a102014-07-21 12:23:48 -07001855 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001856 return -1;
1857 }
1858
David Brazdilfc5934e2016-09-08 11:55:48 +01001859 // Create the output OAT file.
1860 const std::string out_oat_path_str(out_oat_path);
1861 Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1862 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1863 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1864 if (out_oat_fd.get() < 0) {
1865 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001866 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001867 }
David Brazdilfc5934e2016-09-08 11:55:48 +01001868 if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1869 return -1;
1870 }
1871
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001872 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1873 // unlink the old one.
1874 base::unique_fd in_vdex_fd;
1875 std::string in_vdex_path_str;
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001876 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001877 // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1878 in_vdex_path_str = create_vdex_filename(input_file);
1879 if (in_vdex_path_str.empty()) {
1880 ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1881 return -1;
1882 }
1883 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1884 if (in_vdex_fd.get() < 0) {
1885 ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
1886 in_vdex_path_str.c_str(), strerror(errno));
1887 return -1;
1888 }
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001889 } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
1890 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1891 const char* path = nullptr;
1892 if (is_odex_location) {
1893 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1894 path = in_odex_path;
1895 } else {
1896 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
1897 return -1;
1898 }
1899 } else {
1900 path = out_oat_path;
1901 }
1902 in_vdex_path_str = create_vdex_filename(path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001903 if (in_vdex_path_str.empty()) {
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001904 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001905 return -1;
1906 }
1907 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00001908 }
1909
David Brazdilfc5934e2016-09-08 11:55:48 +01001910 // Infer the name of the output VDEX and create it.
1911 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
1912 if (out_vdex_path_str.empty()) {
1913 return -1;
1914 }
1915 Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
1916 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1917 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1918 if (out_vdex_fd.get() < 0) {
1919 ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
1920 return -1;
1921 }
1922 if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
1923 uid, out_vdex_path_str.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001924 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001925 }
1926
Andreas Gampee1c01352014-12-10 16:41:11 -08001927 // Create a swap file if necessary.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001928 base::unique_fd swap_fd;
Richard Uhlerc92fb622015-03-26 15:47:38 -07001929 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001930 // Make sure there really is enough space.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001931 char swap_file_name[PKG_PATH_MAX];
David Brazdilfc5934e2016-09-08 11:55:48 +01001932 strcpy(swap_file_name, out_oat_path);
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001933 if (add_extension_to_file_name(swap_file_name, ".swap")) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001934 swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001935 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001936 if (swap_fd.get() < 0) {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001937 // Could not create swap file. Optimistically go on and hope that we can compile
1938 // without it.
1939 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08001940 } else {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001941 // Immediately unlink. We don't really want to hit flash.
Narayan Kamath5006f3a2016-04-07 10:42:41 +01001942 if (unlink(swap_file_name) < 0) {
1943 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1944 }
Andreas Gampee1c01352014-12-10 16:41:11 -08001945 }
1946 }
Dave Allisond9370732014-01-30 14:19:23 -08001947
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001948 // Avoid generating an app image for extract only since it will not contain any classes.
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001949 Dex2oatFileWrapper<std::function<void ()>> image_fd;
David Brazdilfc5934e2016-09-08 11:55:48 +01001950 const std::string image_path = create_image_filename(out_oat_path);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00001951 if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001952 char app_image_format[kPropertyValueMax];
1953 bool have_app_image_format =
1954 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1955 // Use app images only if it is enabled (by a set image format) and we are compiling
1956 // profile-guided (so the app image doesn't conservatively contain all classes).
1957 if (profile_guided && have_app_image_format) {
1958 // Recreate is true since we do not want to modify a mapped image. If the app is
1959 // already running and we modify the image file, it can cause crashes (b/27493510).
Andreas Gampe89b008d2016-06-03 21:13:50 -07001960 image_fd.reset(open_output_file(image_path.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001961 true /*recreate*/,
1962 0600 /*permissions*/),
Andreas Gampe89b008d2016-06-03 21:13:50 -07001963 [image_path]() { unlink(image_path.c_str()); }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001964 );
1965 if (image_fd.get() < 0) {
1966 // Could not create application image file. Go on since we can compile without
1967 // it.
1968 LOG(ERROR) << "installd could not create '"
1969 << image_path
1970 << "' for image file during dexopt";
1971 } else if (!set_permissions_and_ownership(image_fd.get(),
1972 is_public,
1973 uid,
Andreas Gampe89b008d2016-06-03 21:13:50 -07001974 image_path.c_str())) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001975 image_fd.reset(-1);
1976 }
1977 }
1978 // If we have a valid image file path but no image fd, explicitly erase the image file.
1979 if (image_fd.get() < 0) {
Andreas Gampe89b008d2016-06-03 21:13:50 -07001980 if (unlink(image_path.c_str()) < 0) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001981 if (errno != ENOENT) {
1982 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1983 }
1984 }
1985 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001986 }
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001987
Alex Light7365a102014-07-21 12:23:48 -07001988 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001989
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001990 pid_t pid = fork();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001991 if (pid == 0) {
1992 /* child -- drop privileges before continuing */
Calin Juravle6a1648e2016-02-01 12:12:16 +00001993 drop_capabilities(uid);
1994
Andreas Gampe13f14192015-09-21 13:21:30 -07001995 SetDex2OatAndPatchOatScheduling(boot_complete);
David Brazdilfc5934e2016-09-08 11:55:48 +01001996 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1997 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
Andreas Gampe6fb5a012016-06-03 16:09:32 -07001998 _exit(67);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001999 }
2000
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002001 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002002 run_patchoat(input_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002003 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002004 out_oat_fd.get(),
2005 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002006 input_file,
David Brazdilfc5934e2016-09-08 11:55:48 +01002007 in_vdex_path_str.c_str(),
2008 out_oat_path,
2009 out_vdex_path_str.c_str(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002010 pkgname,
2011 instruction_set);
Nicolas Geoffray920c60c2016-11-25 11:33:31 +00002012 } else {
David Brazdilaaa1d4e2016-02-05 15:42:01 +00002013 // Pass dex2oat the relative path to the input file.
David Sehr40e566d2016-06-02 10:42:12 -07002014 const char *input_file_name = get_location_from_path(input_file);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002015 run_dex2oat(input_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002016 out_oat_fd.get(),
Nicolas Geoffray53caf0d2016-11-10 10:50:03 +00002017 in_vdex_fd.get(),
David Brazdilfc5934e2016-09-08 11:55:48 +01002018 out_vdex_fd.get(),
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002019 image_fd.get(),
2020 input_file_name,
David Brazdilfc5934e2016-09-08 11:55:48 +01002021 out_oat_path,
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002022 swap_fd.get(),
2023 instruction_set,
2024 compiler_filter,
2025 vm_safe_mode,
2026 debuggable,
2027 boot_complete,
2028 reference_profile_fd.get(),
2029 shared_libraries);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002030 }
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002031 _exit(68); /* only get here on exec failure */
Mike Lockwood94afecf2012-10-24 10:45:23 -07002032 } else {
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002033 int res = wait_child(pid);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002034 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07002035 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002036 } else {
Alex Light7365a102014-07-21 12:23:48 -07002037 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002038 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002039 }
2040 }
2041
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002042 struct utimbuf ut;
Alex Light7365a102014-07-21 12:23:48 -07002043 ut.actime = input_stat.st_atime;
2044 ut.modtime = input_stat.st_mtime;
David Brazdilfc5934e2016-09-08 11:55:48 +01002045 utime(out_oat_path, &ut);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07002046
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002047 // We've been successful, don't delete output.
David Brazdilfc5934e2016-09-08 11:55:48 +01002048 out_oat_fd.SetCleanup(false);
2049 out_vdex_fd.SetCleanup(false);
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002050 image_fd.SetCleanup(false);
2051 reference_profile_fd.SetCleanup(false);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002052
Andreas Gampe6fb5a012016-06-03 16:09:32 -07002053 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002054}
2055
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002056binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2057 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2058 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2059 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
2060 const std::unique_ptr<std::string>& sharedLibraries) {
2061 ENFORCE_UID(AID_SYSTEM);
2062
2063 const char* apk_path = apkPath.c_str();
2064 const char* pkgname = packageName ? packageName->c_str() : "*";
2065 const char* instruction_set = instructionSet.c_str();
2066 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
2067 const char* compiler_filter = compilerFilter.c_str();
2068 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
2069 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
2070
2071 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
2072 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
2073 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
2074}
2075
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002076binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2077 ENFORCE_UID(AID_SYSTEM);
2078 const char* instruction_set = instructionSet.c_str();
2079
2080 char boot_marker_path[PKG_PATH_MAX];
2081 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002082 "%s/%s/%s/.booting",
2083 android_data_dir.path,
2084 DALVIK_CACHE,
2085 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002086
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002087 ALOGV("mark_boot_complete : %s", boot_marker_path);
2088 if (unlink(boot_marker_path) != 0) {
2089 ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path, strerror(errno));
2090 return binder::Status::fromServiceSpecificError(-1);
2091 }
2092 return binder::Status::ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002093}
2094
Mike Lockwood94afecf2012-10-24 10:45:23 -07002095void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
2096 struct stat* statbuf)
2097{
2098 while (path[basepos] != 0) {
2099 if (path[basepos] == '/') {
2100 path[basepos] = 0;
2101 if (lstat(path, statbuf) < 0) {
2102 ALOGV("Making directory: %s\n", path);
2103 if (mkdir(path, mode) == 0) {
2104 chown(path, uid, gid);
2105 } else {
2106 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
2107 }
2108 }
2109 path[basepos] = '/';
2110 basepos++;
2111 }
2112 basepos++;
2113 }
2114}
2115
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002116binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2117 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2118 const std::string& nativeLibPath32, int32_t userId) {
2119 ENFORCE_UID(AID_SYSTEM);
2120 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2121 const char* pkgname = packageName.c_str();
2122 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002123 struct stat s, libStat;
2124 int rc = 0;
2125
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002126 std::string _pkgdir(create_data_user_ce_package_path(uuid_, userId, pkgname));
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002127 std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
2128
2129 const char* pkgdir = _pkgdir.c_str();
2130 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002131
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002132 if (stat(pkgdir, &s) < 0) {
2133 return binder::Status::fromServiceSpecificError(-1);
2134 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002135
2136 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
2137 ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002138 return binder::Status::fromServiceSpecificError(-1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002139 }
2140
2141 if (chmod(pkgdir, 0700) < 0) {
2142 ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
2143 rc = -1;
2144 goto out;
2145 }
2146
2147 if (lstat(libsymlink, &libStat) < 0) {
2148 if (errno != ENOENT) {
2149 ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
2150 rc = -1;
2151 goto out;
2152 }
2153 } else {
2154 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002155 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002156 rc = -1;
2157 goto out;
2158 }
2159 } else if (S_ISLNK(libStat.st_mode)) {
2160 if (unlink(libsymlink) < 0) {
2161 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
2162 rc = -1;
2163 goto out;
2164 }
2165 }
2166 }
2167
2168 if (symlink(asecLibDir, libsymlink) < 0) {
2169 ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
2170 strerror(errno));
2171 rc = -errno;
2172 goto out;
2173 }
2174
2175out:
2176 if (chmod(pkgdir, s.st_mode) < 0) {
2177 ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
2178 rc = -errno;
2179 }
2180
2181 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
2182 ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002183 rc = -errno;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002184 }
2185
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002186 return rc ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002187}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002188
2189static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2190{
2191 static const char *IDMAP_BIN = "/system/bin/idmap";
2192 static const size_t MAX_INT_LEN = 32;
2193 char idmap_str[MAX_INT_LEN];
2194
2195 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
2196
2197 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
2198 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
2199}
2200
2201// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2202// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2203static int flatten_path(const char *prefix, const char *suffix,
2204 const char *overlay_path, char *idmap_path, size_t N)
2205{
2206 if (overlay_path == NULL || idmap_path == NULL) {
2207 return -1;
2208 }
2209 const size_t len_overlay_path = strlen(overlay_path);
2210 // will access overlay_path + 1 further below; requires absolute path
2211 if (len_overlay_path < 2 || *overlay_path != '/') {
2212 return -1;
2213 }
2214 const size_t len_idmap_root = strlen(prefix);
2215 const size_t len_suffix = strlen(suffix);
2216 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2217 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2218 // additions below would cause overflow
2219 return -1;
2220 }
2221 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2222 return -1;
2223 }
2224 memset(idmap_path, 0, N);
2225 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2226 char *ch = idmap_path + len_idmap_root;
2227 while (*ch != '\0') {
2228 if (*ch == '/') {
2229 *ch = '@';
2230 }
2231 ++ch;
2232 }
2233 return 0;
2234}
2235
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002236binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2237 const std::string& overlayApkPath, int32_t uid) {
2238 ENFORCE_UID(AID_SYSTEM);
2239 const char* target_apk = targetApkPath.c_str();
2240 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002241 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2242
2243 int idmap_fd = -1;
2244 char idmap_path[PATH_MAX];
2245
2246 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2247 idmap_path, sizeof(idmap_path)) == -1) {
2248 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2249 goto fail;
2250 }
2251
2252 unlink(idmap_path);
2253 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2254 if (idmap_fd < 0) {
2255 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2256 goto fail;
2257 }
2258 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2259 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2260 goto fail;
2261 }
2262 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2263 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2264 goto fail;
2265 }
2266
2267 pid_t pid;
2268 pid = fork();
2269 if (pid == 0) {
2270 /* child -- drop privileges before continuing */
2271 if (setgid(uid) != 0) {
2272 ALOGE("setgid(%d) failed during idmap\n", uid);
2273 exit(1);
2274 }
2275 if (setuid(uid) != 0) {
2276 ALOGE("setuid(%d) failed during idmap\n", uid);
2277 exit(1);
2278 }
2279 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2280 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2281 exit(1);
2282 }
2283
2284 run_idmap(target_apk, overlay_apk, idmap_fd);
2285 exit(1); /* only if exec call to idmap failed */
2286 } else {
2287 int status = wait_child(pid);
2288 if (status != 0) {
2289 ALOGE("idmap failed, status=0x%04x\n", status);
2290 goto fail;
2291 }
2292 }
2293
2294 close(idmap_fd);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002295 return binder::Status::ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002296fail:
2297 if (idmap_fd >= 0) {
2298 close(idmap_fd);
2299 unlink(idmap_path);
2300 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002301 return binder::Status::fromServiceSpecificError(-1);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002302}
Robert Craige9887e42014-02-20 10:25:56 -05002303
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002304binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2305 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2306 const std::string& seInfo) {
2307 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002308 int res = 0;
Robert Craige9887e42014-02-20 10:25:56 -05002309
Robert Craigda30dc72014-03-27 10:21:12 -04002310 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002311 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002312 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2313 const char* pkgName = packageName.c_str();
2314 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002315
2316 if (!pkgName || !seinfo) {
2317 ALOGE("Package name or seinfo tag is null when trying to restorecon.");
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002318 return binder::Status::fromServiceSpecificError(-1);
Robert Craige9887e42014-02-20 10:25:56 -05002319 }
2320
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002321 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002322 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002323 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002324 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2325 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002326 res = -1;
2327 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002328 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002329 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002330 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002331 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
2332 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyea0e4b12015-11-19 15:35:27 -07002333 // TODO: include result once 25796509 is fixed
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002334 }
Robert Craige9887e42014-02-20 10:25:56 -05002335 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002336 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Robert Craige9887e42014-02-20 10:25:56 -05002337}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002338
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002339binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2340 const std::string& instructionSet) {
2341 ENFORCE_UID(AID_SYSTEM);
2342 const char* oat_dir = oatDir.c_str();
2343 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002344 char oat_instr_dir[PKG_PATH_MAX];
2345
2346 if (validate_apk_path(oat_dir)) {
2347 ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002348 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002349 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002350 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002351 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002352 }
2353 if (selinux_android_restorecon(oat_dir, 0)) {
2354 ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002355 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002356 }
2357 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002358 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002359 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002360 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002361 return binder::Status::ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002362}
2363
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002364binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2365 ENFORCE_UID(AID_SYSTEM);
2366 const char* apk_path = packageDir.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002367 if (validate_apk_path(apk_path)) {
2368 ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002369 return binder::Status::fromServiceSpecificError(-1);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002370 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002371 int res = delete_dir_contents(apk_path, 1 /* also_delete_dir */,
2372 NULL /* exclusion_predicate */);
2373 return res ? binder::Status::fromServiceSpecificError(-1) : binder::Status::ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002374}
2375
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002376binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2377 const std::string& fromBase, const std::string& toBase) {
2378 ENFORCE_UID(AID_SYSTEM);
2379 const char* relative_path = relativePath.c_str();
2380 const char* from_base = fromBase.c_str();
2381 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002382 char from_path[PKG_PATH_MAX];
2383 char to_path[PKG_PATH_MAX];
2384 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2385 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2386
2387 if (validate_apk_path_subdirs(from_path)) {
2388 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002389 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002390 }
2391
2392 if (validate_apk_path_subdirs(to_path)) {
2393 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002394 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002395 }
2396
2397 const int ret = link(from_path, to_path);
2398 if (ret < 0) {
2399 ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002400 return binder::Status::fromServiceSpecificError(-1);
Narayan Kamathd845c962015-06-04 13:20:27 +01002401 }
2402
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002403 return binder::Status::ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002404}
2405
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002406// Helper for move_ab, so that we can have common failure-case cleanup.
2407static bool unlink_and_rename(const char* from, const char* to) {
2408 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2409 // return a failure.
2410 struct stat s;
2411 if (stat(to, &s) == 0) {
2412 if (!S_ISREG(s.st_mode)) {
2413 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2414 return false;
2415 }
2416 if (unlink(to) != 0) {
2417 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2418 return false;
2419 }
2420 } else {
2421 // This may be a permission problem. We could investigate the error code, but we'll just
2422 // let the rename failure do the work for us.
2423 }
2424
2425 // Try to rename "to" to "from."
2426 if (rename(from, to) != 0) {
2427 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2428 return false;
2429 }
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002430 return true;
2431}
2432
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002433// Move/rename a B artifact (from) to an A artifact (to).
2434static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2435 // Check whether B exists.
2436 {
2437 struct stat s;
2438 if (stat(b_path.c_str(), &s) != 0) {
2439 // Silently ignore for now. The service calling this isn't smart enough to understand
2440 // lack of artifacts at the moment.
2441 return false;
2442 }
2443 if (!S_ISREG(s.st_mode)) {
2444 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2445 // Try to unlink, but swallow errors.
2446 unlink(b_path.c_str());
2447 return false;
2448 }
2449 }
2450
2451 // Rename B to A.
2452 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2453 // Delete the b_path so we don't try again (or fail earlier).
2454 if (unlink(b_path.c_str()) != 0) {
2455 PLOG(ERROR) << "Could not unlink " << b_path;
2456 }
2457
2458 return false;
2459 }
2460
2461 return true;
2462}
2463
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002464binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2465 const std::string& instructionSet, const std::string& outputPath) {
2466 ENFORCE_UID(AID_SYSTEM);
2467 const char* apk_path = apkPath.c_str();
2468 const char* instruction_set = instructionSet.c_str();
2469 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07002470
2471 // Get the current slot suffix. No suffix, no A/B.
2472 std::string slot_suffix;
2473 {
2474 char buf[kPropertyValueMax];
2475 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002476 return binder::Status::fromServiceSpecificError(-1);
Andreas Gamped089ca12016-06-27 14:25:30 -07002477 }
2478 slot_suffix = buf;
2479
Andreas Gampefd12eda2016-07-12 09:47:17 -07002480 if (!ValidateTargetSlotSuffix(slot_suffix)) {
Andreas Gamped089ca12016-06-27 14:25:30 -07002481 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002482 return binder::Status::fromServiceSpecificError(-1);
Andreas Gamped089ca12016-06-27 14:25:30 -07002483 }
2484 }
2485
2486 // Validate other inputs.
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002487 if (validate_apk_path(apk_path) != 0) {
2488 LOG(ERROR) << "invalid apk_path " << apk_path;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002489 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002490 }
2491 if (validate_apk_path(oat_dir) != 0) {
2492 LOG(ERROR) << "invalid oat_dir " << oat_dir;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002493 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002494 }
2495
2496 char a_path[PKG_PATH_MAX];
2497 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002498 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002499 }
David Brazdilfc5934e2016-09-08 11:55:48 +01002500 const std::string a_vdex_path = create_vdex_filename(a_path);
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002501 const std::string a_image_path = create_image_filename(a_path);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002502
Andreas Gamped089ca12016-06-27 14:25:30 -07002503 // B path = A path + slot suffix.
2504 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002505 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 -07002506 const std::string b_image_path = StringPrintf("%s.%s",
2507 a_image_path.c_str(),
2508 slot_suffix.c_str());
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002509
David Brazdilfc5934e2016-09-08 11:55:48 +01002510 bool success = true;
2511 if (move_ab_path(b_path, a_path)) {
2512 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2513 // Note: we can live without an app image. As such, ignore failure to move the image file.
2514 // If we decide to require the app image, or the app image being moved correctly,
2515 // then change accordingly.
2516 constexpr bool kIgnoreAppImageFailure = true;
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002517
David Brazdilfc5934e2016-09-08 11:55:48 +01002518 if (!a_image_path.empty()) {
2519 if (!move_ab_path(b_image_path, a_image_path)) {
David Brazdilc338c7f2016-09-12 16:26:40 +01002520 unlink(a_image_path.c_str());
David Brazdilfc5934e2016-09-08 11:55:48 +01002521 if (!kIgnoreAppImageFailure) {
2522 success = false;
2523 }
2524 }
2525 }
2526 } else {
2527 // Cleanup: delete B image, ignore errors.
2528 unlink(b_image_path.c_str());
2529 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002530 }
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002531 } else {
2532 // Cleanup: delete B image, ignore errors.
David Brazdilfc5934e2016-09-08 11:55:48 +01002533 unlink(b_vdex_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002534 unlink(b_image_path.c_str());
Andreas Gampeab15dbf2016-06-06 15:36:18 -07002535 success = false;
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002536 }
2537
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002538 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002539}
2540
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002541binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2542 const std::string& instructionSet, const std::string& outputPath) {
2543 ENFORCE_UID(AID_SYSTEM);
2544 const char* apk_path = apkPath.c_str();
2545 const char* instruction_set = instructionSet.c_str();
2546 const char* oat_dir = outputPath.c_str();
2547
Andreas Gampeb31206b2016-09-09 17:07:04 -07002548 // Delete the oat/odex file.
2549 char out_path[PKG_PATH_MAX];
2550 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002551 return binder::Status::fromServiceSpecificError(-1);
Andreas Gampeb31206b2016-09-09 17:07:04 -07002552 }
2553
2554 // In case of a permission failure report the issue. Otherwise just print a warning.
2555 auto unlink_and_check = [](const char* path) -> bool {
2556 int result = unlink(path);
2557 if (result != 0) {
2558 if (errno == EACCES || errno == EPERM) {
2559 PLOG(ERROR) << "Could not unlink " << path;
2560 return false;
2561 }
2562 PLOG(WARNING) << "Could not unlink " << path;
2563 }
2564 return true;
2565 };
2566
2567 // Delete the oat/odex file.
2568 bool return_value_oat = unlink_and_check(out_path);
2569
2570 // Derive and delete the app image.
2571 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2572
2573 // Report success.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002574 bool success = return_value_oat && return_value_art;
2575 return success ? binder::Status::ok() : binder::Status::fromServiceSpecificError(-1);
Andreas Gampeb31206b2016-09-09 17:07:04 -07002576}
2577
Andreas Gampe02d0de52015-11-11 20:43:16 -08002578} // namespace installd
2579} // namespace android