blob: f2d1b338fa07ed934d8863d7a1acdb34026dac08 [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
David Brazdil7fcbb812018-01-17 17:05:40 +000085static_assert(DEXOPT_MASK == 0x5fe, "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070086
87
88
Andreas Gampe73dae112015-11-19 14:12:14 -080089template<typename T>
90static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
91 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
92}
93
94template<typename T>
95static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
96 return RoundDown(x + n - 1, n);
97}
98
99class OTAPreoptService {
100 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800101 // Main driver. Performs the following steps.
102 //
103 // 1) Parse options (read system properties etc from B partition).
104 //
105 // 2) Read in package data.
106 //
107 // 3) Prepare environment variables.
108 //
109 // 4) Prepare(compile) boot image, if necessary.
110 //
111 // 5) Run update.
112 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700113 if (!ReadArguments(argc, argv)) {
114 LOG(ERROR) << "Failed reading command line.";
115 return 1;
116 }
117
Andreas Gampe73dae112015-11-19 14:12:14 -0800118 if (!ReadSystemProperties()) {
119 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700120 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800121 }
122
123 if (!ReadEnvironment()) {
124 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700125 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800126 }
127
Andreas Gamped089ca12016-06-27 14:25:30 -0700128 if (!CheckAndInitializeInstalldGlobals()) {
129 LOG(ERROR) << "Failed initializing globals.";
130 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800131 }
132
133 PrepareEnvironment();
134
Andreas Gamped089ca12016-06-27 14:25:30 -0700135 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800136 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700137 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800138 }
139
140 int dexopt_retcode = RunPreopt();
141
142 return dexopt_retcode;
143 }
144
Andreas Gamped089ca12016-06-27 14:25:30 -0700145 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800146 const std::string* prop_value = system_properties_.GetProperty(key);
147 if (prop_value == nullptr) {
148 if (default_value == nullptr) {
149 return 0;
150 }
151 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600152 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800153 value[kPropertyValueMax - 1] = 0;
154 return strlen(default_value);// TODO: Need to truncate?
155 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700156 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600157 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700158 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800159 }
160
Andreas Gamped089ca12016-06-27 14:25:30 -0700161 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000162 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700163 }
164
165 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000166 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700167 }
168
Andreas Gampe73dae112015-11-19 14:12:14 -0800169private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700170
Andreas Gampe73dae112015-11-19 14:12:14 -0800171 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700172 static constexpr const char* kPropertyFiles[] = {
173 "/default.prop", "/system/build.prop"
174 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800175
Andreas Gampe1842af32016-03-16 14:28:50 -0700176 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
177 if (!system_properties_.Load(kPropertyFiles[i])) {
178 return false;
179 }
180 }
181
182 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800183 }
184
185 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700186 // Parse the environment variables from init.environ.rc, which have the form
187 // export NAME VALUE
188 // For simplicity, don't respect string quotation. The values we are interested in can be
189 // encoded without them.
190 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
191 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
192 std::smatch export_match;
193 if (!std::regex_match(line, export_match, export_regex)) {
194 return true;
195 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800196
Andreas Gampe1842af32016-03-16 14:28:50 -0700197 if (export_match.size() != 3) {
198 return true;
199 }
200
201 std::string name = export_match[1].str();
202 std::string value = export_match[2].str();
203
204 system_properties_.SetProperty(name, value);
205
206 return true;
207 });
208 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800209 return false;
210 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700211
Andreas Gamped089ca12016-06-27 14:25:30 -0700212 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
213 return false;
214 }
215 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
216
217 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
218 return false;
219 }
220 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
221
222 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
223 return false;
224 }
225 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
226
227 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
228 return false;
229 }
230 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
231
232 return true;
233 }
234
235 const std::string& GetAndroidData() const {
236 return android_data_;
237 }
238
239 const std::string& GetAndroidRoot() const {
240 return android_root_;
241 }
242
243 const std::string GetOtaDirectoryPrefix() const {
244 return GetAndroidData() + "/ota";
245 }
246
247 bool CheckAndInitializeInstalldGlobals() {
248 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
249 // do not use any datapath that includes this, but we'll still have to set it.
250 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
251 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
252 if (result != 0) {
253 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
254 return false;
255 }
256
257 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
258 LOG(ERROR) << "Could not initialize globals; exiting.";
259 return false;
260 }
261
262 // This is different from the normal installd. We only do the base
263 // directory, the rest will be created on demand when each app is compiled.
264 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
265 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
266 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700267 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800268
269 return true;
270 }
271
Shubham Ajmera45c87432017-06-22 11:10:27 -0700272 bool ParseBool(const char* in) {
273 if (strcmp(in, "true") == 0) {
274 return true;
275 }
276 return false;
277 }
278
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700279 bool ParseUInt(const char* in, uint32_t* out) {
280 char* end;
281 long long int result = strtoll(in, &end, 0);
282 if (in == end || *end != '\0') {
283 return false;
284 }
285 if (result < std::numeric_limits<uint32_t>::min() ||
286 std::numeric_limits<uint32_t>::max() < result) {
287 return false;
288 }
289 *out = static_cast<uint32_t>(result);
290 return true;
291 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700292
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700293 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000294 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800295 }
296
297 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700298 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
299 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
300 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800301
302 for (const std::string& e : environ_) {
303 putenv(const_cast<char*>(e.c_str()));
304 }
305 }
306
307 // Ensure that we have the right boot image. The first time any app is
308 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700309 bool PrepareBootImage(bool force) const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000310 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800311 LOG(ERROR) << "Instruction set missing.";
312 return false;
313 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000314 const char* isa = parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800315
316 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700317 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800318 std::string isa_path = dalvik_cache + "/" + isa;
319 std::string art_path = isa_path + "/system@framework@boot.art";
320 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700321 bool cleared = false;
322 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
323 // Files exist, assume everything is alright if not forced. Otherwise clean up.
324 if (!force) {
325 return true;
326 }
327 ClearDirectory(isa_path);
328 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800329 }
330
Andreas Gamped089ca12016-06-27 14:25:30 -0700331 // Reset umask in otapreopt, so that we control the the access for the files we create.
332 umask(0);
333
Andreas Gampe73dae112015-11-19 14:12:14 -0800334 // Create the directories, if necessary.
335 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700336 if (!CreatePath(dalvik_cache)) {
337 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800338 return false;
339 }
340 }
341 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700342 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800343 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
344 return false;
345 }
346 }
347
Andreas Gampe5709b572016-02-12 17:42:59 -0800348 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700349 if (!cleared) {
350 ClearDirectory(isa_path);
351 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800352
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700353 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800354 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
355 return PatchoatBootImage(art_path, isa);
356 } else {
357 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700358 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800359 }
360 }
361
Andreas Gamped089ca12016-06-27 14:25:30 -0700362 static bool CreatePath(const std::string& path) {
363 // Create the given path. Use string processing instead of dirname, as dirname's need for
364 // a writable char buffer is painful.
365
366 // First, try to use the full path.
367 if (mkdir(path.c_str(), 0711) == 0) {
368 return true;
369 }
370 if (errno != ENOENT) {
371 PLOG(ERROR) << "Could not create path " << path;
372 return false;
373 }
374
375 // Now find the parent and try that first.
376 size_t last_slash = path.find_last_of('/');
377 if (last_slash == std::string::npos || last_slash == 0) {
378 PLOG(ERROR) << "Could not create " << path;
379 return false;
380 }
381
382 if (!CreatePath(path.substr(0, last_slash))) {
383 return false;
384 }
385
386 if (mkdir(path.c_str(), 0711) == 0) {
387 return true;
388 }
389 PLOG(ERROR) << "Could not create " << path;
390 return false;
391 }
392
393 static void ClearDirectory(const std::string& dir) {
394 DIR* c_dir = opendir(dir.c_str());
395 if (c_dir == nullptr) {
396 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
397 return;
398 }
399
400 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
401 const char* name = de->d_name;
402 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
403 continue;
404 }
405 // We only want to delete regular files and symbolic links.
406 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
407 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
408 LOG(WARNING) << "Unexpected file "
409 << file
410 << " of type "
411 << std::hex
412 << de->d_type
413 << " encountered.";
414 } else {
415 // Try to unlink the file.
416 if (unlink(file.c_str()) != 0) {
417 PLOG(ERROR) << "Unable to unlink " << file;
418 }
419 }
420 }
421 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
422 }
423
424 bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800425 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
426
427 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700428 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800429
430 cmd.push_back("--input-image-location=/system/framework/boot.art");
431 cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
432
433 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
434
435 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
436 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800437 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800438
439 std::string error_msg;
440 bool result = Exec(cmd, &error_msg);
441 if (!result) {
442 LOG(ERROR) << "Could not generate boot image: " << error_msg;
443 }
444 return result;
445 }
446
447 bool Dex2oatBootImage(const std::string& boot_cp,
448 const std::string& art_path,
449 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700450 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800451 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
452 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700453 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800454 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700455 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800456 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
457 }
458 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
459
460 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
461 ART_BASE_ADDRESS_MAX_DELTA);
462 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
463
464 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
465
466 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
467 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
468 "-Xms",
469 true,
470 cmd);
471 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
472 "-Xmx",
473 true,
474 cmd);
475 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
476 "--compiler-filter=",
477 false,
478 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700479 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800480 // TODO: Compiled-classes.
481 const std::string* extra_opts =
482 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
483 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700484 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800485 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
486 }
487 // TODO: Should we lower this? It's usually set close to max, because
488 // normally there's not much else going on at boot.
489 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
490 "-j",
491 false,
492 cmd);
493 AddCompilerOptionFromSystemProperty(
494 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
495 "--instruction-set-variant=",
496 false,
497 cmd);
498 AddCompilerOptionFromSystemProperty(
499 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
500 "--instruction-set-features=",
501 false,
502 cmd);
503
504 std::string error_msg;
505 bool result = Exec(cmd, &error_msg);
506 if (!result) {
507 LOG(ERROR) << "Could not generate boot image: " << error_msg;
508 }
509 return result;
510 }
511
512 static const char* ParseNull(const char* arg) {
513 return (strcmp(arg, "!") == 0) ? nullptr : arg;
514 }
515
Andreas Gamped089ca12016-06-27 14:25:30 -0700516 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700517 // There's one thing we have to be careful about: we may/will be asked to compile an app
518 // living in the system image. This may be a valid request - if the app wasn't compiled,
519 // e.g., if the system image wasn't large enough to include preopted files. However, the
520 // data we have is from the old system, so the driver (the OTA service) can't actually
521 // know. Thus, we will get requests for apps that have preopted components. To avoid
522 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
523 // simple checks:
524 //
525 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
526 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
527 //
528 // 2) If you replace the name in the apk_path with "oat," does the path exist?
529 // (=have a subdirectory for preopted files)
530 //
531 // If the answer to both is yes, skip the dexopt.
532 //
533 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
534 // be stripped), that's not true for APKs signed outside the build system (so the
535 // jar content must be exactly the same).
536
537 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000538 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700539 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000540 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700541 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800542 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700543 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700544 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700545 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700546 CHECK(EndsWith(path, "/"));
547 path = path + "oat";
548 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800549 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700550 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700551 }
552 }
553 }
554
Andreas Gamped089ca12016-06-27 14:25:30 -0700555 // Another issue is unavailability of files in the new system. If the partition
556 // layout changes, otapreopt_chroot may not know about this. Then files from that
557 // partition will not be available and fail to build. This is problematic, as
558 // this tool will wipe the OTA artifact cache and try again (for robustness after
559 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700560 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800561 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700562 return true;
563 }
564
565 return false;
566 }
567
Calin Juravlec9e76792018-02-01 14:44:56 +0000568 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800569 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700570 int Dexopt() {
Calin Juravlec9e76792018-02-01 14:44:56 +0000571 return dexopt(parameters_.apk_path,
572 parameters_.uid,
573 parameters_.pkgName,
574 parameters_.instruction_set,
575 parameters_.dexopt_needed,
576 parameters_.oat_dir,
577 parameters_.dexopt_flags,
578 parameters_.compiler_filter,
579 parameters_.volume_uuid,
580 parameters_.shared_libraries,
581 parameters_.se_info,
582 parameters_.downgrade,
583 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000584 parameters_.profile_name,
585 parameters_.dex_metadata_path);
Andreas Gampe73dae112015-11-19 14:12:14 -0800586 }
587
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700588 int RunPreopt() {
589 if (ShouldSkipPreopt()) {
590 return 0;
591 }
592
593 int dexopt_result = Dexopt();
594 if (dexopt_result == 0) {
595 return 0;
596 }
597
598 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
599 // Then regenerate and retry.
600 if (WEXITSTATUS(dexopt_result) ==
601 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
602 if (!PrepareBootImage(/* force */ true)) {
603 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
604 << dexopt_result;
605 return dexopt_result;
606 }
607
608 int dexopt_result_boot_image_retry = Dexopt();
609 if (dexopt_result_boot_image_retry == 0) {
610 return 0;
611 }
612 }
613
614 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
615 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000616 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700617 return dexopt_result;
618 }
619
620 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000621 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700622 return Dexopt();
623 }
624
Andreas Gampe73dae112015-11-19 14:12:14 -0800625 ////////////////////////////////////
626 // Helpers, mostly taken from ART //
627 ////////////////////////////////////
628
629 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700630 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700631 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800632
633 CHECK_GE(arg_vector.size(), 1U) << command_line;
634
635 // Convert the args to char pointers.
636 const char* program = arg_vector[0].c_str();
637 std::vector<char*> args;
638 for (size_t i = 0; i < arg_vector.size(); ++i) {
639 const std::string& arg = arg_vector[i];
640 char* arg_str = const_cast<char*>(arg.c_str());
641 CHECK(arg_str != nullptr) << i;
642 args.push_back(arg_str);
643 }
644 args.push_back(nullptr);
645
646 // Fork and exec.
647 pid_t pid = fork();
648 if (pid == 0) {
649 // No allocation allowed between fork and exec.
650
651 // Change process groups, so we don't get reaped by ProcessManager.
652 setpgid(0, 0);
653
654 execv(program, &args[0]);
655
656 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
657 // _exit to avoid atexit handlers in child.
658 _exit(1);
659 } else {
660 if (pid == -1) {
661 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
662 command_line.c_str(), strerror(errno));
663 return false;
664 }
665
666 // wait for subprocess to finish
667 int status;
668 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
669 if (got_pid != pid) {
670 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
671 "wanted %d, got %d: %s",
672 command_line.c_str(), pid, got_pid, strerror(errno));
673 return false;
674 }
675 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
676 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
677 command_line.c_str());
678 return false;
679 }
680 }
681 return true;
682 }
683
684 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
685 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
686 constexpr size_t kPageSize = PAGE_SIZE;
687 CHECK_EQ(min_delta % kPageSize, 0u);
688 CHECK_EQ(max_delta % kPageSize, 0u);
689 CHECK_LT(min_delta, max_delta);
690
691 std::default_random_engine generator;
692 generator.seed(GetSeed());
693 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
694 int32_t r = distribution(generator);
695 if (r % 2 == 0) {
696 r = RoundUp(r, kPageSize);
697 } else {
698 r = RoundDown(r, kPageSize);
699 }
700 CHECK_LE(min_delta, r);
701 CHECK_GE(max_delta, r);
702 CHECK_EQ(r % kPageSize, 0u);
703 return r;
704 }
705
706 static uint64_t GetSeed() {
707#ifdef __BIONIC__
708 // Bionic exposes arc4random, use it.
709 uint64_t random_data;
710 arc4random_buf(&random_data, sizeof(random_data));
711 return random_data;
712#else
713#error "This is only supposed to run with bionic. Otherwise, implement..."
714#endif
715 }
716
717 void AddCompilerOptionFromSystemProperty(const char* system_property,
718 const char* prefix,
719 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700720 std::vector<std::string>& out) const {
721 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800722 if (value != nullptr) {
723 if (runtime) {
724 out.push_back("--runtime-arg");
725 }
726 if (prefix != nullptr) {
727 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
728 } else {
729 out.push_back(*value);
730 }
731 }
732 }
733
Andreas Gamped089ca12016-06-27 14:25:30 -0700734 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
735 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
736 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
737 // The index of the instruction-set string inside the package parameters. Needed for
738 // some special-casing that requires knowledge of the instruction-set.
739 static constexpr size_t kISAIndex = 3;
740
Andreas Gampe73dae112015-11-19 14:12:14 -0800741 // Stores the system properties read out of the B partition. We need to use these properties
742 // to compile, instead of the A properties we could get from init/get_property.
743 SystemProperties system_properties_;
744
Andreas Gamped089ca12016-06-27 14:25:30 -0700745 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700746 std::string android_root_;
747 std::string android_data_;
748 std::string boot_classpath_;
749 std::string asec_mountpoint_;
750
Calin Juravlec9e76792018-02-01 14:44:56 +0000751 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800752
753 // Store environment values we need to set.
754 std::vector<std::string> environ_;
755};
756
757OTAPreoptService gOps;
758
759////////////////////////
760// Plug-in functions. //
761////////////////////////
762
763int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800764 return gOps.GetProperty(key, value, default_value);
765}
766
767// Compute the output path of
768bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
769 const char *apk_path,
770 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700771 const char *file_name_start;
772 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800773
774 file_name_start = strrchr(apk_path, '/');
775 if (file_name_start == nullptr) {
776 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
777 return false;
778 }
779 file_name_end = strrchr(file_name_start, '.');
780 if (file_name_end == nullptr) {
781 ALOGE("apk_path '%s' has no extension\n", apk_path);
782 return false;
783 }
784
785 // Calculate file_name
786 file_name_start++; // Move past '/', is valid as file_name_end is valid.
787 size_t file_name_len = file_name_end - file_name_start;
788 std::string file_name(file_name_start, file_name_len);
789
790 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700791 snprintf(path,
792 PKG_PATH_MAX,
793 "%s/%s/%s.odex.%s",
794 oat_dir,
795 instruction_set,
796 file_name.c_str(),
797 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800798 return true;
799}
800
801/*
802 * Computes the odex file for the given apk_path and instruction_set.
803 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
804 *
805 * Returns false if it failed to determine the odex file path.
806 */
807bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
808 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800809 const char *path_end = strrchr(apk_path, '/');
810 if (path_end == nullptr) {
811 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
812 return false;
813 }
814 std::string path_component(apk_path, path_end - apk_path);
815
816 const char *name_begin = path_end + 1;
817 const char *extension_start = strrchr(name_begin, '.');
818 if (extension_start == nullptr) {
819 ALOGE("apk_path '%s' has no extension.\n", apk_path);
820 return false;
821 }
822 std::string name_component(name_begin, extension_start - name_begin);
823
Andreas Gamped089ca12016-06-27 14:25:30 -0700824 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800825 path_component.c_str(),
826 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700827 name_component.c_str(),
828 gOps.GetTargetSlot().c_str());
829 if (new_path.length() >= PKG_PATH_MAX) {
830 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
831 return false;
832 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800833 strcpy(path, new_path.c_str());
834 return true;
835}
836
837bool create_cache_path(char path[PKG_PATH_MAX],
838 const char *src,
839 const char *instruction_set) {
840 size_t srclen = strlen(src);
841
842 /* demand that we are an absolute path */
843 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
844 return false;
845 }
846
847 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
848 return false;
849 }
850
851 std::string from_src = std::string(src + 1);
852 std::replace(from_src.begin(), from_src.end(), '/', '@');
853
854 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700855 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800856 DALVIK_CACHE,
857 instruction_set,
858 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100859 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800860
861 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
862 return false;
863 }
864 strcpy(path, assembled_path.c_str());
865
866 return true;
867}
868
Andreas Gampe73dae112015-11-19 14:12:14 -0800869static int log_callback(int type, const char *fmt, ...) {
870 va_list ap;
871 int priority;
872
873 switch (type) {
874 case SELINUX_WARNING:
875 priority = ANDROID_LOG_WARN;
876 break;
877 case SELINUX_INFO:
878 priority = ANDROID_LOG_INFO;
879 break;
880 default:
881 priority = ANDROID_LOG_ERROR;
882 break;
883 }
884 va_start(ap, fmt);
885 LOG_PRI_VA(priority, "SELinux", fmt, ap);
886 va_end(ap);
887 return 0;
888}
889
890static int otapreopt_main(const int argc, char *argv[]) {
891 int selinux_enabled = (is_selinux_enabled() > 0);
892
893 setenv("ANDROID_LOG_TAGS", "*:v", 1);
894 android::base::InitLogging(argv);
895
Andreas Gampe73dae112015-11-19 14:12:14 -0800896 if (argc < 2) {
897 ALOGE("Expecting parameters");
898 exit(1);
899 }
900
901 union selinux_callback cb;
902 cb.func_log = log_callback;
903 selinux_set_callback(SELINUX_CB_LOG, cb);
904
Andreas Gampe73dae112015-11-19 14:12:14 -0800905 if (selinux_enabled && selinux_status_open(true) < 0) {
906 ALOGE("Could not open selinux status; exiting.\n");
907 exit(1);
908 }
909
910 int ret = android::installd::gOps.Main(argc, argv);
911
912 return ret;
913}
914
915} // namespace installd
916} // namespace android
917
918int main(const int argc, char *argv[]) {
919 return android::installd::otapreopt_main(argc, argv);
920}