• 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 #ifndef _WIN32
23 #include <sys/wait.h>
24 #endif
25 #include <unistd.h>
26 
27 // We need dladdr.
28 #if !defined(__APPLE__) && !defined(_WIN32)
29 #ifndef _GNU_SOURCE
30 #define _GNU_SOURCE
31 #define DEFINED_GNU_SOURCE
32 #endif
33 #include <dlfcn.h>
34 #include <libgen.h>
35 #ifdef DEFINED_GNU_SOURCE
36 #undef _GNU_SOURCE
37 #undef DEFINED_GNU_SOURCE
38 #endif
39 #endif
40 
41 #include <memory>
42 #include <sstream>
43 
44 #include "android-base/file.h"
45 #include "android-base/stringprintf.h"
46 #include "android-base/strings.h"
47 
48 #include "base/bit_utils.h"
49 #include "base/globals.h"
50 #include "base/os.h"
51 #include "base/stl_util.h"
52 #include "base/unix_file/fd_file.h"
53 
54 #if defined(__APPLE__)
55 #include <crt_externs.h>
56 #include <sys/syscall.h>
57 #include "AvailabilityMacros.h"  // For MAC_OS_X_VERSION_MAX_ALLOWED
58 #endif
59 
60 #if defined(__linux__)
61 #include <linux/unistd.h>
62 #endif
63 
64 namespace art {
65 
66 using android::base::StringPrintf;
67 
68 static constexpr const char* kClassesDex = "classes.dex";
69 static constexpr const char* kAndroidRootEnvVar = "ANDROID_ROOT";
70 static constexpr const char* kAndroidRootDefaultPath = "/system";
71 static constexpr const char* kAndroidSystemExtRootEnvVar = "ANDROID_SYSTEM_EXT";
72 static constexpr const char* kAndroidSystemExtRootDefaultPath = "/system_ext";
73 static constexpr const char* kAndroidDataEnvVar = "ANDROID_DATA";
74 static constexpr const char* kAndroidDataDefaultPath = "/data";
75 static constexpr const char* kAndroidArtRootEnvVar = "ANDROID_ART_ROOT";
76 static constexpr const char* kAndroidConscryptRootEnvVar = "ANDROID_CONSCRYPT_ROOT";
77 static constexpr const char* kAndroidI18nRootEnvVar = "ANDROID_I18N_ROOT";
78 static constexpr const char* kApexDefaultPath = "/apex/";
79 static constexpr const char* kArtApexDataEnvVar = "ART_APEX_DATA";
80 
81 // Get the "root" directory containing the "lib" directory where this instance
82 // of the libartbase library (which contains `GetRootContainingLibartbase`) is
83 // located:
84 // - on host this "root" is normally the Android Root (e.g. something like
85 //   "$ANDROID_BUILD_TOP/out/host/linux-x86/");
86 // - on target this "root" is normally the ART Root ("/apex/com.android.art").
87 // Return the empty string if that directory cannot be found or if this code is
88 // run on Windows or macOS.
GetRootContainingLibartbase()89 static std::string GetRootContainingLibartbase() {
90 #if !defined( _WIN32) && !defined(__APPLE__)
91   // Check where libartbase is from, and derive from there.
92   Dl_info info;
93   if (dladdr(reinterpret_cast<const void*>(&GetRootContainingLibartbase), /* out */ &info) != 0) {
94     // Make a duplicate of the fname so dirname can modify it.
95     UniqueCPtr<char> fname(strdup(info.dli_fname));
96 
97     char* dir1 = dirname(fname.get());  // This is the lib directory.
98     char* dir2 = dirname(dir1);         // This is the "root" directory.
99     if (OS::DirectoryExists(dir2)) {
100       std::string tmp = dir2;  // Make a copy here so that fname can be released.
101       return tmp;
102     }
103   }
104 #endif
105   return "";
106 }
107 
GetAndroidRootSafe(std::string * error_msg)108 std::string GetAndroidRootSafe(std::string* error_msg) {
109 #ifdef _WIN32
110   UNUSED(kAndroidRootEnvVar, kAndroidRootDefaultPath, GetRootContainingLibartbase);
111   *error_msg = "GetAndroidRootSafe unsupported for Windows.";
112   return "";
113 #else
114   // Prefer ANDROID_ROOT if it's set.
115   const char* android_root_from_env = getenv(kAndroidRootEnvVar);
116   if (android_root_from_env != nullptr) {
117     if (!OS::DirectoryExists(android_root_from_env)) {
118       *error_msg =
119           StringPrintf("Failed to find %s directory %s", kAndroidRootEnvVar, android_root_from_env);
120       return "";
121     }
122     return android_root_from_env;
123   }
124 
125   // On host, libartbase is currently installed in "$ANDROID_ROOT/lib"
126   // (e.g. something like "$ANDROID_BUILD_TOP/out/host/linux-x86/lib". Use this
127   // information to infer the location of the Android Root (on host only).
128   //
129   // Note that this could change in the future, if we decided to install ART
130   // artifacts in a different location, e.g. within an "ART APEX" directory.
131   if (!kIsTargetBuild) {
132     std::string root_containing_libartbase = GetRootContainingLibartbase();
133     if (!root_containing_libartbase.empty()) {
134       return root_containing_libartbase;
135     }
136   }
137 
138   // Try the default path.
139   if (!OS::DirectoryExists(kAndroidRootDefaultPath)) {
140     *error_msg =
141         StringPrintf("Failed to find default Android Root directory %s", kAndroidRootDefaultPath);
142     return "";
143   }
144   return kAndroidRootDefaultPath;
145 #endif
146 }
147 
GetAndroidRoot()148 std::string GetAndroidRoot() {
149   std::string error_msg;
150   std::string ret = GetAndroidRootSafe(&error_msg);
151   if (ret.empty()) {
152     LOG(FATAL) << error_msg;
153     UNREACHABLE();
154   }
155   return ret;
156 }
157 
158 
GetAndroidDirSafe(const char * env_var,const char * default_dir,bool must_exist,std::string * error_msg)159 static const char* GetAndroidDirSafe(const char* env_var,
160                                      const char* default_dir,
161                                      bool must_exist,
162                                      std::string* error_msg) {
163   const char* android_dir = getenv(env_var);
164   if (android_dir == nullptr) {
165     if (!must_exist || OS::DirectoryExists(default_dir)) {
166       android_dir = default_dir;
167     } else {
168       *error_msg = StringPrintf("%s not set and %s does not exist", env_var, default_dir);
169       return nullptr;
170     }
171   }
172   if (must_exist && !OS::DirectoryExists(android_dir)) {
173     *error_msg = StringPrintf("Failed to find directory %s", android_dir);
174     return nullptr;
175   }
176   return android_dir;
177 }
178 
GetAndroidDir(const char * env_var,const char * default_dir,bool must_exist=true)179 static const char* GetAndroidDir(const char* env_var,
180                                  const char* default_dir,
181                                  bool must_exist = true) {
182   std::string error_msg;
183   const char* dir = GetAndroidDirSafe(env_var, default_dir, must_exist, &error_msg);
184   if (dir != nullptr) {
185     return dir;
186   } else {
187     LOG(FATAL) << error_msg;
188     UNREACHABLE();
189   }
190 }
191 
GetArtRootSafe(bool must_exist,std::string * error_msg)192 static std::string GetArtRootSafe(bool must_exist, /*out*/ std::string* error_msg) {
193 #ifdef _WIN32
194   UNUSED(kAndroidArtRootEnvVar, kAndroidArtApexDefaultPath, GetRootContainingLibartbase);
195   UNUSED(must_exist);
196   *error_msg = "GetArtRootSafe unsupported for Windows.";
197   return "";
198 #else
199   // Prefer ANDROID_ART_ROOT if it's set.
200   const char* android_art_root_from_env = getenv(kAndroidArtRootEnvVar);
201   if (android_art_root_from_env != nullptr) {
202     if (must_exist && !OS::DirectoryExists(android_art_root_from_env)) {
203       *error_msg = StringPrintf("Failed to find %s directory %s",
204                                 kAndroidArtRootEnvVar,
205                                 android_art_root_from_env);
206       return "";
207     }
208     return android_art_root_from_env;
209   }
210 
211   // On target, libartbase is normally installed in
212   // "$ANDROID_ART_ROOT/lib(64)" (e.g. something like
213   // "/apex/com.android.art/lib(64)". Use this information to infer the
214   // location of the ART Root (on target only).
215   if (kIsTargetBuild) {
216     // *However*, a copy of libartbase may still be installed outside the
217     // ART Root on some occasions, as ART target gtests install their binaries
218     // and their dependencies under the Android Root, i.e. "/system" (see
219     // b/129534335). For that reason, we cannot reliably use
220     // `GetRootContainingLibartbase` to find the ART Root. (Note that this is
221     // not really a problem in practice, as Android Q devices define
222     // ANDROID_ART_ROOT in their default environment, and will instead use
223     // the logic above anyway.)
224     //
225     // TODO(b/129534335): Re-enable this logic when the only instance of
226     // libartbase on target is the one from the ART APEX.
227     if ((false)) {
228       std::string root_containing_libartbase = GetRootContainingLibartbase();
229       if (!root_containing_libartbase.empty()) {
230         return root_containing_libartbase;
231       }
232     }
233   }
234 
235   // Try the default path.
236   if (must_exist && !OS::DirectoryExists(kAndroidArtApexDefaultPath)) {
237     *error_msg = StringPrintf("Failed to find default ART root directory %s",
238                               kAndroidArtApexDefaultPath);
239     return "";
240   }
241   return kAndroidArtApexDefaultPath;
242 #endif
243 }
244 
GetArtRootSafe(std::string * error_msg)245 std::string GetArtRootSafe(std::string* error_msg) {
246   return GetArtRootSafe(/* must_exist= */ true, error_msg);
247 }
248 
GetArtRoot()249 std::string GetArtRoot() {
250   std::string error_msg;
251   std::string ret = GetArtRootSafe(&error_msg);
252   if (ret.empty()) {
253     LOG(FATAL) << error_msg;
254     UNREACHABLE();
255   }
256   return ret;
257 }
258 
GetArtBinDir()259 std::string GetArtBinDir() {
260   // Environment variable `ANDROID_ART_ROOT` is defined as
261   // `$ANDROID_HOST_OUT/com.android.art` on host. However, host ART binaries are
262   // still installed in `$ANDROID_HOST_OUT/bin` (i.e. outside the ART Root). The
263   // situation is cleaner on target, where `ANDROID_ART_ROOT` is
264   // `$ANDROID_ROOT/apex/com.android.art` and ART binaries are installed in
265   // `$ANDROID_ROOT/apex/com.android.art/bin`.
266   std::string android_art_root = kIsTargetBuild ? GetArtRoot() : GetAndroidRoot();
267   return android_art_root + "/bin";
268 }
269 
GetAndroidDataSafe(std::string * error_msg)270 std::string GetAndroidDataSafe(std::string* error_msg) {
271   const char* android_dir = GetAndroidDirSafe(kAndroidDataEnvVar,
272                                               kAndroidDataDefaultPath,
273                                               /* must_exist= */ true,
274                                               error_msg);
275   return (android_dir != nullptr) ? android_dir : "";
276 }
277 
GetAndroidData()278 std::string GetAndroidData() {
279   return GetAndroidDir(kAndroidDataEnvVar, kAndroidDataDefaultPath);
280 }
281 
GetArtApexData()282 std::string GetArtApexData() {
283   return GetAndroidDir(kArtApexDataEnvVar, kArtApexDataDefaultPath, /*must_exist=*/false);
284 }
285 
GetFirstBootClasspathExtensionJar(const std::string & android_root)286 static std::string GetFirstBootClasspathExtensionJar(const std::string& android_root) {
287   DCHECK(kIsTargetBuild);
288 
289   // This method finds the first non-APEX DEX file in the boot class path as defined by the
290   // DEX2OATBOOTCLASSPATH environment variable. This corresponds to the first boot classpath
291   // extension (see IMAGE SECTION documentation in image.h). When on-device signing is used the
292   // boot class extensions are compiled together as a single image with a name derived from the
293   // first extension. This first boot classpath extension is usually
294   // '/system/framework/framework.jar'.
295   //
296   // DEX2OATBOOTCLASSPATH is generated at build time by in the init.environ.rc.in:
297   //   ${ANDROID_BUILD_TOP}/system/core/rootdir/Android.mk
298   // and initialized on Android by init in init.environ.rc:
299   //   ${ANDROID_BUILD_TOP}/system/core/rootdir/init.environ.rc.in.
300   // It is used by installd too.
301   const char* bcp = getenv("DEX2OATBOOTCLASSPATH");
302   const std::string kDefaultBcpExtensionJar = android_root + "/framework/framework.jar";
303   if (bcp != nullptr) {
304     for (std::string_view component : SplitString(bcp, ':')) {
305       if (component.empty()) {
306         continue;
307       }
308       if (!LocationIsOnApex(component)) {
309         return std::string{component};
310       }
311     }
312   }
313   return kDefaultBcpExtensionJar;
314 }
315 
GetDefaultBootImageLocation(const std::string & android_root,bool deny_art_apex_data_files)316 std::string GetDefaultBootImageLocation(const std::string& android_root,
317                                         bool deny_art_apex_data_files) {
318   constexpr static const char* kJavalibBootArt = "javalib/boot.art";
319   constexpr static const char* kEtcBootImageProf = "etc/boot-image.prof";
320 
321   // Boot image consists of two parts:
322   //  - the primary boot image in the ART APEX (contains the Core Libraries)
323   //  - the boot image extensions (contains framework libraries) on the system partition, or
324   //    in the ART APEX data directory, if an update for the ART module has been been installed.
325   if (kIsTargetBuild && !deny_art_apex_data_files) {
326     // If the ART APEX has been updated, the compiled boot image extension will be in the ART APEX
327     // data directory (assuming there is space and we trust the artifacts there). Otherwise, for a factory installed ART APEX it is
328     // under $ANDROID_ROOT/framework/.
329     const std::string first_extension_jar{GetFirstBootClasspathExtensionJar(android_root)};
330     const std::string boot_extension_image = GetApexDataBootImage(first_extension_jar);
331     const std::string boot_extension_filename =
332         GetSystemImageFilename(boot_extension_image.c_str(), kRuntimeISA);
333     if (OS::FileExists(boot_extension_filename.c_str(), /*check_file_type=*/true)) {
334       return StringPrintf("%s/%s:%s!%s/%s",
335                           kAndroidArtApexDefaultPath,
336                           kJavalibBootArt,
337                           boot_extension_image.c_str(),
338                           android_root.c_str(),
339                           kEtcBootImageProf);
340     } else if (errno == EACCES) {
341       // Additional warning for potential SELinux misconfiguration.
342       PLOG(ERROR) << "Default boot image check failed, could not stat: " << boot_extension_image;
343     }
344   }
345   return StringPrintf("%s/%s:%s/framework/boot-framework.art!%s/%s",
346                       kAndroidArtApexDefaultPath,
347                       kJavalibBootArt,
348                       android_root.c_str(),
349                       android_root.c_str(),
350                       kEtcBootImageProf);
351 }
352 
GetDefaultBootImageLocation(std::string * error_msg)353 std::string GetDefaultBootImageLocation(std::string* error_msg) {
354   std::string android_root = GetAndroidRootSafe(error_msg);
355   if (android_root.empty()) {
356     return "";
357   }
358   return GetDefaultBootImageLocation(android_root, /*deny_art_apex_data_files=*/false);
359 }
360 
GetDalvikCacheDirectory(std::string_view root_directory,std::string_view sub_directory={})361 static std::string GetDalvikCacheDirectory(std::string_view root_directory,
362                                            std::string_view sub_directory = {}) {
363   static constexpr std::string_view kDalvikCache = "dalvik-cache";
364   std::stringstream oss;
365   oss << root_directory << '/' << kDalvikCache;
366   if (!sub_directory.empty()) {
367     oss << '/' << sub_directory;
368   }
369   return oss.str();
370 }
371 
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)372 void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
373                     bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
374 #ifdef _WIN32
375   UNUSED(subdir);
376   UNUSED(create_if_absent);
377   UNUSED(dalvik_cache);
378   UNUSED(have_android_data);
379   UNUSED(dalvik_cache_exists);
380   UNUSED(is_global_cache);
381   LOG(FATAL) << "GetDalvikCache unsupported on Windows.";
382 #else
383   CHECK(subdir != nullptr);
384   std::string unused_error_msg;
385   std::string android_data = GetAndroidDataSafe(&unused_error_msg);
386   if (android_data.empty()) {
387     *have_android_data = false;
388     *dalvik_cache_exists = false;
389     *is_global_cache = false;
390     return;
391   } else {
392     *have_android_data = true;
393   }
394   const std::string dalvik_cache_root = GetDalvikCacheDirectory(android_data);
395   *dalvik_cache = dalvik_cache_root + '/' + subdir;
396   *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
397   *is_global_cache = (android_data == kAndroidDataDefaultPath);
398   if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
399     // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
400     *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
401                             (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
402   }
403 #endif
404 }
405 
GetDalvikCacheFilename(const char * location,const char * cache_location,std::string * filename,std::string * error_msg)406 bool GetDalvikCacheFilename(const char* location, const char* cache_location,
407                             std::string* filename, std::string* error_msg) {
408   if (location[0] != '/') {
409     *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
410     return false;
411   }
412   std::string cache_file(&location[1]);  // skip leading slash
413   if (!android::base::EndsWith(location, ".dex") &&
414       !android::base::EndsWith(location, ".art") &&
415       !android::base::EndsWith(location, ".oat")) {
416     cache_file += "/";
417     cache_file += kClassesDex;
418   }
419   std::replace(cache_file.begin(), cache_file.end(), '/', '@');
420   *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
421   return true;
422 }
423 
GetApexDataDalvikCacheDirectory(InstructionSet isa)424 static std::string GetApexDataDalvikCacheDirectory(InstructionSet isa) {
425   if (isa != InstructionSet::kNone) {
426     return GetDalvikCacheDirectory(GetArtApexData(), GetInstructionSetString(isa));
427   }
428   return GetDalvikCacheDirectory(GetArtApexData());
429 }
430 
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,bool encode_location,std::string_view file_extension)431 static std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
432                                                   InstructionSet isa,
433                                                   bool encode_location,
434                                                   std::string_view file_extension) {
435   if (LocationIsOnApex(dex_location)) {
436     return {};
437   }
438   std::string apex_data_dalvik_cache = GetApexDataDalvikCacheDirectory(isa);
439   if (encode_location) {
440     // Arguments: "/system/framework/xyz.jar", "arm", true, "odex"
441     // Result:
442     // "/data/misc/apexdata/com.android.art/dalvik-cache/arm/system@framework@xyz.jar@classes.odex"
443     std::string result, unused_error_msg;
444     GetDalvikCacheFilename(std::string{dex_location}.c_str(),
445                            apex_data_dalvik_cache.c_str(),
446                            &result,
447                            &unused_error_msg);
448     return ReplaceFileExtension(result, file_extension);
449   } else {
450     // Arguments: "/system/framework/xyz.jar", "x86_64", false, "art"
451     // Results: "/data/misc/apexdata/com.android.art/dalvik-cache/x86_64/boot-xyz.jar@classes.art"
452     std::string basename = android::base::Basename(std::string{dex_location});
453     return apex_data_dalvik_cache + "/boot-" + ReplaceFileExtension(basename, file_extension);
454   }
455 }
456 
GetApexDataOatFilename(std::string_view location,InstructionSet isa)457 std::string GetApexDataOatFilename(std::string_view location, InstructionSet isa) {
458   return GetApexDataDalvikCacheFilename(location, isa, /*encode_location=*/false, "oat");
459 }
460 
GetApexDataOdexFilename(std::string_view location,InstructionSet isa)461 std::string GetApexDataOdexFilename(std::string_view location, InstructionSet isa) {
462   return GetApexDataDalvikCacheFilename(location, isa, /*encode_location=*/true, "odex");
463 }
464 
GetApexDataBootImage(std::string_view dex_location)465 std::string GetApexDataBootImage(std::string_view dex_location) {
466   return GetApexDataDalvikCacheFilename(dex_location,
467                                         InstructionSet::kNone,
468                                         /*encode_location=*/false,
469                                         kArtImageExtension);
470 }
471 
GetApexDataImage(std::string_view dex_location)472 std::string GetApexDataImage(std::string_view dex_location) {
473   return GetApexDataDalvikCacheFilename(dex_location,
474                                         InstructionSet::kNone,
475                                         /*encode_location=*/true,
476                                         kArtImageExtension);
477 }
478 
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,std::string_view file_extension)479 std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
480                                            InstructionSet isa,
481                                            std::string_view file_extension) {
482   return GetApexDataDalvikCacheFilename(
483       dex_location, isa, /*encode_location=*/true, file_extension);
484 }
485 
GetVdexFilename(const std::string & oat_location)486 std::string GetVdexFilename(const std::string& oat_location) {
487   return ReplaceFileExtension(oat_location, "vdex");
488 }
489 
InsertIsaDirectory(const InstructionSet isa,std::string * filename)490 static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
491   // in = /foo/bar/baz
492   // out = /foo/bar/<isa>/baz
493   size_t pos = filename->rfind('/');
494   CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
495   filename->insert(pos, "/", 1);
496   filename->insert(pos + 1, GetInstructionSetString(isa));
497 }
498 
GetSystemImageFilename(const char * location,const InstructionSet isa)499 std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
500   // location = /system/framework/boot.art
501   // filename = /system/framework/<isa>/boot.art
502   std::string filename(location);
503   InsertIsaDirectory(isa, &filename);
504   return filename;
505 }
506 
ReplaceFileExtension(std::string_view filename,std::string_view new_extension)507 std::string ReplaceFileExtension(std::string_view filename, std::string_view new_extension) {
508   const size_t last_ext = filename.find_last_of("./");
509   std::string result;
510   if (last_ext == std::string::npos || filename[last_ext] != '.') {
511     result.reserve(filename.size() + 1 + new_extension.size());
512     result.append(filename).append(".").append(new_extension);
513   } else {
514     result.reserve(last_ext + 1 + new_extension.size());
515     result.append(filename.substr(0, last_ext + 1)).append(new_extension);
516   }
517   return result;
518 }
519 
LocationIsOnArtApexData(std::string_view location)520 bool LocationIsOnArtApexData(std::string_view location) {
521   const std::string art_apex_data = GetArtApexData();
522   return android::base::StartsWith(location, art_apex_data);
523 }
524 
LocationIsOnArtModule(std::string_view full_path)525 bool LocationIsOnArtModule(std::string_view full_path) {
526   std::string unused_error_msg;
527   std::string module_path = GetArtRootSafe(/* must_exist= */ kIsTargetBuild, &unused_error_msg);
528   if (module_path.empty()) {
529     return false;
530   }
531   return android::base::StartsWith(full_path, module_path);
532 }
533 
StartsWithSlash(const char * str)534 static bool StartsWithSlash(const char* str) {
535   DCHECK(str != nullptr);
536   return str[0] == '/';
537 }
538 
EndsWithSlash(const char * str)539 static bool EndsWithSlash(const char* str) {
540   DCHECK(str != nullptr);
541   size_t len = strlen(str);
542   return len > 0 && str[len - 1] == '/';
543 }
544 
545 // Returns true if `full_path` is located in folder either provided with `env_var`
546 // or in `default_path` otherwise. The caller may optionally provide a `subdir`
547 // which will be appended to the tested prefix.
548 // `default_path` and the value of environment variable `env_var`
549 // are expected to begin with a slash and not end with one. If this ever changes,
550 // 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)551 static bool IsLocationOn(std::string_view full_path,
552                          const char* env_var,
553                          const char* default_path,
554                          const char* subdir = nullptr) {
555   std::string unused_error_msg;
556   const char* path = GetAndroidDirSafe(env_var,
557                                        default_path,
558                                        /* must_exist= */ kIsTargetBuild,
559                                        &unused_error_msg);
560   if (path == nullptr) {
561     return false;
562   }
563 
564   // Build the path which we will check is a prefix of `full_path`. The prefix must
565   // end with a slash, so that "/foo/bar" does not match "/foo/barz".
566   DCHECK(StartsWithSlash(path)) << path;
567   std::string path_prefix(path);
568   if (!EndsWithSlash(path_prefix.c_str())) {
569     path_prefix.append("/");
570   }
571   if (subdir != nullptr) {
572     // If `subdir` is provided, we assume it is provided without a starting slash
573     // but ending with one, e.g. "sub/dir/". `path_prefix` ends with a slash at
574     // this point, so we simply append `subdir`.
575     DCHECK(!StartsWithSlash(subdir) && EndsWithSlash(subdir)) << subdir;
576     path_prefix.append(subdir);
577   }
578 
579   return android::base::StartsWith(full_path, path_prefix);
580 }
581 
LocationIsOnSystemFramework(std::string_view full_path)582 bool LocationIsOnSystemFramework(std::string_view full_path) {
583   return IsLocationOn(full_path,
584                       kAndroidRootEnvVar,
585                       kAndroidRootDefaultPath,
586                       /* subdir= */ "framework/");
587 }
588 
LocationIsOnSystemExtFramework(std::string_view full_path)589 bool LocationIsOnSystemExtFramework(std::string_view full_path) {
590   return IsLocationOn(full_path,
591                       kAndroidSystemExtRootEnvVar,
592                       kAndroidSystemExtRootDefaultPath,
593                       /* subdir= */ "framework/") ||
594       // When the 'system_ext' partition is not present, builds will create
595       // '/system/system_ext' instead.
596       IsLocationOn(full_path,
597                    kAndroidRootEnvVar,
598                    kAndroidRootDefaultPath,
599                    /* subdir= */ "system_ext/framework/");
600 }
601 
LocationIsOnConscryptModule(std::string_view full_path)602 bool LocationIsOnConscryptModule(std::string_view full_path) {
603   return IsLocationOn(
604       full_path, kAndroidConscryptRootEnvVar, kAndroidConscryptApexDefaultPath);
605 }
606 
LocationIsOnI18nModule(std::string_view full_path)607 bool LocationIsOnI18nModule(std::string_view full_path) {
608   return IsLocationOn(
609       full_path, kAndroidI18nRootEnvVar, kAndroidI18nApexDefaultPath);
610 }
611 
LocationIsOnApex(std::string_view full_path)612 bool LocationIsOnApex(std::string_view full_path) {
613   return android::base::StartsWith(full_path, kApexDefaultPath);
614 }
615 
LocationIsOnSystem(const std::string & location)616 bool LocationIsOnSystem(const std::string& location) {
617 #ifdef _WIN32
618   UNUSED(location);
619   LOG(FATAL) << "LocationIsOnSystem is unsupported on Windows.";
620   return false;
621 #else
622   UniqueCPtr<const char[]> full_path(realpath(location.c_str(), nullptr));
623   return full_path != nullptr &&
624       android::base::StartsWith(full_path.get(), GetAndroidRoot().c_str());
625 #endif
626 }
627 
LocationIsTrusted(const std::string & location,bool trust_art_apex_data_files)628 bool LocationIsTrusted(const std::string& location, bool trust_art_apex_data_files) {
629   if (LocationIsOnSystem(location)) {
630     return true;
631   }
632   return LocationIsOnArtApexData(location) & trust_art_apex_data_files;
633 }
634 
ArtModuleRootDistinctFromAndroidRoot()635 bool ArtModuleRootDistinctFromAndroidRoot() {
636   std::string error_msg;
637   const char* android_root = GetAndroidDirSafe(kAndroidRootEnvVar,
638                                                kAndroidRootDefaultPath,
639                                                /* must_exist= */ kIsTargetBuild,
640                                                &error_msg);
641   const char* art_root = GetAndroidDirSafe(kAndroidArtRootEnvVar,
642                                            kAndroidArtApexDefaultPath,
643                                            /* must_exist= */ kIsTargetBuild,
644                                            &error_msg);
645   return (android_root != nullptr)
646       && (art_root != nullptr)
647       && (std::string_view(android_root) != std::string_view(art_root));
648 }
649 
DupCloexec(int fd)650 int DupCloexec(int fd) {
651 #if defined(__linux__)
652   return fcntl(fd, F_DUPFD_CLOEXEC, 0);
653 #else
654   return dup(fd);
655 #endif
656 }
657 
658 }  // namespace art
659