otapreopt.cpp revision 9fb85b0667235ebfdea00ea345febc8f6eb203d2
1/*
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("/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("/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, 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 to create.
239        // TODO: Delete files, just for a blank slate.
240        const std::string& boot_cp = *system_properties_.GetProperty(kBootClassPathPropertyName);
241
242        std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
243        if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
244          return PatchoatBootImage(art_path, isa);
245        } else {
246          // No preopted boot image. Try to compile.
247          return Dex2oatBootImage(boot_cp, art_path, oat_path, isa);
248        }
249    }
250
251    bool PatchoatBootImage(const std::string& art_path, const char* isa) {
252        // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
253
254        std::vector<std::string> cmd;
255        cmd.push_back("/system/bin/patchoat");
256
257        cmd.push_back("--input-image-location=/system/framework/boot.art");
258        cmd.push_back(StringPrintf("--output-image-file=%s", art_path.c_str()));
259
260        cmd.push_back(StringPrintf("--instruction-set=%s", isa));
261
262        int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
263                                                          ART_BASE_ADDRESS_MAX_DELTA);
264        cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
265
266        std::string error_msg;
267        bool result = Exec(cmd, &error_msg);
268        if (!result) {
269            LOG(ERROR) << "Could not generate boot image: " << error_msg;
270        }
271        return result;
272    }
273
274    bool Dex2oatBootImage(const std::string& boot_cp,
275                          const std::string& art_path,
276                          const std::string& oat_path,
277                          const char* isa) {
278        // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
279        std::vector<std::string> cmd;
280        cmd.push_back("/system/bin/dex2oat");
281        cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
282        for (const std::string& boot_part : Split(boot_cp, ':')) {
283            cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
284        }
285        cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
286
287        int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
288                ART_BASE_ADDRESS_MAX_DELTA);
289        cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
290
291        cmd.push_back(StringPrintf("--instruction-set=%s", isa));
292
293        // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
294        AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
295                "-Xms",
296                true,
297                cmd);
298        AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
299                "-Xmx",
300                true,
301                cmd);
302        AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
303                "--compiler-filter=",
304                false,
305                cmd);
306        cmd.push_back("--image-classes=/system/etc/preloaded-classes");
307        // TODO: Compiled-classes.
308        const std::string* extra_opts =
309                system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
310        if (extra_opts != nullptr) {
311            std::vector<std::string> extra_vals = Split(*extra_opts, ' ');
312            cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
313        }
314        // TODO: Should we lower this? It's usually set close to max, because
315        //       normally there's not much else going on at boot.
316        AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
317                "-j",
318                false,
319                cmd);
320        AddCompilerOptionFromSystemProperty(
321                StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
322                "--instruction-set-variant=",
323                false,
324                cmd);
325        AddCompilerOptionFromSystemProperty(
326                StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
327                "--instruction-set-features=",
328                false,
329                cmd);
330
331        std::string error_msg;
332        bool result = Exec(cmd, &error_msg);
333        if (!result) {
334            LOG(ERROR) << "Could not generate boot image: " << error_msg;
335        }
336        return result;
337    }
338
339    static const char* ParseNull(const char* arg) {
340        return (strcmp(arg, "!") == 0) ? nullptr : arg;
341    }
342
343    int RunPreopt() {
344        /* apk_path, uid, pkgname, instruction_set, dexopt_needed, oat_dir, dexopt_flags,
345           volume_uuid, use_profiles */
346        int ret = dexopt(package_parameters_[0],
347                atoi(package_parameters_[1]),
348                package_parameters_[2],
349                package_parameters_[3],
350                atoi(package_parameters_[4]),
351                package_parameters_[5],
352                atoi(package_parameters_[6]),
353                ParseNull(package_parameters_[7]),
354                (atoi(package_parameters_[8]) == 0 ? false : true));
355        return ret;
356    }
357
358    ////////////////////////////////////
359    // Helpers, mostly taken from ART //
360    ////////////////////////////////////
361
362    // Wrapper on fork/execv to run a command in a subprocess.
363    bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
364        const std::string command_line(Join(arg_vector, ' '));
365
366        CHECK_GE(arg_vector.size(), 1U) << command_line;
367
368        // Convert the args to char pointers.
369        const char* program = arg_vector[0].c_str();
370        std::vector<char*> args;
371        for (size_t i = 0; i < arg_vector.size(); ++i) {
372            const std::string& arg = arg_vector[i];
373            char* arg_str = const_cast<char*>(arg.c_str());
374            CHECK(arg_str != nullptr) << i;
375            args.push_back(arg_str);
376        }
377        args.push_back(nullptr);
378
379        // Fork and exec.
380        pid_t pid = fork();
381        if (pid == 0) {
382            // No allocation allowed between fork and exec.
383
384            // Change process groups, so we don't get reaped by ProcessManager.
385            setpgid(0, 0);
386
387            execv(program, &args[0]);
388
389            PLOG(ERROR) << "Failed to execv(" << command_line << ")";
390            // _exit to avoid atexit handlers in child.
391            _exit(1);
392        } else {
393            if (pid == -1) {
394                *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
395                        command_line.c_str(), strerror(errno));
396                return false;
397            }
398
399            // wait for subprocess to finish
400            int status;
401            pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
402            if (got_pid != pid) {
403                *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
404                        "wanted %d, got %d: %s",
405                        command_line.c_str(), pid, got_pid, strerror(errno));
406                return false;
407            }
408            if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
409                *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
410                        command_line.c_str());
411                return false;
412            }
413        }
414        return true;
415    }
416
417    // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
418    static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
419        constexpr size_t kPageSize = PAGE_SIZE;
420        CHECK_EQ(min_delta % kPageSize, 0u);
421        CHECK_EQ(max_delta % kPageSize, 0u);
422        CHECK_LT(min_delta, max_delta);
423
424        std::default_random_engine generator;
425        generator.seed(GetSeed());
426        std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
427        int32_t r = distribution(generator);
428        if (r % 2 == 0) {
429            r = RoundUp(r, kPageSize);
430        } else {
431            r = RoundDown(r, kPageSize);
432        }
433        CHECK_LE(min_delta, r);
434        CHECK_GE(max_delta, r);
435        CHECK_EQ(r % kPageSize, 0u);
436        return r;
437    }
438
439    static uint64_t GetSeed() {
440#ifdef __BIONIC__
441        // Bionic exposes arc4random, use it.
442        uint64_t random_data;
443        arc4random_buf(&random_data, sizeof(random_data));
444        return random_data;
445#else
446#error "This is only supposed to run with bionic. Otherwise, implement..."
447#endif
448    }
449
450    void AddCompilerOptionFromSystemProperty(const char* system_property,
451            const char* prefix,
452            bool runtime,
453            std::vector<std::string>& out) {
454        const std::string* value =
455        system_properties_.GetProperty(system_property);
456        if (value != nullptr) {
457            if (runtime) {
458                out.push_back("--runtime-arg");
459            }
460            if (prefix != nullptr) {
461                out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
462            } else {
463                out.push_back(*value);
464            }
465        }
466    }
467
468    // Stores the system properties read out of the B partition. We need to use these properties
469    // to compile, instead of the A properties we could get from init/get_property.
470    SystemProperties system_properties_;
471
472    const char* package_parameters_[9];
473
474    // Store environment values we need to set.
475    std::vector<std::string> environ_;
476};
477
478OTAPreoptService gOps;
479
480////////////////////////
481// Plug-in functions. //
482////////////////////////
483
484int get_property(const char *key, char *value, const char *default_value) {
485    // TODO: Replace with system-properties map.
486    return gOps.GetProperty(key, value, default_value);
487}
488
489// Compute the output path of
490bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
491                             const char *apk_path,
492                             const char *instruction_set) {
493    // TODO: Insert B directory.
494    char *file_name_start;
495    char *file_name_end;
496
497    file_name_start = strrchr(apk_path, '/');
498    if (file_name_start == nullptr) {
499        ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
500        return false;
501    }
502    file_name_end = strrchr(file_name_start, '.');
503    if (file_name_end == nullptr) {
504        ALOGE("apk_path '%s' has no extension\n", apk_path);
505        return false;
506    }
507
508    // Calculate file_name
509    file_name_start++;  // Move past '/', is valid as file_name_end is valid.
510    size_t file_name_len = file_name_end - file_name_start;
511    std::string file_name(file_name_start, file_name_len);
512
513    // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
514    snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex.b", oat_dir, instruction_set,
515             file_name.c_str());
516    return true;
517}
518
519/*
520 * Computes the odex file for the given apk_path and instruction_set.
521 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
522 *
523 * Returns false if it failed to determine the odex file path.
524 */
525bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
526                              const char *instruction_set) {
527    if (StringPrintf("%soat/%s/odex.b", apk_path, instruction_set).length() + 1 > PKG_PATH_MAX) {
528        ALOGE("apk_path '%s' may be too long to form odex file path.\n", apk_path);
529        return false;
530    }
531
532    const char *path_end = strrchr(apk_path, '/');
533    if (path_end == nullptr) {
534        ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
535        return false;
536    }
537    std::string path_component(apk_path, path_end - apk_path);
538
539    const char *name_begin = path_end + 1;
540    const char *extension_start = strrchr(name_begin, '.');
541    if (extension_start == nullptr) {
542        ALOGE("apk_path '%s' has no extension.\n", apk_path);
543        return false;
544    }
545    std::string name_component(name_begin, extension_start - name_begin);
546
547    std::string new_path = StringPrintf("%s/oat/%s/%s.odex.b",
548                                        path_component.c_str(),
549                                        instruction_set,
550                                        name_component.c_str());
551    CHECK_LT(new_path.length(), PKG_PATH_MAX);
552    strcpy(path, new_path.c_str());
553    return true;
554}
555
556bool create_cache_path(char path[PKG_PATH_MAX],
557                       const char *src,
558                       const char *instruction_set) {
559    size_t srclen = strlen(src);
560
561        /* demand that we are an absolute path */
562    if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
563        return false;
564    }
565
566    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
567        return false;
568    }
569
570    std::string from_src = std::string(src + 1);
571    std::replace(from_src.begin(), from_src.end(), '/', '@');
572
573    std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
574                                              OTAPreoptService::kOTADataDirectory,
575                                              DALVIK_CACHE,
576                                              instruction_set,
577                                              from_src.c_str(),
578                                              DALVIK_CACHE_POSTFIX2);
579
580    if (assembled_path.length() + 1 > PKG_PATH_MAX) {
581        return false;
582    }
583    strcpy(path, assembled_path.c_str());
584
585    return true;
586}
587
588bool initialize_globals() {
589    const char* data_path = getenv("ANDROID_DATA");
590    if (data_path == nullptr) {
591        ALOGE("Could not find ANDROID_DATA");
592        return false;
593    }
594    return init_globals_from_data_and_root(data_path, kOTARootDirectory);
595}
596
597static bool initialize_directories() {
598    // This is different from the normal installd. We only do the base
599    // directory, the rest will be created on demand when each app is compiled.
600    mode_t old_umask = umask(0);
601    LOG(INFO) << "Old umask: " << old_umask;
602    if (access(OTAPreoptService::kOTADataDirectory, R_OK) < 0) {
603        ALOGE("Could not access %s\n", OTAPreoptService::kOTADataDirectory);
604        return false;
605    }
606    return true;
607}
608
609static int log_callback(int type, const char *fmt, ...) {
610    va_list ap;
611    int priority;
612
613    switch (type) {
614        case SELINUX_WARNING:
615            priority = ANDROID_LOG_WARN;
616            break;
617        case SELINUX_INFO:
618            priority = ANDROID_LOG_INFO;
619            break;
620        default:
621            priority = ANDROID_LOG_ERROR;
622            break;
623    }
624    va_start(ap, fmt);
625    LOG_PRI_VA(priority, "SELinux", fmt, ap);
626    va_end(ap);
627    return 0;
628}
629
630static int otapreopt_main(const int argc, char *argv[]) {
631    int selinux_enabled = (is_selinux_enabled() > 0);
632
633    setenv("ANDROID_LOG_TAGS", "*:v", 1);
634    android::base::InitLogging(argv);
635
636    ALOGI("otapreopt firing up\n");
637
638    if (argc < 2) {
639        ALOGE("Expecting parameters");
640        exit(1);
641    }
642
643    union selinux_callback cb;
644    cb.func_log = log_callback;
645    selinux_set_callback(SELINUX_CB_LOG, cb);
646
647    if (!initialize_globals()) {
648        ALOGE("Could not initialize globals; exiting.\n");
649        exit(1);
650    }
651
652    if (!initialize_directories()) {
653        ALOGE("Could not create directories; exiting.\n");
654        exit(1);
655    }
656
657    if (selinux_enabled && selinux_status_open(true) < 0) {
658        ALOGE("Could not open selinux status; exiting.\n");
659        exit(1);
660    }
661
662    int ret = android::installd::gOps.Main(argc, argv);
663
664    return ret;
665}
666
667}  // namespace installd
668}  // namespace android
669
670int main(const int argc, char *argv[]) {
671    return android::installd::otapreopt_main(argc, argv);
672}
673