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/logging.h"
46 #include "android-base/stringprintf.h"
47 #include "android-base/strings.h"
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
58 #include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
59 #endif
60
61 #if defined(__linux__)
62 #include <linux/unistd.h>
63 #endif
64
65 namespace art {
66
67 using android::base::StringPrintf;
68
69 static constexpr const char* kClassesDex = "classes.dex";
70 static constexpr const char* kAndroidRootEnvVar = "ANDROID_ROOT";
71 static constexpr const char* kAndroidRootDefaultPath = "/system";
72 static constexpr const char* kAndroidSystemExtRootEnvVar = "ANDROID_SYSTEM_EXT";
73 static constexpr const char* kAndroidSystemExtRootDefaultPath = "/system_ext";
74 static constexpr const char* kAndroidDataEnvVar = "ANDROID_DATA";
75 static constexpr const char* kAndroidDataDefaultPath = "/data";
76 static constexpr const char* kAndroidArtRootEnvVar = "ANDROID_ART_ROOT";
77 static constexpr const char* kAndroidConscryptRootEnvVar = "ANDROID_CONSCRYPT_ROOT";
78 static constexpr const char* kAndroidI18nRootEnvVar = "ANDROID_I18N_ROOT";
79 static constexpr const char* kApexDefaultPath = "/apex/";
80 static constexpr const char* kArtApexDataEnvVar = "ART_APEX_DATA";
81
82 // Get the "root" directory containing the "lib" directory where this instance
83 // of the libartbase library (which contains `GetRootContainingLibartbase`) is
84 // located:
85 // - on host this "root" is normally the Android Root (e.g. something like
86 // "$ANDROID_BUILD_TOP/out/host/linux-x86/");
87 // - on target this "root" is normally the ART Root ("/apex/com.android.art").
88 // Return the empty string if that directory cannot be found or if this code is
89 // run on Windows or macOS.
GetRootContainingLibartbase()90 static std::string GetRootContainingLibartbase() {
91 #if !defined(_WIN32) && !defined(__APPLE__)
92 // Check where libartbase is from, and derive from there.
93 Dl_info info;
94 if (dladdr(reinterpret_cast<const void*>(&GetRootContainingLibartbase), /* out */ &info) != 0) {
95 // Make a duplicate of the fname so dirname can modify it.
96 UniqueCPtr<char> fname(strdup(info.dli_fname));
97
98 char* dir1 = dirname(fname.get()); // This is the lib directory.
99 char* dir2 = dirname(dir1); // This is the "root" directory.
100 if (OS::DirectoryExists(dir2)) {
101 std::string tmp = dir2; // Make a copy here so that fname can be released.
102 return tmp;
103 }
104 }
105 #endif
106 return "";
107 }
108
GetAndroidRootSafe(std::string * error_msg)109 std::string GetAndroidRootSafe(std::string* error_msg) {
110 #ifdef _WIN32
111 UNUSED(kAndroidRootEnvVar, kAndroidRootDefaultPath, GetRootContainingLibartbase);
112 *error_msg = "GetAndroidRootSafe unsupported for Windows.";
113 return "";
114 #else
115 // Prefer ANDROID_ROOT if it's set.
116 const char* android_root_from_env = getenv(kAndroidRootEnvVar);
117 if (android_root_from_env != nullptr) {
118 if (!OS::DirectoryExists(android_root_from_env)) {
119 *error_msg =
120 StringPrintf("Failed to find %s directory %s", kAndroidRootEnvVar, android_root_from_env);
121 return "";
122 }
123 return android_root_from_env;
124 }
125
126 // On host, libartbase is currently installed in "$ANDROID_ROOT/lib"
127 // (e.g. something like "$ANDROID_BUILD_TOP/out/host/linux-x86/lib". Use this
128 // information to infer the location of the Android Root (on host only).
129 //
130 // Note that this could change in the future, if we decided to install ART
131 // artifacts in a different location, e.g. within an "ART APEX" directory.
132 if (!kIsTargetBuild) {
133 std::string root_containing_libartbase = GetRootContainingLibartbase();
134 if (!root_containing_libartbase.empty()) {
135 return root_containing_libartbase;
136 }
137 }
138
139 // Try the default path.
140 if (!OS::DirectoryExists(kAndroidRootDefaultPath)) {
141 *error_msg =
142 StringPrintf("Failed to find default Android Root directory %s", kAndroidRootDefaultPath);
143 return "";
144 }
145 return kAndroidRootDefaultPath;
146 #endif
147 }
148
GetAndroidRoot()149 std::string GetAndroidRoot() {
150 std::string error_msg;
151 std::string ret = GetAndroidRootSafe(&error_msg);
152 if (ret.empty()) {
153 LOG(FATAL) << error_msg;
154 UNREACHABLE();
155 }
156 return ret;
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(
204 "Failed to find %s directory %s", kAndroidArtRootEnvVar, android_art_root_from_env);
205 return "";
206 }
207 return android_art_root_from_env;
208 }
209
210 // On target, libartbase is normally installed in
211 // "$ANDROID_ART_ROOT/lib(64)" (e.g. something like
212 // "/apex/com.android.art/lib(64)". Use this information to infer the
213 // location of the ART Root (on target only).
214 if (kIsTargetBuild) {
215 // *However*, a copy of libartbase may still be installed outside the
216 // ART Root on some occasions, as ART target gtests install their binaries
217 // and their dependencies under the Android Root, i.e. "/system" (see
218 // b/129534335). For that reason, we cannot reliably use
219 // `GetRootContainingLibartbase` to find the ART Root. (Note that this is
220 // not really a problem in practice, as Android Q devices define
221 // ANDROID_ART_ROOT in their default environment, and will instead use
222 // the logic above anyway.)
223 //
224 // TODO(b/129534335): Re-enable this logic when the only instance of
225 // libartbase on target is the one from the ART APEX.
226 if ((false)) {
227 std::string root_containing_libartbase = GetRootContainingLibartbase();
228 if (!root_containing_libartbase.empty()) {
229 return root_containing_libartbase;
230 }
231 }
232 }
233
234 // Try the default path.
235 if (must_exist && !OS::DirectoryExists(kAndroidArtApexDefaultPath)) {
236 *error_msg =
237 StringPrintf("Failed to find default ART root directory %s", kAndroidArtApexDefaultPath);
238 return "";
239 }
240 return kAndroidArtApexDefaultPath;
241 #endif
242 }
243
GetArtRootSafe(std::string * error_msg)244 std::string GetArtRootSafe(std::string* error_msg) {
245 return GetArtRootSafe(/* must_exist= */ true, error_msg);
246 }
247
GetArtRoot()248 std::string GetArtRoot() {
249 std::string error_msg;
250 std::string ret = GetArtRootSafe(&error_msg);
251 if (ret.empty()) {
252 LOG(FATAL) << error_msg;
253 UNREACHABLE();
254 }
255 return ret;
256 }
257
GetArtBinDir()258 std::string GetArtBinDir() {
259 // Environment variable `ANDROID_ART_ROOT` is defined as
260 // `$ANDROID_HOST_OUT/com.android.art` on host. However, host ART binaries are
261 // still installed in `$ANDROID_HOST_OUT/bin` (i.e. outside the ART Root). The
262 // situation is cleaner on target, where `ANDROID_ART_ROOT` is
263 // `$ANDROID_ROOT/apex/com.android.art` and ART binaries are installed in
264 // `$ANDROID_ROOT/apex/com.android.art/bin`.
265 std::string android_art_root = kIsTargetBuild ? GetArtRoot() : GetAndroidRoot();
266 return android_art_root + "/bin";
267 }
268
GetAndroidDataSafe(std::string * error_msg)269 std::string GetAndroidDataSafe(std::string* error_msg) {
270 const char* android_dir = GetAndroidDirSafe(kAndroidDataEnvVar,
271 kAndroidDataDefaultPath,
272 /* must_exist= */ true,
273 error_msg);
274 return (android_dir != nullptr) ? android_dir : "";
275 }
276
GetAndroidData()277 std::string GetAndroidData() { return GetAndroidDir(kAndroidDataEnvVar, kAndroidDataDefaultPath); }
278
GetArtApexData()279 std::string GetArtApexData() {
280 return GetAndroidDir(kArtApexDataEnvVar, kArtApexDataDefaultPath, /*must_exist=*/false);
281 }
282
GetPrebuiltPrimaryBootImageDir(const std::string & android_root)283 static std::string GetPrebuiltPrimaryBootImageDir(const std::string& android_root) {
284 return StringPrintf("%s/framework", android_root.c_str());
285 }
286
GetPrebuiltPrimaryBootImageDir()287 std::string GetPrebuiltPrimaryBootImageDir() {
288 std::string android_root = GetAndroidRoot();
289 if (android_root.empty()) {
290 return "";
291 }
292 return GetPrebuiltPrimaryBootImageDir(android_root);
293 }
294
GetDefaultBootImageLocation(const std::string & android_root,bool deny_art_apex_data_files)295 std::string GetDefaultBootImageLocation(const std::string& android_root,
296 bool deny_art_apex_data_files) {
297 constexpr static const char* kEtcBootImageProf = "etc/boot-image.prof";
298 constexpr static const char* kBootImageStem = "boot";
299 constexpr static const char* kMinimalBootImageStem = "boot_minimal";
300
301 // If an update for the ART module has been been installed, a single boot image for the entire
302 // bootclasspath is in the ART APEX data directory.
303 if (kIsTargetBuild && !deny_art_apex_data_files) {
304 const std::string boot_image =
305 GetApexDataDalvikCacheDirectory(InstructionSet::kNone) + "/" + kBootImageStem + ".art";
306 const std::string boot_image_filename = GetSystemImageFilename(boot_image.c_str(), kRuntimeISA);
307 if (OS::FileExists(boot_image_filename.c_str(), /*check_file_type=*/true)) {
308 // Typically "/data/misc/apexdata/com.android.art/dalvik-cache/boot.art!/apex/com.android.art
309 // /etc/boot-image.prof!/system/etc/boot-image.prof".
310 return StringPrintf("%s!%s/%s!%s/%s",
311 boot_image.c_str(),
312 kAndroidArtApexDefaultPath,
313 kEtcBootImageProf,
314 android_root.c_str(),
315 kEtcBootImageProf);
316 } else if (errno == EACCES) {
317 // Additional warning for potential SELinux misconfiguration.
318 PLOG(ERROR) << "Default boot image check failed, could not stat: " << boot_image_filename;
319 }
320
321 // odrefresh can generate a minimal boot image, which only includes code from BCP jars in the
322 // ART module, when it fails to generate a single boot image for the entire bootclasspath (i.e.,
323 // full boot image). Use it if it exists.
324 const std::string minimal_boot_image = GetApexDataDalvikCacheDirectory(InstructionSet::kNone) +
325 "/" + kMinimalBootImageStem + ".art";
326 const std::string minimal_boot_image_filename =
327 GetSystemImageFilename(minimal_boot_image.c_str(), kRuntimeISA);
328 if (OS::FileExists(minimal_boot_image_filename.c_str(), /*check_file_type=*/true)) {
329 // Typically "/data/misc/apexdata/com.android.art/dalvik-cache/boot_minimal.art!/apex
330 // /com.android.art/etc/boot-image.prof:/nonx/boot_minimal-framework.art!/system/etc
331 // /boot-image.prof".
332 return StringPrintf("%s!%s/%s:/nonx/%s-framework.art!%s/%s",
333 minimal_boot_image.c_str(),
334 kAndroidArtApexDefaultPath,
335 kEtcBootImageProf,
336 kMinimalBootImageStem,
337 android_root.c_str(),
338 kEtcBootImageProf);
339 } else if (errno == EACCES) {
340 // Additional warning for potential SELinux misconfiguration.
341 PLOG(ERROR) << "Minimal boot image check failed, could not stat: " << boot_image_filename;
342 }
343 }
344 // Boot image consists of two parts:
345 // - the primary boot image (contains the Core Libraries)
346 // - the boot image extensions (contains framework libraries)
347 // Typically "/apex/com.android.art/javalib/boot.art!/apex/com.android.art/etc/boot-image.prof:
348 // /system/framework/boot-framework.art!/system/etc/boot-image.prof".
349 return StringPrintf("%s/%s.art!%s/%s:%s/framework/%s-framework.art!%s/%s",
350 GetPrebuiltPrimaryBootImageDir(android_root).c_str(),
351 kBootImageStem,
352 kAndroidArtApexDefaultPath,
353 kEtcBootImageProf,
354 android_root.c_str(),
355 kBootImageStem,
356 android_root.c_str(),
357 kEtcBootImageProf);
358 }
359
GetDefaultBootImageLocation(std::string * error_msg)360 std::string GetDefaultBootImageLocation(std::string* error_msg) {
361 std::string android_root = GetAndroidRootSafe(error_msg);
362 if (android_root.empty()) {
363 return "";
364 }
365 return GetDefaultBootImageLocation(android_root, /*deny_art_apex_data_files=*/false);
366 }
367
368 static /*constinit*/ std::string_view dalvik_cache_sub_dir = "dalvik-cache";
369
OverrideDalvikCacheSubDirectory(std::string sub_dir)370 void OverrideDalvikCacheSubDirectory(std::string sub_dir) {
371 static std::string overridden_dalvik_cache_sub_dir;
372 overridden_dalvik_cache_sub_dir = std::move(sub_dir);
373 dalvik_cache_sub_dir = overridden_dalvik_cache_sub_dir;
374 }
375
GetDalvikCacheDirectory(std::string_view root_directory,std::string_view sub_directory={})376 static std::string GetDalvikCacheDirectory(std::string_view root_directory,
377 std::string_view sub_directory = {}) {
378 std::stringstream oss;
379 oss << root_directory << '/' << dalvik_cache_sub_dir;
380 if (!sub_directory.empty()) {
381 oss << '/' << sub_directory;
382 }
383 return oss.str();
384 }
385
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)386 void GetDalvikCache(const char* subdir,
387 const bool create_if_absent,
388 std::string* dalvik_cache,
389 bool* have_android_data,
390 bool* dalvik_cache_exists,
391 bool* is_global_cache) {
392 #ifdef _WIN32
393 UNUSED(subdir);
394 UNUSED(create_if_absent);
395 UNUSED(dalvik_cache);
396 UNUSED(have_android_data);
397 UNUSED(dalvik_cache_exists);
398 UNUSED(is_global_cache);
399 LOG(FATAL) << "GetDalvikCache unsupported on Windows.";
400 #else
401 CHECK(subdir != nullptr);
402 std::string unused_error_msg;
403 std::string android_data = GetAndroidDataSafe(&unused_error_msg);
404 if (android_data.empty()) {
405 *have_android_data = false;
406 *dalvik_cache_exists = false;
407 *is_global_cache = false;
408 return;
409 } else {
410 *have_android_data = true;
411 }
412 const std::string dalvik_cache_root = GetDalvikCacheDirectory(android_data);
413 *dalvik_cache = dalvik_cache_root + '/' + subdir;
414 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
415 *is_global_cache = (android_data == kAndroidDataDefaultPath);
416 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
417 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
418 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
419 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
420 }
421 #endif
422 }
423
424 // Returns a path formed by encoding the dex location into the filename. The path returned will be
425 // rooted at `cache_location`.
GetLocationEncodedFilename(const char * location,const char * cache_location,std::string * filename,std::string * error_msg)426 static bool GetLocationEncodedFilename(const char* location,
427 const char* cache_location,
428 std::string* filename,
429 std::string* error_msg) {
430 if (location[0] != '/') {
431 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
432 return false;
433 }
434 std::string cache_file(&location[1]); // skip leading slash
435 if (!android::base::EndsWith(location, ".dex") && !android::base::EndsWith(location, ".art") &&
436 !android::base::EndsWith(location, ".oat")) {
437 cache_file += "/";
438 cache_file += kClassesDex;
439 }
440 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
441 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
442 return true;
443 }
444
GetDalvikCacheFilename(const char * location,const char * cache_location,std::string * filename,std::string * error_msg)445 bool GetDalvikCacheFilename(const char* location,
446 const char* cache_location,
447 std::string* filename,
448 std::string* error_msg) {
449 return GetLocationEncodedFilename(location, cache_location, filename, error_msg);
450 }
451
GetApexDataDalvikCacheDirectory(InstructionSet isa)452 std::string GetApexDataDalvikCacheDirectory(InstructionSet isa) {
453 if (isa != InstructionSet::kNone) {
454 return GetDalvikCacheDirectory(GetArtApexData(), GetInstructionSetString(isa));
455 }
456 return GetDalvikCacheDirectory(GetArtApexData());
457 }
458
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,bool is_boot_classpath_location,std::string_view file_extension)459 static std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
460 InstructionSet isa,
461 bool is_boot_classpath_location,
462 std::string_view file_extension) {
463 if (LocationIsOnApex(dex_location) && is_boot_classpath_location) {
464 // We don't compile boot images for updatable APEXes.
465 return {};
466 }
467 std::string apex_data_dalvik_cache = GetApexDataDalvikCacheDirectory(isa);
468 if (!is_boot_classpath_location) {
469 // Arguments: "/system/framework/xyz.jar", "arm", true, "odex"
470 // Result:
471 // "/data/misc/apexdata/com.android.art/dalvik-cache/arm/system@framework@xyz.jar@classes.odex"
472 std::string result, unused_error_msg;
473 GetDalvikCacheFilename(std::string{dex_location}.c_str(),
474 apex_data_dalvik_cache.c_str(),
475 &result,
476 &unused_error_msg);
477 return ReplaceFileExtension(result, file_extension);
478 } else {
479 // Arguments: "/system/framework/xyz.jar", "x86_64", false, "art"
480 // Results: "/data/misc/apexdata/com.android.art/dalvik-cache/x86_64/boot-xyz.jar@classes.art"
481 std::string basename = android::base::Basename(std::string{dex_location});
482 return apex_data_dalvik_cache + "/boot-" + ReplaceFileExtension(basename, file_extension);
483 }
484 }
485
GetApexDataOatFilename(std::string_view location,InstructionSet isa)486 std::string GetApexDataOatFilename(std::string_view location, InstructionSet isa) {
487 return GetApexDataDalvikCacheFilename(location, isa, /*is_boot_classpath_location=*/true, "oat");
488 }
489
GetApexDataOdexFilename(std::string_view location,InstructionSet isa)490 std::string GetApexDataOdexFilename(std::string_view location, InstructionSet isa) {
491 return GetApexDataDalvikCacheFilename(
492 location, isa, /*is_boot_classpath_location=*/false, "odex");
493 }
494
GetApexDataBootImage(std::string_view dex_location)495 std::string GetApexDataBootImage(std::string_view dex_location) {
496 return GetApexDataDalvikCacheFilename(dex_location,
497 InstructionSet::kNone,
498 /*is_boot_classpath_location=*/true,
499 kArtImageExtension);
500 }
501
GetApexDataImage(std::string_view dex_location)502 std::string GetApexDataImage(std::string_view dex_location) {
503 return GetApexDataDalvikCacheFilename(dex_location,
504 InstructionSet::kNone,
505 /*is_boot_classpath_location=*/false,
506 kArtImageExtension);
507 }
508
GetApexDataDalvikCacheFilename(std::string_view dex_location,InstructionSet isa,std::string_view file_extension)509 std::string GetApexDataDalvikCacheFilename(std::string_view dex_location,
510 InstructionSet isa,
511 std::string_view file_extension) {
512 return GetApexDataDalvikCacheFilename(
513 dex_location, isa, /*is_boot_classpath_location=*/false, file_extension);
514 }
515
GetVdexFilename(const std::string & oat_location)516 std::string GetVdexFilename(const std::string& oat_location) {
517 return ReplaceFileExtension(oat_location, "vdex");
518 }
519
GetDmFilename(const std::string & dex_location)520 std::string GetDmFilename(const std::string& dex_location) {
521 return ReplaceFileExtension(dex_location, "dm");
522 }
523
GetSystemOdexFilenameForApex(std::string_view location,InstructionSet isa)524 std::string GetSystemOdexFilenameForApex(std::string_view location, InstructionSet isa) {
525 DCHECK(LocationIsOnApex(location));
526 std::string dir = GetAndroidRoot() + "/framework/oat/" + GetInstructionSetString(isa);
527 std::string result, error_msg;
528 bool ret =
529 GetLocationEncodedFilename(std::string{location}.c_str(), dir.c_str(), &result, &error_msg);
530 // This should never fail. The function fails only if the location is not absolute, and a location
531 // on /apex is always absolute.
532 DCHECK(ret) << error_msg;
533 return ReplaceFileExtension(result, "odex");
534 }
535
InsertIsaDirectory(const InstructionSet isa,std::string * filename)536 static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
537 // in = /foo/bar/baz
538 // out = /foo/bar/<isa>/baz
539 size_t pos = filename->rfind('/');
540 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
541 filename->insert(pos, "/", 1);
542 filename->insert(pos + 1, GetInstructionSetString(isa));
543 }
544
GetSystemImageFilename(const char * location,const InstructionSet isa)545 std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
546 // location = /system/framework/boot.art
547 // filename = /system/framework/<isa>/boot.art
548 std::string filename(location);
549 InsertIsaDirectory(isa, &filename);
550 return filename;
551 }
552
ReplaceFileExtension(std::string_view filename,std::string_view new_extension)553 std::string ReplaceFileExtension(std::string_view filename, std::string_view new_extension) {
554 const size_t last_ext = filename.find_last_of("./");
555 std::string result;
556 if (last_ext == std::string::npos || filename[last_ext] != '.') {
557 result.reserve(filename.size() + 1 + new_extension.size());
558 result.append(filename).append(".").append(new_extension);
559 } else {
560 result.reserve(last_ext + 1 + new_extension.size());
561 result.append(filename.substr(0, last_ext + 1)).append(new_extension);
562 }
563 return result;
564 }
565
LocationIsOnArtApexData(std::string_view location)566 bool LocationIsOnArtApexData(std::string_view location) {
567 const std::string art_apex_data = GetArtApexData();
568 return android::base::StartsWith(location, art_apex_data);
569 }
570
LocationIsOnArtModule(std::string_view full_path)571 bool LocationIsOnArtModule(std::string_view full_path) {
572 std::string unused_error_msg;
573 std::string module_path = GetArtRootSafe(/* must_exist= */ kIsTargetBuild, &unused_error_msg);
574 if (module_path.empty()) {
575 return false;
576 }
577 return android::base::StartsWith(full_path, module_path);
578 }
579
StartsWithSlash(const char * str)580 static bool StartsWithSlash(const char* str) {
581 DCHECK(str != nullptr);
582 return str[0] == '/';
583 }
584
EndsWithSlash(const char * str)585 static bool EndsWithSlash(const char* str) {
586 DCHECK(str != nullptr);
587 size_t len = strlen(str);
588 return len > 0 && str[len - 1] == '/';
589 }
590
591 // Returns true if `full_path` is located in folder either provided with `env_var`
592 // or in `default_path` otherwise. The caller may optionally provide a `subdir`
593 // which will be appended to the tested prefix.
594 // `default_path` and the value of environment variable `env_var`
595 // are expected to begin with a slash and not end with one. If this ever changes,
596 // 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)597 static bool IsLocationOn(std::string_view full_path,
598 const char* env_var,
599 const char* default_path,
600 const char* subdir = nullptr) {
601 std::string unused_error_msg;
602 const char* path = GetAndroidDirSafe(env_var,
603 default_path,
604 /* must_exist= */ kIsTargetBuild,
605 &unused_error_msg);
606 if (path == nullptr) {
607 return false;
608 }
609
610 // Build the path which we will check is a prefix of `full_path`. The prefix must
611 // end with a slash, so that "/foo/bar" does not match "/foo/barz".
612 DCHECK(StartsWithSlash(path)) << path;
613 std::string path_prefix(path);
614 if (!EndsWithSlash(path_prefix.c_str())) {
615 path_prefix.append("/");
616 }
617 if (subdir != nullptr) {
618 // If `subdir` is provided, we assume it is provided without a starting slash
619 // but ending with one, e.g. "sub/dir/". `path_prefix` ends with a slash at
620 // this point, so we simply append `subdir`.
621 DCHECK(!StartsWithSlash(subdir) && EndsWithSlash(subdir)) << subdir;
622 path_prefix.append(subdir);
623 }
624
625 return android::base::StartsWith(full_path, path_prefix);
626 }
627
LocationIsOnSystemFramework(std::string_view full_path)628 bool LocationIsOnSystemFramework(std::string_view full_path) {
629 return IsLocationOn(full_path,
630 kAndroidRootEnvVar,
631 kAndroidRootDefaultPath,
632 /* subdir= */ "framework/");
633 }
634
LocationIsOnSystemExtFramework(std::string_view full_path)635 bool LocationIsOnSystemExtFramework(std::string_view full_path) {
636 return IsLocationOn(full_path,
637 kAndroidSystemExtRootEnvVar,
638 kAndroidSystemExtRootDefaultPath,
639 /* subdir= */ "framework/") ||
640 // When the 'system_ext' partition is not present, builds will create
641 // '/system/system_ext' instead.
642 IsLocationOn(full_path,
643 kAndroidRootEnvVar,
644 kAndroidRootDefaultPath,
645 /* subdir= */ "system_ext/framework/");
646 }
647
LocationIsOnConscryptModule(std::string_view full_path)648 bool LocationIsOnConscryptModule(std::string_view full_path) {
649 return IsLocationOn(full_path, kAndroidConscryptRootEnvVar, kAndroidConscryptApexDefaultPath);
650 }
651
LocationIsOnI18nModule(std::string_view full_path)652 bool LocationIsOnI18nModule(std::string_view full_path) {
653 return IsLocationOn(full_path, kAndroidI18nRootEnvVar, kAndroidI18nApexDefaultPath);
654 }
655
LocationIsOnApex(std::string_view full_path)656 bool LocationIsOnApex(std::string_view full_path) {
657 return android::base::StartsWith(full_path, kApexDefaultPath);
658 }
659
ApexNameFromLocation(std::string_view full_path)660 std::string_view ApexNameFromLocation(std::string_view full_path) {
661 if (!android::base::StartsWith(full_path, kApexDefaultPath)) {
662 return {};
663 }
664 size_t start = strlen(kApexDefaultPath);
665 size_t end = full_path.find('/', start);
666 if (end == std::string_view::npos) {
667 return {};
668 }
669 return full_path.substr(start, end - start);
670 }
671
LocationIsOnSystem(const std::string & location)672 bool LocationIsOnSystem(const std::string& location) {
673 #ifdef _WIN32
674 UNUSED(location);
675 LOG(FATAL) << "LocationIsOnSystem is unsupported on Windows.";
676 return false;
677 #else
678 return android::base::StartsWith(location, GetAndroidRoot().c_str());
679 #endif
680 }
681
LocationIsTrusted(const std::string & location,bool trust_art_apex_data_files)682 bool LocationIsTrusted(const std::string& location, bool trust_art_apex_data_files) {
683 if (LocationIsOnSystem(location) || LocationIsOnArtModule(location)) {
684 return true;
685 }
686 return LocationIsOnArtApexData(location) & trust_art_apex_data_files;
687 }
688
ArtModuleRootDistinctFromAndroidRoot()689 bool ArtModuleRootDistinctFromAndroidRoot() {
690 std::string error_msg;
691 const char* android_root = GetAndroidDirSafe(kAndroidRootEnvVar,
692 kAndroidRootDefaultPath,
693 /* must_exist= */ kIsTargetBuild,
694 &error_msg);
695 const char* art_root = GetAndroidDirSafe(kAndroidArtRootEnvVar,
696 kAndroidArtApexDefaultPath,
697 /* must_exist= */ kIsTargetBuild,
698 &error_msg);
699 return (android_root != nullptr) && (art_root != nullptr) &&
700 (std::string_view(android_root) != std::string_view(art_root));
701 }
702
DupCloexec(int fd)703 int DupCloexec(int fd) {
704 #if defined(__linux__)
705 return fcntl(fd, F_DUPFD_CLOEXEC, 0);
706 #else
707 return dup(fd);
708 #endif
709 }
710
711 } // namespace art
712