blob: 27f7939b571f5f7101db48c9f7c498a9172f1697 [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>
19#include <random>
20#include <selinux/android.h>
21#include <selinux/avc.h>
22#include <stdlib.h>
23#include <string.h>
24#include <sys/capability.h>
25#include <sys/prctl.h>
26#include <sys/stat.h>
27#include <sys/wait.h>
28
29#include <android-base/logging.h>
30#include <android-base/macros.h>
31#include <android-base/stringprintf.h>
32#include <cutils/fs.h>
33#include <cutils/log.h>
34#include <cutils/properties.h>
35#include <private/android_filesystem_config.h>
36
37#include <commands.h>
38#include <globals.h>
39#include <installd_deps.h> // Need to fill in requirements of commands.
40#include <string_helpers.h>
41#include <system_properties.h>
42#include <utils.h>
43
44#ifndef LOG_TAG
45#define LOG_TAG "otapreopt"
46#endif
47
48#define BUFFER_MAX 1024 /* input buffer for commands */
49#define TOKEN_MAX 16 /* max number of arguments in buffer */
50#define REPLY_MAX 256 /* largest reply allowed */
51
52using android::base::StringPrintf;
53
54namespace android {
55namespace installd {
56
57static constexpr const char* kBootClassPathPropertyName = "env.BOOTCLASSPATH";
58static constexpr const char* kAndroidRootPathPropertyName = "env.ANDROID_ROOT";
59static constexpr const char* kOTARootDirectory = "/system-b";
60static constexpr size_t kISAIndex = 3;
61
62template<typename T>
63static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
64 return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
65}
66
67template<typename T>
68static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
69 return RoundDown(x + n - 1, n);
70}
71
72class OTAPreoptService {
73 public:
74 static constexpr const char* kOTADataDirectory = "/data/ota";
75
76 // Main driver. Performs the following steps.
77 //
78 // 1) Parse options (read system properties etc from B partition).
79 //
80 // 2) Read in package data.
81 //
82 // 3) Prepare environment variables.
83 //
84 // 4) Prepare(compile) boot image, if necessary.
85 //
86 // 5) Run update.
87 int Main(int argc, char** argv) {
88 if (!ReadSystemProperties()) {
89 LOG(ERROR)<< "Failed reading system properties.";
90 return 1;
91 }
92
93 if (!ReadEnvironment()) {
94 LOG(ERROR) << "Failed reading environment properties.";
95 return 2;
96 }
97
98 if (!ReadPackage(argc, argv)) {
99 LOG(ERROR) << "Failed reading command line file.";
100 return 3;
101 }
102
103 PrepareEnvironment();
104
105 if (!PrepareBootImage()) {
106 LOG(ERROR) << "Failed preparing boot image.";
107 return 4;
108 }
109
110 int dexopt_retcode = RunPreopt();
111
112 return dexopt_retcode;
113 }
114
115 int GetProperty(const char* key, char* value, const char* default_value) {
116 const std::string* prop_value = system_properties_.GetProperty(key);
117 if (prop_value == nullptr) {
118 if (default_value == nullptr) {
119 return 0;
120 }
121 // Copy in the default value.
122 strncpy(value, default_value, kPropertyValueMax - 1);
123 value[kPropertyValueMax - 1] = 0;
124 return strlen(default_value);// TODO: Need to truncate?
125 }
126 size_t size = std::min(kPropertyValueMax - 1, prop_value->length());
127 strncpy(value, prop_value->data(), size);
128 value[size] = 0;
129 return static_cast<int>(size);
130 }
131
132private:
133 bool ReadSystemProperties() {
134 // TODO(agampe): What to do about the things in default.prop? It's only heap sizes, so it's easy
135 // to emulate for now, but has issues (e.g., vendors modifying the boot classpath
136 // may require larger values here - revisit). That's why this goes first, so that
137 // if those dummy values are overridden in build.prop, that's what we'll get.
138 //
139 // Note: It seems we'll get access to the B root partition, so we should read the default.prop
140 // file.
141 // if (!system_properties_.Load(b_mount_path_ + "/default.prop") {
142 // return false;
143 // }
144 system_properties_.SetProperty("dalvik.vm.image-dex2oat-Xms", "64m");
145 system_properties_.SetProperty("dalvik.vm.image-dex2oat-Xmx", "64m");
146 system_properties_.SetProperty("dalvik.vm.dex2oat-Xms", "64m");
147 system_properties_.SetProperty("dalvik.vm.dex2oat-Xmx", "512m");
148
149 // TODO(agampe): Do this properly/test.
150 return system_properties_.Load(b_mount_path_ + "/system/build.prop");
151 }
152
153 bool ReadEnvironment() {
154 // Read important environment variables. For simplicity, store them as
155 // system properties.
156 // TODO(agampe): We'll have to parse init.environ.rc for BOOTCLASSPATH.
157 // For now, just the A version.
158 const char* boot_classpath = getenv("BOOTCLASSPATH");
159 if (boot_classpath == nullptr) {
160 return false;
161 }
162 system_properties_.SetProperty(kBootClassPathPropertyName, boot_classpath);
163
164 const char* root_path = getenv("ANDROID_ROOT");
165 if (root_path == nullptr) {
166 return false;
167 }
168 system_properties_.SetProperty(kAndroidRootPathPropertyName, b_mount_path_ + root_path);
169
170 return true;
171 }
172
173 bool ReadPackage(int argc ATTRIBUTE_UNUSED, char** argv) {
174 size_t index = 0;
175 while (index < ARRAY_SIZE(package_parameters_) &&
176 argv[index + 1] != nullptr) {
177 package_parameters_[index] = argv[index + 1];
178 index++;
179 }
180 if (index != ARRAY_SIZE(package_parameters_)) {
181 LOG(ERROR) << "Wrong number of parameters";
182 return false;
183 }
184
185 return true;
186 }
187
188 void PrepareEnvironment() {
189 CHECK(system_properties_.GetProperty(kBootClassPathPropertyName) != nullptr);
190 const std::string& boot_cp =
191 *system_properties_.GetProperty(kBootClassPathPropertyName);
192 environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_cp.c_str()));
193 environ_.push_back(StringPrintf("ANDROID_DATA=%s", kOTADataDirectory));
194 CHECK(system_properties_.GetProperty(kAndroidRootPathPropertyName) != nullptr);
195 const std::string& android_root =
196 *system_properties_.GetProperty(kAndroidRootPathPropertyName);
197 environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root.c_str()));
198
199 for (const std::string& e : environ_) {
200 putenv(const_cast<char*>(e.c_str()));
201 }
202 }
203
204 // Ensure that we have the right boot image. The first time any app is
205 // compiled, we'll try to generate it.
206 bool PrepareBootImage() {
207 if (package_parameters_[kISAIndex] == nullptr) {
208 LOG(ERROR) << "Instruction set missing.";
209 return false;
210 }
211 const char* isa = package_parameters_[kISAIndex];
212
213 // Check whether the file exists where expected.
214 std::string dalvik_cache = std::string(kOTADataDirectory) + "/" + DALVIK_CACHE;
215 std::string isa_path = dalvik_cache + "/" + isa;
216 std::string art_path = isa_path + "/system@framework@boot.art";
217 std::string oat_path = isa_path + "/system@framework@boot.oat";
218 if (access(art_path.c_str(), F_OK) == 0 &&
219 access(oat_path.c_str(), F_OK) == 0) {
220 // Files exist, assume everything is alright.
221 return true;
222 }
223
224 // Create the directories, if necessary.
225 if (access(dalvik_cache.c_str(), F_OK) != 0) {
226 if (mkdir(dalvik_cache.c_str(), 0711) != 0) {
227 PLOG(ERROR) << "Could not create dalvik-cache dir";
228 return false;
229 }
230 }
231 if (access(isa_path.c_str(), F_OK) != 0) {
232 if (mkdir(isa_path.c_str(), 0711) != 0) {
233 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
234 return false;
235 }
236 }
237
238 // Prepare and run dex2oat.
239 // TODO: Delete files, just for a blank slate.
240 const std::string& boot_cp = *system_properties_.GetProperty(kBootClassPathPropertyName);
241
242 // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
243 std::vector<std::string> cmd;
244 cmd.push_back(b_mount_path_ + "/system/bin/dex2oat");
245 cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
246 for (const std::string& boot_part : Split(boot_cp, ':')) {
247 cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
248 }
249 cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
250
251 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
252 ART_BASE_ADDRESS_MAX_DELTA);
253 cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
254
255 cmd.push_back(StringPrintf("--instruction-set=%s", isa));
256
257 // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
258 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
259 "-Xms",
260 true,
261 cmd);
262 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
263 "-Xmx",
264 true,
265 cmd);
266 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
267 "--compiler-filter=",
268 false,
269 cmd);
270 cmd.push_back(StringPrintf("--image-classes=%s/system/etc/preloaded-classes",
271 b_mount_path_.c_str()));
272 // TODO: Compiled-classes.
273 const std::string* extra_opts =
274 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
275 if (extra_opts != nullptr) {
276 std::vector<std::string> extra_vals = Split(*extra_opts, ' ');
277 cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
278 }
279 // TODO: Should we lower this? It's usually set close to max, because
280 // normally there's not much else going on at boot.
281 AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
282 "-j",
283 false,
284 cmd);
285 AddCompilerOptionFromSystemProperty(
286 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
287 "--instruction-set-variant=",
288 false,
289 cmd);
290 AddCompilerOptionFromSystemProperty(
291 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
292 "--instruction-set-features=",
293 false,
294 cmd);
295
296 std::string error_msg;
297 bool result = Exec(cmd, &error_msg);
298 if (!result) {
299 LOG(ERROR) << "Could not generate boot image: " << error_msg;
300 }
301 return result;
302 }
303
304 static const char* ParseNull(const char* arg) {
305 return (strcmp(arg, "!") == 0) ? nullptr : arg;
306 }
307
308 int RunPreopt() {
309 /* apk_path, uid, pkgname, instruction_set, dexopt_needed, oat_dir, dexopt_flags,
310 volume_uuid, use_profiles */
311 int ret = dexopt(package_parameters_[0],
312 atoi(package_parameters_[1]),
313 package_parameters_[2],
314 package_parameters_[3],
315 atoi(package_parameters_[4]),
316 package_parameters_[5],
317 atoi(package_parameters_[6]),
318 ParseNull(package_parameters_[7]),
319 (atoi(package_parameters_[8]) == 0 ? false : true));
320 return ret;
321 }
322
323 ////////////////////////////////////
324 // Helpers, mostly taken from ART //
325 ////////////////////////////////////
326
327 // Wrapper on fork/execv to run a command in a subprocess.
328 bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
329 const std::string command_line(Join(arg_vector, ' '));
330
331 CHECK_GE(arg_vector.size(), 1U) << command_line;
332
333 // Convert the args to char pointers.
334 const char* program = arg_vector[0].c_str();
335 std::vector<char*> args;
336 for (size_t i = 0; i < arg_vector.size(); ++i) {
337 const std::string& arg = arg_vector[i];
338 char* arg_str = const_cast<char*>(arg.c_str());
339 CHECK(arg_str != nullptr) << i;
340 args.push_back(arg_str);
341 }
342 args.push_back(nullptr);
343
344 // Fork and exec.
345 pid_t pid = fork();
346 if (pid == 0) {
347 // No allocation allowed between fork and exec.
348
349 // Change process groups, so we don't get reaped by ProcessManager.
350 setpgid(0, 0);
351
352 execv(program, &args[0]);
353
354 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
355 // _exit to avoid atexit handlers in child.
356 _exit(1);
357 } else {
358 if (pid == -1) {
359 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
360 command_line.c_str(), strerror(errno));
361 return false;
362 }
363
364 // wait for subprocess to finish
365 int status;
366 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
367 if (got_pid != pid) {
368 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
369 "wanted %d, got %d: %s",
370 command_line.c_str(), pid, got_pid, strerror(errno));
371 return false;
372 }
373 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
374 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
375 command_line.c_str());
376 return false;
377 }
378 }
379 return true;
380 }
381
382 // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
383 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
384 constexpr size_t kPageSize = PAGE_SIZE;
385 CHECK_EQ(min_delta % kPageSize, 0u);
386 CHECK_EQ(max_delta % kPageSize, 0u);
387 CHECK_LT(min_delta, max_delta);
388
389 std::default_random_engine generator;
390 generator.seed(GetSeed());
391 std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
392 int32_t r = distribution(generator);
393 if (r % 2 == 0) {
394 r = RoundUp(r, kPageSize);
395 } else {
396 r = RoundDown(r, kPageSize);
397 }
398 CHECK_LE(min_delta, r);
399 CHECK_GE(max_delta, r);
400 CHECK_EQ(r % kPageSize, 0u);
401 return r;
402 }
403
404 static uint64_t GetSeed() {
405#ifdef __BIONIC__
406 // Bionic exposes arc4random, use it.
407 uint64_t random_data;
408 arc4random_buf(&random_data, sizeof(random_data));
409 return random_data;
410#else
411#error "This is only supposed to run with bionic. Otherwise, implement..."
412#endif
413 }
414
415 void AddCompilerOptionFromSystemProperty(const char* system_property,
416 const char* prefix,
417 bool runtime,
418 std::vector<std::string>& out) {
419 const std::string* value =
420 system_properties_.GetProperty(system_property);
421 if (value != nullptr) {
422 if (runtime) {
423 out.push_back("--runtime-arg");
424 }
425 if (prefix != nullptr) {
426 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
427 } else {
428 out.push_back(*value);
429 }
430 }
431 }
432
433 // The path where the B partitions are mounted.
434 // TODO(agampe): If we're running this *inside* the change-root, we wouldn't need this.
435 std::string b_mount_path_;
436
437 // Stores the system properties read out of the B partition. We need to use these properties
438 // to compile, instead of the A properties we could get from init/get_property.
439 SystemProperties system_properties_;
440
441 const char* package_parameters_[9];
442
443 // Store environment values we need to set.
444 std::vector<std::string> environ_;
445};
446
447OTAPreoptService gOps;
448
449////////////////////////
450// Plug-in functions. //
451////////////////////////
452
453int get_property(const char *key, char *value, const char *default_value) {
454 // TODO: Replace with system-properties map.
455 return gOps.GetProperty(key, value, default_value);
456}
457
458// Compute the output path of
459bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
460 const char *apk_path,
461 const char *instruction_set) {
462 // TODO: Insert B directory.
463 char *file_name_start;
464 char *file_name_end;
465
466 file_name_start = strrchr(apk_path, '/');
467 if (file_name_start == nullptr) {
468 ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
469 return false;
470 }
471 file_name_end = strrchr(file_name_start, '.');
472 if (file_name_end == nullptr) {
473 ALOGE("apk_path '%s' has no extension\n", apk_path);
474 return false;
475 }
476
477 // Calculate file_name
478 file_name_start++; // Move past '/', is valid as file_name_end is valid.
479 size_t file_name_len = file_name_end - file_name_start;
480 std::string file_name(file_name_start, file_name_len);
481
482 // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
483 snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex.b", oat_dir, instruction_set,
484 file_name.c_str());
485 return true;
486}
487
488/*
489 * Computes the odex file for the given apk_path and instruction_set.
490 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
491 *
492 * Returns false if it failed to determine the odex file path.
493 */
494bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
495 const char *instruction_set) {
496 if (StringPrintf("%soat/%s/odex.b", apk_path, instruction_set).length() + 1 > PKG_PATH_MAX) {
497 ALOGE("apk_path '%s' may be too long to form odex file path.\n", apk_path);
498 return false;
499 }
500
501 const char *path_end = strrchr(apk_path, '/');
502 if (path_end == nullptr) {
503 ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
504 return false;
505 }
506 std::string path_component(apk_path, path_end - apk_path);
507
508 const char *name_begin = path_end + 1;
509 const char *extension_start = strrchr(name_begin, '.');
510 if (extension_start == nullptr) {
511 ALOGE("apk_path '%s' has no extension.\n", apk_path);
512 return false;
513 }
514 std::string name_component(name_begin, extension_start - name_begin);
515
516 std::string new_path = StringPrintf("%s/oat/%s/%s.odex.b",
517 path_component.c_str(),
518 instruction_set,
519 name_component.c_str());
520 CHECK_LT(new_path.length(), PKG_PATH_MAX);
521 strcpy(path, new_path.c_str());
522 return true;
523}
524
525bool create_cache_path(char path[PKG_PATH_MAX],
526 const char *src,
527 const char *instruction_set) {
528 size_t srclen = strlen(src);
529
530 /* demand that we are an absolute path */
531 if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
532 return false;
533 }
534
535 if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
536 return false;
537 }
538
539 std::string from_src = std::string(src + 1);
540 std::replace(from_src.begin(), from_src.end(), '/', '@');
541
542 std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
543 OTAPreoptService::kOTADataDirectory,
544 DALVIK_CACHE,
545 instruction_set,
546 from_src.c_str(),
547 DALVIK_CACHE_POSTFIX2);
548
549 if (assembled_path.length() + 1 > PKG_PATH_MAX) {
550 return false;
551 }
552 strcpy(path, assembled_path.c_str());
553
554 return true;
555}
556
557bool initialize_globals() {
558 const char* data_path = getenv("ANDROID_DATA");
559 if (data_path == nullptr) {
560 ALOGE("Could not find ANDROID_DATA");
561 return false;
562 }
563 return init_globals_from_data_and_root(data_path, kOTARootDirectory);
564}
565
566static bool initialize_directories() {
567 // This is different from the normal installd. We only do the base
568 // directory, the rest will be created on demand when each app is compiled.
569 mode_t old_umask = umask(0);
570 LOG(INFO) << "Old umask: " << old_umask;
571 if (access(OTAPreoptService::kOTADataDirectory, R_OK) < 0) {
572 ALOGE("Could not access %s\n", OTAPreoptService::kOTADataDirectory);
573 return false;
574 }
575 return true;
576}
577
578static int log_callback(int type, const char *fmt, ...) {
579 va_list ap;
580 int priority;
581
582 switch (type) {
583 case SELINUX_WARNING:
584 priority = ANDROID_LOG_WARN;
585 break;
586 case SELINUX_INFO:
587 priority = ANDROID_LOG_INFO;
588 break;
589 default:
590 priority = ANDROID_LOG_ERROR;
591 break;
592 }
593 va_start(ap, fmt);
594 LOG_PRI_VA(priority, "SELinux", fmt, ap);
595 va_end(ap);
596 return 0;
597}
598
599static int otapreopt_main(const int argc, char *argv[]) {
600 int selinux_enabled = (is_selinux_enabled() > 0);
601
602 setenv("ANDROID_LOG_TAGS", "*:v", 1);
603 android::base::InitLogging(argv);
604
605 ALOGI("otapreopt firing up\n");
606
607 if (argc < 2) {
608 ALOGE("Expecting parameters");
609 exit(1);
610 }
611
612 union selinux_callback cb;
613 cb.func_log = log_callback;
614 selinux_set_callback(SELINUX_CB_LOG, cb);
615
616 if (!initialize_globals()) {
617 ALOGE("Could not initialize globals; exiting.\n");
618 exit(1);
619 }
620
621 if (!initialize_directories()) {
622 ALOGE("Could not create directories; exiting.\n");
623 exit(1);
624 }
625
626 if (selinux_enabled && selinux_status_open(true) < 0) {
627 ALOGE("Could not open selinux status; exiting.\n");
628 exit(1);
629 }
630
631 int ret = android::installd::gOps.Main(argc, argv);
632
633 return ret;
634}
635
636} // namespace installd
637} // namespace android
638
639int main(const int argc, char *argv[]) {
640 return android::installd::otapreopt_main(argc, argv);
641}