• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <limits>
20 #include <random>
21 #include <regex>
22 #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/mman.h>
30 
31 #include <android-base/logging.h>
32 #include <android-base/macros.h>
33 #include <android-base/stringprintf.h>
34 #include <android-base/strings.h>
35 #include <cutils/fs.h>
36 #include <cutils/properties.h>
37 #include <log/log.h>
38 #include <private/android_filesystem_config.h>
39 
40 #include "android-base/file.h"
41 #include "dexopt.h"
42 #include "file_parsing.h"
43 #include "globals.h"
44 #include "installd_constants.h"
45 #include "installd_deps.h"  // Need to fill in requirements of commands.
46 #include "otapreopt_parameters.h"
47 #include "otapreopt_utils.h"
48 #include "system_properties.h"
49 #include "utils.h"
50 
51 #ifndef LOG_TAG
52 #define LOG_TAG "otapreopt"
53 #endif
54 
55 #define BUFFER_MAX    1024  /* input buffer for commands */
56 #define TOKEN_MAX     16    /* max number of arguments in buffer */
57 #define REPLY_MAX     256   /* largest reply allowed */
58 
59 using android::base::EndsWith;
60 using android::base::Split;
61 using android::base::StartsWith;
62 using android::base::StringPrintf;
63 
64 namespace android {
65 namespace installd {
66 
67 // 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 
73 static_assert(DEXOPT_PUBLIC         == 1 << 1, "DEXOPT_PUBLIC unexpected.");
74 static_assert(DEXOPT_DEBUGGABLE     == 1 << 2, "DEXOPT_DEBUGGABLE unexpected.");
75 static_assert(DEXOPT_BOOTCOMPLETE   == 1 << 3, "DEXOPT_BOOTCOMPLETE unexpected.");
76 static_assert(DEXOPT_PROFILE_GUIDED == 1 << 4, "DEXOPT_PROFILE_GUIDED unexpected.");
77 static_assert(DEXOPT_SECONDARY_DEX  == 1 << 5, "DEXOPT_SECONDARY_DEX unexpected.");
78 static_assert(DEXOPT_FORCE          == 1 << 6, "DEXOPT_FORCE unexpected.");
79 static_assert(DEXOPT_STORAGE_CE     == 1 << 7, "DEXOPT_STORAGE_CE unexpected.");
80 static_assert(DEXOPT_STORAGE_DE     == 1 << 8, "DEXOPT_STORAGE_DE unexpected.");
81 static_assert(DEXOPT_ENABLE_HIDDEN_API_CHECKS == 1 << 10,
82         "DEXOPT_ENABLE_HIDDEN_API_CHECKS unexpected");
83 static_assert(DEXOPT_GENERATE_COMPACT_DEX == 1 << 11, "DEXOPT_GENERATE_COMPACT_DEX unexpected");
84 static_assert(DEXOPT_GENERATE_APP_IMAGE == 1 << 12, "DEXOPT_GENERATE_APP_IMAGE unexpected");
85 
86 static_assert(DEXOPT_MASK           == (0x3dfe | DEXOPT_IDLE_BACKGROUND_JOB),
87               "DEXOPT_MASK unexpected.");
88 
89 
90 template<typename T>
IsPowerOfTwo(T x)91 static constexpr bool IsPowerOfTwo(T x) {
92   static_assert(std::is_integral<T>::value, "T must be integral");
93   // TODO: assert unsigned. There is currently many uses with signed values.
94   return (x & (x - 1)) == 0;
95 }
96 
97 template<typename T>
RoundDown(T x,typename std::decay<T>::type n)98 static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
99     return (x & -n);
100 }
101 
102 template<typename T>
RoundUp(T x,typename std::remove_reference<T>::type n)103 static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
104     return RoundDown(x + n - 1, n);
105 }
106 
107 class OTAPreoptService {
108  public:
109     // Main driver. Performs the following steps.
110     //
111     // 1) Parse options (read system properties etc from B partition).
112     //
113     // 2) Read in package data.
114     //
115     // 3) Prepare environment variables.
116     //
117     // 4) Prepare(compile) boot image, if necessary.
118     //
119     // 5) Run update.
Main(int argc,char ** argv)120     int Main(int argc, char** argv) {
121         if (!ReadArguments(argc, argv)) {
122             LOG(ERROR) << "Failed reading command line.";
123             return 1;
124         }
125 
126         if (!ReadSystemProperties()) {
127             LOG(ERROR)<< "Failed reading system properties.";
128             return 2;
129         }
130 
131         if (!ReadEnvironment()) {
132             LOG(ERROR) << "Failed reading environment properties.";
133             return 3;
134         }
135 
136         if (!CheckAndInitializeInstalldGlobals()) {
137             LOG(ERROR) << "Failed initializing globals.";
138             return 4;
139         }
140 
141         PrepareEnvironmentVariables();
142 
143         if (!EnsureBootImageAndDalvikCache()) {
144             LOG(ERROR) << "Bad boot image.";
145             return 5;
146         }
147 
148         int dexopt_retcode = RunPreopt();
149 
150         return dexopt_retcode;
151     }
152 
GetProperty(const char * key,char * value,const char * default_value) const153     int GetProperty(const char* key, char* value, const char* default_value) const {
154         const std::string* prop_value = system_properties_.GetProperty(key);
155         if (prop_value == nullptr) {
156             if (default_value == nullptr) {
157                 return 0;
158             }
159             // Copy in the default value.
160             strlcpy(value, default_value, kPropertyValueMax - 1);
161             value[kPropertyValueMax - 1] = 0;
162             return strlen(default_value);// TODO: Need to truncate?
163         }
164         size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
165         strlcpy(value, prop_value->data(), size);
166         return static_cast<int>(size - 1);
167     }
168 
GetOTADataDirectory() const169     std::string GetOTADataDirectory() const {
170         return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
171     }
172 
GetTargetSlot() const173     const std::string& GetTargetSlot() const {
174         return parameters_.target_slot;
175     }
176 
177 private:
178 
ReadSystemProperties()179     bool ReadSystemProperties() {
180         // TODO This file does not have a stable format. It should be read by
181         // code shared by init and otapreopt. See b/181182967#comment80
182         static constexpr const char* kPropertyFiles[] = {
183                 "/system/build.prop"
184         };
185 
186         for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
187             if (!system_properties_.Load(kPropertyFiles[i])) {
188                 return false;
189             }
190         }
191 
192         return true;
193     }
194 
ReadEnvironment()195     bool ReadEnvironment() {
196         // Parse the environment variables from init.environ.rc, which have the form
197         //   export NAME VALUE
198         // For simplicity, don't respect string quotation. The values we are interested in can be
199         // encoded without them.
200         //
201         // init.environ.rc and derive_classpath all have the same format for
202         // environment variable exports (since they are all meant to be read by
203         // init) and can be matched by the same regex.
204 
205         std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
206         auto parse_results = [&](auto& input) {
207           ParseFile(input, [&](const std::string& line) {
208               std::smatch export_match;
209               if (!std::regex_match(line, export_match, export_regex)) {
210                   return true;
211               }
212 
213               if (export_match.size() != 3) {
214                   return true;
215               }
216 
217               std::string name = export_match[1].str();
218               std::string value = export_match[2].str();
219 
220               system_properties_.SetProperty(name, value);
221 
222               return true;
223           });
224         };
225 
226         // TODO Just like with the system-properties above we really should have
227         // common code between init and otapreopt to deal with reading these
228         // things. See b/181182967
229         // There have been a variety of places the various env-vars have been
230         // over the years.  Expand or reduce this list as needed.
231         static constexpr const char* kEnvironmentVariableSources[] = {
232                 "/init.environ.rc",
233         };
234         // First get everything from the static files.
235         for (const char* env_vars_file : kEnvironmentVariableSources) {
236           parse_results(env_vars_file);
237         }
238 
239         // Next get everything from derive_classpath, since we're already in the
240         // chroot it will get the new versions of any dependencies.
241         {
242           android::base::unique_fd fd(memfd_create("derive_classpath_temp", MFD_CLOEXEC));
243           if (!fd.ok()) {
244             LOG(ERROR) << "Unable to create fd for derive_classpath";
245             return false;
246           }
247           std::string memfd_file = StringPrintf("/proc/%d/fd/%d", getpid(), fd.get());
248           std::string error_msg;
249           if (!Exec({"/apex/com.android.sdkext/bin/derive_classpath", memfd_file}, &error_msg)) {
250             PLOG(ERROR) << "Running derive_classpath failed: " << error_msg;
251             return false;
252           }
253           std::ifstream ifs(memfd_file);
254           parse_results(ifs);
255         }
256 
257         if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
258             return false;
259         }
260         android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
261 
262         if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
263             return false;
264         }
265         android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
266 
267         if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
268             return false;
269         }
270         boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
271 
272         if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
273             return false;
274         }
275         asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
276 
277         return true;
278     }
279 
GetAndroidData() const280     const std::string& GetAndroidData() const {
281         return android_data_;
282     }
283 
GetAndroidRoot() const284     const std::string& GetAndroidRoot() const {
285         return android_root_;
286     }
287 
GetOtaDirectoryPrefix() const288     const std::string GetOtaDirectoryPrefix() const {
289         return GetAndroidData() + "/ota";
290     }
291 
CheckAndInitializeInstalldGlobals()292     bool CheckAndInitializeInstalldGlobals() {
293         // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
294         // do not use any datapath that includes this, but we'll still have to set it.
295         CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
296         int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
297         if (result != 0) {
298             LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
299             return false;
300         }
301 
302         if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
303             LOG(ERROR) << "Could not initialize globals; exiting.";
304             return false;
305         }
306 
307         // This is different from the normal installd. We only do the base
308         // directory, the rest will be created on demand when each app is compiled.
309         if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
310             LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
311             return false;
312         }
313 
314         return true;
315     }
316 
ParseBool(const char * in)317     bool ParseBool(const char* in) {
318         if (strcmp(in, "true") == 0) {
319             return true;
320         }
321         return false;
322     }
323 
ParseUInt(const char * in,uint32_t * out)324     bool ParseUInt(const char* in, uint32_t* out) {
325         char* end;
326         long long int result = strtoll(in, &end, 0);
327         if (in == end || *end != '\0') {
328             return false;
329         }
330         if (result < std::numeric_limits<uint32_t>::min() ||
331                 std::numeric_limits<uint32_t>::max() < result) {
332             return false;
333         }
334         *out = static_cast<uint32_t>(result);
335         return true;
336     }
337 
ReadArguments(int argc,char ** argv)338     bool ReadArguments(int argc, char** argv) {
339         return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
340     }
341 
PrepareEnvironmentVariables()342     void PrepareEnvironmentVariables() {
343         environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
344         environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
345         environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
346 
347         for (const std::string& e : environ_) {
348             putenv(const_cast<char*>(e.c_str()));
349         }
350     }
351 
352     // Ensure that we have the right boot image and cache file structures.
EnsureBootImageAndDalvikCache() const353     bool EnsureBootImageAndDalvikCache() const {
354         if (parameters_.instruction_set == nullptr) {
355             LOG(ERROR) << "Instruction set missing.";
356             return false;
357         }
358         const char* isa = parameters_.instruction_set;
359         std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
360         std::string isa_path = dalvik_cache + "/" + isa;
361 
362         // Reset umask in otapreopt, so that we control the the access for the files we create.
363         umask(0);
364 
365         // Create the directories, if necessary.
366         if (access(dalvik_cache.c_str(), F_OK) != 0) {
367             if (!CreatePath(dalvik_cache)) {
368                 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
369                 return false;
370             }
371         }
372         if (access(isa_path.c_str(), F_OK) != 0) {
373             if (!CreatePath(isa_path)) {
374                 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
375                 return false;
376             }
377         }
378 
379         // Check whether we have a boot image.
380         // TODO: check that the files are correct wrt/ jars.
381         std::string preopted_boot_art_path =
382             StringPrintf("/apex/com.android.art/javalib/%s/boot.art", isa);
383         if (access(preopted_boot_art_path.c_str(), F_OK) != 0) {
384             PLOG(ERROR) << "Bad access() to " << preopted_boot_art_path;
385             return false;
386         }
387 
388         return true;
389     }
390 
CreatePath(const std::string & path)391     static bool CreatePath(const std::string& path) {
392         // Create the given path. Use string processing instead of dirname, as dirname's need for
393         // a writable char buffer is painful.
394 
395         // First, try to use the full path.
396         if (mkdir(path.c_str(), 0711) == 0) {
397             return true;
398         }
399         if (errno != ENOENT) {
400             PLOG(ERROR) << "Could not create path " << path;
401             return false;
402         }
403 
404         // Now find the parent and try that first.
405         size_t last_slash = path.find_last_of('/');
406         if (last_slash == std::string::npos || last_slash == 0) {
407             PLOG(ERROR) << "Could not create " << path;
408             return false;
409         }
410 
411         if (!CreatePath(path.substr(0, last_slash))) {
412             return false;
413         }
414 
415         if (mkdir(path.c_str(), 0711) == 0) {
416             return true;
417         }
418         PLOG(ERROR) << "Could not create " << path;
419         return false;
420     }
421 
ParseNull(const char * arg)422     static const char* ParseNull(const char* arg) {
423         return (strcmp(arg, "!") == 0) ? nullptr : arg;
424     }
425 
ShouldSkipPreopt() const426     bool ShouldSkipPreopt() const {
427         // There's one thing we have to be careful about: we may/will be asked to compile an app
428         // living in the system image. This may be a valid request - if the app wasn't compiled,
429         // e.g., if the system image wasn't large enough to include preopted files. However, the
430         // data we have is from the old system, so the driver (the OTA service) can't actually
431         // know. Thus, we will get requests for apps that have preopted components. To avoid
432         // duplication (we'd generate files that are not used and are *not* cleaned up), do two
433         // simple checks:
434         //
435         // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
436         //    (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
437         //
438         // 2) If you replace the name in the apk_path with "oat," does the path exist?
439         //    (=have a subdirectory for preopted files)
440         //
441         // If the answer to both is yes, skip the dexopt.
442         //
443         // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
444         //       be stripped), that's not true for APKs signed outside the build system (so the
445         //       jar content must be exactly the same).
446 
447         //       (This is ugly as it's the only thing where we need to understand the contents
448         //        of parameters_, but it beats postponing the decision or using the call-
449         //        backs to do weird things.)
450         const char* apk_path = parameters_.apk_path;
451         CHECK(apk_path != nullptr);
452         if (StartsWith(apk_path, android_root_)) {
453             const char* last_slash = strrchr(apk_path, '/');
454             if (last_slash != nullptr) {
455                 std::string path(apk_path, last_slash - apk_path + 1);
456                 CHECK(EndsWith(path, "/"));
457                 path = path + "oat";
458                 if (access(path.c_str(), F_OK) == 0) {
459                     LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
460                     return true;
461                 }
462             }
463         }
464 
465         // Another issue is unavailability of files in the new system. If the partition
466         // layout changes, otapreopt_chroot may not know about this. Then files from that
467         // partition will not be available and fail to build. This is problematic, as
468         // this tool will wipe the OTA artifact cache and try again (for robustness after
469         // a failed OTA with remaining cache artifacts).
470         if (access(apk_path, F_OK) != 0) {
471             LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
472             return true;
473         }
474 
475         return false;
476     }
477 
478     // Run dexopt with the parameters of parameters_.
479     // TODO(calin): embed the profile name in the parameters.
Dexopt()480     int Dexopt() {
481         std::string error;
482         int res = dexopt(parameters_.apk_path,
483                          parameters_.uid,
484                          parameters_.pkgName,
485                          parameters_.instruction_set,
486                          parameters_.dexopt_needed,
487                          parameters_.oat_dir,
488                          parameters_.dexopt_flags,
489                          parameters_.compiler_filter,
490                          parameters_.volume_uuid,
491                          parameters_.shared_libraries,
492                          parameters_.se_info,
493                          parameters_.downgrade,
494                          parameters_.target_sdk_version,
495                          parameters_.profile_name,
496                          parameters_.dex_metadata_path,
497                          parameters_.compilation_reason,
498                          &error);
499         if (res != 0) {
500             LOG(ERROR) << "During preopt of " << parameters_.apk_path << " got result " << res
501                        << " error: " << error;
502         }
503         return res;
504     }
505 
RunPreopt()506     int RunPreopt() {
507         if (ShouldSkipPreopt()) {
508             return 0;
509         }
510 
511         int dexopt_result = Dexopt();
512         if (dexopt_result == 0) {
513             return 0;
514         }
515 
516         // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
517         // if possible.
518         if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
519             return dexopt_result;
520         }
521 
522         LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
523         parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
524         return Dexopt();
525     }
526 
527     ////////////////////////////////////
528     // Helpers, mostly taken from ART //
529     ////////////////////////////////////
530 
531     // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
ChooseRelocationOffsetDelta(int32_t min_delta,int32_t max_delta)532     static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
533         constexpr size_t kPageSize = PAGE_SIZE;
534         static_assert(IsPowerOfTwo(kPageSize), "page size must be power of two");
535         CHECK_EQ(min_delta % kPageSize, 0u);
536         CHECK_EQ(max_delta % kPageSize, 0u);
537         CHECK_LT(min_delta, max_delta);
538 
539         std::default_random_engine generator;
540         generator.seed(GetSeed());
541         std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
542         int32_t r = distribution(generator);
543         if (r % 2 == 0) {
544             r = RoundUp(r, kPageSize);
545         } else {
546             r = RoundDown(r, kPageSize);
547         }
548         CHECK_LE(min_delta, r);
549         CHECK_GE(max_delta, r);
550         CHECK_EQ(r % kPageSize, 0u);
551         return r;
552     }
553 
GetSeed()554     static uint64_t GetSeed() {
555 #ifdef __BIONIC__
556         // Bionic exposes arc4random, use it.
557         uint64_t random_data;
558         arc4random_buf(&random_data, sizeof(random_data));
559         return random_data;
560 #else
561 #error "This is only supposed to run with bionic. Otherwise, implement..."
562 #endif
563     }
564 
AddCompilerOptionFromSystemProperty(const char * system_property,const char * prefix,bool runtime,std::vector<std::string> & out) const565     void AddCompilerOptionFromSystemProperty(const char* system_property,
566             const char* prefix,
567             bool runtime,
568             std::vector<std::string>& out) const {
569         const std::string* value = system_properties_.GetProperty(system_property);
570         if (value != nullptr) {
571             if (runtime) {
572                 out.push_back("--runtime-arg");
573             }
574             if (prefix != nullptr) {
575                 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
576             } else {
577                 out.push_back(*value);
578             }
579         }
580     }
581 
582     static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
583     static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
584     static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
585     // The index of the instruction-set string inside the package parameters. Needed for
586     // some special-casing that requires knowledge of the instruction-set.
587     static constexpr size_t kISAIndex = 3;
588 
589     // Stores the system properties read out of the B partition. We need to use these properties
590     // to compile, instead of the A properties we could get from init/get_property.
591     SystemProperties system_properties_;
592 
593     // Some select properties that are always needed.
594     std::string android_root_;
595     std::string android_data_;
596     std::string boot_classpath_;
597     std::string asec_mountpoint_;
598 
599     OTAPreoptParameters parameters_;
600 
601     // Store environment values we need to set.
602     std::vector<std::string> environ_;
603 };
604 
605 OTAPreoptService gOps;
606 
607 ////////////////////////
608 // Plug-in functions. //
609 ////////////////////////
610 
get_property(const char * key,char * value,const char * default_value)611 int get_property(const char *key, char *value, const char *default_value) {
612     return gOps.GetProperty(key, value, default_value);
613 }
614 
615 // Compute the output path of
calculate_oat_file_path(char path[PKG_PATH_MAX],const char * oat_dir,const char * apk_path,const char * instruction_set)616 bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
617                              const char *apk_path,
618                              const char *instruction_set) {
619     const char *file_name_start;
620     const char *file_name_end;
621 
622     file_name_start = strrchr(apk_path, '/');
623     if (file_name_start == nullptr) {
624         ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
625         return false;
626     }
627     file_name_end = strrchr(file_name_start, '.');
628     if (file_name_end == nullptr) {
629         ALOGE("apk_path '%s' has no extension\n", apk_path);
630         return false;
631     }
632 
633     // Calculate file_name
634     file_name_start++;  // Move past '/', is valid as file_name_end is valid.
635     size_t file_name_len = file_name_end - file_name_start;
636     std::string file_name(file_name_start, file_name_len);
637 
638     // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
639     snprintf(path,
640              PKG_PATH_MAX,
641              "%s/%s/%s.odex.%s",
642              oat_dir,
643              instruction_set,
644              file_name.c_str(),
645              gOps.GetTargetSlot().c_str());
646     return true;
647 }
648 
649 /*
650  * Computes the odex file for the given apk_path and instruction_set.
651  * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
652  *
653  * Returns false if it failed to determine the odex file path.
654  */
calculate_odex_file_path(char path[PKG_PATH_MAX],const char * apk_path,const char * instruction_set)655 bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
656                               const char *instruction_set) {
657     const char *path_end = strrchr(apk_path, '/');
658     if (path_end == nullptr) {
659         ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
660         return false;
661     }
662     std::string path_component(apk_path, path_end - apk_path);
663 
664     const char *name_begin = path_end + 1;
665     const char *extension_start = strrchr(name_begin, '.');
666     if (extension_start == nullptr) {
667         ALOGE("apk_path '%s' has no extension.\n", apk_path);
668         return false;
669     }
670     std::string name_component(name_begin, extension_start - name_begin);
671 
672     std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
673                                         path_component.c_str(),
674                                         instruction_set,
675                                         name_component.c_str(),
676                                         gOps.GetTargetSlot().c_str());
677     if (new_path.length() >= PKG_PATH_MAX) {
678         LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
679         return false;
680     }
681     strcpy(path, new_path.c_str());
682     return true;
683 }
684 
create_cache_path(char path[PKG_PATH_MAX],const char * src,const char * instruction_set)685 bool create_cache_path(char path[PKG_PATH_MAX],
686                        const char *src,
687                        const char *instruction_set) {
688     size_t srclen = strlen(src);
689 
690         /* demand that we are an absolute path */
691     if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
692         return false;
693     }
694 
695     if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
696         return false;
697     }
698 
699     std::string from_src = std::string(src + 1);
700     std::replace(from_src.begin(), from_src.end(), '/', '@');
701 
702     std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
703                                               gOps.GetOTADataDirectory().c_str(),
704                                               DALVIK_CACHE,
705                                               instruction_set,
706                                               from_src.c_str(),
707                                               DALVIK_CACHE_POSTFIX);
708 
709     if (assembled_path.length() + 1 > PKG_PATH_MAX) {
710         return false;
711     }
712     strcpy(path, assembled_path.c_str());
713 
714     return true;
715 }
716 
log_callback(int type,const char * fmt,...)717 static int log_callback(int type, const char *fmt, ...) {
718     va_list ap;
719     int priority;
720 
721     switch (type) {
722         case SELINUX_WARNING:
723             priority = ANDROID_LOG_WARN;
724             break;
725         case SELINUX_INFO:
726             priority = ANDROID_LOG_INFO;
727             break;
728         default:
729             priority = ANDROID_LOG_ERROR;
730             break;
731     }
732     va_start(ap, fmt);
733     LOG_PRI_VA(priority, "SELinux", fmt, ap);
734     va_end(ap);
735     return 0;
736 }
737 
otapreopt_main(const int argc,char * argv[])738 static int otapreopt_main(const int argc, char *argv[]) {
739     int selinux_enabled = (is_selinux_enabled() > 0);
740 
741     setenv("ANDROID_LOG_TAGS", "*:v", 1);
742     android::base::InitLogging(argv);
743 
744     if (argc < 2) {
745         ALOGE("Expecting parameters");
746         exit(1);
747     }
748 
749     union selinux_callback cb;
750     cb.func_log = log_callback;
751     selinux_set_callback(SELINUX_CB_LOG, cb);
752 
753     if (selinux_enabled && selinux_status_open(true) < 0) {
754         ALOGE("Could not open selinux status; exiting.\n");
755         exit(1);
756     }
757 
758     int ret = android::installd::gOps.Main(argc, argv);
759 
760     return ret;
761 }
762 
763 }  // namespace installd
764 }  // namespace android
765 
main(const int argc,char * argv[])766 int main(const int argc, char *argv[]) {
767     return android::installd::otapreopt_main(argc, argv);
768 }
769