blob: e978e79d8636a3eae6538baa6e779eba4fe0986a [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>
Alex Lightfbdc7262021-04-26 16:48:18 -070029#include <sys/mman.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080030
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>
Mark Salyzyn7823e122016-09-29 08:08:05 -070037#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080038#include <private/android_filesystem_config.h>
39
Alex Lightfbdc7262021-04-26 16:48:18 -070040#include "android-base/file.h"
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::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070061using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080062using android::base::StringPrintf;
63
64namespace android {
65namespace installd {
66
Andreas Gampeef21fd22017-05-22 13:36:06 -070067// Check expected values for dexopt flags. If you need to change this:
68//
69// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
70//
71// You most likely need to increase the protocol version and all that entails!
72
73static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
74static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
75static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
76static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
77static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
78static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
79static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
80static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080081static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
82 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Mathieu Chartier351bc942018-03-06 13:55:58 -080083static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070084static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070085
Patrick Baumann2271b3e2020-04-14 17:03:00 -070086static_assert(DEXOPT_MASK == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080087 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070088
89
Andreas Gampea64a6272018-07-10 10:43:47 -070090template<typename T>
91static constexpr bool IsPowerOfTwo(T x) {
92 static_assert(std::is_integral<T>::value, "T must be integral");
93 // TODO: assert unsigned. There is currently many uses with signed values.
94 return (x & (x - 1)) == 0;
95}
Andreas Gampeef21fd22017-05-22 13:36:06 -070096
Andreas Gampe73dae112015-11-19 14:12:14 -080097template<typename T>
98static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
Elliott Hughes0beed272020-07-29 14:28:25 -070099 return (x & -n);
Andreas Gampe73dae112015-11-19 14:12:14 -0800100}
101
102template<typename T>
103static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
104 return RoundDown(x + n - 1, n);
105}
106
107class OTAPreoptService {
108 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800109 // Main driver. Performs the following steps.
110 //
111 // 1) Parse options (read system properties etc from B partition).
112 //
113 // 2) Read in package data.
114 //
115 // 3) Prepare environment variables.
116 //
117 // 4) Prepare(compile) boot image, if necessary.
118 //
119 // 5) Run update.
120 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700121 if (!ReadArguments(argc, argv)) {
122 LOG(ERROR) << "Failed reading command line.";
123 return 1;
124 }
125
Andreas Gampe73dae112015-11-19 14:12:14 -0800126 if (!ReadSystemProperties()) {
127 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700128 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800129 }
130
131 if (!ReadEnvironment()) {
132 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700133 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800134 }
135
Andreas Gamped089ca12016-06-27 14:25:30 -0700136 if (!CheckAndInitializeInstalldGlobals()) {
137 LOG(ERROR) << "Failed initializing globals.";
138 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800139 }
140
Orion Hodson640cb762020-03-26 09:24:41 +0000141 PrepareEnvironmentVariables();
Andreas Gampe73dae112015-11-19 14:12:14 -0800142
Jiakai Zhang202524b2021-12-22 16:40:52 +0000143 if (!EnsureDalvikCache()) {
144 LOG(ERROR) << "Bad dalvik cache.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700145 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800146 }
147
148 int dexopt_retcode = RunPreopt();
149
150 return dexopt_retcode;
151 }
152
Andreas Gamped089ca12016-06-27 14:25:30 -0700153 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800154 const std::string* prop_value = system_properties_.GetProperty(key);
155 if (prop_value == nullptr) {
156 if (default_value == nullptr) {
157 return 0;
158 }
159 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600160 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800161 value[kPropertyValueMax - 1] = 0;
162 return strlen(default_value);// TODO: Need to truncate?
163 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700164 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600165 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700166 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800167 }
168
Andreas Gamped089ca12016-06-27 14:25:30 -0700169 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000170 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700171 }
172
173 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000174 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700175 }
176
Andreas Gampe73dae112015-11-19 14:12:14 -0800177private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700178
Andreas Gampe73dae112015-11-19 14:12:14 -0800179 bool ReadSystemProperties() {
Alex Lightc36d0012021-03-03 16:10:12 -0800180 // TODO This file does not have a stable format. It should be read by
181 // code shared by init and otapreopt. See b/181182967#comment80
Andreas Gampe1842af32016-03-16 14:28:50 -0700182 static constexpr const char* kPropertyFiles[] = {
Alex Lightc36d0012021-03-03 16:10:12 -0800183 "/system/build.prop"
Andreas Gampe1842af32016-03-16 14:28:50 -0700184 };
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.
Alex Lightfbdc7262021-04-26 16:48:18 -0700200 //
201 // init.environ.rc and derive_classpath all have the same format for
202 // environment variable exports (since they are all meant to be read by
203 // init) and can be matched by the same regex.
204
205 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
206 auto parse_results = [&](auto& input) {
207 ParseFile(input, [&](const std::string& line) {
208 std::smatch export_match;
209 if (!std::regex_match(line, export_match, export_regex)) {
210 return true;
211 }
212
213 if (export_match.size() != 3) {
214 return true;
215 }
216
217 std::string name = export_match[1].str();
218 std::string value = export_match[2].str();
219
220 system_properties_.SetProperty(name, value);
221
222 return true;
223 });
224 };
225
Alex Light9c3d87d2021-03-03 16:49:08 -0800226 // TODO Just like with the system-properties above we really should have
227 // common code between init and otapreopt to deal with reading these
228 // things. See b/181182967
Alex Lightfbdc7262021-04-26 16:48:18 -0700229 // There have been a variety of places the various env-vars have been
230 // over the years. Expand or reduce this list as needed.
Alex Light9c3d87d2021-03-03 16:49:08 -0800231 static constexpr const char* kEnvironmentVariableSources[] = {
Alex Lightfbdc7262021-04-26 16:48:18 -0700232 "/init.environ.rc",
Alex Light9c3d87d2021-03-03 16:49:08 -0800233 };
Alex Lightfbdc7262021-04-26 16:48:18 -0700234 // First get everything from the static files.
Alex Light9c3d87d2021-03-03 16:49:08 -0800235 for (const char* env_vars_file : kEnvironmentVariableSources) {
Alex Lightfbdc7262021-04-26 16:48:18 -0700236 parse_results(env_vars_file);
Andreas Gampe73dae112015-11-19 14:12:14 -0800237 }
Alex Lightfbdc7262021-04-26 16:48:18 -0700238
239 // Next get everything from derive_classpath, since we're already in the
240 // chroot it will get the new versions of any dependencies.
241 {
242 android::base::unique_fd fd(memfd_create("derive_classpath_temp", MFD_CLOEXEC));
243 if (!fd.ok()) {
244 LOG(ERROR) << "Unable to create fd for derive_classpath";
245 return false;
246 }
247 std::string memfd_file = StringPrintf("/proc/%d/fd/%d", getpid(), fd.get());
248 std::string error_msg;
249 if (!Exec({"/apex/com.android.sdkext/bin/derive_classpath", memfd_file}, &error_msg)) {
250 PLOG(ERROR) << "Running derive_classpath failed: " << error_msg;
251 return false;
252 }
253 std::ifstream ifs(memfd_file);
254 parse_results(ifs);
255 }
256
Andreas Gamped089ca12016-06-27 14:25:30 -0700257 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
258 return false;
259 }
260 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
261
262 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
263 return false;
264 }
265 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
266
267 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
268 return false;
269 }
270 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
271
272 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
273 return false;
274 }
275 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
276
277 return true;
278 }
279
280 const std::string& GetAndroidData() const {
281 return android_data_;
282 }
283
284 const std::string& GetAndroidRoot() const {
285 return android_root_;
286 }
287
288 const std::string GetOtaDirectoryPrefix() const {
289 return GetAndroidData() + "/ota";
290 }
291
292 bool CheckAndInitializeInstalldGlobals() {
293 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
294 // do not use any datapath that includes this, but we'll still have to set it.
295 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
296 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
297 if (result != 0) {
298 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
299 return false;
300 }
301
302 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
303 LOG(ERROR) << "Could not initialize globals; exiting.";
304 return false;
305 }
306
307 // This is different from the normal installd. We only do the base
308 // directory, the rest will be created on demand when each app is compiled.
309 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
310 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
311 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700312 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800313
314 return true;
315 }
316
Shubham Ajmera45c87432017-06-22 11:10:27 -0700317 bool ParseBool(const char* in) {
318 if (strcmp(in, "true") == 0) {
319 return true;
320 }
321 return false;
322 }
323
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700324 bool ParseUInt(const char* in, uint32_t* out) {
325 char* end;
326 long long int result = strtoll(in, &end, 0);
327 if (in == end || *end != '\0') {
328 return false;
329 }
330 if (result < std::numeric_limits<uint32_t>::min() ||
331 std::numeric_limits<uint32_t>::max() < result) {
332 return false;
333 }
334 *out = static_cast<uint32_t>(result);
335 return true;
336 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700337
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700338 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000339 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800340 }
341
Orion Hodson640cb762020-03-26 09:24:41 +0000342 void PrepareEnvironmentVariables() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700343 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
344 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
345 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800346
347 for (const std::string& e : environ_) {
348 putenv(const_cast<char*>(e.c_str()));
349 }
350 }
351
Jiakai Zhang202524b2021-12-22 16:40:52 +0000352 // Ensure that we have the right cache file structures.
353 bool EnsureDalvikCache() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000354 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800355 LOG(ERROR) << "Instruction set missing.";
356 return false;
357 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000358 const char* isa = parameters_.instruction_set;
Andreas Gamped089ca12016-06-27 14:25:30 -0700359 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800360 std::string isa_path = dalvik_cache + "/" + isa;
Andreas Gampe73dae112015-11-19 14:12:14 -0800361
Andreas Gamped089ca12016-06-27 14:25:30 -0700362 // Reset umask in otapreopt, so that we control the the access for the files we create.
363 umask(0);
364
Andreas Gampe73dae112015-11-19 14:12:14 -0800365 // Create the directories, if necessary.
366 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700367 if (!CreatePath(dalvik_cache)) {
368 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800369 return false;
370 }
371 }
372 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700373 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800374 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
375 return false;
376 }
377 }
378
Orion Hodson640cb762020-03-26 09:24:41 +0000379 return true;
Andreas Gampe5709b572016-02-12 17:42:59 -0800380 }
381
Andreas Gamped089ca12016-06-27 14:25:30 -0700382 static bool CreatePath(const std::string& path) {
383 // Create the given path. Use string processing instead of dirname, as dirname's need for
384 // a writable char buffer is painful.
385
386 // First, try to use the full path.
387 if (mkdir(path.c_str(), 0711) == 0) {
388 return true;
389 }
390 if (errno != ENOENT) {
391 PLOG(ERROR) << "Could not create path " << path;
392 return false;
393 }
394
395 // Now find the parent and try that first.
396 size_t last_slash = path.find_last_of('/');
397 if (last_slash == std::string::npos || last_slash == 0) {
398 PLOG(ERROR) << "Could not create " << path;
399 return false;
400 }
401
402 if (!CreatePath(path.substr(0, last_slash))) {
403 return false;
404 }
405
406 if (mkdir(path.c_str(), 0711) == 0) {
407 return true;
408 }
409 PLOG(ERROR) << "Could not create " << path;
410 return false;
411 }
412
Andreas Gampe73dae112015-11-19 14:12:14 -0800413 static const char* ParseNull(const char* arg) {
414 return (strcmp(arg, "!") == 0) ? nullptr : arg;
415 }
416
Andreas Gamped089ca12016-06-27 14:25:30 -0700417 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700418 // There's one thing we have to be careful about: we may/will be asked to compile an app
419 // living in the system image. This may be a valid request - if the app wasn't compiled,
420 // e.g., if the system image wasn't large enough to include preopted files. However, the
421 // data we have is from the old system, so the driver (the OTA service) can't actually
422 // know. Thus, we will get requests for apps that have preopted components. To avoid
423 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
424 // simple checks:
425 //
426 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
427 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
428 //
429 // 2) If you replace the name in the apk_path with "oat," does the path exist?
430 // (=have a subdirectory for preopted files)
431 //
432 // If the answer to both is yes, skip the dexopt.
433 //
434 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
435 // be stripped), that's not true for APKs signed outside the build system (so the
436 // jar content must be exactly the same).
437
438 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000439 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700440 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000441 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700442 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800443 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700444 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700445 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700446 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700447 CHECK(EndsWith(path, "/"));
448 path = path + "oat";
449 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800450 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700451 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700452 }
453 }
454 }
455
Andreas Gamped089ca12016-06-27 14:25:30 -0700456 // Another issue is unavailability of files in the new system. If the partition
457 // layout changes, otapreopt_chroot may not know about this. Then files from that
458 // partition will not be available and fail to build. This is problematic, as
459 // this tool will wipe the OTA artifact cache and try again (for robustness after
460 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700461 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800462 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700463 return true;
464 }
465
466 return false;
467 }
468
Calin Juravlec9e76792018-02-01 14:44:56 +0000469 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800470 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700471 int Dexopt() {
Alex Light6c857b72021-02-25 13:37:13 -0800472 std::string error;
473 int res = dexopt(parameters_.apk_path,
474 parameters_.uid,
475 parameters_.pkgName,
476 parameters_.instruction_set,
477 parameters_.dexopt_needed,
478 parameters_.oat_dir,
479 parameters_.dexopt_flags,
480 parameters_.compiler_filter,
481 parameters_.volume_uuid,
482 parameters_.shared_libraries,
483 parameters_.se_info,
484 parameters_.downgrade,
485 parameters_.target_sdk_version,
486 parameters_.profile_name,
487 parameters_.dex_metadata_path,
488 parameters_.compilation_reason,
489 &error);
490 if (res != 0) {
491 LOG(ERROR) << "During preopt of " << parameters_.apk_path << " got result " << res
492 << " error: " << error;
493 }
494 return res;
Andreas Gampe73dae112015-11-19 14:12:14 -0800495 }
496
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700497 int RunPreopt() {
498 if (ShouldSkipPreopt()) {
499 return 0;
500 }
501
502 int dexopt_result = Dexopt();
503 if (dexopt_result == 0) {
504 return 0;
505 }
506
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700507 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
508 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000509 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700510 return dexopt_result;
511 }
512
513 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000514 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700515 return Dexopt();
516 }
517
Andreas Gampe73dae112015-11-19 14:12:14 -0800518 ////////////////////////////////////
519 // Helpers, mostly taken from ART //
520 ////////////////////////////////////
521
Andreas Gampe73dae112015-11-19 14:12:14 -0800522 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
523 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
524 constexpr size_t kPageSize = PAGE_SIZE;
Elliott Hughes0beed272020-07-29 14:28:25 -0700525 static_assert(IsPowerOfTwo(kPageSize), "page size must be power of two");
Andreas Gampe73dae112015-11-19 14:12:14 -0800526 CHECK_EQ(min_delta % kPageSize, 0u);
527 CHECK_EQ(max_delta % kPageSize, 0u);
528 CHECK_LT(min_delta, max_delta);
529
530 std::default_random_engine generator;
531 generator.seed(GetSeed());
532 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
533 int32_t r = distribution(generator);
534 if (r % 2 == 0) {
535 r = RoundUp(r, kPageSize);
536 } else {
537 r = RoundDown(r, kPageSize);
538 }
539 CHECK_LE(min_delta, r);
540 CHECK_GE(max_delta, r);
541 CHECK_EQ(r % kPageSize, 0u);
542 return r;
543 }
544
545 static uint64_t GetSeed() {
546#ifdef __BIONIC__
547 // Bionic exposes arc4random, use it.
548 uint64_t random_data;
549 arc4random_buf(&random_data, sizeof(random_data));
550 return random_data;
551#else
552#error "This is only supposed to run with bionic. Otherwise, implement..."
553#endif
554 }
555
556 void AddCompilerOptionFromSystemProperty(const char* system_property,
557 const char* prefix,
558 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700559 std::vector<std::string>& out) const {
560 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800561 if (value != nullptr) {
562 if (runtime) {
563 out.push_back("--runtime-arg");
564 }
565 if (prefix != nullptr) {
566 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
567 } else {
568 out.push_back(*value);
569 }
570 }
571 }
572
Andreas Gamped089ca12016-06-27 14:25:30 -0700573 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
574 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
575 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
576 // The index of the instruction-set string inside the package parameters. Needed for
577 // some special-casing that requires knowledge of the instruction-set.
578 static constexpr size_t kISAIndex = 3;
579
Andreas Gampe73dae112015-11-19 14:12:14 -0800580 // Stores the system properties read out of the B partition. We need to use these properties
581 // to compile, instead of the A properties we could get from init/get_property.
582 SystemProperties system_properties_;
583
Andreas Gamped089ca12016-06-27 14:25:30 -0700584 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700585 std::string android_root_;
586 std::string android_data_;
587 std::string boot_classpath_;
588 std::string asec_mountpoint_;
589
Calin Juravlec9e76792018-02-01 14:44:56 +0000590 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800591
592 // Store environment values we need to set.
593 std::vector<std::string> environ_;
594};
595
596OTAPreoptService gOps;
597
598////////////////////////
599// Plug-in functions. //
600////////////////////////
601
602int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800603 return gOps.GetProperty(key, value, default_value);
604}
605
606// Compute the output path of
607bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
608 const char *apk_path,
609 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700610 const char *file_name_start;
611 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800612
613 file_name_start = strrchr(apk_path, '/');
614 if (file_name_start == nullptr) {
615 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
616 return false;
617 }
618 file_name_end = strrchr(file_name_start, '.');
619 if (file_name_end == nullptr) {
620 ALOGE("apk_path '%s' has no extension\n", apk_path);
621 return false;
622 }
623
624 // Calculate file_name
625 file_name_start++; // Move past '/', is valid as file_name_end is valid.
626 size_t file_name_len = file_name_end - file_name_start;
627 std::string file_name(file_name_start, file_name_len);
628
629 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700630 snprintf(path,
631 PKG_PATH_MAX,
632 "%s/%s/%s.odex.%s",
633 oat_dir,
634 instruction_set,
635 file_name.c_str(),
636 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800637 return true;
638}
639
640/*
641 * Computes the odex file for the given apk_path and instruction_set.
642 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
643 *
644 * Returns false if it failed to determine the odex file path.
645 */
646bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
647 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800648 const char *path_end = strrchr(apk_path, '/');
649 if (path_end == nullptr) {
650 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
651 return false;
652 }
653 std::string path_component(apk_path, path_end - apk_path);
654
655 const char *name_begin = path_end + 1;
656 const char *extension_start = strrchr(name_begin, '.');
657 if (extension_start == nullptr) {
658 ALOGE("apk_path '%s' has no extension.\n", apk_path);
659 return false;
660 }
661 std::string name_component(name_begin, extension_start - name_begin);
662
Andreas Gamped089ca12016-06-27 14:25:30 -0700663 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800664 path_component.c_str(),
665 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700666 name_component.c_str(),
667 gOps.GetTargetSlot().c_str());
668 if (new_path.length() >= PKG_PATH_MAX) {
669 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
670 return false;
671 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800672 strcpy(path, new_path.c_str());
673 return true;
674}
675
676bool create_cache_path(char path[PKG_PATH_MAX],
677 const char *src,
678 const char *instruction_set) {
679 size_t srclen = strlen(src);
680
681 /* demand that we are an absolute path */
682 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
683 return false;
684 }
685
686 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
687 return false;
688 }
689
690 std::string from_src = std::string(src + 1);
691 std::replace(from_src.begin(), from_src.end(), '/', '@');
692
693 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700694 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800695 DALVIK_CACHE,
696 instruction_set,
697 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100698 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800699
700 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
701 return false;
702 }
703 strcpy(path, assembled_path.c_str());
704
705 return true;
706}
707
Andreas Gampe73dae112015-11-19 14:12:14 -0800708static int log_callback(int type, const char *fmt, ...) {
709 va_list ap;
710 int priority;
711
712 switch (type) {
713 case SELINUX_WARNING:
714 priority = ANDROID_LOG_WARN;
715 break;
716 case SELINUX_INFO:
717 priority = ANDROID_LOG_INFO;
718 break;
719 default:
720 priority = ANDROID_LOG_ERROR;
721 break;
722 }
723 va_start(ap, fmt);
724 LOG_PRI_VA(priority, "SELinux", fmt, ap);
725 va_end(ap);
726 return 0;
727}
728
729static int otapreopt_main(const int argc, char *argv[]) {
730 int selinux_enabled = (is_selinux_enabled() > 0);
731
732 setenv("ANDROID_LOG_TAGS", "*:v", 1);
733 android::base::InitLogging(argv);
734
Andreas Gampe73dae112015-11-19 14:12:14 -0800735 if (argc < 2) {
736 ALOGE("Expecting parameters");
737 exit(1);
738 }
739
740 union selinux_callback cb;
741 cb.func_log = log_callback;
742 selinux_set_callback(SELINUX_CB_LOG, cb);
743
Andreas Gampe73dae112015-11-19 14:12:14 -0800744 if (selinux_enabled && selinux_status_open(true) < 0) {
745 ALOGE("Could not open selinux status; exiting.\n");
746 exit(1);
747 }
748
749 int ret = android::installd::gOps.Main(argc, argv);
750
751 return ret;
752}
753
754} // namespace installd
755} // namespace android
756
757int main(const int argc, char *argv[]) {
758 return android::installd::otapreopt_main(argc, argv);
759}