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