blob: 58355f9db0bba7a33489c685a750f6b84e726f90 [file] [log] [blame]
Andreas Gampe73dae112015-11-19 14:12:14 -08001/*
2 ** Copyright 2016, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17#include <algorithm>
18#include <inttypes.h>
Andreas Gampec4ced4f2017-04-14 20:39:56 -070019#include <limits>
Andreas Gampe73dae112015-11-19 14:12:14 -080020#include <random>
Andreas Gampe1842af32016-03-16 14:28:50 -070021#include <regex>
Andreas Gampe73dae112015-11-19 14:12:14 -080022#include <selinux/android.h>
23#include <selinux/avc.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/capability.h>
27#include <sys/prctl.h>
28#include <sys/stat.h>
29#include <sys/wait.h>
30
31#include <android-base/logging.h>
32#include <android-base/macros.h>
33#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070034#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080035#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080036#include <cutils/properties.h>
Andreas Gampe54e1a402017-03-20 18:42:49 -070037#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080039#include <private/android_filesystem_config.h>
40
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070041#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070042#include "file_parsing.h"
43#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070044#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070045#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000046#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070047#include "otapreopt_utils.h"
48#include "system_properties.h"
49#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
Andreas Gampe73dae112015-11-19 14:12:14 -080051#ifndef LOG_TAG
52#define LOG_TAG "otapreopt"
53#endif
54
55#define BUFFER_MAX 1024 /* input buffer for commands */
56#define TOKEN_MAX 16 /* max number of arguments in buffer */
57#define REPLY_MAX 256 /* largest reply allowed */
58
Andreas Gampe56f79f92016-06-08 15:11:37 -070059using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070060using android::base::Join;
61using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070062using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080063using android::base::StringPrintf;
64
65namespace android {
66namespace installd {
67
Andreas Gampeef21fd22017-05-22 13:36:06 -070068// Check expected values for dexopt flags. If you need to change this:
69//
70// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
71//
72// You most likely need to increase the protocol version and all that entails!
73
74static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
75static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
76static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
77static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
78static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
79static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
80static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
81static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080082static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
83 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Mathieu Chartier351bc942018-03-06 13:55:58 -080084static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070085
Mathieu Chartier351bc942018-03-06 13:55:58 -080086static_assert(DEXOPT_MASK == (0xdfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080087 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070088
89
90
Andreas Gampe73dae112015-11-19 14:12:14 -080091template<typename T>
92static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
93 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
94}
95
96template<typename T>
97static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
98 return RoundDown(x + n - 1, n);
99}
100
101class OTAPreoptService {
102 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800103 // Main driver. Performs the following steps.
104 //
105 // 1) Parse options (read system properties etc from B partition).
106 //
107 // 2) Read in package data.
108 //
109 // 3) Prepare environment variables.
110 //
111 // 4) Prepare(compile) boot image, if necessary.
112 //
113 // 5) Run update.
114 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700115 if (!ReadArguments(argc, argv)) {
116 LOG(ERROR) << "Failed reading command line.";
117 return 1;
118 }
119
Andreas Gampe73dae112015-11-19 14:12:14 -0800120 if (!ReadSystemProperties()) {
121 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700122 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800123 }
124
125 if (!ReadEnvironment()) {
126 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700127 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800128 }
129
Andreas Gamped089ca12016-06-27 14:25:30 -0700130 if (!CheckAndInitializeInstalldGlobals()) {
131 LOG(ERROR) << "Failed initializing globals.";
132 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800133 }
134
135 PrepareEnvironment();
136
Andreas Gamped089ca12016-06-27 14:25:30 -0700137 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800138 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700139 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800140 }
141
142 int dexopt_retcode = RunPreopt();
143
144 return dexopt_retcode;
145 }
146
Andreas Gamped089ca12016-06-27 14:25:30 -0700147 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800148 const std::string* prop_value = system_properties_.GetProperty(key);
149 if (prop_value == nullptr) {
150 if (default_value == nullptr) {
151 return 0;
152 }
153 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600154 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800155 value[kPropertyValueMax - 1] = 0;
156 return strlen(default_value);// TODO: Need to truncate?
157 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700158 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600159 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700160 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800161 }
162
Andreas Gamped089ca12016-06-27 14:25:30 -0700163 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000164 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700165 }
166
167 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000168 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700169 }
170
Andreas Gampe73dae112015-11-19 14:12:14 -0800171private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700172
Andreas Gampe73dae112015-11-19 14:12:14 -0800173 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700174 static constexpr const char* kPropertyFiles[] = {
175 "/default.prop", "/system/build.prop"
176 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800177
Andreas Gampe1842af32016-03-16 14:28:50 -0700178 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
179 if (!system_properties_.Load(kPropertyFiles[i])) {
180 return false;
181 }
182 }
183
184 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800185 }
186
187 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700188 // Parse the environment variables from init.environ.rc, which have the form
189 // export NAME VALUE
190 // For simplicity, don't respect string quotation. The values we are interested in can be
191 // encoded without them.
192 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
193 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
194 std::smatch export_match;
195 if (!std::regex_match(line, export_match, export_regex)) {
196 return true;
197 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800198
Andreas Gampe1842af32016-03-16 14:28:50 -0700199 if (export_match.size() != 3) {
200 return true;
201 }
202
203 std::string name = export_match[1].str();
204 std::string value = export_match[2].str();
205
206 system_properties_.SetProperty(name, value);
207
208 return true;
209 });
210 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800211 return false;
212 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700213
Andreas Gamped089ca12016-06-27 14:25:30 -0700214 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
215 return false;
216 }
217 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
218
219 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
220 return false;
221 }
222 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
223
224 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
225 return false;
226 }
227 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
228
229 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
230 return false;
231 }
232 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
233
234 return true;
235 }
236
237 const std::string& GetAndroidData() const {
238 return android_data_;
239 }
240
241 const std::string& GetAndroidRoot() const {
242 return android_root_;
243 }
244
245 const std::string GetOtaDirectoryPrefix() const {
246 return GetAndroidData() + "/ota";
247 }
248
249 bool CheckAndInitializeInstalldGlobals() {
250 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
251 // do not use any datapath that includes this, but we'll still have to set it.
252 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
253 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
254 if (result != 0) {
255 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
256 return false;
257 }
258
259 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
260 LOG(ERROR) << "Could not initialize globals; exiting.";
261 return false;
262 }
263
264 // This is different from the normal installd. We only do the base
265 // directory, the rest will be created on demand when each app is compiled.
266 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
267 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
268 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700269 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800270
271 return true;
272 }
273
Shubham Ajmera45c87432017-06-22 11:10:27 -0700274 bool ParseBool(const char* in) {
275 if (strcmp(in, "true") == 0) {
276 return true;
277 }
278 return false;
279 }
280
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700281 bool ParseUInt(const char* in, uint32_t* out) {
282 char* end;
283 long long int result = strtoll(in, &end, 0);
284 if (in == end || *end != '\0') {
285 return false;
286 }
287 if (result < std::numeric_limits<uint32_t>::min() ||
288 std::numeric_limits<uint32_t>::max() < result) {
289 return false;
290 }
291 *out = static_cast<uint32_t>(result);
292 return true;
293 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700294
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700295 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000296 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800297 }
298
299 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700300 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
301 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
302 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800303
304 for (const std::string& e : environ_) {
305 putenv(const_cast<char*>(e.c_str()));
306 }
307 }
308
309 // Ensure that we have the right boot image. The first time any app is
310 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700311 bool PrepareBootImage(bool force) const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000312 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800313 LOG(ERROR) << "Instruction set missing.";
314 return false;
315 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000316 const char* isa = parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800317
318 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700319 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800320 std::string isa_path = dalvik_cache + "/" + isa;
321 std::string art_path = isa_path + "/system@framework@boot.art";
322 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700323 bool cleared = false;
324 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
325 // Files exist, assume everything is alright if not forced. Otherwise clean up.
326 if (!force) {
327 return true;
328 }
329 ClearDirectory(isa_path);
330 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800331 }
332
Andreas Gamped089ca12016-06-27 14:25:30 -0700333 // Reset umask in otapreopt, so that we control the the access for the files we create.
334 umask(0);
335
Andreas Gampe73dae112015-11-19 14:12:14 -0800336 // Create the directories, if necessary.
337 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700338 if (!CreatePath(dalvik_cache)) {
339 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800340 return false;
341 }
342 }
343 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700344 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800345 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
346 return false;
347 }
348 }
349
Andreas Gampe5709b572016-02-12 17:42:59 -0800350 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700351 if (!cleared) {
352 ClearDirectory(isa_path);
353 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800354
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700355 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800356 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
Chris Morin77c48752018-02-13 15:44:47 -0800357 return PatchoatBootImage(isa_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800358 } else {
359 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700360 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800361 }
362 }
363
Andreas Gamped089ca12016-06-27 14:25:30 -0700364 static bool CreatePath(const std::string& path) {
365 // Create the given path. Use string processing instead of dirname, as dirname's need for
366 // a writable char buffer is painful.
367
368 // First, try to use the full path.
369 if (mkdir(path.c_str(), 0711) == 0) {
370 return true;
371 }
372 if (errno != ENOENT) {
373 PLOG(ERROR) << "Could not create path " << path;
374 return false;
375 }
376
377 // Now find the parent and try that first.
378 size_t last_slash = path.find_last_of('/');
379 if (last_slash == std::string::npos || last_slash == 0) {
380 PLOG(ERROR) << "Could not create " << path;
381 return false;
382 }
383
384 if (!CreatePath(path.substr(0, last_slash))) {
385 return false;
386 }
387
388 if (mkdir(path.c_str(), 0711) == 0) {
389 return true;
390 }
391 PLOG(ERROR) << "Could not create " << path;
392 return false;
393 }
394
395 static void ClearDirectory(const std::string& dir) {
396 DIR* c_dir = opendir(dir.c_str());
397 if (c_dir == nullptr) {
398 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
399 return;
400 }
401
402 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
403 const char* name = de->d_name;
404 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
405 continue;
406 }
407 // We only want to delete regular files and symbolic links.
408 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
409 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
410 LOG(WARNING) << "Unexpected file "
411 << file
412 << " of type "
413 << std::hex
414 << de->d_type
415 << " encountered.";
416 } else {
417 // Try to unlink the file.
418 if (unlink(file.c_str()) != 0) {
419 PLOG(ERROR) << "Unable to unlink " << file;
420 }
421 }
422 }
423 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
424 }
425
Chris Morin77c48752018-02-13 15:44:47 -0800426 bool PatchoatBootImage(const std::string& output_dir, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800427 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
428
429 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700430 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800431
432 cmd.push_back("--input-image-location=/system/framework/boot.art");
Chris Morin77c48752018-02-13 15:44:47 -0800433 cmd.push_back(StringPrintf("--output-image-directory=%s", output_dir.c_str()));
Andreas Gampe5709b572016-02-12 17:42:59 -0800434
435 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
436
437 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
438 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800439 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800440
441 std::string error_msg;
442 bool result = Exec(cmd, &error_msg);
443 if (!result) {
444 LOG(ERROR) << "Could not generate boot image: " << error_msg;
445 }
446 return result;
447 }
448
449 bool Dex2oatBootImage(const std::string& boot_cp,
450 const std::string& art_path,
451 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700452 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800453 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
454 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700455 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800456 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700457 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800458 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
459 }
460 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
461
462 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
463 ART_BASE_ADDRESS_MAX_DELTA);
464 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
465
466 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
467
468 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
469 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
470 "-Xms",
471 true,
472 cmd);
473 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
474 "-Xmx",
475 true,
476 cmd);
477 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
478 "--compiler-filter=",
479 false,
480 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700481 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800482 // TODO: Compiled-classes.
483 const std::string* extra_opts =
484 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
485 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700486 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800487 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
488 }
489 // TODO: Should we lower this? It's usually set close to max, because
490 // normally there's not much else going on at boot.
491 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
492 "-j",
493 false,
494 cmd);
495 AddCompilerOptionFromSystemProperty(
496 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
497 "--instruction-set-variant=",
498 false,
499 cmd);
500 AddCompilerOptionFromSystemProperty(
501 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
502 "--instruction-set-features=",
503 false,
504 cmd);
505
506 std::string error_msg;
507 bool result = Exec(cmd, &error_msg);
508 if (!result) {
509 LOG(ERROR) << "Could not generate boot image: " << error_msg;
510 }
511 return result;
512 }
513
514 static const char* ParseNull(const char* arg) {
515 return (strcmp(arg, "!") == 0) ? nullptr : arg;
516 }
517
Andreas Gamped089ca12016-06-27 14:25:30 -0700518 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700519 // There's one thing we have to be careful about: we may/will be asked to compile an app
520 // living in the system image. This may be a valid request - if the app wasn't compiled,
521 // e.g., if the system image wasn't large enough to include preopted files. However, the
522 // data we have is from the old system, so the driver (the OTA service) can't actually
523 // know. Thus, we will get requests for apps that have preopted components. To avoid
524 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
525 // simple checks:
526 //
527 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
528 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
529 //
530 // 2) If you replace the name in the apk_path with "oat," does the path exist?
531 // (=have a subdirectory for preopted files)
532 //
533 // If the answer to both is yes, skip the dexopt.
534 //
535 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
536 // be stripped), that's not true for APKs signed outside the build system (so the
537 // jar content must be exactly the same).
538
539 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000540 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700541 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000542 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700543 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800544 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700545 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700546 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700547 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700548 CHECK(EndsWith(path, "/"));
549 path = path + "oat";
550 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800551 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700552 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700553 }
554 }
555 }
556
Andreas Gamped089ca12016-06-27 14:25:30 -0700557 // Another issue is unavailability of files in the new system. If the partition
558 // layout changes, otapreopt_chroot may not know about this. Then files from that
559 // partition will not be available and fail to build. This is problematic, as
560 // this tool will wipe the OTA artifact cache and try again (for robustness after
561 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700562 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800563 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700564 return true;
565 }
566
567 return false;
568 }
569
Calin Juravlec9e76792018-02-01 14:44:56 +0000570 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800571 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700572 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800573 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000574 return dexopt(parameters_.apk_path,
575 parameters_.uid,
576 parameters_.pkgName,
577 parameters_.instruction_set,
578 parameters_.dexopt_needed,
579 parameters_.oat_dir,
580 parameters_.dexopt_flags,
581 parameters_.compiler_filter,
582 parameters_.volume_uuid,
583 parameters_.shared_libraries,
584 parameters_.se_info,
585 parameters_.downgrade,
586 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000587 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800588 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800589 parameters_.compilation_reason,
590 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800591 }
592
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700593 int RunPreopt() {
594 if (ShouldSkipPreopt()) {
595 return 0;
596 }
597
598 int dexopt_result = Dexopt();
599 if (dexopt_result == 0) {
600 return 0;
601 }
602
603 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
604 // Then regenerate and retry.
605 if (WEXITSTATUS(dexopt_result) ==
606 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
607 if (!PrepareBootImage(/* force */ true)) {
608 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
609 << dexopt_result;
610 return dexopt_result;
611 }
612
613 int dexopt_result_boot_image_retry = Dexopt();
614 if (dexopt_result_boot_image_retry == 0) {
615 return 0;
616 }
617 }
618
619 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
620 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000621 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700622 return dexopt_result;
623 }
624
625 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000626 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700627 return Dexopt();
628 }
629
Andreas Gampe73dae112015-11-19 14:12:14 -0800630 ////////////////////////////////////
631 // Helpers, mostly taken from ART //
632 ////////////////////////////////////
633
634 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700635 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700636 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800637
638 CHECK_GE(arg_vector.size(), 1U) << command_line;
639
640 // Convert the args to char pointers.
641 const char* program = arg_vector[0].c_str();
642 std::vector<char*> args;
643 for (size_t i = 0; i < arg_vector.size(); ++i) {
644 const std::string& arg = arg_vector[i];
645 char* arg_str = const_cast<char*>(arg.c_str());
646 CHECK(arg_str != nullptr) << i;
647 args.push_back(arg_str);
648 }
649 args.push_back(nullptr);
650
651 // Fork and exec.
652 pid_t pid = fork();
653 if (pid == 0) {
654 // No allocation allowed between fork and exec.
655
656 // Change process groups, so we don't get reaped by ProcessManager.
657 setpgid(0, 0);
658
659 execv(program, &args[0]);
660
661 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
662 // _exit to avoid atexit handlers in child.
663 _exit(1);
664 } else {
665 if (pid == -1) {
666 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
667 command_line.c_str(), strerror(errno));
668 return false;
669 }
670
671 // wait for subprocess to finish
672 int status;
673 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
674 if (got_pid != pid) {
675 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
676 "wanted %d, got %d: %s",
677 command_line.c_str(), pid, got_pid, strerror(errno));
678 return false;
679 }
680 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
681 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
682 command_line.c_str());
683 return false;
684 }
685 }
686 return true;
687 }
688
689 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
690 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
691 constexpr size_t kPageSize = PAGE_SIZE;
692 CHECK_EQ(min_delta % kPageSize, 0u);
693 CHECK_EQ(max_delta % kPageSize, 0u);
694 CHECK_LT(min_delta, max_delta);
695
696 std::default_random_engine generator;
697 generator.seed(GetSeed());
698 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
699 int32_t r = distribution(generator);
700 if (r % 2 == 0) {
701 r = RoundUp(r, kPageSize);
702 } else {
703 r = RoundDown(r, kPageSize);
704 }
705 CHECK_LE(min_delta, r);
706 CHECK_GE(max_delta, r);
707 CHECK_EQ(r % kPageSize, 0u);
708 return r;
709 }
710
711 static uint64_t GetSeed() {
712#ifdef __BIONIC__
713 // Bionic exposes arc4random, use it.
714 uint64_t random_data;
715 arc4random_buf(&random_data, sizeof(random_data));
716 return random_data;
717#else
718#error "This is only supposed to run with bionic. Otherwise, implement..."
719#endif
720 }
721
722 void AddCompilerOptionFromSystemProperty(const char* system_property,
723 const char* prefix,
724 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700725 std::vector<std::string>& out) const {
726 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800727 if (value != nullptr) {
728 if (runtime) {
729 out.push_back("--runtime-arg");
730 }
731 if (prefix != nullptr) {
732 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
733 } else {
734 out.push_back(*value);
735 }
736 }
737 }
738
Andreas Gamped089ca12016-06-27 14:25:30 -0700739 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
740 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
741 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
742 // The index of the instruction-set string inside the package parameters. Needed for
743 // some special-casing that requires knowledge of the instruction-set.
744 static constexpr size_t kISAIndex = 3;
745
Andreas Gampe73dae112015-11-19 14:12:14 -0800746 // Stores the system properties read out of the B partition. We need to use these properties
747 // to compile, instead of the A properties we could get from init/get_property.
748 SystemProperties system_properties_;
749
Andreas Gamped089ca12016-06-27 14:25:30 -0700750 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700751 std::string android_root_;
752 std::string android_data_;
753 std::string boot_classpath_;
754 std::string asec_mountpoint_;
755
Calin Juravlec9e76792018-02-01 14:44:56 +0000756 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800757
758 // Store environment values we need to set.
759 std::vector<std::string> environ_;
760};
761
762OTAPreoptService gOps;
763
764////////////////////////
765// Plug-in functions. //
766////////////////////////
767
768int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800769 return gOps.GetProperty(key, value, default_value);
770}
771
772// Compute the output path of
773bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
774 const char *apk_path,
775 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700776 const char *file_name_start;
777 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800778
779 file_name_start = strrchr(apk_path, '/');
780 if (file_name_start == nullptr) {
781 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
782 return false;
783 }
784 file_name_end = strrchr(file_name_start, '.');
785 if (file_name_end == nullptr) {
786 ALOGE("apk_path '%s' has no extension\n", apk_path);
787 return false;
788 }
789
790 // Calculate file_name
791 file_name_start++; // Move past '/', is valid as file_name_end is valid.
792 size_t file_name_len = file_name_end - file_name_start;
793 std::string file_name(file_name_start, file_name_len);
794
795 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700796 snprintf(path,
797 PKG_PATH_MAX,
798 "%s/%s/%s.odex.%s",
799 oat_dir,
800 instruction_set,
801 file_name.c_str(),
802 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800803 return true;
804}
805
806/*
807 * Computes the odex file for the given apk_path and instruction_set.
808 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
809 *
810 * Returns false if it failed to determine the odex file path.
811 */
812bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
813 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800814 const char *path_end = strrchr(apk_path, '/');
815 if (path_end == nullptr) {
816 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
817 return false;
818 }
819 std::string path_component(apk_path, path_end - apk_path);
820
821 const char *name_begin = path_end + 1;
822 const char *extension_start = strrchr(name_begin, '.');
823 if (extension_start == nullptr) {
824 ALOGE("apk_path '%s' has no extension.\n", apk_path);
825 return false;
826 }
827 std::string name_component(name_begin, extension_start - name_begin);
828
Andreas Gamped089ca12016-06-27 14:25:30 -0700829 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800830 path_component.c_str(),
831 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700832 name_component.c_str(),
833 gOps.GetTargetSlot().c_str());
834 if (new_path.length() >= PKG_PATH_MAX) {
835 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
836 return false;
837 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800838 strcpy(path, new_path.c_str());
839 return true;
840}
841
842bool create_cache_path(char path[PKG_PATH_MAX],
843 const char *src,
844 const char *instruction_set) {
845 size_t srclen = strlen(src);
846
847 /* demand that we are an absolute path */
848 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
849 return false;
850 }
851
852 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
853 return false;
854 }
855
856 std::string from_src = std::string(src + 1);
857 std::replace(from_src.begin(), from_src.end(), '/', '@');
858
859 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700860 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800861 DALVIK_CACHE,
862 instruction_set,
863 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100864 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800865
866 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
867 return false;
868 }
869 strcpy(path, assembled_path.c_str());
870
871 return true;
872}
873
Andreas Gampe73dae112015-11-19 14:12:14 -0800874static int log_callback(int type, const char *fmt, ...) {
875 va_list ap;
876 int priority;
877
878 switch (type) {
879 case SELINUX_WARNING:
880 priority = ANDROID_LOG_WARN;
881 break;
882 case SELINUX_INFO:
883 priority = ANDROID_LOG_INFO;
884 break;
885 default:
886 priority = ANDROID_LOG_ERROR;
887 break;
888 }
889 va_start(ap, fmt);
890 LOG_PRI_VA(priority, "SELinux", fmt, ap);
891 va_end(ap);
892 return 0;
893}
894
895static int otapreopt_main(const int argc, char *argv[]) {
896 int selinux_enabled = (is_selinux_enabled() > 0);
897
898 setenv("ANDROID_LOG_TAGS", "*:v", 1);
899 android::base::InitLogging(argv);
900
Andreas Gampe73dae112015-11-19 14:12:14 -0800901 if (argc < 2) {
902 ALOGE("Expecting parameters");
903 exit(1);
904 }
905
906 union selinux_callback cb;
907 cb.func_log = log_callback;
908 selinux_set_callback(SELINUX_CB_LOG, cb);
909
Andreas Gampe73dae112015-11-19 14:12:14 -0800910 if (selinux_enabled && selinux_status_open(true) < 0) {
911 ALOGE("Could not open selinux status; exiting.\n");
912 exit(1);
913 }
914
915 int ret = android::installd::gOps.Main(argc, argv);
916
917 return ret;
918}
919
920} // namespace installd
921} // namespace android
922
923int main(const int argc, char *argv[]) {
924 return android::installd::otapreopt_main(argc, argv);
925}