blob: 60ad14bc3457d03416a6d9c378a4c983d6eac005 [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.");
81
82static_assert(DEXOPT_MASK == 0x1fe, "DEXOPT_MASK unexpected.");
83
84
85
Andreas Gampe73dae112015-11-19 14:12:14 -080086template<typename T>
87static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
88 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
89}
90
91template<typename T>
92static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
93 return RoundDown(x + n - 1, n);
94}
95
96class OTAPreoptService {
97 public:
Andreas Gampe73dae112015-11-19 14:12:14 -080098 // Main driver. Performs the following steps.
99 //
100 // 1) Parse options (read system properties etc from B partition).
101 //
102 // 2) Read in package data.
103 //
104 // 3) Prepare environment variables.
105 //
106 // 4) Prepare(compile) boot image, if necessary.
107 //
108 // 5) Run update.
109 int Main(int argc, char** argv) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700110 if (!ReadArguments(argc, argv)) {
111 LOG(ERROR) << "Failed reading command line.";
112 return 1;
113 }
114
Andreas Gampe73dae112015-11-19 14:12:14 -0800115 if (!ReadSystemProperties()) {
116 LOG(ERROR)<< "Failed reading system properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700117 return 2;
Andreas Gampe73dae112015-11-19 14:12:14 -0800118 }
119
120 if (!ReadEnvironment()) {
121 LOG(ERROR) << "Failed reading environment properties.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700122 return 3;
Andreas Gampe73dae112015-11-19 14:12:14 -0800123 }
124
Andreas Gamped089ca12016-06-27 14:25:30 -0700125 if (!CheckAndInitializeInstalldGlobals()) {
126 LOG(ERROR) << "Failed initializing globals.";
127 return 4;
Andreas Gampe73dae112015-11-19 14:12:14 -0800128 }
129
130 PrepareEnvironment();
131
Andreas Gamped089ca12016-06-27 14:25:30 -0700132 if (!PrepareBootImage(/* force */ false)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800133 LOG(ERROR) << "Failed preparing boot image.";
Andreas Gamped089ca12016-06-27 14:25:30 -0700134 return 5;
Andreas Gampe73dae112015-11-19 14:12:14 -0800135 }
136
137 int dexopt_retcode = RunPreopt();
138
139 return dexopt_retcode;
140 }
141
Andreas Gamped089ca12016-06-27 14:25:30 -0700142 int GetProperty(const char* key, char* value, const char* default_value) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800143 const std::string* prop_value = system_properties_.GetProperty(key);
144 if (prop_value == nullptr) {
145 if (default_value == nullptr) {
146 return 0;
147 }
148 // Copy in the default value.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600149 strlcpy(value, default_value, kPropertyValueMax - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800150 value[kPropertyValueMax - 1] = 0;
151 return strlen(default_value);// TODO: Need to truncate?
152 }
Andreas Gampe7e01b2b2017-09-26 20:41:48 -0700153 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600154 strlcpy(value, prop_value->data(), size);
Andreas Gampe7e01b2b2017-09-26 20:41:48 -0700155 return static_cast<int>(size - 1);
Andreas Gampe73dae112015-11-19 14:12:14 -0800156 }
157
Andreas Gamped089ca12016-06-27 14:25:30 -0700158 std::string GetOTADataDirectory() const {
159 return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), target_slot_.c_str());
160 }
161
162 const std::string& GetTargetSlot() const {
163 return target_slot_;
164 }
165
Andreas Gampe73dae112015-11-19 14:12:14 -0800166private:
Andreas Gamped089ca12016-06-27 14:25:30 -0700167
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700168 struct Parameters {
169 const char *apk_path;
170 uid_t uid;
171 const char *pkgName;
172 const char *instruction_set;
173 int dexopt_needed;
174 const char* oat_dir;
175 int dexopt_flags;
176 const char* compiler_filter;
177 const char* volume_uuid;
178 const char* shared_libraries;
179 const char* se_info;
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700180 bool downgrade;
David Brazdil570d3982018-01-16 20:15:43 +0000181 int target_sdk_version;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700182 };
183
Andreas Gampe73dae112015-11-19 14:12:14 -0800184 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700185 static constexpr const char* kPropertyFiles[] = {
186 "/default.prop", "/system/build.prop"
187 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800188
Andreas Gampe1842af32016-03-16 14:28:50 -0700189 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
190 if (!system_properties_.Load(kPropertyFiles[i])) {
191 return false;
192 }
193 }
194
195 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800196 }
197
198 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700199 // Parse the environment variables from init.environ.rc, which have the form
200 // export NAME VALUE
201 // For simplicity, don't respect string quotation. The values we are interested in can be
202 // encoded without them.
203 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
204 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
205 std::smatch export_match;
206 if (!std::regex_match(line, export_match, export_regex)) {
207 return true;
208 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800209
Andreas Gampe1842af32016-03-16 14:28:50 -0700210 if (export_match.size() != 3) {
211 return true;
212 }
213
214 std::string name = export_match[1].str();
215 std::string value = export_match[2].str();
216
217 system_properties_.SetProperty(name, value);
218
219 return true;
220 });
221 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800222 return false;
223 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700224
Andreas Gamped089ca12016-06-27 14:25:30 -0700225 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
226 return false;
227 }
228 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
229
230 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
231 return false;
232 }
233 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
234
235 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
236 return false;
237 }
238 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
239
240 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
241 return false;
242 }
243 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
244
245 return true;
246 }
247
248 const std::string& GetAndroidData() const {
249 return android_data_;
250 }
251
252 const std::string& GetAndroidRoot() const {
253 return android_root_;
254 }
255
256 const std::string GetOtaDirectoryPrefix() const {
257 return GetAndroidData() + "/ota";
258 }
259
260 bool CheckAndInitializeInstalldGlobals() {
261 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
262 // do not use any datapath that includes this, but we'll still have to set it.
263 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
264 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
265 if (result != 0) {
266 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
267 return false;
268 }
269
270 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
271 LOG(ERROR) << "Could not initialize globals; exiting.";
272 return false;
273 }
274
275 // This is different from the normal installd. We only do the base
276 // directory, the rest will be created on demand when each app is compiled.
277 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
278 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
279 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700280 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800281
282 return true;
283 }
284
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700285 bool ParseBool(const char* in) {
286 if (strcmp(in, "true") == 0) {
287 return true;
288 }
289 return false;
290 }
291
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700292 bool ParseUInt(const char* in, uint32_t* out) {
293 char* end;
294 long long int result = strtoll(in, &end, 0);
295 if (in == end || *end != '\0') {
296 return false;
297 }
298 if (result < std::numeric_limits<uint32_t>::min() ||
299 std::numeric_limits<uint32_t>::max() < result) {
300 return false;
301 }
302 *out = static_cast<uint32_t>(result);
303 return true;
304 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700305
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700306 bool ReadArguments(int argc, char** argv) {
307 // Expected command line:
308 // target-slot [version] dexopt {DEXOPT_PARAMETERS}
Andreas Gamped089ca12016-06-27 14:25:30 -0700309
310 const char* target_slot_arg = argv[1];
311 if (target_slot_arg == nullptr) {
312 LOG(ERROR) << "Missing parameters";
313 return false;
314 }
315 // Sanitize value. Only allow (a-zA-Z0-9_)+.
316 target_slot_ = target_slot_arg;
Andreas Gampefd12eda2016-07-12 09:47:17 -0700317 if (!ValidateTargetSlotSuffix(target_slot_)) {
318 LOG(ERROR) << "Target slot suffix not legal: " << target_slot_;
319 return false;
Andreas Gamped089ca12016-06-27 14:25:30 -0700320 }
321
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700322 // Check for version or "dexopt" next.
323 if (argv[2] == nullptr) {
324 LOG(ERROR) << "Missing parameters";
325 return false;
326 }
327
328 if (std::string("dexopt").compare(argv[2]) == 0) {
329 // This is version 1 (N) or pre-versioning version 2.
330 constexpr int kV2ArgCount = 1 // "otapreopt"
331 + 1 // slot
332 + 1 // "dexopt"
333 + 1 // apk_path
334 + 1 // uid
335 + 1 // pkg
336 + 1 // isa
337 + 1 // dexopt_needed
338 + 1 // oat_dir
339 + 1 // dexopt_flags
340 + 1 // filter
341 + 1 // volume
342 + 1 // libs
Andreas Gampe645e79c2017-04-19 13:58:49 -0700343 + 1; // seinfo
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700344 if (argc == kV2ArgCount) {
345 return ReadArgumentsV2(argc, argv, false);
346 } else {
347 return ReadArgumentsV1(argc, argv);
348 }
349 }
350
351 uint32_t version;
352 if (!ParseUInt(argv[2], &version)) {
353 LOG(ERROR) << "Could not parse version: " << argv[2];
354 return false;
355 }
356
357 switch (version) {
358 case 2:
359 return ReadArgumentsV2(argc, argv, true);
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700360 case 3:
361 return ReadArgumentsV3(argc, argv);
David Brazdil570d3982018-01-16 20:15:43 +0000362 case 4:
363 return ReadArgumentsV4(argc, argv);
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700364
365 default:
366 LOG(ERROR) << "Unsupported version " << version;
367 return false;
368 }
369 }
370
371 bool ReadArgumentsV2(int argc ATTRIBUTE_UNUSED, char** argv, bool versioned) {
372 size_t dexopt_index = versioned ? 3 : 2;
373
374 // Check for "dexopt".
375 if (argv[dexopt_index] == nullptr) {
376 LOG(ERROR) << "Missing parameters";
377 return false;
378 }
379 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
380 LOG(ERROR) << "Expected \"dexopt\"";
381 return false;
382 }
383
384 size_t param_index = 0;
385 for (;; ++param_index) {
386 const char* param = argv[dexopt_index + 1 + param_index];
387 if (param == nullptr) {
388 break;
389 }
390
391 switch (param_index) {
392 case 0:
393 package_parameters_.apk_path = param;
394 break;
395
396 case 1:
397 package_parameters_.uid = atoi(param);
398 break;
399
400 case 2:
401 package_parameters_.pkgName = param;
402 break;
403
404 case 3:
405 package_parameters_.instruction_set = param;
406 break;
407
408 case 4:
409 package_parameters_.dexopt_needed = atoi(param);
410 break;
411
412 case 5:
413 package_parameters_.oat_dir = param;
414 break;
415
416 case 6:
417 package_parameters_.dexopt_flags = atoi(param);
418 break;
419
420 case 7:
421 package_parameters_.compiler_filter = param;
422 break;
423
424 case 8:
425 package_parameters_.volume_uuid = ParseNull(param);
426 break;
427
428 case 9:
429 package_parameters_.shared_libraries = ParseNull(param);
430 break;
431
432 case 10:
433 package_parameters_.se_info = ParseNull(param);
434 break;
435
436 default:
437 LOG(ERROR) << "Too many arguments, got " << param;
438 return false;
439 }
440 }
441
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700442 // Set downgrade to false. It is only relevant when downgrading compiler
443 // filter, which is not the case during ota.
444 package_parameters_.downgrade = false;
445
David Brazdil570d3982018-01-16 20:15:43 +0000446 // Set target_sdk_version to 0, ie the platform SDK version. This is
447 // conservative and may force some classes to verify at runtime.
448 package_parameters_.target_sdk_version = 0;
449
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700450 if (param_index != 11) {
451 LOG(ERROR) << "Not enough parameters";
452 return false;
453 }
454
455 return true;
456 }
457
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700458 bool ReadArgumentsV3(int argc ATTRIBUTE_UNUSED, char** argv) {
459 size_t dexopt_index = 3;
460
461 // Check for "dexopt".
462 if (argv[dexopt_index] == nullptr) {
463 LOG(ERROR) << "Missing parameters";
464 return false;
465 }
466 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
467 LOG(ERROR) << "Expected \"dexopt\"";
468 return false;
469 }
470
471 size_t param_index = 0;
472 for (;; ++param_index) {
473 const char* param = argv[dexopt_index + 1 + param_index];
474 if (param == nullptr) {
475 break;
476 }
477
478 switch (param_index) {
479 case 0:
480 package_parameters_.apk_path = param;
481 break;
482
483 case 1:
484 package_parameters_.uid = atoi(param);
485 break;
486
487 case 2:
488 package_parameters_.pkgName = param;
489 break;
490
491 case 3:
492 package_parameters_.instruction_set = param;
493 break;
494
495 case 4:
496 package_parameters_.dexopt_needed = atoi(param);
497 break;
498
499 case 5:
500 package_parameters_.oat_dir = param;
501 break;
502
503 case 6:
504 package_parameters_.dexopt_flags = atoi(param);
505 break;
506
507 case 7:
508 package_parameters_.compiler_filter = param;
509 break;
510
511 case 8:
512 package_parameters_.volume_uuid = ParseNull(param);
513 break;
514
515 case 9:
516 package_parameters_.shared_libraries = ParseNull(param);
517 break;
518
519 case 10:
520 package_parameters_.se_info = ParseNull(param);
521 break;
522
523 case 11:
524 package_parameters_.downgrade = ParseBool(param);
525 break;
526
527 default:
528 LOG(ERROR) << "Too many arguments, got " << param;
529 return false;
530 }
531 }
532
David Brazdil570d3982018-01-16 20:15:43 +0000533 // Set target_sdk_version to 0, ie the platform SDK version. This is
534 // conservative and may force some classes to verify at runtime.
535 package_parameters_.target_sdk_version = 0;
536
537 if (param_index != 12) {
538 LOG(ERROR) << "Not enough parameters";
539 return false;
540 }
541
542 return true;
543 }
544
545 bool ReadArgumentsV4(int argc ATTRIBUTE_UNUSED, char** argv) {
546 size_t dexopt_index = 3;
547
548 // Check for "dexopt".
549 if (argv[dexopt_index] == nullptr) {
550 LOG(ERROR) << "Missing parameters";
551 return false;
552 }
553 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
554 LOG(ERROR) << "Expected \"dexopt\"";
555 return false;
556 }
557
558 size_t param_index = 0;
559 for (;; ++param_index) {
560 const char* param = argv[dexopt_index + 1 + param_index];
561 if (param == nullptr) {
562 break;
563 }
564
565 switch (param_index) {
566 case 0:
567 package_parameters_.apk_path = param;
568 break;
569
570 case 1:
571 package_parameters_.uid = atoi(param);
572 break;
573
574 case 2:
575 package_parameters_.pkgName = param;
576 break;
577
578 case 3:
579 package_parameters_.instruction_set = param;
580 break;
581
582 case 4:
583 package_parameters_.dexopt_needed = atoi(param);
584 break;
585
586 case 5:
587 package_parameters_.oat_dir = param;
588 break;
589
590 case 6:
591 package_parameters_.dexopt_flags = atoi(param);
592 break;
593
594 case 7:
595 package_parameters_.compiler_filter = param;
596 break;
597
598 case 8:
599 package_parameters_.volume_uuid = ParseNull(param);
600 break;
601
602 case 9:
603 package_parameters_.shared_libraries = ParseNull(param);
604 break;
605
606 case 10:
607 package_parameters_.se_info = ParseNull(param);
608 break;
609
610 case 11:
611 package_parameters_.downgrade = ParseBool(param);
612 break;
613
614 case 12:
615 package_parameters_.target_sdk_version = atoi(param);
616 break;
617
618 default:
619 LOG(ERROR) << "Too many arguments, got " << param;
620 return false;
621 }
622 }
623
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700624 if (param_index != 12) {
625 LOG(ERROR) << "Not enough parameters";
626 return false;
627 }
628
629 return true;
630 }
631
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700632 static int ReplaceMask(int input, int old_mask, int new_mask) {
633 return (input & old_mask) != 0 ? new_mask : 0;
634 }
635
636 bool ReadArgumentsV1(int argc ATTRIBUTE_UNUSED, char** argv) {
637 // Check for "dexopt".
Andreas Gamped089ca12016-06-27 14:25:30 -0700638 if (argv[2] == nullptr) {
639 LOG(ERROR) << "Missing parameters";
640 return false;
641 }
642 if (std::string("dexopt").compare(argv[2]) != 0) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700643 LOG(ERROR) << "Expected \"dexopt\"";
Andreas Gamped089ca12016-06-27 14:25:30 -0700644 return false;
645 }
646
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700647 size_t param_index = 0;
648 for (;; ++param_index) {
649 const char* param = argv[3 + param_index];
650 if (param == nullptr) {
651 break;
652 }
653
654 switch (param_index) {
655 case 0:
656 package_parameters_.apk_path = param;
657 break;
658
659 case 1:
660 package_parameters_.uid = atoi(param);
661 break;
662
663 case 2:
664 package_parameters_.pkgName = param;
665 break;
666
667 case 3:
668 package_parameters_.instruction_set = param;
669 break;
670
671 case 4: {
672 // Version 1 had:
673 // DEXOPT_DEX2OAT_NEEDED = 1
674 // DEXOPT_PATCHOAT_NEEDED = 2
675 // DEXOPT_SELF_PATCHOAT_NEEDED = 3
676 // We will simply use DEX2OAT_FROM_SCRATCH.
677 package_parameters_.dexopt_needed = DEX2OAT_FROM_SCRATCH;
678 break;
679 }
680
681 case 5:
682 package_parameters_.oat_dir = param;
683 break;
684
685 case 6: {
686 // Version 1 had:
687 constexpr int OLD_DEXOPT_PUBLIC = 1 << 1;
Nicolas Geoffray2520d442017-05-05 14:32:51 +0100688 // Note: DEXOPT_SAFEMODE has been removed.
689 // constexpr int OLD_DEXOPT_SAFEMODE = 1 << 2;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700690 constexpr int OLD_DEXOPT_DEBUGGABLE = 1 << 3;
691 constexpr int OLD_DEXOPT_BOOTCOMPLETE = 1 << 4;
692 constexpr int OLD_DEXOPT_PROFILE_GUIDED = 1 << 5;
693 constexpr int OLD_DEXOPT_OTA = 1 << 6;
694 int input = atoi(param);
695 package_parameters_.dexopt_flags =
696 ReplaceMask(input, OLD_DEXOPT_PUBLIC, DEXOPT_PUBLIC) |
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700697 ReplaceMask(input, OLD_DEXOPT_DEBUGGABLE, DEXOPT_DEBUGGABLE) |
698 ReplaceMask(input, OLD_DEXOPT_BOOTCOMPLETE, DEXOPT_BOOTCOMPLETE) |
699 ReplaceMask(input, OLD_DEXOPT_PROFILE_GUIDED, DEXOPT_PROFILE_GUIDED) |
700 ReplaceMask(input, OLD_DEXOPT_OTA, 0);
701 break;
702 }
703
704 case 7:
705 package_parameters_.compiler_filter = param;
706 break;
707
708 case 8:
709 package_parameters_.volume_uuid = ParseNull(param);
710 break;
711
712 case 9:
713 package_parameters_.shared_libraries = ParseNull(param);
714 break;
715
716 default:
717 LOG(ERROR) << "Too many arguments, got " << param;
718 return false;
719 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800720 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700721
722 if (param_index != 10) {
723 LOG(ERROR) << "Not enough parameters";
Andreas Gampe73dae112015-11-19 14:12:14 -0800724 return false;
725 }
726
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700727 // Set se_info to null. It is only relevant for secondary dex files, which we won't
728 // receive from a v1 A side.
729 package_parameters_.se_info = nullptr;
730
Shubham Ajmera54ef8622017-06-22 11:10:27 -0700731 // Set downgrade to false. It is only relevant when downgrading compiler
732 // filter, which is not the case during ota.
733 package_parameters_.downgrade = false;
734
David Brazdil570d3982018-01-16 20:15:43 +0000735 // Set target_sdk_version to 0, ie the platform SDK version. This is
736 // conservative and may force some classes to verify at runtime.
737 package_parameters_.target_sdk_version = 0;
738
Andreas Gampe73dae112015-11-19 14:12:14 -0800739 return true;
740 }
741
742 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700743 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
744 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
745 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800746
747 for (const std::string& e : environ_) {
748 putenv(const_cast<char*>(e.c_str()));
749 }
750 }
751
752 // Ensure that we have the right boot image. The first time any app is
753 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700754 bool PrepareBootImage(bool force) const {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700755 if (package_parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800756 LOG(ERROR) << "Instruction set missing.";
757 return false;
758 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700759 const char* isa = package_parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800760
761 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700762 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800763 std::string isa_path = dalvik_cache + "/" + isa;
764 std::string art_path = isa_path + "/system@framework@boot.art";
765 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700766 bool cleared = false;
767 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
768 // Files exist, assume everything is alright if not forced. Otherwise clean up.
769 if (!force) {
770 return true;
771 }
772 ClearDirectory(isa_path);
773 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800774 }
775
Andreas Gamped089ca12016-06-27 14:25:30 -0700776 // Reset umask in otapreopt, so that we control the the access for the files we create.
777 umask(0);
778
Andreas Gampe73dae112015-11-19 14:12:14 -0800779 // Create the directories, if necessary.
780 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700781 if (!CreatePath(dalvik_cache)) {
782 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800783 return false;
784 }
785 }
786 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700787 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800788 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
789 return false;
790 }
791 }
792
Andreas Gampe5709b572016-02-12 17:42:59 -0800793 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700794 if (!cleared) {
795 ClearDirectory(isa_path);
796 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800797
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700798 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800799 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
800 return PatchoatBootImage(art_path, isa);
801 } else {
802 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700803 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800804 }
805 }
806
Andreas Gamped089ca12016-06-27 14:25:30 -0700807 static bool CreatePath(const std::string& path) {
808 // Create the given path. Use string processing instead of dirname, as dirname's need for
809 // a writable char buffer is painful.
810
811 // First, try to use the full path.
812 if (mkdir(path.c_str(), 0711) == 0) {
813 return true;
814 }
815 if (errno != ENOENT) {
816 PLOG(ERROR) << "Could not create path " << path;
817 return false;
818 }
819
820 // Now find the parent and try that first.
821 size_t last_slash = path.find_last_of('/');
822 if (last_slash == std::string::npos || last_slash == 0) {
823 PLOG(ERROR) << "Could not create " << path;
824 return false;
825 }
826
827 if (!CreatePath(path.substr(0, last_slash))) {
828 return false;
829 }
830
831 if (mkdir(path.c_str(), 0711) == 0) {
832 return true;
833 }
834 PLOG(ERROR) << "Could not create " << path;
835 return false;
836 }
837
838 static void ClearDirectory(const std::string& dir) {
839 DIR* c_dir = opendir(dir.c_str());
840 if (c_dir == nullptr) {
841 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
842 return;
843 }
844
845 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
846 const char* name = de->d_name;
847 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
848 continue;
849 }
850 // We only want to delete regular files and symbolic links.
851 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
852 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
853 LOG(WARNING) << "Unexpected file "
854 << file
855 << " of type "
856 << std::hex
857 << de->d_type
858 << " encountered.";
859 } else {
860 // Try to unlink the file.
861 if (unlink(file.c_str()) != 0) {
862 PLOG(ERROR) << "Unable to unlink " << file;
863 }
864 }
865 }
866 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
867 }
868
869 bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800870 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
871
872 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700873 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800874
875 cmd.push_back("--input-image-location=/system/framework/boot.art");
876 cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
877
878 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
879
880 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
881 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800882 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800883
884 std::string error_msg;
885 bool result = Exec(cmd, &error_msg);
886 if (!result) {
887 LOG(ERROR) << "Could not generate boot image: " << error_msg;
888 }
889 return result;
890 }
891
892 bool Dex2oatBootImage(const std::string& boot_cp,
893 const std::string& art_path,
894 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700895 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800896 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
897 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700898 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800899 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700900 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800901 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
902 }
903 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
904
905 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
906 ART_BASE_ADDRESS_MAX_DELTA);
907 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
908
909 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
910
911 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
912 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
913 "-Xms",
914 true,
915 cmd);
916 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
917 "-Xmx",
918 true,
919 cmd);
920 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
921 "--compiler-filter=",
922 false,
923 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700924 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800925 // TODO: Compiled-classes.
926 const std::string* extra_opts =
927 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
928 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700929 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800930 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
931 }
932 // TODO: Should we lower this? It's usually set close to max, because
933 // normally there's not much else going on at boot.
934 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
935 "-j",
936 false,
937 cmd);
938 AddCompilerOptionFromSystemProperty(
939 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
940 "--instruction-set-variant=",
941 false,
942 cmd);
943 AddCompilerOptionFromSystemProperty(
944 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
945 "--instruction-set-features=",
946 false,
947 cmd);
948
949 std::string error_msg;
950 bool result = Exec(cmd, &error_msg);
951 if (!result) {
952 LOG(ERROR) << "Could not generate boot image: " << error_msg;
953 }
954 return result;
955 }
956
957 static const char* ParseNull(const char* arg) {
958 return (strcmp(arg, "!") == 0) ? nullptr : arg;
959 }
960
Andreas Gamped089ca12016-06-27 14:25:30 -0700961 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700962 // There's one thing we have to be careful about: we may/will be asked to compile an app
963 // living in the system image. This may be a valid request - if the app wasn't compiled,
964 // e.g., if the system image wasn't large enough to include preopted files. However, the
965 // data we have is from the old system, so the driver (the OTA service) can't actually
966 // know. Thus, we will get requests for apps that have preopted components. To avoid
967 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
968 // simple checks:
969 //
970 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
971 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
972 //
973 // 2) If you replace the name in the apk_path with "oat," does the path exist?
974 // (=have a subdirectory for preopted files)
975 //
976 // If the answer to both is yes, skip the dexopt.
977 //
978 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
979 // be stripped), that's not true for APKs signed outside the build system (so the
980 // jar content must be exactly the same).
981
982 // (This is ugly as it's the only thing where we need to understand the contents
983 // of package_parameters_, but it beats postponing the decision or using the call-
984 // backs to do weird things.)
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700985 const char* apk_path = package_parameters_.apk_path;
986 CHECK(apk_path != nullptr);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800987 if (StartsWith(apk_path, android_root_)) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700988 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700989 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700990 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700991 CHECK(EndsWith(path, "/"));
992 path = path + "oat";
993 if (access(path.c_str(), F_OK) == 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700994 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700995 }
996 }
997 }
998
Andreas Gamped089ca12016-06-27 14:25:30 -0700999 // Another issue is unavailability of files in the new system. If the partition
1000 // layout changes, otapreopt_chroot may not know about this. Then files from that
1001 // partition will not be available and fail to build. This is problematic, as
1002 // this tool will wipe the OTA artifact cache and try again (for robustness after
1003 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001004 if (access(apk_path, F_OK) != 0) {
1005 LOG(WARNING) << "Skipping preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -07001006 return true;
1007 }
1008
1009 return false;
1010 }
1011
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001012 // Run dexopt with the parameters of package_parameters_.
1013 int Dexopt() {
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001014 return dexopt(package_parameters_.apk_path,
1015 package_parameters_.uid,
1016 package_parameters_.pkgName,
1017 package_parameters_.instruction_set,
1018 package_parameters_.dexopt_needed,
1019 package_parameters_.oat_dir,
1020 package_parameters_.dexopt_flags,
1021 package_parameters_.compiler_filter,
1022 package_parameters_.volume_uuid,
1023 package_parameters_.shared_libraries,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001024 package_parameters_.se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001025 package_parameters_.downgrade,
1026 package_parameters_.target_sdk_version);
Andreas Gampe73dae112015-11-19 14:12:14 -08001027 }
1028
Andreas Gampeb39d2f02017-04-17 20:04:02 -07001029 int RunPreopt() {
1030 if (ShouldSkipPreopt()) {
1031 return 0;
1032 }
1033
1034 int dexopt_result = Dexopt();
1035 if (dexopt_result == 0) {
1036 return 0;
1037 }
1038
1039 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
1040 // Then regenerate and retry.
1041 if (WEXITSTATUS(dexopt_result) ==
1042 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
1043 if (!PrepareBootImage(/* force */ true)) {
1044 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
1045 << dexopt_result;
1046 return dexopt_result;
1047 }
1048
1049 int dexopt_result_boot_image_retry = Dexopt();
1050 if (dexopt_result_boot_image_retry == 0) {
1051 return 0;
1052 }
1053 }
1054
1055 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
1056 // if possible.
1057 if ((package_parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
1058 return dexopt_result;
1059 }
1060
1061 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
1062 package_parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
1063 return Dexopt();
1064 }
1065
Andreas Gampe73dae112015-11-19 14:12:14 -08001066 ////////////////////////////////////
1067 // Helpers, mostly taken from ART //
1068 ////////////////////////////////////
1069
1070 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -07001071 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -07001072 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -08001073
1074 CHECK_GE(arg_vector.size(), 1U) << command_line;
1075
1076 // Convert the args to char pointers.
1077 const char* program = arg_vector[0].c_str();
1078 std::vector<char*> args;
1079 for (size_t i = 0; i < arg_vector.size(); ++i) {
1080 const std::string& arg = arg_vector[i];
1081 char* arg_str = const_cast<char*>(arg.c_str());
1082 CHECK(arg_str != nullptr) << i;
1083 args.push_back(arg_str);
1084 }
1085 args.push_back(nullptr);
1086
1087 // Fork and exec.
1088 pid_t pid = fork();
1089 if (pid == 0) {
1090 // No allocation allowed between fork and exec.
1091
1092 // Change process groups, so we don't get reaped by ProcessManager.
1093 setpgid(0, 0);
1094
1095 execv(program, &args[0]);
1096
1097 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1098 // _exit to avoid atexit handlers in child.
1099 _exit(1);
1100 } else {
1101 if (pid == -1) {
1102 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1103 command_line.c_str(), strerror(errno));
1104 return false;
1105 }
1106
1107 // wait for subprocess to finish
1108 int status;
1109 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1110 if (got_pid != pid) {
1111 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1112 "wanted %d, got %d: %s",
1113 command_line.c_str(), pid, got_pid, strerror(errno));
1114 return false;
1115 }
1116 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1117 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1118 command_line.c_str());
1119 return false;
1120 }
1121 }
1122 return true;
1123 }
1124
1125 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
1126 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
1127 constexpr size_t kPageSize = PAGE_SIZE;
1128 CHECK_EQ(min_delta % kPageSize, 0u);
1129 CHECK_EQ(max_delta % kPageSize, 0u);
1130 CHECK_LT(min_delta, max_delta);
1131
1132 std::default_random_engine generator;
1133 generator.seed(GetSeed());
1134 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
1135 int32_t r = distribution(generator);
1136 if (r % 2 == 0) {
1137 r = RoundUp(r, kPageSize);
1138 } else {
1139 r = RoundDown(r, kPageSize);
1140 }
1141 CHECK_LE(min_delta, r);
1142 CHECK_GE(max_delta, r);
1143 CHECK_EQ(r % kPageSize, 0u);
1144 return r;
1145 }
1146
1147 static uint64_t GetSeed() {
1148#ifdef __BIONIC__
1149 // Bionic exposes arc4random, use it.
1150 uint64_t random_data;
1151 arc4random_buf(&random_data, sizeof(random_data));
1152 return random_data;
1153#else
1154#error "This is only supposed to run with bionic. Otherwise, implement..."
1155#endif
1156 }
1157
1158 void AddCompilerOptionFromSystemProperty(const char* system_property,
1159 const char* prefix,
1160 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -07001161 std::vector<std::string>& out) const {
1162 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -08001163 if (value != nullptr) {
1164 if (runtime) {
1165 out.push_back("--runtime-arg");
1166 }
1167 if (prefix != nullptr) {
1168 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
1169 } else {
1170 out.push_back(*value);
1171 }
1172 }
1173 }
1174
Andreas Gamped089ca12016-06-27 14:25:30 -07001175 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
1176 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
1177 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
1178 // The index of the instruction-set string inside the package parameters. Needed for
1179 // some special-casing that requires knowledge of the instruction-set.
1180 static constexpr size_t kISAIndex = 3;
1181
Andreas Gampe73dae112015-11-19 14:12:14 -08001182 // Stores the system properties read out of the B partition. We need to use these properties
1183 // to compile, instead of the A properties we could get from init/get_property.
1184 SystemProperties system_properties_;
1185
Andreas Gamped089ca12016-06-27 14:25:30 -07001186 // Some select properties that are always needed.
1187 std::string target_slot_;
1188 std::string android_root_;
1189 std::string android_data_;
1190 std::string boot_classpath_;
1191 std::string asec_mountpoint_;
1192
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001193 Parameters package_parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -08001194
1195 // Store environment values we need to set.
1196 std::vector<std::string> environ_;
1197};
1198
1199OTAPreoptService gOps;
1200
1201////////////////////////
1202// Plug-in functions. //
1203////////////////////////
1204
1205int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001206 return gOps.GetProperty(key, value, default_value);
1207}
1208
1209// Compute the output path of
1210bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
1211 const char *apk_path,
1212 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -07001213 const char *file_name_start;
1214 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -08001215
1216 file_name_start = strrchr(apk_path, '/');
1217 if (file_name_start == nullptr) {
1218 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
1219 return false;
1220 }
1221 file_name_end = strrchr(file_name_start, '.');
1222 if (file_name_end == nullptr) {
1223 ALOGE("apk_path '%s' has no extension\n", apk_path);
1224 return false;
1225 }
1226
1227 // Calculate file_name
1228 file_name_start++; // Move past '/', is valid as file_name_end is valid.
1229 size_t file_name_len = file_name_end - file_name_start;
1230 std::string file_name(file_name_start, file_name_len);
1231
1232 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -07001233 snprintf(path,
1234 PKG_PATH_MAX,
1235 "%s/%s/%s.odex.%s",
1236 oat_dir,
1237 instruction_set,
1238 file_name.c_str(),
1239 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -08001240 return true;
1241}
1242
1243/*
1244 * Computes the odex file for the given apk_path and instruction_set.
1245 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
1246 *
1247 * Returns false if it failed to determine the odex file path.
1248 */
1249bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
1250 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001251 const char *path_end = strrchr(apk_path, '/');
1252 if (path_end == nullptr) {
1253 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
1254 return false;
1255 }
1256 std::string path_component(apk_path, path_end - apk_path);
1257
1258 const char *name_begin = path_end + 1;
1259 const char *extension_start = strrchr(name_begin, '.');
1260 if (extension_start == nullptr) {
1261 ALOGE("apk_path '%s' has no extension.\n", apk_path);
1262 return false;
1263 }
1264 std::string name_component(name_begin, extension_start - name_begin);
1265
Andreas Gamped089ca12016-06-27 14:25:30 -07001266 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -08001267 path_component.c_str(),
1268 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -07001269 name_component.c_str(),
1270 gOps.GetTargetSlot().c_str());
1271 if (new_path.length() >= PKG_PATH_MAX) {
1272 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
1273 return false;
1274 }
Andreas Gampe73dae112015-11-19 14:12:14 -08001275 strcpy(path, new_path.c_str());
1276 return true;
1277}
1278
1279bool create_cache_path(char path[PKG_PATH_MAX],
1280 const char *src,
1281 const char *instruction_set) {
1282 size_t srclen = strlen(src);
1283
1284 /* demand that we are an absolute path */
1285 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
1286 return false;
1287 }
1288
1289 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
1290 return false;
1291 }
1292
1293 std::string from_src = std::string(src + 1);
1294 std::replace(from_src.begin(), from_src.end(), '/', '@');
1295
1296 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -07001297 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -08001298 DALVIK_CACHE,
1299 instruction_set,
1300 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +01001301 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -08001302
1303 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
1304 return false;
1305 }
1306 strcpy(path, assembled_path.c_str());
1307
1308 return true;
1309}
1310
Andreas Gampe73dae112015-11-19 14:12:14 -08001311static int log_callback(int type, const char *fmt, ...) {
1312 va_list ap;
1313 int priority;
1314
1315 switch (type) {
1316 case SELINUX_WARNING:
1317 priority = ANDROID_LOG_WARN;
1318 break;
1319 case SELINUX_INFO:
1320 priority = ANDROID_LOG_INFO;
1321 break;
1322 default:
1323 priority = ANDROID_LOG_ERROR;
1324 break;
1325 }
1326 va_start(ap, fmt);
1327 LOG_PRI_VA(priority, "SELinux", fmt, ap);
1328 va_end(ap);
1329 return 0;
1330}
1331
1332static int otapreopt_main(const int argc, char *argv[]) {
1333 int selinux_enabled = (is_selinux_enabled() > 0);
1334
1335 setenv("ANDROID_LOG_TAGS", "*:v", 1);
1336 android::base::InitLogging(argv);
1337
Andreas Gampe73dae112015-11-19 14:12:14 -08001338 if (argc < 2) {
1339 ALOGE("Expecting parameters");
1340 exit(1);
1341 }
1342
1343 union selinux_callback cb;
1344 cb.func_log = log_callback;
1345 selinux_set_callback(SELINUX_CB_LOG, cb);
1346
Andreas Gampe73dae112015-11-19 14:12:14 -08001347 if (selinux_enabled && selinux_status_open(true) < 0) {
1348 ALOGE("Could not open selinux status; exiting.\n");
1349 exit(1);
1350 }
1351
1352 int ret = android::installd::gOps.Main(argc, argv);
1353
1354 return ret;
1355}
1356
1357} // namespace installd
1358} // namespace android
1359
1360int main(const int argc, char *argv[]) {
1361 return android::installd::otapreopt_main(argc, argv);
1362}