blob: 407cb244e37434cbfbd7003cb3fa3a7fa77680b7 [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>
yangfuteng407697e2022-07-26 15:00:37 +080030#include <sys/wait.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080031
32#include <android-base/logging.h>
33#include <android-base/macros.h>
34#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070035#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080036#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080037#include <cutils/properties.h>
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
Alex Lightfbdc7262021-04-26 16:48:18 -070041#include "android-base/file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070042#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070043#include "file_parsing.h"
44#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070045#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070046#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000047#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070048#include "otapreopt_utils.h"
49#include "system_properties.h"
50#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070051
Andreas Gampe73dae112015-11-19 14:12:14 -080052#ifndef LOG_TAG
53#define LOG_TAG "otapreopt"
54#endif
55
56#define BUFFER_MAX 1024 /* input buffer for commands */
57#define TOKEN_MAX 16 /* max number of arguments in buffer */
58#define REPLY_MAX 256 /* largest reply allowed */
59
Andreas Gampe56f79f92016-06-08 15:11:37 -070060using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070061using android::base::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");
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070085static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070086
Patrick Baumann2271b3e2020-04-14 17:03:00 -070087static_assert(DEXOPT_MASK == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080088 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070089
90
Andreas Gampea64a6272018-07-10 10:43:47 -070091template<typename T>
92static constexpr bool IsPowerOfTwo(T x) {
93 static_assert(std::is_integral<T>::value, "T must be integral");
94 // TODO: assert unsigned. There is currently many uses with signed values.
95 return (x & (x - 1)) == 0;
96}
Andreas Gampeef21fd22017-05-22 13:36:06 -070097
Andreas Gampe73dae112015-11-19 14:12:14 -080098template<typename T>
99static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
Elliott Hughes0beed272020-07-29 14:28:25 -0700100 return (x & -n);
Andreas Gampe73dae112015-11-19 14:12:14 -0800101}
102
103template<typename T>
104static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
105 return RoundDown(x + n - 1, n);
106}
107
108class OTAPreoptService {
109 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800110 // Main driver. Performs the following steps.
111 //
112 // 1) Parse options (read system properties etc from B partition).
113 //
114 // 2) Read in package data.
115 //
116 // 3) Prepare environment variables.
117 //
118 // 4) Prepare(compile) boot image, if necessary.
119 //
120 // 5) Run update.
121 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700122 if (!ReadArguments(argc, argv)) {
123 LOG(ERROR) << "Failed reading command line.";
124 return 1;
125 }
126
Andreas Gampe73dae112015-11-19 14:12:14 -0800127 if (!ReadSystemProperties()) {
128 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700129 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800130 }
131
132 if (!ReadEnvironment()) {
133 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700134 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800135 }
136
Andreas Gamped089ca12016-06-27 14:25:30 -0700137 if (!CheckAndInitializeInstalldGlobals()) {
138 LOG(ERROR) << "Failed initializing globals.";
139 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800140 }
141
Orion Hodson640cb762020-03-26 09:24:41 +0000142 PrepareEnvironmentVariables();
Andreas Gampe73dae112015-11-19 14:12:14 -0800143
Jiakai Zhang202524b2021-12-22 16:40:52 +0000144 if (!EnsureDalvikCache()) {
145 LOG(ERROR) << "Bad dalvik cache.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700146 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800147 }
148
149 int dexopt_retcode = RunPreopt();
150
151 return dexopt_retcode;
152 }
153
Andreas Gamped089ca12016-06-27 14:25:30 -0700154 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800155 const std::string* prop_value = system_properties_.GetProperty(key);
156 if (prop_value == nullptr) {
157 if (default_value == nullptr) {
158 return 0;
159 }
160 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600161 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800162 value[kPropertyValueMax - 1] = 0;
163 return strlen(default_value);// TODO: Need to truncate?
164 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700165 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600166 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700167 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800168 }
169
Andreas Gamped089ca12016-06-27 14:25:30 -0700170 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000171 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700172 }
173
174 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000175 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700176 }
177
Andreas Gampe73dae112015-11-19 14:12:14 -0800178private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700179
Andreas Gampe73dae112015-11-19 14:12:14 -0800180 bool ReadSystemProperties() {
Alex Lightc36d0012021-03-03 16:10:12 -0800181 // TODO This file does not have a stable format. It should be read by
182 // code shared by init and otapreopt. See b/181182967#comment80
Andreas Gampe1842af32016-03-16 14:28:50 -0700183 static constexpr const char* kPropertyFiles[] = {
Alex Lightc36d0012021-03-03 16:10:12 -0800184 "/system/build.prop"
Andreas Gampe1842af32016-03-16 14:28:50 -0700185 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800186
Andreas Gampe1842af32016-03-16 14:28:50 -0700187 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
188 if (!system_properties_.Load(kPropertyFiles[i])) {
189 return false;
190 }
191 }
192
193 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800194 }
195
196 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700197 // Parse the environment variables from init.environ.rc, which have the form
198 // export NAME VALUE
199 // For simplicity, don't respect string quotation. The values we are interested in can be
200 // encoded without them.
Alex Lightfbdc7262021-04-26 16:48:18 -0700201 //
202 // init.environ.rc and derive_classpath all have the same format for
203 // environment variable exports (since they are all meant to be read by
204 // init) and can be matched by the same regex.
205
206 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
207 auto parse_results = [&](auto& input) {
208 ParseFile(input, [&](const std::string& line) {
209 std::smatch export_match;
210 if (!std::regex_match(line, export_match, export_regex)) {
211 return true;
212 }
213
214 if (export_match.size() != 3) {
215 return true;
216 }
217
218 std::string name = export_match[1].str();
219 std::string value = export_match[2].str();
220
221 system_properties_.SetProperty(name, value);
222
223 return true;
224 });
225 };
226
Alex Light9c3d87d2021-03-03 16:49:08 -0800227 // TODO Just like with the system-properties above we really should have
228 // common code between init and otapreopt to deal with reading these
229 // things. See b/181182967
Alex Lightfbdc7262021-04-26 16:48:18 -0700230 // There have been a variety of places the various env-vars have been
231 // over the years. Expand or reduce this list as needed.
Alex Light9c3d87d2021-03-03 16:49:08 -0800232 static constexpr const char* kEnvironmentVariableSources[] = {
Alex Lightfbdc7262021-04-26 16:48:18 -0700233 "/init.environ.rc",
Alex Light9c3d87d2021-03-03 16:49:08 -0800234 };
Alex Lightfbdc7262021-04-26 16:48:18 -0700235 // First get everything from the static files.
Alex Light9c3d87d2021-03-03 16:49:08 -0800236 for (const char* env_vars_file : kEnvironmentVariableSources) {
Alex Lightfbdc7262021-04-26 16:48:18 -0700237 parse_results(env_vars_file);
Andreas Gampe73dae112015-11-19 14:12:14 -0800238 }
Alex Lightfbdc7262021-04-26 16:48:18 -0700239
240 // Next get everything from derive_classpath, since we're already in the
241 // chroot it will get the new versions of any dependencies.
242 {
243 android::base::unique_fd fd(memfd_create("derive_classpath_temp", MFD_CLOEXEC));
244 if (!fd.ok()) {
245 LOG(ERROR) << "Unable to create fd for derive_classpath";
246 return false;
247 }
248 std::string memfd_file = StringPrintf("/proc/%d/fd/%d", getpid(), fd.get());
249 std::string error_msg;
250 if (!Exec({"/apex/com.android.sdkext/bin/derive_classpath", memfd_file}, &error_msg)) {
251 PLOG(ERROR) << "Running derive_classpath failed: " << error_msg;
252 return false;
253 }
254 std::ifstream ifs(memfd_file);
255 parse_results(ifs);
256 }
257
Andreas Gamped089ca12016-06-27 14:25:30 -0700258 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
259 return false;
260 }
261 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
262
263 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
264 return false;
265 }
266 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
267
268 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
269 return false;
270 }
271 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
272
273 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
274 return false;
275 }
276 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
277
278 return true;
279 }
280
281 const std::string& GetAndroidData() const {
282 return android_data_;
283 }
284
285 const std::string& GetAndroidRoot() const {
286 return android_root_;
287 }
288
289 const std::string GetOtaDirectoryPrefix() const {
290 return GetAndroidData() + "/ota";
291 }
292
293 bool CheckAndInitializeInstalldGlobals() {
294 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
295 // do not use any datapath that includes this, but we'll still have to set it.
296 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
297 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
298 if (result != 0) {
299 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
300 return false;
301 }
302
303 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
304 LOG(ERROR) << "Could not initialize globals; exiting.";
305 return false;
306 }
307
308 // This is different from the normal installd. We only do the base
309 // directory, the rest will be created on demand when each app is compiled.
310 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
Martin Stjernholm767d9572023-02-22 20:51:57 +0000311 PLOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
Andreas Gamped089ca12016-06-27 14:25:30 -0700312 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700313 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800314
315 return true;
316 }
317
Shubham Ajmera45c87432017-06-22 11:10:27 -0700318 bool ParseBool(const char* in) {
319 if (strcmp(in, "true") == 0) {
320 return true;
321 }
322 return false;
323 }
324
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700325 bool ParseUInt(const char* in, uint32_t* out) {
326 char* end;
327 long long int result = strtoll(in, &end, 0);
328 if (in == end || *end != '\0') {
329 return false;
330 }
331 if (result < std::numeric_limits<uint32_t>::min() ||
332 std::numeric_limits<uint32_t>::max() < result) {
333 return false;
334 }
335 *out = static_cast<uint32_t>(result);
336 return true;
337 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700338
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700339 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000340 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800341 }
342
Orion Hodson640cb762020-03-26 09:24:41 +0000343 void PrepareEnvironmentVariables() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700344 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
345 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
346 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800347
348 for (const std::string& e : environ_) {
349 putenv(const_cast<char*>(e.c_str()));
350 }
351 }
352
Jiakai Zhang202524b2021-12-22 16:40:52 +0000353 // Ensure that we have the right cache file structures.
354 bool EnsureDalvikCache() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000355 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800356 LOG(ERROR) << "Instruction set missing.";
357 return false;
358 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000359 const char* isa = parameters_.instruction_set;
Andreas Gamped089ca12016-06-27 14:25:30 -0700360 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800361 std::string isa_path = dalvik_cache + "/" + isa;
Andreas Gampe73dae112015-11-19 14:12:14 -0800362
Andreas Gamped089ca12016-06-27 14:25:30 -0700363 // Reset umask in otapreopt, so that we control the the access for the files we create.
364 umask(0);
365
Andreas Gampe73dae112015-11-19 14:12:14 -0800366 // Create the directories, if necessary.
367 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700368 if (!CreatePath(dalvik_cache)) {
369 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800370 return false;
371 }
372 }
373 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700374 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800375 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
376 return false;
377 }
378 }
379
Orion Hodson640cb762020-03-26 09:24:41 +0000380 return true;
Andreas Gampe5709b572016-02-12 17:42:59 -0800381 }
382
Andreas Gamped089ca12016-06-27 14:25:30 -0700383 static bool CreatePath(const std::string& path) {
384 // Create the given path. Use string processing instead of dirname, as dirname's need for
385 // a writable char buffer is painful.
386
387 // First, try to use the full path.
388 if (mkdir(path.c_str(), 0711) == 0) {
389 return true;
390 }
391 if (errno != ENOENT) {
392 PLOG(ERROR) << "Could not create path " << path;
393 return false;
394 }
395
396 // Now find the parent and try that first.
397 size_t last_slash = path.find_last_of('/');
398 if (last_slash == std::string::npos || last_slash == 0) {
399 PLOG(ERROR) << "Could not create " << path;
400 return false;
401 }
402
403 if (!CreatePath(path.substr(0, last_slash))) {
404 return false;
405 }
406
407 if (mkdir(path.c_str(), 0711) == 0) {
408 return true;
409 }
410 PLOG(ERROR) << "Could not create " << path;
411 return false;
412 }
413
Andreas Gampe73dae112015-11-19 14:12:14 -0800414 static const char* ParseNull(const char* arg) {
415 return (strcmp(arg, "!") == 0) ? nullptr : arg;
416 }
417
Andreas Gamped089ca12016-06-27 14:25:30 -0700418 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700419 // There's one thing we have to be careful about: we may/will be asked to compile an app
420 // living in the system image. This may be a valid request - if the app wasn't compiled,
421 // e.g., if the system image wasn't large enough to include preopted files. However, the
422 // data we have is from the old system, so the driver (the OTA service) can't actually
423 // know. Thus, we will get requests for apps that have preopted components. To avoid
424 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
425 // simple checks:
426 //
427 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
428 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
429 //
430 // 2) If you replace the name in the apk_path with "oat," does the path exist?
431 // (=have a subdirectory for preopted files)
432 //
433 // If the answer to both is yes, skip the dexopt.
434 //
435 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
436 // be stripped), that's not true for APKs signed outside the build system (so the
437 // jar content must be exactly the same).
438
439 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000440 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700441 // backs to do weird things.)
Calin Juravlec9e76792018-02-01 14:44:56 +0000442 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700443 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800444 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700445 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700446 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700447 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700448 CHECK(EndsWith(path, "/"));
449 path = path + "oat";
450 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800451 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700452 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700453 }
454 }
455 }
456
Andreas Gamped089ca12016-06-27 14:25:30 -0700457 // Another issue is unavailability of files in the new system. If the partition
458 // layout changes, otapreopt_chroot may not know about this. Then files from that
459 // partition will not be available and fail to build. This is problematic, as
460 // this tool will wipe the OTA artifact cache and try again (for robustness after
461 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700462 if (access(apk_path, F_OK) != 0) {
Martin Stjernholm767d9572023-02-22 20:51:57 +0000463 PLOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700464 return true;
465 }
466
467 return false;
468 }
469
Calin Juravlec9e76792018-02-01 14:44:56 +0000470 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800471 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700472 int Dexopt() {
Alex Light6c857b72021-02-25 13:37:13 -0800473 std::string error;
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100474
475 int dexopt_flags = parameters_.dexopt_flags;
476 // Make sure dex2oat is run with background priority.
477 dexopt_flags |= DEXOPT_BOOTCOMPLETE | DEXOPT_IDLE_BACKGROUND_JOB;
478
Alex Light6c857b72021-02-25 13:37:13 -0800479 int res = dexopt(parameters_.apk_path,
480 parameters_.uid,
481 parameters_.pkgName,
482 parameters_.instruction_set,
483 parameters_.dexopt_needed,
484 parameters_.oat_dir,
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100485 dexopt_flags,
Alex Light6c857b72021-02-25 13:37:13 -0800486 parameters_.compiler_filter,
487 parameters_.volume_uuid,
488 parameters_.shared_libraries,
489 parameters_.se_info,
490 parameters_.downgrade,
491 parameters_.target_sdk_version,
492 parameters_.profile_name,
493 parameters_.dex_metadata_path,
494 parameters_.compilation_reason,
495 &error);
496 if (res != 0) {
497 LOG(ERROR) << "During preopt of " << parameters_.apk_path << " got result " << res
498 << " error: " << error;
499 }
500 return res;
Andreas Gampe73dae112015-11-19 14:12:14 -0800501 }
502
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700503 int RunPreopt() {
504 if (ShouldSkipPreopt()) {
505 return 0;
506 }
507
508 int dexopt_result = Dexopt();
509 if (dexopt_result == 0) {
510 return 0;
511 }
512
yangfuteng407697e2022-07-26 15:00:37 +0800513 if (WIFSIGNALED(dexopt_result)) {
514 LOG(WARNING) << "Interrupted by signal " << WTERMSIG(dexopt_result) ;
515 return dexopt_result;
516 }
517
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700518 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
519 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000520 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700521 return dexopt_result;
522 }
523
524 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000525 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700526 return Dexopt();
527 }
528
Andreas Gampe73dae112015-11-19 14:12:14 -0800529 ////////////////////////////////////
530 // Helpers, mostly taken from ART //
531 ////////////////////////////////////
532
Andreas Gampe73dae112015-11-19 14:12:14 -0800533 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
534 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
535 constexpr size_t kPageSize = PAGE_SIZE;
Elliott Hughes0beed272020-07-29 14:28:25 -0700536 static_assert(IsPowerOfTwo(kPageSize), "page size must be power of two");
Andreas Gampe73dae112015-11-19 14:12:14 -0800537 CHECK_EQ(min_delta % kPageSize, 0u);
538 CHECK_EQ(max_delta % kPageSize, 0u);
539 CHECK_LT(min_delta, max_delta);
540
541 std::default_random_engine generator;
542 generator.seed(GetSeed());
543 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
544 int32_t r = distribution(generator);
545 if (r % 2 == 0) {
546 r = RoundUp(r, kPageSize);
547 } else {
548 r = RoundDown(r, kPageSize);
549 }
550 CHECK_LE(min_delta, r);
551 CHECK_GE(max_delta, r);
552 CHECK_EQ(r % kPageSize, 0u);
553 return r;
554 }
555
556 static uint64_t GetSeed() {
557#ifdef __BIONIC__
558 // Bionic exposes arc4random, use it.
559 uint64_t random_data;
560 arc4random_buf(&random_data, sizeof(random_data));
561 return random_data;
562#else
563#error "This is only supposed to run with bionic. Otherwise, implement..."
564#endif
565 }
566
567 void AddCompilerOptionFromSystemProperty(const char* system_property,
568 const char* prefix,
569 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -0700570 std::vector<std::string>& out) const {
571 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -0800572 if (value != nullptr) {
573 if (runtime) {
574 out.push_back("--runtime-arg");
575 }
576 if (prefix != nullptr) {
577 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
578 } else {
579 out.push_back(*value);
580 }
581 }
582 }
583
Andreas Gamped089ca12016-06-27 14:25:30 -0700584 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
585 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
586 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
587 // The index of the instruction-set string inside the package parameters. Needed for
588 // some special-casing that requires knowledge of the instruction-set.
589 static constexpr size_t kISAIndex = 3;
590
Andreas Gampe73dae112015-11-19 14:12:14 -0800591 // Stores the system properties read out of the B partition. We need to use these properties
592 // to compile, instead of the A properties we could get from init/get_property.
593 SystemProperties system_properties_;
594
Andreas Gamped089ca12016-06-27 14:25:30 -0700595 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700596 std::string android_root_;
597 std::string android_data_;
598 std::string boot_classpath_;
599 std::string asec_mountpoint_;
600
Calin Juravlec9e76792018-02-01 14:44:56 +0000601 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800602
603 // Store environment values we need to set.
604 std::vector<std::string> environ_;
605};
606
607OTAPreoptService gOps;
608
609////////////////////////
610// Plug-in functions. //
611////////////////////////
612
613int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800614 return gOps.GetProperty(key, value, default_value);
615}
616
617// Compute the output path of
618bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
619 const char *apk_path,
620 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700621 const char *file_name_start;
622 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800623
624 file_name_start = strrchr(apk_path, '/');
625 if (file_name_start == nullptr) {
626 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
627 return false;
628 }
629 file_name_end = strrchr(file_name_start, '.');
630 if (file_name_end == nullptr) {
631 ALOGE("apk_path '%s' has no extension\n", apk_path);
632 return false;
633 }
634
635 // Calculate file_name
636 file_name_start++; // Move past '/', is valid as file_name_end is valid.
637 size_t file_name_len = file_name_end - file_name_start;
638 std::string file_name(file_name_start, file_name_len);
639
640 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700641 snprintf(path,
642 PKG_PATH_MAX,
643 "%s/%s/%s.odex.%s",
644 oat_dir,
645 instruction_set,
646 file_name.c_str(),
647 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800648 return true;
649}
650
651/*
652 * Computes the odex file for the given apk_path and instruction_set.
653 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
654 *
655 * Returns false if it failed to determine the odex file path.
656 */
657bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
658 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800659 const char *path_end = strrchr(apk_path, '/');
660 if (path_end == nullptr) {
661 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
662 return false;
663 }
664 std::string path_component(apk_path, path_end - apk_path);
665
666 const char *name_begin = path_end + 1;
667 const char *extension_start = strrchr(name_begin, '.');
668 if (extension_start == nullptr) {
669 ALOGE("apk_path '%s' has no extension.\n", apk_path);
670 return false;
671 }
672 std::string name_component(name_begin, extension_start - name_begin);
673
Andreas Gamped089ca12016-06-27 14:25:30 -0700674 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800675 path_component.c_str(),
676 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700677 name_component.c_str(),
678 gOps.GetTargetSlot().c_str());
679 if (new_path.length() >= PKG_PATH_MAX) {
680 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
681 return false;
682 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800683 strcpy(path, new_path.c_str());
684 return true;
685}
686
687bool create_cache_path(char path[PKG_PATH_MAX],
688 const char *src,
689 const char *instruction_set) {
690 size_t srclen = strlen(src);
691
692 /* demand that we are an absolute path */
693 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
694 return false;
695 }
696
697 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
698 return false;
699 }
700
701 std::string from_src = std::string(src + 1);
702 std::replace(from_src.begin(), from_src.end(), '/', '@');
703
704 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700705 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800706 DALVIK_CACHE,
707 instruction_set,
708 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100709 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800710
711 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
712 return false;
713 }
714 strcpy(path, assembled_path.c_str());
715
716 return true;
717}
718
Jiakai Zhang6af6b972023-03-13 10:10:18 +0000719bool force_compile_without_image() {
720 // We don't have a boot image anyway. Compile without a boot image.
721 return true;
722}
723
Andreas Gampe73dae112015-11-19 14:12:14 -0800724static int log_callback(int type, const char *fmt, ...) {
725 va_list ap;
726 int priority;
727
728 switch (type) {
729 case SELINUX_WARNING:
730 priority = ANDROID_LOG_WARN;
731 break;
732 case SELINUX_INFO:
733 priority = ANDROID_LOG_INFO;
734 break;
735 default:
736 priority = ANDROID_LOG_ERROR;
737 break;
738 }
739 va_start(ap, fmt);
740 LOG_PRI_VA(priority, "SELinux", fmt, ap);
741 va_end(ap);
742 return 0;
743}
744
745static int otapreopt_main(const int argc, char *argv[]) {
746 int selinux_enabled = (is_selinux_enabled() > 0);
747
748 setenv("ANDROID_LOG_TAGS", "*:v", 1);
749 android::base::InitLogging(argv);
750
Andreas Gampe73dae112015-11-19 14:12:14 -0800751 if (argc < 2) {
752 ALOGE("Expecting parameters");
753 exit(1);
754 }
755
756 union selinux_callback cb;
757 cb.func_log = log_callback;
758 selinux_set_callback(SELINUX_CB_LOG, cb);
759
Andreas Gampe73dae112015-11-19 14:12:14 -0800760 if (selinux_enabled && selinux_status_open(true) < 0) {
761 ALOGE("Could not open selinux status; exiting.\n");
762 exit(1);
763 }
764
765 int ret = android::installd::gOps.Main(argc, argv);
766
767 return ret;
768}
769
770} // namespace installd
771} // namespace android
772
773int main(const int argc, char *argv[]) {
774 return android::installd::otapreopt_main(argc, argv);
775}