blob: e54407cf9152e267a8a2e66ebbf946246a6adaf1 [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>
21#include <stdlib.h>
22#include <sys/capability.h>
23#include <sys/file.h>
24#include <sys/resource.h>
25#include <sys/stat.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070026#include <sys/types.h>
27#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070029
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080030#include <android-base/stringprintf.h>
31#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <cutils/fs.h>
33#include <cutils/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070034#include <cutils/sched_policy.h>
35#include <diskusage/dirsize.h>
36#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070038#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080039#include <system/thread_defs.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070040
Andreas Gampe02d0de52015-11-11 20:43:16 -080041#include <globals.h>
42#include <installd_deps.h>
43#include <utils.h>
44
45#ifndef LOG_TAG
46#define LOG_TAG "installd"
47#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070048
49using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070050
Andreas Gampe02d0de52015-11-11 20:43:16 -080051namespace android {
52namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070053
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070054static constexpr const char* kCpPath = "/system/bin/cp";
55static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070056
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000057#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
58
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070059int create_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000060 appid_t appid, const char* seinfo, int target_sdk_version) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070061 uid_t uid = multiuser_get_uid(userid, appid);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000062 int target_mode = target_sdk_version >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -070063 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070064 auto path = create_data_user_package_path(uuid, userid, pkgname);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000065 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070066 PLOG(ERROR) << "Failed to prepare " << path;
67 return -1;
68 }
69 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
70 PLOG(ERROR) << "Failed to setfilecon " << path;
71 return -1;
72 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070073 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -070074 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070075 auto path = create_data_user_de_package_path(uuid, userid, pkgname);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000076 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) == -1) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070077 PLOG(ERROR) << "Failed to prepare " << path;
Jeff Sharkeya03c7472016-01-13 09:47:08 -070078 // TODO: include result once 25796509 is fixed
79 return 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070080 }
81 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
82 PLOG(ERROR) << "Failed to setfilecon " << path;
Jeff Sharkeya03c7472016-01-13 09:47:08 -070083 // TODO: include result once 25796509 is fixed
84 return 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070085 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070086 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070087 return 0;
88}
89
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070090int migrate_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
91 // This method only exists to upgrade system apps that have requested
92 // forceDeviceEncrypted, so their default storage always lives in a
93 // consistent location. This only works on non-FBE devices, since we
94 // never want to risk exposing data on a device with real CE/DE storage.
95
96 auto ce_path = create_data_user_package_path(uuid, userid, pkgname);
97 auto de_path = create_data_user_de_package_path(uuid, userid, pkgname);
98
99 // If neither directory is marked as default, assume CE is default
100 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
101 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
102 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
103 PLOG(ERROR) << "Failed to mark default storage " << ce_path;
104 return -1;
105 }
106 }
107
108 // Migrate default data location if needed
109 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
110 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
111
112 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
113 LOG(WARNING) << "Requested default storage " << target
114 << " is not active; migrating from " << source;
115 if (delete_dir_contents_and_dir(target) != 0) {
116 PLOG(ERROR) << "Failed to delete";
117 return -1;
118 }
119 if (rename(source.c_str(), target.c_str()) != 0) {
120 PLOG(ERROR) << "Failed to rename";
121 return -1;
122 }
123 }
124
125 return 0;
126}
127
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700128int clear_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
129 std::string suffix = "";
130 if (flags & FLAG_CLEAR_CACHE_ONLY) {
131 suffix = CACHE_DIR_POSTFIX;
132 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
133 suffix = CODE_CACHE_DIR_POSTFIX;
134 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700135
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700136 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700137 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700138 auto path = create_data_user_package_path(uuid, userid, pkgname) + suffix;
139 if (access(path.c_str(), F_OK) == 0) {
140 res |= delete_dir_contents(path);
141 }
142 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700143 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700144 auto path = create_data_user_de_package_path(uuid, userid, pkgname) + suffix;
145 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700146 // TODO: include result once 25796509 is fixed
147 delete_dir_contents(path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700148 }
149 }
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700150 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700151}
152
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700153int destroy_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
154 int res = 0;
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700155 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700156 res |= delete_dir_contents_and_dir(
157 create_data_user_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700158 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700159 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700160 // TODO: include result once 25796509 is fixed
161 delete_dir_contents_and_dir(
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700162 create_data_user_de_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700163 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700164 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700165}
166
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700167int move_complete_app(const char *from_uuid, const char *to_uuid, const char *package_name,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000168 const char *data_app_name, appid_t appid, const char* seinfo, int target_sdk_version) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700169 std::vector<userid_t> users = get_known_users(from_uuid);
170
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700171 // Copy app
172 {
173 std::string from(create_data_app_package_path(from_uuid, data_app_name));
174 std::string to(create_data_app_package_path(to_uuid, data_app_name));
175 std::string to_parent(create_data_app_path(to_uuid));
176
177 char *argv[] = {
178 (char*) kCpPath,
179 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
180 (char*) "-p", /* preserve timestamps, ownership, and permissions */
181 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
182 (char*) "-P", /* Do not follow symlinks [default] */
183 (char*) "-d", /* don't dereference symlinks */
184 (char*) from.c_str(),
185 (char*) to_parent.c_str()
186 };
187
188 LOG(DEBUG) << "Copying " << from << " to " << to;
189 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
190
191 if (rc != 0) {
192 LOG(ERROR) << "Failed copying " << from << " to " << to
193 << ": status " << rc;
194 goto fail;
195 }
196
197 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
198 LOG(ERROR) << "Failed to restorecon " << to;
199 goto fail;
200 }
201 }
202
203 // Copy private data for all known users
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700204 // TODO: handle user_de paths
Jeff Sharkeye3637242015-04-08 20:56:42 -0700205 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700206 std::string from(create_data_user_package_path(from_uuid, user, package_name));
207 std::string to(create_data_user_package_path(to_uuid, user, package_name));
208 std::string to_parent(create_data_user_path(to_uuid, user));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700209
210 // Data source may not exist for all users; that's okay
211 if (access(from.c_str(), F_OK) != 0) {
212 LOG(INFO) << "Missing source " << from;
213 continue;
214 }
215
216 std::string user_path(create_data_user_path(to_uuid, user));
217 if (fs_prepare_dir(user_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM) != 0) {
218 LOG(ERROR) << "Failed to prepare user target " << user_path;
219 goto fail;
220 }
221
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700222 if (create_app_data(to_uuid, package_name, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000223 appid, seinfo, target_sdk_version) != 0) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700224 LOG(ERROR) << "Failed to create package target " << to;
225 goto fail;
226 }
227
228 char *argv[] = {
229 (char*) kCpPath,
230 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
231 (char*) "-p", /* preserve timestamps, ownership, and permissions */
232 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
233 (char*) "-P", /* Do not follow symlinks [default] */
234 (char*) "-d", /* don't dereference symlinks */
235 (char*) from.c_str(),
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700236 (char*) to_parent.c_str()
Jeff Sharkeye3637242015-04-08 20:56:42 -0700237 };
238
239 LOG(DEBUG) << "Copying " << from << " to " << to;
240 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
241
242 if (rc != 0) {
243 LOG(ERROR) << "Failed copying " << from << " to " << to
244 << ": status " << rc;
245 goto fail;
246 }
247
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700248 if (restorecon_app_data(to_uuid, package_name, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700249 appid, seinfo) != 0) {
250 LOG(ERROR) << "Failed to restorecon";
251 goto fail;
252 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700253 }
254
Jeff Sharkey31f08982015-07-07 13:31:37 -0700255 // We let the framework scan the new location and persist that before
256 // deleting the data in the old location; this ordering ensures that
257 // we can recover from things like battery pulls.
Jeff Sharkeye3637242015-04-08 20:56:42 -0700258 return 0;
259
260fail:
261 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700262 {
263 std::string to(create_data_app_package_path(to_uuid, data_app_name));
264 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
265 LOG(WARNING) << "Failed to rollback " << to;
266 }
267 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700268 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700269 std::string to(create_data_user_package_path(to_uuid, user, package_name));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700270 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
271 LOG(WARNING) << "Failed to rollback " << to;
272 }
273 }
274 return -1;
275}
276
Robin Lee7c8bec02014-06-10 18:46:26 +0100277int make_user_config(userid_t userid)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700278{
Robin Lee095c7632014-04-25 15:05:19 +0100279 if (ensure_config_user_dirs(userid) == -1) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700280 return -1;
281 }
282
283 return 0;
284}
285
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700286int delete_user(const char *uuid, userid_t userid) {
287 int res = 0;
Robin Lee095c7632014-04-25 15:05:19 +0100288
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700289 std::string data_path(create_data_user_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700290 std::string data_de_path(create_data_user_de_path(uuid, userid));
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700291 std::string media_path(create_data_media_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700292
293 res |= delete_dir_contents_and_dir(data_path);
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700294 // TODO: include result once 25796509 is fixed
295 delete_dir_contents_and_dir(data_de_path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700296 res |= delete_dir_contents_and_dir(media_path);
Robin Lee095c7632014-04-25 15:05:19 +0100297
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700298 // Config paths only exist on internal storage
299 if (uuid == nullptr) {
300 char config_path[PATH_MAX];
301 if ((create_user_config_path(config_path, userid) != 0)
302 || (delete_dir_contents(config_path, 1, NULL) != 0)) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700303 res = -1;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700304 }
Robin Lee095c7632014-04-25 15:05:19 +0100305 }
306
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700307 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100308}
309
Mike Lockwood94afecf2012-10-24 10:45:23 -0700310/* Try to ensure free_size bytes of storage are available.
311 * Returns 0 on success.
312 * This is rather simple-minded because doing a full LRU would
313 * be potentially memory-intensive, and without atime it would
314 * also require that apps constantly modify file metadata even
315 * when just reading from the cache, which is pretty awful.
316 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700317int free_cache(const char *uuid, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700318{
319 cache_t* cache;
320 int64_t avail;
321 DIR *d;
322 struct dirent *de;
323 char tmpdir[PATH_MAX];
324 char *dirpos;
325
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700326 std::string data_path(create_data_path(uuid));
327
328 avail = data_disk_free(data_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700329 if (avail < 0) return -1;
330
331 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
332 if (avail >= free_size) return 0;
333
334 cache = start_cache_collection();
335
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700336 // Special case for owner on internal storage
337 if (uuid == nullptr) {
338 std::string _tmpdir(create_data_user_path(nullptr, 0));
339 add_cache_files(cache, _tmpdir.c_str(), "cache");
Mike Lockwood94afecf2012-10-24 10:45:23 -0700340 }
341
342 // Search for other users and add any cache files from them.
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700343 std::string _tmpdir(create_data_path(uuid) + "/" + SECONDARY_USER_PREFIX);
344 strcpy(tmpdir, _tmpdir.c_str());
345
Mike Lockwood94afecf2012-10-24 10:45:23 -0700346 dirpos = tmpdir + strlen(tmpdir);
347 d = opendir(tmpdir);
348 if (d != NULL) {
349 while ((de = readdir(d))) {
350 if (de->d_type == DT_DIR) {
351 const char *name = de->d_name;
352 /* always skip "." and ".." */
353 if (name[0] == '.') {
354 if (name[1] == 0) continue;
355 if ((name[1] == '.') && (name[2] == 0)) continue;
356 }
357 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
358 strcpy(dirpos, name);
359 //ALOGI("adding cache files from %s\n", tmpdir);
360 add_cache_files(cache, tmpdir, "cache");
361 } else {
362 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
363 }
364 }
365 }
366 closedir(d);
367 }
368
369 // Collect cache files on external storage for all users (if it is mounted as part
370 // of the internal storage).
371 strcpy(tmpdir, android_media_dir.path);
372 dirpos = tmpdir + strlen(tmpdir);
373 d = opendir(tmpdir);
374 if (d != NULL) {
375 while ((de = readdir(d))) {
376 if (de->d_type == DT_DIR) {
377 const char *name = de->d_name;
378 /* skip any dir that doesn't start with a number, so not a user */
379 if (name[0] < '0' || name[0] > '9') {
380 continue;
381 }
382 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
383 strcpy(dirpos, name);
384 if (lookup_media_dir(tmpdir, "Android") == 0
385 && lookup_media_dir(tmpdir, "data") == 0) {
386 //ALOGI("adding cache files from %s\n", tmpdir);
387 add_cache_files(cache, tmpdir, "cache");
388 }
389 } else {
390 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
391 }
392 }
393 }
394 closedir(d);
395 }
396
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700397 clear_cache_files(data_path, cache, free_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700398 finish_cache_collection(cache);
399
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700400 return data_disk_free(data_path) >= free_size ? 0 : -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700401}
402
Narayan Kamath1b400322014-04-11 13:17:00 +0100403int rm_dex(const char *path, const char *instruction_set)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700404{
405 char dex_path[PKG_PATH_MAX];
406
Jeff Sharkey770180a2014-09-08 17:14:26 -0700407 if (validate_apk_path(path) && validate_system_app_path(path)) {
408 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
409 return -1;
410 }
411
Andreas Gampe02d0de52015-11-11 20:43:16 -0800412 if (!create_cache_path(dex_path, path, instruction_set)) return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700413
414 ALOGV("unlink %s\n", dex_path);
415 if (unlink(dex_path) < 0) {
Jeff Sharkey770180a2014-09-08 17:14:26 -0700416 if (errno != ENOENT) {
417 ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
418 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700419 return -1;
420 } else {
421 return 0;
422 }
423}
424
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700425int get_app_size(const char *uuid, const char *pkgname, int userid, int flags,
426 const char *apkpath, const char *libdirpath, const char *fwdlock_apkpath,
427 const char *asecpath, const char *instruction_set, int64_t *_codesize, int64_t *_datasize,
428 int64_t *_cachesize, int64_t* _asecsize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700429 DIR *d;
430 int dfd;
431 struct dirent *de;
432 struct stat s;
433 char path[PKG_PATH_MAX];
434
435 int64_t codesize = 0;
436 int64_t datasize = 0;
437 int64_t cachesize = 0;
438 int64_t asecsize = 0;
439
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700440 /* count the source apk as code -- but only if it's not
441 * on the /system partition and its not on the sdcard. */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700442 if (validate_system_app_path(apkpath) &&
443 strncmp(apkpath, android_asec_dir.path, android_asec_dir.len) != 0) {
444 if (stat(apkpath, &s) == 0) {
445 codesize += stat_size(&s);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700446 if (S_ISDIR(s.st_mode)) {
447 d = opendir(apkpath);
448 if (d != NULL) {
449 dfd = dirfd(d);
450 codesize += calculate_dir_size(dfd);
451 closedir(d);
452 }
453 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700454 }
455 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700456
457 /* count the forward locked apk as code if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700458 if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
459 if (stat(fwdlock_apkpath, &s) == 0) {
460 codesize += stat_size(&s);
461 }
462 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700463
464 /* count the cached dexfile as code */
Andreas Gampe02d0de52015-11-11 20:43:16 -0800465 if (create_cache_path(path, apkpath, instruction_set)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700466 if (stat(path, &s) == 0) {
467 codesize += stat_size(&s);
468 }
469 }
470
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700471 /* add in size of any libraries */
Dianne Hackborn8b417802013-05-01 18:55:10 -0700472 if (libdirpath != NULL && libdirpath[0] != '!') {
473 d = opendir(libdirpath);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 if (d != NULL) {
475 dfd = dirfd(d);
476 codesize += calculate_dir_size(dfd);
477 closedir(d);
478 }
479 }
480
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700481 /* compute asec size if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482 if (asecpath != NULL && asecpath[0] != '!') {
483 if (stat(asecpath, &s) == 0) {
484 asecsize += stat_size(&s);
485 }
486 }
487
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700488 std::vector<userid_t> users;
489 if (userid == -1) {
490 users = get_known_users(uuid);
491 } else {
492 users.push_back(userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700493 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700494
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700495 for (auto user : users) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700496 // TODO: handle user_de directories
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700497 if (!(flags & FLAG_STORAGE_CE)) continue;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700498
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700499 std::string _pkgdir(create_data_user_package_path(uuid, user, pkgname));
500 const char* pkgdir = _pkgdir.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700501
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700502 d = opendir(pkgdir);
503 if (d == NULL) {
504 PLOG(WARNING) << "Failed to open " << pkgdir;
505 continue;
506 }
507 dfd = dirfd(d);
508
509 /* most stuff in the pkgdir is data, except for the "cache"
510 * directory and below, which is cache, and the "lib" directory
511 * and below, which is code...
512 */
513 while ((de = readdir(d))) {
514 const char *name = de->d_name;
515
516 if (de->d_type == DT_DIR) {
517 int subfd;
518 int64_t statsize = 0;
519 int64_t dirsize = 0;
520 /* always skip "." and ".." */
521 if (name[0] == '.') {
522 if (name[1] == 0) continue;
523 if ((name[1] == '.') && (name[2] == 0)) continue;
524 }
525 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
526 statsize = stat_size(&s);
527 }
528 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
529 if (subfd >= 0) {
530 dirsize = calculate_dir_size(subfd);
531 }
532 if(!strcmp(name,"lib")) {
533 codesize += dirsize + statsize;
534 } else if(!strcmp(name,"cache")) {
535 cachesize += dirsize + statsize;
536 } else {
537 datasize += dirsize + statsize;
538 }
539 } else if (de->d_type == DT_LNK && !strcmp(name,"lib")) {
540 // This is the symbolic link to the application's library
541 // code. We'll count this as code instead of data, since
542 // it is not something that the app creates.
543 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
544 codesize += stat_size(&s);
545 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700546 } else {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700547 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
548 datasize += stat_size(&s);
549 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700550 }
551 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700552 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700553 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700554 *_codesize = codesize;
555 *_datasize = datasize;
556 *_cachesize = cachesize;
557 *_asecsize = asecsize;
558 return 0;
559}
560
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700561static int split_count(const char *str)
562{
563 char *ctx;
564 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800565 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700566
567 strncpy(buf, str, sizeof(buf));
568 char *pBuf = buf;
569
570 while(strtok_r(pBuf, " ", &ctx) != NULL) {
571 count++;
572 pBuf = NULL;
573 }
574
575 return count;
576}
577
neo.chae14e084d2015-01-07 18:46:13 +0900578static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700579{
580 char *ctx;
581 int count = 0;
582 char *tok;
583 char *pBuf = buf;
584
585 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
586 argv[count++] = tok;
587 pBuf = NULL;
588 }
589
590 return count;
591}
592
Alex Light7365a102014-07-21 12:23:48 -0700593static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800594 const char* output_file_name, const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -0700595{
596 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +0100597 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -0700598
599 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
600 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
601 ALOGE("Instruction set %s longer than max length of %d",
602 instruction_set, MAX_INSTRUCTION_SET_LEN);
603 return;
604 }
605
606 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
607 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
608 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
609 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
610 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
611 // The caller has already gotten all the locks we need.
612 const char* no_lock_arg = "--no-lock-output";
613 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
614 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", oat_fd);
615 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_fd);
Alex Lighta7915d42014-08-11 10:07:02 -0700616 ALOGV("Running %s isa=%s in-fd=%d (%s) out-fd=%d (%s)\n",
Alex Light7365a102014-07-21 12:23:48 -0700617 PATCHOAT_BIN, instruction_set, input_fd, input_file_name, oat_fd, output_file_name);
618
619 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
620 char* argv[7];
621 argv[0] = (char*) PATCHOAT_BIN;
622 argv[1] = (char*) patched_image_location_arg;
623 argv[2] = (char*) no_lock_arg;
624 argv[3] = instruction_set_arg;
625 argv[4] = output_oat_fd_arg;
626 argv[5] = input_oat_fd_arg;
627 argv[6] = NULL;
628
629 execv(PATCHOAT_BIN, (char* const *)argv);
630 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
631}
632
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700633static bool check_boolean_property(const char* property_name, bool default_value = false) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800634 char tmp_property_value[kPropertyValueMax];
635 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700636 if (!have_property) {
637 return default_value;
638 }
639 return strcmp(tmp_property_value, "true") == 0;
640}
641
Mathieu Chartieredc8bc42015-10-21 14:05:28 -0700642static void run_dex2oat(int zip_fd, int oat_fd, int image_fd, const char* input_file_name,
Calin Juravledf9dadd2015-11-04 14:47:37 +0000643 const char* output_file_name, int swap_fd, const char *instruction_set,
David Brazdilb0fad6d2015-12-30 11:16:04 +0000644 bool vm_safe_mode, bool debuggable, bool post_bootcomplete, bool extract_only,
645 const std::vector<int>& profile_files_fd, const std::vector<int>& reference_profile_files_fd) {
Calin Juravle8fc73152014-08-19 18:48:50 +0100646 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
647
648 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
649 ALOGE("Instruction set %s longer than max length of %d",
650 instruction_set, MAX_INSTRUCTION_SET_LEN);
651 return;
652 }
653
Calin Juravle60a794d2015-12-24 12:36:41 +0200654 if (profile_files_fd.size() != reference_profile_files_fd.size()) {
655 ALOGE("Invalid configuration of profile files: pf_size (%zu) != rpf_size (%zu)",
656 profile_files_fd.size(), reference_profile_files_fd.size());
657 return;
658 }
659
Andreas Gampe02d0de52015-11-11 20:43:16 -0800660 char dex2oat_Xms_flag[kPropertyValueMax];
661 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700662
Andreas Gampe02d0de52015-11-11 20:43:16 -0800663 char dex2oat_Xmx_flag[kPropertyValueMax];
664 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700665
Andreas Gampe02d0de52015-11-11 20:43:16 -0800666 char dex2oat_compiler_filter_flag[kPropertyValueMax];
667 bool have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700668 dex2oat_compiler_filter_flag, NULL) > 0;
669
Andreas Gampe02d0de52015-11-11 20:43:16 -0800670 char dex2oat_threads_buf[kPropertyValueMax];
671 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -0700672 ? "dalvik.vm.dex2oat-threads"
673 : "dalvik.vm.boot-dex2oat-threads",
674 dex2oat_threads_buf,
675 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800676 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700677 if (have_dex2oat_threads_flag) {
678 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
679 }
680
Andreas Gampe02d0de52015-11-11 20:43:16 -0800681 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +0100682 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800683 char dex2oat_isa_features[kPropertyValueMax];
684 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +0100685 dex2oat_isa_features, NULL) > 0;
686
Andreas Gampe02d0de52015-11-11 20:43:16 -0800687 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -0800688 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800689 char dex2oat_isa_variant[kPropertyValueMax];
690 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -0800691 dex2oat_isa_variant, NULL) > 0;
692
neo.chae14e084d2015-01-07 18:46:13 +0900693 const char *dex2oat_norelocation = "-Xnorelocate";
694 bool have_dex2oat_relocation_skip_flag = false;
695
Andreas Gampe02d0de52015-11-11 20:43:16 -0800696 char dex2oat_flags[kPropertyValueMax];
697 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700698 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -0800699 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
700
Brian Carlstrom538998f2014-07-30 14:37:11 -0700701 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -0800702 char vold_decrypt[kPropertyValueMax];
703 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700704 bool skip_compilation = (have_vold_decrypt &&
705 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
706 (strcmp(vold_decrypt, "1") == 0)));
707
David Srbecky528c8dd2015-05-28 16:55:50 +0100708 bool generate_debug_info = check_boolean_property("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700709
Mathieu Chartier416fa122016-02-03 13:48:16 -0800710 char app_image_format[kPropertyValueMax];
711 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
712 bool have_app_image_format =
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -0800713 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
Mathieu Chartier416fa122016-02-03 13:48:16 -0800714 if (have_app_image_format) {
715 sprintf(image_format_arg, "--image-format=%s", app_image_format);
716 }
717
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700718 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700719
Brian Carlstrom53e07762014-06-27 14:15:19 -0700720 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700721
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700722 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +0100723
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700724 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
725 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
726 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -0700727 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +0100728 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -0800729 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
730 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
731 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
732 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
733 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -0800734 bool have_dex2oat_swap_fd = false;
735 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -0700736 bool have_dex2oat_image_fd = false;
737 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700738
739 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
740 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
741 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
742 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +0100743 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -0800744 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +0100745 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -0800746 if (swap_fd >= 0) {
747 have_dex2oat_swap_fd = true;
748 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
749 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -0700750 if (image_fd >= 0) {
751 have_dex2oat_image_fd = true;
752 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
753 }
Calin Juravle57c69c32014-06-06 14:42:16 +0100754
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700755 if (have_dex2oat_Xms_flag) {
756 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
757 }
758 if (have_dex2oat_Xmx_flag) {
759 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
760 }
Brian Carlstrom538998f2014-07-30 14:37:11 -0700761 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -0700762 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -0700763 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +0900764 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +0100765 } else if (vm_safe_mode) {
766 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +0100767 have_dex2oat_compiler_filter_flag = true;
David Brazdilb0fad6d2015-12-30 11:16:04 +0000768 } else if (extract_only) {
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700769 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-at-runtime");
770 have_dex2oat_compiler_filter_flag = true;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700771 } else if (have_dex2oat_compiler_filter_flag) {
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700772 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", dex2oat_compiler_filter_flag);
773 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700774
Andreas Gampe598c25e2015-03-03 09:15:06 -0800775 // Check whether all apps should be compiled debuggable.
776 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800777 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -0800778 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -0800779 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -0800780 (prop_buf[0] == '1');
781 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200782 std::vector<std::string> profile_file_args(profile_files_fd.size());
783 std::vector<std::string> reference_profile_file_args(profile_files_fd.size());
784 // "reference-profile-file-fd" is longer than "profile-file-fd" so we can
785 // use it to set the max length.
786 char profile_buf[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
787 for (size_t k = 0; k < profile_files_fd.size(); k++) {
788 sprintf(profile_buf, "--profile-file-fd=%d", profile_files_fd[k]);
789 profile_file_args[k].assign(profile_buf);
790 sprintf(profile_buf, "--reference-profile-file-fd=%d", reference_profile_files_fd[k]);
791 reference_profile_file_args[k].assign(profile_buf);
792 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800793
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700794 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +0100795
neo.chae14e084d2015-01-07 18:46:13 +0900796 const char* argv[7 // program name, mandatory arguments and the final NULL
797 + (have_dex2oat_isa_variant ? 1 : 0)
798 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900799 + (have_dex2oat_Xms_flag ? 2 : 0)
800 + (have_dex2oat_Xmx_flag ? 2 : 0)
801 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700802 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900803 + (have_dex2oat_swap_fd ? 1 : 0)
Mathieu Chartieredc8bc42015-10-21 14:05:28 -0700804 + (have_dex2oat_image_fd ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900805 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +0100806 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -0800807 + (debuggable ? 1 : 0)
Mathieu Chartier416fa122016-02-03 13:48:16 -0800808 + (have_app_image_format ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +0200809 + dex2oat_flags_count
810 + profile_files_fd.size()
811 + reference_profile_files_fd.size()];
Calin Juravle4fdff462014-06-06 16:58:43 +0100812 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +0900813 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +0100814 argv[i++] = zip_fd_arg;
815 argv[i++] = zip_location_arg;
816 argv[i++] = oat_fd_arg;
817 argv[i++] = oat_location_arg;
818 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -0800819 if (have_dex2oat_isa_variant) {
820 argv[i++] = instruction_set_variant_arg;
821 }
Calin Juravle8fc73152014-08-19 18:48:50 +0100822 if (have_dex2oat_isa_features) {
823 argv[i++] = instruction_set_features_arg;
824 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700825 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900826 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700827 argv[i++] = dex2oat_Xms_arg;
828 }
829 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900830 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700831 argv[i++] = dex2oat_Xmx_arg;
832 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700833 if (have_dex2oat_compiler_filter_flag) {
834 argv[i++] = dex2oat_compiler_filter_arg;
835 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700836 if (have_dex2oat_threads_flag) {
837 argv[i++] = dex2oat_threads_arg;
838 }
Andreas Gampee1c01352014-12-10 16:41:11 -0800839 if (have_dex2oat_swap_fd) {
840 argv[i++] = dex2oat_swap_fd;
841 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -0700842 if (have_dex2oat_image_fd) {
843 argv[i++] = dex2oat_image_fd;
844 }
David Srbecky528c8dd2015-05-28 16:55:50 +0100845 if (generate_debug_info) {
846 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700847 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800848 if (debuggable) {
849 argv[i++] = "--debuggable";
850 }
Mathieu Chartier416fa122016-02-03 13:48:16 -0800851 if (have_app_image_format) {
852 argv[i++] = image_format_arg;
853 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700854 if (dex2oat_flags_count) {
855 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +0100856 }
neo.chae14e084d2015-01-07 18:46:13 +0900857 if (have_dex2oat_relocation_skip_flag) {
858 argv[i++] = RUNTIME_ARG;
859 argv[i++] = dex2oat_norelocation;
860 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200861 for (size_t k = 0; k < profile_file_args.size(); k++) {
862 argv[i++] = profile_file_args[k].c_str();
863 argv[i++] = reference_profile_file_args[k].c_str();
864 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700865 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +0100866 argv[i] = NULL;
867
neo.chae14e084d2015-01-07 18:46:13 +0900868 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700869 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700870}
871
Andreas Gampee1c01352014-12-10 16:41:11 -0800872/*
Andreas Gampec968c012015-07-16 15:55:41 -0700873 * Whether dexopt should use a swap file when compiling an APK.
874 *
875 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
876 * itself, anyways).
877 *
878 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
879 *
880 * Otherwise, return true if this is a low-mem device.
881 *
882 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -0800883 */
Andreas Gampec968c012015-07-16 15:55:41 -0700884static bool kAlwaysProvideSwapFile = false;
885static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -0800886
887static bool ShouldUseSwapFileForDexopt() {
888 if (kAlwaysProvideSwapFile) {
889 return true;
890 }
891
Andreas Gampec968c012015-07-16 15:55:41 -0700892 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -0800893 char dex2oat_prop_buf[kPropertyValueMax];
894 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -0700895 if (strcmp(dex2oat_prop_buf, "true") == 0) {
896 return true;
897 } else {
898 return false;
899 }
900 }
901
902 // Shortcut for default value. This is an implementation optimization for the process sketched
903 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
904 // as low-mem is never returning false. The compiler will optimize this away if it can.
905 if (kDefaultProvideSwapFile) {
906 return true;
907 }
908
909 bool is_low_mem = check_boolean_property("ro.config.low_ram");
910 if (is_low_mem) {
911 return true;
912 }
913
914 // Default value must be false here.
915 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -0800916}
917
Andreas Gampe94dd3d32015-09-14 16:33:11 -0700918static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
919 if (set_to_bg) {
920 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
921 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
922 exit(70);
923 }
924 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
925 ALOGE("setpriority failed: %s\n", strerror(errno));
926 exit(71);
927 }
928 }
929}
930
Calin Juravle60a794d2015-12-24 12:36:41 +0200931constexpr const char* PROFILE_FILE_EXTENSION = ".prof";
932constexpr const char* REFERENCE_PROFILE_FILE_EXTENSION = ".prof.ref";
933
934static void close_all_fds(const std::vector<int>& fds, const char* description) {
935 for (size_t i = 0; i < fds.size(); i++) {
936 if (close(fds[i]) != 0) {
937 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
938 }
939 }
940}
941
942static int open_code_cache_for_user(userid_t user, const char* volume_uuid, const char* pkgname) {
943 std::string code_cache_path =
944 create_data_user_package_path(volume_uuid, user, pkgname) + CODE_CACHE_DIR_POSTFIX;
945
946 struct stat buffer;
947 // Check that the code cache exists. If not, return and don't log an error.
948 if (TEMP_FAILURE_RETRY(lstat(code_cache_path.c_str(), &buffer)) == -1) {
949 if (errno != ENOENT) {
950 PLOG(ERROR) << "Failed to lstat code_cache: " << code_cache_path;
951 return -1;
952 }
953 }
954
955 int code_cache_fd = open(code_cache_path.c_str(),
956 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
957 if (code_cache_fd < 0) {
958 PLOG(ERROR) << "Failed to open code_cache: " << code_cache_path;
959 }
960 return code_cache_fd;
961}
962
963// Keep profile paths in sync with ActivityThread.
964static void open_profile_files_for_user(uid_t uid, const char* pkgname, int code_cache_fd,
965 /*out*/ int* profile_fd, /*out*/ int* reference_profile_fd) {
966 *profile_fd = -1;
967 *reference_profile_fd = -1;
968 std::string profile_file(pkgname);
969 profile_file += PROFILE_FILE_EXTENSION;
970
971 // Check if the profile exists. If not, early return and don't log an error.
972 struct stat buffer;
973 if (TEMP_FAILURE_RETRY(fstatat(
974 code_cache_fd, profile_file.c_str(), &buffer, AT_SYMLINK_NOFOLLOW)) == -1) {
975 if (errno != ENOENT) {
976 PLOG(ERROR) << "Failed to fstatat profile file: " << profile_file;
977 return;
978 }
979 }
980
981 // Open in read-write to allow transfer of information from the current profile
982 // to the reference profile.
983 *profile_fd = openat(code_cache_fd, profile_file.c_str(), O_RDWR | O_NOFOLLOW);
984 if (*profile_fd < 0) {
985 PLOG(ERROR) << "Failed to open profile file: " << profile_file;
986 return;
987 }
988
989 std::string reference_profile(pkgname);
990 reference_profile += REFERENCE_PROFILE_FILE_EXTENSION;
991 // Give read-write permissions just for the user (changed with fchown after opening).
992 // We need write permission because dex2oat will update the reference profile files
993 // with the content of the corresponding current profile files.
994 *reference_profile_fd = openat(code_cache_fd, reference_profile.c_str(),
995 O_CREAT | O_RDWR | O_NOFOLLOW, S_IWUSR | S_IRUSR);
996 if (*reference_profile_fd < 0) {
997 close(*profile_fd);
998 return;
999 }
1000 if (fchown(*reference_profile_fd, uid, uid) < 0) {
1001 PLOG(ERROR) << "Cannot change reference profile file owner: " << reference_profile;
1002 close(*profile_fd);
1003 *profile_fd = -1;
1004 *reference_profile_fd = -1;
1005 }
1006}
1007
1008static void open_profile_files(const char* volume_uuid, uid_t uid, const char* pkgname,
1009 std::vector<int>* profile_fds, std::vector<int>* reference_profile_fds) {
1010 std::vector<userid_t> users = get_known_users(volume_uuid);
1011 for (auto user : users) {
1012 int code_cache_fd = open_code_cache_for_user(user, volume_uuid, pkgname);
1013 if (code_cache_fd < 0) {
1014 continue;
1015 }
1016 int profile_fd = -1;
1017 int reference_profile_fd = -1;
1018 open_profile_files_for_user(
1019 uid, pkgname, code_cache_fd, &profile_fd, &reference_profile_fd);
1020 close(code_cache_fd);
1021
1022 // Add to the lists only if both fds are valid.
1023 if ((profile_fd >= 0) && (reference_profile_fd >= 0)) {
1024 profile_fds->push_back(profile_fd);
1025 reference_profile_fds->push_back(reference_profile_fd);
1026 }
1027 }
1028}
1029
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001030static void trim_extension(char* path) {
1031 // Trim the extension.
1032 int pos = strlen(path);
1033 for (; pos >= 0 && path[pos] != '.'; --pos) {}
1034 if (pos >= 0) {
1035 path[pos] = '\0'; // Trim extension
1036 }
1037}
1038
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001039static bool add_extension_to_file_name(char* file_name, const char* extension) {
1040 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
1041 return false;
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001042 }
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001043 strcat(file_name, extension);
1044 return true;
1045}
1046
1047static int open_output_file(char* file_name, bool recreate) {
1048 int flags = O_RDWR | O_CREAT;
1049 if (recreate) {
1050 unlink(file_name);
1051 flags |= O_EXCL;
1052 }
1053 return open(file_name, flags, 0600);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001054}
1055
1056static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
1057 if (fchmod(fd,
1058 S_IRUSR|S_IWUSR|S_IRGRP |
1059 (is_public ? S_IROTH : 0)) < 0) {
1060 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1061 return false;
1062 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
1063 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1064 return false;
1065 }
1066 return true;
1067}
1068
Calin Juravle60a794d2015-12-24 12:36:41 +02001069int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1070 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* volume_uuid,
1071 bool use_profiles)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001072{
1073 struct utimbuf ut;
Fyodor Kupolov26ff93c2015-04-02 16:59:10 -07001074 struct stat input_stat;
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001075 char out_path[PKG_PATH_MAX];
Andreas Gampee1c01352014-12-10 16:41:11 -08001076 char swap_file_name[PKG_PATH_MAX];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001077 char image_path[PKG_PATH_MAX];
Alex Light7365a102014-07-21 12:23:48 -07001078 const char *input_file;
1079 char in_odex_path[PKG_PATH_MAX];
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001080 int res, input_fd=-1, out_fd=-1, image_fd=-1, swap_fd=-1;
Todd Kennedy76e767c2015-09-25 07:47:47 -07001081 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
1082 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1083 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1084 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
David Brazdilb0fad6d2015-12-30 11:16:04 +00001085 bool extract_only = (dexopt_flags & DEXOPT_EXTRACTONLY) != 0;
Calin Juravle60a794d2015-12-24 12:36:41 +02001086 std::vector<int> profile_files_fd;
1087 std::vector<int> reference_profile_files_fd;
1088 if (use_profiles) {
1089 open_profile_files(volume_uuid, uid, pkgname,
1090 &profile_files_fd, &reference_profile_files_fd);
1091 if (profile_files_fd.empty()) {
1092 // Skip profile guided compilation because no profiles were found.
1093 return 0;
1094 }
1095 }
Todd Kennedy76e767c2015-09-25 07:47:47 -07001096
Todd Kennedye296e002015-11-16 14:41:36 -08001097 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -07001098 LOG_FATAL("dexopt flags contains unknown fields\n");
1099 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001100
Andreas Gampee1c01352014-12-10 16:41:11 -08001101 // Early best-effort check whether we can fit the the path into our buffers.
1102 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1103 // without a swap file, if necessary.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001104 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001105 ALOGE("apk_path too long '%s'\n", apk_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001106 return -1;
1107 }
1108
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001109 if (oat_dir != NULL && oat_dir[0] != '!') {
1110 if (validate_apk_path(oat_dir)) {
1111 ALOGE("invalid oat_dir '%s'\n", oat_dir);
1112 return -1;
Chih-Wei Huang0e8ae162014-04-28 15:47:45 +08001113 }
Andreas Gampe02d0de52015-11-11 20:43:16 -08001114 if (!calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001115 return -1;
1116 }
1117 } else {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001118 if (!create_cache_path(out_path, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001119 return -1;
1120 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001121 }
1122
Richard Uhlerc92fb622015-03-26 15:47:38 -07001123 switch (dexopt_needed) {
1124 case DEXOPT_DEX2OAT_NEEDED:
1125 input_file = apk_path;
1126 break;
1127
1128 case DEXOPT_PATCHOAT_NEEDED:
1129 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1130 return -1;
1131 }
1132 input_file = in_odex_path;
1133 break;
1134
1135 case DEXOPT_SELF_PATCHOAT_NEEDED:
1136 input_file = out_path;
1137 break;
1138
1139 default:
1140 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1141 exit(72);
Alex Light7365a102014-07-21 12:23:48 -07001142 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001143
Alex Light7365a102014-07-21 12:23:48 -07001144 memset(&input_stat, 0, sizeof(input_stat));
1145 stat(input_file, &input_stat);
1146
1147 input_fd = open(input_file, O_RDONLY, 0);
1148 if (input_fd < 0) {
1149 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001150 return -1;
1151 }
1152
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001153 unlink(out_path);
1154 out_fd = open(out_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1155 if (out_fd < 0) {
1156 ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001157 goto fail;
1158 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001159 if (!set_permissions_and_ownership(out_fd, is_public, uid, out_path)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001160 goto fail;
1161 }
1162
Andreas Gampee1c01352014-12-10 16:41:11 -08001163 // Create a swap file if necessary.
Richard Uhlerc92fb622015-03-26 15:47:38 -07001164 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001165 // Make sure there really is enough space.
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001166 strcpy(swap_file_name, out_path);
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001167 if (add_extension_to_file_name(swap_file_name, ".swap")) {
1168 swap_fd = open_output_file(swap_file_name, /*recreate*/true);
1169 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001170 if (swap_fd < 0) {
1171 // Could not create swap file. Optimistically go on and hope that we can compile
1172 // without it.
1173 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08001174 } else {
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001175 // Immediately unlink. We don't really want to hit flash.
1176 unlink(swap_file_name);
Andreas Gampee1c01352014-12-10 16:41:11 -08001177 }
1178 }
Dave Allisond9370732014-01-30 14:19:23 -08001179
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001180 // Avoid generating an app image for extract only since it will not contain any classes.
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001181 strcpy(image_path, out_path);
1182 trim_extension(image_path);
1183 if (add_extension_to_file_name(image_path, ".art")) {
1184 char app_image_format[kPropertyValueMax];
1185 bool have_app_image_format =
1186 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1187 if (!extract_only && have_app_image_format) {
1188 // Recreate is false since we want to avoid deleting the image in case dex2oat decides to
1189 // not compile anything.
1190 image_fd = open_output_file(image_path, /*recreate*/false);
1191 if (image_fd < 0) {
1192 // Could not create application image file. Go on since we can compile without it.
1193 ALOGE("installd could not create '%s' for image file during dexopt\n", image_path);
1194 } else if (!set_permissions_and_ownership(image_fd, is_public, uid, image_path)) {
1195 image_fd = -1;
1196 }
1197 }
1198 // If we have a valid image file path but no image fd, erase the image file.
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001199 if (image_fd < 0) {
Mathieu Chartier41fdcbf2016-02-03 14:25:02 -08001200 unlink(image_path);
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001201 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001202 }
Mathieu Chartiere80d58d2016-02-03 10:47:44 -08001203
Alex Light7365a102014-07-21 12:23:48 -07001204 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001205
1206 pid_t pid;
1207 pid = fork();
1208 if (pid == 0) {
1209 /* child -- drop privileges before continuing */
1210 if (setgid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001211 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001212 exit(64);
1213 }
1214 if (setuid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001215 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001216 exit(65);
1217 }
1218 // drop capabilities
1219 struct __user_cap_header_struct capheader;
1220 struct __user_cap_data_struct capdata[2];
1221 memset(&capheader, 0, sizeof(capheader));
1222 memset(&capdata, 0, sizeof(capdata));
1223 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1224 if (capset(&capheader, &capdata[0]) < 0) {
1225 ALOGE("capset failed: %s\n", strerror(errno));
1226 exit(66);
1227 }
Andreas Gampe13f14192015-09-21 13:21:30 -07001228 SetDex2OatAndPatchOatScheduling(boot_complete);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001229 if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
1230 ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001231 exit(67);
1232 }
1233
Richard Uhlerc92fb622015-03-26 15:47:38 -07001234 if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
1235 || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
Andreas Gampebd872e42014-12-15 11:41:11 -08001236 run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001237 } else if (dexopt_needed == DEXOPT_DEX2OAT_NEEDED) {
David Brazdilaaa1d4e2016-02-05 15:42:01 +00001238 // Pass dex2oat the relative path to the input file.
1239 const char *input_file_name = strrchr(input_file, '/');
1240 if (input_file_name == NULL) {
1241 input_file_name = input_file;
1242 } else {
1243 input_file_name++;
1244 }
1245 run_dex2oat(input_fd, out_fd, image_fd, input_file_name, out_path, swap_fd,
David Brazdilb0fad6d2015-12-30 11:16:04 +00001246 instruction_set, vm_safe_mode, debuggable, boot_complete, extract_only,
Calin Juravle60a794d2015-12-24 12:36:41 +02001247 profile_files_fd, reference_profile_files_fd);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001248 } else {
1249 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1250 exit(73);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001251 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001252 exit(68); /* only get here on exec failure */
1253 } else {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001254 res = wait_child(pid);
1255 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07001256 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001257 } else {
Alex Light7365a102014-07-21 12:23:48 -07001258 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001259 goto fail;
1260 }
1261 }
1262
Alex Light7365a102014-07-21 12:23:48 -07001263 ut.actime = input_stat.st_atime;
1264 ut.modtime = input_stat.st_mtime;
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001265 utime(out_path, &ut);
1266
1267 close(out_fd);
Alex Light7365a102014-07-21 12:23:48 -07001268 close(input_fd);
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001269 if (swap_fd >= 0) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001270 close(swap_fd);
1271 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001272 if (use_profiles != 0) {
1273 close_all_fds(profile_files_fd, "profile_files_fd");
1274 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1275 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001276 if (image_fd >= 0) {
1277 close(image_fd);
1278 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001279 return 0;
1280
1281fail:
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001282 if (out_fd >= 0) {
1283 close(out_fd);
1284 unlink(out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001285 }
Alex Light7365a102014-07-21 12:23:48 -07001286 if (input_fd >= 0) {
1287 close(input_fd);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001288 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001289 if (use_profiles != 0) {
1290 close_all_fds(profile_files_fd, "profile_files_fd");
1291 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1292 }
Mathieu Chartieredc8bc42015-10-21 14:05:28 -07001293 if (swap_fd >= 0) {
1294 close(swap_fd);
1295 }
1296 if (image_fd >= 0) {
1297 close(image_fd);
1298 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001299 return -1;
1300}
1301
Narayan Kamath091ea772014-11-10 15:03:46 +00001302int mark_boot_complete(const char* instruction_set)
1303{
1304 char boot_marker_path[PKG_PATH_MAX];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001305 sprintf(boot_marker_path,
1306 "%s/%s/%s/.booting",
1307 android_data_dir.path,
1308 DALVIK_CACHE,
1309 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001310
1311 ALOGV("mark_boot_complete : %s", boot_marker_path);
1312 if (unlink(boot_marker_path) != 0) {
1313 ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
1314 strerror(errno));
1315 return -1;
1316 }
1317
1318 return 0;
1319}
1320
Mike Lockwood94afecf2012-10-24 10:45:23 -07001321void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1322 struct stat* statbuf)
1323{
1324 while (path[basepos] != 0) {
1325 if (path[basepos] == '/') {
1326 path[basepos] = 0;
1327 if (lstat(path, statbuf) < 0) {
1328 ALOGV("Making directory: %s\n", path);
1329 if (mkdir(path, mode) == 0) {
1330 chown(path, uid, gid);
1331 } else {
1332 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1333 }
1334 }
1335 path[basepos] = '/';
1336 basepos++;
1337 }
1338 basepos++;
1339 }
1340}
1341
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001342int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001343{
Mike Lockwood94afecf2012-10-24 10:45:23 -07001344 struct stat s, libStat;
1345 int rc = 0;
1346
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001347 std::string _pkgdir(create_data_user_package_path(uuid, userId, pkgname));
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001348 std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
1349
1350 const char* pkgdir = _pkgdir.c_str();
1351 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001352
1353 if (stat(pkgdir, &s) < 0) return -1;
1354
1355 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1356 ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1357 return -1;
1358 }
1359
1360 if (chmod(pkgdir, 0700) < 0) {
1361 ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1362 rc = -1;
1363 goto out;
1364 }
1365
1366 if (lstat(libsymlink, &libStat) < 0) {
1367 if (errno != ENOENT) {
1368 ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1369 rc = -1;
1370 goto out;
1371 }
1372 } else {
1373 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001374 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001375 rc = -1;
1376 goto out;
1377 }
1378 } else if (S_ISLNK(libStat.st_mode)) {
1379 if (unlink(libsymlink) < 0) {
1380 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1381 rc = -1;
1382 goto out;
1383 }
1384 }
1385 }
1386
1387 if (symlink(asecLibDir, libsymlink) < 0) {
1388 ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1389 strerror(errno));
1390 rc = -errno;
1391 goto out;
1392 }
1393
1394out:
1395 if (chmod(pkgdir, s.st_mode) < 0) {
1396 ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1397 rc = -errno;
1398 }
1399
1400 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1401 ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1402 return -errno;
1403 }
1404
1405 return rc;
1406}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001407
1408static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1409{
1410 static const char *IDMAP_BIN = "/system/bin/idmap";
1411 static const size_t MAX_INT_LEN = 32;
1412 char idmap_str[MAX_INT_LEN];
1413
1414 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1415
1416 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1417 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1418}
1419
1420// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1421// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1422static int flatten_path(const char *prefix, const char *suffix,
1423 const char *overlay_path, char *idmap_path, size_t N)
1424{
1425 if (overlay_path == NULL || idmap_path == NULL) {
1426 return -1;
1427 }
1428 const size_t len_overlay_path = strlen(overlay_path);
1429 // will access overlay_path + 1 further below; requires absolute path
1430 if (len_overlay_path < 2 || *overlay_path != '/') {
1431 return -1;
1432 }
1433 const size_t len_idmap_root = strlen(prefix);
1434 const size_t len_suffix = strlen(suffix);
1435 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1436 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1437 // additions below would cause overflow
1438 return -1;
1439 }
1440 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1441 return -1;
1442 }
1443 memset(idmap_path, 0, N);
1444 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1445 char *ch = idmap_path + len_idmap_root;
1446 while (*ch != '\0') {
1447 if (*ch == '/') {
1448 *ch = '@';
1449 }
1450 ++ch;
1451 }
1452 return 0;
1453}
1454
1455int idmap(const char *target_apk, const char *overlay_apk, uid_t uid)
1456{
1457 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1458
1459 int idmap_fd = -1;
1460 char idmap_path[PATH_MAX];
1461
1462 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1463 idmap_path, sizeof(idmap_path)) == -1) {
1464 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1465 goto fail;
1466 }
1467
1468 unlink(idmap_path);
1469 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1470 if (idmap_fd < 0) {
1471 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1472 goto fail;
1473 }
1474 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1475 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1476 goto fail;
1477 }
1478 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1479 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1480 goto fail;
1481 }
1482
1483 pid_t pid;
1484 pid = fork();
1485 if (pid == 0) {
1486 /* child -- drop privileges before continuing */
1487 if (setgid(uid) != 0) {
1488 ALOGE("setgid(%d) failed during idmap\n", uid);
1489 exit(1);
1490 }
1491 if (setuid(uid) != 0) {
1492 ALOGE("setuid(%d) failed during idmap\n", uid);
1493 exit(1);
1494 }
1495 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1496 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1497 exit(1);
1498 }
1499
1500 run_idmap(target_apk, overlay_apk, idmap_fd);
1501 exit(1); /* only if exec call to idmap failed */
1502 } else {
1503 int status = wait_child(pid);
1504 if (status != 0) {
1505 ALOGE("idmap failed, status=0x%04x\n", status);
1506 goto fail;
1507 }
1508 }
1509
1510 close(idmap_fd);
1511 return 0;
1512fail:
1513 if (idmap_fd >= 0) {
1514 close(idmap_fd);
1515 unlink(idmap_path);
1516 }
1517 return -1;
1518}
Robert Craige9887e42014-02-20 10:25:56 -05001519
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001520int restorecon_app_data(const char* uuid, const char* pkgName, userid_t userid, int flags,
1521 appid_t appid, const char* seinfo) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001522 int res = 0;
Robert Craige9887e42014-02-20 10:25:56 -05001523
Robert Craigda30dc72014-03-27 10:21:12 -04001524 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001525 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Robert Craigda30dc72014-03-27 10:21:12 -04001526
1527 if (!pkgName || !seinfo) {
1528 ALOGE("Package name or seinfo tag is null when trying to restorecon.");
Robert Craige9887e42014-02-20 10:25:56 -05001529 return -1;
1530 }
1531
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001532 uid_t uid = multiuser_get_uid(userid, appid);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001533 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001534 auto path = create_data_user_package_path(uuid, userid, pkgName);
1535 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1536 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001537 res = -1;
1538 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001539 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001540 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001541 auto path = create_data_user_de_package_path(uuid, userid, pkgName);
1542 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1543 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyea0e4b12015-11-19 15:35:27 -07001544 // TODO: include result once 25796509 is fixed
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001545 }
Robert Craige9887e42014-02-20 10:25:56 -05001546 }
1547
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001548 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001549}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001550
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001551int create_oat_dir(const char* oat_dir, const char* instruction_set)
1552{
1553 char oat_instr_dir[PKG_PATH_MAX];
1554
1555 if (validate_apk_path(oat_dir)) {
1556 ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
1557 return -1;
1558 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001559 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001560 return -1;
1561 }
1562 if (selinux_android_restorecon(oat_dir, 0)) {
1563 ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
1564 return -1;
1565 }
1566 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001567 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001568 return -1;
1569 }
1570 return 0;
1571}
1572
1573int rm_package_dir(const char* apk_path)
1574{
1575 if (validate_apk_path(apk_path)) {
1576 ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
1577 return -1;
1578 }
1579 return delete_dir_contents(apk_path, 1 /* also_delete_dir */ , NULL /* exclusion_predicate */);
1580}
1581
Narayan Kamathd845c962015-06-04 13:20:27 +01001582int link_file(const char* relative_path, const char* from_base, const char* to_base) {
1583 char from_path[PKG_PATH_MAX];
1584 char to_path[PKG_PATH_MAX];
1585 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1586 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1587
1588 if (validate_apk_path_subdirs(from_path)) {
1589 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
1590 return -1;
1591 }
1592
1593 if (validate_apk_path_subdirs(to_path)) {
1594 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
1595 return -1;
1596 }
1597
1598 const int ret = link(from_path, to_path);
1599 if (ret < 0) {
1600 ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
1601 return -1;
1602 }
1603
1604 return 0;
1605}
1606
Andreas Gampe02d0de52015-11-11 20:43:16 -08001607} // namespace installd
1608} // namespace android