• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 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 "common_art_test.h"
18 
19 #include <dirent.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <ftw.h>
23 #include <libgen.h>
24 #include <stdlib.h>
25 #include <sys/capability.h>
26 #include <unistd.h>
27 
28 #include <cstdio>
29 #include <filesystem>
30 #include <functional>
31 
32 #include "android-base/file.h"
33 #include "android-base/logging.h"
34 #include "android-base/process.h"
35 #include "android-base/scopeguard.h"
36 #include "android-base/stringprintf.h"
37 #include "android-base/strings.h"
38 #include "android-base/unique_fd.h"
39 #include "art_field-inl.h"
40 #include "base/file_utils.h"
41 #include "base/logging.h"
42 #include "base/macros.h"
43 #include "base/mem_map.h"
44 #include "base/mutex.h"
45 #include "base/os.h"
46 #include "base/runtime_debug.h"
47 #include "base/scoped_cap.h"
48 #include "base/stl_util.h"
49 #include "base/string_view_cpp20.h"
50 #include "base/testing.h"
51 #include "base/unix_file/fd_file.h"
52 #include "dex/art_dex_file_loader.h"
53 #include "dex/dex_file-inl.h"
54 #include "dex/dex_file_loader.h"
55 #include "dex/primitive.h"
56 #include "gtest/gtest.h"
57 #include "nativehelper/scoped_local_ref.h"
58 
59 namespace art {
60 
61 using android::base::StringPrintf;
62 
ScratchDir(bool keep_files)63 ScratchDir::ScratchDir(bool keep_files) : keep_files_(keep_files) {
64   // ANDROID_DATA needs to be set
65   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
66       "Are you subclassing RuntimeTest?";
67   path_ = getenv("ANDROID_DATA");
68   path_ += "/tmp-XXXXXX";
69   bool ok = (mkdtemp(&path_[0]) != nullptr);
70   CHECK(ok) << strerror(errno) << " for " << path_;
71   path_ += "/";
72 }
73 
~ScratchDir()74 ScratchDir::~ScratchDir() {
75   if (!keep_files_) {
76     std::filesystem::remove_all(path_);
77   }
78 }
79 
ScratchFile()80 ScratchFile::ScratchFile() {
81   // ANDROID_DATA needs to be set
82   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
83       "Are you subclassing RuntimeTest?";
84   filename_ = getenv("ANDROID_DATA");
85   filename_ += "/TmpFile-XXXXXX";
86   int fd = mkstemp(&filename_[0]);
87   CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
88   file_.reset(new File(fd, GetFilename(), true));
89 }
90 
ScratchFile(const ScratchFile & other,const char * suffix)91 ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
92     : ScratchFile(other.GetFilename() + suffix) {}
93 
ScratchFile(const std::string & filename)94 ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
95   int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
96   CHECK_NE(-1, fd);
97   file_.reset(new File(fd, GetFilename(), true));
98 }
99 
ScratchFile(File * file)100 ScratchFile::ScratchFile(File* file) {
101   CHECK(file != nullptr);
102   filename_ = file->GetPath();
103   file_.reset(file);
104 }
105 
ScratchFile(ScratchFile && other)106 ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
107   *this = std::move(other);
108 }
109 
operator =(ScratchFile && other)110 ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
111   if (GetFile() != other.GetFile()) {
112     std::swap(filename_, other.filename_);
113     std::swap(file_, other.file_);
114   }
115   return *this;
116 }
117 
~ScratchFile()118 ScratchFile::~ScratchFile() {
119   Unlink();
120 }
121 
GetFd() const122 int ScratchFile::GetFd() const {
123   return file_->Fd();
124 }
125 
Close()126 void ScratchFile::Close() {
127   if (file_ != nullptr) {
128     if (file_->FlushCloseOrErase() != 0) {
129       PLOG(WARNING) << "Error closing scratch file.";
130     }
131     file_.reset();
132   }
133 }
134 
Unlink()135 void ScratchFile::Unlink() {
136   if (!OS::FileExists(filename_.c_str())) {
137     return;
138   }
139   Close();
140   int unlink_result = unlink(filename_.c_str());
141   CHECK_EQ(0, unlink_result);
142 }
143 
144 // Temporarily drops all root capabilities when the test is run as root. This is a noop otherwise.
ScopedUnroot()145 android::base::ScopeGuard<std::function<void()>> ScopedUnroot() {
146   ScopedCap old_cap(cap_get_proc());
147   CHECK_NE(old_cap.Get(), nullptr);
148   ScopedCap new_cap(cap_dup(old_cap.Get()));
149   CHECK_NE(new_cap.Get(), nullptr);
150   CHECK_EQ(cap_clear_flag(new_cap.Get(), CAP_EFFECTIVE), 0);
151   CHECK_EQ(cap_set_proc(new_cap.Get()), 0);
152   // `old_cap` is actually not shared with anyone else, but we have to wrap it with a `shared_ptr`
153   // because `std::function` requires captures to be copyable.
154   return android::base::make_scope_guard(
155       [old_cap = std::make_shared<ScopedCap>(std::move(old_cap))]() {
156         CHECK_EQ(cap_set_proc(old_cap->Get()), 0);
157       });
158 }
159 
160 // Temporarily drops write permission on a file/directory.
ScopedInaccessible(const std::string & path)161 android::base::ScopeGuard<std::function<void()>> ScopedInaccessible(const std::string& path) {
162   std::filesystem::perms old_perms = std::filesystem::status(path).permissions();
163   std::filesystem::permissions(path, std::filesystem::perms::none);
164   return android::base::make_scope_guard([=]() { std::filesystem::permissions(path, old_perms); });
165 }
166 
GetAndroidBuildTop()167 std::string CommonArtTestImpl::GetAndroidBuildTop() {
168   CHECK(IsHost());
169   std::string android_build_top;
170 
171   // Look at how we were invoked to find the expected directory.
172   std::string argv;
173   if (android::base::ReadFileToString("/proc/self/cmdline", &argv)) {
174     // /proc/self/cmdline is the programs 'argv' with elements delimited by '\0'.
175     std::filesystem::path path(argv.substr(0, argv.find('\0')));
176     path = std::filesystem::absolute(path);
177     // Walk up until we find the one of the well-known directories.
178     for (; path.parent_path() != path; path = path.parent_path()) {
179       // We are running tests from out/host/linux-x86 on developer machine.
180       if (path.filename() == std::filesystem::path("linux-x86")) {
181         android_build_top = path.parent_path().parent_path().parent_path();
182         break;
183       }
184       // We are running tests from testcases (extracted from zip) on tradefed.
185       // The first path is for remote runs and the second path for local runs.
186       if (path.filename() == std::filesystem::path("testcases") ||
187           StartsWith(path.filename().string(), "host_testcases")) {
188         android_build_top = path.append("art_common");
189         break;
190       }
191     }
192   }
193   CHECK(!android_build_top.empty());
194 
195   // Check that the expected directory matches the environment variable.
196   const char* android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
197   android_build_top = std::filesystem::path(android_build_top).string();
198   CHECK(!android_build_top.empty());
199   if (android_build_top_from_env != nullptr) {
200     if (std::filesystem::weakly_canonical(android_build_top).string() !=
201         std::filesystem::weakly_canonical(android_build_top_from_env).string()) {
202       LOG(WARNING) << "Execution path (" << argv << ") not below ANDROID_BUILD_TOP ("
203                    << android_build_top_from_env << ")! Using env-var.";
204       android_build_top = android_build_top_from_env;
205     }
206   } else {
207     setenv("ANDROID_BUILD_TOP", android_build_top.c_str(), /*overwrite=*/0);
208   }
209   if (android_build_top.back() != '/') {
210     android_build_top += '/';
211   }
212   return android_build_top;
213 }
214 
GetAndroidHostOut()215 std::string CommonArtTestImpl::GetAndroidHostOut() {
216   CHECK(IsHost());
217 
218   // Check that the expected directory matches the environment variable.
219   // ANDROID_HOST_OUT is set by envsetup or unset and is the full path to host binaries/libs
220   const char* android_host_out_from_env = getenv("ANDROID_HOST_OUT");
221   // OUT_DIR is a user-settable ENV_VAR that controls where soong puts build artifacts. It can
222   // either be relative to ANDROID_BUILD_TOP or a concrete path.
223   const char* android_out_dir = getenv("OUT_DIR");
224   // Take account of OUT_DIR setting.
225   if (android_out_dir == nullptr) {
226     android_out_dir = "out";
227   }
228   std::string android_host_out;
229   if (android_out_dir[0] == '/') {
230     android_host_out = (std::filesystem::path(android_out_dir) / "host" / "linux-x86").string();
231   } else {
232     android_host_out =
233         (std::filesystem::path(GetAndroidBuildTop()) / android_out_dir / "host" / "linux-x86")
234             .string();
235   }
236   std::filesystem::path expected(android_host_out);
237   if (android_host_out_from_env != nullptr) {
238     std::filesystem::path from_env(std::filesystem::weakly_canonical(android_host_out_from_env));
239     if (std::filesystem::weakly_canonical(expected).string() != from_env.string()) {
240       LOG(WARNING) << "Execution path (" << expected << ") not below ANDROID_HOST_OUT ("
241                    << from_env << ")! Using env-var.";
242       expected = from_env;
243     }
244   } else {
245     setenv("ANDROID_HOST_OUT", android_host_out.c_str(), /*overwrite=*/0);
246   }
247   return expected.string();
248 }
249 
SetUpAndroidRootEnvVars()250 void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
251   if (IsHost()) {
252     std::string android_host_out = GetAndroidHostOut();
253 
254     // Environment variable ANDROID_ROOT is set on the device, but not
255     // necessarily on the host.
256     const char* android_root_from_env = getenv("ANDROID_ROOT");
257     if (android_root_from_env == nullptr) {
258       // Use ANDROID_HOST_OUT for ANDROID_ROOT.
259       setenv("ANDROID_ROOT", android_host_out.c_str(), 1);
260       android_root_from_env = getenv("ANDROID_ROOT");
261     }
262 
263     // Environment variable ANDROID_I18N_ROOT is set on the device, but not
264     // necessarily on the host. It needs to be set so that various libraries
265     // like libcore / icu4j / icu4c can find their data files.
266     const char* android_i18n_root_from_env = getenv("ANDROID_I18N_ROOT");
267     if (android_i18n_root_from_env == nullptr) {
268       // Use ${ANDROID_I18N_OUT}/com.android.i18n for ANDROID_I18N_ROOT.
269       std::string android_i18n_root = android_host_out;
270       android_i18n_root += "/com.android.i18n";
271       setenv("ANDROID_I18N_ROOT", android_i18n_root.c_str(), 1);
272     }
273 
274     // Environment variable ANDROID_ART_ROOT is set on the device, but not
275     // necessarily on the host. It needs to be set so that various libraries
276     // like libcore / icu4j / icu4c can find their data files.
277     const char* android_art_root_from_env = getenv("ANDROID_ART_ROOT");
278     if (android_art_root_from_env == nullptr) {
279       // Use ${ANDROID_HOST_OUT}/com.android.art for ANDROID_ART_ROOT.
280       std::string android_art_root = android_host_out;
281       android_art_root += "/com.android.art";
282       setenv("ANDROID_ART_ROOT", android_art_root.c_str(), 1);
283     }
284 
285     // Environment variable ANDROID_TZDATA_ROOT is set on the device, but not
286     // necessarily on the host. It needs to be set so that various libraries
287     // like libcore / icu4j / icu4c can find their data files.
288     const char* android_tzdata_root_from_env = getenv("ANDROID_TZDATA_ROOT");
289     if (android_tzdata_root_from_env == nullptr) {
290       // Use ${ANDROID_HOST_OUT}/com.android.tzdata for ANDROID_TZDATA_ROOT.
291       std::string android_tzdata_root = android_host_out;
292       android_tzdata_root += "/com.android.tzdata";
293       setenv("ANDROID_TZDATA_ROOT", android_tzdata_root.c_str(), 1);
294     }
295 
296     setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
297   }
298 }
299 
SetUpAndroidDataDir(std::string & android_data)300 void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
301   if (IsHost()) {
302     const char* tmpdir = getenv("TMPDIR");
303     if (tmpdir != nullptr && tmpdir[0] != 0) {
304       android_data = tmpdir;
305     } else {
306       android_data = "/tmp";
307     }
308   } else {
309     // On target, we cannot use `/mnt/sdcard` because it is mounted `noexec`,
310     // nor `/data/dalvik-cache` as it is not accessible on `user` builds.
311     // Instead, use `/data/local/tmp`, which does not require any special
312     // permission.
313     android_data = "/data/local/tmp";
314   }
315   android_data += "/art-data-XXXXXX";
316   if (mkdtemp(&android_data[0]) == nullptr) {
317     PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
318   }
319   setenv("ANDROID_DATA", android_data.c_str(), 1);
320 }
321 
SetUp()322 void CommonArtTestImpl::SetUp() {
323   // Some tests clear these and when running with --no_isolate this can cause
324   // later tests to fail
325   Locks::Init();
326   MemMap::Init();
327   SetUpAndroidRootEnvVars();
328   SetUpAndroidDataDir(android_data_);
329 
330   // Re-use the data temporary directory for /system_ext tests
331   android_system_ext_.append(android_data_);
332   android_system_ext_.append("/system_ext");
333   int mkdir_result = mkdir(android_system_ext_.c_str(), 0700);
334   ASSERT_EQ(mkdir_result, 0);
335   setenv("SYSTEM_EXT_ROOT", android_system_ext_.c_str(), 1);
336 
337   std::string system_ext_framework = android_system_ext_ + "/framework";
338   mkdir_result = mkdir(system_ext_framework.c_str(), 0700);
339   ASSERT_EQ(mkdir_result, 0);
340 
341   dalvik_cache_.append(android_data_);
342   dalvik_cache_.append("/dalvik-cache");
343   mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
344   ASSERT_EQ(mkdir_result, 0);
345 
346   if (kIsDebugBuild) {
347     static bool gSlowDebugTestFlag = false;
348     RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
349     SetRuntimeDebugFlagsEnabled(true);
350     CHECK(gSlowDebugTestFlag);
351   }
352 }
353 
TearDownAndroidDataDir(const std::string & android_data,bool fail_on_error)354 void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
355                                                bool fail_on_error) {
356   if (fail_on_error) {
357     ASSERT_EQ(rmdir(android_data.c_str()), 0);
358   } else {
359     rmdir(android_data.c_str());
360   }
361 }
362 
363 // Get prebuilt binary tool.
364 // The paths need to be updated when Android prebuilts update.
GetAndroidTool(const char * name,InstructionSet)365 std::string CommonArtTestImpl::GetAndroidTool(const char* name, InstructionSet) {
366 #ifndef ART_CLANG_PATH
367   UNUSED(name);
368   LOG(FATAL) << "There are no prebuilt tools available.";
369   UNREACHABLE();
370 #else
371   std::string path = GetAndroidBuildTop() + ART_CLANG_PATH + "/bin/";
372   CHECK(OS::DirectoryExists(path.c_str())) << path;
373   path += name;
374   CHECK(OS::FileExists(path.c_str())) << path;
375   return path;
376 #endif
377 }
378 
GetCoreArtLocation()379 std::string CommonArtTestImpl::GetCoreArtLocation() {
380   return GetCoreFileLocation("art");
381 }
382 
GetCoreOatLocation()383 std::string CommonArtTestImpl::GetCoreOatLocation() {
384   return GetCoreFileLocation("oat");
385 }
386 
LoadExpectSingleDexFile(const char * location)387 std::unique_ptr<const DexFile> CommonArtTestImpl::LoadExpectSingleDexFile(const char* location) {
388   std::vector<std::unique_ptr<const DexFile>> dex_files;
389   std::string error_msg;
390   MemMap::Init();
391   static constexpr bool kVerifyChecksum = true;
392   std::string filename(IsHost() ? GetAndroidBuildTop() + location : location);
393   ArtDexFileLoader dex_file_loader(filename.c_str(), std::string(location));
394   if (!dex_file_loader.Open(/* verify= */ true, kVerifyChecksum, &error_msg, &dex_files)) {
395     LOG(FATAL) << "Could not open .dex file '" << filename << "': " << error_msg << "\n";
396     UNREACHABLE();
397   }
398   CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << filename;
399   return std::move(dex_files[0]);
400 }
401 
ClearDirectory(const char * dirpath,bool recursive)402 void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
403   ASSERT_TRUE(dirpath != nullptr);
404   DIR* dir = opendir(dirpath);
405   ASSERT_TRUE(dir != nullptr);
406   dirent* e;
407   struct stat s;
408   while ((e = readdir(dir)) != nullptr) {
409     if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
410       continue;
411     }
412     std::string filename(dirpath);
413     filename.push_back('/');
414     filename.append(e->d_name);
415     int stat_result = lstat(filename.c_str(), &s);
416     ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
417     if (S_ISDIR(s.st_mode)) {
418       if (recursive) {
419         ClearDirectory(filename.c_str());
420         int rmdir_result = rmdir(filename.c_str());
421         ASSERT_EQ(0, rmdir_result) << filename;
422       }
423     } else {
424       int unlink_result = unlink(filename.c_str());
425       ASSERT_EQ(0, unlink_result) << filename;
426     }
427   }
428   closedir(dir);
429 }
430 
TearDown()431 void CommonArtTestImpl::TearDown() {
432   const char* android_data = getenv("ANDROID_DATA");
433   ASSERT_TRUE(android_data != nullptr);
434   ClearDirectory(dalvik_cache_.c_str());
435   int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
436   ASSERT_EQ(0, rmdir_cache_result);
437   ClearDirectory(android_system_ext_.c_str(), true);
438   rmdir_cache_result = rmdir(android_system_ext_.c_str());
439   ASSERT_EQ(0, rmdir_cache_result);
440   TearDownAndroidDataDir(android_data_, true);
441   dalvik_cache_.clear();
442   android_system_ext_.clear();
443 }
444 
GetLibCoreModuleNames() const445 std::vector<std::string> CommonArtTestImpl::GetLibCoreModuleNames() const {
446   return art::testing::GetLibCoreModuleNames();
447 }
448 
GetLibCoreDexFileNames(const std::vector<std::string> & modules) const449 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames(
450     const std::vector<std::string>& modules) const {
451   return art::testing::GetLibCoreDexFileNames(modules);
452 }
453 
GetLibCoreDexFileNames() const454 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames() const {
455   std::vector<std::string> modules = GetLibCoreModuleNames();
456   return art::testing::GetLibCoreDexFileNames(modules);
457 }
458 
GetLibCoreDexLocations(const std::vector<std::string> & modules) const459 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations(
460     const std::vector<std::string>& modules) const {
461   std::vector<std::string> result = GetLibCoreDexFileNames(modules);
462   if (IsHost()) {
463     // Strip the ANDROID_BUILD_TOP directory including the directory separator '/'.
464     std::string prefix = GetAndroidBuildTop();
465     for (std::string& location : result) {
466       CHECK_GT(location.size(), prefix.size());
467       CHECK_EQ(location.compare(0u, prefix.size(), prefix), 0)
468           << " prefix=" << prefix << " location=" << location;
469       location.erase(0u, prefix.size());
470     }
471   }
472   return result;
473 }
474 
GetLibCoreDexLocations() const475 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations() const {
476   std::vector<std::string> modules = GetLibCoreModuleNames();
477   return GetLibCoreDexLocations(modules);
478 }
479 
GetClassPathOption(const char * option,const std::vector<std::string> & class_path)480 std::string CommonArtTestImpl::GetClassPathOption(const char* option,
481                                                   const std::vector<std::string>& class_path) {
482   return option + android::base::Join(class_path, ':');
483 }
484 
485 // Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
486 #ifdef ART_TARGET
487 #ifndef ART_TARGET_NATIVETEST_DIR
488 #error "ART_TARGET_NATIVETEST_DIR not set."
489 #endif
490 // Wrap it as a string literal.
491 #define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
492 #else
493 #define ART_TARGET_NATIVETEST_DIR_STRING ""
494 #endif
495 
GetTestDexFileName(const char * name) const496 std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
497   CHECK(name != nullptr);
498   // The needed jar files for gtest are located next to the gtest binary itself.
499   std::string executable_dir = android::base::GetExecutableDirectory();
500   for (auto ext : {".jar", ".dex"}) {
501     std::string path = executable_dir + "/art-gtest-jars-" + name + ext;
502     if (OS::FileExists(path.c_str())) {
503       return path;
504     }
505   }
506   LOG(FATAL) << "Test file " << name << " not found";
507   UNREACHABLE();
508 }
509 
OpenDexFiles(const char * filename)510 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
511   static constexpr bool kVerify = true;
512   static constexpr bool kVerifyChecksum = true;
513   std::string error_msg;
514   ArtDexFileLoader dex_file_loader(filename);
515   std::vector<std::unique_ptr<const DexFile>> dex_files;
516   bool success = dex_file_loader.Open(kVerify, kVerifyChecksum, &error_msg, &dex_files);
517   CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
518   for (auto& dex_file : dex_files) {
519     CHECK(dex_file->IsReadOnly());
520   }
521   return dex_files;
522 }
523 
OpenDexFile(const char * filename)524 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenDexFile(const char* filename) {
525   std::vector<std::unique_ptr<const DexFile>> dex_files(OpenDexFiles(filename));
526   CHECK_EQ(dex_files.size(), 1u) << "Expected only one dex file";
527   return std::move(dex_files[0]);
528 }
529 
OpenTestDexFiles(const char * name)530 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
531     const char* name) {
532   return OpenDexFiles(GetTestDexFileName(name).c_str());
533 }
534 
OpenTestDexFile(const char * name)535 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
536   return OpenDexFile(GetTestDexFileName(name).c_str());
537 }
538 
GetImageDirectory()539 std::string CommonArtTestImpl::GetImageDirectory() {
540   if (IsHost()) {
541     const char* host_dir = getenv("ANDROID_HOST_OUT");
542     CHECK(host_dir != nullptr);
543     return std::string(host_dir) + "/apex/art_boot_images/javalib";
544   }
545   // On device, the boot image is generated by `generate-boot-image`.
546   // In a standalone test, the boot image is located next to the gtest binary itself.
547   std::string path = android::base::GetExecutableDirectory() + "/art_boot_images";
548   if (OS::DirectoryExists(path.c_str())) {
549     return path;
550   }
551   // In a chroot environment prepared by scripts, the boot image is located in a predefined
552   // location on /system.
553   path = "/system/framework/art_boot_images";
554   if (OS::DirectoryExists(path.c_str())) {
555     return path;
556   }
557   // In art-target-gtest-chroot, the boot image is located in a predefined location on /data because
558   // /system is a mount point that replicates the real one on device.
559   path = "/data/local/tmp/art_boot_images";
560   if (OS::DirectoryExists(path.c_str())) {
561     return path;
562   }
563   LOG(FATAL) << "Boot image not found";
564   UNREACHABLE();
565 }
566 
GetCoreFileLocation(const char * suffix)567 std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
568   CHECK(suffix != nullptr);
569   return GetImageDirectory() + "/boot." + suffix;
570 }
571 
CreateClassPath(const std::vector<std::unique_ptr<const DexFile>> & dex_files)572 std::string CommonArtTestImpl::CreateClassPath(
573     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
574   CHECK(!dex_files.empty());
575   std::string classpath = dex_files[0]->GetLocation();
576   for (size_t i = 1; i < dex_files.size(); i++) {
577     classpath += ":" + dex_files[i]->GetLocation();
578   }
579   return classpath;
580 }
581 
CreateClassPathWithChecksums(const std::vector<std::unique_ptr<const DexFile>> & dex_files)582 std::string CommonArtTestImpl::CreateClassPathWithChecksums(
583     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
584   CHECK(!dex_files.empty());
585   std::string classpath = dex_files[0]->GetLocation() + "*" +
586       std::to_string(dex_files[0]->GetLocationChecksum());
587   for (size_t i = 1; i < dex_files.size(); i++) {
588     classpath += ":" + dex_files[i]->GetLocation() + "*" +
589         std::to_string(dex_files[i]->GetLocationChecksum());
590   }
591   return classpath;
592 }
593 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,const OutputHandlerFn & handler)594 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
595     const std::vector<std::string>& argv,
596     const PostForkFn& post_fork,
597     const OutputHandlerFn& handler) {
598   ForkAndExecResult result;
599   result.status_code = 0;
600   result.stage = ForkAndExecResult::kLink;
601 
602   std::vector<const char*> c_args;
603   c_args.reserve(argv.size() + 1);
604   for (const std::string& str : argv) {
605     c_args.push_back(str.c_str());
606   }
607   c_args.push_back(nullptr);
608 
609   android::base::unique_fd link[2];
610   {
611     int link_fd[2];
612 
613     if (pipe(link_fd) == -1) {
614       return result;
615     }
616     link[0].reset(link_fd[0]);
617     link[1].reset(link_fd[1]);
618   }
619 
620   result.stage = ForkAndExecResult::kFork;
621 
622   pid_t pid = fork();
623   if (pid == -1) {
624     return result;
625   }
626 
627   if (pid == 0) {
628     if (!post_fork()) {
629       LOG(ERROR) << "Failed post-fork function";
630       exit(1);
631       UNREACHABLE();
632     }
633 
634     // Redirect stdout and stderr.
635     dup2(link[1].get(), STDOUT_FILENO);
636     dup2(link[1].get(), STDERR_FILENO);
637 
638     link[0].reset();
639     link[1].reset();
640 
641     execv(c_args[0], const_cast<char* const*>(c_args.data()));
642     exit(1);
643     UNREACHABLE();
644   }
645 
646   result.stage = ForkAndExecResult::kWaitpid;
647   link[1].reset();
648 
649   char buffer[128] = { 0 };
650   ssize_t bytes_read = 0;
651   while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
652     handler(buffer, bytes_read);
653   }
654   handler(buffer, 0u);  // End with a virtual write of zero length to simplify clients.
655 
656   link[0].reset();
657 
658   if (waitpid(pid, &result.status_code, 0) == -1) {
659     return result;
660   }
661 
662   result.stage = ForkAndExecResult::kFinished;
663   return result;
664 }
665 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,std::string * output)666 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
667     const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
668   auto string_collect_fn = [output](char* buf, size_t len) {
669     *output += std::string(buf, len);
670   };
671   return ForkAndExec(argv, post_fork, string_collect_fn);
672 }
673 
GetPidByName(const std::string & process_name)674 std::vector<pid_t> GetPidByName(const std::string& process_name) {
675   std::vector<pid_t> results;
676   for (pid_t pid : android::base::AllPids{}) {
677     std::string cmdline;
678     if (!android::base::ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline)) {
679       continue;
680     }
681     // Take the first argument.
682     size_t pos = cmdline.find('\0');
683     if (pos != std::string::npos) {
684       cmdline.resize(pos);
685     }
686     if (cmdline == process_name) {
687       results.push_back(pid);
688     }
689   }
690   return results;
691 }
692 
693 }  // namespace art
694