blob: 632a886a1b741e89783b5a481ac6a8b4c0c608ba [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>
26#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070027
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080028#include <android-base/stringprintf.h>
29#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <cutils/fs.h>
31#include <cutils/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070032#include <cutils/sched_policy.h>
33#include <diskusage/dirsize.h>
34#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070036#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <system/thread_defs.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070038
Andreas Gampe02d0de52015-11-11 20:43:16 -080039#include <globals.h>
40#include <installd_deps.h>
41#include <utils.h>
42
43#ifndef LOG_TAG
44#define LOG_TAG "installd"
45#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070046
47using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070048
Andreas Gampe02d0de52015-11-11 20:43:16 -080049namespace android {
50namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070051
Jeff Sharkeye3637242015-04-08 20:56:42 -070052static const char* kCpPath = "/system/bin/cp";
53
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000054#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
55
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070056int create_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000057 appid_t appid, const char* seinfo, int target_sdk_version) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070058 uid_t uid = multiuser_get_uid(userid, appid);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000059 int target_mode = target_sdk_version >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070060 if (flags & FLAG_CE_STORAGE) {
61 auto path = create_data_user_package_path(uuid, userid, pkgname);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000062 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070063 PLOG(ERROR) << "Failed to prepare " << path;
64 return -1;
65 }
66 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
67 PLOG(ERROR) << "Failed to setfilecon " << path;
68 return -1;
69 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070070 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070071 if (flags & FLAG_DE_STORAGE) {
72 auto path = create_data_user_de_package_path(uuid, userid, pkgname);
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000073 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) == -1) {
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070074 PLOG(ERROR) << "Failed to prepare " << path;
Jeff Sharkeya03c7472016-01-13 09:47:08 -070075 // TODO: include result once 25796509 is fixed
76 return 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070077 }
78 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
79 PLOG(ERROR) << "Failed to setfilecon " << path;
Jeff Sharkeya03c7472016-01-13 09:47:08 -070080 // TODO: include result once 25796509 is fixed
81 return 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070082 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070083 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070084 return 0;
85}
86
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070087int clear_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
88 std::string suffix = "";
89 if (flags & FLAG_CLEAR_CACHE_ONLY) {
90 suffix = CACHE_DIR_POSTFIX;
91 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
92 suffix = CODE_CACHE_DIR_POSTFIX;
93 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070094
Jeff Sharkeyebf728f2015-11-18 14:15:17 -070095 int res = 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070096 if (flags & FLAG_CE_STORAGE) {
97 auto path = create_data_user_package_path(uuid, userid, pkgname) + suffix;
98 if (access(path.c_str(), F_OK) == 0) {
99 res |= delete_dir_contents(path);
100 }
101 }
102 if (flags & FLAG_DE_STORAGE) {
103 auto path = create_data_user_de_package_path(uuid, userid, pkgname) + suffix;
104 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700105 // TODO: include result once 25796509 is fixed
106 delete_dir_contents(path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700107 }
108 }
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700109 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700110}
111
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700112int destroy_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
113 int res = 0;
114 if (flags & FLAG_CE_STORAGE) {
115 res |= delete_dir_contents_and_dir(
116 create_data_user_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700117 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700118 if (flags & FLAG_DE_STORAGE) {
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700119 // TODO: include result once 25796509 is fixed
120 delete_dir_contents_and_dir(
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700121 create_data_user_de_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700122 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700123 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700124}
125
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700126int move_complete_app(const char *from_uuid, const char *to_uuid, const char *package_name,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000127 const char *data_app_name, appid_t appid, const char* seinfo, int target_sdk_version) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700128 std::vector<userid_t> users = get_known_users(from_uuid);
129
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700130 // Copy app
131 {
132 std::string from(create_data_app_package_path(from_uuid, data_app_name));
133 std::string to(create_data_app_package_path(to_uuid, data_app_name));
134 std::string to_parent(create_data_app_path(to_uuid));
135
136 char *argv[] = {
137 (char*) kCpPath,
138 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
139 (char*) "-p", /* preserve timestamps, ownership, and permissions */
140 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
141 (char*) "-P", /* Do not follow symlinks [default] */
142 (char*) "-d", /* don't dereference symlinks */
143 (char*) from.c_str(),
144 (char*) to_parent.c_str()
145 };
146
147 LOG(DEBUG) << "Copying " << from << " to " << to;
148 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
149
150 if (rc != 0) {
151 LOG(ERROR) << "Failed copying " << from << " to " << to
152 << ": status " << rc;
153 goto fail;
154 }
155
156 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
157 LOG(ERROR) << "Failed to restorecon " << to;
158 goto fail;
159 }
160 }
161
162 // Copy private data for all known users
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700163 // TODO: handle user_de paths
Jeff Sharkeye3637242015-04-08 20:56:42 -0700164 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700165 std::string from(create_data_user_package_path(from_uuid, user, package_name));
166 std::string to(create_data_user_package_path(to_uuid, user, package_name));
167 std::string to_parent(create_data_user_path(to_uuid, user));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700168
169 // Data source may not exist for all users; that's okay
170 if (access(from.c_str(), F_OK) != 0) {
171 LOG(INFO) << "Missing source " << from;
172 continue;
173 }
174
175 std::string user_path(create_data_user_path(to_uuid, user));
176 if (fs_prepare_dir(user_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM) != 0) {
177 LOG(ERROR) << "Failed to prepare user target " << user_path;
178 goto fail;
179 }
180
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700181 if (create_app_data(to_uuid, package_name, user, FLAG_CE_STORAGE | FLAG_DE_STORAGE,
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000182 appid, seinfo, target_sdk_version) != 0) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700183 LOG(ERROR) << "Failed to create package target " << to;
184 goto fail;
185 }
186
187 char *argv[] = {
188 (char*) kCpPath,
189 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
190 (char*) "-p", /* preserve timestamps, ownership, and permissions */
191 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
192 (char*) "-P", /* Do not follow symlinks [default] */
193 (char*) "-d", /* don't dereference symlinks */
194 (char*) from.c_str(),
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700195 (char*) to_parent.c_str()
Jeff Sharkeye3637242015-04-08 20:56:42 -0700196 };
197
198 LOG(DEBUG) << "Copying " << from << " to " << to;
199 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
200
201 if (rc != 0) {
202 LOG(ERROR) << "Failed copying " << from << " to " << to
203 << ": status " << rc;
204 goto fail;
205 }
206
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700207 if (restorecon_app_data(to_uuid, package_name, user, FLAG_CE_STORAGE | FLAG_DE_STORAGE,
208 appid, seinfo) != 0) {
209 LOG(ERROR) << "Failed to restorecon";
210 goto fail;
211 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700212 }
213
Jeff Sharkey31f08982015-07-07 13:31:37 -0700214 // We let the framework scan the new location and persist that before
215 // deleting the data in the old location; this ordering ensures that
216 // we can recover from things like battery pulls.
Jeff Sharkeye3637242015-04-08 20:56:42 -0700217 return 0;
218
219fail:
220 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700221 {
222 std::string to(create_data_app_package_path(to_uuid, data_app_name));
223 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
224 LOG(WARNING) << "Failed to rollback " << to;
225 }
226 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700227 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700228 std::string to(create_data_user_package_path(to_uuid, user, package_name));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700229 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
230 LOG(WARNING) << "Failed to rollback " << to;
231 }
232 }
233 return -1;
234}
235
Robin Lee7c8bec02014-06-10 18:46:26 +0100236int make_user_config(userid_t userid)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700237{
Robin Lee095c7632014-04-25 15:05:19 +0100238 if (ensure_config_user_dirs(userid) == -1) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700239 return -1;
240 }
241
242 return 0;
243}
244
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700245int delete_user(const char *uuid, userid_t userid) {
246 int res = 0;
Robin Lee095c7632014-04-25 15:05:19 +0100247
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700248 std::string data_path(create_data_user_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700249 std::string data_de_path(create_data_user_de_path(uuid, userid));
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700250 std::string media_path(create_data_media_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700251
252 res |= delete_dir_contents_and_dir(data_path);
Jeff Sharkeya03c7472016-01-13 09:47:08 -0700253 // TODO: include result once 25796509 is fixed
254 delete_dir_contents_and_dir(data_de_path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700255 res |= delete_dir_contents_and_dir(media_path);
Robin Lee095c7632014-04-25 15:05:19 +0100256
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700257 // Config paths only exist on internal storage
258 if (uuid == nullptr) {
259 char config_path[PATH_MAX];
260 if ((create_user_config_path(config_path, userid) != 0)
261 || (delete_dir_contents(config_path, 1, NULL) != 0)) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700262 res = -1;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700263 }
Robin Lee095c7632014-04-25 15:05:19 +0100264 }
265
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700266 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100267}
268
Mike Lockwood94afecf2012-10-24 10:45:23 -0700269/* Try to ensure free_size bytes of storage are available.
270 * Returns 0 on success.
271 * This is rather simple-minded because doing a full LRU would
272 * be potentially memory-intensive, and without atime it would
273 * also require that apps constantly modify file metadata even
274 * when just reading from the cache, which is pretty awful.
275 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700276int free_cache(const char *uuid, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700277{
278 cache_t* cache;
279 int64_t avail;
280 DIR *d;
281 struct dirent *de;
282 char tmpdir[PATH_MAX];
283 char *dirpos;
284
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700285 std::string data_path(create_data_path(uuid));
286
287 avail = data_disk_free(data_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700288 if (avail < 0) return -1;
289
290 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
291 if (avail >= free_size) return 0;
292
293 cache = start_cache_collection();
294
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700295 // Special case for owner on internal storage
296 if (uuid == nullptr) {
297 std::string _tmpdir(create_data_user_path(nullptr, 0));
298 add_cache_files(cache, _tmpdir.c_str(), "cache");
Mike Lockwood94afecf2012-10-24 10:45:23 -0700299 }
300
301 // Search for other users and add any cache files from them.
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700302 std::string _tmpdir(create_data_path(uuid) + "/" + SECONDARY_USER_PREFIX);
303 strcpy(tmpdir, _tmpdir.c_str());
304
Mike Lockwood94afecf2012-10-24 10:45:23 -0700305 dirpos = tmpdir + strlen(tmpdir);
306 d = opendir(tmpdir);
307 if (d != NULL) {
308 while ((de = readdir(d))) {
309 if (de->d_type == DT_DIR) {
310 const char *name = de->d_name;
311 /* always skip "." and ".." */
312 if (name[0] == '.') {
313 if (name[1] == 0) continue;
314 if ((name[1] == '.') && (name[2] == 0)) continue;
315 }
316 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
317 strcpy(dirpos, name);
318 //ALOGI("adding cache files from %s\n", tmpdir);
319 add_cache_files(cache, tmpdir, "cache");
320 } else {
321 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
322 }
323 }
324 }
325 closedir(d);
326 }
327
328 // Collect cache files on external storage for all users (if it is mounted as part
329 // of the internal storage).
330 strcpy(tmpdir, android_media_dir.path);
331 dirpos = tmpdir + strlen(tmpdir);
332 d = opendir(tmpdir);
333 if (d != NULL) {
334 while ((de = readdir(d))) {
335 if (de->d_type == DT_DIR) {
336 const char *name = de->d_name;
337 /* skip any dir that doesn't start with a number, so not a user */
338 if (name[0] < '0' || name[0] > '9') {
339 continue;
340 }
341 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
342 strcpy(dirpos, name);
343 if (lookup_media_dir(tmpdir, "Android") == 0
344 && lookup_media_dir(tmpdir, "data") == 0) {
345 //ALOGI("adding cache files from %s\n", tmpdir);
346 add_cache_files(cache, tmpdir, "cache");
347 }
348 } else {
349 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
350 }
351 }
352 }
353 closedir(d);
354 }
355
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700356 clear_cache_files(data_path, cache, free_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700357 finish_cache_collection(cache);
358
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700359 return data_disk_free(data_path) >= free_size ? 0 : -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700360}
361
Narayan Kamath1b400322014-04-11 13:17:00 +0100362int rm_dex(const char *path, const char *instruction_set)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700363{
364 char dex_path[PKG_PATH_MAX];
365
Jeff Sharkey770180a2014-09-08 17:14:26 -0700366 if (validate_apk_path(path) && validate_system_app_path(path)) {
367 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
368 return -1;
369 }
370
Andreas Gampe02d0de52015-11-11 20:43:16 -0800371 if (!create_cache_path(dex_path, path, instruction_set)) return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700372
373 ALOGV("unlink %s\n", dex_path);
374 if (unlink(dex_path) < 0) {
Jeff Sharkey770180a2014-09-08 17:14:26 -0700375 if (errno != ENOENT) {
376 ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
377 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700378 return -1;
379 } else {
380 return 0;
381 }
382}
383
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700384int get_app_size(const char *uuid, const char *pkgname, int userid, int flags,
385 const char *apkpath, const char *libdirpath, const char *fwdlock_apkpath,
386 const char *asecpath, const char *instruction_set, int64_t *_codesize, int64_t *_datasize,
387 int64_t *_cachesize, int64_t* _asecsize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700388 DIR *d;
389 int dfd;
390 struct dirent *de;
391 struct stat s;
392 char path[PKG_PATH_MAX];
393
394 int64_t codesize = 0;
395 int64_t datasize = 0;
396 int64_t cachesize = 0;
397 int64_t asecsize = 0;
398
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700399 /* count the source apk as code -- but only if it's not
400 * on the /system partition and its not on the sdcard. */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700401 if (validate_system_app_path(apkpath) &&
402 strncmp(apkpath, android_asec_dir.path, android_asec_dir.len) != 0) {
403 if (stat(apkpath, &s) == 0) {
404 codesize += stat_size(&s);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700405 if (S_ISDIR(s.st_mode)) {
406 d = opendir(apkpath);
407 if (d != NULL) {
408 dfd = dirfd(d);
409 codesize += calculate_dir_size(dfd);
410 closedir(d);
411 }
412 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700413 }
414 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700415
416 /* count the forward locked apk as code if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700417 if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
418 if (stat(fwdlock_apkpath, &s) == 0) {
419 codesize += stat_size(&s);
420 }
421 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700422
423 /* count the cached dexfile as code */
Andreas Gampe02d0de52015-11-11 20:43:16 -0800424 if (create_cache_path(path, apkpath, instruction_set)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700425 if (stat(path, &s) == 0) {
426 codesize += stat_size(&s);
427 }
428 }
429
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700430 /* add in size of any libraries */
Dianne Hackborn8b417802013-05-01 18:55:10 -0700431 if (libdirpath != NULL && libdirpath[0] != '!') {
432 d = opendir(libdirpath);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700433 if (d != NULL) {
434 dfd = dirfd(d);
435 codesize += calculate_dir_size(dfd);
436 closedir(d);
437 }
438 }
439
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700440 /* compute asec size if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700441 if (asecpath != NULL && asecpath[0] != '!') {
442 if (stat(asecpath, &s) == 0) {
443 asecsize += stat_size(&s);
444 }
445 }
446
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700447 std::vector<userid_t> users;
448 if (userid == -1) {
449 users = get_known_users(uuid);
450 } else {
451 users.push_back(userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700452 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700453
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700454 for (auto user : users) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700455 // TODO: handle user_de directories
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700456 if (!(flags & FLAG_CE_STORAGE)) continue;
457
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700458 std::string _pkgdir(create_data_user_package_path(uuid, user, pkgname));
459 const char* pkgdir = _pkgdir.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700460
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700461 d = opendir(pkgdir);
462 if (d == NULL) {
463 PLOG(WARNING) << "Failed to open " << pkgdir;
464 continue;
465 }
466 dfd = dirfd(d);
467
468 /* most stuff in the pkgdir is data, except for the "cache"
469 * directory and below, which is cache, and the "lib" directory
470 * and below, which is code...
471 */
472 while ((de = readdir(d))) {
473 const char *name = de->d_name;
474
475 if (de->d_type == DT_DIR) {
476 int subfd;
477 int64_t statsize = 0;
478 int64_t dirsize = 0;
479 /* always skip "." and ".." */
480 if (name[0] == '.') {
481 if (name[1] == 0) continue;
482 if ((name[1] == '.') && (name[2] == 0)) continue;
483 }
484 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
485 statsize = stat_size(&s);
486 }
487 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
488 if (subfd >= 0) {
489 dirsize = calculate_dir_size(subfd);
490 }
491 if(!strcmp(name,"lib")) {
492 codesize += dirsize + statsize;
493 } else if(!strcmp(name,"cache")) {
494 cachesize += dirsize + statsize;
495 } else {
496 datasize += dirsize + statsize;
497 }
498 } else if (de->d_type == DT_LNK && !strcmp(name,"lib")) {
499 // This is the symbolic link to the application's library
500 // code. We'll count this as code instead of data, since
501 // it is not something that the app creates.
502 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
503 codesize += stat_size(&s);
504 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 } else {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700506 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
507 datasize += stat_size(&s);
508 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700509 }
510 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700511 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700512 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700513 *_codesize = codesize;
514 *_datasize = datasize;
515 *_cachesize = cachesize;
516 *_asecsize = asecsize;
517 return 0;
518}
519
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700520static int split_count(const char *str)
521{
522 char *ctx;
523 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800524 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700525
526 strncpy(buf, str, sizeof(buf));
527 char *pBuf = buf;
528
529 while(strtok_r(pBuf, " ", &ctx) != NULL) {
530 count++;
531 pBuf = NULL;
532 }
533
534 return count;
535}
536
neo.chae14e084d2015-01-07 18:46:13 +0900537static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700538{
539 char *ctx;
540 int count = 0;
541 char *tok;
542 char *pBuf = buf;
543
544 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
545 argv[count++] = tok;
546 pBuf = NULL;
547 }
548
549 return count;
550}
551
Alex Light7365a102014-07-21 12:23:48 -0700552static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800553 const char* output_file_name, const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -0700554{
555 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +0100556 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -0700557
558 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
559 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
560 ALOGE("Instruction set %s longer than max length of %d",
561 instruction_set, MAX_INSTRUCTION_SET_LEN);
562 return;
563 }
564
565 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
566 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
567 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
568 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
569 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
570 // The caller has already gotten all the locks we need.
571 const char* no_lock_arg = "--no-lock-output";
572 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
573 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", oat_fd);
574 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_fd);
Alex Lighta7915d42014-08-11 10:07:02 -0700575 ALOGV("Running %s isa=%s in-fd=%d (%s) out-fd=%d (%s)\n",
Alex Light7365a102014-07-21 12:23:48 -0700576 PATCHOAT_BIN, instruction_set, input_fd, input_file_name, oat_fd, output_file_name);
577
578 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
579 char* argv[7];
580 argv[0] = (char*) PATCHOAT_BIN;
581 argv[1] = (char*) patched_image_location_arg;
582 argv[2] = (char*) no_lock_arg;
583 argv[3] = instruction_set_arg;
584 argv[4] = output_oat_fd_arg;
585 argv[5] = input_oat_fd_arg;
586 argv[6] = NULL;
587
588 execv(PATCHOAT_BIN, (char* const *)argv);
589 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
590}
591
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700592static bool check_boolean_property(const char* property_name, bool default_value = false) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800593 char tmp_property_value[kPropertyValueMax];
594 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700595 if (!have_property) {
596 return default_value;
597 }
598 return strcmp(tmp_property_value, "true") == 0;
599}
600
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700601static void run_dex2oat(int zip_fd, int oat_fd, const char* input_file_name,
Calin Juravledf9dadd2015-11-04 14:47:37 +0000602 const char* output_file_name, int swap_fd, const char *instruction_set,
Calin Juravle60a794d2015-12-24 12:36:41 +0200603 bool vm_safe_mode, bool debuggable, bool post_bootcomplete, bool use_jit,
604 const std::vector<int>& profile_files_fd, const std::vector<int>& reference_profile_files_fd)
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700605{
Calin Juravle8fc73152014-08-19 18:48:50 +0100606 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
607
608 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
609 ALOGE("Instruction set %s longer than max length of %d",
610 instruction_set, MAX_INSTRUCTION_SET_LEN);
611 return;
612 }
613
Calin Juravle60a794d2015-12-24 12:36:41 +0200614 if (profile_files_fd.size() != reference_profile_files_fd.size()) {
615 ALOGE("Invalid configuration of profile files: pf_size (%zu) != rpf_size (%zu)",
616 profile_files_fd.size(), reference_profile_files_fd.size());
617 return;
618 }
619
Andreas Gampe02d0de52015-11-11 20:43:16 -0800620 char dex2oat_Xms_flag[kPropertyValueMax];
621 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700622
Andreas Gampe02d0de52015-11-11 20:43:16 -0800623 char dex2oat_Xmx_flag[kPropertyValueMax];
624 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700625
Andreas Gampe02d0de52015-11-11 20:43:16 -0800626 char dex2oat_compiler_filter_flag[kPropertyValueMax];
627 bool have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700628 dex2oat_compiler_filter_flag, NULL) > 0;
629
Andreas Gampe02d0de52015-11-11 20:43:16 -0800630 char dex2oat_threads_buf[kPropertyValueMax];
631 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -0700632 ? "dalvik.vm.dex2oat-threads"
633 : "dalvik.vm.boot-dex2oat-threads",
634 dex2oat_threads_buf,
635 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800636 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700637 if (have_dex2oat_threads_flag) {
638 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
639 }
640
Andreas Gampe02d0de52015-11-11 20:43:16 -0800641 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +0100642 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800643 char dex2oat_isa_features[kPropertyValueMax];
644 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +0100645 dex2oat_isa_features, NULL) > 0;
646
Andreas Gampe02d0de52015-11-11 20:43:16 -0800647 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -0800648 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800649 char dex2oat_isa_variant[kPropertyValueMax];
650 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -0800651 dex2oat_isa_variant, NULL) > 0;
652
neo.chae14e084d2015-01-07 18:46:13 +0900653 const char *dex2oat_norelocation = "-Xnorelocate";
654 bool have_dex2oat_relocation_skip_flag = false;
655
Andreas Gampe02d0de52015-11-11 20:43:16 -0800656 char dex2oat_flags[kPropertyValueMax];
657 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700658 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -0800659 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
660
Brian Carlstrom538998f2014-07-30 14:37:11 -0700661 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -0800662 char vold_decrypt[kPropertyValueMax];
663 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700664 bool skip_compilation = (have_vold_decrypt &&
665 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
666 (strcmp(vold_decrypt, "1") == 0)));
667
David Srbecky528c8dd2015-05-28 16:55:50 +0100668 bool generate_debug_info = check_boolean_property("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700669
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700670 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700671
Brian Carlstrom53e07762014-06-27 14:15:19 -0700672 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700673
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700674 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +0100675
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700676 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
677 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
678 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -0700679 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +0100680 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -0800681 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
682 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
683 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
684 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
685 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -0800686 bool have_dex2oat_swap_fd = false;
687 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700688
689 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
690 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
691 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
692 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +0100693 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -0800694 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +0100695 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -0800696 if (swap_fd >= 0) {
697 have_dex2oat_swap_fd = true;
698 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
699 }
Calin Juravle57c69c32014-06-06 14:42:16 +0100700
Todd Kennedy12434f82015-09-25 14:45:37 -0700701 // use the JIT if either it's specified as a dexopt flag or if the property is set
702 use_jit = use_jit || check_boolean_property("debug.usejit");
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700703 if (have_dex2oat_Xms_flag) {
704 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
705 }
706 if (have_dex2oat_Xmx_flag) {
707 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
708 }
Brian Carlstrom538998f2014-07-30 14:37:11 -0700709 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -0700710 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -0700711 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +0900712 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +0100713 } else if (vm_safe_mode) {
714 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +0100715 have_dex2oat_compiler_filter_flag = true;
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700716 } else if (use_jit) {
717 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-at-runtime");
718 have_dex2oat_compiler_filter_flag = true;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700719 } else if (have_dex2oat_compiler_filter_flag) {
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700720 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", dex2oat_compiler_filter_flag);
721 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700722
Andreas Gampe598c25e2015-03-03 09:15:06 -0800723 // Check whether all apps should be compiled debuggable.
724 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800725 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -0800726 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -0800727 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -0800728 (prop_buf[0] == '1');
729 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200730 std::vector<std::string> profile_file_args(profile_files_fd.size());
731 std::vector<std::string> reference_profile_file_args(profile_files_fd.size());
732 // "reference-profile-file-fd" is longer than "profile-file-fd" so we can
733 // use it to set the max length.
734 char profile_buf[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
735 for (size_t k = 0; k < profile_files_fd.size(); k++) {
736 sprintf(profile_buf, "--profile-file-fd=%d", profile_files_fd[k]);
737 profile_file_args[k].assign(profile_buf);
738 sprintf(profile_buf, "--reference-profile-file-fd=%d", reference_profile_files_fd[k]);
739 reference_profile_file_args[k].assign(profile_buf);
740 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800741
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700742 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +0100743
neo.chae14e084d2015-01-07 18:46:13 +0900744 const char* argv[7 // program name, mandatory arguments and the final NULL
745 + (have_dex2oat_isa_variant ? 1 : 0)
746 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900747 + (have_dex2oat_Xms_flag ? 2 : 0)
748 + (have_dex2oat_Xmx_flag ? 2 : 0)
749 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700750 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900751 + (have_dex2oat_swap_fd ? 1 : 0)
752 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +0100753 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -0800754 + (debuggable ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +0200755 + dex2oat_flags_count
756 + profile_files_fd.size()
757 + reference_profile_files_fd.size()];
Calin Juravle4fdff462014-06-06 16:58:43 +0100758 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +0900759 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +0100760 argv[i++] = zip_fd_arg;
761 argv[i++] = zip_location_arg;
762 argv[i++] = oat_fd_arg;
763 argv[i++] = oat_location_arg;
764 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -0800765 if (have_dex2oat_isa_variant) {
766 argv[i++] = instruction_set_variant_arg;
767 }
Calin Juravle8fc73152014-08-19 18:48:50 +0100768 if (have_dex2oat_isa_features) {
769 argv[i++] = instruction_set_features_arg;
770 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700771 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900772 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700773 argv[i++] = dex2oat_Xms_arg;
774 }
775 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900776 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700777 argv[i++] = dex2oat_Xmx_arg;
778 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700779 if (have_dex2oat_compiler_filter_flag) {
780 argv[i++] = dex2oat_compiler_filter_arg;
781 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700782 if (have_dex2oat_threads_flag) {
783 argv[i++] = dex2oat_threads_arg;
784 }
Andreas Gampee1c01352014-12-10 16:41:11 -0800785 if (have_dex2oat_swap_fd) {
786 argv[i++] = dex2oat_swap_fd;
787 }
David Srbecky528c8dd2015-05-28 16:55:50 +0100788 if (generate_debug_info) {
789 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700790 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800791 if (debuggable) {
792 argv[i++] = "--debuggable";
793 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700794 if (dex2oat_flags_count) {
795 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +0100796 }
neo.chae14e084d2015-01-07 18:46:13 +0900797 if (have_dex2oat_relocation_skip_flag) {
798 argv[i++] = RUNTIME_ARG;
799 argv[i++] = dex2oat_norelocation;
800 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200801 for (size_t k = 0; k < profile_file_args.size(); k++) {
802 argv[i++] = profile_file_args[k].c_str();
803 argv[i++] = reference_profile_file_args[k].c_str();
804 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700805 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +0100806 argv[i] = NULL;
807
neo.chae14e084d2015-01-07 18:46:13 +0900808 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700809 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700810}
811
Andreas Gampee1c01352014-12-10 16:41:11 -0800812/*
Andreas Gampec968c012015-07-16 15:55:41 -0700813 * Whether dexopt should use a swap file when compiling an APK.
814 *
815 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
816 * itself, anyways).
817 *
818 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
819 *
820 * Otherwise, return true if this is a low-mem device.
821 *
822 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -0800823 */
Andreas Gampec968c012015-07-16 15:55:41 -0700824static bool kAlwaysProvideSwapFile = false;
825static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -0800826
827static bool ShouldUseSwapFileForDexopt() {
828 if (kAlwaysProvideSwapFile) {
829 return true;
830 }
831
Andreas Gampec968c012015-07-16 15:55:41 -0700832 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -0800833 char dex2oat_prop_buf[kPropertyValueMax];
834 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -0700835 if (strcmp(dex2oat_prop_buf, "true") == 0) {
836 return true;
837 } else {
838 return false;
839 }
840 }
841
842 // Shortcut for default value. This is an implementation optimization for the process sketched
843 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
844 // as low-mem is never returning false. The compiler will optimize this away if it can.
845 if (kDefaultProvideSwapFile) {
846 return true;
847 }
848
849 bool is_low_mem = check_boolean_property("ro.config.low_ram");
850 if (is_low_mem) {
851 return true;
852 }
853
854 // Default value must be false here.
855 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -0800856}
857
Andreas Gampe94dd3d32015-09-14 16:33:11 -0700858static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
859 if (set_to_bg) {
860 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
861 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
862 exit(70);
863 }
864 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
865 ALOGE("setpriority failed: %s\n", strerror(errno));
866 exit(71);
867 }
868 }
869}
870
Calin Juravle60a794d2015-12-24 12:36:41 +0200871constexpr const char* PROFILE_FILE_EXTENSION = ".prof";
872constexpr const char* REFERENCE_PROFILE_FILE_EXTENSION = ".prof.ref";
873
874static void close_all_fds(const std::vector<int>& fds, const char* description) {
875 for (size_t i = 0; i < fds.size(); i++) {
876 if (close(fds[i]) != 0) {
877 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
878 }
879 }
880}
881
882static int open_code_cache_for_user(userid_t user, const char* volume_uuid, const char* pkgname) {
883 std::string code_cache_path =
884 create_data_user_package_path(volume_uuid, user, pkgname) + CODE_CACHE_DIR_POSTFIX;
885
886 struct stat buffer;
887 // Check that the code cache exists. If not, return and don't log an error.
888 if (TEMP_FAILURE_RETRY(lstat(code_cache_path.c_str(), &buffer)) == -1) {
889 if (errno != ENOENT) {
890 PLOG(ERROR) << "Failed to lstat code_cache: " << code_cache_path;
891 return -1;
892 }
893 }
894
895 int code_cache_fd = open(code_cache_path.c_str(),
896 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
897 if (code_cache_fd < 0) {
898 PLOG(ERROR) << "Failed to open code_cache: " << code_cache_path;
899 }
900 return code_cache_fd;
901}
902
903// Keep profile paths in sync with ActivityThread.
904static void open_profile_files_for_user(uid_t uid, const char* pkgname, int code_cache_fd,
905 /*out*/ int* profile_fd, /*out*/ int* reference_profile_fd) {
906 *profile_fd = -1;
907 *reference_profile_fd = -1;
908 std::string profile_file(pkgname);
909 profile_file += PROFILE_FILE_EXTENSION;
910
911 // Check if the profile exists. If not, early return and don't log an error.
912 struct stat buffer;
913 if (TEMP_FAILURE_RETRY(fstatat(
914 code_cache_fd, profile_file.c_str(), &buffer, AT_SYMLINK_NOFOLLOW)) == -1) {
915 if (errno != ENOENT) {
916 PLOG(ERROR) << "Failed to fstatat profile file: " << profile_file;
917 return;
918 }
919 }
920
921 // Open in read-write to allow transfer of information from the current profile
922 // to the reference profile.
923 *profile_fd = openat(code_cache_fd, profile_file.c_str(), O_RDWR | O_NOFOLLOW);
924 if (*profile_fd < 0) {
925 PLOG(ERROR) << "Failed to open profile file: " << profile_file;
926 return;
927 }
928
929 std::string reference_profile(pkgname);
930 reference_profile += REFERENCE_PROFILE_FILE_EXTENSION;
931 // Give read-write permissions just for the user (changed with fchown after opening).
932 // We need write permission because dex2oat will update the reference profile files
933 // with the content of the corresponding current profile files.
934 *reference_profile_fd = openat(code_cache_fd, reference_profile.c_str(),
935 O_CREAT | O_RDWR | O_NOFOLLOW, S_IWUSR | S_IRUSR);
936 if (*reference_profile_fd < 0) {
937 close(*profile_fd);
938 return;
939 }
940 if (fchown(*reference_profile_fd, uid, uid) < 0) {
941 PLOG(ERROR) << "Cannot change reference profile file owner: " << reference_profile;
942 close(*profile_fd);
943 *profile_fd = -1;
944 *reference_profile_fd = -1;
945 }
946}
947
948static void open_profile_files(const char* volume_uuid, uid_t uid, const char* pkgname,
949 std::vector<int>* profile_fds, std::vector<int>* reference_profile_fds) {
950 std::vector<userid_t> users = get_known_users(volume_uuid);
951 for (auto user : users) {
952 int code_cache_fd = open_code_cache_for_user(user, volume_uuid, pkgname);
953 if (code_cache_fd < 0) {
954 continue;
955 }
956 int profile_fd = -1;
957 int reference_profile_fd = -1;
958 open_profile_files_for_user(
959 uid, pkgname, code_cache_fd, &profile_fd, &reference_profile_fd);
960 close(code_cache_fd);
961
962 // Add to the lists only if both fds are valid.
963 if ((profile_fd >= 0) && (reference_profile_fd >= 0)) {
964 profile_fds->push_back(profile_fd);
965 reference_profile_fds->push_back(reference_profile_fd);
966 }
967 }
968}
969
970int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
971 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* volume_uuid,
972 bool use_profiles)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700973{
974 struct utimbuf ut;
Fyodor Kupolov26ff93c2015-04-02 16:59:10 -0700975 struct stat input_stat;
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700976 char out_path[PKG_PATH_MAX];
Andreas Gampee1c01352014-12-10 16:41:11 -0800977 char swap_file_name[PKG_PATH_MAX];
Alex Light7365a102014-07-21 12:23:48 -0700978 const char *input_file;
979 char in_odex_path[PKG_PATH_MAX];
Andreas Gampee1c01352014-12-10 16:41:11 -0800980 int res, input_fd=-1, out_fd=-1, swap_fd=-1;
Todd Kennedy76e767c2015-09-25 07:47:47 -0700981 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
982 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
983 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
984 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Todd Kennedy12434f82015-09-25 14:45:37 -0700985 bool use_jit = (dexopt_flags & DEXOPT_USEJIT) != 0;
Calin Juravle60a794d2015-12-24 12:36:41 +0200986 std::vector<int> profile_files_fd;
987 std::vector<int> reference_profile_files_fd;
988 if (use_profiles) {
989 open_profile_files(volume_uuid, uid, pkgname,
990 &profile_files_fd, &reference_profile_files_fd);
991 if (profile_files_fd.empty()) {
992 // Skip profile guided compilation because no profiles were found.
993 return 0;
994 }
995 }
Todd Kennedy76e767c2015-09-25 07:47:47 -0700996
Todd Kennedye296e002015-11-16 14:41:36 -0800997 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -0700998 LOG_FATAL("dexopt flags contains unknown fields\n");
999 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001000
Andreas Gampee1c01352014-12-10 16:41:11 -08001001 // Early best-effort check whether we can fit the the path into our buffers.
1002 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1003 // without a swap file, if necessary.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001004 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001005 ALOGE("apk_path too long '%s'\n", apk_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001006 return -1;
1007 }
1008
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001009 if (oat_dir != NULL && oat_dir[0] != '!') {
1010 if (validate_apk_path(oat_dir)) {
1011 ALOGE("invalid oat_dir '%s'\n", oat_dir);
1012 return -1;
Chih-Wei Huang0e8ae162014-04-28 15:47:45 +08001013 }
Andreas Gampe02d0de52015-11-11 20:43:16 -08001014 if (!calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001015 return -1;
1016 }
1017 } else {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001018 if (!create_cache_path(out_path, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001019 return -1;
1020 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001021 }
1022
Richard Uhlerc92fb622015-03-26 15:47:38 -07001023 switch (dexopt_needed) {
1024 case DEXOPT_DEX2OAT_NEEDED:
1025 input_file = apk_path;
1026 break;
1027
1028 case DEXOPT_PATCHOAT_NEEDED:
1029 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1030 return -1;
1031 }
1032 input_file = in_odex_path;
1033 break;
1034
1035 case DEXOPT_SELF_PATCHOAT_NEEDED:
1036 input_file = out_path;
1037 break;
1038
1039 default:
1040 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1041 exit(72);
Alex Light7365a102014-07-21 12:23:48 -07001042 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001043
Alex Light7365a102014-07-21 12:23:48 -07001044 memset(&input_stat, 0, sizeof(input_stat));
1045 stat(input_file, &input_stat);
1046
1047 input_fd = open(input_file, O_RDONLY, 0);
1048 if (input_fd < 0) {
1049 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001050 return -1;
1051 }
1052
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001053 unlink(out_path);
1054 out_fd = open(out_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1055 if (out_fd < 0) {
1056 ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001057 goto fail;
1058 }
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001059 if (fchmod(out_fd,
Mike Lockwood94afecf2012-10-24 10:45:23 -07001060 S_IRUSR|S_IWUSR|S_IRGRP |
1061 (is_public ? S_IROTH : 0)) < 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001062 ALOGE("installd cannot chmod '%s' during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001063 goto fail;
1064 }
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001065 if (fchown(out_fd, AID_SYSTEM, uid) < 0) {
1066 ALOGE("installd cannot chown '%s' during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001067 goto fail;
1068 }
1069
Andreas Gampee1c01352014-12-10 16:41:11 -08001070 // Create a swap file if necessary.
Richard Uhlerc92fb622015-03-26 15:47:38 -07001071 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001072 // Make sure there really is enough space.
1073 size_t out_len = strlen(out_path);
1074 if (out_len + strlen(".swap") + 1 <= PKG_PATH_MAX) {
1075 strcpy(swap_file_name, out_path);
1076 strcpy(swap_file_name + strlen(out_path), ".swap");
1077 unlink(swap_file_name);
1078 swap_fd = open(swap_file_name, O_RDWR | O_CREAT | O_EXCL, 0600);
1079 if (swap_fd < 0) {
1080 // Could not create swap file. Optimistically go on and hope that we can compile
1081 // without it.
1082 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1083 } else {
1084 // Immediately unlink. We don't really want to hit flash.
1085 unlink(swap_file_name);
1086 }
1087 } else {
1088 // Swap file path is too long. Try to run without.
1089 ALOGE("installd could not create swap file for path %s during dexopt\n", out_path);
1090 }
1091 }
Dave Allisond9370732014-01-30 14:19:23 -08001092
Alex Light7365a102014-07-21 12:23:48 -07001093 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001094
1095 pid_t pid;
1096 pid = fork();
1097 if (pid == 0) {
1098 /* child -- drop privileges before continuing */
1099 if (setgid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001100 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001101 exit(64);
1102 }
1103 if (setuid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001104 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001105 exit(65);
1106 }
1107 // drop capabilities
1108 struct __user_cap_header_struct capheader;
1109 struct __user_cap_data_struct capdata[2];
1110 memset(&capheader, 0, sizeof(capheader));
1111 memset(&capdata, 0, sizeof(capdata));
1112 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1113 if (capset(&capheader, &capdata[0]) < 0) {
1114 ALOGE("capset failed: %s\n", strerror(errno));
1115 exit(66);
1116 }
Andreas Gampe13f14192015-09-21 13:21:30 -07001117 SetDex2OatAndPatchOatScheduling(boot_complete);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001118 if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
1119 ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001120 exit(67);
1121 }
1122
Richard Uhlerc92fb622015-03-26 15:47:38 -07001123 if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
1124 || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
Andreas Gampebd872e42014-12-15 11:41:11 -08001125 run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001126 } else if (dexopt_needed == DEXOPT_DEX2OAT_NEEDED) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001127 run_dex2oat(input_fd, out_fd, input_file, out_path, swap_fd,
1128 instruction_set, vm_safe_mode, debuggable, boot_complete, use_jit,
1129 profile_files_fd, reference_profile_files_fd);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001130 } else {
1131 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1132 exit(73);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001133 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001134 exit(68); /* only get here on exec failure */
1135 } else {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001136 res = wait_child(pid);
1137 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07001138 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001139 } else {
Alex Light7365a102014-07-21 12:23:48 -07001140 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001141 goto fail;
1142 }
1143 }
1144
Alex Light7365a102014-07-21 12:23:48 -07001145 ut.actime = input_stat.st_atime;
1146 ut.modtime = input_stat.st_mtime;
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001147 utime(out_path, &ut);
1148
1149 close(out_fd);
Alex Light7365a102014-07-21 12:23:48 -07001150 close(input_fd);
Andreas Gampee1c01352014-12-10 16:41:11 -08001151 if (swap_fd != -1) {
1152 close(swap_fd);
1153 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001154 if (use_profiles != 0) {
1155 close_all_fds(profile_files_fd, "profile_files_fd");
1156 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1157 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001158 return 0;
1159
1160fail:
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001161 if (out_fd >= 0) {
1162 close(out_fd);
1163 unlink(out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001164 }
Alex Light7365a102014-07-21 12:23:48 -07001165 if (input_fd >= 0) {
1166 close(input_fd);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001167 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001168 if (use_profiles != 0) {
1169 close_all_fds(profile_files_fd, "profile_files_fd");
1170 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1171 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001172 return -1;
1173}
1174
Narayan Kamath091ea772014-11-10 15:03:46 +00001175int mark_boot_complete(const char* instruction_set)
1176{
1177 char boot_marker_path[PKG_PATH_MAX];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001178 sprintf(boot_marker_path,
1179 "%s/%s/%s/.booting",
1180 android_data_dir.path,
1181 DALVIK_CACHE,
1182 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001183
1184 ALOGV("mark_boot_complete : %s", boot_marker_path);
1185 if (unlink(boot_marker_path) != 0) {
1186 ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
1187 strerror(errno));
1188 return -1;
1189 }
1190
1191 return 0;
1192}
1193
Mike Lockwood94afecf2012-10-24 10:45:23 -07001194void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1195 struct stat* statbuf)
1196{
1197 while (path[basepos] != 0) {
1198 if (path[basepos] == '/') {
1199 path[basepos] = 0;
1200 if (lstat(path, statbuf) < 0) {
1201 ALOGV("Making directory: %s\n", path);
1202 if (mkdir(path, mode) == 0) {
1203 chown(path, uid, gid);
1204 } else {
1205 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1206 }
1207 }
1208 path[basepos] = '/';
1209 basepos++;
1210 }
1211 basepos++;
1212 }
1213}
1214
1215int movefileordir(char* srcpath, char* dstpath, int dstbasepos,
1216 int dstuid, int dstgid, struct stat* statbuf)
1217{
1218 DIR *d;
1219 struct dirent *de;
1220 int res;
1221
1222 int srcend = strlen(srcpath);
1223 int dstend = strlen(dstpath);
Dave Allisond9370732014-01-30 14:19:23 -08001224
Mike Lockwood94afecf2012-10-24 10:45:23 -07001225 if (lstat(srcpath, statbuf) < 0) {
1226 ALOGW("Unable to stat %s: %s\n", srcpath, strerror(errno));
1227 return 1;
1228 }
Dave Allisond9370732014-01-30 14:19:23 -08001229
Mike Lockwood94afecf2012-10-24 10:45:23 -07001230 if ((statbuf->st_mode&S_IFDIR) == 0) {
1231 mkinnerdirs(dstpath, dstbasepos, S_IRWXU|S_IRWXG|S_IXOTH,
1232 dstuid, dstgid, statbuf);
1233 ALOGV("Renaming %s to %s (uid %d)\n", srcpath, dstpath, dstuid);
1234 if (rename(srcpath, dstpath) >= 0) {
1235 if (chown(dstpath, dstuid, dstgid) < 0) {
1236 ALOGE("cannot chown %s: %s\n", dstpath, strerror(errno));
1237 unlink(dstpath);
1238 return 1;
1239 }
1240 } else {
1241 ALOGW("Unable to rename %s to %s: %s\n",
1242 srcpath, dstpath, strerror(errno));
1243 return 1;
1244 }
1245 return 0;
1246 }
1247
1248 d = opendir(srcpath);
1249 if (d == NULL) {
1250 ALOGW("Unable to opendir %s: %s\n", srcpath, strerror(errno));
1251 return 1;
1252 }
1253
1254 res = 0;
Dave Allisond9370732014-01-30 14:19:23 -08001255
Mike Lockwood94afecf2012-10-24 10:45:23 -07001256 while ((de = readdir(d))) {
1257 const char *name = de->d_name;
1258 /* always skip "." and ".." */
1259 if (name[0] == '.') {
1260 if (name[1] == 0) continue;
1261 if ((name[1] == '.') && (name[2] == 0)) continue;
1262 }
Dave Allisond9370732014-01-30 14:19:23 -08001263
Mike Lockwood94afecf2012-10-24 10:45:23 -07001264 if ((srcend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1265 ALOGW("Source path too long; skipping: %s/%s\n", srcpath, name);
1266 continue;
1267 }
Dave Allisond9370732014-01-30 14:19:23 -08001268
Mike Lockwood94afecf2012-10-24 10:45:23 -07001269 if ((dstend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1270 ALOGW("Destination path too long; skipping: %s/%s\n", dstpath, name);
1271 continue;
1272 }
Dave Allisond9370732014-01-30 14:19:23 -08001273
Mike Lockwood94afecf2012-10-24 10:45:23 -07001274 srcpath[srcend] = dstpath[dstend] = '/';
1275 strcpy(srcpath+srcend+1, name);
1276 strcpy(dstpath+dstend+1, name);
Dave Allisond9370732014-01-30 14:19:23 -08001277
Mike Lockwood94afecf2012-10-24 10:45:23 -07001278 if (movefileordir(srcpath, dstpath, dstbasepos, dstuid, dstgid, statbuf) != 0) {
1279 res = 1;
1280 }
Dave Allisond9370732014-01-30 14:19:23 -08001281
Mike Lockwood94afecf2012-10-24 10:45:23 -07001282 // Note: we will be leaving empty directories behind in srcpath,
1283 // but that is okay, the package manager will be erasing all of the
1284 // data associated with .apks that disappear.
Dave Allisond9370732014-01-30 14:19:23 -08001285
Mike Lockwood94afecf2012-10-24 10:45:23 -07001286 srcpath[srcend] = dstpath[dstend] = 0;
1287 }
Dave Allisond9370732014-01-30 14:19:23 -08001288
Mike Lockwood94afecf2012-10-24 10:45:23 -07001289 closedir(d);
1290 return res;
1291}
1292
1293int movefiles()
1294{
1295 DIR *d;
1296 int dfd, subfd;
1297 struct dirent *de;
1298 struct stat s;
1299 char buf[PKG_PATH_MAX+1];
1300 int bufp, bufe, bufi, readlen;
1301
1302 char srcpkg[PKG_NAME_MAX];
1303 char dstpkg[PKG_NAME_MAX];
1304 char srcpath[PKG_PATH_MAX];
1305 char dstpath[PKG_PATH_MAX];
1306 int dstuid=-1, dstgid=-1;
1307 int hasspace;
1308
1309 d = opendir(UPDATE_COMMANDS_DIR_PREFIX);
1310 if (d == NULL) {
1311 goto done;
1312 }
1313 dfd = dirfd(d);
1314
1315 /* Iterate through all files in the directory, executing the
1316 * file movements requested there-in.
1317 */
1318 while ((de = readdir(d))) {
1319 const char *name = de->d_name;
1320
1321 if (de->d_type == DT_DIR) {
1322 continue;
1323 } else {
1324 subfd = openat(dfd, name, O_RDONLY);
1325 if (subfd < 0) {
1326 ALOGW("Unable to open update commands at %s%s\n",
1327 UPDATE_COMMANDS_DIR_PREFIX, name);
1328 continue;
1329 }
Dave Allisond9370732014-01-30 14:19:23 -08001330
Mike Lockwood94afecf2012-10-24 10:45:23 -07001331 bufp = 0;
1332 bufe = 0;
1333 buf[PKG_PATH_MAX] = 0;
1334 srcpkg[0] = dstpkg[0] = 0;
1335 while (1) {
1336 bufi = bufp;
1337 while (bufi < bufe && buf[bufi] != '\n') {
1338 bufi++;
1339 }
1340 if (bufi < bufe) {
1341 buf[bufi] = 0;
1342 ALOGV("Processing line: %s\n", buf+bufp);
1343 hasspace = 0;
1344 while (bufp < bufi && isspace(buf[bufp])) {
1345 hasspace = 1;
1346 bufp++;
1347 }
1348 if (buf[bufp] == '#' || bufp == bufi) {
1349 // skip comments and empty lines.
1350 } else if (hasspace) {
1351 if (dstpkg[0] == 0) {
1352 ALOGW("Path before package line in %s%s: %s\n",
1353 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1354 } else if (srcpkg[0] == 0) {
1355 // Skip -- source package no longer exists.
1356 } else {
1357 ALOGV("Move file: %s (from %s to %s)\n", buf+bufp, srcpkg, dstpkg);
1358 if (!create_move_path(srcpath, srcpkg, buf+bufp, 0) &&
1359 !create_move_path(dstpath, dstpkg, buf+bufp, 0)) {
1360 movefileordir(srcpath, dstpath,
1361 strlen(dstpath)-strlen(buf+bufp),
1362 dstuid, dstgid, &s);
1363 }
1364 }
1365 } else {
1366 char* div = strchr(buf+bufp, ':');
1367 if (div == NULL) {
1368 ALOGW("Bad package spec in %s%s; no ':' sep: %s\n",
1369 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1370 } else {
1371 *div = 0;
1372 div++;
1373 if (strlen(buf+bufp) < PKG_NAME_MAX) {
1374 strcpy(dstpkg, buf+bufp);
1375 } else {
1376 srcpkg[0] = dstpkg[0] = 0;
1377 ALOGW("Package name too long in %s%s: %s\n",
1378 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1379 }
1380 if (strlen(div) < PKG_NAME_MAX) {
1381 strcpy(srcpkg, div);
1382 } else {
1383 srcpkg[0] = dstpkg[0] = 0;
1384 ALOGW("Package name too long in %s%s: %s\n",
1385 UPDATE_COMMANDS_DIR_PREFIX, name, div);
1386 }
1387 if (srcpkg[0] != 0) {
1388 if (!create_pkg_path(srcpath, srcpkg, PKG_DIR_POSTFIX, 0)) {
1389 if (lstat(srcpath, &s) < 0) {
1390 // Package no longer exists -- skip.
1391 srcpkg[0] = 0;
1392 }
1393 } else {
1394 srcpkg[0] = 0;
1395 ALOGW("Can't create path %s in %s%s\n",
1396 div, UPDATE_COMMANDS_DIR_PREFIX, name);
1397 }
1398 if (srcpkg[0] != 0) {
1399 if (!create_pkg_path(dstpath, dstpkg, PKG_DIR_POSTFIX, 0)) {
1400 if (lstat(dstpath, &s) == 0) {
1401 dstuid = s.st_uid;
1402 dstgid = s.st_gid;
1403 } else {
1404 // Destination package doesn't
1405 // exist... due to original-package,
1406 // this is normal, so don't be
1407 // noisy about it.
1408 srcpkg[0] = 0;
1409 }
1410 } else {
1411 srcpkg[0] = 0;
1412 ALOGW("Can't create path %s in %s%s\n",
1413 div, UPDATE_COMMANDS_DIR_PREFIX, name);
1414 }
1415 }
1416 ALOGV("Transfering from %s to %s: uid=%d\n",
1417 srcpkg, dstpkg, dstuid);
1418 }
1419 }
1420 }
1421 bufp = bufi+1;
1422 } else {
1423 if (bufp == 0) {
1424 if (bufp < bufe) {
1425 ALOGW("Line too long in %s%s, skipping: %s\n",
1426 UPDATE_COMMANDS_DIR_PREFIX, name, buf);
1427 }
1428 } else if (bufp < bufe) {
1429 memcpy(buf, buf+bufp, bufe-bufp);
1430 bufe -= bufp;
1431 bufp = 0;
1432 }
1433 readlen = read(subfd, buf+bufe, PKG_PATH_MAX-bufe);
1434 if (readlen < 0) {
1435 ALOGW("Failure reading update commands in %s%s: %s\n",
1436 UPDATE_COMMANDS_DIR_PREFIX, name, strerror(errno));
1437 break;
1438 } else if (readlen == 0) {
1439 break;
1440 }
1441 bufe += readlen;
1442 buf[bufe] = 0;
1443 ALOGV("Read buf: %s\n", buf);
1444 }
1445 }
1446 close(subfd);
1447 }
1448 }
1449 closedir(d);
1450done:
1451 return 0;
1452}
1453
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001454int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001455{
Mike Lockwood94afecf2012-10-24 10:45:23 -07001456 struct stat s, libStat;
1457 int rc = 0;
1458
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001459 std::string _pkgdir(create_data_user_package_path(uuid, userId, pkgname));
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001460 std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
1461
1462 const char* pkgdir = _pkgdir.c_str();
1463 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001464
1465 if (stat(pkgdir, &s) < 0) return -1;
1466
1467 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1468 ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1469 return -1;
1470 }
1471
1472 if (chmod(pkgdir, 0700) < 0) {
1473 ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1474 rc = -1;
1475 goto out;
1476 }
1477
1478 if (lstat(libsymlink, &libStat) < 0) {
1479 if (errno != ENOENT) {
1480 ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1481 rc = -1;
1482 goto out;
1483 }
1484 } else {
1485 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001486 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001487 rc = -1;
1488 goto out;
1489 }
1490 } else if (S_ISLNK(libStat.st_mode)) {
1491 if (unlink(libsymlink) < 0) {
1492 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1493 rc = -1;
1494 goto out;
1495 }
1496 }
1497 }
1498
1499 if (symlink(asecLibDir, libsymlink) < 0) {
1500 ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1501 strerror(errno));
1502 rc = -errno;
1503 goto out;
1504 }
1505
1506out:
1507 if (chmod(pkgdir, s.st_mode) < 0) {
1508 ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1509 rc = -errno;
1510 }
1511
1512 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1513 ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1514 return -errno;
1515 }
1516
1517 return rc;
1518}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001519
1520static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1521{
1522 static const char *IDMAP_BIN = "/system/bin/idmap";
1523 static const size_t MAX_INT_LEN = 32;
1524 char idmap_str[MAX_INT_LEN];
1525
1526 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1527
1528 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1529 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1530}
1531
1532// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1533// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1534static int flatten_path(const char *prefix, const char *suffix,
1535 const char *overlay_path, char *idmap_path, size_t N)
1536{
1537 if (overlay_path == NULL || idmap_path == NULL) {
1538 return -1;
1539 }
1540 const size_t len_overlay_path = strlen(overlay_path);
1541 // will access overlay_path + 1 further below; requires absolute path
1542 if (len_overlay_path < 2 || *overlay_path != '/') {
1543 return -1;
1544 }
1545 const size_t len_idmap_root = strlen(prefix);
1546 const size_t len_suffix = strlen(suffix);
1547 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1548 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1549 // additions below would cause overflow
1550 return -1;
1551 }
1552 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1553 return -1;
1554 }
1555 memset(idmap_path, 0, N);
1556 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1557 char *ch = idmap_path + len_idmap_root;
1558 while (*ch != '\0') {
1559 if (*ch == '/') {
1560 *ch = '@';
1561 }
1562 ++ch;
1563 }
1564 return 0;
1565}
1566
1567int idmap(const char *target_apk, const char *overlay_apk, uid_t uid)
1568{
1569 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1570
1571 int idmap_fd = -1;
1572 char idmap_path[PATH_MAX];
1573
1574 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1575 idmap_path, sizeof(idmap_path)) == -1) {
1576 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1577 goto fail;
1578 }
1579
1580 unlink(idmap_path);
1581 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1582 if (idmap_fd < 0) {
1583 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1584 goto fail;
1585 }
1586 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1587 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1588 goto fail;
1589 }
1590 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1591 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1592 goto fail;
1593 }
1594
1595 pid_t pid;
1596 pid = fork();
1597 if (pid == 0) {
1598 /* child -- drop privileges before continuing */
1599 if (setgid(uid) != 0) {
1600 ALOGE("setgid(%d) failed during idmap\n", uid);
1601 exit(1);
1602 }
1603 if (setuid(uid) != 0) {
1604 ALOGE("setuid(%d) failed during idmap\n", uid);
1605 exit(1);
1606 }
1607 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1608 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1609 exit(1);
1610 }
1611
1612 run_idmap(target_apk, overlay_apk, idmap_fd);
1613 exit(1); /* only if exec call to idmap failed */
1614 } else {
1615 int status = wait_child(pid);
1616 if (status != 0) {
1617 ALOGE("idmap failed, status=0x%04x\n", status);
1618 goto fail;
1619 }
1620 }
1621
1622 close(idmap_fd);
1623 return 0;
1624fail:
1625 if (idmap_fd >= 0) {
1626 close(idmap_fd);
1627 unlink(idmap_path);
1628 }
1629 return -1;
1630}
Robert Craige9887e42014-02-20 10:25:56 -05001631
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001632int restorecon_app_data(const char* uuid, const char* pkgName, userid_t userid, int flags,
1633 appid_t appid, const char* seinfo) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001634 int res = 0;
Robert Craige9887e42014-02-20 10:25:56 -05001635
Robert Craigda30dc72014-03-27 10:21:12 -04001636 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001637 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Robert Craigda30dc72014-03-27 10:21:12 -04001638
1639 if (!pkgName || !seinfo) {
1640 ALOGE("Package name or seinfo tag is null when trying to restorecon.");
Robert Craige9887e42014-02-20 10:25:56 -05001641 return -1;
1642 }
1643
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001644 uid_t uid = multiuser_get_uid(userid, appid);
1645 if (flags & FLAG_CE_STORAGE) {
1646 auto path = create_data_user_package_path(uuid, userid, pkgName);
1647 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1648 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001649 res = -1;
1650 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001651 }
1652 if (flags & FLAG_DE_STORAGE) {
1653 auto path = create_data_user_de_package_path(uuid, userid, pkgName);
1654 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1655 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyea0e4b12015-11-19 15:35:27 -07001656 // TODO: include result once 25796509 is fixed
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001657 }
Robert Craige9887e42014-02-20 10:25:56 -05001658 }
1659
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001660 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001661}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001662
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001663int create_oat_dir(const char* oat_dir, const char* instruction_set)
1664{
1665 char oat_instr_dir[PKG_PATH_MAX];
1666
1667 if (validate_apk_path(oat_dir)) {
1668 ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
1669 return -1;
1670 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001671 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001672 return -1;
1673 }
1674 if (selinux_android_restorecon(oat_dir, 0)) {
1675 ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
1676 return -1;
1677 }
1678 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001679 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001680 return -1;
1681 }
1682 return 0;
1683}
1684
1685int rm_package_dir(const char* apk_path)
1686{
1687 if (validate_apk_path(apk_path)) {
1688 ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
1689 return -1;
1690 }
1691 return delete_dir_contents(apk_path, 1 /* also_delete_dir */ , NULL /* exclusion_predicate */);
1692}
1693
Narayan Kamathd845c962015-06-04 13:20:27 +01001694int link_file(const char* relative_path, const char* from_base, const char* to_base) {
1695 char from_path[PKG_PATH_MAX];
1696 char to_path[PKG_PATH_MAX];
1697 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1698 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1699
1700 if (validate_apk_path_subdirs(from_path)) {
1701 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
1702 return -1;
1703 }
1704
1705 if (validate_apk_path_subdirs(to_path)) {
1706 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
1707 return -1;
1708 }
1709
1710 const int ret = link(from_path, to_path);
1711 if (ret < 0) {
1712 ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
1713 return -1;
1714 }
1715
1716 return 0;
1717}
1718
Andreas Gampe02d0de52015-11-11 20:43:16 -08001719} // namespace installd
1720} // namespace android