blob: 7674c45442015fdbaf41c76a04512273490c4a13 [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
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070054int create_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags,
55 appid_t appid, const char* seinfo) {
56 uid_t uid = multiuser_get_uid(userid, appid);
57 if (flags & FLAG_CE_STORAGE) {
58 auto path = create_data_user_package_path(uuid, userid, pkgname);
59 if (fs_prepare_dir_strict(path.c_str(), 0751, uid, uid) != 0) {
60 PLOG(ERROR) << "Failed to prepare " << path;
61 return -1;
62 }
63 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
64 PLOG(ERROR) << "Failed to setfilecon " << path;
65 return -1;
66 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070067 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070068 if (flags & FLAG_DE_STORAGE) {
69 auto path = create_data_user_de_package_path(uuid, userid, pkgname);
70 if (fs_prepare_dir_strict(path.c_str(), 0751, uid, uid) == -1) {
71 PLOG(ERROR) << "Failed to prepare " << path;
72 return -1;
73 }
74 if (selinux_android_setfilecon(path.c_str(), pkgname, seinfo, uid) < 0) {
75 PLOG(ERROR) << "Failed to setfilecon " << path;
76 return -1;
77 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070078 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070079 return 0;
80}
81
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070082int clear_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
83 std::string suffix = "";
84 if (flags & FLAG_CLEAR_CACHE_ONLY) {
85 suffix = CACHE_DIR_POSTFIX;
86 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
87 suffix = CODE_CACHE_DIR_POSTFIX;
88 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070089
Jeff Sharkeyebf728f2015-11-18 14:15:17 -070090 int res = 0;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -070091 if (flags & FLAG_CE_STORAGE) {
92 auto path = create_data_user_package_path(uuid, userid, pkgname) + suffix;
93 if (access(path.c_str(), F_OK) == 0) {
94 res |= delete_dir_contents(path);
95 }
96 }
97 if (flags & FLAG_DE_STORAGE) {
98 auto path = create_data_user_de_package_path(uuid, userid, pkgname) + suffix;
99 if (access(path.c_str(), F_OK) == 0) {
100 res |= delete_dir_contents(path);
101 }
102 }
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700103 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700104}
105
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700106int destroy_app_data(const char *uuid, const char *pkgname, userid_t userid, int flags) {
107 int res = 0;
108 if (flags & FLAG_CE_STORAGE) {
109 res |= delete_dir_contents_and_dir(
110 create_data_user_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700111 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700112 if (flags & FLAG_DE_STORAGE) {
113 res |= delete_dir_contents_and_dir(
114 create_data_user_de_package_path(uuid, userid, pkgname));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700115 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700116 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700117}
118
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700119int move_complete_app(const char *from_uuid, const char *to_uuid, const char *package_name,
120 const char *data_app_name, appid_t appid, const char* seinfo) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700121 std::vector<userid_t> users = get_known_users(from_uuid);
122
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700123 // Copy app
124 {
125 std::string from(create_data_app_package_path(from_uuid, data_app_name));
126 std::string to(create_data_app_package_path(to_uuid, data_app_name));
127 std::string to_parent(create_data_app_path(to_uuid));
128
129 char *argv[] = {
130 (char*) kCpPath,
131 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
132 (char*) "-p", /* preserve timestamps, ownership, and permissions */
133 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
134 (char*) "-P", /* Do not follow symlinks [default] */
135 (char*) "-d", /* don't dereference symlinks */
136 (char*) from.c_str(),
137 (char*) to_parent.c_str()
138 };
139
140 LOG(DEBUG) << "Copying " << from << " to " << to;
141 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
142
143 if (rc != 0) {
144 LOG(ERROR) << "Failed copying " << from << " to " << to
145 << ": status " << rc;
146 goto fail;
147 }
148
149 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
150 LOG(ERROR) << "Failed to restorecon " << to;
151 goto fail;
152 }
153 }
154
155 // Copy private data for all known users
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700156 // TODO: handle user_de paths
Jeff Sharkeye3637242015-04-08 20:56:42 -0700157 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700158 std::string from(create_data_user_package_path(from_uuid, user, package_name));
159 std::string to(create_data_user_package_path(to_uuid, user, package_name));
160 std::string to_parent(create_data_user_path(to_uuid, user));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700161
162 // Data source may not exist for all users; that's okay
163 if (access(from.c_str(), F_OK) != 0) {
164 LOG(INFO) << "Missing source " << from;
165 continue;
166 }
167
168 std::string user_path(create_data_user_path(to_uuid, user));
169 if (fs_prepare_dir(user_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM) != 0) {
170 LOG(ERROR) << "Failed to prepare user target " << user_path;
171 goto fail;
172 }
173
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700174 if (create_app_data(to_uuid, package_name, user, FLAG_CE_STORAGE | FLAG_DE_STORAGE,
175 appid, seinfo) != 0) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700176 LOG(ERROR) << "Failed to create package target " << to;
177 goto fail;
178 }
179
180 char *argv[] = {
181 (char*) kCpPath,
182 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
183 (char*) "-p", /* preserve timestamps, ownership, and permissions */
184 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
185 (char*) "-P", /* Do not follow symlinks [default] */
186 (char*) "-d", /* don't dereference symlinks */
187 (char*) from.c_str(),
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700188 (char*) to_parent.c_str()
Jeff Sharkeye3637242015-04-08 20:56:42 -0700189 };
190
191 LOG(DEBUG) << "Copying " << from << " to " << to;
192 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
193
194 if (rc != 0) {
195 LOG(ERROR) << "Failed copying " << from << " to " << to
196 << ": status " << rc;
197 goto fail;
198 }
199
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700200 if (restorecon_app_data(to_uuid, package_name, user, FLAG_CE_STORAGE | FLAG_DE_STORAGE,
201 appid, seinfo) != 0) {
202 LOG(ERROR) << "Failed to restorecon";
203 goto fail;
204 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700205 }
206
Jeff Sharkey31f08982015-07-07 13:31:37 -0700207 // We let the framework scan the new location and persist that before
208 // deleting the data in the old location; this ordering ensures that
209 // we can recover from things like battery pulls.
Jeff Sharkeye3637242015-04-08 20:56:42 -0700210 return 0;
211
212fail:
213 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700214 {
215 std::string to(create_data_app_package_path(to_uuid, data_app_name));
216 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
217 LOG(WARNING) << "Failed to rollback " << to;
218 }
219 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700220 for (auto user : users) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700221 std::string to(create_data_user_package_path(to_uuid, user, package_name));
Jeff Sharkeye3637242015-04-08 20:56:42 -0700222 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
223 LOG(WARNING) << "Failed to rollback " << to;
224 }
225 }
226 return -1;
227}
228
Robin Lee7c8bec02014-06-10 18:46:26 +0100229int make_user_config(userid_t userid)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700230{
Robin Lee095c7632014-04-25 15:05:19 +0100231 if (ensure_config_user_dirs(userid) == -1) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700232 return -1;
233 }
234
235 return 0;
236}
237
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700238int delete_user(const char *uuid, userid_t userid) {
239 int res = 0;
Robin Lee095c7632014-04-25 15:05:19 +0100240
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700241 std::string data_path(create_data_user_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700242 std::string data_de_path(create_data_user_de_path(uuid, userid));
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700243 std::string media_path(create_data_media_path(uuid, userid));
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700244
245 res |= delete_dir_contents_and_dir(data_path);
246 res |= delete_dir_contents_and_dir(data_de_path);
247 res |= delete_dir_contents_and_dir(media_path);
Robin Lee095c7632014-04-25 15:05:19 +0100248
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700249 // Config paths only exist on internal storage
250 if (uuid == nullptr) {
251 char config_path[PATH_MAX];
252 if ((create_user_config_path(config_path, userid) != 0)
253 || (delete_dir_contents(config_path, 1, NULL) != 0)) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700254 res = -1;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700255 }
Robin Lee095c7632014-04-25 15:05:19 +0100256 }
257
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700258 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100259}
260
Mike Lockwood94afecf2012-10-24 10:45:23 -0700261/* Try to ensure free_size bytes of storage are available.
262 * Returns 0 on success.
263 * This is rather simple-minded because doing a full LRU would
264 * be potentially memory-intensive, and without atime it would
265 * also require that apps constantly modify file metadata even
266 * when just reading from the cache, which is pretty awful.
267 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700268int free_cache(const char *uuid, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700269{
270 cache_t* cache;
271 int64_t avail;
272 DIR *d;
273 struct dirent *de;
274 char tmpdir[PATH_MAX];
275 char *dirpos;
276
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700277 std::string data_path(create_data_path(uuid));
278
279 avail = data_disk_free(data_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700280 if (avail < 0) return -1;
281
282 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
283 if (avail >= free_size) return 0;
284
285 cache = start_cache_collection();
286
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700287 // Special case for owner on internal storage
288 if (uuid == nullptr) {
289 std::string _tmpdir(create_data_user_path(nullptr, 0));
290 add_cache_files(cache, _tmpdir.c_str(), "cache");
Mike Lockwood94afecf2012-10-24 10:45:23 -0700291 }
292
293 // Search for other users and add any cache files from them.
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700294 std::string _tmpdir(create_data_path(uuid) + "/" + SECONDARY_USER_PREFIX);
295 strcpy(tmpdir, _tmpdir.c_str());
296
Mike Lockwood94afecf2012-10-24 10:45:23 -0700297 dirpos = tmpdir + strlen(tmpdir);
298 d = opendir(tmpdir);
299 if (d != NULL) {
300 while ((de = readdir(d))) {
301 if (de->d_type == DT_DIR) {
302 const char *name = de->d_name;
303 /* always skip "." and ".." */
304 if (name[0] == '.') {
305 if (name[1] == 0) continue;
306 if ((name[1] == '.') && (name[2] == 0)) continue;
307 }
308 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
309 strcpy(dirpos, name);
310 //ALOGI("adding cache files from %s\n", tmpdir);
311 add_cache_files(cache, tmpdir, "cache");
312 } else {
313 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
314 }
315 }
316 }
317 closedir(d);
318 }
319
320 // Collect cache files on external storage for all users (if it is mounted as part
321 // of the internal storage).
322 strcpy(tmpdir, android_media_dir.path);
323 dirpos = tmpdir + strlen(tmpdir);
324 d = opendir(tmpdir);
325 if (d != NULL) {
326 while ((de = readdir(d))) {
327 if (de->d_type == DT_DIR) {
328 const char *name = de->d_name;
329 /* skip any dir that doesn't start with a number, so not a user */
330 if (name[0] < '0' || name[0] > '9') {
331 continue;
332 }
333 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
334 strcpy(dirpos, name);
335 if (lookup_media_dir(tmpdir, "Android") == 0
336 && lookup_media_dir(tmpdir, "data") == 0) {
337 //ALOGI("adding cache files from %s\n", tmpdir);
338 add_cache_files(cache, tmpdir, "cache");
339 }
340 } else {
341 ALOGW("Path exceeds limit: %s%s", tmpdir, name);
342 }
343 }
344 }
345 closedir(d);
346 }
347
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700348 clear_cache_files(data_path, cache, free_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700349 finish_cache_collection(cache);
350
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700351 return data_disk_free(data_path) >= free_size ? 0 : -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700352}
353
Narayan Kamath1b400322014-04-11 13:17:00 +0100354int rm_dex(const char *path, const char *instruction_set)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700355{
356 char dex_path[PKG_PATH_MAX];
357
Jeff Sharkey770180a2014-09-08 17:14:26 -0700358 if (validate_apk_path(path) && validate_system_app_path(path)) {
359 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
360 return -1;
361 }
362
Andreas Gampe02d0de52015-11-11 20:43:16 -0800363 if (!create_cache_path(dex_path, path, instruction_set)) return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700364
365 ALOGV("unlink %s\n", dex_path);
366 if (unlink(dex_path) < 0) {
Jeff Sharkey770180a2014-09-08 17:14:26 -0700367 if (errno != ENOENT) {
368 ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
369 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700370 return -1;
371 } else {
372 return 0;
373 }
374}
375
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700376int get_app_size(const char *uuid, const char *pkgname, int userid, int flags,
377 const char *apkpath, const char *libdirpath, const char *fwdlock_apkpath,
378 const char *asecpath, const char *instruction_set, int64_t *_codesize, int64_t *_datasize,
379 int64_t *_cachesize, int64_t* _asecsize) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700380 DIR *d;
381 int dfd;
382 struct dirent *de;
383 struct stat s;
384 char path[PKG_PATH_MAX];
385
386 int64_t codesize = 0;
387 int64_t datasize = 0;
388 int64_t cachesize = 0;
389 int64_t asecsize = 0;
390
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700391 /* count the source apk as code -- but only if it's not
392 * on the /system partition and its not on the sdcard. */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700393 if (validate_system_app_path(apkpath) &&
394 strncmp(apkpath, android_asec_dir.path, android_asec_dir.len) != 0) {
395 if (stat(apkpath, &s) == 0) {
396 codesize += stat_size(&s);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700397 if (S_ISDIR(s.st_mode)) {
398 d = opendir(apkpath);
399 if (d != NULL) {
400 dfd = dirfd(d);
401 codesize += calculate_dir_size(dfd);
402 closedir(d);
403 }
404 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700405 }
406 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700407
408 /* count the forward locked apk as code if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700409 if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
410 if (stat(fwdlock_apkpath, &s) == 0) {
411 codesize += stat_size(&s);
412 }
413 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700414
415 /* count the cached dexfile as code */
Andreas Gampe02d0de52015-11-11 20:43:16 -0800416 if (create_cache_path(path, apkpath, instruction_set)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700417 if (stat(path, &s) == 0) {
418 codesize += stat_size(&s);
419 }
420 }
421
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700422 /* add in size of any libraries */
Dianne Hackborn8b417802013-05-01 18:55:10 -0700423 if (libdirpath != NULL && libdirpath[0] != '!') {
424 d = opendir(libdirpath);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700425 if (d != NULL) {
426 dfd = dirfd(d);
427 codesize += calculate_dir_size(dfd);
428 closedir(d);
429 }
430 }
431
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700432 /* compute asec size if it is given */
Mike Lockwood94afecf2012-10-24 10:45:23 -0700433 if (asecpath != NULL && asecpath[0] != '!') {
434 if (stat(asecpath, &s) == 0) {
435 asecsize += stat_size(&s);
436 }
437 }
438
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700439 std::vector<userid_t> users;
440 if (userid == -1) {
441 users = get_known_users(uuid);
442 } else {
443 users.push_back(userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700444 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700445
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700446 for (auto user : users) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700447 // TODO: handle user_de directories
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700448 if (!(flags & FLAG_CE_STORAGE)) continue;
449
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700450 std::string _pkgdir(create_data_user_package_path(uuid, user, pkgname));
451 const char* pkgdir = _pkgdir.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700452
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700453 d = opendir(pkgdir);
454 if (d == NULL) {
455 PLOG(WARNING) << "Failed to open " << pkgdir;
456 continue;
457 }
458 dfd = dirfd(d);
459
460 /* most stuff in the pkgdir is data, except for the "cache"
461 * directory and below, which is cache, and the "lib" directory
462 * and below, which is code...
463 */
464 while ((de = readdir(d))) {
465 const char *name = de->d_name;
466
467 if (de->d_type == DT_DIR) {
468 int subfd;
469 int64_t statsize = 0;
470 int64_t dirsize = 0;
471 /* always skip "." and ".." */
472 if (name[0] == '.') {
473 if (name[1] == 0) continue;
474 if ((name[1] == '.') && (name[2] == 0)) continue;
475 }
476 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
477 statsize = stat_size(&s);
478 }
479 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
480 if (subfd >= 0) {
481 dirsize = calculate_dir_size(subfd);
482 }
483 if(!strcmp(name,"lib")) {
484 codesize += dirsize + statsize;
485 } else if(!strcmp(name,"cache")) {
486 cachesize += dirsize + statsize;
487 } else {
488 datasize += dirsize + statsize;
489 }
490 } else if (de->d_type == DT_LNK && !strcmp(name,"lib")) {
491 // This is the symbolic link to the application's library
492 // code. We'll count this as code instead of data, since
493 // it is not something that the app creates.
494 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
495 codesize += stat_size(&s);
496 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700497 } else {
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700498 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
499 datasize += stat_size(&s);
500 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700501 }
502 }
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700503 closedir(d);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700504 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 *_codesize = codesize;
506 *_datasize = datasize;
507 *_cachesize = cachesize;
508 *_asecsize = asecsize;
509 return 0;
510}
511
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700512static int split_count(const char *str)
513{
514 char *ctx;
515 int count = 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800516 char buf[kPropertyValueMax];
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700517
518 strncpy(buf, str, sizeof(buf));
519 char *pBuf = buf;
520
521 while(strtok_r(pBuf, " ", &ctx) != NULL) {
522 count++;
523 pBuf = NULL;
524 }
525
526 return count;
527}
528
neo.chae14e084d2015-01-07 18:46:13 +0900529static int split(char *buf, const char **argv)
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700530{
531 char *ctx;
532 int count = 0;
533 char *tok;
534 char *pBuf = buf;
535
536 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
537 argv[count++] = tok;
538 pBuf = NULL;
539 }
540
541 return count;
542}
543
Alex Light7365a102014-07-21 12:23:48 -0700544static void run_patchoat(int input_fd, int oat_fd, const char* input_file_name,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800545 const char* output_file_name, const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
Alex Light7365a102014-07-21 12:23:48 -0700546{
547 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Calin Juravle8fc73152014-08-19 18:48:50 +0100548 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
Alex Light7365a102014-07-21 12:23:48 -0700549
550 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
551 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
552 ALOGE("Instruction set %s longer than max length of %d",
553 instruction_set, MAX_INSTRUCTION_SET_LEN);
554 return;
555 }
556
557 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
558 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
559 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
560 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
561 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
562 // The caller has already gotten all the locks we need.
563 const char* no_lock_arg = "--no-lock-output";
564 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
565 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", oat_fd);
566 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_fd);
Alex Lighta7915d42014-08-11 10:07:02 -0700567 ALOGV("Running %s isa=%s in-fd=%d (%s) out-fd=%d (%s)\n",
Alex Light7365a102014-07-21 12:23:48 -0700568 PATCHOAT_BIN, instruction_set, input_fd, input_file_name, oat_fd, output_file_name);
569
570 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
571 char* argv[7];
572 argv[0] = (char*) PATCHOAT_BIN;
573 argv[1] = (char*) patched_image_location_arg;
574 argv[2] = (char*) no_lock_arg;
575 argv[3] = instruction_set_arg;
576 argv[4] = output_oat_fd_arg;
577 argv[5] = input_oat_fd_arg;
578 argv[6] = NULL;
579
580 execv(PATCHOAT_BIN, (char* const *)argv);
581 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
582}
583
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700584static bool check_boolean_property(const char* property_name, bool default_value = false) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800585 char tmp_property_value[kPropertyValueMax];
586 bool have_property = get_property(property_name, tmp_property_value, nullptr) > 0;
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700587 if (!have_property) {
588 return default_value;
589 }
590 return strcmp(tmp_property_value, "true") == 0;
591}
592
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700593static void run_dex2oat(int zip_fd, int oat_fd, const char* input_file_name,
Calin Juravledf9dadd2015-11-04 14:47:37 +0000594 const char* output_file_name, int swap_fd, const char *instruction_set,
Calin Juravle60a794d2015-12-24 12:36:41 +0200595 bool vm_safe_mode, bool debuggable, bool post_bootcomplete, bool use_jit,
596 const std::vector<int>& profile_files_fd, const std::vector<int>& reference_profile_files_fd)
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700597{
Calin Juravle8fc73152014-08-19 18:48:50 +0100598 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
599
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
Calin Juravle60a794d2015-12-24 12:36:41 +0200606 if (profile_files_fd.size() != reference_profile_files_fd.size()) {
607 ALOGE("Invalid configuration of profile files: pf_size (%zu) != rpf_size (%zu)",
608 profile_files_fd.size(), reference_profile_files_fd.size());
609 return;
610 }
611
Andreas Gampe02d0de52015-11-11 20:43:16 -0800612 char dex2oat_Xms_flag[kPropertyValueMax];
613 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700614
Andreas Gampe02d0de52015-11-11 20:43:16 -0800615 char dex2oat_Xmx_flag[kPropertyValueMax];
616 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700617
Andreas Gampe02d0de52015-11-11 20:43:16 -0800618 char dex2oat_compiler_filter_flag[kPropertyValueMax];
619 bool have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700620 dex2oat_compiler_filter_flag, NULL) > 0;
621
Andreas Gampe02d0de52015-11-11 20:43:16 -0800622 char dex2oat_threads_buf[kPropertyValueMax];
623 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
Andreas Gampe919461c2015-09-28 08:55:01 -0700624 ? "dalvik.vm.dex2oat-threads"
625 : "dalvik.vm.boot-dex2oat-threads",
626 dex2oat_threads_buf,
627 NULL) > 0;
Andreas Gampe02d0de52015-11-11 20:43:16 -0800628 char dex2oat_threads_arg[kPropertyValueMax + 2];
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700629 if (have_dex2oat_threads_flag) {
630 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
631 }
632
Andreas Gampe02d0de52015-11-11 20:43:16 -0800633 char dex2oat_isa_features_key[kPropertyKeyMax];
Calin Juravle8fc73152014-08-19 18:48:50 +0100634 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800635 char dex2oat_isa_features[kPropertyValueMax];
636 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
Calin Juravle8fc73152014-08-19 18:48:50 +0100637 dex2oat_isa_features, NULL) > 0;
638
Andreas Gampe02d0de52015-11-11 20:43:16 -0800639 char dex2oat_isa_variant_key[kPropertyKeyMax];
Ian Rogers16a95b22014-11-08 16:58:13 -0800640 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
Andreas Gampe02d0de52015-11-11 20:43:16 -0800641 char dex2oat_isa_variant[kPropertyValueMax];
642 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
Ian Rogers16a95b22014-11-08 16:58:13 -0800643 dex2oat_isa_variant, NULL) > 0;
644
neo.chae14e084d2015-01-07 18:46:13 +0900645 const char *dex2oat_norelocation = "-Xnorelocate";
646 bool have_dex2oat_relocation_skip_flag = false;
647
Andreas Gampe02d0de52015-11-11 20:43:16 -0800648 char dex2oat_flags[kPropertyValueMax];
649 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700650 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
Brian Carlstrom0ae8e392014-02-10 16:42:52 -0800651 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
652
Brian Carlstrom538998f2014-07-30 14:37:11 -0700653 // If we booting without the real /data, don't spend time compiling.
Andreas Gampe02d0de52015-11-11 20:43:16 -0800654 char vold_decrypt[kPropertyValueMax];
655 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700656 bool skip_compilation = (have_vold_decrypt &&
657 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
658 (strcmp(vold_decrypt, "1") == 0)));
659
David Srbecky528c8dd2015-05-28 16:55:50 +0100660 bool generate_debug_info = check_boolean_property("debug.generate-debug-info");
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700661
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700662 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700663
Brian Carlstrom53e07762014-06-27 14:15:19 -0700664 static const char* RUNTIME_ARG = "--runtime-arg";
Brian Carlstrom53e07762014-06-27 14:15:19 -0700665
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700666 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
Narayan Kamath1b400322014-04-11 13:17:00 +0100667
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700668 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
669 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
670 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
Brian Carlstrom7195fcc2014-06-16 13:28:03 -0700671 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
Narayan Kamath1b400322014-04-11 13:17:00 +0100672 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
Andreas Gampe02d0de52015-11-11 20:43:16 -0800673 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
674 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
675 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
676 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
677 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Andreas Gampee1c01352014-12-10 16:41:11 -0800678 bool have_dex2oat_swap_fd = false;
679 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700680
681 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
682 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
683 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
684 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
Narayan Kamath1b400322014-04-11 13:17:00 +0100685 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
Ian Rogers16a95b22014-11-08 16:58:13 -0800686 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
Calin Juravle8fc73152014-08-19 18:48:50 +0100687 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
Andreas Gampee1c01352014-12-10 16:41:11 -0800688 if (swap_fd >= 0) {
689 have_dex2oat_swap_fd = true;
690 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
691 }
Calin Juravle57c69c32014-06-06 14:42:16 +0100692
Todd Kennedy12434f82015-09-25 14:45:37 -0700693 // use the JIT if either it's specified as a dexopt flag or if the property is set
694 use_jit = use_jit || check_boolean_property("debug.usejit");
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700695 if (have_dex2oat_Xms_flag) {
696 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
697 }
698 if (have_dex2oat_Xmx_flag) {
699 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
700 }
Brian Carlstrom538998f2014-07-30 14:37:11 -0700701 if (skip_compilation) {
Brian Carlstrome18987e2014-08-15 09:55:50 -0700702 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
Brian Carlstrom538998f2014-07-30 14:37:11 -0700703 have_dex2oat_compiler_filter_flag = true;
neo.chae14e084d2015-01-07 18:46:13 +0900704 have_dex2oat_relocation_skip_flag = true;
Calin Juravleb1efac12014-08-21 19:05:20 +0100705 } else if (vm_safe_mode) {
706 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
Calin Juravle97477d22014-08-27 16:10:03 +0100707 have_dex2oat_compiler_filter_flag = true;
Mathieu Chartierd4a7b452015-03-20 15:39:47 -0700708 } else if (use_jit) {
709 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-at-runtime");
710 have_dex2oat_compiler_filter_flag = true;
Brian Carlstrom538998f2014-07-30 14:37:11 -0700711 } else if (have_dex2oat_compiler_filter_flag) {
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700712 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", dex2oat_compiler_filter_flag);
713 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700714
Andreas Gampe598c25e2015-03-03 09:15:06 -0800715 // Check whether all apps should be compiled debuggable.
716 if (!debuggable) {
Andreas Gampe02d0de52015-11-11 20:43:16 -0800717 char prop_buf[kPropertyValueMax];
Andreas Gampe598c25e2015-03-03 09:15:06 -0800718 debuggable =
Andreas Gampe02d0de52015-11-11 20:43:16 -0800719 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
Andreas Gampe598c25e2015-03-03 09:15:06 -0800720 (prop_buf[0] == '1');
721 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200722 std::vector<std::string> profile_file_args(profile_files_fd.size());
723 std::vector<std::string> reference_profile_file_args(profile_files_fd.size());
724 // "reference-profile-file-fd" is longer than "profile-file-fd" so we can
725 // use it to set the max length.
726 char profile_buf[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
727 for (size_t k = 0; k < profile_files_fd.size(); k++) {
728 sprintf(profile_buf, "--profile-file-fd=%d", profile_files_fd[k]);
729 profile_file_args[k].assign(profile_buf);
730 sprintf(profile_buf, "--reference-profile-file-fd=%d", reference_profile_files_fd[k]);
731 reference_profile_file_args[k].assign(profile_buf);
732 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800733
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700734 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
Calin Juravle4fdff462014-06-06 16:58:43 +0100735
neo.chae14e084d2015-01-07 18:46:13 +0900736 const char* argv[7 // program name, mandatory arguments and the final NULL
737 + (have_dex2oat_isa_variant ? 1 : 0)
738 + (have_dex2oat_isa_features ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900739 + (have_dex2oat_Xms_flag ? 2 : 0)
740 + (have_dex2oat_Xmx_flag ? 2 : 0)
741 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700742 + (have_dex2oat_threads_flag ? 1 : 0)
neo.chae14e084d2015-01-07 18:46:13 +0900743 + (have_dex2oat_swap_fd ? 1 : 0)
744 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
David Srbecky528c8dd2015-05-28 16:55:50 +0100745 + (generate_debug_info ? 1 : 0)
Andreas Gampe598c25e2015-03-03 09:15:06 -0800746 + (debuggable ? 1 : 0)
Calin Juravle60a794d2015-12-24 12:36:41 +0200747 + dex2oat_flags_count
748 + profile_files_fd.size()
749 + reference_profile_files_fd.size()];
Calin Juravle4fdff462014-06-06 16:58:43 +0100750 int i = 0;
neo.chae14e084d2015-01-07 18:46:13 +0900751 argv[i++] = DEX2OAT_BIN;
Calin Juravle4fdff462014-06-06 16:58:43 +0100752 argv[i++] = zip_fd_arg;
753 argv[i++] = zip_location_arg;
754 argv[i++] = oat_fd_arg;
755 argv[i++] = oat_location_arg;
756 argv[i++] = instruction_set_arg;
Ian Rogers16a95b22014-11-08 16:58:13 -0800757 if (have_dex2oat_isa_variant) {
758 argv[i++] = instruction_set_variant_arg;
759 }
Calin Juravle8fc73152014-08-19 18:48:50 +0100760 if (have_dex2oat_isa_features) {
761 argv[i++] = instruction_set_features_arg;
762 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700763 if (have_dex2oat_Xms_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900764 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700765 argv[i++] = dex2oat_Xms_arg;
766 }
767 if (have_dex2oat_Xmx_flag) {
neo.chae14e084d2015-01-07 18:46:13 +0900768 argv[i++] = RUNTIME_ARG;
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700769 argv[i++] = dex2oat_Xmx_arg;
770 }
Brian Carlstromcf51ba12014-07-28 19:13:28 -0700771 if (have_dex2oat_compiler_filter_flag) {
772 argv[i++] = dex2oat_compiler_filter_arg;
773 }
Andreas Gampe8d7af8b2015-03-30 18:45:03 -0700774 if (have_dex2oat_threads_flag) {
775 argv[i++] = dex2oat_threads_arg;
776 }
Andreas Gampee1c01352014-12-10 16:41:11 -0800777 if (have_dex2oat_swap_fd) {
778 argv[i++] = dex2oat_swap_fd;
779 }
David Srbecky528c8dd2015-05-28 16:55:50 +0100780 if (generate_debug_info) {
781 argv[i++] = "--generate-debug-info";
Andreas Gampe3822b8b2015-04-24 14:30:04 -0700782 }
Andreas Gampe598c25e2015-03-03 09:15:06 -0800783 if (debuggable) {
784 argv[i++] = "--debuggable";
785 }
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700786 if (dex2oat_flags_count) {
787 i += split(dex2oat_flags, argv + i);
Calin Juravle4fdff462014-06-06 16:58:43 +0100788 }
neo.chae14e084d2015-01-07 18:46:13 +0900789 if (have_dex2oat_relocation_skip_flag) {
790 argv[i++] = RUNTIME_ARG;
791 argv[i++] = dex2oat_norelocation;
792 }
Calin Juravle60a794d2015-12-24 12:36:41 +0200793 for (size_t k = 0; k < profile_file_args.size(); k++) {
794 argv[i++] = profile_file_args[k].c_str();
795 argv[i++] = reference_profile_file_args[k].c_str();
796 }
Brian Carlstrome46a75a2014-06-27 16:03:06 -0700797 // Do not add after dex2oat_flags, they should override others for debugging.
Calin Juravle4fdff462014-06-06 16:58:43 +0100798 argv[i] = NULL;
799
neo.chae14e084d2015-01-07 18:46:13 +0900800 execv(DEX2OAT_BIN, (char * const *)argv);
Yevgeny Roubanb0d8d002014-09-08 17:02:10 +0700801 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700802}
803
Andreas Gampee1c01352014-12-10 16:41:11 -0800804/*
Andreas Gampec968c012015-07-16 15:55:41 -0700805 * Whether dexopt should use a swap file when compiling an APK.
806 *
807 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
808 * itself, anyways).
809 *
810 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
811 *
812 * Otherwise, return true if this is a low-mem device.
813 *
814 * Otherwise, return default value.
Andreas Gampee1c01352014-12-10 16:41:11 -0800815 */
Andreas Gampec968c012015-07-16 15:55:41 -0700816static bool kAlwaysProvideSwapFile = false;
817static bool kDefaultProvideSwapFile = true;
Andreas Gampee1c01352014-12-10 16:41:11 -0800818
819static bool ShouldUseSwapFileForDexopt() {
820 if (kAlwaysProvideSwapFile) {
821 return true;
822 }
823
Andreas Gampec968c012015-07-16 15:55:41 -0700824 // Check the "override" property. If it exists, return value == "true".
Andreas Gampe02d0de52015-11-11 20:43:16 -0800825 char dex2oat_prop_buf[kPropertyValueMax];
826 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
Andreas Gampec968c012015-07-16 15:55:41 -0700827 if (strcmp(dex2oat_prop_buf, "true") == 0) {
828 return true;
829 } else {
830 return false;
831 }
832 }
833
834 // Shortcut for default value. This is an implementation optimization for the process sketched
835 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
836 // as low-mem is never returning false. The compiler will optimize this away if it can.
837 if (kDefaultProvideSwapFile) {
838 return true;
839 }
840
841 bool is_low_mem = check_boolean_property("ro.config.low_ram");
842 if (is_low_mem) {
843 return true;
844 }
845
846 // Default value must be false here.
847 return kDefaultProvideSwapFile;
Andreas Gampee1c01352014-12-10 16:41:11 -0800848}
849
Andreas Gampe94dd3d32015-09-14 16:33:11 -0700850static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
851 if (set_to_bg) {
852 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
853 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
854 exit(70);
855 }
856 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
857 ALOGE("setpriority failed: %s\n", strerror(errno));
858 exit(71);
859 }
860 }
861}
862
Calin Juravle60a794d2015-12-24 12:36:41 +0200863constexpr const char* PROFILE_FILE_EXTENSION = ".prof";
864constexpr const char* REFERENCE_PROFILE_FILE_EXTENSION = ".prof.ref";
865
866static void close_all_fds(const std::vector<int>& fds, const char* description) {
867 for (size_t i = 0; i < fds.size(); i++) {
868 if (close(fds[i]) != 0) {
869 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
870 }
871 }
872}
873
874static int open_code_cache_for_user(userid_t user, const char* volume_uuid, const char* pkgname) {
875 std::string code_cache_path =
876 create_data_user_package_path(volume_uuid, user, pkgname) + CODE_CACHE_DIR_POSTFIX;
877
878 struct stat buffer;
879 // Check that the code cache exists. If not, return and don't log an error.
880 if (TEMP_FAILURE_RETRY(lstat(code_cache_path.c_str(), &buffer)) == -1) {
881 if (errno != ENOENT) {
882 PLOG(ERROR) << "Failed to lstat code_cache: " << code_cache_path;
883 return -1;
884 }
885 }
886
887 int code_cache_fd = open(code_cache_path.c_str(),
888 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
889 if (code_cache_fd < 0) {
890 PLOG(ERROR) << "Failed to open code_cache: " << code_cache_path;
891 }
892 return code_cache_fd;
893}
894
895// Keep profile paths in sync with ActivityThread.
896static void open_profile_files_for_user(uid_t uid, const char* pkgname, int code_cache_fd,
897 /*out*/ int* profile_fd, /*out*/ int* reference_profile_fd) {
898 *profile_fd = -1;
899 *reference_profile_fd = -1;
900 std::string profile_file(pkgname);
901 profile_file += PROFILE_FILE_EXTENSION;
902
903 // Check if the profile exists. If not, early return and don't log an error.
904 struct stat buffer;
905 if (TEMP_FAILURE_RETRY(fstatat(
906 code_cache_fd, profile_file.c_str(), &buffer, AT_SYMLINK_NOFOLLOW)) == -1) {
907 if (errno != ENOENT) {
908 PLOG(ERROR) << "Failed to fstatat profile file: " << profile_file;
909 return;
910 }
911 }
912
913 // Open in read-write to allow transfer of information from the current profile
914 // to the reference profile.
915 *profile_fd = openat(code_cache_fd, profile_file.c_str(), O_RDWR | O_NOFOLLOW);
916 if (*profile_fd < 0) {
917 PLOG(ERROR) << "Failed to open profile file: " << profile_file;
918 return;
919 }
920
921 std::string reference_profile(pkgname);
922 reference_profile += REFERENCE_PROFILE_FILE_EXTENSION;
923 // Give read-write permissions just for the user (changed with fchown after opening).
924 // We need write permission because dex2oat will update the reference profile files
925 // with the content of the corresponding current profile files.
926 *reference_profile_fd = openat(code_cache_fd, reference_profile.c_str(),
927 O_CREAT | O_RDWR | O_NOFOLLOW, S_IWUSR | S_IRUSR);
928 if (*reference_profile_fd < 0) {
929 close(*profile_fd);
930 return;
931 }
932 if (fchown(*reference_profile_fd, uid, uid) < 0) {
933 PLOG(ERROR) << "Cannot change reference profile file owner: " << reference_profile;
934 close(*profile_fd);
935 *profile_fd = -1;
936 *reference_profile_fd = -1;
937 }
938}
939
940static void open_profile_files(const char* volume_uuid, uid_t uid, const char* pkgname,
941 std::vector<int>* profile_fds, std::vector<int>* reference_profile_fds) {
942 std::vector<userid_t> users = get_known_users(volume_uuid);
943 for (auto user : users) {
944 int code_cache_fd = open_code_cache_for_user(user, volume_uuid, pkgname);
945 if (code_cache_fd < 0) {
946 continue;
947 }
948 int profile_fd = -1;
949 int reference_profile_fd = -1;
950 open_profile_files_for_user(
951 uid, pkgname, code_cache_fd, &profile_fd, &reference_profile_fd);
952 close(code_cache_fd);
953
954 // Add to the lists only if both fds are valid.
955 if ((profile_fd >= 0) && (reference_profile_fd >= 0)) {
956 profile_fds->push_back(profile_fd);
957 reference_profile_fds->push_back(reference_profile_fd);
958 }
959 }
960}
961
962int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
963 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* volume_uuid,
964 bool use_profiles)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700965{
966 struct utimbuf ut;
Fyodor Kupolov26ff93c2015-04-02 16:59:10 -0700967 struct stat input_stat;
Brian Carlstrom1705fc42013-03-21 18:20:22 -0700968 char out_path[PKG_PATH_MAX];
Andreas Gampee1c01352014-12-10 16:41:11 -0800969 char swap_file_name[PKG_PATH_MAX];
Alex Light7365a102014-07-21 12:23:48 -0700970 const char *input_file;
971 char in_odex_path[PKG_PATH_MAX];
Andreas Gampee1c01352014-12-10 16:41:11 -0800972 int res, input_fd=-1, out_fd=-1, swap_fd=-1;
Todd Kennedy76e767c2015-09-25 07:47:47 -0700973 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
974 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
975 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
976 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
Todd Kennedy12434f82015-09-25 14:45:37 -0700977 bool use_jit = (dexopt_flags & DEXOPT_USEJIT) != 0;
Calin Juravle60a794d2015-12-24 12:36:41 +0200978 std::vector<int> profile_files_fd;
979 std::vector<int> reference_profile_files_fd;
980 if (use_profiles) {
981 open_profile_files(volume_uuid, uid, pkgname,
982 &profile_files_fd, &reference_profile_files_fd);
983 if (profile_files_fd.empty()) {
984 // Skip profile guided compilation because no profiles were found.
985 return 0;
986 }
987 }
Todd Kennedy76e767c2015-09-25 07:47:47 -0700988
Todd Kennedye296e002015-11-16 14:41:36 -0800989 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
Todd Kennedy76e767c2015-09-25 07:47:47 -0700990 LOG_FATAL("dexopt flags contains unknown fields\n");
991 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700992
Andreas Gampee1c01352014-12-10 16:41:11 -0800993 // Early best-effort check whether we can fit the the path into our buffers.
994 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
995 // without a swap file, if necessary.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700996 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -0800997 ALOGE("apk_path too long '%s'\n", apk_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700998 return -1;
999 }
1000
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001001 if (oat_dir != NULL && oat_dir[0] != '!') {
1002 if (validate_apk_path(oat_dir)) {
1003 ALOGE("invalid oat_dir '%s'\n", oat_dir);
1004 return -1;
Chih-Wei Huang0e8ae162014-04-28 15:47:45 +08001005 }
Andreas Gampe02d0de52015-11-11 20:43:16 -08001006 if (!calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001007 return -1;
1008 }
1009 } else {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001010 if (!create_cache_path(out_path, apk_path, instruction_set)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001011 return -1;
1012 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001013 }
1014
Richard Uhlerc92fb622015-03-26 15:47:38 -07001015 switch (dexopt_needed) {
1016 case DEXOPT_DEX2OAT_NEEDED:
1017 input_file = apk_path;
1018 break;
1019
1020 case DEXOPT_PATCHOAT_NEEDED:
1021 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1022 return -1;
1023 }
1024 input_file = in_odex_path;
1025 break;
1026
1027 case DEXOPT_SELF_PATCHOAT_NEEDED:
1028 input_file = out_path;
1029 break;
1030
1031 default:
1032 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1033 exit(72);
Alex Light7365a102014-07-21 12:23:48 -07001034 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001035
Alex Light7365a102014-07-21 12:23:48 -07001036 memset(&input_stat, 0, sizeof(input_stat));
1037 stat(input_file, &input_stat);
1038
1039 input_fd = open(input_file, O_RDONLY, 0);
1040 if (input_fd < 0) {
1041 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001042 return -1;
1043 }
1044
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001045 unlink(out_path);
1046 out_fd = open(out_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1047 if (out_fd < 0) {
1048 ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001049 goto fail;
1050 }
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001051 if (fchmod(out_fd,
Mike Lockwood94afecf2012-10-24 10:45:23 -07001052 S_IRUSR|S_IWUSR|S_IRGRP |
1053 (is_public ? S_IROTH : 0)) < 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001054 ALOGE("installd cannot chmod '%s' during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001055 goto fail;
1056 }
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001057 if (fchown(out_fd, AID_SYSTEM, uid) < 0) {
1058 ALOGE("installd cannot chown '%s' during dexopt\n", out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001059 goto fail;
1060 }
1061
Andreas Gampee1c01352014-12-10 16:41:11 -08001062 // Create a swap file if necessary.
Richard Uhlerc92fb622015-03-26 15:47:38 -07001063 if (ShouldUseSwapFileForDexopt()) {
Andreas Gampee1c01352014-12-10 16:41:11 -08001064 // Make sure there really is enough space.
1065 size_t out_len = strlen(out_path);
1066 if (out_len + strlen(".swap") + 1 <= PKG_PATH_MAX) {
1067 strcpy(swap_file_name, out_path);
1068 strcpy(swap_file_name + strlen(out_path), ".swap");
1069 unlink(swap_file_name);
1070 swap_fd = open(swap_file_name, O_RDWR | O_CREAT | O_EXCL, 0600);
1071 if (swap_fd < 0) {
1072 // Could not create swap file. Optimistically go on and hope that we can compile
1073 // without it.
1074 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1075 } else {
1076 // Immediately unlink. We don't really want to hit flash.
1077 unlink(swap_file_name);
1078 }
1079 } else {
1080 // Swap file path is too long. Try to run without.
1081 ALOGE("installd could not create swap file for path %s during dexopt\n", out_path);
1082 }
1083 }
Dave Allisond9370732014-01-30 14:19:23 -08001084
Alex Light7365a102014-07-21 12:23:48 -07001085 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001086
1087 pid_t pid;
1088 pid = fork();
1089 if (pid == 0) {
1090 /* child -- drop privileges before continuing */
1091 if (setgid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001092 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001093 exit(64);
1094 }
1095 if (setuid(uid) != 0) {
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001096 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001097 exit(65);
1098 }
1099 // drop capabilities
1100 struct __user_cap_header_struct capheader;
1101 struct __user_cap_data_struct capdata[2];
1102 memset(&capheader, 0, sizeof(capheader));
1103 memset(&capdata, 0, sizeof(capdata));
1104 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1105 if (capset(&capheader, &capdata[0]) < 0) {
1106 ALOGE("capset failed: %s\n", strerror(errno));
1107 exit(66);
1108 }
Andreas Gampe13f14192015-09-21 13:21:30 -07001109 SetDex2OatAndPatchOatScheduling(boot_complete);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001110 if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
1111 ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001112 exit(67);
1113 }
1114
Richard Uhlerc92fb622015-03-26 15:47:38 -07001115 if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
1116 || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
Andreas Gampebd872e42014-12-15 11:41:11 -08001117 run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001118 } else if (dexopt_needed == DEXOPT_DEX2OAT_NEEDED) {
Calin Juravle60a794d2015-12-24 12:36:41 +02001119 run_dex2oat(input_fd, out_fd, input_file, out_path, swap_fd,
1120 instruction_set, vm_safe_mode, debuggable, boot_complete, use_jit,
1121 profile_files_fd, reference_profile_files_fd);
Richard Uhlerc92fb622015-03-26 15:47:38 -07001122 } else {
1123 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1124 exit(73);
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001125 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001126 exit(68); /* only get here on exec failure */
1127 } else {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001128 res = wait_child(pid);
1129 if (res == 0) {
Alex Light7365a102014-07-21 12:23:48 -07001130 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001131 } else {
Alex Light7365a102014-07-21 12:23:48 -07001132 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001133 goto fail;
1134 }
1135 }
1136
Alex Light7365a102014-07-21 12:23:48 -07001137 ut.actime = input_stat.st_atime;
1138 ut.modtime = input_stat.st_mtime;
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001139 utime(out_path, &ut);
1140
1141 close(out_fd);
Alex Light7365a102014-07-21 12:23:48 -07001142 close(input_fd);
Andreas Gampee1c01352014-12-10 16:41:11 -08001143 if (swap_fd != -1) {
1144 close(swap_fd);
1145 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001146 if (use_profiles != 0) {
1147 close_all_fds(profile_files_fd, "profile_files_fd");
1148 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1149 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001150 return 0;
1151
1152fail:
Brian Carlstrom1705fc42013-03-21 18:20:22 -07001153 if (out_fd >= 0) {
1154 close(out_fd);
1155 unlink(out_path);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001156 }
Alex Light7365a102014-07-21 12:23:48 -07001157 if (input_fd >= 0) {
1158 close(input_fd);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001159 }
Calin Juravle60a794d2015-12-24 12:36:41 +02001160 if (use_profiles != 0) {
1161 close_all_fds(profile_files_fd, "profile_files_fd");
1162 close_all_fds(reference_profile_files_fd, "reference_profile_files_fd");
1163 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001164 return -1;
1165}
1166
Narayan Kamath091ea772014-11-10 15:03:46 +00001167int mark_boot_complete(const char* instruction_set)
1168{
1169 char boot_marker_path[PKG_PATH_MAX];
Andreas Gampe02d0de52015-11-11 20:43:16 -08001170 sprintf(boot_marker_path,
1171 "%s/%s/%s/.booting",
1172 android_data_dir.path,
1173 DALVIK_CACHE,
1174 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001175
1176 ALOGV("mark_boot_complete : %s", boot_marker_path);
1177 if (unlink(boot_marker_path) != 0) {
1178 ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
1179 strerror(errno));
1180 return -1;
1181 }
1182
1183 return 0;
1184}
1185
Mike Lockwood94afecf2012-10-24 10:45:23 -07001186void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1187 struct stat* statbuf)
1188{
1189 while (path[basepos] != 0) {
1190 if (path[basepos] == '/') {
1191 path[basepos] = 0;
1192 if (lstat(path, statbuf) < 0) {
1193 ALOGV("Making directory: %s\n", path);
1194 if (mkdir(path, mode) == 0) {
1195 chown(path, uid, gid);
1196 } else {
1197 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1198 }
1199 }
1200 path[basepos] = '/';
1201 basepos++;
1202 }
1203 basepos++;
1204 }
1205}
1206
1207int movefileordir(char* srcpath, char* dstpath, int dstbasepos,
1208 int dstuid, int dstgid, struct stat* statbuf)
1209{
1210 DIR *d;
1211 struct dirent *de;
1212 int res;
1213
1214 int srcend = strlen(srcpath);
1215 int dstend = strlen(dstpath);
Dave Allisond9370732014-01-30 14:19:23 -08001216
Mike Lockwood94afecf2012-10-24 10:45:23 -07001217 if (lstat(srcpath, statbuf) < 0) {
1218 ALOGW("Unable to stat %s: %s\n", srcpath, strerror(errno));
1219 return 1;
1220 }
Dave Allisond9370732014-01-30 14:19:23 -08001221
Mike Lockwood94afecf2012-10-24 10:45:23 -07001222 if ((statbuf->st_mode&S_IFDIR) == 0) {
1223 mkinnerdirs(dstpath, dstbasepos, S_IRWXU|S_IRWXG|S_IXOTH,
1224 dstuid, dstgid, statbuf);
1225 ALOGV("Renaming %s to %s (uid %d)\n", srcpath, dstpath, dstuid);
1226 if (rename(srcpath, dstpath) >= 0) {
1227 if (chown(dstpath, dstuid, dstgid) < 0) {
1228 ALOGE("cannot chown %s: %s\n", dstpath, strerror(errno));
1229 unlink(dstpath);
1230 return 1;
1231 }
1232 } else {
1233 ALOGW("Unable to rename %s to %s: %s\n",
1234 srcpath, dstpath, strerror(errno));
1235 return 1;
1236 }
1237 return 0;
1238 }
1239
1240 d = opendir(srcpath);
1241 if (d == NULL) {
1242 ALOGW("Unable to opendir %s: %s\n", srcpath, strerror(errno));
1243 return 1;
1244 }
1245
1246 res = 0;
Dave Allisond9370732014-01-30 14:19:23 -08001247
Mike Lockwood94afecf2012-10-24 10:45:23 -07001248 while ((de = readdir(d))) {
1249 const char *name = de->d_name;
1250 /* always skip "." and ".." */
1251 if (name[0] == '.') {
1252 if (name[1] == 0) continue;
1253 if ((name[1] == '.') && (name[2] == 0)) continue;
1254 }
Dave Allisond9370732014-01-30 14:19:23 -08001255
Mike Lockwood94afecf2012-10-24 10:45:23 -07001256 if ((srcend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1257 ALOGW("Source path too long; skipping: %s/%s\n", srcpath, name);
1258 continue;
1259 }
Dave Allisond9370732014-01-30 14:19:23 -08001260
Mike Lockwood94afecf2012-10-24 10:45:23 -07001261 if ((dstend+strlen(name)) >= (PKG_PATH_MAX-2)) {
1262 ALOGW("Destination path too long; skipping: %s/%s\n", dstpath, name);
1263 continue;
1264 }
Dave Allisond9370732014-01-30 14:19:23 -08001265
Mike Lockwood94afecf2012-10-24 10:45:23 -07001266 srcpath[srcend] = dstpath[dstend] = '/';
1267 strcpy(srcpath+srcend+1, name);
1268 strcpy(dstpath+dstend+1, name);
Dave Allisond9370732014-01-30 14:19:23 -08001269
Mike Lockwood94afecf2012-10-24 10:45:23 -07001270 if (movefileordir(srcpath, dstpath, dstbasepos, dstuid, dstgid, statbuf) != 0) {
1271 res = 1;
1272 }
Dave Allisond9370732014-01-30 14:19:23 -08001273
Mike Lockwood94afecf2012-10-24 10:45:23 -07001274 // Note: we will be leaving empty directories behind in srcpath,
1275 // but that is okay, the package manager will be erasing all of the
1276 // data associated with .apks that disappear.
Dave Allisond9370732014-01-30 14:19:23 -08001277
Mike Lockwood94afecf2012-10-24 10:45:23 -07001278 srcpath[srcend] = dstpath[dstend] = 0;
1279 }
Dave Allisond9370732014-01-30 14:19:23 -08001280
Mike Lockwood94afecf2012-10-24 10:45:23 -07001281 closedir(d);
1282 return res;
1283}
1284
1285int movefiles()
1286{
1287 DIR *d;
1288 int dfd, subfd;
1289 struct dirent *de;
1290 struct stat s;
1291 char buf[PKG_PATH_MAX+1];
1292 int bufp, bufe, bufi, readlen;
1293
1294 char srcpkg[PKG_NAME_MAX];
1295 char dstpkg[PKG_NAME_MAX];
1296 char srcpath[PKG_PATH_MAX];
1297 char dstpath[PKG_PATH_MAX];
1298 int dstuid=-1, dstgid=-1;
1299 int hasspace;
1300
1301 d = opendir(UPDATE_COMMANDS_DIR_PREFIX);
1302 if (d == NULL) {
1303 goto done;
1304 }
1305 dfd = dirfd(d);
1306
1307 /* Iterate through all files in the directory, executing the
1308 * file movements requested there-in.
1309 */
1310 while ((de = readdir(d))) {
1311 const char *name = de->d_name;
1312
1313 if (de->d_type == DT_DIR) {
1314 continue;
1315 } else {
1316 subfd = openat(dfd, name, O_RDONLY);
1317 if (subfd < 0) {
1318 ALOGW("Unable to open update commands at %s%s\n",
1319 UPDATE_COMMANDS_DIR_PREFIX, name);
1320 continue;
1321 }
Dave Allisond9370732014-01-30 14:19:23 -08001322
Mike Lockwood94afecf2012-10-24 10:45:23 -07001323 bufp = 0;
1324 bufe = 0;
1325 buf[PKG_PATH_MAX] = 0;
1326 srcpkg[0] = dstpkg[0] = 0;
1327 while (1) {
1328 bufi = bufp;
1329 while (bufi < bufe && buf[bufi] != '\n') {
1330 bufi++;
1331 }
1332 if (bufi < bufe) {
1333 buf[bufi] = 0;
1334 ALOGV("Processing line: %s\n", buf+bufp);
1335 hasspace = 0;
1336 while (bufp < bufi && isspace(buf[bufp])) {
1337 hasspace = 1;
1338 bufp++;
1339 }
1340 if (buf[bufp] == '#' || bufp == bufi) {
1341 // skip comments and empty lines.
1342 } else if (hasspace) {
1343 if (dstpkg[0] == 0) {
1344 ALOGW("Path before package line in %s%s: %s\n",
1345 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1346 } else if (srcpkg[0] == 0) {
1347 // Skip -- source package no longer exists.
1348 } else {
1349 ALOGV("Move file: %s (from %s to %s)\n", buf+bufp, srcpkg, dstpkg);
1350 if (!create_move_path(srcpath, srcpkg, buf+bufp, 0) &&
1351 !create_move_path(dstpath, dstpkg, buf+bufp, 0)) {
1352 movefileordir(srcpath, dstpath,
1353 strlen(dstpath)-strlen(buf+bufp),
1354 dstuid, dstgid, &s);
1355 }
1356 }
1357 } else {
1358 char* div = strchr(buf+bufp, ':');
1359 if (div == NULL) {
1360 ALOGW("Bad package spec in %s%s; no ':' sep: %s\n",
1361 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1362 } else {
1363 *div = 0;
1364 div++;
1365 if (strlen(buf+bufp) < PKG_NAME_MAX) {
1366 strcpy(dstpkg, buf+bufp);
1367 } else {
1368 srcpkg[0] = dstpkg[0] = 0;
1369 ALOGW("Package name too long in %s%s: %s\n",
1370 UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
1371 }
1372 if (strlen(div) < PKG_NAME_MAX) {
1373 strcpy(srcpkg, div);
1374 } else {
1375 srcpkg[0] = dstpkg[0] = 0;
1376 ALOGW("Package name too long in %s%s: %s\n",
1377 UPDATE_COMMANDS_DIR_PREFIX, name, div);
1378 }
1379 if (srcpkg[0] != 0) {
1380 if (!create_pkg_path(srcpath, srcpkg, PKG_DIR_POSTFIX, 0)) {
1381 if (lstat(srcpath, &s) < 0) {
1382 // Package no longer exists -- skip.
1383 srcpkg[0] = 0;
1384 }
1385 } else {
1386 srcpkg[0] = 0;
1387 ALOGW("Can't create path %s in %s%s\n",
1388 div, UPDATE_COMMANDS_DIR_PREFIX, name);
1389 }
1390 if (srcpkg[0] != 0) {
1391 if (!create_pkg_path(dstpath, dstpkg, PKG_DIR_POSTFIX, 0)) {
1392 if (lstat(dstpath, &s) == 0) {
1393 dstuid = s.st_uid;
1394 dstgid = s.st_gid;
1395 } else {
1396 // Destination package doesn't
1397 // exist... due to original-package,
1398 // this is normal, so don't be
1399 // noisy about it.
1400 srcpkg[0] = 0;
1401 }
1402 } else {
1403 srcpkg[0] = 0;
1404 ALOGW("Can't create path %s in %s%s\n",
1405 div, UPDATE_COMMANDS_DIR_PREFIX, name);
1406 }
1407 }
1408 ALOGV("Transfering from %s to %s: uid=%d\n",
1409 srcpkg, dstpkg, dstuid);
1410 }
1411 }
1412 }
1413 bufp = bufi+1;
1414 } else {
1415 if (bufp == 0) {
1416 if (bufp < bufe) {
1417 ALOGW("Line too long in %s%s, skipping: %s\n",
1418 UPDATE_COMMANDS_DIR_PREFIX, name, buf);
1419 }
1420 } else if (bufp < bufe) {
1421 memcpy(buf, buf+bufp, bufe-bufp);
1422 bufe -= bufp;
1423 bufp = 0;
1424 }
1425 readlen = read(subfd, buf+bufe, PKG_PATH_MAX-bufe);
1426 if (readlen < 0) {
1427 ALOGW("Failure reading update commands in %s%s: %s\n",
1428 UPDATE_COMMANDS_DIR_PREFIX, name, strerror(errno));
1429 break;
1430 } else if (readlen == 0) {
1431 break;
1432 }
1433 bufe += readlen;
1434 buf[bufe] = 0;
1435 ALOGV("Read buf: %s\n", buf);
1436 }
1437 }
1438 close(subfd);
1439 }
1440 }
1441 closedir(d);
1442done:
1443 return 0;
1444}
1445
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001446int linklib(const char* uuid, const char* pkgname, const char* asecLibDir, int userId)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001447{
Mike Lockwood94afecf2012-10-24 10:45:23 -07001448 struct stat s, libStat;
1449 int rc = 0;
1450
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001451 std::string _pkgdir(create_data_user_package_path(uuid, userId, pkgname));
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001452 std::string _libsymlink(_pkgdir + PKG_LIB_POSTFIX);
1453
1454 const char* pkgdir = _pkgdir.c_str();
1455 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001456
1457 if (stat(pkgdir, &s) < 0) return -1;
1458
1459 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1460 ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1461 return -1;
1462 }
1463
1464 if (chmod(pkgdir, 0700) < 0) {
1465 ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1466 rc = -1;
1467 goto out;
1468 }
1469
1470 if (lstat(libsymlink, &libStat) < 0) {
1471 if (errno != ENOENT) {
1472 ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1473 rc = -1;
1474 goto out;
1475 }
1476 } else {
1477 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001478 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001479 rc = -1;
1480 goto out;
1481 }
1482 } else if (S_ISLNK(libStat.st_mode)) {
1483 if (unlink(libsymlink) < 0) {
1484 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1485 rc = -1;
1486 goto out;
1487 }
1488 }
1489 }
1490
1491 if (symlink(asecLibDir, libsymlink) < 0) {
1492 ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1493 strerror(errno));
1494 rc = -errno;
1495 goto out;
1496 }
1497
1498out:
1499 if (chmod(pkgdir, s.st_mode) < 0) {
1500 ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1501 rc = -errno;
1502 }
1503
1504 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1505 ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1506 return -errno;
1507 }
1508
1509 return rc;
1510}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001511
1512static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1513{
1514 static const char *IDMAP_BIN = "/system/bin/idmap";
1515 static const size_t MAX_INT_LEN = 32;
1516 char idmap_str[MAX_INT_LEN];
1517
1518 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1519
1520 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1521 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1522}
1523
1524// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1525// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1526static int flatten_path(const char *prefix, const char *suffix,
1527 const char *overlay_path, char *idmap_path, size_t N)
1528{
1529 if (overlay_path == NULL || idmap_path == NULL) {
1530 return -1;
1531 }
1532 const size_t len_overlay_path = strlen(overlay_path);
1533 // will access overlay_path + 1 further below; requires absolute path
1534 if (len_overlay_path < 2 || *overlay_path != '/') {
1535 return -1;
1536 }
1537 const size_t len_idmap_root = strlen(prefix);
1538 const size_t len_suffix = strlen(suffix);
1539 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1540 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1541 // additions below would cause overflow
1542 return -1;
1543 }
1544 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1545 return -1;
1546 }
1547 memset(idmap_path, 0, N);
1548 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1549 char *ch = idmap_path + len_idmap_root;
1550 while (*ch != '\0') {
1551 if (*ch == '/') {
1552 *ch = '@';
1553 }
1554 ++ch;
1555 }
1556 return 0;
1557}
1558
1559int idmap(const char *target_apk, const char *overlay_apk, uid_t uid)
1560{
1561 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1562
1563 int idmap_fd = -1;
1564 char idmap_path[PATH_MAX];
1565
1566 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1567 idmap_path, sizeof(idmap_path)) == -1) {
1568 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1569 goto fail;
1570 }
1571
1572 unlink(idmap_path);
1573 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1574 if (idmap_fd < 0) {
1575 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1576 goto fail;
1577 }
1578 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1579 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1580 goto fail;
1581 }
1582 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1583 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1584 goto fail;
1585 }
1586
1587 pid_t pid;
1588 pid = fork();
1589 if (pid == 0) {
1590 /* child -- drop privileges before continuing */
1591 if (setgid(uid) != 0) {
1592 ALOGE("setgid(%d) failed during idmap\n", uid);
1593 exit(1);
1594 }
1595 if (setuid(uid) != 0) {
1596 ALOGE("setuid(%d) failed during idmap\n", uid);
1597 exit(1);
1598 }
1599 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1600 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1601 exit(1);
1602 }
1603
1604 run_idmap(target_apk, overlay_apk, idmap_fd);
1605 exit(1); /* only if exec call to idmap failed */
1606 } else {
1607 int status = wait_child(pid);
1608 if (status != 0) {
1609 ALOGE("idmap failed, status=0x%04x\n", status);
1610 goto fail;
1611 }
1612 }
1613
1614 close(idmap_fd);
1615 return 0;
1616fail:
1617 if (idmap_fd >= 0) {
1618 close(idmap_fd);
1619 unlink(idmap_path);
1620 }
1621 return -1;
1622}
Robert Craige9887e42014-02-20 10:25:56 -05001623
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001624int restorecon_app_data(const char* uuid, const char* pkgName, userid_t userid, int flags,
1625 appid_t appid, const char* seinfo) {
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001626 int res = 0;
Robert Craige9887e42014-02-20 10:25:56 -05001627
Robert Craigda30dc72014-03-27 10:21:12 -04001628 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001629 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Robert Craigda30dc72014-03-27 10:21:12 -04001630
1631 if (!pkgName || !seinfo) {
1632 ALOGE("Package name or seinfo tag is null when trying to restorecon.");
Robert Craige9887e42014-02-20 10:25:56 -05001633 return -1;
1634 }
1635
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001636 uid_t uid = multiuser_get_uid(userid, appid);
1637 if (flags & FLAG_CE_STORAGE) {
1638 auto path = create_data_user_package_path(uuid, userid, pkgName);
1639 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1640 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001641 res = -1;
1642 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001643 }
1644 if (flags & FLAG_DE_STORAGE) {
1645 auto path = create_data_user_de_package_path(uuid, userid, pkgName);
1646 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1647 PLOG(ERROR) << "restorecon failed for " << path;
Jeff Sharkeyea0e4b12015-11-19 15:35:27 -07001648 // TODO: include result once 25796509 is fixed
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001649 }
Robert Craige9887e42014-02-20 10:25:56 -05001650 }
1651
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001652 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001653}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001654
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001655int create_oat_dir(const char* oat_dir, const char* instruction_set)
1656{
1657 char oat_instr_dir[PKG_PATH_MAX];
1658
1659 if (validate_apk_path(oat_dir)) {
1660 ALOGE("invalid apk path '%s' (bad prefix)\n", oat_dir);
1661 return -1;
1662 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001663 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001664 return -1;
1665 }
1666 if (selinux_android_restorecon(oat_dir, 0)) {
1667 ALOGE("cannot restorecon dir '%s': %s\n", oat_dir, strerror(errno));
1668 return -1;
1669 }
1670 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001671 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001672 return -1;
1673 }
1674 return 0;
1675}
1676
1677int rm_package_dir(const char* apk_path)
1678{
1679 if (validate_apk_path(apk_path)) {
1680 ALOGE("invalid apk path '%s' (bad prefix)\n", apk_path);
1681 return -1;
1682 }
1683 return delete_dir_contents(apk_path, 1 /* also_delete_dir */ , NULL /* exclusion_predicate */);
1684}
1685
Narayan Kamathd845c962015-06-04 13:20:27 +01001686int link_file(const char* relative_path, const char* from_base, const char* to_base) {
1687 char from_path[PKG_PATH_MAX];
1688 char to_path[PKG_PATH_MAX];
1689 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1690 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1691
1692 if (validate_apk_path_subdirs(from_path)) {
1693 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", from_path);
1694 return -1;
1695 }
1696
1697 if (validate_apk_path_subdirs(to_path)) {
1698 ALOGE("invalid app data sub-path '%s' (bad prefix)\n", to_path);
1699 return -1;
1700 }
1701
1702 const int ret = link(from_path, to_path);
1703 if (ret < 0) {
1704 ALOGE("link(%s, %s) failed : %s", from_path, to_path, strerror(errno));
1705 return -1;
1706 }
1707
1708 return 0;
1709}
1710
Andreas Gampe02d0de52015-11-11 20:43:16 -08001711} // namespace installd
1712} // namespace android