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