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