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/wait.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 <dex2oat_return_codes.h>
38 #include <log/log.h>
39 #include <private/android_filesystem_config.h>
40 
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::Join;
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           == (0x1dfe | DEXOPT_IDLE_BACKGROUND_JOB),
88               "DEXOPT_MASK unexpected.");
89 
90 
91 
92 template<typename T>
RoundDown(T x,typename std::decay<T>::type n)93 static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
94     return DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))(x & -n);
95 }
96 
97 template<typename T>
RoundUp(T x,typename std::remove_reference<T>::type n)98 static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
99     return RoundDown(x + n - 1, n);
100 }
101 
102 class OTAPreoptService {
103  public:
104     // Main driver. Performs the following steps.
105     //
106     // 1) Parse options (read system properties etc from B partition).
107     //
108     // 2) Read in package data.
109     //
110     // 3) Prepare environment variables.
111     //
112     // 4) Prepare(compile) boot image, if necessary.
113     //
114     // 5) Run update.
Main(int argc,char ** argv)115     int Main(int argc, char** argv) {
116         if (!ReadArguments(argc, argv)) {
117             LOG(ERROR) << "Failed reading command line.";
118             return 1;
119         }
120 
121         if (!ReadSystemProperties()) {
122             LOG(ERROR)<< "Failed reading system properties.";
123             return 2;
124         }
125 
126         if (!ReadEnvironment()) {
127             LOG(ERROR) << "Failed reading environment properties.";
128             return 3;
129         }
130 
131         if (!CheckAndInitializeInstalldGlobals()) {
132             LOG(ERROR) << "Failed initializing globals.";
133             return 4;
134         }
135 
136         PrepareEnvironment();
137 
138         if (!PrepareBootImage(/* force */ false)) {
139             LOG(ERROR) << "Failed preparing boot image.";
140             return 5;
141         }
142 
143         int dexopt_retcode = RunPreopt();
144 
145         return dexopt_retcode;
146     }
147 
GetProperty(const char * key,char * value,const char * default_value) const148     int GetProperty(const char* key, char* value, const char* default_value) const {
149         const std::string* prop_value = system_properties_.GetProperty(key);
150         if (prop_value == nullptr) {
151             if (default_value == nullptr) {
152                 return 0;
153             }
154             // Copy in the default value.
155             strlcpy(value, default_value, kPropertyValueMax - 1);
156             value[kPropertyValueMax - 1] = 0;
157             return strlen(default_value);// TODO: Need to truncate?
158         }
159         size_t size = std::min(kPropertyValueMax - 1, prop_value->length()) + 1;
160         strlcpy(value, prop_value->data(), size);
161         return static_cast<int>(size - 1);
162     }
163 
GetOTADataDirectory() const164     std::string GetOTADataDirectory() const {
165         return StringPrintf("%s/%s", GetOtaDirectoryPrefix().c_str(), GetTargetSlot().c_str());
166     }
167 
GetTargetSlot() const168     const std::string& GetTargetSlot() const {
169         return parameters_.target_slot;
170     }
171 
172 private:
173 
ReadSystemProperties()174     bool ReadSystemProperties() {
175         static constexpr const char* kPropertyFiles[] = {
176                 "/default.prop", "/system/build.prop"
177         };
178 
179         for (size_t i = 0; i < arraysize(kPropertyFiles); ++i) {
180             if (!system_properties_.Load(kPropertyFiles[i])) {
181                 return false;
182             }
183         }
184 
185         return true;
186     }
187 
ReadEnvironment()188     bool ReadEnvironment() {
189         // Parse the environment variables from init.environ.rc, which have the form
190         //   export NAME VALUE
191         // For simplicity, don't respect string quotation. The values we are interested in can be
192         // encoded without them.
193         std::regex export_regex("\\s*export\\s+(\\S+)\\s+(\\S+)");
194         bool parse_result = ParseFile("/init.environ.rc", [&](const std::string& line) {
195             std::smatch export_match;
196             if (!std::regex_match(line, export_match, export_regex)) {
197                 return true;
198             }
199 
200             if (export_match.size() != 3) {
201                 return true;
202             }
203 
204             std::string name = export_match[1].str();
205             std::string value = export_match[2].str();
206 
207             system_properties_.SetProperty(name, value);
208 
209             return true;
210         });
211         if (!parse_result) {
212             return false;
213         }
214 
215         if (system_properties_.GetProperty(kAndroidDataPathPropertyName) == nullptr) {
216             return false;
217         }
218         android_data_ = *system_properties_.GetProperty(kAndroidDataPathPropertyName);
219 
220         if (system_properties_.GetProperty(kAndroidRootPathPropertyName) == nullptr) {
221             return false;
222         }
223         android_root_ = *system_properties_.GetProperty(kAndroidRootPathPropertyName);
224 
225         if (system_properties_.GetProperty(kBootClassPathPropertyName) == nullptr) {
226             return false;
227         }
228         boot_classpath_ = *system_properties_.GetProperty(kBootClassPathPropertyName);
229 
230         if (system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) == nullptr) {
231             return false;
232         }
233         asec_mountpoint_ = *system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME);
234 
235         return true;
236     }
237 
GetAndroidData() const238     const std::string& GetAndroidData() const {
239         return android_data_;
240     }
241 
GetAndroidRoot() const242     const std::string& GetAndroidRoot() const {
243         return android_root_;
244     }
245 
GetOtaDirectoryPrefix() const246     const std::string GetOtaDirectoryPrefix() const {
247         return GetAndroidData() + "/ota";
248     }
249 
CheckAndInitializeInstalldGlobals()250     bool CheckAndInitializeInstalldGlobals() {
251         // init_globals_from_data_and_root requires "ASEC_MOUNTPOINT" in the environment. We
252         // do not use any datapath that includes this, but we'll still have to set it.
253         CHECK(system_properties_.GetProperty(ASEC_MOUNTPOINT_ENV_NAME) != nullptr);
254         int result = setenv(ASEC_MOUNTPOINT_ENV_NAME, asec_mountpoint_.c_str(), 0);
255         if (result != 0) {
256             LOG(ERROR) << "Could not set ASEC_MOUNTPOINT environment variable";
257             return false;
258         }
259 
260         if (!init_globals_from_data_and_root(GetAndroidData().c_str(), GetAndroidRoot().c_str())) {
261             LOG(ERROR) << "Could not initialize globals; exiting.";
262             return false;
263         }
264 
265         // This is different from the normal installd. We only do the base
266         // directory, the rest will be created on demand when each app is compiled.
267         if (access(GetOtaDirectoryPrefix().c_str(), R_OK) < 0) {
268             LOG(ERROR) << "Could not access " << GetOtaDirectoryPrefix();
269             return false;
270         }
271 
272         return true;
273     }
274 
ParseBool(const char * in)275     bool ParseBool(const char* in) {
276         if (strcmp(in, "true") == 0) {
277             return true;
278         }
279         return false;
280     }
281 
ParseUInt(const char * in,uint32_t * out)282     bool ParseUInt(const char* in, uint32_t* out) {
283         char* end;
284         long long int result = strtoll(in, &end, 0);
285         if (in == end || *end != '\0') {
286             return false;
287         }
288         if (result < std::numeric_limits<uint32_t>::min() ||
289                 std::numeric_limits<uint32_t>::max() < result) {
290             return false;
291         }
292         *out = static_cast<uint32_t>(result);
293         return true;
294     }
295 
ReadArguments(int argc,char ** argv)296     bool ReadArguments(int argc, char** argv) {
297         return parameters_.ReadArguments(argc, const_cast<const char**>(argv));
298     }
299 
PrepareEnvironment()300     void PrepareEnvironment() {
301         environ_.push_back(StringPrintf("BOOTCLASSPATH=%s", boot_classpath_.c_str()));
302         environ_.push_back(StringPrintf("ANDROID_DATA=%s", GetOTADataDirectory().c_str()));
303         environ_.push_back(StringPrintf("ANDROID_ROOT=%s", android_root_.c_str()));
304 
305         for (const std::string& e : environ_) {
306             putenv(const_cast<char*>(e.c_str()));
307         }
308     }
309 
310     // Ensure that we have the right boot image. The first time any app is
311     // compiled, we'll try to generate it.
PrepareBootImage(bool force) const312     bool PrepareBootImage(bool force) const {
313         if (parameters_.instruction_set == nullptr) {
314             LOG(ERROR) << "Instruction set missing.";
315             return false;
316         }
317         const char* isa = parameters_.instruction_set;
318 
319         // Check whether the file exists where expected.
320         std::string dalvik_cache = GetOTADataDirectory() + "/" + DALVIK_CACHE;
321         std::string isa_path = dalvik_cache + "/" + isa;
322         std::string art_path = isa_path + "/system@framework@boot.art";
323         std::string oat_path = isa_path + "/system@framework@boot.oat";
324         bool cleared = false;
325         if (access(art_path.c_str(), F_OK) == 0 && access(oat_path.c_str(), F_OK) == 0) {
326             // Files exist, assume everything is alright if not forced. Otherwise clean up.
327             if (!force) {
328                 return true;
329             }
330             ClearDirectory(isa_path);
331             cleared = true;
332         }
333 
334         // Reset umask in otapreopt, so that we control the the access for the files we create.
335         umask(0);
336 
337         // Create the directories, if necessary.
338         if (access(dalvik_cache.c_str(), F_OK) != 0) {
339             if (!CreatePath(dalvik_cache)) {
340                 PLOG(ERROR) << "Could not create dalvik-cache dir " << dalvik_cache;
341                 return false;
342             }
343         }
344         if (access(isa_path.c_str(), F_OK) != 0) {
345             if (!CreatePath(isa_path)) {
346                 PLOG(ERROR) << "Could not create dalvik-cache isa dir";
347                 return false;
348             }
349         }
350 
351         // Prepare to create.
352         if (!cleared) {
353             ClearDirectory(isa_path);
354         }
355 
356         std::string preopted_boot_art_path = StringPrintf("/system/framework/%s/boot.art", isa);
357         if (access(preopted_boot_art_path.c_str(), F_OK) == 0) {
358           return PatchoatBootImage(isa_path, isa);
359         } else {
360           // No preopted boot image. Try to compile.
361           return Dex2oatBootImage(boot_classpath_, art_path, oat_path, isa);
362         }
363     }
364 
CreatePath(const std::string & path)365     static bool CreatePath(const std::string& path) {
366         // Create the given path. Use string processing instead of dirname, as dirname's need for
367         // a writable char buffer is painful.
368 
369         // First, try to use the full path.
370         if (mkdir(path.c_str(), 0711) == 0) {
371             return true;
372         }
373         if (errno != ENOENT) {
374             PLOG(ERROR) << "Could not create path " << path;
375             return false;
376         }
377 
378         // Now find the parent and try that first.
379         size_t last_slash = path.find_last_of('/');
380         if (last_slash == std::string::npos || last_slash == 0) {
381             PLOG(ERROR) << "Could not create " << path;
382             return false;
383         }
384 
385         if (!CreatePath(path.substr(0, last_slash))) {
386             return false;
387         }
388 
389         if (mkdir(path.c_str(), 0711) == 0) {
390             return true;
391         }
392         PLOG(ERROR) << "Could not create " << path;
393         return false;
394     }
395 
ClearDirectory(const std::string & dir)396     static void ClearDirectory(const std::string& dir) {
397         DIR* c_dir = opendir(dir.c_str());
398         if (c_dir == nullptr) {
399             PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
400             return;
401         }
402 
403         for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
404             const char* name = de->d_name;
405             if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
406                 continue;
407             }
408             // We only want to delete regular files and symbolic links.
409             std::string file = StringPrintf("%s/%s", dir.c_str(), name);
410             if (de->d_type != DT_REG && de->d_type != DT_LNK) {
411                 LOG(WARNING) << "Unexpected file "
412                              << file
413                              << " of type "
414                              << std::hex
415                              << de->d_type
416                              << " encountered.";
417             } else {
418                 // Try to unlink the file.
419                 if (unlink(file.c_str()) != 0) {
420                     PLOG(ERROR) << "Unable to unlink " << file;
421                 }
422             }
423         }
424         CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
425     }
426 
PatchoatBootImage(const std::string & output_dir,const char * isa) const427     bool PatchoatBootImage(const std::string& output_dir, const char* isa) const {
428         // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
429 
430         std::vector<std::string> cmd;
431         cmd.push_back("/system/bin/patchoat");
432 
433         cmd.push_back("--input-image-location=/system/framework/boot.art");
434         cmd.push_back(StringPrintf("--output-image-directory=%s", output_dir.c_str()));
435 
436         cmd.push_back(StringPrintf("--instruction-set=%s", isa));
437 
438         int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
439                                                           ART_BASE_ADDRESS_MAX_DELTA);
440         cmd.push_back(StringPrintf("--base-offset-delta=%d", base_offset));
441 
442         std::string error_msg;
443         bool result = Exec(cmd, &error_msg);
444         if (!result) {
445             LOG(ERROR) << "Could not generate boot image: " << error_msg;
446         }
447         return result;
448     }
449 
Dex2oatBootImage(const std::string & boot_cp,const std::string & art_path,const std::string & oat_path,const char * isa) const450     bool Dex2oatBootImage(const std::string& boot_cp,
451                           const std::string& art_path,
452                           const std::string& oat_path,
453                           const char* isa) const {
454         // This needs to be kept in sync with ART, see art/runtime/gc/space/image_space.cc.
455         std::vector<std::string> cmd;
456         cmd.push_back("/system/bin/dex2oat");
457         cmd.push_back(StringPrintf("--image=%s", art_path.c_str()));
458         for (const std::string& boot_part : Split(boot_cp, ":")) {
459             cmd.push_back(StringPrintf("--dex-file=%s", boot_part.c_str()));
460         }
461         cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
462 
463         int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
464                 ART_BASE_ADDRESS_MAX_DELTA);
465         cmd.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
466 
467         cmd.push_back(StringPrintf("--instruction-set=%s", isa));
468 
469         // These things are pushed by AndroidRuntime, see frameworks/base/core/jni/AndroidRuntime.cpp.
470         AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xms",
471                 "-Xms",
472                 true,
473                 cmd);
474         AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-Xmx",
475                 "-Xmx",
476                 true,
477                 cmd);
478         AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-filter",
479                 "--compiler-filter=",
480                 false,
481                 cmd);
482         cmd.push_back("--image-classes=/system/etc/preloaded-classes");
483         // TODO: Compiled-classes.
484         const std::string* extra_opts =
485                 system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
486         if (extra_opts != nullptr) {
487             std::vector<std::string> extra_vals = Split(*extra_opts, " ");
488             cmd.insert(cmd.end(), extra_vals.begin(), extra_vals.end());
489         }
490         // TODO: Should we lower this? It's usually set close to max, because
491         //       normally there's not much else going on at boot.
492         AddCompilerOptionFromSystemProperty("dalvik.vm.image-dex2oat-threads",
493                 "-j",
494                 false,
495                 cmd);
496         AddCompilerOptionFromSystemProperty(
497                 StringPrintf("dalvik.vm.isa.%s.variant", isa).c_str(),
498                 "--instruction-set-variant=",
499                 false,
500                 cmd);
501         AddCompilerOptionFromSystemProperty(
502                 StringPrintf("dalvik.vm.isa.%s.features", isa).c_str(),
503                 "--instruction-set-features=",
504                 false,
505                 cmd);
506 
507         std::string error_msg;
508         bool result = Exec(cmd, &error_msg);
509         if (!result) {
510             LOG(ERROR) << "Could not generate boot image: " << error_msg;
511         }
512         return result;
513     }
514 
ParseNull(const char * arg)515     static const char* ParseNull(const char* arg) {
516         return (strcmp(arg, "!") == 0) ? nullptr : arg;
517     }
518 
ShouldSkipPreopt() const519     bool ShouldSkipPreopt() const {
520         // There's one thing we have to be careful about: we may/will be asked to compile an app
521         // living in the system image. This may be a valid request - if the app wasn't compiled,
522         // e.g., if the system image wasn't large enough to include preopted files. However, the
523         // data we have is from the old system, so the driver (the OTA service) can't actually
524         // know. Thus, we will get requests for apps that have preopted components. To avoid
525         // duplication (we'd generate files that are not used and are *not* cleaned up), do two
526         // simple checks:
527         //
528         // 1) Does the apk_path start with the value of ANDROID_ROOT? (~in the system image)
529         //    (For simplicity, assume the value of ANDROID_ROOT does not contain a symlink.)
530         //
531         // 2) If you replace the name in the apk_path with "oat," does the path exist?
532         //    (=have a subdirectory for preopted files)
533         //
534         // If the answer to both is yes, skip the dexopt.
535         //
536         // Note: while one may think it's OK to call dexopt and it will fail (because APKs should
537         //       be stripped), that's not true for APKs signed outside the build system (so the
538         //       jar content must be exactly the same).
539 
540         //       (This is ugly as it's the only thing where we need to understand the contents
541         //        of parameters_, but it beats postponing the decision or using the call-
542         //        backs to do weird things.)
543         const char* apk_path = parameters_.apk_path;
544         CHECK(apk_path != nullptr);
545         if (StartsWith(apk_path, android_root_)) {
546             const char* last_slash = strrchr(apk_path, '/');
547             if (last_slash != nullptr) {
548                 std::string path(apk_path, last_slash - apk_path + 1);
549                 CHECK(EndsWith(path, "/"));
550                 path = path + "oat";
551                 if (access(path.c_str(), F_OK) == 0) {
552                     LOG(INFO) << "Skipping A/B OTA preopt of already preopted package " << apk_path;
553                     return true;
554                 }
555             }
556         }
557 
558         // Another issue is unavailability of files in the new system. If the partition
559         // layout changes, otapreopt_chroot may not know about this. Then files from that
560         // partition will not be available and fail to build. This is problematic, as
561         // this tool will wipe the OTA artifact cache and try again (for robustness after
562         // a failed OTA with remaining cache artifacts).
563         if (access(apk_path, F_OK) != 0) {
564             LOG(WARNING) << "Skipping A/B OTA preopt of non-existing package " << apk_path;
565             return true;
566         }
567 
568         return false;
569     }
570 
571     // Run dexopt with the parameters of parameters_.
572     // TODO(calin): embed the profile name in the parameters.
Dexopt()573     int Dexopt() {
574         std::string dummy;
575         return dexopt(parameters_.apk_path,
576                       parameters_.uid,
577                       parameters_.pkgName,
578                       parameters_.instruction_set,
579                       parameters_.dexopt_needed,
580                       parameters_.oat_dir,
581                       parameters_.dexopt_flags,
582                       parameters_.compiler_filter,
583                       parameters_.volume_uuid,
584                       parameters_.shared_libraries,
585                       parameters_.se_info,
586                       parameters_.downgrade,
587                       parameters_.target_sdk_version,
588                       parameters_.profile_name,
589                       parameters_.dex_metadata_path,
590                       parameters_.compilation_reason,
591                       &dummy);
592     }
593 
RunPreopt()594     int RunPreopt() {
595         if (ShouldSkipPreopt()) {
596             return 0;
597         }
598 
599         int dexopt_result = Dexopt();
600         if (dexopt_result == 0) {
601             return 0;
602         }
603 
604         // If the dexopt failed, we may have a stale boot image from a previous OTA run.
605         // Then regenerate and retry.
606         if (WEXITSTATUS(dexopt_result) ==
607                 static_cast<int>(art::dex2oat::ReturnCode::kCreateRuntime)) {
608             if (!PrepareBootImage(/* force */ true)) {
609                 LOG(ERROR) << "Forced boot image creating failed. Original error return was "
610                         << dexopt_result;
611                 return dexopt_result;
612             }
613 
614             int dexopt_result_boot_image_retry = Dexopt();
615             if (dexopt_result_boot_image_retry == 0) {
616                 return 0;
617             }
618         }
619 
620         // If this was a profile-guided run, we may have profile version issues. Try to downgrade,
621         // if possible.
622         if ((parameters_.dexopt_flags & DEXOPT_PROFILE_GUIDED) == 0) {
623             return dexopt_result;
624         }
625 
626         LOG(WARNING) << "Downgrading compiler filter in an attempt to progress compilation";
627         parameters_.dexopt_flags &= ~DEXOPT_PROFILE_GUIDED;
628         return Dexopt();
629     }
630 
631     ////////////////////////////////////
632     // Helpers, mostly taken from ART //
633     ////////////////////////////////////
634 
635     // Wrapper on fork/execv to run a command in a subprocess.
Exec(const std::vector<std::string> & arg_vector,std::string * error_msg)636     static bool Exec(const std::vector<std::string>& arg_vector, std::string* error_msg) {
637         const std::string command_line = Join(arg_vector, ' ');
638 
639         CHECK_GE(arg_vector.size(), 1U) << command_line;
640 
641         // Convert the args to char pointers.
642         const char* program = arg_vector[0].c_str();
643         std::vector<char*> args;
644         for (size_t i = 0; i < arg_vector.size(); ++i) {
645             const std::string& arg = arg_vector[i];
646             char* arg_str = const_cast<char*>(arg.c_str());
647             CHECK(arg_str != nullptr) << i;
648             args.push_back(arg_str);
649         }
650         args.push_back(nullptr);
651 
652         // Fork and exec.
653         pid_t pid = fork();
654         if (pid == 0) {
655             // No allocation allowed between fork and exec.
656 
657             // Change process groups, so we don't get reaped by ProcessManager.
658             setpgid(0, 0);
659 
660             execv(program, &args[0]);
661 
662             PLOG(ERROR) << "Failed to execv(" << command_line << ")";
663             // _exit to avoid atexit handlers in child.
664             _exit(1);
665         } else {
666             if (pid == -1) {
667                 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
668                         command_line.c_str(), strerror(errno));
669                 return false;
670             }
671 
672             // wait for subprocess to finish
673             int status;
674             pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
675             if (got_pid != pid) {
676                 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
677                         "wanted %d, got %d: %s",
678                         command_line.c_str(), pid, got_pid, strerror(errno));
679                 return false;
680             }
681             if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
682                 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
683                         command_line.c_str());
684                 return false;
685             }
686         }
687         return true;
688     }
689 
690     // Choose a random relocation offset. Taken from art/runtime/gc/image_space.cc.
ChooseRelocationOffsetDelta(int32_t min_delta,int32_t max_delta)691     static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
692         constexpr size_t kPageSize = PAGE_SIZE;
693         CHECK_EQ(min_delta % kPageSize, 0u);
694         CHECK_EQ(max_delta % kPageSize, 0u);
695         CHECK_LT(min_delta, max_delta);
696 
697         std::default_random_engine generator;
698         generator.seed(GetSeed());
699         std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
700         int32_t r = distribution(generator);
701         if (r % 2 == 0) {
702             r = RoundUp(r, kPageSize);
703         } else {
704             r = RoundDown(r, kPageSize);
705         }
706         CHECK_LE(min_delta, r);
707         CHECK_GE(max_delta, r);
708         CHECK_EQ(r % kPageSize, 0u);
709         return r;
710     }
711 
GetSeed()712     static uint64_t GetSeed() {
713 #ifdef __BIONIC__
714         // Bionic exposes arc4random, use it.
715         uint64_t random_data;
716         arc4random_buf(&random_data, sizeof(random_data));
717         return random_data;
718 #else
719 #error "This is only supposed to run with bionic. Otherwise, implement..."
720 #endif
721     }
722 
AddCompilerOptionFromSystemProperty(const char * system_property,const char * prefix,bool runtime,std::vector<std::string> & out) const723     void AddCompilerOptionFromSystemProperty(const char* system_property,
724             const char* prefix,
725             bool runtime,
726             std::vector<std::string>& out) const {
727         const std::string* value = system_properties_.GetProperty(system_property);
728         if (value != nullptr) {
729             if (runtime) {
730                 out.push_back("--runtime-arg");
731             }
732             if (prefix != nullptr) {
733                 out.push_back(StringPrintf("%s%s", prefix, value->c_str()));
734             } else {
735                 out.push_back(*value);
736             }
737         }
738     }
739 
740     static constexpr const char* kBootClassPathPropertyName = "BOOTCLASSPATH";
741     static constexpr const char* kAndroidRootPathPropertyName = "ANDROID_ROOT";
742     static constexpr const char* kAndroidDataPathPropertyName = "ANDROID_DATA";
743     // The index of the instruction-set string inside the package parameters. Needed for
744     // some special-casing that requires knowledge of the instruction-set.
745     static constexpr size_t kISAIndex = 3;
746 
747     // Stores the system properties read out of the B partition. We need to use these properties
748     // to compile, instead of the A properties we could get from init/get_property.
749     SystemProperties system_properties_;
750 
751     // Some select properties that are always needed.
752     std::string android_root_;
753     std::string android_data_;
754     std::string boot_classpath_;
755     std::string asec_mountpoint_;
756 
757     OTAPreoptParameters parameters_;
758 
759     // Store environment values we need to set.
760     std::vector<std::string> environ_;
761 };
762 
763 OTAPreoptService gOps;
764 
765 ////////////////////////
766 // Plug-in functions. //
767 ////////////////////////
768 
get_property(const char * key,char * value,const char * default_value)769 int get_property(const char *key, char *value, const char *default_value) {
770     return gOps.GetProperty(key, value, default_value);
771 }
772 
773 // 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)774 bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir,
775                              const char *apk_path,
776                              const char *instruction_set) {
777     const char *file_name_start;
778     const char *file_name_end;
779 
780     file_name_start = strrchr(apk_path, '/');
781     if (file_name_start == nullptr) {
782         ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
783         return false;
784     }
785     file_name_end = strrchr(file_name_start, '.');
786     if (file_name_end == nullptr) {
787         ALOGE("apk_path '%s' has no extension\n", apk_path);
788         return false;
789     }
790 
791     // Calculate file_name
792     file_name_start++;  // Move past '/', is valid as file_name_end is valid.
793     size_t file_name_len = file_name_end - file_name_start;
794     std::string file_name(file_name_start, file_name_len);
795 
796     // <apk_parent_dir>/oat/<isa>/<file_name>.odex.b
797     snprintf(path,
798              PKG_PATH_MAX,
799              "%s/%s/%s.odex.%s",
800              oat_dir,
801              instruction_set,
802              file_name.c_str(),
803              gOps.GetTargetSlot().c_str());
804     return true;
805 }
806 
807 /*
808  * Computes the odex file for the given apk_path and instruction_set.
809  * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
810  *
811  * Returns false if it failed to determine the odex file path.
812  */
calculate_odex_file_path(char path[PKG_PATH_MAX],const char * apk_path,const char * instruction_set)813 bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
814                               const char *instruction_set) {
815     const char *path_end = strrchr(apk_path, '/');
816     if (path_end == nullptr) {
817         ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
818         return false;
819     }
820     std::string path_component(apk_path, path_end - apk_path);
821 
822     const char *name_begin = path_end + 1;
823     const char *extension_start = strrchr(name_begin, '.');
824     if (extension_start == nullptr) {
825         ALOGE("apk_path '%s' has no extension.\n", apk_path);
826         return false;
827     }
828     std::string name_component(name_begin, extension_start - name_begin);
829 
830     std::string new_path = StringPrintf("%s/oat/%s/%s.odex.%s",
831                                         path_component.c_str(),
832                                         instruction_set,
833                                         name_component.c_str(),
834                                         gOps.GetTargetSlot().c_str());
835     if (new_path.length() >= PKG_PATH_MAX) {
836         LOG(ERROR) << "apk_path of " << apk_path << " is too long: " << new_path;
837         return false;
838     }
839     strcpy(path, new_path.c_str());
840     return true;
841 }
842 
create_cache_path(char path[PKG_PATH_MAX],const char * src,const char * instruction_set)843 bool create_cache_path(char path[PKG_PATH_MAX],
844                        const char *src,
845                        const char *instruction_set) {
846     size_t srclen = strlen(src);
847 
848         /* demand that we are an absolute path */
849     if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
850         return false;
851     }
852 
853     if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
854         return false;
855     }
856 
857     std::string from_src = std::string(src + 1);
858     std::replace(from_src.begin(), from_src.end(), '/', '@');
859 
860     std::string assembled_path = StringPrintf("%s/%s/%s/%s%s",
861                                               gOps.GetOTADataDirectory().c_str(),
862                                               DALVIK_CACHE,
863                                               instruction_set,
864                                               from_src.c_str(),
865                                               DALVIK_CACHE_POSTFIX);
866 
867     if (assembled_path.length() + 1 > PKG_PATH_MAX) {
868         return false;
869     }
870     strcpy(path, assembled_path.c_str());
871 
872     return true;
873 }
874 
log_callback(int type,const char * fmt,...)875 static int log_callback(int type, const char *fmt, ...) {
876     va_list ap;
877     int priority;
878 
879     switch (type) {
880         case SELINUX_WARNING:
881             priority = ANDROID_LOG_WARN;
882             break;
883         case SELINUX_INFO:
884             priority = ANDROID_LOG_INFO;
885             break;
886         default:
887             priority = ANDROID_LOG_ERROR;
888             break;
889     }
890     va_start(ap, fmt);
891     LOG_PRI_VA(priority, "SELinux", fmt, ap);
892     va_end(ap);
893     return 0;
894 }
895 
otapreopt_main(const int argc,char * argv[])896 static int otapreopt_main(const int argc, char *argv[]) {
897     int selinux_enabled = (is_selinux_enabled() > 0);
898 
899     setenv("ANDROID_LOG_TAGS", "*:v", 1);
900     android::base::InitLogging(argv);
901 
902     if (argc < 2) {
903         ALOGE("Expecting parameters");
904         exit(1);
905     }
906 
907     union selinux_callback cb;
908     cb.func_log = log_callback;
909     selinux_set_callback(SELINUX_CB_LOG, cb);
910 
911     if (selinux_enabled && selinux_status_open(true) < 0) {
912         ALOGE("Could not open selinux status; exiting.\n");
913         exit(1);
914     }
915 
916     int ret = android::installd::gOps.Main(argc, argv);
917 
918     return ret;
919 }
920 
921 }  // namespace installd
922 }  // namespace android
923 
main(const int argc,char * argv[])924 int main(const int argc, char *argv[]) {
925     return android::installd::otapreopt_main(argc, argv);
926 }
927