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 <linux/unistd.h> 18#include <sys/mount.h> 19#include <sys/wait.h> 20 21#include <android-base/logging.h> 22#include <android-base/macros.h> 23#include <android-base/stringprintf.h> 24 25#ifndef LOG_TAG 26#define LOG_TAG "otapreopt" 27#endif 28 29using android::base::StringPrintf; 30 31namespace android { 32namespace installd { 33 34static int otapreopt_chroot(const int argc, char **arg) { 35 // We need to run the otapreopt tool from the postinstall partition. As such, set up a 36 // mount namespace and change root. 37 38 // Create our own mount namespace. 39 if (unshare(CLONE_NEWNS) != 0) { 40 PLOG(ERROR) << "Failed to unshare() for otapreopt."; 41 exit(200); 42 } 43 44 // Make postinstall private, so that our changes don't propagate. 45 if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) { 46 PLOG(ERROR) << "Failed to mount private."; 47 exit(201); 48 } 49 50 // Bind mount necessary directories. 51 constexpr const char* kBindMounts[] = { 52 "/data", "/dev", "/proc", "/sys" 53 }; 54 for (size_t i = 0; i < arraysize(kBindMounts); ++i) { 55 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]); 56 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) { 57 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i]; 58 exit(202); 59 } 60 } 61 62 // Chdir into /postinstall. 63 if (chdir("/postinstall") != 0) { 64 PLOG(ERROR) << "Unable to chdir into /postinstall."; 65 exit(203); 66 } 67 68 // Make /postinstall the root in our mount namespace. 69 if (chroot(".") != 0) { 70 PLOG(ERROR) << "Failed to chroot"; 71 exit(204); 72 } 73 74 if (chdir("/") != 0) { 75 PLOG(ERROR) << "Unable to chdir into /."; 76 exit(205); 77 } 78 79 // Now go on and run otapreopt. 80 81 const char* argv[1 + 9 + 1]; 82 CHECK_EQ(argc, 10); 83 argv[0] = "/system/bin/otapreopt"; 84 for (size_t i = 1; i <= 9; ++i) { 85 argv[i] = arg[i]; 86 } 87 argv[10] = nullptr; 88 89 execv(argv[0], (char * const *)argv); 90 PLOG(ERROR) << "execv(OTAPREOPT) failed."; 91 exit(99); 92} 93 94} // namespace installd 95} // namespace android 96 97int main(const int argc, char *argv[]) { 98 return android::installd::otapreopt_chroot(argc, argv); 99} 100