blob: 443821c3b9538e3e0c86f0026a693076059c0d69 [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>
Andreas Gampe73dae112015-11-19 14:12:14 -080029
30#include <android-base/logging.h>
31#include <android-base/macros.h>
32#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070033#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080034#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080035#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070036#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080037#include <private/android_filesystem_config.h>
38
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070039#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070040#include "file_parsing.h"
41#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070042#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070043#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000044#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070045#include "otapreopt_utils.h"
46#include "system_properties.h"
47#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070048
Andreas Gampe73dae112015-11-19 14:12:14 -080049#ifndef LOG_TAG
50#define LOG_TAG "otapreopt"
51#endif
52
53#define BUFFER_MAX 1024 /* input buffer for commands */
54#define TOKEN_MAX 16 /* max number of arguments in buffer */
55#define REPLY_MAX 256 /* largest reply allowed */
56
Andreas Gampe56f79f92016-06-08 15:11:37 -070057using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070058using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070059using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080060using android::base::StringPrintf;
61
62namespace android {
63namespace installd {
64
Andreas Gampeef21fd22017-05-22 13:36:06 -070065// Check expected values for dexopt flags. If you need to change this:
66//
67// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
68//
69// You most likely need to increase the protocol version and all that entails!
70
71static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
72static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
73static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
74static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
75static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
76static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
77static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
78static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080079static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
80 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Mathieu Chartier351bc942018-03-06 13:55:58 -080081static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070082static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070083
Patrick Baumann2271b3e2020-04-14 17:03:00 -070084static_assert(DEXOPT_MASK == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080085 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070086
87
Andreas Gampea64a6272018-07-10 10:43:47 -070088template<typename T>
89static constexpr bool IsPowerOfTwo(T x) {
90 static_assert(std::is_integral<T>::value, "T must be integral");
91 // TODO: assert unsigned. There is currently many uses with signed values.
92 return (x & (x - 1)) == 0;
93}
Andreas Gampeef21fd22017-05-22 13:36:06 -070094
Andreas Gampe73dae112015-11-19 14:12:14 -080095template<typename T>
96static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
Elliott Hughes0beed272020-07-29 14:28:25 -070097 return (x & -n);
Andreas Gampe73dae112015-11-19 14:12:14 -080098}
99
100template<typename T>
101static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
102 return RoundDown(x + n - 1, n);
103}
104
105class OTAPreoptService {
106 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800107 // Main driver. Performs the following steps.
108 //
109 // 1) Parse options (read system properties etc from B partition).
110 //
111 // 2) Read in package data.
112 //
113 // 3) Prepare environment variables.
114 //
115 // 4) Prepare(compile) boot image, if necessary.
116 //
117 // 5) Run update.
118 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700119 if (!ReadArguments(argc, argv)) {
120 LOG(ERROR) << "Failed reading command line.";
121 return 1;
122 }
123
Andreas Gampe73dae112015-11-19 14:12:14 -0800124 if (!ReadSystemProperties()) {
125 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700126 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800127 }
128
129 if (!ReadEnvironment()) {
130 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700131 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800132 }
133
Andreas Gamped089ca12016-06-27 14:25:30 -0700134 if (!CheckAndInitializeInstalldGlobals()) {
135 LOG(ERROR) << "Failed initializing globals.";
136 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800137 }
138
Orion Hodson640cb762020-03-26 09:24:41 +0000139 PrepareEnvironmentVariables();
Andreas Gampe73dae112015-11-19 14:12:14 -0800140
Orion Hodson640cb762020-03-26 09:24:41 +0000141 if (!EnsureBootImageAndDalvikCache()) {
142 LOG(ERROR) << "Bad boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700143 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800144 }
145
146 int dexopt_retcode = RunPreopt();
147
148 return dexopt_retcode;
149 }
150
Andreas Gamped089ca12016-06-27 14:25:30 -0700151 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800152 const std::string* prop_value = system_properties_.GetProperty(key);
153 if (prop_value == nullptr) {
154 if (default_value == nullptr) {
155 return 0;
156 }
157 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600158 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800159 value[kPropertyValueMax - 1] = 0;
160 return strlen(default_value);// TODO: Need to truncate?
161 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700162 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600163 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700164 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800165 }
166
Andreas Gamped089ca12016-06-27 14:25:30 -0700167 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000168 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700169 }
170
171 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000172 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700173 }
174
Andreas Gampe73dae112015-11-19 14:12:14 -0800175private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700176
Andreas Gampe73dae112015-11-19 14:12:14 -0800177 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700178 static constexpr const char* kPropertyFiles[] = {
179 "/default.prop", "/system/build.prop"
180 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800181
Andreas Gampe1842af32016-03-16 14:28:50 -0700182 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
183 if (!system_properties_.Load(kPropertyFiles[i])) {
184 return false;
185 }
186 }
187
188 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800189 }
190
191 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700192 // Parse the environment variables from init.environ.rc, which have the form
193 // export NAME VALUE
194 // For simplicity, don't respect string quotation. The values we are interested in can be
195 // encoded without them.
196 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
197 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
198 std::smatch export_match;
199 if (!std::regex_match(line, export_match, export_regex)) {
200 return true;
201 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800202
Andreas Gampe1842af32016-03-16 14:28:50 -0700203 if (export_match.size() != 3) {
204 return true;
205 }
206
207 std::string name = export_match[1].str();
208 std::string value = export_match[2].str();
209
210 system_properties_.SetProperty(name, value);
211
212 return true;
213 });
214 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800215 return false;
216 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700217
Andreas Gamped089ca12016-06-27 14:25:30 -0700218 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
219 return false;
220 }
221 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
222
223 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
224 return false;
225 }
226 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
227
228 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
229 return false;
230 }
231 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
232
233 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
234 return false;
235 }
236 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
237
238 return true;
239 }
240
241 const std::string& GetAndroidData() const {
242 return android_data_;
243 }
244
245 const std::string& GetAndroidRoot() const {
246 return android_root_;
247 }
248
249 const std::string GetOtaDirectoryPrefix() const {
250 return GetAndroidData() + "/ota";
251 }
252
253 bool CheckAndInitializeInstalldGlobals() {
254 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
255 // do not use any datapath that includes this, but we'll still have to set it.
256 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
257 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
258 if (result != 0) {
259 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
260 return false;
261 }
262
263 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
264 LOG(ERROR) << "Could not initialize globals; exiting.";
265 return false;
266 }
267
268 // This is different from the normal installd. We only do the base
269 // directory, the rest will be created on demand when each app is compiled.
270 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
271 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
272 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700273 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800274
275 return true;
276 }
277
Shubham Ajmera45c87432017-06-22 11:10:27 -0700278 bool ParseBool(const char* in) {
279 if (strcmp(in, "true") == 0) {
280 return true;
281 }
282 return false;
283 }
284
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700285 bool ParseUInt(const char* in, uint32_t* out) {
286 char* end;
287 long long int result = strtoll(in, &end, 0);
288 if (in == end || *end != '\0') {
289 return false;
290 }
291 if (result < std::numeric_limits<uint32_t>::min() ||
292 std::numeric_limits<uint32_t>::max() < result) {
293 return false;
294 }
295 *out = static_cast<uint32_t>(result);
296 return true;
297 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700298
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700299 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000300 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800301 }
302
Orion Hodson640cb762020-03-26 09:24:41 +0000303 void PrepareEnvironmentVariables() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700304 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
305 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
306 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800307
308 for (const std::string& e : environ_) {
309 putenv(const_cast<char*>(e.c_str()));
310 }
311 }
312
Orion Hodson640cb762020-03-26 09:24:41 +0000313 // Ensure that we have the right boot image and cache file structures.
314 bool EnsureBootImageAndDalvikCache() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000315 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800316 LOG(ERROR) << "Instruction set missing.";
317 return false;
318 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000319 const char* isa = parameters_.instruction_set;
Andreas Gamped089ca12016-06-27 14:25:30 -0700320 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800321 std::string isa_path = dalvik_cache + "/" + isa;
Andreas Gampe73dae112015-11-19 14:12:14 -0800322
Andreas Gamped089ca12016-06-27 14:25:30 -0700323 // Reset umask in otapreopt, so that we control the the access for the files we create.
324 umask(0);
325
Andreas Gampe73dae112015-11-19 14:12:14 -0800326 // Create the directories, if necessary.
327 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700328 if (!CreatePath(dalvik_cache)) {
329 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800330 return false;
331 }
332 }
333 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700334 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800335 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
336 return false;
337 }
338 }
339
Orion Hodson640cb762020-03-26 09:24:41 +0000340 // Clear cached artifacts.
341 ClearDirectory(isa_path);
342
343 // Check whether we have a boot image.
Andreas Gampebd7aef12018-10-23 13:58:44 -0700344 // TODO: check that the files are correct wrt/ jars.
Orion Hodson640cb762020-03-26 09:24:41 +0000345 std::string preopted_boot_art_path =
346 StringPrintf("/apex/com.android.art/javalib/%s/boot.art", isa);
347 if (access(preopted_boot_art_path.c_str(), F_OK) != 0) {
348 PLOG(ERROR) << "Bad access() to " << preopted_boot_art_path;
349 return false;
Andreas Gampebd7aef12018-10-23 13:58:44 -0700350 }
351
Orion Hodson640cb762020-03-26 09:24:41 +0000352 return true;
Andreas Gampe5709b572016-02-12 17:42:59 -0800353 }
354
Andreas Gamped089ca12016-06-27 14:25:30 -0700355 static bool CreatePath(const std::string& path) {
356 // Create the given path. Use string processing instead of dirname, as dirname's need for
357 // a writable char buffer is painful.
358
359 // First, try to use the full path.
360 if (mkdir(path.c_str(), 0711) == 0) {
361 return true;
362 }
363 if (errno != ENOENT) {
364 PLOG(ERROR) << "Could not create path " << path;
365 return false;
366 }
367
368 // Now find the parent and try that first.
369 size_t last_slash = path.find_last_of('/');
370 if (last_slash == std::string::npos || last_slash == 0) {
371 PLOG(ERROR) << "Could not create " << path;
372 return false;
373 }
374
375 if (!CreatePath(path.substr(0, last_slash))) {
376 return false;
377 }
378
379 if (mkdir(path.c_str(), 0711) == 0) {
380 return true;
381 }
382 PLOG(ERROR) << "Could not create " << path;
383 return false;
384 }
385
386 static void ClearDirectory(const std::string& dir) {
387 DIR* c_dir = opendir(dir.c_str());
388 if (c_dir == nullptr) {
389 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
390 return;
391 }
392
393 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
394 const char* name = de->d_name;
395 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
396 continue;
397 }
398 // We only want to delete regular files and symbolic links.
399 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
400 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
401 LOG(WARNING) << "Unexpected file "
402 << file
403 << " of type "
404 << std::hex
405 << de->d_type
406 << " encountered.";
407 } else {
408 // Try to unlink the file.
409 if (unlink(file.c_str()) != 0) {
410 PLOG(ERROR) << "Unable to unlink " << file;
411 }
412 }
413 }
414 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
415 }
416
Andreas Gampe73dae112015-11-19 14:12:14 -0800417 static const char* ParseNull(const char* arg) {
418 return (strcmp(arg, "!") == 0) ? nullptr : arg;
419 }
420
Andreas Gamped089ca12016-06-27 14:25:30 -0700421 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700422 // There's one thing we have to be careful about: we may/will be asked to compile an app
423 // living in the system image. This may be a valid request - if the app wasn't compiled,
424 // e.g., if the system image wasn't large enough to include preopted files. However, the
425 // data we have is from the old system, so the driver (the OTA service) can't actually
426 // know. Thus, we will get requests for apps that have preopted components. To avoid
427 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
428 // simple checks:
429 //
430 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
431 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
432 //
433 // 2) If you replace the name in the apk_path with "oat," does the path exist?
434 // (=have a subdirectory for preopted files)
435 //
436 // If the answer to both is yes, skip the dexopt.
437 //
438 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
439 // be stripped), that's not true for APKs signed outside the build system (so the
440 // jar content must be exactly the same).
441
442 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000443 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700444 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000445 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700446 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800447 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700448 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700449 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700450 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700451 CHECK(EndsWith(path, "/"));
452 path = path + "oat";
453 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800454 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700455 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700456 }
457 }
458 }
459
Andreas Gamped089ca12016-06-27 14:25:30 -0700460 // Another issue is unavailability of files in the new system. If the partition
461 // layout changes, otapreopt_chroot may not know about this. Then files from that
462 // partition will not be available and fail to build. This is problematic, as
463 // this tool will wipe the OTA artifact cache and try again (for robustness after
464 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700465 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800466 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700467 return true;
468 }
469
470 return false;
471 }
472
Calin Juravlec9e76792018-02-01 14:44:56 +0000473 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800474 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700475 int Dexopt() {
Andreas Gampe023b2242018-02-28 16:03:25 -0800476 std::string dummy;
Calin Juravlec9e76792018-02-01 14:44:56 +0000477 return dexopt(parameters_.apk_path,
478 parameters_.uid,
479 parameters_.pkgName,
480 parameters_.instruction_set,
481 parameters_.dexopt_needed,
482 parameters_.oat_dir,
483 parameters_.dexopt_flags,
484 parameters_.compiler_filter,
485 parameters_.volume_uuid,
486 parameters_.shared_libraries,
487 parameters_.se_info,
488 parameters_.downgrade,
489 parameters_.target_sdk_version,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +0000490 parameters_.profile_name,
Calin Juravledcccd832018-02-13 18:31:32 -0800491 parameters_.dex_metadata_path,
Andreas Gampe023b2242018-02-28 16:03:25 -0800492 parameters_.compilation_reason,
493 &dummy);
Andreas Gampe73dae112015-11-19 14:12:14 -0800494 }
495
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700496 int RunPreopt() {
497 if (ShouldSkipPreopt()) {
498 return 0;
499 }
500
501 int dexopt_result = Dexopt();
502 if (dexopt_result == 0) {
503 return 0;
504 }
505
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700506 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
507 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000508 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700509 return dexopt_result;
510 }
511
512 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000513 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700514 return Dexopt();
515 }
516
Andreas Gampe73dae112015-11-19 14:12:14 -0800517 ////////////////////////////////////
518 // Helpers, mostly taken from ART //
519 ////////////////////////////////////
520
Andreas Gampe73dae112015-11-19 14:12:14 -0800521 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
522 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
523 constexpr size_t kPageSize = PAGE_SIZE;
Elliott Hughes0beed272020-07-29 14:28:25 -0700524 static_assert(IsPowerOfTwo(kPageSize), "page size must be power of two");
Andreas Gampe73dae112015-11-19 14:12:14 -0800525 CHECK_EQ(min_delta % kPageSize, 0u);
526 CHECK_EQ(max_delta % kPageSize, 0u);
527 CHECK_LT(min_delta, max_delta);
528
529 std::default_random_engine generator;
530 generator.seed(GetSeed());
531 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
532 int32_t r = distribution(generator);
533 if (r % 2 == 0) {
534 r = RoundUp(r, kPageSize);
535 } else {
536 r = RoundDown(r, kPageSize);
537 }
538 CHECK_LE(min_delta, r);
539 CHECK_GE(max_delta, r);
540 CHECK_EQ(r % kPageSize, 0u);
541 return r;
542 }
543
544 static uint64_t GetSeed() {
545#ifdef __BIONIC__
546 // Bionic exposes arc4random, use it.
547 uint64_t random_data;
548 arc4random_buf(&random_data, sizeof(random_data));
549 return random_data;
550#else
551#error "This is only supposed to run with bionic. Otherwise, implement..."
552#endif
553 }
554
555 void AddCompilerOptionFromSystemProperty(const char* system_property,
556 const char* prefix,
557 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700558 std::vector<std::string>& out) const {
559 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800560 if (value != nullptr) {
561 if (runtime) {
562 out.push_back("--runtime-arg");
563 }
564 if (prefix != nullptr) {
565 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
566 } else {
567 out.push_back(*value);
568 }
569 }
570 }
571
Andreas Gamped089ca12016-06-27 14:25:30 -0700572 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
573 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
574 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
575 // The index of the instruction-set string inside the package parameters. Needed for
576 // some special-casing that requires knowledge of the instruction-set.
577 static constexpr size_t kISAIndex = 3;
578
Andreas Gampe73dae112015-11-19 14:12:14 -0800579 // Stores the system properties read out of the B partition. We need to use these properties
580 // to compile, instead of the A properties we could get from init/get_property.
581 SystemProperties system_properties_;
582
Andreas Gamped089ca12016-06-27 14:25:30 -0700583 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700584 std::string android_root_;
585 std::string android_data_;
586 std::string boot_classpath_;
587 std::string asec_mountpoint_;
588
Calin Juravlec9e76792018-02-01 14:44:56 +0000589 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800590
591 // Store environment values we need to set.
592 std::vector<std::string> environ_;
593};
594
595OTAPreoptService gOps;
596
597////////////////////////
598// Plug-in functions. //
599////////////////////////
600
601int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800602 return gOps.GetProperty(key, value, default_value);
603}
604
605// Compute the output path of
606bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
607 const char *apk_path,
608 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700609 const char *file_name_start;
610 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800611
612 file_name_start = strrchr(apk_path, '/');
613 if (file_name_start == nullptr) {
614 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
615 return false;
616 }
617 file_name_end = strrchr(file_name_start, '.');
618 if (file_name_end == nullptr) {
619 ALOGE("apk_path '%s' has no extension\n", apk_path);
620 return false;
621 }
622
623 // Calculate file_name
624 file_name_start++; // Move past '/', is valid as file_name_end is valid.
625 size_t file_name_len = file_name_end - file_name_start;
626 std::string file_name(file_name_start, file_name_len);
627
628 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700629 snprintf(path,
630 PKG_PATH_MAX,
631 "%s/%s/%s.odex.%s",
632 oat_dir,
633 instruction_set,
634 file_name.c_str(),
635 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800636 return true;
637}
638
639/*
640 * Computes the odex file for the given apk_path and instruction_set.
641 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
642 *
643 * Returns false if it failed to determine the odex file path.
644 */
645bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
646 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800647 const char *path_end = strrchr(apk_path, '/');
648 if (path_end == nullptr) {
649 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
650 return false;
651 }
652 std::string path_component(apk_path, path_end - apk_path);
653
654 const char *name_begin = path_end + 1;
655 const char *extension_start = strrchr(name_begin, '.');
656 if (extension_start == nullptr) {
657 ALOGE("apk_path '%s' has no extension.\n", apk_path);
658 return false;
659 }
660 std::string name_component(name_begin, extension_start - name_begin);
661
Andreas Gamped089ca12016-06-27 14:25:30 -0700662 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800663 path_component.c_str(),
664 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700665 name_component.c_str(),
666 gOps.GetTargetSlot().c_str());
667 if (new_path.length() >= PKG_PATH_MAX) {
668 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
669 return false;
670 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800671 strcpy(path, new_path.c_str());
672 return true;
673}
674
675bool create_cache_path(char path[PKG_PATH_MAX],
676 const char *src,
677 const char *instruction_set) {
678 size_t srclen = strlen(src);
679
680 /* demand that we are an absolute path */
681 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
682 return false;
683 }
684
685 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
686 return false;
687 }
688
689 std::string from_src = std::string(src + 1);
690 std::replace(from_src.begin(), from_src.end(), '/', '@');
691
692 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700693 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800694 DALVIK_CACHE,
695 instruction_set,
696 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100697 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800698
699 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
700 return false;
701 }
702 strcpy(path, assembled_path.c_str());
703
704 return true;
705}
706
Andreas Gampe73dae112015-11-19 14:12:14 -0800707static int log_callback(int type, const char *fmt, ...) {
708 va_list ap;
709 int priority;
710
711 switch (type) {
712 case SELINUX_WARNING:
713 priority = ANDROID_LOG_WARN;
714 break;
715 case SELINUX_INFO:
716 priority = ANDROID_LOG_INFO;
717 break;
718 default:
719 priority = ANDROID_LOG_ERROR;
720 break;
721 }
722 va_start(ap, fmt);
723 LOG_PRI_VA(priority, "SELinux", fmt, ap);
724 va_end(ap);
725 return 0;
726}
727
728static int otapreopt_main(const int argc, char *argv[]) {
729 int selinux_enabled = (is_selinux_enabled() > 0);
730
731 setenv("ANDROID_LOG_TAGS", "*:v", 1);
732 android::base::InitLogging(argv);
733
Andreas Gampe73dae112015-11-19 14:12:14 -0800734 if (argc < 2) {
735 ALOGE("Expecting parameters");
736 exit(1);
737 }
738
739 union selinux_callback cb;
740 cb.func_log = log_callback;
741 selinux_set_callback(SELINUX_CB_LOG, cb);
742
Andreas Gampe73dae112015-11-19 14:12:14 -0800743 if (selinux_enabled && selinux_status_open(true) < 0) {
744 ALOGE("Could not open selinux status; exiting.\n");
745 exit(1);
746 }
747
748 int ret = android::installd::gOps.Main(argc, argv);
749
750 return ret;
751}
752
753} // namespace installd
754} // namespace android
755
756int main(const int argc, char *argv[]) {
757 return android::installd::otapreopt_main(argc, argv);
758}