blob: 0c2d341a16d442405bd85c79cb18122912ba6589 [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 Sharkey1b9d9a62017-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 Gampe5696e632017-09-26 20:41:48 -0700153 size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -0600154 strlcpy(value, prop_value->data(), size);
Andreas Gampe5696e632017-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 Ajmera45c87432017-06-22 11:10:27 -0700180 bool downgrade;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700181 };
182
Andreas Gampe73dae112015-11-19 14:12:14 -0800183 bool ReadSystemProperties() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700184 static constexpr const char* kPropertyFiles[] = {
185 "/default.prop", "/system/build.prop"
186 };
Andreas Gampe73dae112015-11-19 14:12:14 -0800187
Andreas Gampe1842af32016-03-16 14:28:50 -0700188 for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
189 if (!system_properties_.Load(kPropertyFiles[i])) {
190 return false;
191 }
192 }
193
194 return true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800195 }
196
197 bool ReadEnvironment() {
Andreas Gampe1842af32016-03-16 14:28:50 -0700198 // Parse the environment variables from init.environ.rc, which have the form
199 // export NAME VALUE
200 // For simplicity, don't respect string quotation. The values we are interested in can be
201 // encoded without them.
202 std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
203 bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
204 std::smatch export_match;
205 if (!std::regex_match(line, export_match, export_regex)) {
206 return true;
207 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800208
Andreas Gampe1842af32016-03-16 14:28:50 -0700209 if (export_match.size() != 3) {
210 return true;
211 }
212
213 std::string name = export_match[1].str();
214 std::string value = export_match[2].str();
215
216 system_properties_.SetProperty(name, value);
217
218 return true;
219 });
220 if (!parse_result) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800221 return false;
222 }
Andreas Gampe1842af32016-03-16 14:28:50 -0700223
Andreas Gamped089ca12016-06-27 14:25:30 -0700224 if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
225 return false;
226 }
227 android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
228
229 if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
230 return false;
231 }
232 android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
233
234 if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
235 return false;
236 }
237 boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
238
239 if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
240 return false;
241 }
242 asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
243
244 return true;
245 }
246
247 const std::string& GetAndroidData() const {
248 return android_data_;
249 }
250
251 const std::string& GetAndroidRoot() const {
252 return android_root_;
253 }
254
255 const std::string GetOtaDirectoryPrefix() const {
256 return GetAndroidData() + "/ota";
257 }
258
259 bool CheckAndInitializeInstalldGlobals() {
260 // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
261 // do not use any datapath that includes this, but we'll still have to set it.
262 CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
263 int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
264 if (result != 0) {
265 LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
266 return false;
267 }
268
269 if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
270 LOG(ERROR) << "Could not initialize globals; exiting.";
271 return false;
272 }
273
274 // This is different from the normal installd. We only do the base
275 // directory, the rest will be created on demand when each app is compiled.
276 if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
277 LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
278 return false;
Andreas Gampe1842af32016-03-16 14:28:50 -0700279 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800280
281 return true;
282 }
283
Shubham Ajmera45c87432017-06-22 11:10:27 -0700284 bool ParseBool(const char* in) {
285 if (strcmp(in, "true") == 0) {
286 return true;
287 }
288 return false;
289 }
290
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700291 bool ParseUInt(const char* in, uint32_t* out) {
292 char* end;
293 long long int result = strtoll(in, &end, 0);
294 if (in == end || *end != '\0') {
295 return false;
296 }
297 if (result < std::numeric_limits<uint32_t>::min() ||
298 std::numeric_limits<uint32_t>::max() < result) {
299 return false;
300 }
301 *out = static_cast<uint32_t>(result);
302 return true;
303 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700304
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700305 bool ReadArguments(int argc, char** argv) {
306 // Expected command line:
307 // target-slot [version] dexopt {DEXOPT_PARAMETERS}
Andreas Gamped089ca12016-06-27 14:25:30 -0700308
309 const char* target_slot_arg = argv[1];
310 if (target_slot_arg == nullptr) {
311 LOG(ERROR) << "Missing parameters";
312 return false;
313 }
314 // Sanitize value. Only allow (a-zA-Z0-9_)+.
315 target_slot_ = target_slot_arg;
Andreas Gampefd12eda2016-07-12 09:47:17 -0700316 if (!ValidateTargetSlotSuffix(target_slot_)) {
317 LOG(ERROR) << "Target slot suffix not legal: " << target_slot_;
318 return false;
Andreas Gamped089ca12016-06-27 14:25:30 -0700319 }
320
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700321 // Check for version or "dexopt" next.
322 if (argv[2] == nullptr) {
323 LOG(ERROR) << "Missing parameters";
324 return false;
325 }
326
327 if (std::string("dexopt").compare(argv[2]) == 0) {
328 // This is version 1 (N) or pre-versioning version 2.
329 constexpr int kV2ArgCount = 1 // "otapreopt"
330 + 1 // slot
331 + 1 // "dexopt"
332 + 1 // apk_path
333 + 1 // uid
334 + 1 // pkg
335 + 1 // isa
336 + 1 // dexopt_needed
337 + 1 // oat_dir
338 + 1 // dexopt_flags
339 + 1 // filter
340 + 1 // volume
341 + 1 // libs
Andreas Gampe645e79c2017-04-19 13:58:49 -0700342 + 1; // seinfo
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700343 if (argc == kV2ArgCount) {
344 return ReadArgumentsV2(argc, argv, false);
345 } else {
346 return ReadArgumentsV1(argc, argv);
347 }
348 }
349
350 uint32_t version;
351 if (!ParseUInt(argv[2], &version)) {
352 LOG(ERROR) << "Could not parse version: " << argv[2];
353 return false;
354 }
355
356 switch (version) {
357 case 2:
358 return ReadArgumentsV2(argc, argv, true);
Shubham Ajmera45c87432017-06-22 11:10:27 -0700359 case 3:
360 return ReadArgumentsV3(argc, argv);
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700361
362 default:
363 LOG(ERROR) << "Unsupported version " << version;
364 return false;
365 }
366 }
367
368 bool ReadArgumentsV2(int argc ATTRIBUTE_UNUSED, char** argv, bool versioned) {
369 size_t dexopt_index = versioned ? 3 : 2;
370
371 // Check for "dexopt".
372 if (argv[dexopt_index] == nullptr) {
373 LOG(ERROR) << "Missing parameters";
374 return false;
375 }
376 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
377 LOG(ERROR) << "Expected \"dexopt\"";
378 return false;
379 }
380
381 size_t param_index = 0;
382 for (;; ++param_index) {
383 const char* param = argv[dexopt_index + 1 + param_index];
384 if (param == nullptr) {
385 break;
386 }
387
388 switch (param_index) {
389 case 0:
390 package_parameters_.apk_path = param;
391 break;
392
393 case 1:
394 package_parameters_.uid = atoi(param);
395 break;
396
397 case 2:
398 package_parameters_.pkgName = param;
399 break;
400
401 case 3:
402 package_parameters_.instruction_set = param;
403 break;
404
405 case 4:
406 package_parameters_.dexopt_needed = atoi(param);
407 break;
408
409 case 5:
410 package_parameters_.oat_dir = param;
411 break;
412
413 case 6:
414 package_parameters_.dexopt_flags = atoi(param);
415 break;
416
417 case 7:
418 package_parameters_.compiler_filter = param;
419 break;
420
421 case 8:
422 package_parameters_.volume_uuid = ParseNull(param);
423 break;
424
425 case 9:
426 package_parameters_.shared_libraries = ParseNull(param);
427 break;
428
429 case 10:
430 package_parameters_.se_info = ParseNull(param);
431 break;
432
433 default:
434 LOG(ERROR) << "Too many arguments, got " << param;
435 return false;
436 }
437 }
438
Shubham Ajmera45c87432017-06-22 11:10:27 -0700439 // Set downgrade to false. It is only relevant when downgrading compiler
440 // filter, which is not the case during ota.
441 package_parameters_.downgrade = false;
442
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700443 if (param_index != 11) {
444 LOG(ERROR) << "Not enough parameters";
445 return false;
446 }
447
448 return true;
449 }
450
Shubham Ajmera45c87432017-06-22 11:10:27 -0700451 bool ReadArgumentsV3(int argc ATTRIBUTE_UNUSED, char** argv) {
452 size_t dexopt_index = 3;
453
454 // Check for "dexopt".
455 if (argv[dexopt_index] == nullptr) {
456 LOG(ERROR) << "Missing parameters";
457 return false;
458 }
459 if (std::string("dexopt").compare(argv[dexopt_index]) != 0) {
460 LOG(ERROR) << "Expected \"dexopt\"";
461 return false;
462 }
463
464 size_t param_index = 0;
465 for (;; ++param_index) {
466 const char* param = argv[dexopt_index + 1 + param_index];
467 if (param == nullptr) {
468 break;
469 }
470
471 switch (param_index) {
472 case 0:
473 package_parameters_.apk_path = param;
474 break;
475
476 case 1:
477 package_parameters_.uid = atoi(param);
478 break;
479
480 case 2:
481 package_parameters_.pkgName = param;
482 break;
483
484 case 3:
485 package_parameters_.instruction_set = param;
486 break;
487
488 case 4:
489 package_parameters_.dexopt_needed = atoi(param);
490 break;
491
492 case 5:
493 package_parameters_.oat_dir = param;
494 break;
495
496 case 6:
497 package_parameters_.dexopt_flags = atoi(param);
498 break;
499
500 case 7:
501 package_parameters_.compiler_filter = param;
502 break;
503
504 case 8:
505 package_parameters_.volume_uuid = ParseNull(param);
506 break;
507
508 case 9:
509 package_parameters_.shared_libraries = ParseNull(param);
510 break;
511
512 case 10:
513 package_parameters_.se_info = ParseNull(param);
514 break;
515
516 case 11:
517 package_parameters_.downgrade = ParseBool(param);
518 break;
519
520 default:
521 LOG(ERROR) << "Too many arguments, got " << param;
522 return false;
523 }
524 }
525
526 if (param_index != 12) {
527 LOG(ERROR) << "Not enough parameters";
528 return false;
529 }
530
531 return true;
532 }
533
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700534 static int ReplaceMask(int input, int old_mask, int new_mask) {
535 return (input & old_mask) != 0 ? new_mask : 0;
536 }
537
538 bool ReadArgumentsV1(int argc ATTRIBUTE_UNUSED, char** argv) {
539 // Check for "dexopt".
Andreas Gamped089ca12016-06-27 14:25:30 -0700540 if (argv[2] == nullptr) {
541 LOG(ERROR) << "Missing parameters";
542 return false;
543 }
544 if (std::string("dexopt").compare(argv[2]) != 0) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700545 LOG(ERROR) << "Expected \"dexopt\"";
Andreas Gamped089ca12016-06-27 14:25:30 -0700546 return false;
547 }
548
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700549 size_t param_index = 0;
550 for (;; ++param_index) {
551 const char* param = argv[3 + param_index];
552 if (param == nullptr) {
553 break;
554 }
555
556 switch (param_index) {
557 case 0:
558 package_parameters_.apk_path = param;
559 break;
560
561 case 1:
562 package_parameters_.uid = atoi(param);
563 break;
564
565 case 2:
566 package_parameters_.pkgName = param;
567 break;
568
569 case 3:
570 package_parameters_.instruction_set = param;
571 break;
572
573 case 4: {
574 // Version 1 had:
575 // DEXOPT_DEX2OAT_NEEDED = 1
576 // DEXOPT_PATCHOAT_NEEDED = 2
577 // DEXOPT_SELF_PATCHOAT_NEEDED = 3
578 // We will simply use DEX2OAT_FROM_SCRATCH.
579 package_parameters_.dexopt_needed = DEX2OAT_FROM_SCRATCH;
580 break;
581 }
582
583 case 5:
584 package_parameters_.oat_dir = param;
585 break;
586
587 case 6: {
588 // Version 1 had:
589 constexpr int OLD_DEXOPT_PUBLIC = 1 << 1;
Nicolas Geoffray2520d442017-05-05 14:32:51 +0100590 // Note: DEXOPT_SAFEMODE has been removed.
591 // constexpr int OLD_DEXOPT_SAFEMODE = 1 << 2;
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700592 constexpr int OLD_DEXOPT_DEBUGGABLE = 1 << 3;
593 constexpr int OLD_DEXOPT_BOOTCOMPLETE = 1 << 4;
594 constexpr int OLD_DEXOPT_PROFILE_GUIDED = 1 << 5;
595 constexpr int OLD_DEXOPT_OTA = 1 << 6;
596 int input = atoi(param);
597 package_parameters_.dexopt_flags =
598 ReplaceMask(input, OLD_DEXOPT_PUBLIC, DEXOPT_PUBLIC) |
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700599 ReplaceMask(input, OLD_DEXOPT_DEBUGGABLE, DEXOPT_DEBUGGABLE) |
600 ReplaceMask(input, OLD_DEXOPT_BOOTCOMPLETE, DEXOPT_BOOTCOMPLETE) |
601 ReplaceMask(input, OLD_DEXOPT_PROFILE_GUIDED, DEXOPT_PROFILE_GUIDED) |
602 ReplaceMask(input, OLD_DEXOPT_OTA, 0);
603 break;
604 }
605
606 case 7:
607 package_parameters_.compiler_filter = param;
608 break;
609
610 case 8:
611 package_parameters_.volume_uuid = ParseNull(param);
612 break;
613
614 case 9:
615 package_parameters_.shared_libraries = ParseNull(param);
616 break;
617
618 default:
619 LOG(ERROR) << "Too many arguments, got " << param;
620 return false;
621 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800622 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700623
624 if (param_index != 10) {
625 LOG(ERROR) << "Not enough parameters";
Andreas Gampe73dae112015-11-19 14:12:14 -0800626 return false;
627 }
628
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700629 // Set se_info to null. It is only relevant for secondary dex files, which we won't
630 // receive from a v1 A side.
631 package_parameters_.se_info = nullptr;
632
Shubham Ajmera45c87432017-06-22 11:10:27 -0700633 // Set downgrade to false. It is only relevant when downgrading compiler
634 // filter, which is not the case during ota.
635 package_parameters_.downgrade = false;
636
Andreas Gampe73dae112015-11-19 14:12:14 -0800637 return true;
638 }
639
640 void PrepareEnvironment() {
Andreas Gamped089ca12016-06-27 14:25:30 -0700641 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
642 environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
643 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
Andreas Gampe73dae112015-11-19 14:12:14 -0800644
645 for (const std::string& e : environ_) {
646 putenv(const_cast<char*>(e.c_str()));
647 }
648 }
649
650 // Ensure that we have the right boot image. The first time any app is
651 // compiled, we'll try to generate it.
Andreas Gamped089ca12016-06-27 14:25:30 -0700652 bool PrepareBootImage(bool force) const {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700653 if (package_parameters_.instruction_set == nullptr) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800654 LOG(ERROR) << "Instruction set missing.";
655 return false;
656 }
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700657 const char* isa = package_parameters_.instruction_set;
Andreas Gampe73dae112015-11-19 14:12:14 -0800658
659 // Check whether the file exists where expected.
Andreas Gamped089ca12016-06-27 14:25:30 -0700660 std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
Andreas Gampe73dae112015-11-19 14:12:14 -0800661 std::string isa_path = dalvik_cache + "/" + isa;
662 std::string art_path = isa_path + "/system@framework@boot.art";
663 std::string oat_path = isa_path + "/system@framework@boot.oat";
Andreas Gamped089ca12016-06-27 14:25:30 -0700664 bool cleared = false;
665 if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
666 // Files exist, assume everything is alright if not forced. Otherwise clean up.
667 if (!force) {
668 return true;
669 }
670 ClearDirectory(isa_path);
671 cleared = true;
Andreas Gampe73dae112015-11-19 14:12:14 -0800672 }
673
Andreas Gamped089ca12016-06-27 14:25:30 -0700674 // Reset umask in otapreopt, so that we control the the access for the files we create.
675 umask(0);
676
Andreas Gampe73dae112015-11-19 14:12:14 -0800677 // Create the directories, if necessary.
678 if (access(dalvik_cache.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700679 if (!CreatePath(dalvik_cache)) {
680 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
Andreas Gampe73dae112015-11-19 14:12:14 -0800681 return false;
682 }
683 }
684 if (access(isa_path.c_str(), F_OK) != 0) {
Andreas Gamped089ca12016-06-27 14:25:30 -0700685 if (!CreatePath(isa_path)) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800686 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
687 return false;
688 }
689 }
690
Andreas Gampe5709b572016-02-12 17:42:59 -0800691 // Prepare to create.
Andreas Gamped089ca12016-06-27 14:25:30 -0700692 if (!cleared) {
693 ClearDirectory(isa_path);
694 }
Andreas Gampe73dae112015-11-19 14:12:14 -0800695
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700696 std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800697 if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
698 return PatchoatBootImage(art_path, isa);
699 } else {
700 // No preopted boot image. Try to compile.
Andreas Gamped089ca12016-06-27 14:25:30 -0700701 return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
Andreas Gampe5709b572016-02-12 17:42:59 -0800702 }
703 }
704
Andreas Gamped089ca12016-06-27 14:25:30 -0700705 static bool CreatePath(const std::string& path) {
706 // Create the given path. Use string processing instead of dirname, as dirname's need for
707 // a writable char buffer is painful.
708
709 // First, try to use the full path.
710 if (mkdir(path.c_str(), 0711) == 0) {
711 return true;
712 }
713 if (errno != ENOENT) {
714 PLOG(ERROR) << "Could not create path " << path;
715 return false;
716 }
717
718 // Now find the parent and try that first.
719 size_t last_slash = path.find_last_of('/');
720 if (last_slash == std::string::npos || last_slash == 0) {
721 PLOG(ERROR) << "Could not create " << path;
722 return false;
723 }
724
725 if (!CreatePath(path.substr(0, last_slash))) {
726 return false;
727 }
728
729 if (mkdir(path.c_str(), 0711) == 0) {
730 return true;
731 }
732 PLOG(ERROR) << "Could not create " << path;
733 return false;
734 }
735
736 static void ClearDirectory(const std::string& dir) {
737 DIR* c_dir = opendir(dir.c_str());
738 if (c_dir == nullptr) {
739 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
740 return;
741 }
742
743 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
744 const char* name = de->d_name;
745 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
746 continue;
747 }
748 // We only want to delete regular files and symbolic links.
749 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
750 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
751 LOG(WARNING) << "Unexpected file "
752 << file
753 << " of type "
754 << std::hex
755 << de->d_type
756 << " encountered.";
757 } else {
758 // Try to unlink the file.
759 if (unlink(file.c_str()) != 0) {
760 PLOG(ERROR) << "Unable to unlink " << file;
761 }
762 }
763 }
764 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
765 }
766
767 bool PatchoatBootImage(const std::string& art_path, const char* isa) const {
Andreas Gampe5709b572016-02-12 17:42:59 -0800768 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
769
770 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700771 cmd.push_back("/system/bin/patchoat");
Andreas Gampe5709b572016-02-12 17:42:59 -0800772
773 cmd.push_back("--input-image-location=/system/framework/boot.art");
774 cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
775
776 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
777
778 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
779 ART_BASE_ADDRESS_MAX_DELTA);
Andreas Gampefebf0bf2016-02-29 18:04:17 -0800780 cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
Andreas Gampe5709b572016-02-12 17:42:59 -0800781
782 std::string error_msg;
783 bool result = Exec(cmd, &error_msg);
784 if (!result) {
785 LOG(ERROR) << "Could not generate boot image: " << error_msg;
786 }
787 return result;
788 }
789
790 bool Dex2oatBootImage(const std::string& boot_cp,
791 const std::string& art_path,
792 const std::string& oat_path,
Andreas Gamped089ca12016-06-27 14:25:30 -0700793 const char* isa) const {
Andreas Gampe73dae112015-11-19 14:12:14 -0800794 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
795 std::vector<std::string> cmd;
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700796 cmd.push_back("/system/bin/dex2oat");
Andreas Gampe73dae112015-11-19 14:12:14 -0800797 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
Andreas Gampe6db8db92016-06-03 10:22:19 -0700798 for (const std::string& boot_part : Split(boot_cp, ":")) {
Andreas Gampe73dae112015-11-19 14:12:14 -0800799 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
800 }
801 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
802
803 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
804 ART_BASE_ADDRESS_MAX_DELTA);
805 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
806
807 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
808
809 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
810 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
811 "-Xms",
812 true,
813 cmd);
814 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
815 "-Xmx",
816 true,
817 cmd);
818 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
819 "--compiler-filter=",
820 false,
821 cmd);
Andreas Gampe9fb85b02016-03-16 10:09:29 -0700822 cmd.push_back("--image-classes=/system/etc/preloaded-classes");
Andreas Gampe73dae112015-11-19 14:12:14 -0800823 // TODO: Compiled-classes.
824 const std::string* extra_opts =
825 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
826 if (extra_opts != nullptr) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700827 std::vector<std::string> extra_vals = Split(*extra_opts, " ");
Andreas Gampe73dae112015-11-19 14:12:14 -0800828 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
829 }
830 // TODO: Should we lower this? It's usually set close to max, because
831 // normally there's not much else going on at boot.
832 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
833 "-j",
834 false,
835 cmd);
836 AddCompilerOptionFromSystemProperty(
837 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
838 "--instruction-set-variant=",
839 false,
840 cmd);
841 AddCompilerOptionFromSystemProperty(
842 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
843 "--instruction-set-features=",
844 false,
845 cmd);
846
847 std::string error_msg;
848 bool result = Exec(cmd, &error_msg);
849 if (!result) {
850 LOG(ERROR) << "Could not generate boot image: " << error_msg;
851 }
852 return result;
853 }
854
855 static const char* ParseNull(const char* arg) {
856 return (strcmp(arg, "!") == 0) ? nullptr : arg;
857 }
858
Andreas Gamped089ca12016-06-27 14:25:30 -0700859 bool ShouldSkipPreopt() const {
Andreas Gampe56f79f92016-06-08 15:11:37 -0700860 // There's one thing we have to be careful about: we may/will be asked to compile an app
861 // living in the system image. This may be a valid request - if the app wasn't compiled,
862 // e.g., if the system image wasn't large enough to include preopted files. However, the
863 // data we have is from the old system, so the driver (the OTA service) can't actually
864 // know. Thus, we will get requests for apps that have preopted components. To avoid
865 // duplication (we'd generate files that are not used and are *not* cleaned up), do two
866 // simple checks:
867 //
868 // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
869 // (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
870 //
871 // 2) If you replace the name in the apk_path with "oat," does the path exist?
872 // (=have a subdirectory for preopted files)
873 //
874 // If the answer to both is yes, skip the dexopt.
875 //
876 // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
877 // be stripped), that's not true for APKs signed outside the build system (so the
878 // jar content must be exactly the same).
879
880 // (This is ugly as it's the only thing where we need to understand the contents
881 // of package_parameters_, but it beats postponing the decision or using the call-
882 // backs to do weird things.)
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700883 const char* apk_path = package_parameters_.apk_path;
884 CHECK(apk_path != nullptr);
885 if (StartsWith(apk_path, android_root_.c_str())) {
886 const char* last_slash = strrchr(apk_path, '/');
Andreas Gampe56f79f92016-06-08 15:11:37 -0700887 if (last_slash != nullptr) {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700888 std::string path(apk_path, last_slash - apk_path + 1);
Andreas Gampe56f79f92016-06-08 15:11:37 -0700889 CHECK(EndsWith(path, "/"));
890 path = path + "oat";
891 if (access(path.c_str(), F_OK) == 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800892 LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700893 return true;
Andreas Gampe56f79f92016-06-08 15:11:37 -0700894 }
895 }
896 }
897
Andreas Gamped089ca12016-06-27 14:25:30 -0700898 // Another issue is unavailability of files in the new system. If the partition
899 // layout changes, otapreopt_chroot may not know about this. Then files from that
900 // partition will not be available and fail to build. This is problematic, as
901 // this tool will wipe the OTA artifact cache and try again (for robustness after
902 // a failed OTA with remaining cache artifacts).
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700903 if (access(apk_path, F_OK) != 0) {
Calin Juravleb3591f62017-11-17 16:38:17 -0800904 LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
Andreas Gamped089ca12016-06-27 14:25:30 -0700905 return true;
906 }
907
908 return false;
909 }
910
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700911 // Run dexopt with the parameters of package_parameters_.
912 int Dexopt() {
Andreas Gampec4ced4f2017-04-14 20:39:56 -0700913 return dexopt(package_parameters_.apk_path,
914 package_parameters_.uid,
915 package_parameters_.pkgName,
916 package_parameters_.instruction_set,
917 package_parameters_.dexopt_needed,
918 package_parameters_.oat_dir,
919 package_parameters_.dexopt_flags,
920 package_parameters_.compiler_filter,
921 package_parameters_.volume_uuid,
922 package_parameters_.shared_libraries,
Shubham Ajmera45c87432017-06-22 11:10:27 -0700923 package_parameters_.se_info,
924 package_parameters_.downgrade);
Andreas Gampe73dae112015-11-19 14:12:14 -0800925 }
926
Andreas Gampeb39d2f02017-04-17 20:04:02 -0700927 int RunPreopt() {
928 if (ShouldSkipPreopt()) {
929 return 0;
930 }
931
932 int dexopt_result = Dexopt();
933 if (dexopt_result == 0) {
934 return 0;
935 }
936
937 // If the dexopt failed, we may have a stale boot image from a previous OTA run.
938 // Then regenerate and retry.
939 if (WEXITSTATUS(dexopt_result) ==
940 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
941 if (!PrepareBootImage(/* force */ true)) {
942 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
943 << dexopt_result;
944 return dexopt_result;
945 }
946
947 int dexopt_result_boot_image_retry = Dexopt();
948 if (dexopt_result_boot_image_retry == 0) {
949 return 0;
950 }
951 }
952
953 // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
954 // if possible.
955 if ((package_parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
956 return dexopt_result;
957 }
958
959 LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
960 package_parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
961 return Dexopt();
962 }
963
Andreas Gampe73dae112015-11-19 14:12:14 -0800964 ////////////////////////////////////
965 // Helpers, mostly taken from ART //
966 ////////////////////////////////////
967
968 // Wrapper on fork/execv to run a command in a subprocess.
Andreas Gamped089ca12016-06-27 14:25:30 -0700969 static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
Andreas Gampe6db8db92016-06-03 10:22:19 -0700970 const std::string command_line = Join(arg_vector, ' ');
Andreas Gampe73dae112015-11-19 14:12:14 -0800971
972 CHECK_GE(arg_vector.size(), 1U) << command_line;
973
974 // Convert the args to char pointers.
975 const char* program = arg_vector[0].c_str();
976 std::vector<char*> args;
977 for (size_t i = 0; i < arg_vector.size(); ++i) {
978 const std::string& arg = arg_vector[i];
979 char* arg_str = const_cast<char*>(arg.c_str());
980 CHECK(arg_str != nullptr) << i;
981 args.push_back(arg_str);
982 }
983 args.push_back(nullptr);
984
985 // Fork and exec.
986 pid_t pid = fork();
987 if (pid == 0) {
988 // No allocation allowed between fork and exec.
989
990 // Change process groups, so we don't get reaped by ProcessManager.
991 setpgid(0, 0);
992
993 execv(program, &args[0]);
994
995 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
996 // _exit to avoid atexit handlers in child.
997 _exit(1);
998 } else {
999 if (pid == -1) {
1000 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1001 command_line.c_str(), strerror(errno));
1002 return false;
1003 }
1004
1005 // wait for subprocess to finish
1006 int status;
1007 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1008 if (got_pid != pid) {
1009 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1010 "wanted %d, got %d: %s",
1011 command_line.c_str(), pid, got_pid, strerror(errno));
1012 return false;
1013 }
1014 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1015 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1016 command_line.c_str());
1017 return false;
1018 }
1019 }
1020 return true;
1021 }
1022
1023 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
1024 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
1025 constexpr size_t kPageSize = PAGE_SIZE;
1026 CHECK_EQ(min_delta % kPageSize, 0u);
1027 CHECK_EQ(max_delta % kPageSize, 0u);
1028 CHECK_LT(min_delta, max_delta);
1029
1030 std::default_random_engine generator;
1031 generator.seed(GetSeed());
1032 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
1033 int32_t r = distribution(generator);
1034 if (r % 2 == 0) {
1035 r = RoundUp(r, kPageSize);
1036 } else {
1037 r = RoundDown(r, kPageSize);
1038 }
1039 CHECK_LE(min_delta, r);
1040 CHECK_GE(max_delta, r);
1041 CHECK_EQ(r % kPageSize, 0u);
1042 return r;
1043 }
1044
1045 static uint64_t GetSeed() {
1046#ifdef __BIONIC__
1047 // Bionic exposes arc4random, use it.
1048 uint64_t random_data;
1049 arc4random_buf(&random_data, sizeof(random_data));
1050 return random_data;
1051#else
1052#error "This is only supposed to run with bionic. Otherwise, implement..."
1053#endif
1054 }
1055
1056 void AddCompilerOptionFromSystemProperty(const char* system_property,
1057 const char* prefix,
1058 bool runtime,
Andreas Gamped089ca12016-06-27 14:25:30 -07001059 std::vector<std::string>& out) const {
1060 const std::string* value = system_properties_.GetProperty(system_property);
Andreas Gampe73dae112015-11-19 14:12:14 -08001061 if (value != nullptr) {
1062 if (runtime) {
1063 out.push_back("--runtime-arg");
1064 }
1065 if (prefix != nullptr) {
1066 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
1067 } else {
1068 out.push_back(*value);
1069 }
1070 }
1071 }
1072
Andreas Gamped089ca12016-06-27 14:25:30 -07001073 static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
1074 static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
1075 static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
1076 // The index of the instruction-set string inside the package parameters. Needed for
1077 // some special-casing that requires knowledge of the instruction-set.
1078 static constexpr size_t kISAIndex = 3;
1079
Andreas Gampe73dae112015-11-19 14:12:14 -08001080 // Stores the system properties read out of the B partition. We need to use these properties
1081 // to compile, instead of the A properties we could get from init/get_property.
1082 SystemProperties system_properties_;
1083
Andreas Gamped089ca12016-06-27 14:25:30 -07001084 // Some select properties that are always needed.
1085 std::string target_slot_;
1086 std::string android_root_;
1087 std::string android_data_;
1088 std::string boot_classpath_;
1089 std::string asec_mountpoint_;
1090
Andreas Gampec4ced4f2017-04-14 20:39:56 -07001091 Parameters package_parameters_;
Andreas Gampe73dae112015-11-19 14:12:14 -08001092
1093 // Store environment values we need to set.
1094 std::vector<std::string> environ_;
1095};
1096
1097OTAPreoptService gOps;
1098
1099////////////////////////
1100// Plug-in functions. //
1101////////////////////////
1102
1103int get_property(const char *key, char *value, const char *default_value) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001104 return gOps.GetProperty(key, value, default_value);
1105}
1106
1107// Compute the output path of
1108bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
1109 const char *apk_path,
1110 const char *instruction_set) {
Dan Austin9c8f93a2016-06-03 16:15:54 -07001111 const char *file_name_start;
1112 const char *file_name_end;
Andreas Gampe73dae112015-11-19 14:12:14 -08001113
1114 file_name_start = strrchr(apk_path, '/');
1115 if (file_name_start == nullptr) {
1116 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
1117 return false;
1118 }
1119 file_name_end = strrchr(file_name_start, '.');
1120 if (file_name_end == nullptr) {
1121 ALOGE("apk_path '%s' has no extension\n", apk_path);
1122 return false;
1123 }
1124
1125 // Calculate file_name
1126 file_name_start++; // Move past '/', is valid as file_name_end is valid.
1127 size_t file_name_len = file_name_end - file_name_start;
1128 std::string file_name(file_name_start, file_name_len);
1129
1130 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
Andreas Gamped089ca12016-06-27 14:25:30 -07001131 snprintf(path,
1132 PKG_PATH_MAX,
1133 "%s/%s/%s.odex.%s",
1134 oat_dir,
1135 instruction_set,
1136 file_name.c_str(),
1137 gOps.GetTargetSlot().c_str());
Andreas Gampe73dae112015-11-19 14:12:14 -08001138 return true;
1139}
1140
1141/*
1142 * Computes the odex file for the given apk_path and instruction_set.
1143 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
1144 *
1145 * Returns false if it failed to determine the odex file path.
1146 */
1147bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
1148 const char *instruction_set) {
Andreas Gampe73dae112015-11-19 14:12:14 -08001149 const char *path_end = strrchr(apk_path, '/');
1150 if (path_end == nullptr) {
1151 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
1152 return false;
1153 }
1154 std::string path_component(apk_path, path_end - apk_path);
1155
1156 const char *name_begin = path_end + 1;
1157 const char *extension_start = strrchr(name_begin, '.');
1158 if (extension_start == nullptr) {
1159 ALOGE("apk_path '%s' has no extension.\n", apk_path);
1160 return false;
1161 }
1162 std::string name_component(name_begin, extension_start - name_begin);
1163
Andreas Gamped089ca12016-06-27 14:25:30 -07001164 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
Andreas Gampe73dae112015-11-19 14:12:14 -08001165 path_component.c_str(),
1166 instruction_set,
Andreas Gamped089ca12016-06-27 14:25:30 -07001167 name_component.c_str(),
1168 gOps.GetTargetSlot().c_str());
1169 if (new_path.length() >= PKG_PATH_MAX) {
1170 LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
1171 return false;
1172 }
Andreas Gampe73dae112015-11-19 14:12:14 -08001173 strcpy(path, new_path.c_str());
1174 return true;
1175}
1176
1177bool create_cache_path(char path[PKG_PATH_MAX],
1178 const char *src,
1179 const char *instruction_set) {
1180 size_t srclen = strlen(src);
1181
1182 /* demand that we are an absolute path */
1183 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
1184 return false;
1185 }
1186
1187 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
1188 return false;
1189 }
1190
1191 std::string from_src = std::string(src + 1);
1192 std::replace(from_src.begin(), from_src.end(), '/', '@');
1193
1194 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
Andreas Gamped089ca12016-06-27 14:25:30 -07001195 gOps.GetOTADataDirectory().c_str(),
Andreas Gampe73dae112015-11-19 14:12:14 -08001196 DALVIK_CACHE,
1197 instruction_set,
1198 from_src.c_str(),
David Brazdil249c1792016-09-06 15:35:28 +01001199 DALVIK_CACHE_POSTFIX);
Andreas Gampe73dae112015-11-19 14:12:14 -08001200
1201 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
1202 return false;
1203 }
1204 strcpy(path, assembled_path.c_str());
1205
1206 return true;
1207}
1208
Andreas Gampe73dae112015-11-19 14:12:14 -08001209static int log_callback(int type, const char *fmt, ...) {
1210 va_list ap;
1211 int priority;
1212
1213 switch (type) {
1214 case SELINUX_WARNING:
1215 priority = ANDROID_LOG_WARN;
1216 break;
1217 case SELINUX_INFO:
1218 priority = ANDROID_LOG_INFO;
1219 break;
1220 default:
1221 priority = ANDROID_LOG_ERROR;
1222 break;
1223 }
1224 va_start(ap, fmt);
1225 LOG_PRI_VA(priority, "SELinux", fmt, ap);
1226 va_end(ap);
1227 return 0;
1228}
1229
1230static int otapreopt_main(const int argc, char *argv[]) {
1231 int selinux_enabled = (is_selinux_enabled() > 0);
1232
1233 setenv("ANDROID_LOG_TAGS", "*:v", 1);
1234 android::base::InitLogging(argv);
1235
Andreas Gampe73dae112015-11-19 14:12:14 -08001236 if (argc < 2) {
1237 ALOGE("Expecting parameters");
1238 exit(1);
1239 }
1240
1241 union selinux_callback cb;
1242 cb.func_log = log_callback;
1243 selinux_set_callback(SELINUX_CB_LOG, cb);
1244
Andreas Gampe73dae112015-11-19 14:12:14 -08001245 if (selinux_enabled && selinux_status_open(true) < 0) {
1246 ALOGE("Could not open selinux status; exiting.\n");
1247 exit(1);
1248 }
1249
1250 int ret = android::installd::gOps.Main(argc, argv);
1251
1252 return ret;
1253}
1254
1255} // namespace installd
1256} // namespace android
1257
1258int main(const int argc, char *argv[]) {
1259 return android::installd::otapreopt_main(argc, argv);
1260}