blob: 27ae8f6e6fdbb0a1d977bf57572c2f3be1a59a17 [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
Andreas Gampe73dae112015-11-19 14:12:14 -080017#include <inttypes.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080018#include <selinux/android.h>
19#include <selinux/avc.h>
20#include <stdlib.h>
21#include <string.h>
22#include <sys/capability.h>
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +010023#include <sys/mman.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080024#include <sys/prctl.h>
25#include <sys/stat.h>
yangfuteng407697e2022-07-26 15:00:37 +080026#include <sys/wait.h>
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +010027#include <algorithm>
28#include <iterator>
29#include <limits>
30#include <random>
31#include <regex>
Andreas Gampe73dae112015-11-19 14:12:14 -080032
33#include <android-base/logging.h>
34#include <android-base/macros.h>
35#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070036#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080037#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080038#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070039#include <log/log.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080040#include <private/android_filesystem_config.h>
41
Alex Lightfbdc7262021-04-26 16:48:18 -070042#include "android-base/file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070043#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070044#include "file_parsing.h"
45#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070046#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070047#include "installd_deps.h" // Need to fill in requirements of commands.
Calin Juravlec9e76792018-02-01 14:44:56 +000048#include "otapreopt_parameters.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070049#include "otapreopt_utils.h"
50#include "system_properties.h"
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +010051#include "unique_file.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070052#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070053
Andreas Gampe73dae112015-11-19 14:12:14 -080054#ifndef LOG_TAG
55#define LOG_TAG "otapreopt"
56#endif
57
58#define BUFFER_MAX 1024 /* input buffer for commands */
59#define TOKEN_MAX 16 /* max number of arguments in buffer */
60#define REPLY_MAX 256 /* largest reply allowed */
61
Andreas Gampe56f79f92016-06-08 15:11:37 -070062using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070063using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070064using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080065using android::base::StringPrintf;
66
67namespace android {
68namespace installd {
69
Andreas Gampeef21fd22017-05-22 13:36:06 -070070// Check expected values for dexopt flags. If you need to change this:
71//
72// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
73//
74// You most likely need to increase the protocol version and all that entails!
75
76static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
77static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
78static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
79static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
80static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
81static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
82static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
83static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil22cce5a2018-02-12 18:04:59 -080084static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
85 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Mathieu Chartier351bc942018-03-06 13:55:58 -080086static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
Mathieu Chartierad45a1b2018-03-12 17:55:06 -070087static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070088
Patrick Baumann2271b3e2020-04-14 17:03:00 -070089static_assert(DEXOPT_MASK == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
Andreas Gamped32eec22018-02-28 16:02:51 -080090 "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070091
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +010092constexpr const char* kAotCompilerFilters[]{
93 "space-profile", "space", "speed-profile", "speed", "everything-profile", "everything",
94};
Andreas Gampeef21fd22017-05-22 13:36:06 -070095
Andreas Gampea64a6272018-07-10 10:43:47 -070096template<typename T>
97static constexpr bool IsPowerOfTwo(T x) {
98 static_assert(std::is_integral<T>::value, "T must be integral");
99 // TODO: assert unsigned. There is currently many uses with signed values.
100 return (x & (x - 1)) == 0;
101}
Andreas Gampeef21fd22017-05-22 13:36:06 -0700102
Andreas Gampe73dae112015-11-19 14:12:14 -0800103template<typename T>
104static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
Elliott Hughes0beed272020-07-29 14:28:25 -0700105 return (x & -n);
Andreas Gampe73dae112015-11-19 14:12:14 -0800106}
107
108template<typename T>
109static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
110 return RoundDown(x + n - 1, n);
111}
112
113class OTAPreoptService {
114 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800115 // Main driver. Performs the following steps.
116 //
117 // 1) Parse options (read system properties etc from B partition).
118 //
119 // 2) Read in package data.
120 //
121 // 3) Prepare environment variables.
122 //
123 // 4) Prepare(compile) boot image, if necessary.
124 //
125 // 5) Run update.
126 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700127 if (!ReadArguments(argc, argv)) {
128 LOG(ERROR) << "Failed reading command line.";
129 return 1;
130 }
131
Andreas Gampe73dae112015-11-19 14:12:14 -0800132 if (!ReadSystemProperties()) {
133 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700134 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800135 }
136
137 if (!ReadEnvironment()) {
138 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700139 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800140 }
141
Andreas Gamped089ca12016-06-27 14:25:30 -0700142 if (!CheckAndInitializeInstalldGlobals()) {
143 LOG(ERROR) << "Failed initializing globals.";
144 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800145 }
146
Orion Hodson640cb762020-03-26 09:24:41 +0000147 PrepareEnvironmentVariables();
Andreas Gampe73dae112015-11-19 14:12:14 -0800148
Jiakai Zhang202524b2021-12-22 16:40:52 +0000149 if (!EnsureDalvikCache()) {
150 LOG(ERROR) << "Bad dalvik cache.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700151 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800152 }
153
154 int dexopt_retcode = RunPreopt();
155
156 return dexopt_retcode;
157 }
158
Andreas Gamped089ca12016-06-27 14:25:30 -0700159 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800160 const std::string* prop_value = system_properties_.GetProperty(key);
161 if (prop_value == nullptr) {
162 if (default_value == nullptr) {
163 return 0;
164 }
165 // Copy in the default value.
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600166 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800167 value[kPropertyValueMax - 1] = 0;
168 return strlen(default_value);// TODO: Need to truncate?
169 }
Andreas Gampe5696e632017-09-26 20:41:48 -0700170 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600171 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-09-26 20:41:48 -0700172 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800173 }
174
Andreas Gamped089ca12016-06-27 14:25:30 -0700175 std::string GetOTADataDirectory() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000176 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
Andreas Gamped089ca12016-06-27 14:25:30 -0700177 }
178
179 const std::string& GetTargetSlot() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000180 return parameters_.target_slot;
Andreas Gamped089ca12016-06-27 14:25:30 -0700181 }
182
Andreas Gampe73dae112015-11-19 14:12:14 -0800183private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700184
Andreas Gampe73dae112015-11-19 14:12:14 -0800185 bool ReadSystemProperties() {
Alex Lightc36d0012021-03-03 16:10:12 -0800186 // TODO This file does not have a stable format. It should be read by
187 // code shared by init and otapreopt. See b/181182967#comment80
Andreas Gampe1842af32016-03-16 14:28:50 -0700188 static constexpr const char* kPropertyFiles[] = {
Alex Lightc36d0012021-03-03 16:10:12 -0800189 "/system/build.prop"
Andreas Gampe1842af32016-03-16 14:28:50 -0700190 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800191
Andreas Gampe1842af32016-03-16 14:28:50 -0700192 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
193 if (!system_properties_.Load(kPropertyFiles[i])) {
194 return false;
195 }
196 }
197
198 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800199 }
200
201 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700202 // Parse the environment variables from init.environ.rc, which have the form
203 // export NAME VALUE
204 // For simplicity, don't respect string quotation. The values we are interested in can be
205 // encoded without them.
Alex Lightfbdc7262021-04-26 16:48:18 -0700206 //
207 // init.environ.rc and derive_classpath all have the same format for
208 // environment variable exports (since they are all meant to be read by
209 // init) and can be matched by the same regex.
210
211 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
212 auto parse_results = [&](auto& input) {
213 ParseFile(input, [&](const std::string& line) {
214 std::smatch export_match;
215 if (!std::regex_match(line, export_match, export_regex)) {
216 return true;
217 }
218
219 if (export_match.size() != 3) {
220 return true;
221 }
222
223 std::string name = export_match[1].str();
224 std::string value = export_match[2].str();
225
226 system_properties_.SetProperty(name, value);
227
228 return true;
229 });
230 };
231
Alex Light9c3d87d2021-03-03 16:49:08 -0800232 // TODO Just like with the system-properties above we really should have
233 // common code between init and otapreopt to deal with reading these
234 // things. See b/181182967
Alex Lightfbdc7262021-04-26 16:48:18 -0700235 // There have been a variety of places the various env-vars have been
236 // over the years. Expand or reduce this list as needed.
Alex Light9c3d87d2021-03-03 16:49:08 -0800237 static constexpr const char* kEnvironmentVariableSources[] = {
Alex Lightfbdc7262021-04-26 16:48:18 -0700238 "/init.environ.rc",
Alex Light9c3d87d2021-03-03 16:49:08 -0800239 };
Alex Lightfbdc7262021-04-26 16:48:18 -0700240 // First get everything from the static files.
Alex Light9c3d87d2021-03-03 16:49:08 -0800241 for (const char* env_vars_file : kEnvironmentVariableSources) {
Alex Lightfbdc7262021-04-26 16:48:18 -0700242 parse_results(env_vars_file);
Andreas Gampe73dae112015-11-19 14:12:14 -0800243 }
Alex Lightfbdc7262021-04-26 16:48:18 -0700244
245 // Next get everything from derive_classpath, since we're already in the
246 // chroot it will get the new versions of any dependencies.
247 {
248 android::base::unique_fd fd(memfd_create("derive_classpath_temp", MFD_CLOEXEC));
249 if (!fd.ok()) {
250 LOG(ERROR) << "Unable to create fd for derive_classpath";
251 return false;
252 }
253 std::string memfd_file = StringPrintf("/proc/%d/fd/%d", getpid(), fd.get());
254 std::string error_msg;
255 if (!Exec({"/apex/com.android.sdkext/bin/derive_classpath", memfd_file}, &error_msg)) {
256 PLOG(ERROR) << "Running derive_classpath failed: " << error_msg;
257 return false;
258 }
259 std::ifstream ifs(memfd_file);
260 parse_results(ifs);
261 }
262
Andreas Gamped089ca12016-06-27 14:25:30 -0700263 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
264 return false;
265 }
266 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
267
268 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
269 return false;
270 }
271 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
272
273 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
274 return false;
275 }
276 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
277
278 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
279 return false;
280 }
281 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
282
283 return true;
284 }
285
286 const std::string& GetAndroidData() const {
287 return android_data_;
288 }
289
290 const std::string& GetAndroidRoot() const {
291 return android_root_;
292 }
293
294 const std::string GetOtaDirectoryPrefix() const {
295 return GetAndroidData() + "/ota";
296 }
297
298 bool CheckAndInitializeInstalldGlobals() {
299 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
300 // do not use any datapath that includes this, but we'll still have to set it.
301 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
302 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
303 if (result != 0) {
304 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
305 return false;
306 }
307
308 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
309 LOG(ERROR) << "Could not initialize globals; exiting.";
310 return false;
311 }
312
313 // This is different from the normal installd. We only do the base
314 // directory, the rest will be created on demand when each app is compiled.
315 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
Martin Stjernholm767d9572023-02-22 20:51:57 +0000316 PLOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
Andreas Gamped089ca12016-06-27 14:25:30 -0700317 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700318 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800319
320 return true;
321 }
322
Shubham Ajmera45c87432017-06-22 11:10:27 -0700323 bool ParseBool(const char* in) {
324 if (strcmp(in, "true") == 0) {
325 return true;
326 }
327 return false;
328 }
329
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700330 bool ParseUInt(const char* in, uint32_t* out) {
331 char* end;
332 long long int result = strtoll(in, &end, 0);
333 if (in == end || *end != '\0') {
334 return false;
335 }
336 if (result < std::numeric_limits<uint32_t>::min() ||
337 std::numeric_limits<uint32_t>::max() < result) {
338 return false;
339 }
340 *out = static_cast<uint32_t>(result);
341 return true;
342 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700343
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700344 bool ReadArguments(int argc, char** argv) {
Calin Juravlec9e76792018-02-01 14:44:56 +0000345 return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
Andreas Gampe73dae112015-11-19 14:12:14 -0800346 }
347
Orion Hodson640cb762020-03-26 09:24:41 +0000348 void PrepareEnvironmentVariables() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700349 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
350 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
351 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800352
353 for (const std::string& e : environ_) {
354 putenv(const_cast<char*>(e.c_str()));
355 }
356 }
357
Jiakai Zhang202524b2021-12-22 16:40:52 +0000358 // Ensure that we have the right cache file structures.
359 bool EnsureDalvikCache() const {
Calin Juravlec9e76792018-02-01 14:44:56 +0000360 if (parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800361 LOG(ERROR) << "Instruction set missing.";
362 return false;
363 }
Calin Juravlec9e76792018-02-01 14:44:56 +0000364 const char* isa = parameters_.instruction_set;
Andreas Gamped089ca12016-06-27 14:25:30 -0700365 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800366 std::string isa_path = dalvik_cache + "/" + isa;
Andreas Gampe73dae112015-11-19 14:12:14 -0800367
Andreas Gamped089ca12016-06-27 14:25:30 -0700368 // Reset umask in otapreopt, so that we control the the access for the files we create.
369 umask(0);
370
Andreas Gampe73dae112015-11-19 14:12:14 -0800371 // Create the directories, if necessary.
372 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700373 if (!CreatePath(dalvik_cache)) {
374 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800375 return false;
376 }
377 }
378 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700379 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800380 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
381 return false;
382 }
383 }
384
Orion Hodson640cb762020-03-26 09:24:41 +0000385 return true;
Andreas Gampe5709b572016-02-12 17:42:59 -0800386 }
387
Andreas Gamped089ca12016-06-27 14:25:30 -0700388 static bool CreatePath(const std::string& path) {
389 // Create the given path. Use string processing instead of dirname, as dirname's need for
390 // a writable char buffer is painful.
391
392 // First, try to use the full path.
393 if (mkdir(path.c_str(), 0711) == 0) {
394 return true;
395 }
396 if (errno != ENOENT) {
397 PLOG(ERROR) << "Could not create path " << path;
398 return false;
399 }
400
401 // Now find the parent and try that first.
402 size_t last_slash = path.find_last_of('/');
403 if (last_slash == std::string::npos || last_slash == 0) {
404 PLOG(ERROR) << "Could not create " << path;
405 return false;
406 }
407
408 if (!CreatePath(path.substr(0, last_slash))) {
409 return false;
410 }
411
412 if (mkdir(path.c_str(), 0711) == 0) {
413 return true;
414 }
415 PLOG(ERROR) << "Could not create " << path;
416 return false;
417 }
418
Andreas Gampe73dae112015-11-19 14:12:14 -0800419 static const char* ParseNull(const char* arg) {
420 return (strcmp(arg, "!") == 0) ? nullptr : arg;
421 }
422
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100423 bool IsAotCompilation() const {
424 if (std::find(std::begin(kAotCompilerFilters), std::end(kAotCompilerFilters),
425 parameters_.compiler_filter) == std::end(kAotCompilerFilters)) {
426 return false;
427 }
428
429 int dexopt_flags = parameters_.dexopt_flags;
430 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
431 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
432 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
433
434 if (profile_guided) {
435 UniqueFile reference_profile =
436 maybe_open_reference_profile(parameters_.pkgName, parameters_.apk_path,
437 parameters_.profile_name, profile_guided,
438 is_public, parameters_.uid, is_secondary_dex);
439 struct stat sbuf;
440 if (reference_profile.fd() == -1 ||
441 (fstat(reference_profile.fd(), &sbuf) != -1 && sbuf.st_size == 0)) {
442 return false;
443 }
444 }
445
446 return true;
447 }
448
Andreas Gamped089ca12016-06-27 14:25:30 -0700449 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700450 // There's one thing we have to be careful about: we may/will be asked to compile an app
451 // living in the system image. This may be a valid request - if the app wasn't compiled,
452 // e.g., if the system image wasn't large enough to include preopted files. However, the
453 // data we have is from the old system, so the driver (the OTA service) can't actually
454 // know. Thus, we will get requests for apps that have preopted components. To avoid
455 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
456 // simple checks:
457 //
458 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
459 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
460 //
461 // 2) If you replace the name in the apk_path with "oat," does the path exist?
462 // (=have a subdirectory for preopted files)
463 //
464 // If the answer to both is yes, skip the dexopt.
465 //
466 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
467 // be stripped), that's not true for APKs signed outside the build system (so the
468 // jar content must be exactly the same).
469
470 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000471 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700472 // backs to do weird things.)
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100473
474 // In addition, no need to preopt for "verify". The existing vdex files in the OTA package
475 // and the /data partition will still be usable after the OTA update is applied.
Calin Juravlec9e76792018-02-01 14:44:56 +0000476 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700477 CHECK(apk_path != nullptr);
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100478 if (StartsWith(apk_path, android_root_) || !IsAotCompilation()) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700479 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700480 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700481 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700482 CHECK(EndsWith(path, "/"));
483 path = path + "oat";
484 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800485 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700486 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700487 }
488 }
489 }
490
Andreas Gamped089ca12016-06-27 14:25:30 -0700491 // Another issue is unavailability of files in the new system. If the partition
492 // layout changes, otapreopt_chroot may not know about this. Then files from that
493 // partition will not be available and fail to build. This is problematic, as
494 // this tool will wipe the OTA artifact cache and try again (for robustness after
495 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700496 if (access(apk_path, F_OK) != 0) {
Martin Stjernholm767d9572023-02-22 20:51:57 +0000497 PLOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700498 return true;
499 }
500
501 return false;
502 }
503
Calin Juravlec9e76792018-02-01 14:44:56 +0000504 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800505 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700506 int Dexopt() {
Alex Light6c857b72021-02-25 13:37:13 -0800507 std::string error;
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100508
509 int dexopt_flags = parameters_.dexopt_flags;
510 // Make sure dex2oat is run with background priority.
511 dexopt_flags |= DEXOPT_BOOTCOMPLETE | DEXOPT_IDLE_BACKGROUND_JOB;
512
Alex Light6c857b72021-02-25 13:37:13 -0800513 int res = dexopt(parameters_.apk_path,
514 parameters_.uid,
515 parameters_.pkgName,
516 parameters_.instruction_set,
517 parameters_.dexopt_needed,
518 parameters_.oat_dir,
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100519 dexopt_flags,
Alex Light6c857b72021-02-25 13:37:13 -0800520 parameters_.compiler_filter,
521 parameters_.volume_uuid,
522 parameters_.shared_libraries,
523 parameters_.se_info,
524 parameters_.downgrade,
525 parameters_.target_sdk_version,
526 parameters_.profile_name,
527 parameters_.dex_metadata_path,
528 parameters_.compilation_reason,
529 &error);
530 if (res != 0) {
531 LOG(ERROR) << "During preopt of " << parameters_.apk_path << " got result " << res
532 << " error: " << error;
533 }
534 return res;
Andreas Gampe73dae112015-11-19 14:12:14 -0800535 }
536
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700537 int RunPreopt() {
538 if (ShouldSkipPreopt()) {
539 return 0;
540 }
541
542 int dexopt_result = Dexopt();
543 if (dexopt_result == 0) {
544 return 0;
545 }
546
yangfuteng407697e2022-07-26 15:00:37 +0800547 if (WIFSIGNALED(dexopt_result)) {
548 LOG(WARNING) << "Interrupted by signal " << WTERMSIG(dexopt_result) ;
549 return dexopt_result;
550 }
551
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700552 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
553 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000554 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700555 return dexopt_result;
556 }
557
558 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000559 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700560 return Dexopt();
561 }
562
Andreas Gamped089ca12016-06-27 14:25:30 -0700563 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
564 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
565 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
566 // The index of the instruction-set string inside the package parameters. Needed for
567 // some special-casing that requires knowledge of the instruction-set.
568 static constexpr size_t kISAIndex = 3;
569
Andreas Gampe73dae112015-11-19 14:12:14 -0800570 // Stores the system properties read out of the B partition. We need to use these properties
571 // to compile, instead of the A properties we could get from init/get_property.
572 SystemProperties system_properties_;
573
Andreas Gamped089ca12016-06-27 14:25:30 -0700574 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700575 std::string android_root_;
576 std::string android_data_;
577 std::string boot_classpath_;
578 std::string asec_mountpoint_;
579
Calin Juravlec9e76792018-02-01 14:44:56 +0000580 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800581
582 // Store environment values we need to set.
583 std::vector<std::string> environ_;
584};
585
586OTAPreoptService gOps;
587
588////////////////////////
589// Plug-in functions. //
590////////////////////////
591
592int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800593 return gOps.GetProperty(key, value, default_value);
594}
595
596// Compute the output path of
597bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
598 const char *apk_path,
599 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700600 const char *file_name_start;
601 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800602
603 file_name_start = strrchr(apk_path, '/');
604 if (file_name_start == nullptr) {
605 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
606 return false;
607 }
608 file_name_end = strrchr(file_name_start, '.');
609 if (file_name_end == nullptr) {
610 ALOGE("apk_path '%s' has no extension\n", apk_path);
611 return false;
612 }
613
614 // Calculate file_name
615 file_name_start++; // Move past '/', is valid as file_name_end is valid.
616 size_t file_name_len = file_name_end - file_name_start;
617 std::string file_name(file_name_start, file_name_len);
618
619 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700620 snprintf(path,
621 PKG_PATH_MAX,
622 "%s/%s/%s.odex.%s",
623 oat_dir,
624 instruction_set,
625 file_name.c_str(),
626 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800627 return true;
628}
629
630/*
631 * Computes the odex file for the given apk_path and instruction_set.
632 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
633 *
634 * Returns false if it failed to determine the odex file path.
635 */
636bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
637 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800638 const char *path_end = strrchr(apk_path, '/');
639 if (path_end == nullptr) {
640 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
641 return false;
642 }
643 std::string path_component(apk_path, path_end - apk_path);
644
645 const char *name_begin = path_end + 1;
646 const char *extension_start = strrchr(name_begin, '.');
647 if (extension_start == nullptr) {
648 ALOGE("apk_path '%s' has no extension.\n", apk_path);
649 return false;
650 }
651 std::string name_component(name_begin, extension_start - name_begin);
652
Andreas Gamped089ca12016-06-27 14:25:30 -0700653 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800654 path_component.c_str(),
655 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700656 name_component.c_str(),
657 gOps.GetTargetSlot().c_str());
658 if (new_path.length() >= PKG_PATH_MAX) {
659 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
660 return false;
661 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800662 strcpy(path, new_path.c_str());
663 return true;
664}
665
666bool create_cache_path(char path[PKG_PATH_MAX],
667 const char *src,
668 const char *instruction_set) {
669 size_t srclen = strlen(src);
670
671 /* demand that we are an absolute path */
672 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
673 return false;
674 }
675
676 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
677 return false;
678 }
679
680 std::string from_src = std::string(src + 1);
681 std::replace(from_src.begin(), from_src.end(), '/', '@');
682
683 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700684 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800685 DALVIK_CACHE,
686 instruction_set,
687 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100688 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800689
690 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
691 return false;
692 }
693 strcpy(path, assembled_path.c_str());
694
695 return true;
696}
697
Jiakai Zhang6af6b972023-03-13 10:10:18 +0000698bool force_compile_without_image() {
699 // We don't have a boot image anyway. Compile without a boot image.
700 return true;
701}
702
Andreas Gampe73dae112015-11-19 14:12:14 -0800703static int log_callback(int type, const char *fmt, ...) {
704 va_list ap;
705 int priority;
706
707 switch (type) {
708 case SELINUX_WARNING:
709 priority = ANDROID_LOG_WARN;
710 break;
711 case SELINUX_INFO:
712 priority = ANDROID_LOG_INFO;
713 break;
714 default:
715 priority = ANDROID_LOG_ERROR;
716 break;
717 }
718 va_start(ap, fmt);
719 LOG_PRI_VA(priority, "SELinux", fmt, ap);
720 va_end(ap);
721 return 0;
722}
723
724static int otapreopt_main(const int argc, char *argv[]) {
725 int selinux_enabled = (is_selinux_enabled() > 0);
726
727 setenv("ANDROID_LOG_TAGS", "*:v", 1);
728 android::base::InitLogging(argv);
729
Andreas Gampe73dae112015-11-19 14:12:14 -0800730 if (argc < 2) {
731 ALOGE("Expecting parameters");
732 exit(1);
733 }
734
735 union selinux_callback cb;
736 cb.func_log = log_callback;
737 selinux_set_callback(SELINUX_CB_LOG, cb);
738
Andreas Gampe73dae112015-11-19 14:12:14 -0800739 if (selinux_enabled && selinux_status_open(true) < 0) {
740 ALOGE("Could not open selinux status; exiting.\n");
741 exit(1);
742 }
743
744 int ret = android::installd::gOps.Main(argc, argv);
745
746 return ret;
747}
748
749} // namespace installd
750} // namespace android
751
752int main(const int argc, char *argv[]) {
753 return android::installd::otapreopt_main(argc, argv);
754}