blob: 28c7658d6ed6dfa5827de78d6b032b52a132455c [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 Gampece9fe7f2018-09-18 10:25:58 -070035#include <art_image_values.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080036#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080037#include <cutils/properties.h>
Andreas Gampe54e1a402017-03-20 18:42:49 -070038#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070039#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080040#include <private/android_filesystem_config.h>
41
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070042#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070043#include "file_parsing.h"
44#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070045#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070046#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000047#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070048#include "otapreopt_utils.h"
49#include "system_properties.h"
50#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070051
Andreas Gampe73dae112015-11-19 14:12:14 -080052#ifndef LOG_TAG
53#define LOG_TAG "otapreopt"
54#endif
55
56#define BUFFER_MAX 1024 /* input buffer for commands */
57#define TOKEN_MAX 16 /* max number of arguments in buffer */
58#define REPLY_MAX 256 /* largest reply allowed */
59
Andreas Gampe56f79f92016-06-08 15:11:37 -070060using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070061using android::base::Join;
62using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070063using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080064using android::base::StringPrintf;
65
66namespace android {
67namespace installd {
68
Andreas Gampeef21fd22017-05-22 13:36:06 -070069// Check expected values for dexopt flags. If you need to change this:
70//
71// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
72//
73// You most likely need to increase the protocol version and all that entails!
74
75static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
76static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
77static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
78static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
79static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
80static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
81static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
82static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080083static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
84 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Mathieu Chartier351bc942018-03-06 13:55:58 -080085static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070086static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070087
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070088static_assert(DEXOPT_MASK == (0x1dfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080089 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070090
91
Andreas Gampea64a6272018-07-10 10:43:47 -070092template<typename T>
93static constexpr bool IsPowerOfTwo(T x) {
94 static_assert(std::is_integral<T>::value, "T must be integral");
95 // TODO: assert unsigned. There is currently many uses with signed values.
96 return (x & (x - 1)) == 0;
97}
Andreas Gampeef21fd22017-05-22 13:36:06 -070098
Andreas Gampe73dae112015-11-19 14:12:14 -080099template<typename T>
100static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
101 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
102}
103
104template<typename T>
105static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
106 return RoundDown(x + n - 1, n);
107}
108
109class OTAPreoptService {
110 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800111 // Main driver. Performs the following steps.
112 //
113 // 1) Parse options (read system properties etc from B partition).
114 //
115 // 2) Read in package data.
116 //
117 // 3) Prepare environment variables.
118 //
119 // 4) Prepare(compile) boot image, if necessary.
120 //
121 // 5) Run update.
122 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700123 if (!ReadArguments(argc, argv)) {
124 LOG(ERROR) << "Failed reading command line.";
125 return 1;
126 }
127
Andreas Gampe73dae112015-11-19 14:12:14 -0800128 if (!ReadSystemProperties()) {
129 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700130 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800131 }
132
133 if (!ReadEnvironment()) {
134 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700135 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800136 }
137
Andreas Gamped089ca12016-06-27 14:25:30 -0700138 if (!CheckAndInitializeInstalldGlobals()) {
139 LOG(ERROR) << "Failed initializing globals.";
140 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800141 }
142
143 PrepareEnvironment();
144
Andreas Gamped089ca12016-06-27 14:25:30 -0700145 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800146 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700147 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800148 }
149
150 int dexopt_retcode = RunPreopt();
151
152 return dexopt_retcode;
153 }
154
Andreas Gamped089ca12016-06-27 14:25:30 -0700155 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800156 const std::string* prop_value = system_properties_.GetProperty(key);
157 if (prop_value == nullptr) {
158 if (default_value == nullptr) {
159 return 0;
160 }
161 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600162 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800163 value[kPropertyValueMax - 1] = 0;
164 return strlen(default_value);// TODO: Need to truncate?
165 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700166 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600167 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700168 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800169 }
170
Andreas Gamped089ca12016-06-27 14:25:30 -0700171 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000172 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700173 }
174
175 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000176 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700177 }
178
Andreas Gampe73dae112015-11-19 14:12:14 -0800179private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700180
Andreas Gampe73dae112015-11-19 14:12:14 -0800181 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700182 static constexpr const char* kPropertyFiles[] = {
183 "/default.prop", "/system/build.prop"
184 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800185
Andreas Gampe1842af32016-03-16 14:28:50 -0700186 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
187 if (!system_properties_.Load(kPropertyFiles[i])) {
188 return false;
189 }
190 }
191
192 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800193 }
194
195 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700196 // Parse the environment variables from init.environ.rc, which have the form
197 // export NAME VALUE
198 // For simplicity, don't respect string quotation. The values we are interested in can be
199 // encoded without them.
200 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
201 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
202 std::smatch export_match;
203 if (!std::regex_match(line, export_match, export_regex)) {
204 return true;
205 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800206
Andreas Gampe1842af32016-03-16 14:28:50 -0700207 if (export_match.size() != 3) {
208 return true;
209 }
210
211 std::string name = export_match[1].str();
212 std::string value = export_match[2].str();
213
214 system_properties_.SetProperty(name, value);
215
216 return true;
217 });
218 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800219 return false;
220 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700221
Andreas Gamped089ca12016-06-27 14:25:30 -0700222 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
223 return false;
224 }
225 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
226
227 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
228 return false;
229 }
230 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
231
232 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
233 return false;
234 }
235 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
236
237 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
238 return false;
239 }
240 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
241
242 return true;
243 }
244
245 const std::string& GetAndroidData() const {
246 return android_data_;
247 }
248
249 const std::string& GetAndroidRoot() const {
250 return android_root_;
251 }
252
253 const std::string GetOtaDirectoryPrefix() const {
254 return GetAndroidData() + "/ota";
255 }
256
257 bool CheckAndInitializeInstalldGlobals() {
258 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
259 // do not use any datapath that includes this, but we'll still have to set it.
260 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
261 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
262 if (result != 0) {
263 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
264 return false;
265 }
266
267 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
268 LOG(ERROR) << "Could not initialize globals; exiting.";
269 return false;
270 }
271
272 // This is different from the normal installd. We only do the base
273 // directory, the rest will be created on demand when each app is compiled.
274 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
275 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
276 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700277 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800278
279 return true;
280 }
281
Shubham Ajmera45c87432017-06-22 11:10:27 -0700282 bool ParseBool(const char* in) {
283 if (strcmp(in, "true") == 0) {
284 return true;
285 }
286 return false;
287 }
288
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700289 bool ParseUInt(const char* in, uint32_t* out) {
290 char* end;
291 long long int result = strtoll(in, &end, 0);
292 if (in == end || *end != '\0') {
293 return false;
294 }
295 if (result < std::numeric_limits<uint32_t>::min() ||
296 std::numeric_limits<uint32_t>::max() < result) {
297 return false;
298 }
299 *out = static_cast<uint32_t>(result);
300 return true;
301 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700302
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700303 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000304 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800305 }
306
307 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700308 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
309 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
310 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800311
312 for (const std::string& e : environ_) {
313 putenv(const_cast<char*>(e.c_str()));
314 }
315 }
316
317 // Ensure that we have the right boot image. The first time any app is
318 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700319 bool PrepareBootImage(bool force) const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000320 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800321 LOG(ERROR) << "Instruction set missing.";
322 return false;
323 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000324 const char* isa = parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800325
326 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700327 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800328 std::string isa_path = dalvik_cache + "/" + isa;
329 std::string art_path = isa_path + "/system@framework@boot.art";
330 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700331 bool cleared = false;
332 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
333 // Files exist, assume everything is alright if not forced. Otherwise clean up.
334 if (!force) {
335 return true;
336 }
337 ClearDirectory(isa_path);
338 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800339 }
340
Andreas Gamped089ca12016-06-27 14:25:30 -0700341 // Reset umask in otapreopt, so that we control the the access for the files we create.
342 umask(0);
343
Andreas Gampe73dae112015-11-19 14:12:14 -0800344 // Create the directories, if necessary.
345 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700346 if (!CreatePath(dalvik_cache)) {
347 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800348 return false;
349 }
350 }
351 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700352 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800353 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
354 return false;
355 }
356 }
357
Andreas Gampe5709b572016-02-12 17:42:59 -0800358 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700359 if (!cleared) {
360 ClearDirectory(isa_path);
361 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800362
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700363 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe3ad80d22018-10-03 11:27:09 -0700364 if (access(preopted_boot_art_path.c_str(), F_OK) != 0) {
Andreas Gampe5709b572016-02-12 17:42:59 -0800365 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700366 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800367 }
Andreas Gampe3ad80d22018-10-03 11:27:09 -0700368 return true;
Andreas Gampe5709b572016-02-12 17:42:59 -0800369 }
370
Andreas Gamped089ca12016-06-27 14:25:30 -0700371 static bool CreatePath(const std::string& path) {
372 // Create the given path. Use string processing instead of dirname, as dirname's need for
373 // a writable char buffer is painful.
374
375 // First, try to use the full path.
376 if (mkdir(path.c_str(), 0711) == 0) {
377 return true;
378 }
379 if (errno != ENOENT) {
380 PLOG(ERROR) << "Could not create path " << path;
381 return false;
382 }
383
384 // Now find the parent and try that first.
385 size_t last_slash = path.find_last_of('/');
386 if (last_slash == std::string::npos || last_slash == 0) {
387 PLOG(ERROR) << "Could not create " << path;
388 return false;
389 }
390
391 if (!CreatePath(path.substr(0, last_slash))) {
392 return false;
393 }
394
395 if (mkdir(path.c_str(), 0711) == 0) {
396 return true;
397 }
398 PLOG(ERROR) << "Could not create " << path;
399 return false;
400 }
401
402 static void ClearDirectory(const std::string& dir) {
403 DIR* c_dir = opendir(dir.c_str());
404 if (c_dir == nullptr) {
405 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
406 return;
407 }
408
409 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
410 const char* name = de->d_name;
411 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
412 continue;
413 }
414 // We only want to delete regular files and symbolic links.
415 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
416 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
417 LOG(WARNING) << "Unexpected file "
418 << file
419 << " of type "
420 << std::hex
421 << de->d_type
422 << " encountered.";
423 } else {
424 // Try to unlink the file.
425 if (unlink(file.c_str()) != 0) {
426 PLOG(ERROR) << "Unable to unlink " << file;
427 }
428 }
429 }
430 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
431 }
432
Andreas Gampe5709b572016-02-12 17:42:59 -0800433 bool Dex2oatBootImage(const std::string& boot_cp,
434 const std::string& art_path,
435 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700436 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800437 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
438 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700439 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800440 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700441 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800442 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
443 }
444 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
445
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700446 int32_t base_offset = ChooseRelocationOffsetDelta(art::GetImageMinBaseAddressDelta(),
447 art::GetImageMaxBaseAddressDelta());
448 cmd.push_back(StringPrintf("--base=0x%x", art::GetImageBaseAddress() + base_offset));
Andreas Gampe73dae112015-11-19 14:12:14 -0800449
450 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
451
452 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
453 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
454 "-Xms",
455 true,
456 cmd);
457 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
458 "-Xmx",
459 true,
460 cmd);
461 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
462 "--compiler-filter=",
463 false,
464 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700465 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800466 // TODO: Compiled-classes.
467 const std::string* extra_opts =
468 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
469 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700470 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800471 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
472 }
473 // TODO: Should we lower this? It's usually set close to max, because
474 // normally there's not much else going on at boot.
475 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
476 "-j",
477 false,
478 cmd);
479 AddCompilerOptionFromSystemProperty(
480 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
481 "--instruction-set-variant=",
482 false,
483 cmd);
484 AddCompilerOptionFromSystemProperty(
485 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
486 "--instruction-set-features=",
487 false,
488 cmd);
489
490 std::string error_msg;
491 bool result = Exec(cmd, &error_msg);
492 if (!result) {
493 LOG(ERROR) << "Could not generate boot image: " << error_msg;
494 }
495 return result;
496 }
497
498 static const char* ParseNull(const char* arg) {
499 return (strcmp(arg, "!") == 0) ? nullptr : arg;
500 }
501
Andreas Gamped089ca12016-06-27 14:25:30 -0700502 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700503 // There's one thing we have to be careful about: we may/will be asked to compile an app
504 // living in the system image. This may be a valid request - if the app wasn't compiled,
505 // e.g., if the system image wasn't large enough to include preopted files. However, the
506 // data we have is from the old system, so the driver (the OTA service) can't actually
507 // know. Thus, we will get requests for apps that have preopted components. To avoid
508 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
509 // simple checks:
510 //
511 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
512 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
513 //
514 // 2) If you replace the name in the apk_path with "oat," does the path exist?
515 // (=have a subdirectory for preopted files)
516 //
517 // If the answer to both is yes, skip the dexopt.
518 //
519 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
520 // be stripped), that's not true for APKs signed outside the build system (so the
521 // jar content must be exactly the same).
522
523 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000524 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700525 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000526 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700527 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800528 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700529 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700530 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700531 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700532 CHECK(EndsWith(path, "/"));
533 path = path + "oat";
534 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800535 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700536 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700537 }
538 }
539 }
540
Andreas Gamped089ca12016-06-27 14:25:30 -0700541 // Another issue is unavailability of files in the new system. If the partition
542 // layout changes, otapreopt_chroot may not know about this. Then files from that
543 // partition will not be available and fail to build. This is problematic, as
544 // this tool will wipe the OTA artifact cache and try again (for robustness after
545 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700546 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800547 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700548 return true;
549 }
550
551 return false;
552 }
553
Calin Juravlec9e76792018-02-01 14:44:56 +0000554 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800555 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700556 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800557 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000558 return dexopt(parameters_.apk_path,
559 parameters_.uid,
560 parameters_.pkgName,
561 parameters_.instruction_set,
562 parameters_.dexopt_needed,
563 parameters_.oat_dir,
564 parameters_.dexopt_flags,
565 parameters_.compiler_filter,
566 parameters_.volume_uuid,
567 parameters_.shared_libraries,
568 parameters_.se_info,
569 parameters_.downgrade,
570 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000571 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800572 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800573 parameters_.compilation_reason,
574 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800575 }
576
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700577 int RunPreopt() {
578 if (ShouldSkipPreopt()) {
579 return 0;
580 }
581
582 int dexopt_result = Dexopt();
583 if (dexopt_result == 0) {
584 return 0;
585 }
586
587 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
588 // Then regenerate and retry.
589 if (WEXITSTATUS(dexopt_result) ==
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700590 static_cast<int>(::art::dex2oat::ReturnCode::kCreateRuntime)) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700591 if (!PrepareBootImage(/* force */ true)) {
592 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
593 << dexopt_result;
594 return dexopt_result;
595 }
596
597 int dexopt_result_boot_image_retry = Dexopt();
598 if (dexopt_result_boot_image_retry == 0) {
599 return 0;
600 }
601 }
602
603 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
604 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000605 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700606 return dexopt_result;
607 }
608
609 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000610 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700611 return Dexopt();
612 }
613
Andreas Gampe73dae112015-11-19 14:12:14 -0800614 ////////////////////////////////////
615 // Helpers, mostly taken from ART //
616 ////////////////////////////////////
617
618 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700619 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700620 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800621
622 CHECK_GE(arg_vector.size(), 1U) << command_line;
623
624 // Convert the args to char pointers.
625 const char* program = arg_vector[0].c_str();
626 std::vector<char*> args;
627 for (size_t i = 0; i < arg_vector.size(); ++i) {
628 const std::string& arg = arg_vector[i];
629 char* arg_str = const_cast<char*>(arg.c_str());
630 CHECK(arg_str != nullptr) << i;
631 args.push_back(arg_str);
632 }
633 args.push_back(nullptr);
634
635 // Fork and exec.
636 pid_t pid = fork();
637 if (pid == 0) {
638 // No allocation allowed between fork and exec.
639
640 // Change process groups, so we don't get reaped by ProcessManager.
641 setpgid(0, 0);
642
643 execv(program, &args[0]);
644
645 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
646 // _exit to avoid atexit handlers in child.
647 _exit(1);
648 } else {
649 if (pid == -1) {
650 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
651 command_line.c_str(), strerror(errno));
652 return false;
653 }
654
655 // wait for subprocess to finish
656 int status;
657 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
658 if (got_pid != pid) {
659 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
660 "wanted %d, got %d: %s",
661 command_line.c_str(), pid, got_pid, strerror(errno));
662 return false;
663 }
664 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
665 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
666 command_line.c_str());
667 return false;
668 }
669 }
670 return true;
671 }
672
673 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
674 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
675 constexpr size_t kPageSize = PAGE_SIZE;
676 CHECK_EQ(min_delta % kPageSize, 0u);
677 CHECK_EQ(max_delta % kPageSize, 0u);
678 CHECK_LT(min_delta, max_delta);
679
680 std::default_random_engine generator;
681 generator.seed(GetSeed());
682 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
683 int32_t r = distribution(generator);
684 if (r % 2 == 0) {
685 r = RoundUp(r, kPageSize);
686 } else {
687 r = RoundDown(r, kPageSize);
688 }
689 CHECK_LE(min_delta, r);
690 CHECK_GE(max_delta, r);
691 CHECK_EQ(r % kPageSize, 0u);
692 return r;
693 }
694
695 static uint64_t GetSeed() {
696#ifdef __BIONIC__
697 // Bionic exposes arc4random, use it.
698 uint64_t random_data;
699 arc4random_buf(&random_data, sizeof(random_data));
700 return random_data;
701#else
702#error "This is only supposed to run with bionic. Otherwise, implement..."
703#endif
704 }
705
706 void AddCompilerOptionFromSystemProperty(const char* system_property,
707 const char* prefix,
708 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700709 std::vector<std::string>& out) const {
710 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800711 if (value != nullptr) {
712 if (runtime) {
713 out.push_back("--runtime-arg");
714 }
715 if (prefix != nullptr) {
716 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
717 } else {
718 out.push_back(*value);
719 }
720 }
721 }
722
Andreas Gamped089ca12016-06-27 14:25:30 -0700723 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
724 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
725 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
726 // The index of the instruction-set string inside the package parameters. Needed for
727 // some special-casing that requires knowledge of the instruction-set.
728 static constexpr size_t kISAIndex = 3;
729
Andreas Gampe73dae112015-11-19 14:12:14 -0800730 // Stores the system properties read out of the B partition. We need to use these properties
731 // to compile, instead of the A properties we could get from init/get_property.
732 SystemProperties system_properties_;
733
Andreas Gamped089ca12016-06-27 14:25:30 -0700734 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700735 std::string android_root_;
736 std::string android_data_;
737 std::string boot_classpath_;
738 std::string asec_mountpoint_;
739
Calin Juravlec9e76792018-02-01 14:44:56 +0000740 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800741
742 // Store environment values we need to set.
743 std::vector<std::string> environ_;
744};
745
746OTAPreoptService gOps;
747
748////////////////////////
749// Plug-in functions. //
750////////////////////////
751
752int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800753 return gOps.GetProperty(key, value, default_value);
754}
755
756// Compute the output path of
757bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
758 const char *apk_path,
759 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700760 const char *file_name_start;
761 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800762
763 file_name_start = strrchr(apk_path, '/');
764 if (file_name_start == nullptr) {
765 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
766 return false;
767 }
768 file_name_end = strrchr(file_name_start, '.');
769 if (file_name_end == nullptr) {
770 ALOGE("apk_path '%s' has no extension\n", apk_path);
771 return false;
772 }
773
774 // Calculate file_name
775 file_name_start++; // Move past '/', is valid as file_name_end is valid.
776 size_t file_name_len = file_name_end - file_name_start;
777 std::string file_name(file_name_start, file_name_len);
778
779 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700780 snprintf(path,
781 PKG_PATH_MAX,
782 "%s/%s/%s.odex.%s",
783 oat_dir,
784 instruction_set,
785 file_name.c_str(),
786 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800787 return true;
788}
789
790/*
791 * Computes the odex file for the given apk_path and instruction_set.
792 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
793 *
794 * Returns false if it failed to determine the odex file path.
795 */
796bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
797 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800798 const char *path_end = strrchr(apk_path, '/');
799 if (path_end == nullptr) {
800 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
801 return false;
802 }
803 std::string path_component(apk_path, path_end - apk_path);
804
805 const char *name_begin = path_end + 1;
806 const char *extension_start = strrchr(name_begin, '.');
807 if (extension_start == nullptr) {
808 ALOGE("apk_path '%s' has no extension.\n", apk_path);
809 return false;
810 }
811 std::string name_component(name_begin, extension_start - name_begin);
812
Andreas Gamped089ca12016-06-27 14:25:30 -0700813 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800814 path_component.c_str(),
815 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700816 name_component.c_str(),
817 gOps.GetTargetSlot().c_str());
818 if (new_path.length() >= PKG_PATH_MAX) {
819 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
820 return false;
821 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800822 strcpy(path, new_path.c_str());
823 return true;
824}
825
826bool create_cache_path(char path[PKG_PATH_MAX],
827 const char *src,
828 const char *instruction_set) {
829 size_t srclen = strlen(src);
830
831 /* demand that we are an absolute path */
832 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
833 return false;
834 }
835
836 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
837 return false;
838 }
839
840 std::string from_src = std::string(src + 1);
841 std::replace(from_src.begin(), from_src.end(), '/', '@');
842
843 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700844 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800845 DALVIK_CACHE,
846 instruction_set,
847 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100848 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800849
850 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
851 return false;
852 }
853 strcpy(path, assembled_path.c_str());
854
855 return true;
856}
857
Andreas Gampe73dae112015-11-19 14:12:14 -0800858static int log_callback(int type, const char *fmt, ...) {
859 va_list ap;
860 int priority;
861
862 switch (type) {
863 case SELINUX_WARNING:
864 priority = ANDROID_LOG_WARN;
865 break;
866 case SELINUX_INFO:
867 priority = ANDROID_LOG_INFO;
868 break;
869 default:
870 priority = ANDROID_LOG_ERROR;
871 break;
872 }
873 va_start(ap, fmt);
874 LOG_PRI_VA(priority, "SELinux", fmt, ap);
875 va_end(ap);
876 return 0;
877}
878
879static int otapreopt_main(const int argc, char *argv[]) {
880 int selinux_enabled = (is_selinux_enabled() > 0);
881
882 setenv("ANDROID_LOG_TAGS", "*:v", 1);
883 android::base::InitLogging(argv);
884
Andreas Gampe73dae112015-11-19 14:12:14 -0800885 if (argc < 2) {
886 ALOGE("Expecting parameters");
887 exit(1);
888 }
889
890 union selinux_callback cb;
891 cb.func_log = log_callback;
892 selinux_set_callback(SELINUX_CB_LOG, cb);
893
Andreas Gampe73dae112015-11-19 14:12:14 -0800894 if (selinux_enabled && selinux_status_open(true) < 0) {
895 ALOGE("Could not open selinux status; exiting.\n");
896 exit(1);
897 }
898
899 int ret = android::installd::gOps.Main(argc, argv);
900
901 return ret;
902}
903
904} // namespace installd
905} // namespace android
906
907int main(const int argc, char *argv[]) {
908 return android::installd::otapreopt_main(argc, argv);
909}