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