blob: 73098f80e4c3486fdd126580e0b2888dd0baea62 [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 Gampe5709b572016-02-12 17:42:59 -0800364 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
Chris Morin77c48752018-02-13 15:44:47 -0800365 return PatchoatBootImage(isa_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800366 } else {
367 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700368 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800369 }
370 }
371
Andreas Gamped089ca12016-06-27 14:25:30 -0700372 static bool CreatePath(const std::string& path) {
373 // Create the given path. Use string processing instead of dirname, as dirname's need for
374 // a writable char buffer is painful.
375
376 // First, try to use the full path.
377 if (mkdir(path.c_str(), 0711) == 0) {
378 return true;
379 }
380 if (errno != ENOENT) {
381 PLOG(ERROR) << "Could not create path " << path;
382 return false;
383 }
384
385 // Now find the parent and try that first.
386 size_t last_slash = path.find_last_of('/');
387 if (last_slash == std::string::npos || last_slash == 0) {
388 PLOG(ERROR) << "Could not create " << path;
389 return false;
390 }
391
392 if (!CreatePath(path.substr(0, last_slash))) {
393 return false;
394 }
395
396 if (mkdir(path.c_str(), 0711) == 0) {
397 return true;
398 }
399 PLOG(ERROR) << "Could not create " << path;
400 return false;
401 }
402
403 static void ClearDirectory(const std::string& dir) {
404 DIR* c_dir = opendir(dir.c_str());
405 if (c_dir == nullptr) {
406 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
407 return;
408 }
409
410 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
411 const char* name = de->d_name;
412 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
413 continue;
414 }
415 // We only want to delete regular files and symbolic links.
416 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
417 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
418 LOG(WARNING) << "Unexpected file "
419 << file
420 << " of type "
421 << std::hex
422 << de->d_type
423 << " encountered.";
424 } else {
425 // Try to unlink the file.
426 if (unlink(file.c_str()) != 0) {
427 PLOG(ERROR) << "Unable to unlink " << file;
428 }
429 }
430 }
431 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
432 }
433
Chris Morin77c48752018-02-13 15:44:47 -0800434 bool PatchoatBootImage(const std::string& output_dir, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800435 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
436
437 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700438 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800439
440 cmd.push_back("--input-image-location=/system/framework/boot.art");
Chris Morin77c48752018-02-13 15:44:47 -0800441 cmd.push_back(StringPrintf("--output-image-directory=%s", output_dir.c_str()));
Andreas Gampe5709b572016-02-12 17:42:59 -0800442
443 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
444
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700445 int32_t base_offset = ChooseRelocationOffsetDelta(art::GetImageMinBaseAddressDelta(),
446 art::GetImageMaxBaseAddressDelta());
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800447 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800448
449 std::string error_msg;
450 bool result = Exec(cmd, &error_msg);
451 if (!result) {
452 LOG(ERROR) << "Could not generate boot image: " << error_msg;
453 }
454 return result;
455 }
456
457 bool Dex2oatBootImage(const std::string& boot_cp,
458 const std::string& art_path,
459 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700460 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800461 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
462 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700463 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800464 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700465 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800466 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
467 }
468 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
469
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700470 int32_t base_offset = ChooseRelocationOffsetDelta(art::GetImageMinBaseAddressDelta(),
471 art::GetImageMaxBaseAddressDelta());
472 cmd.push_back(StringPrintf("--base=0x%x", art::GetImageBaseAddress() + base_offset));
Andreas Gampe73dae112015-11-19 14:12:14 -0800473
474 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
475
476 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
477 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
478 "-Xms",
479 true,
480 cmd);
481 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
482 "-Xmx",
483 true,
484 cmd);
485 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
486 "--compiler-filter=",
487 false,
488 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700489 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800490 // TODO: Compiled-classes.
491 const std::string* extra_opts =
492 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
493 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700494 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800495 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
496 }
497 // TODO: Should we lower this? It's usually set close to max, because
498 // normally there's not much else going on at boot.
499 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
500 "-j",
501 false,
502 cmd);
503 AddCompilerOptionFromSystemProperty(
504 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
505 "--instruction-set-variant=",
506 false,
507 cmd);
508 AddCompilerOptionFromSystemProperty(
509 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
510 "--instruction-set-features=",
511 false,
512 cmd);
513
514 std::string error_msg;
515 bool result = Exec(cmd, &error_msg);
516 if (!result) {
517 LOG(ERROR) << "Could not generate boot image: " << error_msg;
518 }
519 return result;
520 }
521
522 static const char* ParseNull(const char* arg) {
523 return (strcmp(arg, "!") == 0) ? nullptr : arg;
524 }
525
Andreas Gamped089ca12016-06-27 14:25:30 -0700526 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700527 // There's one thing we have to be careful about: we may/will be asked to compile an app
528 // living in the system image. This may be a valid request - if the app wasn't compiled,
529 // e.g., if the system image wasn't large enough to include preopted files. However, the
530 // data we have is from the old system, so the driver (the OTA service) can't actually
531 // know. Thus, we will get requests for apps that have preopted components. To avoid
532 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
533 // simple checks:
534 //
535 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
536 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
537 //
538 // 2) If you replace the name in the apk_path with "oat," does the path exist?
539 // (=have a subdirectory for preopted files)
540 //
541 // If the answer to both is yes, skip the dexopt.
542 //
543 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
544 // be stripped), that's not true for APKs signed outside the build system (so the
545 // jar content must be exactly the same).
546
547 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000548 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700549 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000550 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700551 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800552 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700553 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700554 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700555 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700556 CHECK(EndsWith(path, "/"));
557 path = path + "oat";
558 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800559 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700560 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700561 }
562 }
563 }
564
Andreas Gamped089ca12016-06-27 14:25:30 -0700565 // Another issue is unavailability of files in the new system. If the partition
566 // layout changes, otapreopt_chroot may not know about this. Then files from that
567 // partition will not be available and fail to build. This is problematic, as
568 // this tool will wipe the OTA artifact cache and try again (for robustness after
569 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700570 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800571 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700572 return true;
573 }
574
575 return false;
576 }
577
Calin Juravlec9e76792018-02-01 14:44:56 +0000578 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800579 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700580 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800581 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000582 return dexopt(parameters_.apk_path,
583 parameters_.uid,
584 parameters_.pkgName,
585 parameters_.instruction_set,
586 parameters_.dexopt_needed,
587 parameters_.oat_dir,
588 parameters_.dexopt_flags,
589 parameters_.compiler_filter,
590 parameters_.volume_uuid,
591 parameters_.shared_libraries,
592 parameters_.se_info,
593 parameters_.downgrade,
594 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000595 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800596 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800597 parameters_.compilation_reason,
598 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800599 }
600
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700601 int RunPreopt() {
602 if (ShouldSkipPreopt()) {
603 return 0;
604 }
605
606 int dexopt_result = Dexopt();
607 if (dexopt_result == 0) {
608 return 0;
609 }
610
611 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
612 // Then regenerate and retry.
613 if (WEXITSTATUS(dexopt_result) ==
Andreas Gampece9fe7f2018-09-18 10:25:58 -0700614 static_cast<int>(::art::dex2oat::ReturnCode::kCreateRuntime)) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700615 if (!PrepareBootImage(/* force */ true)) {
616 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
617 << dexopt_result;
618 return dexopt_result;
619 }
620
621 int dexopt_result_boot_image_retry = Dexopt();
622 if (dexopt_result_boot_image_retry == 0) {
623 return 0;
624 }
625 }
626
627 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
628 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000629 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700630 return dexopt_result;
631 }
632
633 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000634 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700635 return Dexopt();
636 }
637
Andreas Gampe73dae112015-11-19 14:12:14 -0800638 ////////////////////////////////////
639 // Helpers, mostly taken from ART //
640 ////////////////////////////////////
641
642 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700643 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700644 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800645
646 CHECK_GE(arg_vector.size(), 1U) << command_line;
647
648 // Convert the args to char pointers.
649 const char* program = arg_vector[0].c_str();
650 std::vector<char*> args;
651 for (size_t i = 0; i < arg_vector.size(); ++i) {
652 const std::string& arg = arg_vector[i];
653 char* arg_str = const_cast<char*>(arg.c_str());
654 CHECK(arg_str != nullptr) << i;
655 args.push_back(arg_str);
656 }
657 args.push_back(nullptr);
658
659 // Fork and exec.
660 pid_t pid = fork();
661 if (pid == 0) {
662 // No allocation allowed between fork and exec.
663
664 // Change process groups, so we don't get reaped by ProcessManager.
665 setpgid(0, 0);
666
667 execv(program, &args[0]);
668
669 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
670 // _exit to avoid atexit handlers in child.
671 _exit(1);
672 } else {
673 if (pid == -1) {
674 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
675 command_line.c_str(), strerror(errno));
676 return false;
677 }
678
679 // wait for subprocess to finish
680 int status;
681 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
682 if (got_pid != pid) {
683 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
684 "wanted %d, got %d: %s",
685 command_line.c_str(), pid, got_pid, strerror(errno));
686 return false;
687 }
688 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
689 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
690 command_line.c_str());
691 return false;
692 }
693 }
694 return true;
695 }
696
697 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
698 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
699 constexpr size_t kPageSize = PAGE_SIZE;
700 CHECK_EQ(min_delta % kPageSize, 0u);
701 CHECK_EQ(max_delta % kPageSize, 0u);
702 CHECK_LT(min_delta, max_delta);
703
704 std::default_random_engine generator;
705 generator.seed(GetSeed());
706 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
707 int32_t r = distribution(generator);
708 if (r % 2 == 0) {
709 r = RoundUp(r, kPageSize);
710 } else {
711 r = RoundDown(r, kPageSize);
712 }
713 CHECK_LE(min_delta, r);
714 CHECK_GE(max_delta, r);
715 CHECK_EQ(r % kPageSize, 0u);
716 return r;
717 }
718
719 static uint64_t GetSeed() {
720#ifdef __BIONIC__
721 // Bionic exposes arc4random, use it.
722 uint64_t random_data;
723 arc4random_buf(&random_data, sizeof(random_data));
724 return random_data;
725#else
726#error "This is only supposed to run with bionic. Otherwise, implement..."
727#endif
728 }
729
730 void AddCompilerOptionFromSystemProperty(const char* system_property,
731 const char* prefix,
732 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700733 std::vector<std::string>& out) const {
734 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800735 if (value != nullptr) {
736 if (runtime) {
737 out.push_back("--runtime-arg");
738 }
739 if (prefix != nullptr) {
740 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
741 } else {
742 out.push_back(*value);
743 }
744 }
745 }
746
Andreas Gamped089ca12016-06-27 14:25:30 -0700747 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
748 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
749 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
750 // The index of the instruction-set string inside the package parameters. Needed for
751 // some special-casing that requires knowledge of the instruction-set.
752 static constexpr size_t kISAIndex = 3;
753
Andreas Gampe73dae112015-11-19 14:12:14 -0800754 // Stores the system properties read out of the B partition. We need to use these properties
755 // to compile, instead of the A properties we could get from init/get_property.
756 SystemProperties system_properties_;
757
Andreas Gamped089ca12016-06-27 14:25:30 -0700758 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700759 std::string android_root_;
760 std::string android_data_;
761 std::string boot_classpath_;
762 std::string asec_mountpoint_;
763
Calin Juravlec9e76792018-02-01 14:44:56 +0000764 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800765
766 // Store environment values we need to set.
767 std::vector<std::string> environ_;
768};
769
770OTAPreoptService gOps;
771
772////////////////////////
773// Plug-in functions. //
774////////////////////////
775
776int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800777 return gOps.GetProperty(key, value, default_value);
778}
779
780// Compute the output path of
781bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
782 const char *apk_path,
783 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700784 const char *file_name_start;
785 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800786
787 file_name_start = strrchr(apk_path, '/');
788 if (file_name_start == nullptr) {
789 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
790 return false;
791 }
792 file_name_end = strrchr(file_name_start, '.');
793 if (file_name_end == nullptr) {
794 ALOGE("apk_path '%s' has no extension\n", apk_path);
795 return false;
796 }
797
798 // Calculate file_name
799 file_name_start++; // Move past '/', is valid as file_name_end is valid.
800 size_t file_name_len = file_name_end - file_name_start;
801 std::string file_name(file_name_start, file_name_len);
802
803 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700804 snprintf(path,
805 PKG_PATH_MAX,
806 "%s/%s/%s.odex.%s",
807 oat_dir,
808 instruction_set,
809 file_name.c_str(),
810 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800811 return true;
812}
813
814/*
815 * Computes the odex file for the given apk_path and instruction_set.
816 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
817 *
818 * Returns false if it failed to determine the odex file path.
819 */
820bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
821 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800822 const char *path_end = strrchr(apk_path, '/');
823 if (path_end == nullptr) {
824 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
825 return false;
826 }
827 std::string path_component(apk_path, path_end - apk_path);
828
829 const char *name_begin = path_end + 1;
830 const char *extension_start = strrchr(name_begin, '.');
831 if (extension_start == nullptr) {
832 ALOGE("apk_path '%s' has no extension.\n", apk_path);
833 return false;
834 }
835 std::string name_component(name_begin, extension_start - name_begin);
836
Andreas Gamped089ca12016-06-27 14:25:30 -0700837 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800838 path_component.c_str(),
839 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700840 name_component.c_str(),
841 gOps.GetTargetSlot().c_str());
842 if (new_path.length() >= PKG_PATH_MAX) {
843 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
844 return false;
845 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800846 strcpy(path, new_path.c_str());
847 return true;
848}
849
850bool create_cache_path(char path[PKG_PATH_MAX],
851 const char *src,
852 const char *instruction_set) {
853 size_t srclen = strlen(src);
854
855 /* demand that we are an absolute path */
856 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
857 return false;
858 }
859
860 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
861 return false;
862 }
863
864 std::string from_src = std::string(src + 1);
865 std::replace(from_src.begin(), from_src.end(), '/', '@');
866
867 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700868 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800869 DALVIK_CACHE,
870 instruction_set,
871 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100872 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800873
874 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
875 return false;
876 }
877 strcpy(path, assembled_path.c_str());
878
879 return true;
880}
881
Andreas Gampe73dae112015-11-19 14:12:14 -0800882static int log_callback(int type, const char *fmt, ...) {
883 va_list ap;
884 int priority;
885
886 switch (type) {
887 case SELINUX_WARNING:
888 priority = ANDROID_LOG_WARN;
889 break;
890 case SELINUX_INFO:
891 priority = ANDROID_LOG_INFO;
892 break;
893 default:
894 priority = ANDROID_LOG_ERROR;
895 break;
896 }
897 va_start(ap, fmt);
898 LOG_PRI_VA(priority, "SELinux", fmt, ap);
899 va_end(ap);
900 return 0;
901}
902
903static int otapreopt_main(const int argc, char *argv[]) {
904 int selinux_enabled = (is_selinux_enabled() > 0);
905
906 setenv("ANDROID_LOG_TAGS", "*:v", 1);
907 android::base::InitLogging(argv);
908
Andreas Gampe73dae112015-11-19 14:12:14 -0800909 if (argc < 2) {
910 ALOGE("Expecting parameters");
911 exit(1);
912 }
913
914 union selinux_callback cb;
915 cb.func_log = log_callback;
916 selinux_set_callback(SELINUX_CB_LOG, cb);
917
Andreas Gampe73dae112015-11-19 14:12:14 -0800918 if (selinux_enabled && selinux_status_open(true) < 0) {
919 ALOGE("Could not open selinux status; exiting.\n");
920 exit(1);
921 }
922
923 int ret = android::installd::gOps.Main(argc, argv);
924
925 return ret;
926}
927
928} // namespace installd
929} // namespace android
930
931int main(const int argc, char *argv[]) {
932 return android::installd::otapreopt_main(argc, argv);
933}