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