blob: b2e7047a6543b4b7b358ae538386a2358bed80b0 [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 Gamped089ca12016-06-27 14:25:30 -0700325 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800326 std::string isa_path = dalvik_cache + "/" + isa;
Andreas Gampe73dae112015-11-19 14:12:14 -0800327
Andreas Gamped089ca12016-06-27 14:25:30 -0700328 // Reset umask in otapreopt, so that we control the the access for the files we create.
329 umask(0);
330
Andreas Gampe73dae112015-11-19 14:12:14 -0800331 // Create the directories, if necessary.
332 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700333 if (!CreatePath(dalvik_cache)) {
334 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800335 return false;
336 }
337 }
338 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700339 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800340 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
341 return false;
342 }
343 }
344
Andreas Gampebd7aef12018-10-23 13:58:44 -0700345 // Check whether we have files in /data.
346 // TODO: check that the files are correct wrt/ jars.
347 std::string art_path = isa_path + "/system@framework@boot.art";
348 std::string oat_path = isa_path + "/system@framework@boot.oat";
349 bool cleared = false;
350 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
351 // Files exist, assume everything is alright if not forced. Otherwise clean up.
352 if (!force) {
353 return true;
354 }
355 ClearDirectory(isa_path);
356 cleared = true;
357 }
358
359 // Check whether we have an image in /system.
360 // TODO: check that the files are correct wrt/ jars.
361 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
362 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
363 // Note: we ignore |force| here.
364 return true;
365 }
366
367
Andreas Gamped089ca12016-06-27 14:25:30 -0700368 if (!cleared) {
369 ClearDirectory(isa_path);
370 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800371
Andreas Gampebd7aef12018-10-23 13:58:44 -0700372 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800373 }
374
Andreas Gamped089ca12016-06-27 14:25:30 -0700375 static bool CreatePath(const std::string& path) {
376 // Create the given path. Use string processing instead of dirname, as dirname's need for
377 // a writable char buffer is painful.
378
379 // First, try to use the full path.
380 if (mkdir(path.c_str(), 0711) == 0) {
381 return true;
382 }
383 if (errno != ENOENT) {
384 PLOG(ERROR) << "Could not create path " << path;
385 return false;
386 }
387
388 // Now find the parent and try that first.
389 size_t last_slash = path.find_last_of('/');
390 if (last_slash == std::string::npos || last_slash == 0) {
391 PLOG(ERROR) << "Could not create " << path;
392 return false;
393 }
394
395 if (!CreatePath(path.substr(0, last_slash))) {
396 return false;
397 }
398
399 if (mkdir(path.c_str(), 0711) == 0) {
400 return true;
401 }
402 PLOG(ERROR) << "Could not create " << path;
403 return false;
404 }
405
406 static void ClearDirectory(const std::string& dir) {
407 DIR* c_dir = opendir(dir.c_str());
408 if (c_dir == nullptr) {
409 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
410 return;
411 }
412
413 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
414 const char* name = de->d_name;
415 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
416 continue;
417 }
418 // We only want to delete regular files and symbolic links.
419 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
420 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
421 LOG(WARNING) << "Unexpected file "
422 << file
423 << " of type "
424 << std::hex
425 << de->d_type
426 << " encountered.";
427 } else {
428 // Try to unlink the file.
429 if (unlink(file.c_str()) != 0) {
430 PLOG(ERROR) << "Unable to unlink " << file;
431 }
432 }
433 }
434 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
435 }
436
Andreas Gampe5709b572016-02-12 17:42:59 -0800437 bool Dex2oatBootImage(const std::string& boot_cp,
438 const std::string& art_path,
439 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700440 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800441 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
442 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700443 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800444 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700445 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800446 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
447 }
448 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
449
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700450 int32_t base_offset = ChooseRelocationOffsetDelta(art::GetImageMinBaseAddressDelta(),
451 art::GetImageMaxBaseAddressDelta());
452 cmd.push_back(StringPrintf("--base=0x%x", art::GetImageBaseAddress() + base_offset));
Andreas Gampe73dae112015-11-19 14:12:14 -0800453
454 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
455
456 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
457 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
458 "-Xms",
459 true,
460 cmd);
461 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
462 "-Xmx",
463 true,
464 cmd);
465 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
466 "--compiler-filter=",
467 false,
468 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700469 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800470 // TODO: Compiled-classes.
471 const std::string* extra_opts =
472 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
473 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700474 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800475 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
476 }
477 // TODO: Should we lower this? It's usually set close to max, because
478 // normally there's not much else going on at boot.
479 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
480 "-j",
481 false,
482 cmd);
483 AddCompilerOptionFromSystemProperty(
484 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
485 "--instruction-set-variant=",
486 false,
487 cmd);
488 AddCompilerOptionFromSystemProperty(
489 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
490 "--instruction-set-features=",
491 false,
492 cmd);
493
494 std::string error_msg;
495 bool result = Exec(cmd, &error_msg);
496 if (!result) {
497 LOG(ERROR) << "Could not generate boot image: " << error_msg;
498 }
499 return result;
500 }
501
502 static const char* ParseNull(const char* arg) {
503 return (strcmp(arg, "!") == 0) ? nullptr : arg;
504 }
505
Andreas Gamped089ca12016-06-27 14:25:30 -0700506 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700507 // There's one thing we have to be careful about: we may/will be asked to compile an app
508 // living in the system image. This may be a valid request - if the app wasn't compiled,
509 // e.g., if the system image wasn't large enough to include preopted files. However, the
510 // data we have is from the old system, so the driver (the OTA service) can't actually
511 // know. Thus, we will get requests for apps that have preopted components. To avoid
512 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
513 // simple checks:
514 //
515 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
516 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
517 //
518 // 2) If you replace the name in the apk_path with "oat," does the path exist?
519 // (=have a subdirectory for preopted files)
520 //
521 // If the answer to both is yes, skip the dexopt.
522 //
523 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
524 // be stripped), that's not true for APKs signed outside the build system (so the
525 // jar content must be exactly the same).
526
527 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000528 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700529 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000530 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700531 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800532 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700533 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700534 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700535 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700536 CHECK(EndsWith(path, "/"));
537 path = path + "oat";
538 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800539 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700540 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700541 }
542 }
543 }
544
Andreas Gamped089ca12016-06-27 14:25:30 -0700545 // Another issue is unavailability of files in the new system. If the partition
546 // layout changes, otapreopt_chroot may not know about this. Then files from that
547 // partition will not be available and fail to build. This is problematic, as
548 // this tool will wipe the OTA artifact cache and try again (for robustness after
549 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700550 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800551 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700552 return true;
553 }
554
555 return false;
556 }
557
Calin Juravlec9e76792018-02-01 14:44:56 +0000558 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800559 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700560 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800561 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000562 return dexopt(parameters_.apk_path,
563 parameters_.uid,
564 parameters_.pkgName,
565 parameters_.instruction_set,
566 parameters_.dexopt_needed,
567 parameters_.oat_dir,
568 parameters_.dexopt_flags,
569 parameters_.compiler_filter,
570 parameters_.volume_uuid,
571 parameters_.shared_libraries,
572 parameters_.se_info,
573 parameters_.downgrade,
574 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000575 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800576 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800577 parameters_.compilation_reason,
578 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800579 }
580
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700581 int RunPreopt() {
582 if (ShouldSkipPreopt()) {
583 return 0;
584 }
585
586 int dexopt_result = Dexopt();
587 if (dexopt_result == 0) {
588 return 0;
589 }
590
591 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
592 // Then regenerate and retry.
593 if (WEXITSTATUS(dexopt_result) ==
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700594 static_cast<int>(::art::dex2oat::ReturnCode::kCreateRuntime)) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700595 if (!PrepareBootImage(/* force */ true)) {
596 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
597 << dexopt_result;
598 return dexopt_result;
599 }
600
601 int dexopt_result_boot_image_retry = Dexopt();
602 if (dexopt_result_boot_image_retry == 0) {
603 return 0;
604 }
605 }
606
607 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
608 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000609 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700610 return dexopt_result;
611 }
612
613 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000614 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700615 return Dexopt();
616 }
617
Andreas Gampe73dae112015-11-19 14:12:14 -0800618 ////////////////////////////////////
619 // Helpers, mostly taken from ART //
620 ////////////////////////////////////
621
622 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700623 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700624 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800625
626 CHECK_GE(arg_vector.size(), 1U) << command_line;
627
628 // Convert the args to char pointers.
629 const char* program = arg_vector[0].c_str();
630 std::vector<char*> args;
631 for (size_t i = 0; i < arg_vector.size(); ++i) {
632 const std::string& arg = arg_vector[i];
633 char* arg_str = const_cast<char*>(arg.c_str());
634 CHECK(arg_str != nullptr) << i;
635 args.push_back(arg_str);
636 }
637 args.push_back(nullptr);
638
639 // Fork and exec.
640 pid_t pid = fork();
641 if (pid == 0) {
642 // No allocation allowed between fork and exec.
643
644 // Change process groups, so we don't get reaped by ProcessManager.
645 setpgid(0, 0);
646
647 execv(program, &args[0]);
648
649 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
650 // _exit to avoid atexit handlers in child.
651 _exit(1);
652 } else {
653 if (pid == -1) {
654 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
655 command_line.c_str(), strerror(errno));
656 return false;
657 }
658
659 // wait for subprocess to finish
660 int status;
661 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
662 if (got_pid != pid) {
663 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
664 "wanted %d, got %d: %s",
665 command_line.c_str(), pid, got_pid, strerror(errno));
666 return false;
667 }
668 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
669 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
670 command_line.c_str());
671 return false;
672 }
673 }
674 return true;
675 }
676
677 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
678 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
679 constexpr size_t kPageSize = PAGE_SIZE;
680 CHECK_EQ(min_delta % kPageSize, 0u);
681 CHECK_EQ(max_delta % kPageSize, 0u);
682 CHECK_LT(min_delta, max_delta);
683
684 std::default_random_engine generator;
685 generator.seed(GetSeed());
686 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
687 int32_t r = distribution(generator);
688 if (r % 2 == 0) {
689 r = RoundUp(r, kPageSize);
690 } else {
691 r = RoundDown(r, kPageSize);
692 }
693 CHECK_LE(min_delta, r);
694 CHECK_GE(max_delta, r);
695 CHECK_EQ(r % kPageSize, 0u);
696 return r;
697 }
698
699 static uint64_t GetSeed() {
700#ifdef __BIONIC__
701 // Bionic exposes arc4random, use it.
702 uint64_t random_data;
703 arc4random_buf(&random_data, sizeof(random_data));
704 return random_data;
705#else
706#error "This is only supposed to run with bionic. Otherwise, implement..."
707#endif
708 }
709
710 void AddCompilerOptionFromSystemProperty(const char* system_property,
711 const char* prefix,
712 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700713 std::vector<std::string>& out) const {
714 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800715 if (value != nullptr) {
716 if (runtime) {
717 out.push_back("--runtime-arg");
718 }
719 if (prefix != nullptr) {
720 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
721 } else {
722 out.push_back(*value);
723 }
724 }
725 }
726
Andreas Gamped089ca12016-06-27 14:25:30 -0700727 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
728 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
729 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
730 // The index of the instruction-set string inside the package parameters. Needed for
731 // some special-casing that requires knowledge of the instruction-set.
732 static constexpr size_t kISAIndex = 3;
733
Andreas Gampe73dae112015-11-19 14:12:14 -0800734 // Stores the system properties read out of the B partition. We need to use these properties
735 // to compile, instead of the A properties we could get from init/get_property.
736 SystemProperties system_properties_;
737
Andreas Gamped089ca12016-06-27 14:25:30 -0700738 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700739 std::string android_root_;
740 std::string android_data_;
741 std::string boot_classpath_;
742 std::string asec_mountpoint_;
743
Calin Juravlec9e76792018-02-01 14:44:56 +0000744 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800745
746 // Store environment values we need to set.
747 std::vector<std::string> environ_;
748};
749
750OTAPreoptService gOps;
751
752////////////////////////
753// Plug-in functions. //
754////////////////////////
755
756int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800757 return gOps.GetProperty(key, value, default_value);
758}
759
760// Compute the output path of
761bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
762 const char *apk_path,
763 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700764 const char *file_name_start;
765 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800766
767 file_name_start = strrchr(apk_path, '/');
768 if (file_name_start == nullptr) {
769 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
770 return false;
771 }
772 file_name_end = strrchr(file_name_start, '.');
773 if (file_name_end == nullptr) {
774 ALOGE("apk_path '%s' has no extension\n", apk_path);
775 return false;
776 }
777
778 // Calculate file_name
779 file_name_start++; // Move past '/', is valid as file_name_end is valid.
780 size_t file_name_len = file_name_end - file_name_start;
781 std::string file_name(file_name_start, file_name_len);
782
783 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700784 snprintf(path,
785 PKG_PATH_MAX,
786 "%s/%s/%s.odex.%s",
787 oat_dir,
788 instruction_set,
789 file_name.c_str(),
790 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800791 return true;
792}
793
794/*
795 * Computes the odex file for the given apk_path and instruction_set.
796 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
797 *
798 * Returns false if it failed to determine the odex file path.
799 */
800bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
801 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800802 const char *path_end = strrchr(apk_path, '/');
803 if (path_end == nullptr) {
804 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
805 return false;
806 }
807 std::string path_component(apk_path, path_end - apk_path);
808
809 const char *name_begin = path_end + 1;
810 const char *extension_start = strrchr(name_begin, '.');
811 if (extension_start == nullptr) {
812 ALOGE("apk_path '%s' has no extension.\n", apk_path);
813 return false;
814 }
815 std::string name_component(name_begin, extension_start - name_begin);
816
Andreas Gamped089ca12016-06-27 14:25:30 -0700817 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800818 path_component.c_str(),
819 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700820 name_component.c_str(),
821 gOps.GetTargetSlot().c_str());
822 if (new_path.length() >= PKG_PATH_MAX) {
823 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
824 return false;
825 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800826 strcpy(path, new_path.c_str());
827 return true;
828}
829
830bool create_cache_path(char path[PKG_PATH_MAX],
831 const char *src,
832 const char *instruction_set) {
833 size_t srclen = strlen(src);
834
835 /* demand that we are an absolute path */
836 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
837 return false;
838 }
839
840 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
841 return false;
842 }
843
844 std::string from_src = std::string(src + 1);
845 std::replace(from_src.begin(), from_src.end(), '/', '@');
846
847 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700848 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800849 DALVIK_CACHE,
850 instruction_set,
851 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100852 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800853
854 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
855 return false;
856 }
857 strcpy(path, assembled_path.c_str());
858
859 return true;
860}
861
Andreas Gampe73dae112015-11-19 14:12:14 -0800862static int log_callback(int type, const char *fmt, ...) {
863 va_list ap;
864 int priority;
865
866 switch (type) {
867 case SELINUX_WARNING:
868 priority = ANDROID_LOG_WARN;
869 break;
870 case SELINUX_INFO:
871 priority = ANDROID_LOG_INFO;
872 break;
873 default:
874 priority = ANDROID_LOG_ERROR;
875 break;
876 }
877 va_start(ap, fmt);
878 LOG_PRI_VA(priority, "SELinux", fmt, ap);
879 va_end(ap);
880 return 0;
881}
882
883static int otapreopt_main(const int argc, char *argv[]) {
884 int selinux_enabled = (is_selinux_enabled() > 0);
885
886 setenv("ANDROID_LOG_TAGS", "*:v", 1);
887 android::base::InitLogging(argv);
888
Andreas Gampe73dae112015-11-19 14:12:14 -0800889 if (argc < 2) {
890 ALOGE("Expecting parameters");
891 exit(1);
892 }
893
894 union selinux_callback cb;
895 cb.func_log = log_callback;
896 selinux_set_callback(SELINUX_CB_LOG, cb);
897
Andreas Gampe73dae112015-11-19 14:12:14 -0800898 if (selinux_enabled && selinux_status_open(true) < 0) {
899 ALOGE("Could not open selinux status; exiting.\n");
900 exit(1);
901 }
902
903 int ret = android::installd::gOps.Main(argc, argv);
904
905 return ret;
906}
907
908} // namespace installd
909} // namespace android
910
911int main(const int argc, char *argv[]) {
912 return android::installd::otapreopt_main(argc, argv);
913}