• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 "file_utils.h"
18 
19 #include <inttypes.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 
23 #ifndef _WIN32
24 #include <sys/wait.h>
25 #endif
26 #include <unistd.h>
27 
28 // We need dladdr.
29 #if !defined(__APPLE__) && !defined(_WIN32)
30 #ifndef _GNU_SOURCE
31 #define _GNU_SOURCE
32 #define DEFINED_GNU_SOURCE
33 #endif
34 #include <dlfcn.h>
35 #include <libgen.h>
36 #ifdef DEFINED_GNU_SOURCE
37 #undef _GNU_SOURCE
38 #undef DEFINED_GNU_SOURCE
39 #endif
40 #endif
41 
42 #include <memory>
43 #include <sstream>
44 #include <vector>
45 
46 #include "android-base/file.h"
47 #include "android-base/logging.h"
48 #include "android-base/properties.h"
49 #include "android-base/stringprintf.h"
50 #include "android-base/strings.h"
51 #include "base/bit_utils.h"
52 #include "base/globals.h"
53 #include "base/os.h"
54 #include "base/stl_util.h"
55 #include "base/unix_file/fd_file.h"
56 #include "base/utils.h"
57 
58 #if defined(__APPLE__)
59 #include <crt_externs.h>
60 #include <sys/syscall.h>
61 
62 #include "AvailabilityMacros.h"  // For MAC_OS_X_VERSION_MAX_ALLOWED
63 #endif
64 
65 #if defined(__linux__)
66 #include <linux/unistd.h>
67 #endif
68 
69 #ifdef ART_TARGET_ANDROID
70 #include "android-modules-utils/sdk_level.h"
71 #endif
72 
73 namespace art {
74 
75 using android::base::ConsumePrefix;
76 using android::base::GetBoolProperty;
77 using android::base::GetProperty;
78 using android::base::StringPrintf;
79 
80 static constexpr const char* kClassesDex = "classes.dex";
81 static constexpr const char* kAndroidRootEnvVar = "ANDROID_ROOT";
82 static constexpr const char* kAndroidRootDefaultPath = "/system";
83 static constexpr const char* kAndroidSystemExtRootEnvVar = "SYSTEM_EXT_ROOT";
84 static constexpr const char* kAndroidSystemExtRootDefaultPath = "/system_ext";
85 static constexpr const char* kAndroidDataEnvVar = "ANDROID_DATA";
86 static constexpr const char* kAndroidDataDefaultPath = "/data";
87 static constexpr const char* kAndroidExpandEnvVar = "ANDROID_EXPAND";
88 static constexpr const char* kAndroidExpandDefaultPath = "/mnt/expand";
89 static constexpr const char* kAndroidArtRootEnvVar = "ANDROID_ART_ROOT";
90 static constexpr const char* kAndroidConscryptRootEnvVar = "ANDROID_CONSCRYPT_ROOT";
91 static constexpr const char* kApexDefaultPath = "/apex/";
92 static constexpr const char* kArtApexDataEnvVar = "ART_APEX_DATA";
93 static constexpr const char* kBootImageStem = "boot";
94 
95 // Get the "root" directory containing the "lib" directory where this instance
96 // of the libartbase library (which contains `GetRootContainingLibartbase`) is
97 // located:
98 // - on host this "root" is normally the Android Root (e.g. something like
99 //   "$ANDROID_BUILD_TOP/out/host/linux-x86/");
100 // - on target this "root" is normally the ART Root ("/apex/com.android.art").
101 // Return the empty string if that directory cannot be found or if this code is
102 // run on Windows or macOS.
GetRootContainingLibartbase()103 static std::string GetRootContainingLibartbase() {
104 #if !defined(_WIN32) && !defined(__APPLE__)
105   // Check where libartbase is from, and derive from there.
106   Dl_info info;
107   if (dladdr(reinterpret_cast<const void*>(&GetRootContainingLibartbase), /* out */ &info) != 0) {
108     // Make a duplicate of the fname so dirname can modify it.
109     UniqueCPtr<char> fname(strdup(info.dli_fname));
110 
111     char* dir1 = dirname(fname.get());  // This is the lib directory.
112     char* dir2 = dirname(dir1);         // This is the "root" directory.
113     if (OS::DirectoryExists(dir2)) {
114       std::string tmp = dir2;  // Make a copy here so that fname can be released.
115       return tmp;
116     }
117   }
118 #endif
119   return "";
120 }
121 
GetAndroidDirSafe(const char * env_var,const char * default_dir,bool must_exist,std::string * error_msg)122 static const char* GetAndroidDirSafe(const char* env_var,
123                                      const char* default_dir,
124                                      bool must_exist,
125                                      std::string* error_msg) {
126   const char* android_dir = getenv(env_var);
127   if (android_dir == nullptr) {
128     if (!must_exist || OS::DirectoryExists(default_dir)) {
129       android_dir = default_dir;
130     } else {
131       *error_msg = StringPrintf("%s not set and %s does not exist", env_var, default_dir);
132       return nullptr;
133     }
134   }
135   if (must_exist && !OS::DirectoryExists(android_dir)) {
136     *error_msg = StringPrintf("Failed to find directory %s", android_dir);
137     return nullptr;
138   }
139   return android_dir;
140 }
141 
GetAndroidDir(const char * env_var,const char * default_dir,bool must_exist=true)142 static const char* GetAndroidDir(const char* env_var,
143                                  const char* default_dir,
144                                  bool must_exist = true) {
145   std::string error_msg;
146   const char* dir = GetAndroidDirSafe(env_var, default_dir, must_exist, &error_msg);
147   if (dir != nullptr) {
148     return dir;
149   } else {
150     LOG(FATAL) << error_msg;
151     UNREACHABLE();
152   }
153 }
154 
GetAndroidRootSafe(std::string * error_msg)155 std::string GetAndroidRootSafe(std::string* error_msg) {
156 #ifdef _WIN32
157   UNUSED(kAndroidRootEnvVar, kAndroidRootDefaultPath, GetRootContainingLibartbase);
158   *error_msg = "GetAndroidRootSafe unsupported for Windows.";
159   return "";
160 #else
161   std::string local_error_msg;
162   const char* dir = GetAndroidDirSafe(kAndroidRootEnvVar, kAndroidRootDefaultPath,
163       /*must_exist=*/ true, &local_error_msg);
164   if (dir == nullptr) {
165     // On host, libartbase is currently installed in "$ANDROID_ROOT/lib"
166     // (e.g. something like "$ANDROID_BUILD_TOP/out/host/linux-x86/lib". Use this
167     // information to infer the location of the Android Root (on host only).
168     //
169     // Note that this could change in the future, if we decided to install ART
170     // artifacts in a different location, e.g. within an "ART APEX" directory.
171     if (!kIsTargetBuild) {
172       std::string root_containing_libartbase = GetRootContainingLibartbase();
173       if (!root_containing_libartbase.empty()) {
174         return root_containing_libartbase;
175       }
176     }
177     *error_msg = std::move(local_error_msg);
178     return "";
179   }
180 
181   return dir;
182 #endif
183 }
184 
GetAndroidRoot()185 std::string GetAndroidRoot() {
186   std::string error_msg;
187   std::string ret = GetAndroidRootSafe(&error_msg);
188   CHECK(!ret.empty()) << error_msg;
189   return ret;
190 }
191 
GetSystemExtRootSafe(std::string * error_msg)192 std::string GetSystemExtRootSafe(std::string* error_msg) {
193 #ifdef _WIN32
194   UNUSED(kAndroidSystemExtRootEnvVar, kAndroidSystemExtRootDefaultPath);
195   *error_msg = "GetSystemExtRootSafe unsupported for Windows.";
196   return "";
197 #else
198   const char* dir = GetAndroidDirSafe(kAndroidSystemExtRootEnvVar, kAndroidSystemExtRootDefaultPath,
199       /*must_exist=*/ true, error_msg);
200   return dir ? dir : "";
201 #endif
202 }
203 
GetSystemExtRoot()204 std::string GetSystemExtRoot() {
205   std::string error_msg;
206   std::string ret = GetSystemExtRootSafe(&error_msg);
207   CHECK(!ret.empty()) << error_msg;
208   return ret;
209 }
210 
GetArtRootSafe(bool must_exist,std::string * error_msg)211 static std::string GetArtRootSafe(bool must_exist, /*out*/ std::string* error_msg) {
212 #ifdef _WIN32
213   UNUSED(kAndroidArtRootEnvVar, kAndroidArtApexDefaultPath, GetRootContainingLibartbase);
214   UNUSED(must_exist);
215   *error_msg = "GetArtRootSafe unsupported for Windows.";
216   return "";
217 #else
218   // Prefer ANDROID_ART_ROOT if it's set.
219   const char* android_art_root_from_env = getenv(kAndroidArtRootEnvVar);
220   if (android_art_root_from_env != nullptr) {
221     if (must_exist && !OS::DirectoryExists(android_art_root_from_env)) {
222       *error_msg = StringPrintf(
223           "Failed to find %s directory %s", kAndroidArtRootEnvVar, android_art_root_from_env);
224       return "";
225     }
226     return android_art_root_from_env;
227   }
228 
229   // On target, libartbase is normally installed in
230   // "$ANDROID_ART_ROOT/lib(64)" (e.g. something like
231   // "/apex/com.android.art/lib(64)". Use this information to infer the
232   // location of the ART Root (on target only).
233   if (kIsTargetBuild) {
234     // *However*, a copy of libartbase may still be installed outside the
235     // ART Root on some occasions, as ART target gtests install their binaries
236     // and their dependencies under the Android Root, i.e. "/system" (see
237     // b/129534335). For that reason, we cannot reliably use
238     // `GetRootContainingLibartbase` to find the ART Root. (Note that this is
239     // not really a problem in practice, as Android Q devices define
240     // ANDROID_ART_ROOT in their default environment, and will instead use
241     // the logic above anyway.)
242     //
243     // TODO(b/129534335): Re-enable this logic when the only instance of
244     // libartbase on target is the one from the ART APEX.
245     if ((false)) {
246       std::string root_containing_libartbase = GetRootContainingLibartbase();
247       if (!root_containing_libartbase.empty()) {
248         return root_containing_libartbase;
249       }
250     }
251   }
252 
253   // Try the default path.
254   if (must_exist && !OS::DirectoryExists(kAndroidArtApexDefaultPath)) {
255     *error_msg =
256         StringPrintf("Failed to find default ART root directory %s", kAndroidArtApexDefaultPath);
257     return "";
258   }
259   return kAndroidArtApexDefaultPath;
260 #endif
261 }
262 
GetArtRootSafe(std::string * error_msg)263 std::string GetArtRootSafe(std::string* error_msg) {
264   return GetArtRootSafe(/* must_exist= */ true, error_msg);
265 }
266 
GetArtRoot()267 std::string GetArtRoot() {
268   std::string error_msg;
269   std::string ret = GetArtRootSafe(&error_msg);
270   if (ret.empty()) {
271     LOG(FATAL) << error_msg;
272     UNREACHABLE();
273   }
274   return ret;
275 }
276 
GetArtBinDir()277 std::string GetArtBinDir() {
278   // Environment variable `ANDROID_ART_ROOT` is defined as
279   // `$ANDROID_HOST_OUT/com.android.art` on host. However, host ART binaries are
280   // still installed in `$ANDROID_HOST_OUT/bin` (i.e. outside the ART Root). The
281   // situation is cleaner on target, where `ANDROID_ART_ROOT` is
282   // `$ANDROID_ROOT/apex/com.android.art` and ART binaries are installed in
283   // `$ANDROID_ROOT/apex/com.android.art/bin`.
284   std::string android_art_root = kIsTargetBuild ? GetArtRoot() : GetAndroidRoot();
285   return android_art_root + "/bin";
286 }
287 
GetAndroidDataSafe(std::string * error_msg)288 std::string GetAndroidDataSafe(std::string* error_msg) {
289   const char* android_dir = GetAndroidDirSafe(kAndroidDataEnvVar,
290                                               kAndroidDataDefaultPath,
291                                               /* must_exist= */ true,
292                                               error_msg);
293   return (android_dir != nullptr) ? android_dir : "";
294 }
295 
GetAndroidData()296 std::string GetAndroidData() { return GetAndroidDir(kAndroidDataEnvVar, kAndroidDataDefaultPath); }
297 
GetAndroidExpandSafe(std::string * error_msg)298 std::string GetAndroidExpandSafe(std::string* error_msg) {
299   const char* android_dir = GetAndroidDirSafe(kAndroidExpandEnvVar,
300                                               kAndroidExpandDefaultPath,
301                                               /*must_exist=*/true,
302                                               error_msg);
303   return (android_dir != nullptr) ? android_dir : "";
304 }
305 
GetAndroidExpand()306 std::string GetAndroidExpand() {
307   return GetAndroidDir(kAndroidExpandEnvVar, kAndroidExpandDefaultPath);
308 }
309 
GetArtApexData()310 std::string GetArtApexData() {
311   return GetAndroidDir(kArtApexDataEnvVar, kArtApexDataDefaultPath, /*must_exist=*/false);
312 }
313 
GetPrebuiltPrimaryBootImageDir(const std::string & android_root)314 static std::string GetPrebuiltPrimaryBootImageDir(const std::string& android_root) {
315   return StringPrintf("%s/framework", android_root.c_str());
316 }
317 
GetPrebuiltPrimaryBootImageDir()318 std::string GetPrebuiltPrimaryBootImageDir() {
319   std::string android_root = GetAndroidRoot();
320   if (android_root.empty()) {
321     return "";
322   }
323   return GetPrebuiltPrimaryBootImageDir(android_root);
324 }
325 
GetFirstMainlineFrameworkLibraryFilename(std::string * error_msg)326 std::string GetFirstMainlineFrameworkLibraryFilename(std::string* error_msg) {
327   const char* env_bcp = getenv("BOOTCLASSPATH");
328   const char* env_dex2oat_bcp = getenv("DEX2OATBOOTCLASSPATH");
329   if (env_bcp == nullptr || env_dex2oat_bcp == nullptr) {
330     *error_msg = "BOOTCLASSPATH and DEX2OATBOOTCLASSPATH must not be empty";
331     return "";
332   }
333 
334   // DEX2OATBOOTCLASSPATH contains core libraries and framework libraries. We used to only compile
335   // those libraries. Now we compile mainline framework libraries as well, and we have repurposed
336   // DEX2OATBOOTCLASSPATH to indicate the separation between mainline framework libraries and other
337   // libraries.
338   std::string_view mainline_bcp(env_bcp);
339   if (!android::base::ConsumePrefix(&mainline_bcp, env_dex2oat_bcp)) {
340     *error_msg = "DEX2OATBOOTCLASSPATH must be a prefix of BOOTCLASSPATH";
341     return "";
342   }
343 
344   std::vector<std::string_view> mainline_bcp_jars;
345   Split(mainline_bcp, ':', &mainline_bcp_jars);
346   if (mainline_bcp_jars.empty()) {
347     *error_msg = "No mainline framework library found";
348     return "";
349   }
350 
351   return std::string(mainline_bcp_jars[0]);
352 }
353 
GetFirstMainlineFrameworkLibraryName(std::string * error_msg)354 static std::string GetFirstMainlineFrameworkLibraryName(std::string* error_msg) {
355   std::string filename = GetFirstMainlineFrameworkLibraryFilename(error_msg);
356   if (filename.empty()) {
357     return "";
358   }
359 
360   std::string jar_name = android::base::Basename(filename);
361 
362   std::string_view library_name(jar_name);
363   if (!android::base::ConsumeSuffix(&library_name, ".jar")) {
364     *error_msg = "Invalid mainline framework jar: " + jar_name;
365     return "";
366   }
367 
368   return std::string(library_name);
369 }
370 
371 // Returns true when no error occurs, even if the extension doesn't exist.
MaybeAppendBootImageMainlineExtension(const std::string & android_root,bool deny_system_files,bool deny_art_apex_data_files,std::string * location,std::string * error_msg)372 static bool MaybeAppendBootImageMainlineExtension(const std::string& android_root,
373                                                   bool deny_system_files,
374                                                   bool deny_art_apex_data_files,
375                                                   /*inout*/ std::string* location,
376                                                   /*out*/ std::string* error_msg) {
377   if (!kIsTargetAndroid || RunningOnVM()) {
378     return true;
379   }
380   // Due to how the runtime determines the mapping between boot images and bootclasspath jars, the
381   // name of the boot image extension must be in the format of
382   // `<primary-boot-image-stem>-<first-library-name>.art`.
383   std::string library_name = GetFirstMainlineFrameworkLibraryName(error_msg);
384   if (library_name.empty()) {
385     return false;
386   }
387 
388   if (!deny_art_apex_data_files) {
389     std::string mainline_extension_location =
390         StringPrintf("%s/%s-%s.art",
391                      GetApexDataDalvikCacheDirectory(InstructionSet::kNone).c_str(),
392                      kBootImageStem,
393                      library_name.c_str());
394     std::string mainline_extension_path =
395         GetSystemImageFilename(mainline_extension_location.c_str(), kRuntimeISA);
396     if (OS::FileExists(mainline_extension_path.c_str(), /*check_file_type=*/true)) {
397       *location += ":" + mainline_extension_location;
398       return true;
399     }
400   }
401 
402   if (!deny_system_files) {
403     std::string mainline_extension_location = StringPrintf(
404         "%s/framework/%s-%s.art", android_root.c_str(), kBootImageStem, library_name.c_str());
405     std::string mainline_extension_path =
406         GetSystemImageFilename(mainline_extension_location.c_str(), kRuntimeISA);
407     // It is expected that the file doesn't exist when the ART module is preloaded on an old source
408     // tree that doesn't dexpreopt mainline BCP jars, so it shouldn't be considered as an error.
409     if (OS::FileExists(mainline_extension_path.c_str(), /*check_file_type=*/true)) {
410       *location += ":" + mainline_extension_location;
411       return true;
412     }
413   }
414 
415   return true;
416 }
417 
GetDefaultBootImageLocationSafe(const std::string & android_root,bool deny_art_apex_data_files,std::string * error_msg)418 std::string GetDefaultBootImageLocationSafe(const std::string& android_root,
419                                             bool deny_art_apex_data_files,
420                                             std::string* error_msg) {
421   constexpr static const char* kEtcBootImageProf = "etc/boot-image.prof";
422   constexpr static const char* kMinimalBootImageStem = "boot_minimal";
423 
424   // If an update for the ART module has been been installed, a single boot image for the entire
425   // bootclasspath is in the ART APEX data directory.
426   if (kIsTargetBuild && !deny_art_apex_data_files) {
427     const std::string boot_image = GetApexDataDalvikCacheDirectory(InstructionSet::kNone) + "/" +
428                                    kBootImageStem + kArtExtension;
429     const std::string boot_image_filename = GetSystemImageFilename(boot_image.c_str(), kRuntimeISA);
430     if (OS::FileExists(boot_image_filename.c_str(), /*check_file_type=*/true)) {
431       // Boot image consists of two parts:
432       //  - the primary boot image (contains the Core Libraries and framework libraries)
433       //  - the boot image mainline extension (contains mainline framework libraries)
434       // Typically
435       // "/data/misc/apexdata/com.android.art/dalvik-cache/boot.art!/apex/com.android.art
436       // /etc/boot-image.prof!/system/etc/boot-image.prof:
437       // /data/misc/apexdata/com.android.art/dalvik-cache/boot-framework-adservices.art".
438       std::string location = StringPrintf("%s!%s/%s!%s/%s",
439                                           boot_image.c_str(),
440                                           kAndroidArtApexDefaultPath,
441                                           kEtcBootImageProf,
442                                           android_root.c_str(),
443                                           kEtcBootImageProf);
444       if (!MaybeAppendBootImageMainlineExtension(android_root,
445                                                  /*deny_system_files=*/true,
446                                                  deny_art_apex_data_files,
447                                                  &location,
448                                                  error_msg)) {
449         return "";
450       }
451       return location;
452     } else if (errno == EACCES) {
453       // Additional warning for potential SELinux misconfiguration.
454       PLOG(ERROR) << "Default boot image check failed, could not stat: " << boot_image_filename;
455     }
456 
457     // odrefresh can generate a minimal boot image, which only includes code from BCP jars in the
458     // ART module, when it fails to generate a single boot image for the entire bootclasspath (i.e.,
459     // full boot image). Use it if it exists.
460     const std::string minimal_boot_image = GetApexDataDalvikCacheDirectory(InstructionSet::kNone) +
461                                            "/" + kMinimalBootImageStem + kArtExtension;
462     const std::string minimal_boot_image_filename =
463         GetSystemImageFilename(minimal_boot_image.c_str(), kRuntimeISA);
464     if (OS::FileExists(minimal_boot_image_filename.c_str(), /*check_file_type=*/true)) {
465       // Typically "/data/misc/apexdata/com.android.art/dalvik-cache/boot_minimal.art!/apex
466       // /com.android.art/etc/boot-image.prof:/nonx/boot_minimal-framework.art!/system/etc
467       // /boot-image.prof".
468       return StringPrintf("%s!%s/%s:/nonx/%s-framework.art!%s/%s",
469                           minimal_boot_image.c_str(),
470                           kAndroidArtApexDefaultPath,
471                           kEtcBootImageProf,
472                           kMinimalBootImageStem,
473                           android_root.c_str(),
474                           kEtcBootImageProf);
475     } else if (errno == EACCES) {
476       // Additional warning for potential SELinux misconfiguration.
477       PLOG(ERROR) << "Minimal boot image check failed, could not stat: " << boot_image_filename;
478     }
479   }
480 
481   // Boot image consists of two parts:
482   //  - the primary boot image (contains the Core Libraries and framework libraries)
483   //  - the boot image mainline extension (contains mainline framework libraries)
484   // Typically "/system/framework/boot.art
485   // !/apex/com.android.art/etc/boot-image.prof!/system/etc/boot-image.prof:
486   // /system/framework/boot-framework-adservices.art".
487 
488   std::string location = StringPrintf("%s/%s.art!%s/%s!%s/%s",
489                                       GetPrebuiltPrimaryBootImageDir(android_root).c_str(),
490                                       kBootImageStem,
491                                       kAndroidArtApexDefaultPath,
492                                       kEtcBootImageProf,
493                                       android_root.c_str(),
494                                       kEtcBootImageProf);
495 
496 #ifdef ART_TARGET_ANDROID
497   // Prior to U, there was a framework extension.
498   if (!android::modules::sdklevel::IsAtLeastU()) {
499     location = StringPrintf("%s/%s.art!%s/%s:%s/framework/%s-framework.art!%s/%s",
500                             GetPrebuiltPrimaryBootImageDir(android_root).c_str(),
501                             kBootImageStem,
502                             kAndroidArtApexDefaultPath,
503                             kEtcBootImageProf,
504                             android_root.c_str(),
505                             kBootImageStem,
506                             android_root.c_str(),
507                             kEtcBootImageProf);
508   }
509 #endif
510 
511   if (!MaybeAppendBootImageMainlineExtension(android_root,
512                                              /*deny_system_files=*/false,
513                                              deny_art_apex_data_files,
514                                              &location,
515                                              error_msg)) {
516     return "";
517   }
518   return location;
519 }
520 
GetDefaultBootImageLocation(const std::string & android_root,bool deny_art_apex_data_files)521 std::string GetDefaultBootImageLocation(const std::string& android_root,
522                                         bool deny_art_apex_data_files) {
523   std::string error_msg;
524   std::string location =
525       GetDefaultBootImageLocationSafe(android_root, deny_art_apex_data_files, &error_msg);
526   CHECK(!location.empty()) << error_msg;
527   return location;
528 }
529 
GetJitZygoteBootImageLocation()530 std::string GetJitZygoteBootImageLocation() {
531   // Intentionally use a non-existing location so that the runtime will fail to find the boot image
532   // and JIT bootclasspath with the given profiles.
533   return "/nonx/boot.art!/apex/com.android.art/etc/boot-image.prof!/system/etc/boot-image.prof";
534 }
535 
GetBootImageLocationForDefaultBcp(bool no_boot_image,std::string user_defined_boot_image,bool deny_art_apex_data_files,std::string * error_msg)536 std::string GetBootImageLocationForDefaultBcp(bool no_boot_image,
537                                               std::string user_defined_boot_image,
538                                               bool deny_art_apex_data_files,
539                                               std::string* error_msg) {
540   if (no_boot_image) {
541     return GetJitZygoteBootImageLocation();
542   }
543   if (!user_defined_boot_image.empty()) {
544     return user_defined_boot_image;
545   }
546   std::string android_root = GetAndroidRootSafe(error_msg);
547   if (!error_msg->empty()) {
548     return "";
549   }
550   return GetDefaultBootImageLocationSafe(android_root, deny_art_apex_data_files, error_msg);
551 }
552 
GetBootImageLocationForDefaultBcpRespectingSysProps(std::string * error_msg)553 std::string GetBootImageLocationForDefaultBcpRespectingSysProps(std::string* error_msg) {
554   bool no_boot_image =
555       GetBoolProperty("persist.device_config.runtime_native_boot.profilebootclasspath",
556                       GetBoolProperty("dalvik.vm.profilebootclasspath", /*default_value=*/false));
557   std::string user_defined_boot_image = GetProperty("dalvik.vm.boot-image", /*default_value=*/"");
558   bool deny_art_apex_data_files =
559       !GetBoolProperty("odsign.verification.success", /*default_value=*/false);
560   return GetBootImageLocationForDefaultBcp(
561       no_boot_image, user_defined_boot_image, deny_art_apex_data_files, error_msg);
562 }
563 
564 static /*constinit*/ std::string_view dalvik_cache_sub_dir = "dalvik-cache";
565 
OverrideDalvikCacheSubDirectory(std::string sub_dir)566 void OverrideDalvikCacheSubDirectory(std::string sub_dir) {
567   static std::string overridden_dalvik_cache_sub_dir;
568   overridden_dalvik_cache_sub_dir = std::move(sub_dir);
569   dalvik_cache_sub_dir = overridden_dalvik_cache_sub_dir;
570 }
571 
GetDalvikCacheDirectory(std::string_view root_directory,std::string_view sub_directory={})572 static std::string GetDalvikCacheDirectory(std::string_view root_directory,
573                                            std::string_view sub_directory = {}) {
574   std::stringstream oss;
575   oss << root_directory << '/' << dalvik_cache_sub_dir;
576   if (!sub_directory.empty()) {
577     oss << '/' << sub_directory;
578   }
579   return oss.str();
580 }
581 
GetDalvikCache(const char * subdir,const bool create_if_absent,std::string * dalvik_cache,bool * have_android_data,bool * dalvik_cache_exists,bool * is_global_cache)582 void GetDalvikCache(const char* subdir,
583                     const bool create_if_absent,
584                     std::string* dalvik_cache,
585                     bool* have_android_data,
586                     bool* dalvik_cache_exists,
587                     bool* is_global_cache) {
588 #ifdef _WIN32
589   UNUSED(subdir);
590   UNUSED(create_if_absent);
591   UNUSED(dalvik_cache);
592   UNUSED(have_android_data);
593   UNUSED(dalvik_cache_exists);
594   UNUSED(is_global_cache);
595   LOG(FATAL) << "GetDalvikCache unsupported on Windows.";
596 #else
597   CHECK(subdir != nullptr);
598   std::string unused_error_msg;
599   std::string android_data = GetAndroidDataSafe(&unused_error_msg);
600   if (android_data.empty()) {
601     *have_android_data = false;
602     *dalvik_cache_exists = false;
603     *is_global_cache = false;
604     return;
605   } else {
606     *have_android_data = true;
607   }
608   const std::string dalvik_cache_root = GetDalvikCacheDirectory(android_data);
609   *dalvik_cache = dalvik_cache_root + '/' + subdir;
610   *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
611   *is_global_cache = (android_data == kAndroidDataDefaultPath);
612   if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
613     // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
614     *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
615                             (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
616   }
617 #endif
618 }
619 
620 // Returns a path formed by encoding the dex location into the filename. The path returned will be
621 // rooted at `cache_location`.
GetLocationEncodedFilename(std::string_view location,std::string_view cache_location,std::string * filename,std::string * error_msg)622 static bool GetLocationEncodedFilename(std::string_view location,
623                                        std::string_view cache_location,
624                                        std::string* filename,
625                                        std::string* error_msg) {
626   if (!location.starts_with('/')) {
627     *error_msg = "Expected path in location to be absolute: " + std::string(location);
628     return false;
629   }
630   *filename = cache_location;
631   *filename += location;  // Including the leading slash.
632   size_t replace_start = cache_location.length() + /* skip the leading slash from `location` */ 1u;
633   std::replace(filename->begin() + replace_start, filename->end(), '/', '@');
634   if (!location.ends_with(".dex") && !location.ends_with(kArtExtension) &&
635       !location.ends_with(kOatExtension)) {
636     *filename += "@";
637     *filename += kClassesDex;
638   }
639   return true;
640 }
641 
GetDalvikCacheFilename(std::string_view location,std::string_view cache_location,std::string * filename,std::string * error_msg)642 bool GetDalvikCacheFilename(std::string_view location,
643                             std::string_view cache_location,
644                             std::string* filename,
645                             std::string* error_msg) {
646   return GetLocationEncodedFilename(location, cache_location, filename, error_msg);
647 }
648 
GetApexDataDalvikCacheDirectory(InstructionSet isa)649 std::string GetApexDataDalvikCacheDirectory(InstructionSet isa) {
650   if (isa != InstructionSet::kNone) {
651     return GetDalvikCacheDirectory(GetArtApexData(), GetInstructionSetString(isa));
652   }
653   return GetDalvikCacheDirectory(GetArtApexData());
654 }
655 
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,bool is_boot_classpath_location,std::string_view file_extension)656 static std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
657                                                   InstructionSet isa,
658                                                   bool is_boot_classpath_location,
659                                                   std::string_view file_extension) {
660   if (LocationIsOnApex(dex_location) && is_boot_classpath_location) {
661     // We don't compile boot images for updatable APEXes.
662     return {};
663   }
664   std::string apex_data_dalvik_cache = GetApexDataDalvikCacheDirectory(isa);
665   if (!is_boot_classpath_location) {
666     // Arguments: "/system/framework/xyz.jar", "arm", true, "odex"
667     // Result:
668     // "/data/misc/apexdata/com.android.art/dalvik-cache/arm/system@framework@xyz.jar@classes.odex"
669     std::string result, unused_error_msg;
670     GetDalvikCacheFilename(dex_location,
671                            apex_data_dalvik_cache,
672                            &result,
673                            &unused_error_msg);
674     return ReplaceFileExtension(result, file_extension);
675   } else {
676     // Arguments: "/system/framework/xyz.jar", "x86_64", false, "art"
677     // Results: "/data/misc/apexdata/com.android.art/dalvik-cache/x86_64/boot-xyz.jar@classes.art"
678     std::string basename = android::base::Basename(std::string{dex_location});
679     return apex_data_dalvik_cache + "/boot-" + ReplaceFileExtension(basename, file_extension);
680   }
681 }
682 
GetApexDataOatFilename(std::string_view location,InstructionSet isa)683 std::string GetApexDataOatFilename(std::string_view location, InstructionSet isa) {
684   return GetApexDataDalvikCacheFilename(
685       location, isa, /*is_boot_classpath_location=*/true, kOatExtension);
686 }
687 
GetApexDataOdexFilename(std::string_view location,InstructionSet isa)688 std::string GetApexDataOdexFilename(std::string_view location, InstructionSet isa) {
689   return GetApexDataDalvikCacheFilename(
690       location, isa, /*is_boot_classpath_location=*/false, kOdexExtension);
691 }
692 
GetApexDataBootImage(std::string_view dex_location)693 std::string GetApexDataBootImage(std::string_view dex_location) {
694   return GetApexDataDalvikCacheFilename(
695       dex_location, InstructionSet::kNone, /*is_boot_classpath_location=*/true, kArtExtension);
696 }
697 
GetApexDataImage(std::string_view dex_location)698 std::string GetApexDataImage(std::string_view dex_location) {
699   return GetApexDataDalvikCacheFilename(
700       dex_location, InstructionSet::kNone, /*is_boot_classpath_location=*/false, kArtExtension);
701 }
702 
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,std::string_view file_extension)703 std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
704                                            InstructionSet isa,
705                                            std::string_view file_extension) {
706   return GetApexDataDalvikCacheFilename(
707       dex_location, isa, /*is_boot_classpath_location=*/false, file_extension);
708 }
709 
GetVdexFilename(const std::string & oat_location)710 std::string GetVdexFilename(const std::string& oat_location) {
711   return ReplaceFileExtension(oat_location, kVdexExtension);
712 }
713 
GetDmFilename(const std::string & dex_location)714 std::string GetDmFilename(const std::string& dex_location) {
715   return ReplaceFileExtension(dex_location, kDmExtension);
716 }
717 
GetSdmFilename(const std::string & dex_location,InstructionSet isa)718 std::string GetSdmFilename(const std::string& dex_location, InstructionSet isa) {
719   return ReplaceFileExtension(dex_location,
720                               StringPrintf("%s%s", GetInstructionSetString(isa), kSdmExtension));
721 }
722 
GetSdcFilename(const std::string & oat_location)723 std::string GetSdcFilename(const std::string& oat_location) {
724   return ReplaceFileExtension(oat_location, kSdcExtension);
725 }
726 
727 // check for the file in /system, followed by /system_ext
GetSystemOdexFilenameForApex(std::string_view location,InstructionSet isa)728 std::string GetSystemOdexFilenameForApex(std::string_view location, InstructionSet isa) {
729   DCHECK(LocationIsOnApex(location));
730   std::string dir = GetAndroidRoot() + "/framework/oat/" + GetInstructionSetString(isa);
731   std::string result, error_msg;
732   bool ret = GetLocationEncodedFilename(location, dir, &result, &error_msg);
733   // This should never fail. The function fails only if the location is not absolute, and a location
734   // on /apex is always absolute.
735   DCHECK(ret) << error_msg;
736   std::string path = ReplaceFileExtension(result, kOdexExtension);
737   if (OS::FileExists(path.c_str(), /*check_file_type=*/true)) {
738     return path;
739   }
740   // check in /system_ext
741   dir = GetSystemExtRoot() + "/framework/oat/" + GetInstructionSetString(isa);
742   ret = GetLocationEncodedFilename(location, dir, &result, &error_msg);
743   // This should never fail. The function fails only if the location is not absolute, and a location
744   // on /apex is always absolute.
745   DCHECK(ret) << error_msg;
746   return ReplaceFileExtension(result, kOdexExtension);
747 }
748 
InsertIsaDirectory(const InstructionSet isa,std::string * filename)749 static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
750   // in = /foo/bar/baz
751   // out = /foo/bar/<isa>/baz
752   size_t pos = filename->rfind('/');
753   CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
754   filename->insert(pos, "/", 1);
755   filename->insert(pos + 1, GetInstructionSetString(isa));
756 }
757 
GetSystemImageFilename(const char * location,const InstructionSet isa)758 std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
759   // location = /system/framework/boot.art
760   // filename = /system/framework/<isa>/boot.art
761   std::string filename(location);
762   InsertIsaDirectory(isa, &filename);
763   return filename;
764 }
765 
ReplaceFileExtension(std::string_view filename,std::string_view new_extension)766 std::string ReplaceFileExtension(std::string_view filename, std::string_view new_extension) {
767   ConsumePrefix(&new_extension, ".");
768   const size_t last_ext = filename.find_last_of("./");
769   std::string result;
770   if (last_ext == std::string::npos || filename[last_ext] != '.') {
771     result.reserve(filename.size() + 1 + new_extension.size());
772     result.append(filename).append(".").append(new_extension);
773   } else {
774     result.reserve(last_ext + 1 + new_extension.size());
775     result.append(filename.substr(0, last_ext + 1)).append(new_extension);
776   }
777   return result;
778 }
779 
LocationIsOnArtApexData(std::string_view location)780 bool LocationIsOnArtApexData(std::string_view location) {
781   const std::string art_apex_data = GetArtApexData();
782   return location.starts_with(art_apex_data);
783 }
784 
LocationIsOnArtModule(std::string_view full_path)785 bool LocationIsOnArtModule(std::string_view full_path) {
786   std::string unused_error_msg;
787   std::string module_path = GetArtRootSafe(/* must_exist= */ kIsTargetBuild, &unused_error_msg);
788   if (module_path.empty()) {
789     return false;
790   }
791   return full_path.starts_with(module_path);
792 }
793 
StartsWithSlash(const char * str)794 static bool StartsWithSlash(const char* str) {
795   DCHECK(str != nullptr);
796   return str[0] == '/';
797 }
798 
EndsWithSlash(const char * str)799 static bool EndsWithSlash(const char* str) {
800   DCHECK(str != nullptr);
801   size_t len = strlen(str);
802   return len > 0 && str[len - 1] == '/';
803 }
804 
805 // Returns true if `full_path` is located in folder either provided with `env_var`
806 // or in `default_path` otherwise. The caller may optionally provide a `subdir`
807 // which will be appended to the tested prefix.
808 // `default_path` and the value of environment variable `env_var`
809 // are expected to begin with a slash and not end with one. If this ever changes,
810 // the path-building logic should be updated.
IsLocationOn(std::string_view full_path,const char * env_var,const char * default_path,const char * subdir=nullptr)811 static bool IsLocationOn(std::string_view full_path,
812                          const char* env_var,
813                          const char* default_path,
814                          const char* subdir = nullptr) {
815   std::string unused_error_msg;
816   const char* path = GetAndroidDirSafe(env_var,
817                                        default_path,
818                                        /* must_exist= */ kIsTargetBuild,
819                                        &unused_error_msg);
820   if (path == nullptr) {
821     return false;
822   }
823 
824   // Build the path which we will check is a prefix of `full_path`. The prefix must
825   // end with a slash, so that "/foo/bar" does not match "/foo/barz".
826   DCHECK(StartsWithSlash(path)) << path;
827   std::string path_prefix(path);
828   if (!EndsWithSlash(path_prefix.c_str())) {
829     path_prefix.append("/");
830   }
831   if (subdir != nullptr) {
832     // If `subdir` is provided, we assume it is provided without a starting slash
833     // but ending with one, e.g. "sub/dir/". `path_prefix` ends with a slash at
834     // this point, so we simply append `subdir`.
835     DCHECK(!StartsWithSlash(subdir) && EndsWithSlash(subdir)) << subdir;
836     path_prefix.append(subdir);
837   }
838 
839   return full_path.starts_with(path_prefix);
840 }
841 
LocationIsOnSystemFramework(std::string_view full_path)842 bool LocationIsOnSystemFramework(std::string_view full_path) {
843   return IsLocationOn(full_path,
844                       kAndroidRootEnvVar,
845                       kAndroidRootDefaultPath,
846                       /* subdir= */ "framework/");
847 }
848 
LocationIsOnSystemExtFramework(std::string_view full_path)849 bool LocationIsOnSystemExtFramework(std::string_view full_path) {
850   return IsLocationOn(full_path,
851                       kAndroidSystemExtRootEnvVar,
852                       kAndroidSystemExtRootDefaultPath,
853                       /* subdir= */ "framework/") ||
854          // When the 'system_ext' partition is not present, builds will create
855          // '/system/system_ext' instead.
856          IsLocationOn(full_path,
857                       kAndroidRootEnvVar,
858                       kAndroidRootDefaultPath,
859                       /* subdir= */ "system_ext/framework/");
860 }
861 
LocationIsOnConscryptModule(std::string_view full_path)862 bool LocationIsOnConscryptModule(std::string_view full_path) {
863   return IsLocationOn(full_path, kAndroidConscryptRootEnvVar, kAndroidConscryptApexDefaultPath);
864 }
865 
LocationIsOnApex(std::string_view full_path)866 bool LocationIsOnApex(std::string_view full_path) {
867   return full_path.starts_with(kApexDefaultPath);
868 }
869 
ApexNameFromLocation(std::string_view full_path)870 std::string_view ApexNameFromLocation(std::string_view full_path) {
871   if (!full_path.starts_with(kApexDefaultPath)) {
872     return {};
873   }
874   size_t start = strlen(kApexDefaultPath);
875   size_t end = full_path.find('/', start);
876   if (end == std::string_view::npos) {
877     return {};
878   }
879   return full_path.substr(start, end - start);
880 }
881 
LocationIsOnSystem(const std::string & location)882 bool LocationIsOnSystem(const std::string& location) {
883 #ifdef _WIN32
884   UNUSED(location);
885   LOG(FATAL) << "LocationIsOnSystem is unsupported on Windows.";
886   return false;
887 #else
888   return location.starts_with(GetAndroidRoot());
889 #endif
890 }
891 
LocationIsOnSystemExt(const std::string & location)892 bool LocationIsOnSystemExt(const std::string& location) {
893 #ifdef _WIN32
894   UNUSED(location);
895   LOG(FATAL) << "LocationIsOnSystemExt is unsupported on Windows.";
896   return false;
897 #else
898   return IsLocationOn(location,
899                       kAndroidSystemExtRootEnvVar,
900                       kAndroidSystemExtRootDefaultPath) ||
901          // When the 'system_ext' partition is not present, builds will create
902          // '/system/system_ext' instead.
903          IsLocationOn(location,
904                       kAndroidRootEnvVar,
905                       kAndroidRootDefaultPath,
906                       /* subdir= */ "system_ext/");
907 #endif
908 }
909 
LocationIsTrusted(const std::string & location,bool trust_art_apex_data_files)910 bool LocationIsTrusted(const std::string& location, bool trust_art_apex_data_files) {
911   if (LocationIsOnSystem(location) || LocationIsOnSystemExt(location)
912         || LocationIsOnArtModule(location)) {
913     return true;
914   }
915   return LocationIsOnArtApexData(location) & trust_art_apex_data_files;
916 }
917 
ArtModuleRootDistinctFromAndroidRoot()918 bool ArtModuleRootDistinctFromAndroidRoot() {
919   std::string error_msg;
920   const char* android_root = GetAndroidDirSafe(kAndroidRootEnvVar,
921                                                kAndroidRootDefaultPath,
922                                                /* must_exist= */ kIsTargetBuild,
923                                                &error_msg);
924   const char* art_root = GetAndroidDirSafe(kAndroidArtRootEnvVar,
925                                            kAndroidArtApexDefaultPath,
926                                            /* must_exist= */ kIsTargetBuild,
927                                            &error_msg);
928   return (android_root != nullptr) && (art_root != nullptr) &&
929          (std::string_view(android_root) != std::string_view(art_root));
930 }
931 
DupCloexec(int fd)932 int DupCloexec(int fd) {
933 #if defined(__linux__)
934   return fcntl(fd, F_DUPFD_CLOEXEC, 0);
935 #else
936   return dup(fd); // NOLINT
937 #endif
938 }
939 
940 }  // namespace art
941