blob: c1a1202f2e93a9fd7955652fdbea55db48a17ec0 [file] [log] [blame]
Andreas Gampe73dae112015-11-19 14:12:14 -08001/*
2 ** Copyright 2016, The Android Open Source Project
3 **
4 ** 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
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** 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
14 ** limitations under the License.
15 */
16
17#include <algorithm>
18#include <inttypes.h>
Andreas Gampec4ced4f2017-04-14 20:39:56 -070019#include <limits>
Andreas Gampe73dae112015-11-19 14:12:14 -080020#include <random>
Andreas Gampe1842af32016-03-16 14:28:50 -070021#include <regex>
Andreas Gampe73dae112015-11-19 14:12:14 -080022#include <selinux/android.h>
23#include <selinux/avc.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/capability.h>
27#include <sys/prctl.h>
28#include <sys/stat.h>
29#include <sys/wait.h>
30
31#include <android-base/logging.h>
32#include <android-base/macros.h>
33#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070034#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080035#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080036#include <cutils/properties.h>
Andreas Gampe54e1a402017-03-20 18:42:49 -070037#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080039#include <private/android_filesystem_config.h>
40
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070041#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070042#include "file_parsing.h"
43#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070044#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070045#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000046#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070047#include "otapreopt_utils.h"
48#include "system_properties.h"
49#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
Andreas Gampe73dae112015-11-19 14:12:14 -080051#ifndef LOG_TAG
52#define LOG_TAG "otapreopt"
53#endif
54
55#define BUFFER_MAX 1024 /* input buffer for commands */
56#define TOKEN_MAX 16 /* max number of arguments in buffer */
57#define REPLY_MAX 256 /* largest reply allowed */
58
Andreas Gampe56f79f92016-06-08 15:11:37 -070059using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070060using android::base::Join;
61using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070062using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080063using android::base::StringPrintf;
64
65namespace android {
66namespace installd {
67
Andreas Gampeef21fd22017-05-22 13:36:06 -070068// Check expected values for dexopt flags. If you need to change this:
69//
70// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
71//
72// You most likely need to increase the protocol version and all that entails!
73
74static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
75static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
76static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
77static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
78static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
79static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
80static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
81static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080082static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
83 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070084
Andreas Gamped32eec22018-02-28 16:02:51 -080085static_assert(DEXOPT_MASK == (0x5fe | DEXOPT_IDLE_BACKGROUND_JOB),
86 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070087
88
89
Andreas Gampe73dae112015-11-19 14:12:14 -080090template<typename T>
91static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
92 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
93}
94
95template<typename T>
96static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
97 return RoundDown(x + n - 1, n);
98}
99
100class OTAPreoptService {
101 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800102 // Main driver. Performs the following steps.
103 //
104 // 1) Parse options (read system properties etc from B partition).
105 //
106 // 2) Read in package data.
107 //
108 // 3) Prepare environment variables.
109 //
110 // 4) Prepare(compile) boot image, if necessary.
111 //
112 // 5) Run update.
113 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700114 if (!ReadArguments(argc, argv)) {
115 LOG(ERROR) << "Failed reading command line.";
116 return 1;
117 }
118
Andreas Gampe73dae112015-11-19 14:12:14 -0800119 if (!ReadSystemProperties()) {
120 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700121 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800122 }
123
124 if (!ReadEnvironment()) {
125 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700126 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800127 }
128
Andreas Gamped089ca12016-06-27 14:25:30 -0700129 if (!CheckAndInitializeInstalldGlobals()) {
130 LOG(ERROR) << "Failed initializing globals.";
131 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800132 }
133
134 PrepareEnvironment();
135
Andreas Gamped089ca12016-06-27 14:25:30 -0700136 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800137 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700138 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800139 }
140
141 int dexopt_retcode = RunPreopt();
142
143 return dexopt_retcode;
144 }
145
Andreas Gamped089ca12016-06-27 14:25:30 -0700146 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800147 const std::string* prop_value = system_properties_.GetProperty(key);
148 if (prop_value == nullptr) {
149 if (default_value == nullptr) {
150 return 0;
151 }
152 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600153 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800154 value[kPropertyValueMax - 1] = 0;
155 return strlen(default_value);// TODO: Need to truncate?
156 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700157 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600158 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700159 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800160 }
161
Andreas Gamped089ca12016-06-27 14:25:30 -0700162 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000163 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700164 }
165
166 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000167 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700168 }
169
Andreas Gampe73dae112015-11-19 14:12:14 -0800170private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700171
Andreas Gampe73dae112015-11-19 14:12:14 -0800172 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700173 static constexpr const char* kPropertyFiles[] = {
174 "/default.prop", "/system/build.prop"
175 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800176
Andreas Gampe1842af32016-03-16 14:28:50 -0700177 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
178 if (!system_properties_.Load(kPropertyFiles[i])) {
179 return false;
180 }
181 }
182
183 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800184 }
185
186 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700187 // Parse the environment variables from init.environ.rc, which have the form
188 // export NAME VALUE
189 // For simplicity, don't respect string quotation. The values we are interested in can be
190 // encoded without them.
191 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
192 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
193 std::smatch export_match;
194 if (!std::regex_match(line, export_match, export_regex)) {
195 return true;
196 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800197
Andreas Gampe1842af32016-03-16 14:28:50 -0700198 if (export_match.size() != 3) {
199 return true;
200 }
201
202 std::string name = export_match[1].str();
203 std::string value = export_match[2].str();
204
205 system_properties_.SetProperty(name, value);
206
207 return true;
208 });
209 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800210 return false;
211 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700212
Andreas Gamped089ca12016-06-27 14:25:30 -0700213 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
214 return false;
215 }
216 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
217
218 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
219 return false;
220 }
221 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
222
223 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
224 return false;
225 }
226 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
227
228 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
229 return false;
230 }
231 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
232
233 return true;
234 }
235
236 const std::string& GetAndroidData() const {
237 return android_data_;
238 }
239
240 const std::string& GetAndroidRoot() const {
241 return android_root_;
242 }
243
244 const std::string GetOtaDirectoryPrefix() const {
245 return GetAndroidData() + "/ota";
246 }
247
248 bool CheckAndInitializeInstalldGlobals() {
249 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
250 // do not use any datapath that includes this, but we'll still have to set it.
251 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
252 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
253 if (result != 0) {
254 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
255 return false;
256 }
257
258 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
259 LOG(ERROR) << "Could not initialize globals; exiting.";
260 return false;
261 }
262
263 // This is different from the normal installd. We only do the base
264 // directory, the rest will be created on demand when each app is compiled.
265 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
266 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
267 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700268 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800269
270 return true;
271 }
272
Shubham Ajmera45c87432017-06-22 11:10:27 -0700273 bool ParseBool(const char* in) {
274 if (strcmp(in, "true") == 0) {
275 return true;
276 }
277 return false;
278 }
279
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700280 bool ParseUInt(const char* in, uint32_t* out) {
281 char* end;
282 long long int result = strtoll(in, &end, 0);
283 if (in == end || *end != '\0') {
284 return false;
285 }
286 if (result < std::numeric_limits<uint32_t>::min() ||
287 std::numeric_limits<uint32_t>::max() < result) {
288 return false;
289 }
290 *out = static_cast<uint32_t>(result);
291 return true;
292 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700293
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700294 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000295 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800296 }
297
298 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700299 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
300 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
301 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800302
303 for (const std::string& e : environ_) {
304 putenv(const_cast<char*>(e.c_str()));
305 }
306 }
307
308 // Ensure that we have the right boot image. The first time any app is
309 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700310 bool PrepareBootImage(bool force) const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000311 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800312 LOG(ERROR) << "Instruction set missing.";
313 return false;
314 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000315 const char* isa = parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800316
317 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700318 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800319 std::string isa_path = dalvik_cache + "/" + isa;
320 std::string art_path = isa_path + "/system@framework@boot.art";
321 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700322 bool cleared = false;
323 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
324 // Files exist, assume everything is alright if not forced. Otherwise clean up.
325 if (!force) {
326 return true;
327 }
328 ClearDirectory(isa_path);
329 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800330 }
331
Andreas Gamped089ca12016-06-27 14:25:30 -0700332 // Reset umask in otapreopt, so that we control the the access for the files we create.
333 umask(0);
334
Andreas Gampe73dae112015-11-19 14:12:14 -0800335 // Create the directories, if necessary.
336 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700337 if (!CreatePath(dalvik_cache)) {
338 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800339 return false;
340 }
341 }
342 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700343 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800344 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
345 return false;
346 }
347 }
348
Andreas Gampe5709b572016-02-12 17:42:59 -0800349 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700350 if (!cleared) {
351 ClearDirectory(isa_path);
352 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800353
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700354 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800355 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
Chris Morin77c48752018-02-13 15:44:47 -0800356 return PatchoatBootImage(isa_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800357 } else {
358 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700359 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800360 }
361 }
362
Andreas Gamped089ca12016-06-27 14:25:30 -0700363 static bool CreatePath(const std::string& path) {
364 // Create the given path. Use string processing instead of dirname, as dirname's need for
365 // a writable char buffer is painful.
366
367 // First, try to use the full path.
368 if (mkdir(path.c_str(), 0711) == 0) {
369 return true;
370 }
371 if (errno != ENOENT) {
372 PLOG(ERROR) << "Could not create path " << path;
373 return false;
374 }
375
376 // Now find the parent and try that first.
377 size_t last_slash = path.find_last_of('/');
378 if (last_slash == std::string::npos || last_slash == 0) {
379 PLOG(ERROR) << "Could not create " << path;
380 return false;
381 }
382
383 if (!CreatePath(path.substr(0, last_slash))) {
384 return false;
385 }
386
387 if (mkdir(path.c_str(), 0711) == 0) {
388 return true;
389 }
390 PLOG(ERROR) << "Could not create " << path;
391 return false;
392 }
393
394 static void ClearDirectory(const std::string& dir) {
395 DIR* c_dir = opendir(dir.c_str());
396 if (c_dir == nullptr) {
397 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
398 return;
399 }
400
401 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
402 const char* name = de->d_name;
403 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
404 continue;
405 }
406 // We only want to delete regular files and symbolic links.
407 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
408 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
409 LOG(WARNING) << "Unexpected file "
410 << file
411 << " of type "
412 << std::hex
413 << de->d_type
414 << " encountered.";
415 } else {
416 // Try to unlink the file.
417 if (unlink(file.c_str()) != 0) {
418 PLOG(ERROR) << "Unable to unlink " << file;
419 }
420 }
421 }
422 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
423 }
424
Chris Morin77c48752018-02-13 15:44:47 -0800425 bool PatchoatBootImage(const std::string& output_dir, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800426 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
427
428 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700429 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800430
431 cmd.push_back("--input-image-location=/system/framework/boot.art");
Chris Morin77c48752018-02-13 15:44:47 -0800432 cmd.push_back(StringPrintf("--output-image-directory=%s", output_dir.c_str()));
Andreas Gampe5709b572016-02-12 17:42:59 -0800433
434 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
435
436 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
437 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800438 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800439
440 std::string error_msg;
441 bool result = Exec(cmd, &error_msg);
442 if (!result) {
443 LOG(ERROR) << "Could not generate boot image: " << error_msg;
444 }
445 return result;
446 }
447
448 bool Dex2oatBootImage(const std::string& boot_cp,
449 const std::string& art_path,
450 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700451 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800452 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
453 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700454 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800455 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700456 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800457 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
458 }
459 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
460
461 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
462 ART_BASE_ADDRESS_MAX_DELTA);
463 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
464
465 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
466
467 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
468 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
469 "-Xms",
470 true,
471 cmd);
472 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
473 "-Xmx",
474 true,
475 cmd);
476 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
477 "--compiler-filter=",
478 false,
479 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700480 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800481 // TODO: Compiled-classes.
482 const std::string* extra_opts =
483 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
484 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700485 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800486 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
487 }
488 // TODO: Should we lower this? It's usually set close to max, because
489 // normally there's not much else going on at boot.
490 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
491 "-j",
492 false,
493 cmd);
494 AddCompilerOptionFromSystemProperty(
495 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
496 "--instruction-set-variant=",
497 false,
498 cmd);
499 AddCompilerOptionFromSystemProperty(
500 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
501 "--instruction-set-features=",
502 false,
503 cmd);
504
505 std::string error_msg;
506 bool result = Exec(cmd, &error_msg);
507 if (!result) {
508 LOG(ERROR) << "Could not generate boot image: " << error_msg;
509 }
510 return result;
511 }
512
513 static const char* ParseNull(const char* arg) {
514 return (strcmp(arg, "!") == 0) ? nullptr : arg;
515 }
516
Andreas Gamped089ca12016-06-27 14:25:30 -0700517 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700518 // There's one thing we have to be careful about: we may/will be asked to compile an app
519 // living in the system image. This may be a valid request - if the app wasn't compiled,
520 // e.g., if the system image wasn't large enough to include preopted files. However, the
521 // data we have is from the old system, so the driver (the OTA service) can't actually
522 // know. Thus, we will get requests for apps that have preopted components. To avoid
523 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
524 // simple checks:
525 //
526 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
527 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
528 //
529 // 2) If you replace the name in the apk_path with "oat," does the path exist?
530 // (=have a subdirectory for preopted files)
531 //
532 // If the answer to both is yes, skip the dexopt.
533 //
534 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
535 // be stripped), that's not true for APKs signed outside the build system (so the
536 // jar content must be exactly the same).
537
538 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000539 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700540 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000541 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700542 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800543 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700544 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700545 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700546 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700547 CHECK(EndsWith(path, "/"));
548 path = path + "oat";
549 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800550 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700551 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700552 }
553 }
554 }
555
Andreas Gamped089ca12016-06-27 14:25:30 -0700556 // Another issue is unavailability of files in the new system. If the partition
557 // layout changes, otapreopt_chroot may not know about this. Then files from that
558 // partition will not be available and fail to build. This is problematic, as
559 // this tool will wipe the OTA artifact cache and try again (for robustness after
560 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700561 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800562 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700563 return true;
564 }
565
566 return false;
567 }
568
Calin Juravlec9e76792018-02-01 14:44:56 +0000569 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800570 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700571 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800572 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000573 return dexopt(parameters_.apk_path,
574 parameters_.uid,
575 parameters_.pkgName,
576 parameters_.instruction_set,
577 parameters_.dexopt_needed,
578 parameters_.oat_dir,
579 parameters_.dexopt_flags,
580 parameters_.compiler_filter,
581 parameters_.volume_uuid,
582 parameters_.shared_libraries,
583 parameters_.se_info,
584 parameters_.downgrade,
585 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000586 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800587 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800588 parameters_.compilation_reason,
589 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800590 }
591
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700592 int RunPreopt() {
593 if (ShouldSkipPreopt()) {
594 return 0;
595 }
596
597 int dexopt_result = Dexopt();
598 if (dexopt_result == 0) {
599 return 0;
600 }
601
602 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
603 // Then regenerate and retry.
604 if (WEXITSTATUS(dexopt_result) ==
605 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
606 if (!PrepareBootImage(/* force */ true)) {
607 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
608 << dexopt_result;
609 return dexopt_result;
610 }
611
612 int dexopt_result_boot_image_retry = Dexopt();
613 if (dexopt_result_boot_image_retry == 0) {
614 return 0;
615 }
616 }
617
618 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
619 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000620 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700621 return dexopt_result;
622 }
623
624 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000625 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700626 return Dexopt();
627 }
628
Andreas Gampe73dae112015-11-19 14:12:14 -0800629 ////////////////////////////////////
630 // Helpers, mostly taken from ART //
631 ////////////////////////////////////
632
633 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700634 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700635 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800636
637 CHECK_GE(arg_vector.size(), 1U) << command_line;
638
639 // Convert the args to char pointers.
640 const char* program = arg_vector[0].c_str();
641 std::vector<char*> args;
642 for (size_t i = 0; i < arg_vector.size(); ++i) {
643 const std::string& arg = arg_vector[i];
644 char* arg_str = const_cast<char*>(arg.c_str());
645 CHECK(arg_str != nullptr) << i;
646 args.push_back(arg_str);
647 }
648 args.push_back(nullptr);
649
650 // Fork and exec.
651 pid_t pid = fork();
652 if (pid == 0) {
653 // No allocation allowed between fork and exec.
654
655 // Change process groups, so we don't get reaped by ProcessManager.
656 setpgid(0, 0);
657
658 execv(program, &args[0]);
659
660 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
661 // _exit to avoid atexit handlers in child.
662 _exit(1);
663 } else {
664 if (pid == -1) {
665 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
666 command_line.c_str(), strerror(errno));
667 return false;
668 }
669
670 // wait for subprocess to finish
671 int status;
672 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
673 if (got_pid != pid) {
674 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
675 "wanted %d, got %d: %s",
676 command_line.c_str(), pid, got_pid, strerror(errno));
677 return false;
678 }
679 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
680 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
681 command_line.c_str());
682 return false;
683 }
684 }
685 return true;
686 }
687
688 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
689 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
690 constexpr size_t kPageSize = PAGE_SIZE;
691 CHECK_EQ(min_delta % kPageSize, 0u);
692 CHECK_EQ(max_delta % kPageSize, 0u);
693 CHECK_LT(min_delta, max_delta);
694
695 std::default_random_engine generator;
696 generator.seed(GetSeed());
697 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
698 int32_t r = distribution(generator);
699 if (r % 2 == 0) {
700 r = RoundUp(r, kPageSize);
701 } else {
702 r = RoundDown(r, kPageSize);
703 }
704 CHECK_LE(min_delta, r);
705 CHECK_GE(max_delta, r);
706 CHECK_EQ(r % kPageSize, 0u);
707 return r;
708 }
709
710 static uint64_t GetSeed() {
711#ifdef __BIONIC__
712 // Bionic exposes arc4random, use it.
713 uint64_t random_data;
714 arc4random_buf(&random_data, sizeof(random_data));
715 return random_data;
716#else
717#error "This is only supposed to run with bionic. Otherwise, implement..."
718#endif
719 }
720
721 void AddCompilerOptionFromSystemProperty(const char* system_property,
722 const char* prefix,
723 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700724 std::vector<std::string>& out) const {
725 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800726 if (value != nullptr) {
727 if (runtime) {
728 out.push_back("--runtime-arg");
729 }
730 if (prefix != nullptr) {
731 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
732 } else {
733 out.push_back(*value);
734 }
735 }
736 }
737
Andreas Gamped089ca12016-06-27 14:25:30 -0700738 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
739 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
740 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
741 // The index of the instruction-set string inside the package parameters. Needed for
742 // some special-casing that requires knowledge of the instruction-set.
743 static constexpr size_t kISAIndex = 3;
744
Andreas Gampe73dae112015-11-19 14:12:14 -0800745 // Stores the system properties read out of the B partition. We need to use these properties
746 // to compile, instead of the A properties we could get from init/get_property.
747 SystemProperties system_properties_;
748
Andreas Gamped089ca12016-06-27 14:25:30 -0700749 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700750 std::string android_root_;
751 std::string android_data_;
752 std::string boot_classpath_;
753 std::string asec_mountpoint_;
754
Calin Juravlec9e76792018-02-01 14:44:56 +0000755 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800756
757 // Store environment values we need to set.
758 std::vector<std::string> environ_;
759};
760
761OTAPreoptService gOps;
762
763////////////////////////
764// Plug-in functions. //
765////////////////////////
766
767int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800768 return gOps.GetProperty(key, value, default_value);
769}
770
771// Compute the output path of
772bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
773 const char *apk_path,
774 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700775 const char *file_name_start;
776 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800777
778 file_name_start = strrchr(apk_path, '/');
779 if (file_name_start == nullptr) {
780 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
781 return false;
782 }
783 file_name_end = strrchr(file_name_start, '.');
784 if (file_name_end == nullptr) {
785 ALOGE("apk_path '%s' has no extension\n", apk_path);
786 return false;
787 }
788
789 // Calculate file_name
790 file_name_start++; // Move past '/', is valid as file_name_end is valid.
791 size_t file_name_len = file_name_end - file_name_start;
792 std::string file_name(file_name_start, file_name_len);
793
794 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700795 snprintf(path,
796 PKG_PATH_MAX,
797 "%s/%s/%s.odex.%s",
798 oat_dir,
799 instruction_set,
800 file_name.c_str(),
801 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800802 return true;
803}
804
805/*
806 * Computes the odex file for the given apk_path and instruction_set.
807 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
808 *
809 * Returns false if it failed to determine the odex file path.
810 */
811bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
812 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800813 const char *path_end = strrchr(apk_path, '/');
814 if (path_end == nullptr) {
815 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
816 return false;
817 }
818 std::string path_component(apk_path, path_end - apk_path);
819
820 const char *name_begin = path_end + 1;
821 const char *extension_start = strrchr(name_begin, '.');
822 if (extension_start == nullptr) {
823 ALOGE("apk_path '%s' has no extension.\n", apk_path);
824 return false;
825 }
826 std::string name_component(name_begin, extension_start - name_begin);
827
Andreas Gamped089ca12016-06-27 14:25:30 -0700828 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800829 path_component.c_str(),
830 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700831 name_component.c_str(),
832 gOps.GetTargetSlot().c_str());
833 if (new_path.length() >= PKG_PATH_MAX) {
834 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
835 return false;
836 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800837 strcpy(path, new_path.c_str());
838 return true;
839}
840
841bool create_cache_path(char path[PKG_PATH_MAX],
842 const char *src,
843 const char *instruction_set) {
844 size_t srclen = strlen(src);
845
846 /* demand that we are an absolute path */
847 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
848 return false;
849 }
850
851 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
852 return false;
853 }
854
855 std::string from_src = std::string(src + 1);
856 std::replace(from_src.begin(), from_src.end(), '/', '@');
857
858 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700859 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800860 DALVIK_CACHE,
861 instruction_set,
862 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100863 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800864
865 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
866 return false;
867 }
868 strcpy(path, assembled_path.c_str());
869
870 return true;
871}
872
Andreas Gampe73dae112015-11-19 14:12:14 -0800873static int log_callback(int type, const char *fmt, ...) {
874 va_list ap;
875 int priority;
876
877 switch (type) {
878 case SELINUX_WARNING:
879 priority = ANDROID_LOG_WARN;
880 break;
881 case SELINUX_INFO:
882 priority = ANDROID_LOG_INFO;
883 break;
884 default:
885 priority = ANDROID_LOG_ERROR;
886 break;
887 }
888 va_start(ap, fmt);
889 LOG_PRI_VA(priority, "SELinux", fmt, ap);
890 va_end(ap);
891 return 0;
892}
893
894static int otapreopt_main(const int argc, char *argv[]) {
895 int selinux_enabled = (is_selinux_enabled() > 0);
896
897 setenv("ANDROID_LOG_TAGS", "*:v", 1);
898 android::base::InitLogging(argv);
899
Andreas Gampe73dae112015-11-19 14:12:14 -0800900 if (argc < 2) {
901 ALOGE("Expecting parameters");
902 exit(1);
903 }
904
905 union selinux_callback cb;
906 cb.func_log = log_callback;
907 selinux_set_callback(SELINUX_CB_LOG, cb);
908
Andreas Gampe73dae112015-11-19 14:12:14 -0800909 if (selinux_enabled && selinux_status_open(true) < 0) {
910 ALOGE("Could not open selinux status; exiting.\n");
911 exit(1);
912 }
913
914 int ret = android::installd::gOps.Main(argc, argv);
915
916 return ret;
917}
918
919} // namespace installd
920} // namespace android
921
922int main(const int argc, char *argv[]) {
923 return android::installd::otapreopt_main(argc, argv);
924}