blob: 3e5e832db2e9a6c927edb0a36c9c3c9888a609ad [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 Brazdil7fcbb812018-01-17 17:05:40 +000081static_assert(DEXOPT_DISABLE_HIDDEN_API_CHECKS == 1 << 10,
82 "DEXOPT_DISABLE_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 Sharkey1b9d9a62017-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 Gampe5696e632017-09-26 20:41:48 -0700155 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600156 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-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 Ajmera45c87432017-06-22 11:10:27 -0700182 bool downgrade;
David Brazdil570d3982018-01-16 20:15:43 +0000183 int target_sdk_version;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700184 };
185
Andreas Gampe73dae112015-11-19 14:12:14 -0800186 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700187 static constexpr const char* kPropertyFiles[] = {
188 "/default.prop", "/system/build.prop"
189 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800190
Andreas Gampe1842af32016-03-16 14:28:50 -0700191 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
192 if (!system_properties_.Load(kPropertyFiles[i])) {
193 return false;
194 }
195 }
196
197 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800198 }
199
200 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700201 // Parse the environment variables from init.environ.rc, which have the form
202 // export NAME VALUE
203 // For simplicity, don't respect string quotation. The values we are interested in can be
204 // encoded without them.
205 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
206 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
207 std::smatch export_match;
208 if (!std::regex_match(line, export_match, export_regex)) {
209 return true;
210 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800211
Andreas Gampe1842af32016-03-16 14:28:50 -0700212 if (export_match.size() != 3) {
213 return true;
214 }
215
216 std::string name = export_match[1].str();
217 std::string value = export_match[2].str();
218
219 system_properties_.SetProperty(name, value);
220
221 return true;
222 });
223 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800224 return false;
225 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700226
Andreas Gamped089ca12016-06-27 14:25:30 -0700227 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
228 return false;
229 }
230 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
231
232 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
233 return false;
234 }
235 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
236
237 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
238 return false;
239 }
240 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
241
242 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
243 return false;
244 }
245 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
246
247 return true;
248 }
249
250 const std::string& GetAndroidData() const {
251 return android_data_;
252 }
253
254 const std::string& GetAndroidRoot() const {
255 return android_root_;
256 }
257
258 const std::string GetOtaDirectoryPrefix() const {
259 return GetAndroidData() + "/ota";
260 }
261
262 bool CheckAndInitializeInstalldGlobals() {
263 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
264 // do not use any datapath that includes this, but we'll still have to set it.
265 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
266 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
267 if (result != 0) {
268 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
269 return false;
270 }
271
272 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
273 LOG(ERROR) << "Could not initialize globals; exiting.";
274 return false;
275 }
276
277 // This is different from the normal installd. We only do the base
278 // directory, the rest will be created on demand when each app is compiled.
279 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
280 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
281 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700282 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800283
284 return true;
285 }
286
Shubham Ajmera45c87432017-06-22 11:10:27 -0700287 bool ParseBool(const char* in) {
288 if (strcmp(in, "true") == 0) {
289 return true;
290 }
291 return false;
292 }
293
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700294 bool ParseUInt(const char* in, uint32_t* out) {
295 char* end;
296 long long int result = strtoll(in, &end, 0);
297 if (in == end || *end != '\0') {
298 return false;
299 }
300 if (result < std::numeric_limits<uint32_t>::min() ||
301 std::numeric_limits<uint32_t>::max() < result) {
302 return false;
303 }
304 *out = static_cast<uint32_t>(result);
305 return true;
306 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700307
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700308 bool ReadArguments(int argc, char** argv) {
309 // Expected command line:
310 // target-slot [version] dexopt {DEXOPT_PARAMETERS}
Andreas Gamped089ca12016-06-27 14:25:30 -0700311
312 const char* target_slot_arg = argv[1];
313 if (target_slot_arg == nullptr) {
314 LOG(ERROR) << "Missing parameters";
315 return false;
316 }
317 // Sanitize value. Only allow (a-zA-Z0-9_)+.
318 target_slot_ = target_slot_arg;
Andreas Gampefd12eda2016-07-12 09:47:17 -0700319 if (!ValidateTargetSlotSuffix(target_slot_)) {
320 LOG(ERROR) << "Target slot suffix not legal: " << target_slot_;
321 return false;
Andreas Gamped089ca12016-06-27 14:25:30 -0700322 }
323
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700324 // Check for version or "dexopt" next.
325 if (argv[2] == nullptr) {
326 LOG(ERROR) << "Missing parameters";
327 return false;
328 }
329
330 if (std::string("dexopt").compare(argv[2]) == 0) {
331 // This is version 1 (N) or pre-versioning version 2.
332 constexpr int kV2ArgCount = 1 // "otapreopt"
333 + 1 // slot
334 + 1 // "dexopt"
335 + 1 // apk_path
336 + 1 // uid
337 + 1 // pkg
338 + 1 // isa
339 + 1 // dexopt_needed
340 + 1 // oat_dir
341 + 1 // dexopt_flags
342 + 1 // filter
343 + 1 // volume
344 + 1 // libs
Andreas Gampe645e79c2017-04-19 13:58:49 -0700345 + 1; // seinfo
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700346 if (argc == kV2ArgCount) {
347 return ReadArgumentsV2(argc, argv, false);
348 } else {
349 return ReadArgumentsV1(argc, argv);
350 }
351 }
352
353 uint32_t version;
354 if (!ParseUInt(argv[2], &version)) {
355 LOG(ERROR) << "Could not parse version: " << argv[2];
356 return false;
357 }
358
359 switch (version) {
360 case 2:
361 return ReadArgumentsV2(argc, argv, true);
Shubham Ajmera45c87432017-06-22 11:10:27 -0700362 case 3:
363 return ReadArgumentsV3(argc, argv);
David Brazdil570d3982018-01-16 20:15:43 +0000364 case 4:
365 return ReadArgumentsV4(argc, argv);
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700366
367 default:
368 LOG(ERROR) << "Unsupported version " << version;
369 return false;
370 }
371 }
372
373 bool ReadArgumentsV2(int argc ATTRIBUTE_UNUSED, char** argv, bool versioned) {
374 size_t dexopt_index = versioned ? 3 : 2;
375
376 // Check for "dexopt".
377 if (argv[dexopt_index] == nullptr) {
378 LOG(ERROR) << "Missing parameters";
379 return false;
380 }
381 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
382 LOG(ERROR) << "Expected \"dexopt\"";
383 return false;
384 }
385
386 size_t param_index = 0;
387 for (;; ++param_index) {
388 const char* param = argv[dexopt_index + 1 + param_index];
389 if (param == nullptr) {
390 break;
391 }
392
393 switch (param_index) {
394 case 0:
395 package_parameters_.apk_path = param;
396 break;
397
398 case 1:
399 package_parameters_.uid = atoi(param);
400 break;
401
402 case 2:
403 package_parameters_.pkgName = param;
404 break;
405
406 case 3:
407 package_parameters_.instruction_set = param;
408 break;
409
410 case 4:
411 package_parameters_.dexopt_needed = atoi(param);
412 break;
413
414 case 5:
415 package_parameters_.oat_dir = param;
416 break;
417
418 case 6:
419 package_parameters_.dexopt_flags = atoi(param);
420 break;
421
422 case 7:
423 package_parameters_.compiler_filter = param;
424 break;
425
426 case 8:
427 package_parameters_.volume_uuid = ParseNull(param);
428 break;
429
430 case 9:
431 package_parameters_.shared_libraries = ParseNull(param);
432 break;
433
434 case 10:
435 package_parameters_.se_info = ParseNull(param);
436 break;
437
438 default:
439 LOG(ERROR) << "Too many arguments, got " << param;
440 return false;
441 }
442 }
443
Shubham Ajmera45c87432017-06-22 11:10:27 -0700444 // Set downgrade to false. It is only relevant when downgrading compiler
445 // filter, which is not the case during ota.
446 package_parameters_.downgrade = false;
447
David Brazdil570d3982018-01-16 20:15:43 +0000448 // Set target_sdk_version to 0, ie the platform SDK version. This is
449 // conservative and may force some classes to verify at runtime.
450 package_parameters_.target_sdk_version = 0;
451
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700452 if (param_index != 11) {
453 LOG(ERROR) << "Not enough parameters";
454 return false;
455 }
456
457 return true;
458 }
459
Shubham Ajmera45c87432017-06-22 11:10:27 -0700460 bool ReadArgumentsV3(int argc ATTRIBUTE_UNUSED, char** argv) {
461 size_t dexopt_index = 3;
462
463 // Check for "dexopt".
464 if (argv[dexopt_index] == nullptr) {
465 LOG(ERROR) << "Missing parameters";
466 return false;
467 }
468 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
469 LOG(ERROR) << "Expected \"dexopt\"";
470 return false;
471 }
472
473 size_t param_index = 0;
474 for (;; ++param_index) {
475 const char* param = argv[dexopt_index + 1 + param_index];
476 if (param == nullptr) {
477 break;
478 }
479
480 switch (param_index) {
481 case 0:
482 package_parameters_.apk_path = param;
483 break;
484
485 case 1:
486 package_parameters_.uid = atoi(param);
487 break;
488
489 case 2:
490 package_parameters_.pkgName = param;
491 break;
492
493 case 3:
494 package_parameters_.instruction_set = param;
495 break;
496
497 case 4:
498 package_parameters_.dexopt_needed = atoi(param);
499 break;
500
501 case 5:
502 package_parameters_.oat_dir = param;
503 break;
504
505 case 6:
506 package_parameters_.dexopt_flags = atoi(param);
507 break;
508
509 case 7:
510 package_parameters_.compiler_filter = param;
511 break;
512
513 case 8:
514 package_parameters_.volume_uuid = ParseNull(param);
515 break;
516
517 case 9:
518 package_parameters_.shared_libraries = ParseNull(param);
519 break;
520
521 case 10:
522 package_parameters_.se_info = ParseNull(param);
523 break;
524
525 case 11:
526 package_parameters_.downgrade = ParseBool(param);
527 break;
528
529 default:
530 LOG(ERROR) << "Too many arguments, got " << param;
531 return false;
532 }
533 }
534
David Brazdil570d3982018-01-16 20:15:43 +0000535 // Set target_sdk_version to 0, ie the platform SDK version. This is
536 // conservative and may force some classes to verify at runtime.
537 package_parameters_.target_sdk_version = 0;
538
539 if (param_index != 12) {
540 LOG(ERROR) << "Not enough parameters";
541 return false;
542 }
543
544 return true;
545 }
546
547 bool ReadArgumentsV4(int argc ATTRIBUTE_UNUSED, char** argv) {
548 size_t dexopt_index = 3;
549
550 // Check for "dexopt".
551 if (argv[dexopt_index] == nullptr) {
552 LOG(ERROR) << "Missing parameters";
553 return false;
554 }
555 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
556 LOG(ERROR) << "Expected \"dexopt\"";
557 return false;
558 }
559
560 size_t param_index = 0;
561 for (;; ++param_index) {
562 const char* param = argv[dexopt_index + 1 + param_index];
563 if (param == nullptr) {
564 break;
565 }
566
567 switch (param_index) {
568 case 0:
569 package_parameters_.apk_path = param;
570 break;
571
572 case 1:
573 package_parameters_.uid = atoi(param);
574 break;
575
576 case 2:
577 package_parameters_.pkgName = param;
578 break;
579
580 case 3:
581 package_parameters_.instruction_set = param;
582 break;
583
584 case 4:
585 package_parameters_.dexopt_needed = atoi(param);
586 break;
587
588 case 5:
589 package_parameters_.oat_dir = param;
590 break;
591
592 case 6:
593 package_parameters_.dexopt_flags = atoi(param);
594 break;
595
596 case 7:
597 package_parameters_.compiler_filter = param;
598 break;
599
600 case 8:
601 package_parameters_.volume_uuid = ParseNull(param);
602 break;
603
604 case 9:
605 package_parameters_.shared_libraries = ParseNull(param);
606 break;
607
608 case 10:
609 package_parameters_.se_info = ParseNull(param);
610 break;
611
612 case 11:
613 package_parameters_.downgrade = ParseBool(param);
614 break;
615
616 case 12:
617 package_parameters_.target_sdk_version = atoi(param);
618 break;
619
620 default:
621 LOG(ERROR) << "Too many arguments, got " << param;
622 return false;
623 }
624 }
625
David Brazdild9024ef2018-01-18 21:41:41 +0000626 if (param_index != 13) {
Shubham Ajmera45c87432017-06-22 11:10:27 -0700627 LOG(ERROR) << "Not enough parameters";
628 return false;
629 }
630
631 return true;
632 }
633
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700634 static int ReplaceMask(int input, int old_mask, int new_mask) {
635 return (input & old_mask) != 0 ? new_mask : 0;
636 }
637
638 bool ReadArgumentsV1(int argc ATTRIBUTE_UNUSED, char** argv) {
639 // Check for "dexopt".
Andreas Gamped089ca12016-06-27 14:25:30 -0700640 if (argv[2] == nullptr) {
641 LOG(ERROR) << "Missing parameters";
642 return false;
643 }
644 if (std::string("dexopt").compare(argv[2]) != 0) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700645 LOG(ERROR) << "Expected \"dexopt\"";
Andreas Gamped089ca12016-06-27 14:25:30 -0700646 return false;
647 }
648
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700649 size_t param_index = 0;
650 for (;; ++param_index) {
651 const char* param = argv[3 + param_index];
652 if (param == nullptr) {
653 break;
654 }
655
656 switch (param_index) {
657 case 0:
658 package_parameters_.apk_path = param;
659 break;
660
661 case 1:
662 package_parameters_.uid = atoi(param);
663 break;
664
665 case 2:
666 package_parameters_.pkgName = param;
667 break;
668
669 case 3:
670 package_parameters_.instruction_set = param;
671 break;
672
673 case 4: {
674 // Version 1 had:
675 // DEXOPT_DEX2OAT_NEEDED = 1
676 // DEXOPT_PATCHOAT_NEEDED = 2
677 // DEXOPT_SELF_PATCHOAT_NEEDED = 3
678 // We will simply use DEX2OAT_FROM_SCRATCH.
679 package_parameters_.dexopt_needed = DEX2OAT_FROM_SCRATCH;
680 break;
681 }
682
683 case 5:
684 package_parameters_.oat_dir = param;
685 break;
686
687 case 6: {
688 // Version 1 had:
689 constexpr int OLD_DEXOPT_PUBLIC = 1 << 1;
Nicolas Geoffray2520d442017-05-05 14:32:51 +0100690 // Note: DEXOPT_SAFEMODE has been removed.
691 // constexpr int OLD_DEXOPT_SAFEMODE = 1 << 2;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700692 constexpr int OLD_DEXOPT_DEBUGGABLE = 1 << 3;
693 constexpr int OLD_DEXOPT_BOOTCOMPLETE = 1 << 4;
694 constexpr int OLD_DEXOPT_PROFILE_GUIDED = 1 << 5;
695 constexpr int OLD_DEXOPT_OTA = 1 << 6;
696 int input = atoi(param);
697 package_parameters_.dexopt_flags =
698 ReplaceMask(input, OLD_DEXOPT_PUBLIC, DEXOPT_PUBLIC) |
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700699 ReplaceMask(input, OLD_DEXOPT_DEBUGGABLE, DEXOPT_DEBUGGABLE) |
700 ReplaceMask(input, OLD_DEXOPT_BOOTCOMPLETE, DEXOPT_BOOTCOMPLETE) |
701 ReplaceMask(input, OLD_DEXOPT_PROFILE_GUIDED, DEXOPT_PROFILE_GUIDED) |
702 ReplaceMask(input, OLD_DEXOPT_OTA, 0);
703 break;
704 }
705
706 case 7:
707 package_parameters_.compiler_filter = param;
708 break;
709
710 case 8:
711 package_parameters_.volume_uuid = ParseNull(param);
712 break;
713
714 case 9:
715 package_parameters_.shared_libraries = ParseNull(param);
716 break;
717
718 default:
719 LOG(ERROR) << "Too many arguments, got " << param;
720 return false;
721 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800722 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700723
724 if (param_index != 10) {
725 LOG(ERROR) << "Not enough parameters";
Andreas Gampe73dae112015-11-19 14:12:14 -0800726 return false;
727 }
728
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700729 // Set se_info to null. It is only relevant for secondary dex files, which we won't
730 // receive from a v1 A side.
731 package_parameters_.se_info = nullptr;
732
Shubham Ajmera45c87432017-06-22 11:10:27 -0700733 // Set downgrade to false. It is only relevant when downgrading compiler
734 // filter, which is not the case during ota.
735 package_parameters_.downgrade = false;
736
David Brazdil570d3982018-01-16 20:15:43 +0000737 // Set target_sdk_version to 0, ie the platform SDK version. This is
738 // conservative and may force some classes to verify at runtime.
739 package_parameters_.target_sdk_version = 0;
740
Andreas Gampe73dae112015-11-19 14:12:14 -0800741 return true;
742 }
743
744 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700745 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
746 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
747 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800748
749 for (const std::string& e : environ_) {
750 putenv(const_cast<char*>(e.c_str()));
751 }
752 }
753
754 // Ensure that we have the right boot image. The first time any app is
755 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700756 bool PrepareBootImage(bool force) const {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700757 if (package_parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800758 LOG(ERROR) << "Instruction set missing.";
759 return false;
760 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700761 const char* isa = package_parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800762
763 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700764 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800765 std::string isa_path = dalvik_cache + "/" + isa;
766 std::string art_path = isa_path + "/system@framework@boot.art";
767 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700768 bool cleared = false;
769 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
770 // Files exist, assume everything is alright if not forced. Otherwise clean up.
771 if (!force) {
772 return true;
773 }
774 ClearDirectory(isa_path);
775 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800776 }
777
Andreas Gamped089ca12016-06-27 14:25:30 -0700778 // Reset umask in otapreopt, so that we control the the access for the files we create.
779 umask(0);
780
Andreas Gampe73dae112015-11-19 14:12:14 -0800781 // Create the directories, if necessary.
782 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700783 if (!CreatePath(dalvik_cache)) {
784 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800785 return false;
786 }
787 }
788 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700789 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800790 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
791 return false;
792 }
793 }
794
Andreas Gampe5709b572016-02-12 17:42:59 -0800795 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700796 if (!cleared) {
797 ClearDirectory(isa_path);
798 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800799
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700800 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800801 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
802 return PatchoatBootImage(art_path, isa);
803 } else {
804 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700805 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800806 }
807 }
808
Andreas Gamped089ca12016-06-27 14:25:30 -0700809 static bool CreatePath(const std::string& path) {
810 // Create the given path. Use string processing instead of dirname, as dirname's need for
811 // a writable char buffer is painful.
812
813 // First, try to use the full path.
814 if (mkdir(path.c_str(), 0711) == 0) {
815 return true;
816 }
817 if (errno != ENOENT) {
818 PLOG(ERROR) << "Could not create path " << path;
819 return false;
820 }
821
822 // Now find the parent and try that first.
823 size_t last_slash = path.find_last_of('/');
824 if (last_slash == std::string::npos || last_slash == 0) {
825 PLOG(ERROR) << "Could not create " << path;
826 return false;
827 }
828
829 if (!CreatePath(path.substr(0, last_slash))) {
830 return false;
831 }
832
833 if (mkdir(path.c_str(), 0711) == 0) {
834 return true;
835 }
836 PLOG(ERROR) << "Could not create " << path;
837 return false;
838 }
839
840 static void ClearDirectory(const std::string& dir) {
841 DIR* c_dir = opendir(dir.c_str());
842 if (c_dir == nullptr) {
843 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
844 return;
845 }
846
847 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
848 const char* name = de->d_name;
849 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
850 continue;
851 }
852 // We only want to delete regular files and symbolic links.
853 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
854 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
855 LOG(WARNING) << "Unexpected file "
856 << file
857 << " of type "
858 << std::hex
859 << de->d_type
860 << " encountered.";
861 } else {
862 // Try to unlink the file.
863 if (unlink(file.c_str()) != 0) {
864 PLOG(ERROR) << "Unable to unlink " << file;
865 }
866 }
867 }
868 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
869 }
870
871 bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800872 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
873
874 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700875 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800876
877 cmd.push_back("--input-image-location=/system/framework/boot.art");
878 cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
879
880 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
881
882 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
883 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800884 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800885
886 std::string error_msg;
887 bool result = Exec(cmd, &error_msg);
888 if (!result) {
889 LOG(ERROR) << "Could not generate boot image: " << error_msg;
890 }
891 return result;
892 }
893
894 bool Dex2oatBootImage(const std::string& boot_cp,
895 const std::string& art_path,
896 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700897 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800898 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
899 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700900 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800901 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700902 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800903 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
904 }
905 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
906
907 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
908 ART_BASE_ADDRESS_MAX_DELTA);
909 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
910
911 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
912
913 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
914 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
915 "-Xms",
916 true,
917 cmd);
918 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
919 "-Xmx",
920 true,
921 cmd);
922 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
923 "--compiler-filter=",
924 false,
925 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700926 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800927 // TODO: Compiled-classes.
928 const std::string* extra_opts =
929 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
930 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700931 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800932 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
933 }
934 // TODO: Should we lower this? It's usually set close to max, because
935 // normally there's not much else going on at boot.
936 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
937 "-j",
938 false,
939 cmd);
940 AddCompilerOptionFromSystemProperty(
941 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
942 "--instruction-set-variant=",
943 false,
944 cmd);
945 AddCompilerOptionFromSystemProperty(
946 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
947 "--instruction-set-features=",
948 false,
949 cmd);
950
951 std::string error_msg;
952 bool result = Exec(cmd, &error_msg);
953 if (!result) {
954 LOG(ERROR) << "Could not generate boot image: " << error_msg;
955 }
956 return result;
957 }
958
959 static const char* ParseNull(const char* arg) {
960 return (strcmp(arg, "!") == 0) ? nullptr : arg;
961 }
962
Andreas Gamped089ca12016-06-27 14:25:30 -0700963 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700964 // There's one thing we have to be careful about: we may/will be asked to compile an app
965 // living in the system image. This may be a valid request - if the app wasn't compiled,
966 // e.g., if the system image wasn't large enough to include preopted files. However, the
967 // data we have is from the old system, so the driver (the OTA service) can't actually
968 // know. Thus, we will get requests for apps that have preopted components. To avoid
969 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
970 // simple checks:
971 //
972 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
973 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
974 //
975 // 2) If you replace the name in the apk_path with "oat," does the path exist?
976 // (=have a subdirectory for preopted files)
977 //
978 // If the answer to both is yes, skip the dexopt.
979 //
980 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
981 // be stripped), that's not true for APKs signed outside the build system (so the
982 // jar content must be exactly the same).
983
984 // (This is ugly as it's the only thing where we need to understand the contents
985 // of package_parameters_, but it beats postponing the decision or using the call-
986 // backs to do weird things.)
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700987 const char* apk_path = package_parameters_.apk_path;
988 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800989 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700990 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700991 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700992 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700993 CHECK(EndsWith(path, "/"));
994 path = path + "oat";
995 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800996 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700997 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700998 }
999 }
1000 }
1001
Andreas Gamped089ca12016-06-27 14:25:30 -07001002 // Another issue is unavailability of files in the new system. If the partition
1003 // layout changes, otapreopt_chroot may not know about this. Then files from that
1004 // partition will not be available and fail to build. This is problematic, as
1005 // this tool will wipe the OTA artifact cache and try again (for robustness after
1006 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001007 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -08001008 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -07001009 return true;
1010 }
1011
1012 return false;
1013 }
1014
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001015 // Run dexopt with the parameters of package_parameters_.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08001016 // TODO(calin): embed the profile name in the parameters.
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001017 int Dexopt() {
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001018 return dexopt(package_parameters_.apk_path,
1019 package_parameters_.uid,
1020 package_parameters_.pkgName,
1021 package_parameters_.instruction_set,
1022 package_parameters_.dexopt_needed,
1023 package_parameters_.oat_dir,
1024 package_parameters_.dexopt_flags,
1025 package_parameters_.compiler_filter,
1026 package_parameters_.volume_uuid,
1027 package_parameters_.shared_libraries,
Shubham Ajmera45c87432017-06-22 11:10:27 -07001028 package_parameters_.se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001029 package_parameters_.downgrade,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08001030 package_parameters_.target_sdk_version,
1031 "primary.prof");
Andreas Gampe73dae112015-11-19 14:12:14 -08001032 }
1033
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001034 int RunPreopt() {
1035 if (ShouldSkipPreopt()) {
1036 return 0;
1037 }
1038
1039 int dexopt_result = Dexopt();
1040 if (dexopt_result == 0) {
1041 return 0;
1042 }
1043
1044 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
1045 // Then regenerate and retry.
1046 if (WEXITSTATUS(dexopt_result) ==
1047 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
1048 if (!PrepareBootImage(/* force */ true)) {
1049 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
1050 << dexopt_result;
1051 return dexopt_result;
1052 }
1053
1054 int dexopt_result_boot_image_retry = Dexopt();
1055 if (dexopt_result_boot_image_retry == 0) {
1056 return 0;
1057 }
1058 }
1059
1060 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
1061 // if possible.
1062 if ((package_parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
1063 return dexopt_result;
1064 }
1065
1066 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
1067 package_parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
1068 return Dexopt();
1069 }
1070
Andreas Gampe73dae112015-11-19 14:12:14 -08001071 ////////////////////////////////////
1072 // Helpers, mostly taken from ART //
1073 ////////////////////////////////////
1074
1075 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -07001076 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -07001077 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -08001078
1079 CHECK_GE(arg_vector.size(), 1U) << command_line;
1080
1081 // Convert the args to char pointers.
1082 const char* program = arg_vector[0].c_str();
1083 std::vector<char*> args;
1084 for (size_t i = 0; i < arg_vector.size(); ++i) {
1085 const std::string& arg = arg_vector[i];
1086 char* arg_str = const_cast<char*>(arg.c_str());
1087 CHECK(arg_str != nullptr) << i;
1088 args.push_back(arg_str);
1089 }
1090 args.push_back(nullptr);
1091
1092 // Fork and exec.
1093 pid_t pid = fork();
1094 if (pid == 0) {
1095 // No allocation allowed between fork and exec.
1096
1097 // Change process groups, so we don't get reaped by ProcessManager.
1098 setpgid(0, 0);
1099
1100 execv(program, &args[0]);
1101
1102 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1103 // _exit to avoid atexit handlers in child.
1104 _exit(1);
1105 } else {
1106 if (pid == -1) {
1107 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1108 command_line.c_str(), strerror(errno));
1109 return false;
1110 }
1111
1112 // wait for subprocess to finish
1113 int status;
1114 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1115 if (got_pid != pid) {
1116 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1117 "wanted %d, got %d: %s",
1118 command_line.c_str(), pid, got_pid, strerror(errno));
1119 return false;
1120 }
1121 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1122 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1123 command_line.c_str());
1124 return false;
1125 }
1126 }
1127 return true;
1128 }
1129
1130 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
1131 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
1132 constexpr size_t kPageSize = PAGE_SIZE;
1133 CHECK_EQ(min_delta % kPageSize, 0u);
1134 CHECK_EQ(max_delta % kPageSize, 0u);
1135 CHECK_LT(min_delta, max_delta);
1136
1137 std::default_random_engine generator;
1138 generator.seed(GetSeed());
1139 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
1140 int32_t r = distribution(generator);
1141 if (r % 2 == 0) {
1142 r = RoundUp(r, kPageSize);
1143 } else {
1144 r = RoundDown(r, kPageSize);
1145 }
1146 CHECK_LE(min_delta, r);
1147 CHECK_GE(max_delta, r);
1148 CHECK_EQ(r % kPageSize, 0u);
1149 return r;
1150 }
1151
1152 static uint64_t GetSeed() {
1153#ifdef __BIONIC__
1154 // Bionic exposes arc4random, use it.
1155 uint64_t random_data;
1156 arc4random_buf(&random_data, sizeof(random_data));
1157 return random_data;
1158#else
1159#error "This is only supposed to run with bionic. Otherwise, implement..."
1160#endif
1161 }
1162
1163 void AddCompilerOptionFromSystemProperty(const char* system_property,
1164 const char* prefix,
1165 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -07001166 std::vector<std::string>& out) const {
1167 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -08001168 if (value != nullptr) {
1169 if (runtime) {
1170 out.push_back("--runtime-arg");
1171 }
1172 if (prefix != nullptr) {
1173 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
1174 } else {
1175 out.push_back(*value);
1176 }
1177 }
1178 }
1179
Andreas Gamped089ca12016-06-27 14:25:30 -07001180 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
1181 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
1182 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
1183 // The index of the instruction-set string inside the package parameters. Needed for
1184 // some special-casing that requires knowledge of the instruction-set.
1185 static constexpr size_t kISAIndex = 3;
1186
Andreas Gampe73dae112015-11-19 14:12:14 -08001187 // Stores the system properties read out of the B partition. We need to use these properties
1188 // to compile, instead of the A properties we could get from init/get_property.
1189 SystemProperties system_properties_;
1190
Andreas Gamped089ca12016-06-27 14:25:30 -07001191 // Some select properties that are always needed.
1192 std::string target_slot_;
1193 std::string android_root_;
1194 std::string android_data_;
1195 std::string boot_classpath_;
1196 std::string asec_mountpoint_;
1197
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001198 Parameters package_parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -08001199
1200 // Store environment values we need to set.
1201 std::vector<std::string> environ_;
1202};
1203
1204OTAPreoptService gOps;
1205
1206////////////////////////
1207// Plug-in functions. //
1208////////////////////////
1209
1210int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001211 return gOps.GetProperty(key, value, default_value);
1212}
1213
1214// Compute the output path of
1215bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
1216 const char *apk_path,
1217 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -07001218 const char *file_name_start;
1219 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -08001220
1221 file_name_start = strrchr(apk_path, '/');
1222 if (file_name_start == nullptr) {
1223 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
1224 return false;
1225 }
1226 file_name_end = strrchr(file_name_start, '.');
1227 if (file_name_end == nullptr) {
1228 ALOGE("apk_path '%s' has no extension\n", apk_path);
1229 return false;
1230 }
1231
1232 // Calculate file_name
1233 file_name_start++; // Move past '/', is valid as file_name_end is valid.
1234 size_t file_name_len = file_name_end - file_name_start;
1235 std::string file_name(file_name_start, file_name_len);
1236
1237 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -07001238 snprintf(path,
1239 PKG_PATH_MAX,
1240 "%s/%s/%s.odex.%s",
1241 oat_dir,
1242 instruction_set,
1243 file_name.c_str(),
1244 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -08001245 return true;
1246}
1247
1248/*
1249 * Computes the odex file for the given apk_path and instruction_set.
1250 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
1251 *
1252 * Returns false if it failed to determine the odex file path.
1253 */
1254bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
1255 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001256 const char *path_end = strrchr(apk_path, '/');
1257 if (path_end == nullptr) {
1258 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
1259 return false;
1260 }
1261 std::string path_component(apk_path, path_end - apk_path);
1262
1263 const char *name_begin = path_end + 1;
1264 const char *extension_start = strrchr(name_begin, '.');
1265 if (extension_start == nullptr) {
1266 ALOGE("apk_path '%s' has no extension.\n", apk_path);
1267 return false;
1268 }
1269 std::string name_component(name_begin, extension_start - name_begin);
1270
Andreas Gamped089ca12016-06-27 14:25:30 -07001271 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -08001272 path_component.c_str(),
1273 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -07001274 name_component.c_str(),
1275 gOps.GetTargetSlot().c_str());
1276 if (new_path.length() >= PKG_PATH_MAX) {
1277 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
1278 return false;
1279 }
Andreas Gampe73dae112015-11-19 14:12:14 -08001280 strcpy(path, new_path.c_str());
1281 return true;
1282}
1283
1284bool create_cache_path(char path[PKG_PATH_MAX],
1285 const char *src,
1286 const char *instruction_set) {
1287 size_t srclen = strlen(src);
1288
1289 /* demand that we are an absolute path */
1290 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
1291 return false;
1292 }
1293
1294 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
1295 return false;
1296 }
1297
1298 std::string from_src = std::string(src + 1);
1299 std::replace(from_src.begin(), from_src.end(), '/', '@');
1300
1301 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -07001302 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -08001303 DALVIK_CACHE,
1304 instruction_set,
1305 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +01001306 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -08001307
1308 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
1309 return false;
1310 }
1311 strcpy(path, assembled_path.c_str());
1312
1313 return true;
1314}
1315
Andreas Gampe73dae112015-11-19 14:12:14 -08001316static int log_callback(int type, const char *fmt, ...) {
1317 va_list ap;
1318 int priority;
1319
1320 switch (type) {
1321 case SELINUX_WARNING:
1322 priority = ANDROID_LOG_WARN;
1323 break;
1324 case SELINUX_INFO:
1325 priority = ANDROID_LOG_INFO;
1326 break;
1327 default:
1328 priority = ANDROID_LOG_ERROR;
1329 break;
1330 }
1331 va_start(ap, fmt);
1332 LOG_PRI_VA(priority, "SELinux", fmt, ap);
1333 va_end(ap);
1334 return 0;
1335}
1336
1337static int otapreopt_main(const int argc, char *argv[]) {
1338 int selinux_enabled = (is_selinux_enabled() > 0);
1339
1340 setenv("ANDROID_LOG_TAGS", "*:v", 1);
1341 android::base::InitLogging(argv);
1342
Andreas Gampe73dae112015-11-19 14:12:14 -08001343 if (argc < 2) {
1344 ALOGE("Expecting parameters");
1345 exit(1);
1346 }
1347
1348 union selinux_callback cb;
1349 cb.func_log = log_callback;
1350 selinux_set_callback(SELINUX_CB_LOG, cb);
1351
Andreas Gampe73dae112015-11-19 14:12:14 -08001352 if (selinux_enabled && selinux_status_open(true) < 0) {
1353 ALOGE("Could not open selinux status; exiting.\n");
1354 exit(1);
1355 }
1356
1357 int ret = android::installd::gOps.Main(argc, argv);
1358
1359 return ret;
1360}
1361
1362} // namespace installd
1363} // namespace android
1364
1365int main(const int argc, char *argv[]) {
1366 return android::installd::otapreopt_main(argc, argv);
1367}