blob: 223b17a422f4de5acff6468bfdac2729850f1f95 [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>
29#include <sys/wait.h>
30
31#include <android-base/logging.h>
32#include <android-base/macros.h>
33#include <android-base/stringprintf.h>
Andreas Gampe6db8db92016-06-03 10:22:19 -070034#include <android-base/strings.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080035#include <cutils/fs.h>
Andreas Gampe73dae112015-11-19 14:12:14 -080036#include <cutils/properties.h>
Andreas Gampe54e1a402017-03-20 18:42:49 -070037#include <dex2oat_return_codes.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
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070041#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070042#include "file_parsing.h"
43#include "globals.h"
Andreas Gampec4ced4f2017-04-14 20:39:56 -070044#include "installd_constants.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070045#include "installd_deps.h" // Need to fill in requirements of commands.
46#include "otapreopt_utils.h"
47#include "system_properties.h"
48#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
Andreas Gampe73dae112015-11-19 14:12:14 -080050#ifndef LOG_TAG
51#define LOG_TAG "otapreopt"
52#endif
53
54#define BUFFER_MAX 1024 /* input buffer for commands */
55#define TOKEN_MAX 16 /* max number of arguments in buffer */
56#define REPLY_MAX 256 /* largest reply allowed */
57
Andreas Gampe56f79f92016-06-08 15:11:37 -070058using android::base::EndsWith;
Andreas Gampe6db8db92016-06-03 10:22:19 -070059using android::base::Join;
60using android::base::Split;
Andreas Gampe56f79f92016-06-08 15:11:37 -070061using android::base::StartsWith;
Andreas Gampe73dae112015-11-19 14:12:14 -080062using android::base::StringPrintf;
63
64namespace android {
65namespace installd {
66
Andreas Gampeef21fd22017-05-22 13:36:06 -070067// Check expected values for dexopt flags. If you need to change this:
68//
69// RUN AN A/B OTA TO MAKE SURE THINGS STILL WORK!
70//
71// You most likely need to increase the protocol version and all that entails!
72
73static_assert(DEXOPT_PUBLIC == 1 << 1, "DEXOPT_PUBLIC unexpected.");
74static_assert(DEXOPT_DEBUGGABLE == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
75static_assert(DEXOPT_BOOTCOMPLETE == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
76static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
77static_assert(DEXOPT_SECONDARY_DEX == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
78static_assert(DEXOPT_FORCE == 1 << 6, "DEXOPT_FORCE unexpected.");
79static_assert(DEXOPT_STORAGE_CE == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
80static_assert(DEXOPT_STORAGE_DE == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
David Brazdil52249162018-02-12 18:04:59 -080081static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
82 "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
Andreas Gampeef21fd22017-05-22 13:36:06 -070083
David Brazdil7fcbb812018-01-17 17:05:40 +000084static_assert(DEXOPT_MASK == 0x5fe, "DEXOPT_MASK unexpected.");
Andreas Gampeef21fd22017-05-22 13:36:06 -070085
86
87
Andreas Gampe73dae112015-11-19 14:12:14 -080088template<typename T>
89static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
90 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
91}
92
93template<typename T>
94static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
95 return RoundDown(x + n - 1, n);
96}
97
98class OTAPreoptService {
99 public:
Andreas Gampe73dae112015-11-19 14:12:14 -0800100 // Main driver. Performs the following steps.
101 //
102 // 1) Parse options (read system properties etc from B partition).
103 //
104 // 2) Read in package data.
105 //
106 // 3) Prepare environment variables.
107 //
108 // 4) Prepare(compile) boot image, if necessary.
109 //
110 // 5) Run update.
111 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700112 if (!ReadArguments(argc, argv)) {
113 LOG(ERROR) << "Failed reading command line.";
114 return 1;
115 }
116
Andreas Gampe73dae112015-11-19 14:12:14 -0800117 if (!ReadSystemProperties()) {
118 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700119 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800120 }
121
122 if (!ReadEnvironment()) {
123 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700124 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800125 }
126
Andreas Gamped089ca12016-06-27 14:25:30 -0700127 if (!CheckAndInitializeInstalldGlobals()) {
128 LOG(ERROR) << "Failed initializing globals.";
129 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800130 }
131
132 PrepareEnvironment();
133
Andreas Gamped089ca12016-06-27 14:25:30 -0700134 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800135 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700136 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800137 }
138
139 int dexopt_retcode = RunPreopt();
140
141 return dexopt_retcode;
142 }
143
Andreas Gamped089ca12016-06-27 14:25:30 -0700144 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800145 const std::string* prop_value = system_properties_.GetProperty(key);
146 if (prop_value == nullptr) {
147 if (default_value == nullptr) {
148 return 0;
149 }
150 // Copy in the default value.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600151 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800152 value[kPropertyValueMax - 1] = 0;
153 return strlen(default_value);// TODO: Need to truncate?
154 }
Andreas Gampe7e01b2b2017-09-26 20:41:48 -0700155 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600156 strlcpy(value, prop_value->data(), size);
Andreas Gampe7e01b2b2017-09-26 20:41:48 -0700157 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800158 }
159
Andreas Gamped089ca12016-06-27 14:25:30 -0700160 std::string GetOTADataDirectory() const {
161 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), target_slot_.c_str());
162 }
163
164 const std::string& GetTargetSlot() const {
165 return target_slot_;
166 }
167
Andreas Gampe73dae112015-11-19 14:12:14 -0800168private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700169
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700170 struct Parameters {
171 const char *apk_path;
172 uid_t uid;
173 const char *pkgName;
174 const char *instruction_set;
175 int dexopt_needed;
176 const char* oat_dir;
177 int dexopt_flags;
178 const char* compiler_filter;
179 const char* volume_uuid;
180 const char* shared_libraries;
181 const char* se_info;
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700182 bool downgrade;
David Brazdil570d3982018-01-16 20:15:43 +0000183 int target_sdk_version;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800184 const char* profile_name;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700185 };
186
Andreas Gampe73dae112015-11-19 14:12:14 -0800187 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700188 static constexpr const char* kPropertyFiles[] = {
189 "/default.prop", "/system/build.prop"
190 };
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.
206 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
207 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
208 std::smatch export_match;
209 if (!std::regex_match(line, export_match, export_regex)) {
210 return true;
211 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800212
Andreas Gampe1842af32016-03-16 14:28:50 -0700213 if (export_match.size() != 3) {
214 return true;
215 }
216
217 std::string name = export_match[1].str();
218 std::string value = export_match[2].str();
219
220 system_properties_.SetProperty(name, value);
221
222 return true;
223 });
224 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800225 return false;
226 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700227
Andreas Gamped089ca12016-06-27 14:25:30 -0700228 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
229 return false;
230 }
231 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
232
233 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
234 return false;
235 }
236 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
237
238 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
239 return false;
240 }
241 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
242
243 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
244 return false;
245 }
246 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
247
248 return true;
249 }
250
251 const std::string& GetAndroidData() const {
252 return android_data_;
253 }
254
255 const std::string& GetAndroidRoot() const {
256 return android_root_;
257 }
258
259 const std::string GetOtaDirectoryPrefix() const {
260 return GetAndroidData() + "/ota";
261 }
262
263 bool CheckAndInitializeInstalldGlobals() {
264 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
265 // do not use any datapath that includes this, but we'll still have to set it.
266 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
267 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
268 if (result != 0) {
269 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
270 return false;
271 }
272
273 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
274 LOG(ERROR) << "Could not initialize globals; exiting.";
275 return false;
276 }
277
278 // This is different from the normal installd. We only do the base
279 // directory, the rest will be created on demand when each app is compiled.
280 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
281 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
282 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700283 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800284
285 return true;
286 }
287
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700288 bool ParseBool(const char* in) {
289 if (strcmp(in, "true") == 0) {
290 return true;
291 }
292 return false;
293 }
294
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700295 bool ParseUInt(const char* in, uint32_t* out) {
296 char* end;
297 long long int result = strtoll(in, &end, 0);
298 if (in == end || *end != '\0') {
299 return false;
300 }
301 if (result < std::numeric_limits<uint32_t>::min() ||
302 std::numeric_limits<uint32_t>::max() < result) {
303 return false;
304 }
305 *out = static_cast<uint32_t>(result);
306 return true;
307 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700308
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700309 bool ReadArguments(int argc, char** argv) {
310 // Expected command line:
311 // target-slot [version] dexopt {DEXOPT_PARAMETERS}
Andreas Gamped089ca12016-06-27 14:25:30 -0700312
313 const char* target_slot_arg = argv[1];
314 if (target_slot_arg == nullptr) {
315 LOG(ERROR) << "Missing parameters";
316 return false;
317 }
318 // Sanitize value. Only allow (a-zA-Z0-9_)+.
319 target_slot_ = target_slot_arg;
Andreas Gampefd12eda2016-07-12 09:47:17 -0700320 if (!ValidateTargetSlotSuffix(target_slot_)) {
321 LOG(ERROR) << "Target slot suffix not legal: " << target_slot_;
322 return false;
Andreas Gamped089ca12016-06-27 14:25:30 -0700323 }
324
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700325 // Check for version or "dexopt" next.
326 if (argv[2] == nullptr) {
327 LOG(ERROR) << "Missing parameters";
328 return false;
329 }
330
331 if (std::string("dexopt").compare(argv[2]) == 0) {
332 // This is version 1 (N) or pre-versioning version 2.
333 constexpr int kV2ArgCount = 1 // "otapreopt"
334 + 1 // slot
335 + 1 // "dexopt"
336 + 1 // apk_path
337 + 1 // uid
338 + 1 // pkg
339 + 1 // isa
340 + 1 // dexopt_needed
341 + 1 // oat_dir
342 + 1 // dexopt_flags
343 + 1 // filter
344 + 1 // volume
345 + 1 // libs
Andreas Gampe645e79c2017-04-19 13:58:49 -0700346 + 1; // seinfo
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700347 if (argc == kV2ArgCount) {
348 return ReadArgumentsV2(argc, argv, false);
349 } else {
350 return ReadArgumentsV1(argc, argv);
351 }
352 }
353
354 uint32_t version;
355 if (!ParseUInt(argv[2], &version)) {
356 LOG(ERROR) << "Could not parse version: " << argv[2];
357 return false;
358 }
359
360 switch (version) {
361 case 2:
362 return ReadArgumentsV2(argc, argv, true);
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700363 case 3:
364 return ReadArgumentsV3(argc, argv);
David Brazdil570d3982018-01-16 20:15:43 +0000365 case 4:
366 return ReadArgumentsV4(argc, argv);
Calin Juravle408cd4a2018-01-20 23:34:18 -0800367 case 5:
368 return ReadArgumentsV5(argc, argv);
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700369
370 default:
371 LOG(ERROR) << "Unsupported version " << version;
372 return false;
373 }
374 }
375
376 bool ReadArgumentsV2(int argc ATTRIBUTE_UNUSED, char** argv, bool versioned) {
377 size_t dexopt_index = versioned ? 3 : 2;
378
379 // Check for "dexopt".
380 if (argv[dexopt_index] == nullptr) {
381 LOG(ERROR) << "Missing parameters";
382 return false;
383 }
384 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
385 LOG(ERROR) << "Expected \"dexopt\"";
386 return false;
387 }
388
389 size_t param_index = 0;
390 for (;; ++param_index) {
391 const char* param = argv[dexopt_index + 1 + param_index];
392 if (param == nullptr) {
393 break;
394 }
395
396 switch (param_index) {
397 case 0:
398 package_parameters_.apk_path = param;
399 break;
400
401 case 1:
402 package_parameters_.uid = atoi(param);
403 break;
404
405 case 2:
406 package_parameters_.pkgName = param;
407 break;
408
409 case 3:
410 package_parameters_.instruction_set = param;
411 break;
412
413 case 4:
414 package_parameters_.dexopt_needed = atoi(param);
415 break;
416
417 case 5:
418 package_parameters_.oat_dir = param;
419 break;
420
421 case 6:
422 package_parameters_.dexopt_flags = atoi(param);
423 break;
424
425 case 7:
426 package_parameters_.compiler_filter = param;
427 break;
428
429 case 8:
430 package_parameters_.volume_uuid = ParseNull(param);
431 break;
432
433 case 9:
434 package_parameters_.shared_libraries = ParseNull(param);
435 break;
436
437 case 10:
438 package_parameters_.se_info = ParseNull(param);
439 break;
440
441 default:
442 LOG(ERROR) << "Too many arguments, got " << param;
443 return false;
444 }
445 }
446
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700447 // Set downgrade to false. It is only relevant when downgrading compiler
448 // filter, which is not the case during ota.
449 package_parameters_.downgrade = false;
450
David Brazdil570d3982018-01-16 20:15:43 +0000451 // Set target_sdk_version to 0, ie the platform SDK version. This is
452 // conservative and may force some classes to verify at runtime.
453 package_parameters_.target_sdk_version = 0;
454
Calin Juravle408cd4a2018-01-20 23:34:18 -0800455 // Set the profile name to the primary apk profile.
456 package_parameters_.profile_name = "primary.prof";
457
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700458 if (param_index != 11) {
459 LOG(ERROR) << "Not enough parameters";
460 return false;
461 }
462
463 return true;
464 }
465
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700466 bool ReadArgumentsV3(int argc ATTRIBUTE_UNUSED, char** argv) {
467 size_t dexopt_index = 3;
468
469 // Check for "dexopt".
470 if (argv[dexopt_index] == nullptr) {
471 LOG(ERROR) << "Missing parameters";
472 return false;
473 }
474 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
475 LOG(ERROR) << "Expected \"dexopt\"";
476 return false;
477 }
478
479 size_t param_index = 0;
480 for (;; ++param_index) {
481 const char* param = argv[dexopt_index + 1 + param_index];
482 if (param == nullptr) {
483 break;
484 }
485
486 switch (param_index) {
487 case 0:
488 package_parameters_.apk_path = param;
489 break;
490
491 case 1:
492 package_parameters_.uid = atoi(param);
493 break;
494
495 case 2:
496 package_parameters_.pkgName = param;
497 break;
498
499 case 3:
500 package_parameters_.instruction_set = param;
501 break;
502
503 case 4:
504 package_parameters_.dexopt_needed = atoi(param);
505 break;
506
507 case 5:
508 package_parameters_.oat_dir = param;
509 break;
510
511 case 6:
512 package_parameters_.dexopt_flags = atoi(param);
513 break;
514
515 case 7:
516 package_parameters_.compiler_filter = param;
517 break;
518
519 case 8:
520 package_parameters_.volume_uuid = ParseNull(param);
521 break;
522
523 case 9:
524 package_parameters_.shared_libraries = ParseNull(param);
525 break;
526
527 case 10:
528 package_parameters_.se_info = ParseNull(param);
529 break;
530
531 case 11:
532 package_parameters_.downgrade = ParseBool(param);
533 break;
534
535 default:
536 LOG(ERROR) << "Too many arguments, got " << param;
537 return false;
538 }
539 }
540
David Brazdil570d3982018-01-16 20:15:43 +0000541 // Set target_sdk_version to 0, ie the platform SDK version. This is
542 // conservative and may force some classes to verify at runtime.
543 package_parameters_.target_sdk_version = 0;
544
Calin Juravle408cd4a2018-01-20 23:34:18 -0800545 // Set the profile name to the primary apk profile.
546 package_parameters_.profile_name = "primary.prof";
547
David Brazdil570d3982018-01-16 20:15:43 +0000548 if (param_index != 12) {
549 LOG(ERROR) << "Not enough parameters";
550 return false;
551 }
552
553 return true;
554 }
555
556 bool ReadArgumentsV4(int argc ATTRIBUTE_UNUSED, char** argv) {
557 size_t dexopt_index = 3;
558
559 // Check for "dexopt".
560 if (argv[dexopt_index] == nullptr) {
561 LOG(ERROR) << "Missing parameters";
562 return false;
563 }
564 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
565 LOG(ERROR) << "Expected \"dexopt\"";
566 return false;
567 }
568
569 size_t param_index = 0;
570 for (;; ++param_index) {
571 const char* param = argv[dexopt_index + 1 + param_index];
572 if (param == nullptr) {
573 break;
574 }
575
576 switch (param_index) {
577 case 0:
578 package_parameters_.apk_path = param;
579 break;
580
581 case 1:
582 package_parameters_.uid = atoi(param);
583 break;
584
585 case 2:
586 package_parameters_.pkgName = param;
587 break;
588
589 case 3:
590 package_parameters_.instruction_set = param;
591 break;
592
593 case 4:
594 package_parameters_.dexopt_needed = atoi(param);
595 break;
596
597 case 5:
598 package_parameters_.oat_dir = param;
599 break;
600
601 case 6:
602 package_parameters_.dexopt_flags = atoi(param);
603 break;
604
605 case 7:
606 package_parameters_.compiler_filter = param;
607 break;
608
609 case 8:
610 package_parameters_.volume_uuid = ParseNull(param);
611 break;
612
613 case 9:
614 package_parameters_.shared_libraries = ParseNull(param);
615 break;
616
617 case 10:
618 package_parameters_.se_info = ParseNull(param);
619 break;
620
621 case 11:
622 package_parameters_.downgrade = ParseBool(param);
623 break;
624
625 case 12:
626 package_parameters_.target_sdk_version = atoi(param);
627 break;
628
629 default:
630 LOG(ERROR) << "Too many arguments, got " << param;
631 return false;
632 }
633 }
634
Calin Juravle408cd4a2018-01-20 23:34:18 -0800635 // Set the profile name to the primary apk profile.
636 package_parameters_.profile_name = "primary.prof";
637
David Brazdild9024ef2018-01-18 21:41:41 +0000638 if (param_index != 13) {
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700639 LOG(ERROR) << "Not enough parameters";
640 return false;
641 }
642
643 return true;
644 }
645
Calin Juravle408cd4a2018-01-20 23:34:18 -0800646 // TODO: this pattern does not scale and result in a lot of code duplication.
647 // Either find a better pattern or refactor the code to eliminate the duplication.
648 bool ReadArgumentsV5(int argc ATTRIBUTE_UNUSED, char** argv) {
649 size_t dexopt_index = 3;
650
651 // Check for "dexopt".
652 if (argv[dexopt_index] == nullptr) {
653 LOG(ERROR) << "Missing parameters";
654 return false;
655 }
656 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
657 LOG(ERROR) << "Expected \"dexopt\"";
658 return false;
659 }
660
661 size_t param_index = 0;
662 for (;; ++param_index) {
663 const char* param = argv[dexopt_index + 1 + param_index];
664 if (param == nullptr) {
665 break;
666 }
667
668 switch (param_index) {
669 case 0:
670 package_parameters_.apk_path = param;
671 break;
672
673 case 1:
674 package_parameters_.uid = atoi(param);
675 break;
676
677 case 2:
678 package_parameters_.pkgName = param;
679 break;
680
681 case 3:
682 package_parameters_.instruction_set = param;
683 break;
684
685 case 4:
686 package_parameters_.dexopt_needed = atoi(param);
687 break;
688
689 case 5:
690 package_parameters_.oat_dir = param;
691 break;
692
693 case 6:
694 package_parameters_.dexopt_flags = atoi(param);
695 break;
696
697 case 7:
698 package_parameters_.compiler_filter = param;
699 break;
700
701 case 8:
702 package_parameters_.volume_uuid = ParseNull(param);
703 break;
704
705 case 9:
706 package_parameters_.shared_libraries = ParseNull(param);
707 break;
708
709 case 10:
710 package_parameters_.se_info = ParseNull(param);
711 break;
712
713 case 11:
714 package_parameters_.downgrade = ParseBool(param);
715 break;
716
717 case 12:
718 package_parameters_.target_sdk_version = atoi(param);
719 break;
720
721 case 13:
722 package_parameters_.profile_name = ParseNull(param);
723 break;
724
725 default:
726 LOG(ERROR) << "Too many arguments, got " << param;
727 return false;
728 }
729 }
730
731 if (param_index != 14) {
732 LOG(ERROR) << "Not enough parameters";
733 return false;
734 }
735
736 return true;
737 }
738
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700739 static int ReplaceMask(int input, int old_mask, int new_mask) {
740 return (input & old_mask) != 0 ? new_mask : 0;
741 }
742
743 bool ReadArgumentsV1(int argc ATTRIBUTE_UNUSED, char** argv) {
744 // Check for "dexopt".
Andreas Gamped089ca12016-06-27 14:25:30 -0700745 if (argv[2] == nullptr) {
746 LOG(ERROR) << "Missing parameters";
747 return false;
748 }
749 if (std::string("dexopt").compare(argv[2]) != 0) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700750 LOG(ERROR) << "Expected \"dexopt\"";
Andreas Gamped089ca12016-06-27 14:25:30 -0700751 return false;
752 }
753
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700754 size_t param_index = 0;
755 for (;; ++param_index) {
756 const char* param = argv[3 + param_index];
757 if (param == nullptr) {
758 break;
759 }
760
761 switch (param_index) {
762 case 0:
763 package_parameters_.apk_path = param;
764 break;
765
766 case 1:
767 package_parameters_.uid = atoi(param);
768 break;
769
770 case 2:
771 package_parameters_.pkgName = param;
772 break;
773
774 case 3:
775 package_parameters_.instruction_set = param;
776 break;
777
778 case 4: {
779 // Version 1 had:
780 // DEXOPT_DEX2OAT_NEEDED = 1
781 // DEXOPT_PATCHOAT_NEEDED = 2
782 // DEXOPT_SELF_PATCHOAT_NEEDED = 3
783 // We will simply use DEX2OAT_FROM_SCRATCH.
784 package_parameters_.dexopt_needed = DEX2OAT_FROM_SCRATCH;
785 break;
786 }
787
788 case 5:
789 package_parameters_.oat_dir = param;
790 break;
791
792 case 6: {
793 // Version 1 had:
794 constexpr int OLD_DEXOPT_PUBLIC = 1 << 1;
Nicolas Geoffray2520d442017-05-05 14:32:51 +0100795 // Note: DEXOPT_SAFEMODE has been removed.
796 // constexpr int OLD_DEXOPT_SAFEMODE = 1 << 2;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700797 constexpr int OLD_DEXOPT_DEBUGGABLE = 1 << 3;
798 constexpr int OLD_DEXOPT_BOOTCOMPLETE = 1 << 4;
799 constexpr int OLD_DEXOPT_PROFILE_GUIDED = 1 << 5;
800 constexpr int OLD_DEXOPT_OTA = 1 << 6;
801 int input = atoi(param);
802 package_parameters_.dexopt_flags =
803 ReplaceMask(input, OLD_DEXOPT_PUBLIC, DEXOPT_PUBLIC) |
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700804 ReplaceMask(input, OLD_DEXOPT_DEBUGGABLE, DEXOPT_DEBUGGABLE) |
805 ReplaceMask(input, OLD_DEXOPT_BOOTCOMPLETE, DEXOPT_BOOTCOMPLETE) |
806 ReplaceMask(input, OLD_DEXOPT_PROFILE_GUIDED, DEXOPT_PROFILE_GUIDED) |
807 ReplaceMask(input, OLD_DEXOPT_OTA, 0);
808 break;
809 }
810
811 case 7:
812 package_parameters_.compiler_filter = param;
813 break;
814
815 case 8:
816 package_parameters_.volume_uuid = ParseNull(param);
817 break;
818
819 case 9:
820 package_parameters_.shared_libraries = ParseNull(param);
821 break;
822
823 default:
824 LOG(ERROR) << "Too many arguments, got " << param;
825 return false;
826 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800827 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700828
829 if (param_index != 10) {
830 LOG(ERROR) << "Not enough parameters";
Andreas Gampe73dae112015-11-19 14:12:14 -0800831 return false;
832 }
833
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700834 // Set se_info to null. It is only relevant for secondary dex files, which we won't
835 // receive from a v1 A side.
836 package_parameters_.se_info = nullptr;
837
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700838 // Set downgrade to false. It is only relevant when downgrading compiler
839 // filter, which is not the case during ota.
840 package_parameters_.downgrade = false;
841
David Brazdil570d3982018-01-16 20:15:43 +0000842 // Set target_sdk_version to 0, ie the platform SDK version. This is
843 // conservative and may force some classes to verify at runtime.
844 package_parameters_.target_sdk_version = 0;
845
Calin Juravle408cd4a2018-01-20 23:34:18 -0800846 // Set the profile name to the primary apk profile.
847 package_parameters_.profile_name = "primary.prof";
848
Andreas Gampe73dae112015-11-19 14:12:14 -0800849 return true;
850 }
851
852 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700853 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
854 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
855 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800856
857 for (const std::string& e : environ_) {
858 putenv(const_cast<char*>(e.c_str()));
859 }
860 }
861
862 // Ensure that we have the right boot image. The first time any app is
863 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700864 bool PrepareBootImage(bool force) const {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700865 if (package_parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800866 LOG(ERROR) << "Instruction set missing.";
867 return false;
868 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700869 const char* isa = package_parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800870
871 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700872 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800873 std::string isa_path = dalvik_cache + "/" + isa;
874 std::string art_path = isa_path + "/system@framework@boot.art";
875 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700876 bool cleared = false;
877 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
878 // Files exist, assume everything is alright if not forced. Otherwise clean up.
879 if (!force) {
880 return true;
881 }
882 ClearDirectory(isa_path);
883 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800884 }
885
Andreas Gamped089ca12016-06-27 14:25:30 -0700886 // Reset umask in otapreopt, so that we control the the access for the files we create.
887 umask(0);
888
Andreas Gampe73dae112015-11-19 14:12:14 -0800889 // Create the directories, if necessary.
890 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700891 if (!CreatePath(dalvik_cache)) {
892 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800893 return false;
894 }
895 }
896 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700897 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800898 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
899 return false;
900 }
901 }
902
Andreas Gampe5709b572016-02-12 17:42:59 -0800903 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700904 if (!cleared) {
905 ClearDirectory(isa_path);
906 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800907
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700908 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800909 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
910 return PatchoatBootImage(art_path, isa);
911 } else {
912 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700913 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800914 }
915 }
916
Andreas Gamped089ca12016-06-27 14:25:30 -0700917 static bool CreatePath(const std::string& path) {
918 // Create the given path. Use string processing instead of dirname, as dirname's need for
919 // a writable char buffer is painful.
920
921 // First, try to use the full path.
922 if (mkdir(path.c_str(), 0711) == 0) {
923 return true;
924 }
925 if (errno != ENOENT) {
926 PLOG(ERROR) << "Could not create path " << path;
927 return false;
928 }
929
930 // Now find the parent and try that first.
931 size_t last_slash = path.find_last_of('/');
932 if (last_slash == std::string::npos || last_slash == 0) {
933 PLOG(ERROR) << "Could not create " << path;
934 return false;
935 }
936
937 if (!CreatePath(path.substr(0, last_slash))) {
938 return false;
939 }
940
941 if (mkdir(path.c_str(), 0711) == 0) {
942 return true;
943 }
944 PLOG(ERROR) << "Could not create " << path;
945 return false;
946 }
947
948 static void ClearDirectory(const std::string& dir) {
949 DIR* c_dir = opendir(dir.c_str());
950 if (c_dir == nullptr) {
951 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
952 return;
953 }
954
955 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
956 const char* name = de->d_name;
957 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
958 continue;
959 }
960 // We only want to delete regular files and symbolic links.
961 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
962 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
963 LOG(WARNING) << "Unexpected file "
964 << file
965 << " of type "
966 << std::hex
967 << de->d_type
968 << " encountered.";
969 } else {
970 // Try to unlink the file.
971 if (unlink(file.c_str()) != 0) {
972 PLOG(ERROR) << "Unable to unlink " << file;
973 }
974 }
975 }
976 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
977 }
978
979 bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800980 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
981
982 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700983 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800984
985 cmd.push_back("--input-image-location=/system/framework/boot.art");
986 cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
987
988 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
989
990 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
991 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800992 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800993
994 std::string error_msg;
995 bool result = Exec(cmd, &error_msg);
996 if (!result) {
997 LOG(ERROR) << "Could not generate boot image: " << error_msg;
998 }
999 return result;
1000 }
1001
1002 bool Dex2oatBootImage(const std::string& boot_cp,
1003 const std::string& art_path,
1004 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -07001005 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -08001006 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
1007 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -07001008 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -08001009 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -07001010 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001011 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
1012 }
1013 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
1014
1015 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
1016 ART_BASE_ADDRESS_MAX_DELTA);
1017 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
1018
1019 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
1020
1021 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
1022 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
1023 "-Xms",
1024 true,
1025 cmd);
1026 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
1027 "-Xmx",
1028 true,
1029 cmd);
1030 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
1031 "--compiler-filter=",
1032 false,
1033 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -07001034 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -08001035 // TODO: Compiled-classes.
1036 const std::string* extra_opts =
1037 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
1038 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -07001039 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -08001040 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
1041 }
1042 // TODO: Should we lower this? It's usually set close to max, because
1043 // normally there's not much else going on at boot.
1044 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
1045 "-j",
1046 false,
1047 cmd);
1048 AddCompilerOptionFromSystemProperty(
1049 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
1050 "--instruction-set-variant=",
1051 false,
1052 cmd);
1053 AddCompilerOptionFromSystemProperty(
1054 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
1055 "--instruction-set-features=",
1056 false,
1057 cmd);
1058
1059 std::string error_msg;
1060 bool result = Exec(cmd, &error_msg);
1061 if (!result) {
1062 LOG(ERROR) << "Could not generate boot image: " << error_msg;
1063 }
1064 return result;
1065 }
1066
1067 static const char* ParseNull(const char* arg) {
1068 return (strcmp(arg, "!") == 0) ? nullptr : arg;
1069 }
1070
Andreas Gamped089ca12016-06-27 14:25:30 -07001071 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -07001072 // There's one thing we have to be careful about: we may/will be asked to compile an app
1073 // living in the system image. This may be a valid request - if the app wasn't compiled,
1074 // e.g., if the system image wasn't large enough to include preopted files. However, the
1075 // data we have is from the old system, so the driver (the OTA service) can't actually
1076 // know. Thus, we will get requests for apps that have preopted components. To avoid
1077 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
1078 // simple checks:
1079 //
1080 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
1081 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
1082 //
1083 // 2) If you replace the name in the apk_path with "oat," does the path exist?
1084 // (=have a subdirectory for preopted files)
1085 //
1086 // If the answer to both is yes, skip the dexopt.
1087 //
1088 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
1089 // be stripped), that's not true for APKs signed outside the build system (so the
1090 // jar content must be exactly the same).
1091
1092 // (This is ugly as it's the only thing where we need to understand the contents
1093 // of package_parameters_, but it beats postponing the decision or using the call-
1094 // backs to do weird things.)
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001095 const char* apk_path = package_parameters_.apk_path;
1096 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001097 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001098 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -07001099 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001100 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -07001101 CHECK(EndsWith(path, "/"));
1102 path = path + "oat";
1103 if (access(path.c_str(), F_OK) == 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -07001104 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -07001105 }
1106 }
1107 }
1108
Andreas Gamped089ca12016-06-27 14:25:30 -07001109 // Another issue is unavailability of files in the new system. If the partition
1110 // layout changes, otapreopt_chroot may not know about this. Then files from that
1111 // partition will not be available and fail to build. This is problematic, as
1112 // this tool will wipe the OTA artifact cache and try again (for robustness after
1113 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001114 if (access(apk_path, F_OK) != 0) {
1115 LOG(WARNING) << "Skipping preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -07001116 return true;
1117 }
1118
1119 return false;
1120 }
1121
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001122 // Run dexopt with the parameters of package_parameters_.
Calin Juravle824a64d2018-01-18 20:23:17 -08001123 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001124 int Dexopt() {
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001125 return dexopt(package_parameters_.apk_path,
1126 package_parameters_.uid,
1127 package_parameters_.pkgName,
1128 package_parameters_.instruction_set,
1129 package_parameters_.dexopt_needed,
1130 package_parameters_.oat_dir,
1131 package_parameters_.dexopt_flags,
1132 package_parameters_.compiler_filter,
1133 package_parameters_.volume_uuid,
1134 package_parameters_.shared_libraries,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001135 package_parameters_.se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001136 package_parameters_.downgrade,
Calin Juravle824a64d2018-01-18 20:23:17 -08001137 package_parameters_.target_sdk_version,
Calin Juravle408cd4a2018-01-20 23:34:18 -08001138 package_parameters_.profile_name);
Andreas Gampe73dae112015-11-19 14:12:14 -08001139 }
1140
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001141 int RunPreopt() {
1142 if (ShouldSkipPreopt()) {
1143 return 0;
1144 }
1145
1146 int dexopt_result = Dexopt();
1147 if (dexopt_result == 0) {
1148 return 0;
1149 }
1150
1151 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
1152 // Then regenerate and retry.
1153 if (WEXITSTATUS(dexopt_result) ==
1154 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
1155 if (!PrepareBootImage(/* force */ true)) {
1156 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
1157 << dexopt_result;
1158 return dexopt_result;
1159 }
1160
1161 int dexopt_result_boot_image_retry = Dexopt();
1162 if (dexopt_result_boot_image_retry == 0) {
1163 return 0;
1164 }
1165 }
1166
1167 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
1168 // if possible.
1169 if ((package_parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
1170 return dexopt_result;
1171 }
1172
1173 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
1174 package_parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
1175 return Dexopt();
1176 }
1177
Andreas Gampe73dae112015-11-19 14:12:14 -08001178 ////////////////////////////////////
1179 // Helpers, mostly taken from ART //
1180 ////////////////////////////////////
1181
1182 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -07001183 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -07001184 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -08001185
1186 CHECK_GE(arg_vector.size(), 1U) << command_line;
1187
1188 // Convert the args to char pointers.
1189 const char* program = arg_vector[0].c_str();
1190 std::vector<char*> args;
1191 for (size_t i = 0; i < arg_vector.size(); ++i) {
1192 const std::string& arg = arg_vector[i];
1193 char* arg_str = const_cast<char*>(arg.c_str());
1194 CHECK(arg_str != nullptr) << i;
1195 args.push_back(arg_str);
1196 }
1197 args.push_back(nullptr);
1198
1199 // Fork and exec.
1200 pid_t pid = fork();
1201 if (pid == 0) {
1202 // No allocation allowed between fork and exec.
1203
1204 // Change process groups, so we don't get reaped by ProcessManager.
1205 setpgid(0, 0);
1206
1207 execv(program, &args[0]);
1208
1209 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1210 // _exit to avoid atexit handlers in child.
1211 _exit(1);
1212 } else {
1213 if (pid == -1) {
1214 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1215 command_line.c_str(), strerror(errno));
1216 return false;
1217 }
1218
1219 // wait for subprocess to finish
1220 int status;
1221 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1222 if (got_pid != pid) {
1223 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1224 "wanted %d, got %d: %s",
1225 command_line.c_str(), pid, got_pid, strerror(errno));
1226 return false;
1227 }
1228 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1229 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1230 command_line.c_str());
1231 return false;
1232 }
1233 }
1234 return true;
1235 }
1236
1237 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
1238 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
1239 constexpr size_t kPageSize = PAGE_SIZE;
1240 CHECK_EQ(min_delta % kPageSize, 0u);
1241 CHECK_EQ(max_delta % kPageSize, 0u);
1242 CHECK_LT(min_delta, max_delta);
1243
1244 std::default_random_engine generator;
1245 generator.seed(GetSeed());
1246 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
1247 int32_t r = distribution(generator);
1248 if (r % 2 == 0) {
1249 r = RoundUp(r, kPageSize);
1250 } else {
1251 r = RoundDown(r, kPageSize);
1252 }
1253 CHECK_LE(min_delta, r);
1254 CHECK_GE(max_delta, r);
1255 CHECK_EQ(r % kPageSize, 0u);
1256 return r;
1257 }
1258
1259 static uint64_t GetSeed() {
1260#ifdef __BIONIC__
1261 // Bionic exposes arc4random, use it.
1262 uint64_t random_data;
1263 arc4random_buf(&random_data, sizeof(random_data));
1264 return random_data;
1265#else
1266#error "This is only supposed to run with bionic. Otherwise, implement..."
1267#endif
1268 }
1269
1270 void AddCompilerOptionFromSystemProperty(const char* system_property,
1271 const char* prefix,
1272 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -07001273 std::vector<std::string>& out) const {
1274 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -08001275 if (value != nullptr) {
1276 if (runtime) {
1277 out.push_back("--runtime-arg");
1278 }
1279 if (prefix != nullptr) {
1280 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
1281 } else {
1282 out.push_back(*value);
1283 }
1284 }
1285 }
1286
Andreas Gamped089ca12016-06-27 14:25:30 -07001287 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
1288 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
1289 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
1290 // The index of the instruction-set string inside the package parameters. Needed for
1291 // some special-casing that requires knowledge of the instruction-set.
1292 static constexpr size_t kISAIndex = 3;
1293
Andreas Gampe73dae112015-11-19 14:12:14 -08001294 // Stores the system properties read out of the B partition. We need to use these properties
1295 // to compile, instead of the A properties we could get from init/get_property.
1296 SystemProperties system_properties_;
1297
Andreas Gamped089ca12016-06-27 14:25:30 -07001298 // Some select properties that are always needed.
1299 std::string target_slot_;
1300 std::string android_root_;
1301 std::string android_data_;
1302 std::string boot_classpath_;
1303 std::string asec_mountpoint_;
1304
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001305 Parameters package_parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -08001306
1307 // Store environment values we need to set.
1308 std::vector<std::string> environ_;
1309};
1310
1311OTAPreoptService gOps;
1312
1313////////////////////////
1314// Plug-in functions. //
1315////////////////////////
1316
1317int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001318 return gOps.GetProperty(key, value, default_value);
1319}
1320
1321// Compute the output path of
1322bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
1323 const char *apk_path,
1324 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -07001325 const char *file_name_start;
1326 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -08001327
1328 file_name_start = strrchr(apk_path, '/');
1329 if (file_name_start == nullptr) {
1330 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
1331 return false;
1332 }
1333 file_name_end = strrchr(file_name_start, '.');
1334 if (file_name_end == nullptr) {
1335 ALOGE("apk_path '%s' has no extension\n", apk_path);
1336 return false;
1337 }
1338
1339 // Calculate file_name
1340 file_name_start++; // Move past '/', is valid as file_name_end is valid.
1341 size_t file_name_len = file_name_end - file_name_start;
1342 std::string file_name(file_name_start, file_name_len);
1343
1344 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -07001345 snprintf(path,
1346 PKG_PATH_MAX,
1347 "%s/%s/%s.odex.%s",
1348 oat_dir,
1349 instruction_set,
1350 file_name.c_str(),
1351 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -08001352 return true;
1353}
1354
1355/*
1356 * Computes the odex file for the given apk_path and instruction_set.
1357 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
1358 *
1359 * Returns false if it failed to determine the odex file path.
1360 */
1361bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
1362 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001363 const char *path_end = strrchr(apk_path, '/');
1364 if (path_end == nullptr) {
1365 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
1366 return false;
1367 }
1368 std::string path_component(apk_path, path_end - apk_path);
1369
1370 const char *name_begin = path_end + 1;
1371 const char *extension_start = strrchr(name_begin, '.');
1372 if (extension_start == nullptr) {
1373 ALOGE("apk_path '%s' has no extension.\n", apk_path);
1374 return false;
1375 }
1376 std::string name_component(name_begin, extension_start - name_begin);
1377
Andreas Gamped089ca12016-06-27 14:25:30 -07001378 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -08001379 path_component.c_str(),
1380 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -07001381 name_component.c_str(),
1382 gOps.GetTargetSlot().c_str());
1383 if (new_path.length() >= PKG_PATH_MAX) {
1384 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
1385 return false;
1386 }
Andreas Gampe73dae112015-11-19 14:12:14 -08001387 strcpy(path, new_path.c_str());
1388 return true;
1389}
1390
1391bool create_cache_path(char path[PKG_PATH_MAX],
1392 const char *src,
1393 const char *instruction_set) {
1394 size_t srclen = strlen(src);
1395
1396 /* demand that we are an absolute path */
1397 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
1398 return false;
1399 }
1400
1401 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
1402 return false;
1403 }
1404
1405 std::string from_src = std::string(src + 1);
1406 std::replace(from_src.begin(), from_src.end(), '/', '@');
1407
1408 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -07001409 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -08001410 DALVIK_CACHE,
1411 instruction_set,
1412 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +01001413 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -08001414
1415 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
1416 return false;
1417 }
1418 strcpy(path, assembled_path.c_str());
1419
1420 return true;
1421}
1422
Andreas Gampe73dae112015-11-19 14:12:14 -08001423static int log_callback(int type, const char *fmt, ...) {
1424 va_list ap;
1425 int priority;
1426
1427 switch (type) {
1428 case SELINUX_WARNING:
1429 priority = ANDROID_LOG_WARN;
1430 break;
1431 case SELINUX_INFO:
1432 priority = ANDROID_LOG_INFO;
1433 break;
1434 default:
1435 priority = ANDROID_LOG_ERROR;
1436 break;
1437 }
1438 va_start(ap, fmt);
1439 LOG_PRI_VA(priority, "SELinux", fmt, ap);
1440 va_end(ap);
1441 return 0;
1442}
1443
1444static int otapreopt_main(const int argc, char *argv[]) {
1445 int selinux_enabled = (is_selinux_enabled() > 0);
1446
1447 setenv("ANDROID_LOG_TAGS", "*:v", 1);
1448 android::base::InitLogging(argv);
1449
Andreas Gampe73dae112015-11-19 14:12:14 -08001450 if (argc < 2) {
1451 ALOGE("Expecting parameters");
1452 exit(1);
1453 }
1454
1455 union selinux_callback cb;
1456 cb.func_log = log_callback;
1457 selinux_set_callback(SELINUX_CB_LOG, cb);
1458
Andreas Gampe73dae112015-11-19 14:12:14 -08001459 if (selinux_enabled && selinux_status_open(true) < 0) {
1460 ALOGE("Could not open selinux status; exiting.\n");
1461 exit(1);
1462 }
1463
1464 int ret = android::installd::gOps.Main(argc, argv);
1465
1466 return ret;
1467}
1468
1469} // namespace installd
1470} // namespace android
1471
1472int main(const int argc, char *argv[]) {
1473 return android::installd::otapreopt_main(argc, argv);
1474}