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