blob: a447cda49221c84cc68cead468cc5227e3241bf3 [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),
Jiakai Zhangd03a6e02023-09-01 10:21:27 +0100425 std::string_view(parameters_.compiler_filter)) ==
426 std::end(kAotCompilerFilters)) {
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100427 return false;
428 }
429
430 int dexopt_flags = parameters_.dexopt_flags;
431 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
432 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
433 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
434
435 if (profile_guided) {
436 UniqueFile reference_profile =
437 maybe_open_reference_profile(parameters_.pkgName, parameters_.apk_path,
438 parameters_.profile_name, profile_guided,
439 is_public, parameters_.uid, is_secondary_dex);
440 struct stat sbuf;
441 if (reference_profile.fd() == -1 ||
442 (fstat(reference_profile.fd(), &sbuf) != -1 && sbuf.st_size == 0)) {
443 return false;
444 }
445 }
446
447 return true;
448 }
449
Andreas Gamped089ca12016-06-27 14:25:30 -0700450 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700451 // There's one thing we have to be careful about: we may/will be asked to compile an app
452 // living in the system image. This may be a valid request - if the app wasn't compiled,
453 // e.g., if the system image wasn't large enough to include preopted files. However, the
454 // data we have is from the old system, so the driver (the OTA service) can't actually
455 // know. Thus, we will get requests for apps that have preopted components. To avoid
456 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
457 // simple checks:
458 //
459 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
460 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
461 //
462 // 2) If you replace the name in the apk_path with "oat," does the path exist?
463 // (=have a subdirectory for preopted files)
464 //
465 // If the answer to both is yes, skip the dexopt.
466 //
467 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
468 // be stripped), that's not true for APKs signed outside the build system (so the
469 // jar content must be exactly the same).
470
471 // (This is ugly as it's the only thing where we need to understand the contents
Calin Juravlec9e76792018-02-01 14:44:56 +0000472 // of parameters_, but it beats postponing the decision or using the call-
Andreas Gampe56f79f92016-06-08 15:11:37 -0700473 // backs to do weird things.)
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100474
475 // In addition, no need to preopt for "verify". The existing vdex files in the OTA package
476 // and the /data partition will still be usable after the OTA update is applied.
Calin Juravlec9e76792018-02-01 14:44:56 +0000477 const char* apk_path = parameters_.apk_path;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700478 CHECK(apk_path != nullptr);
Jiakai Zhangdb8c0f92023-08-03 14:55:16 +0100479 if (StartsWith(apk_path, android_root_) || !IsAotCompilation()) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700480 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700481 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700482 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700483 CHECK(EndsWith(path, "/"));
484 path = path + "oat";
485 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800486 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700487 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700488 }
489 }
490 }
491
Andreas Gamped089ca12016-06-27 14:25:30 -0700492 // Another issue is unavailability of files in the new system. If the partition
493 // layout changes, otapreopt_chroot may not know about this. Then files from that
494 // partition will not be available and fail to build. This is problematic, as
495 // this tool will wipe the OTA artifact cache and try again (for robustness after
496 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700497 if (access(apk_path, F_OK) != 0) {
Martin Stjernholm767d9572023-02-22 20:51:57 +0000498 PLOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700499 return true;
500 }
501
502 return false;
503 }
504
Calin Juravlec9e76792018-02-01 14:44:56 +0000505 // Run dexopt with the parameters of parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800506 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700507 int Dexopt() {
Alex Light6c857b72021-02-25 13:37:13 -0800508 std::string error;
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100509
510 int dexopt_flags = parameters_.dexopt_flags;
511 // Make sure dex2oat is run with background priority.
512 dexopt_flags |= DEXOPT_BOOTCOMPLETE | DEXOPT_IDLE_BACKGROUND_JOB;
513
Alex Light6c857b72021-02-25 13:37:13 -0800514 int res = dexopt(parameters_.apk_path,
515 parameters_.uid,
516 parameters_.pkgName,
517 parameters_.instruction_set,
518 parameters_.dexopt_needed,
519 parameters_.oat_dir,
Martin Stjernholm2aea00b2023-08-02 17:44:43 +0100520 dexopt_flags,
Alex Light6c857b72021-02-25 13:37:13 -0800521 parameters_.compiler_filter,
522 parameters_.volume_uuid,
523 parameters_.shared_libraries,
524 parameters_.se_info,
525 parameters_.downgrade,
526 parameters_.target_sdk_version,
527 parameters_.profile_name,
528 parameters_.dex_metadata_path,
529 parameters_.compilation_reason,
530 &error);
531 if (res != 0) {
532 LOG(ERROR) << "During preopt of " << parameters_.apk_path << " got result " << res
533 << " error: " << error;
534 }
535 return res;
Andreas Gampe73dae112015-11-19 14:12:14 -0800536 }
537
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700538 int RunPreopt() {
539 if (ShouldSkipPreopt()) {
540 return 0;
541 }
542
543 int dexopt_result = Dexopt();
544 if (dexopt_result == 0) {
545 return 0;
546 }
547
yangfuteng407697e2022-07-26 15:00:37 +0800548 if (WIFSIGNALED(dexopt_result)) {
549 LOG(WARNING) << "Interrupted by signal " << WTERMSIG(dexopt_result) ;
550 return dexopt_result;
551 }
552
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700553 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
554 // if possible.
Calin Juravlec9e76792018-02-01 14:44:56 +0000555 if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700556 return dexopt_result;
557 }
558
559 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
Calin Juravlec9e76792018-02-01 14:44:56 +0000560 parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700561 return Dexopt();
562 }
563
Andreas Gamped089ca12016-06-27 14:25:30 -0700564 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
565 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
566 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
567 // The index of the instruction-set string inside the package parameters. Needed for
568 // some special-casing that requires knowledge of the instruction-set.
569 static constexpr size_t kISAIndex = 3;
570
Andreas Gampe73dae112015-11-19 14:12:14 -0800571 // Stores the system properties read out of the B partition. We need to use these properties
572 // to compile, instead of the A properties we could get from init/get_property.
573 SystemProperties system_properties_;
574
Andreas Gamped089ca12016-06-27 14:25:30 -0700575 // Some select properties that are always needed.
Andreas Gamped089ca12016-06-27 14:25:30 -0700576 std::string android_root_;
577 std::string android_data_;
578 std::string boot_classpath_;
579 std::string asec_mountpoint_;
580
Calin Juravlec9e76792018-02-01 14:44:56 +0000581 OTAPreoptParameters parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -0800582
583 // Store environment values we need to set.
584 std::vector<std::string> environ_;
585};
586
587OTAPreoptService gOps;
588
589////////////////////////
590// Plug-in functions. //
591////////////////////////
592
593int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800594 return gOps.GetProperty(key, value, default_value);
595}
596
597// Compute the output path of
598bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
599 const char *apk_path,
600 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -0700601 const char *file_name_start;
602 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -0800603
604 file_name_start = strrchr(apk_path, '/');
605 if (file_name_start == nullptr) {
606 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
607 return false;
608 }
609 file_name_end = strrchr(file_name_start, '.');
610 if (file_name_end == nullptr) {
611 ALOGE("apk_path '%s' has no extension\n", apk_path);
612 return false;
613 }
614
615 // Calculate file_name
616 file_name_start++; // Move past '/', is valid as file_name_end is valid.
617 size_t file_name_len = file_name_end - file_name_start;
618 std::string file_name(file_name_start, file_name_len);
619
620 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -0700621 snprintf(path,
622 PKG_PATH_MAX,
623 "%s/%s/%s.odex.%s",
624 oat_dir,
625 instruction_set,
626 file_name.c_str(),
627 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -0800628 return true;
629}
630
631/*
632 * Computes the odex file for the given apk_path and instruction_set.
633 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
634 *
635 * Returns false if it failed to determine the odex file path.
636 */
637bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
638 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800639 const char *path_end = strrchr(apk_path, '/');
640 if (path_end == nullptr) {
641 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
642 return false;
643 }
644 std::string path_component(apk_path, path_end - apk_path);
645
646 const char *name_begin = path_end + 1;
647 const char *extension_start = strrchr(name_begin, '.');
648 if (extension_start == nullptr) {
649 ALOGE("apk_path '%s' has no extension.\n", apk_path);
650 return false;
651 }
652 std::string name_component(name_begin, extension_start - name_begin);
653
Andreas Gamped089ca12016-06-27 14:25:30 -0700654 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -0800655 path_component.c_str(),
656 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -0700657 name_component.c_str(),
658 gOps.GetTargetSlot().c_str());
659 if (new_path.length() >= PKG_PATH_MAX) {
660 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
661 return false;
662 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800663 strcpy(path, new_path.c_str());
664 return true;
665}
666
667bool create_cache_path(char path[PKG_PATH_MAX],
668 const char *src,
669 const char *instruction_set) {
670 size_t srclen = strlen(src);
671
672 /* demand that we are an absolute path */
673 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
674 return false;
675 }
676
677 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
678 return false;
679 }
680
681 std::string from_src = std::string(src + 1);
682 std::replace(from_src.begin(), from_src.end(), '/', '@');
683
684 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -0700685 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -0800686 DALVIK_CACHE,
687 instruction_set,
688 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +0100689 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -0800690
691 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
692 return false;
693 }
694 strcpy(path, assembled_path.c_str());
695
696 return true;
697}
698
Jiakai Zhang6af6b972023-03-13 10:10:18 +0000699bool force_compile_without_image() {
700 // We don't have a boot image anyway. Compile without a boot image.
701 return true;
702}
703
Andreas Gampe73dae112015-11-19 14:12:14 -0800704static int log_callback(int type, const char *fmt, ...) {
705 va_list ap;
706 int priority;
707
708 switch (type) {
709 case SELINUX_WARNING:
710 priority = ANDROID_LOG_WARN;
711 break;
712 case SELINUX_INFO:
713 priority = ANDROID_LOG_INFO;
714 break;
715 default:
716 priority = ANDROID_LOG_ERROR;
717 break;
718 }
719 va_start(ap, fmt);
720 LOG_PRI_VA(priority, "SELinux", fmt, ap);
721 va_end(ap);
722 return 0;
723}
724
725static int otapreopt_main(const int argc, char *argv[]) {
726 int selinux_enabled = (is_selinux_enabled() > 0);
727
728 setenv("ANDROID_LOG_TAGS", "*:v", 1);
729 android::base::InitLogging(argv);
730
Andreas Gampe73dae112015-11-19 14:12:14 -0800731 if (argc < 2) {
732 ALOGE("Expecting parameters");
733 exit(1);
734 }
735
736 union selinux_callback cb;
737 cb.func_log = log_callback;
738 selinux_set_callback(SELINUX_CB_LOG, cb);
739
Andreas Gampe73dae112015-11-19 14:12:14 -0800740 if (selinux_enabled && selinux_status_open(true) < 0) {
741 ALOGE("Could not open selinux status; exiting.\n");
742 exit(1);
743 }
744
745 int ret = android::installd::gOps.Main(argc, argv);
746
747 return ret;
748}
749
750} // namespace installd
751} // namespace android
752
753int main(const int argc, char *argv[]) {
754 return android::installd::otapreopt_main(argc, argv);
755}