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 <stdlib.h>
24 #include <unistd.h>
25 #include <cstdio>
26 #include <filesystem>
27 #include "android-base/file.h"
28 #include "android-base/logging.h"
29 #include "nativehelper/scoped_local_ref.h"
30 
31 #include "android-base/stringprintf.h"
32 #include "android-base/strings.h"
33 #include "android-base/unique_fd.h"
34 
35 #include "art_field-inl.h"
36 #include "base/file_utils.h"
37 #include "base/logging.h"
38 #include "base/macros.h"
39 #include "base/mem_map.h"
40 #include "base/mutex.h"
41 #include "base/os.h"
42 #include "base/runtime_debug.h"
43 #include "base/stl_util.h"
44 #include "base/unix_file/fd_file.h"
45 #include "dex/art_dex_file_loader.h"
46 #include "dex/dex_file-inl.h"
47 #include "dex/dex_file_loader.h"
48 #include "dex/primitive.h"
49 #include "gtest/gtest.h"
50 
51 namespace art {
52 
53 using android::base::StringPrintf;
54 
ScratchDir()55 ScratchDir::ScratchDir() {
56   // ANDROID_DATA needs to be set
57   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
58       "Are you subclassing RuntimeTest?";
59   path_ = getenv("ANDROID_DATA");
60   path_ += "/tmp-XXXXXX";
61   bool ok = (mkdtemp(&path_[0]) != nullptr);
62   CHECK(ok) << strerror(errno) << " for " << path_;
63   path_ += "/";
64 }
65 
~ScratchDir()66 ScratchDir::~ScratchDir() {
67   // Recursively delete the directory and all its content.
68   nftw(path_.c_str(), [](const char* name, const struct stat*, int type, struct FTW *) {
69     if (type == FTW_F) {
70       unlink(name);
71     } else if (type == FTW_DP) {
72       rmdir(name);
73     }
74     return 0;
75   }, 256 /* max open file descriptors */, FTW_DEPTH);
76 }
77 
ScratchFile()78 ScratchFile::ScratchFile() {
79   // ANDROID_DATA needs to be set
80   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
81       "Are you subclassing RuntimeTest?";
82   filename_ = getenv("ANDROID_DATA");
83   filename_ += "/TmpFile-XXXXXX";
84   int fd = mkstemp(&filename_[0]);
85   CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
86   file_.reset(new File(fd, GetFilename(), true));
87 }
88 
ScratchFile(const ScratchFile & other,const char * suffix)89 ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
90     : ScratchFile(other.GetFilename() + suffix) {}
91 
ScratchFile(const std::string & filename)92 ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
93   int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
94   CHECK_NE(-1, fd);
95   file_.reset(new File(fd, GetFilename(), true));
96 }
97 
ScratchFile(File * file)98 ScratchFile::ScratchFile(File* file) {
99   CHECK(file != nullptr);
100   filename_ = file->GetPath();
101   file_.reset(file);
102 }
103 
ScratchFile(ScratchFile && other)104 ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
105   *this = std::move(other);
106 }
107 
operator =(ScratchFile && other)108 ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
109   if (GetFile() != other.GetFile()) {
110     std::swap(filename_, other.filename_);
111     std::swap(file_, other.file_);
112   }
113   return *this;
114 }
115 
~ScratchFile()116 ScratchFile::~ScratchFile() {
117   Unlink();
118 }
119 
GetFd() const120 int ScratchFile::GetFd() const {
121   return file_->Fd();
122 }
123 
Close()124 void ScratchFile::Close() {
125   if (file_.get() != nullptr) {
126     if (file_->FlushCloseOrErase() != 0) {
127       PLOG(WARNING) << "Error closing scratch file.";
128     }
129   }
130 }
131 
Unlink()132 void ScratchFile::Unlink() {
133   if (!OS::FileExists(filename_.c_str())) {
134     return;
135   }
136   Close();
137   int unlink_result = unlink(filename_.c_str());
138   CHECK_EQ(0, unlink_result);
139 }
140 
SetUpAndroidRootEnvVars()141 void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
142   if (IsHost()) {
143     // Make sure that ANDROID_BUILD_TOP is set. If not, set it from CWD.
144     const char* android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
145     if (android_build_top_from_env == nullptr) {
146       // Not set by build server, so default to current directory.
147       char* cwd = getcwd(nullptr, 0);
148       setenv("ANDROID_BUILD_TOP", cwd, 1);
149       free(cwd);
150       android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
151     }
152 
153     const char* android_host_out_from_env = getenv("ANDROID_HOST_OUT");
154     if (android_host_out_from_env == nullptr) {
155       // Not set by build server, so default to the usual value of
156       // ANDROID_HOST_OUT.
157       std::string android_host_out;
158 #if defined(__linux__)
159       // Fallback
160       android_host_out = std::string(android_build_top_from_env) + "/out/host/linux-x86";
161       // Look at how we were invoked
162       std::string argv;
163       if (android::base::ReadFileToString("/proc/self/cmdline", &argv)) {
164         // /proc/self/cmdline is the programs 'argv' with elements delimited by '\0'.
165         std::string cmdpath(argv.substr(0, argv.find('\0')));
166         std::filesystem::path path(cmdpath);
167         // If the path is relative then prepend the android_build_top_from_env to it
168         if (path.is_relative()) {
169           path = std::filesystem::path(android_build_top_from_env).append(cmdpath);
170           DCHECK(path.is_absolute()) << path;
171         }
172         // Walk up until we find the linux-x86 directory or we hit the root directory.
173         while (path.has_parent_path() && path.parent_path() != path &&
174                path.filename() != std::filesystem::path("linux-x86")) {
175           path = path.parent_path();
176         }
177         // If we found a linux-x86 directory path is now android_host_out
178         if (path.filename() == std::filesystem::path("linux-x86")) {
179           android_host_out = path.string();
180         }
181       }
182 #elif defined(__APPLE__)
183       android_host_out = std::string(android_build_top_from_env) + "/out/host/darwin-x86";
184 #else
185 #error unsupported OS
186 #endif
187       setenv("ANDROID_HOST_OUT", android_host_out.c_str(), 1);
188       android_host_out_from_env = getenv("ANDROID_HOST_OUT");
189     }
190 
191     // Environment variable ANDROID_ROOT is set on the device, but not
192     // necessarily on the host.
193     const char* android_root_from_env = getenv("ANDROID_ROOT");
194     if (android_root_from_env == nullptr) {
195       // Use ANDROID_HOST_OUT for ANDROID_ROOT.
196       setenv("ANDROID_ROOT", android_host_out_from_env, 1);
197       android_root_from_env = getenv("ANDROID_ROOT");
198     }
199 
200     // Environment variable ANDROID_I18N_ROOT is set on the device, but not
201     // necessarily on the host. It needs to be set so that various libraries
202     // like libcore / icu4j / icu4c can find their data files.
203     const char* android_i18n_root_from_env = getenv("ANDROID_I18N_ROOT");
204     if (android_i18n_root_from_env == nullptr) {
205       // Use ${ANDROID_I18N_OUT}/com.android.i18n for ANDROID_I18N_ROOT.
206       std::string android_i18n_root = android_host_out_from_env;
207       android_i18n_root += "/com.android.i18n";
208       setenv("ANDROID_I18N_ROOT", android_i18n_root.c_str(), 1);
209     }
210 
211     // Environment variable ANDROID_ART_ROOT is set on the device, but not
212     // necessarily on the host. It needs to be set so that various libraries
213     // like libcore / icu4j / icu4c can find their data files.
214     const char* android_art_root_from_env = getenv("ANDROID_ART_ROOT");
215     if (android_art_root_from_env == nullptr) {
216       // Use ${ANDROID_HOST_OUT}/com.android.art for ANDROID_ART_ROOT.
217       std::string android_art_root = android_host_out_from_env;
218       android_art_root += "/com.android.art";
219       setenv("ANDROID_ART_ROOT", android_art_root.c_str(), 1);
220     }
221 
222     // Environment variable ANDROID_TZDATA_ROOT is set on the device, but not
223     // necessarily on the host. It needs to be set so that various libraries
224     // like libcore / icu4j / icu4c can find their data files.
225     const char* android_tzdata_root_from_env = getenv("ANDROID_TZDATA_ROOT");
226     if (android_tzdata_root_from_env == nullptr) {
227       // Use ${ANDROID_HOST_OUT}/com.android.tzdata for ANDROID_TZDATA_ROOT.
228       std::string android_tzdata_root = android_host_out_from_env;
229       android_tzdata_root += "/com.android.tzdata";
230       setenv("ANDROID_TZDATA_ROOT", android_tzdata_root.c_str(), 1);
231     }
232 
233     setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
234   }
235 }
236 
SetUpAndroidDataDir(std::string & android_data)237 void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
238   // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
239   if (IsHost()) {
240     const char* tmpdir = getenv("TMPDIR");
241     if (tmpdir != nullptr && tmpdir[0] != 0) {
242       android_data = tmpdir;
243     } else {
244       android_data = "/tmp";
245     }
246   } else {
247     android_data = "/data/dalvik-cache";
248   }
249   android_data += "/art-data-XXXXXX";
250   if (mkdtemp(&android_data[0]) == nullptr) {
251     PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
252   }
253   setenv("ANDROID_DATA", android_data.c_str(), 1);
254 }
255 
SetUp()256 void CommonArtTestImpl::SetUp() {
257   SetUpAndroidRootEnvVars();
258   SetUpAndroidDataDir(android_data_);
259   dalvik_cache_.append(android_data_.c_str());
260   dalvik_cache_.append("/dalvik-cache");
261   int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
262   ASSERT_EQ(mkdir_result, 0);
263 
264   static bool gSlowDebugTestFlag = false;
265   RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
266   SetRuntimeDebugFlagsEnabled(true);
267   CHECK(gSlowDebugTestFlag);
268 }
269 
TearDownAndroidDataDir(const std::string & android_data,bool fail_on_error)270 void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
271                                                bool fail_on_error) {
272   if (fail_on_error) {
273     ASSERT_EQ(rmdir(android_data.c_str()), 0);
274   } else {
275     rmdir(android_data.c_str());
276   }
277 }
278 
279 // Helper - find directory with the following format:
280 // ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
GetAndroidToolsDir(const std::string & subdir1,const std::string & subdir2,const std::string & subdir3)281 std::string CommonArtTestImpl::GetAndroidToolsDir(const std::string& subdir1,
282                                                   const std::string& subdir2,
283                                                   const std::string& subdir3) {
284   std::string root;
285   const char* android_build_top = getenv("ANDROID_BUILD_TOP");
286   if (android_build_top != nullptr) {
287     root = android_build_top;
288   } else {
289     // Not set by build server, so default to current directory
290     char* cwd = getcwd(nullptr, 0);
291     setenv("ANDROID_BUILD_TOP", cwd, 1);
292     root = cwd;
293     free(cwd);
294   }
295 
296   std::string toolsdir = root + "/" + subdir1;
297   std::string founddir;
298   DIR* dir;
299   if ((dir = opendir(toolsdir.c_str())) != nullptr) {
300     float maxversion = 0;
301     struct dirent* entry;
302     while ((entry = readdir(dir)) != nullptr) {
303       std::string format = subdir2 + "-%f";
304       float version;
305       if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
306         if (version > maxversion) {
307           maxversion = version;
308           founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
309         }
310       }
311     }
312     closedir(dir);
313   }
314 
315   if (founddir.empty()) {
316     ADD_FAILURE() << "Cannot find Android tools directory.";
317   }
318   return founddir;
319 }
320 
GetAndroidHostToolsDir()321 std::string CommonArtTestImpl::GetAndroidHostToolsDir() {
322   return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
323                             "x86_64-linux-glibc2.17",
324                             "x86_64-linux");
325 }
326 
GetCoreArtLocation()327 std::string CommonArtTestImpl::GetCoreArtLocation() {
328   return GetCoreFileLocation("art");
329 }
330 
GetCoreOatLocation()331 std::string CommonArtTestImpl::GetCoreOatLocation() {
332   return GetCoreFileLocation("oat");
333 }
334 
LoadExpectSingleDexFile(const char * location)335 std::unique_ptr<const DexFile> CommonArtTestImpl::LoadExpectSingleDexFile(const char* location) {
336   std::vector<std::unique_ptr<const DexFile>> dex_files;
337   std::string error_msg;
338   MemMap::Init();
339   static constexpr bool kVerifyChecksum = true;
340   const ArtDexFileLoader dex_file_loader;
341   if (!dex_file_loader.Open(
342         location, location, /* verify= */ true, kVerifyChecksum, &error_msg, &dex_files)) {
343     LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
344     UNREACHABLE();
345   } else {
346     CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
347     return std::move(dex_files[0]);
348   }
349 }
350 
ClearDirectory(const char * dirpath,bool recursive)351 void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
352   ASSERT_TRUE(dirpath != nullptr);
353   DIR* dir = opendir(dirpath);
354   ASSERT_TRUE(dir != nullptr);
355   dirent* e;
356   struct stat s;
357   while ((e = readdir(dir)) != nullptr) {
358     if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
359       continue;
360     }
361     std::string filename(dirpath);
362     filename.push_back('/');
363     filename.append(e->d_name);
364     int stat_result = lstat(filename.c_str(), &s);
365     ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
366     if (S_ISDIR(s.st_mode)) {
367       if (recursive) {
368         ClearDirectory(filename.c_str());
369         int rmdir_result = rmdir(filename.c_str());
370         ASSERT_EQ(0, rmdir_result) << filename;
371       }
372     } else {
373       int unlink_result = unlink(filename.c_str());
374       ASSERT_EQ(0, unlink_result) << filename;
375     }
376   }
377   closedir(dir);
378 }
379 
TearDown()380 void CommonArtTestImpl::TearDown() {
381   const char* android_data = getenv("ANDROID_DATA");
382   ASSERT_TRUE(android_data != nullptr);
383   ClearDirectory(dalvik_cache_.c_str());
384   int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
385   ASSERT_EQ(0, rmdir_cache_result);
386   TearDownAndroidDataDir(android_data_, true);
387   dalvik_cache_.clear();
388 }
389 
GetDexFileName(const std::string & jar_prefix,bool host)390 static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
391   if (host) {
392     std::string path = GetAndroidRoot();
393     return StringPrintf("%s/framework/%s-hostdex.jar", path.c_str(), jar_prefix.c_str());
394   } else {
395     const char* apex = (jar_prefix == "conscrypt") ? "com.android.conscrypt" : "com.android.art";
396     return StringPrintf("/apex/%s/javalib/%s.jar", apex, jar_prefix.c_str());
397   }
398 }
399 
GetLibCoreModuleNames() const400 std::vector<std::string> CommonArtTestImpl::GetLibCoreModuleNames() const {
401   // Note: This must start with the CORE_IMG_JARS in Android.common_path.mk
402   // because that's what we use for compiling the core.art image.
403   // It may contain additional modules from TEST_CORE_JARS.
404   return {
405       // CORE_IMG_JARS modules.
406       "core-oj",
407       "core-libart",
408       "core-icu4j",
409       "okhttp",
410       "bouncycastle",
411       "apache-xml",
412       // Additional modules.
413       "conscrypt",
414   };
415 }
416 
GetLibCoreDexFileNames(const std::vector<std::string> & modules) const417 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames(
418     const std::vector<std::string>& modules) const {
419   std::vector<std::string> result;
420   result.reserve(modules.size());
421   for (const std::string& module : modules) {
422     result.push_back(GetDexFileName(module, IsHost()));
423   }
424   return result;
425 }
426 
GetLibCoreDexFileNames() const427 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames() const {
428   std::vector<std::string> modules = GetLibCoreModuleNames();
429   return GetLibCoreDexFileNames(modules);
430 }
431 
GetLibCoreDexLocations(const std::vector<std::string> & modules) const432 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations(
433     const std::vector<std::string>& modules) const {
434   std::vector<std::string> result = GetLibCoreDexFileNames(modules);
435   if (IsHost()) {
436     // Strip the ANDROID_BUILD_TOP directory including the directory separator '/'.
437     const char* host_dir = getenv("ANDROID_BUILD_TOP");
438     CHECK(host_dir != nullptr);
439     std::string prefix = host_dir;
440     CHECK(!prefix.empty());
441     if (prefix.back() != '/') {
442       prefix += '/';
443     }
444     for (std::string& location : result) {
445       CHECK_GT(location.size(), prefix.size());
446       CHECK_EQ(location.compare(0u, prefix.size(), prefix), 0);
447       location.erase(0u, prefix.size());
448     }
449   }
450   return result;
451 }
452 
GetLibCoreDexLocations() const453 std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations() const {
454   std::vector<std::string> modules = GetLibCoreModuleNames();
455   return GetLibCoreDexLocations(modules);
456 }
457 
GetClassPathOption(const char * option,const std::vector<std::string> & class_path)458 std::string CommonArtTestImpl::GetClassPathOption(const char* option,
459                                                   const std::vector<std::string>& class_path) {
460   return option + android::base::Join(class_path, ':');
461 }
462 
463 // Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
464 #ifdef ART_TARGET
465 #ifndef ART_TARGET_NATIVETEST_DIR
466 #error "ART_TARGET_NATIVETEST_DIR not set."
467 #endif
468 // Wrap it as a string literal.
469 #define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
470 #else
471 #define ART_TARGET_NATIVETEST_DIR_STRING ""
472 #endif
473 
GetTestDexFileName(const char * name) const474 std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
475   CHECK(name != nullptr);
476   std::string filename;
477   if (IsHost()) {
478     filename += GetAndroidRoot() + "/framework/";
479   } else {
480     filename += ART_TARGET_NATIVETEST_DIR_STRING;
481   }
482   filename += "art-gtest-";
483   filename += name;
484   filename += ".jar";
485   return filename;
486 }
487 
OpenDexFiles(const char * filename)488 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
489   static constexpr bool kVerify = true;
490   static constexpr bool kVerifyChecksum = true;
491   std::string error_msg;
492   const ArtDexFileLoader dex_file_loader;
493   std::vector<std::unique_ptr<const DexFile>> dex_files;
494   bool success = dex_file_loader.Open(filename,
495                                       filename,
496                                       kVerify,
497                                       kVerifyChecksum,
498                                       &error_msg,
499                                       &dex_files);
500   CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
501   for (auto& dex_file : dex_files) {
502     CHECK_EQ(PROT_READ, dex_file->GetPermissions());
503     CHECK(dex_file->IsReadOnly());
504   }
505   return dex_files;
506 }
507 
OpenDexFile(const char * filename)508 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenDexFile(const char* filename) {
509   std::vector<std::unique_ptr<const DexFile>> dex_files(OpenDexFiles(filename));
510   CHECK_EQ(dex_files.size(), 1u) << "Expected only one dex file";
511   return std::move(dex_files[0]);
512 }
513 
OpenTestDexFiles(const char * name)514 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
515     const char* name) {
516   return OpenDexFiles(GetTestDexFileName(name).c_str());
517 }
518 
OpenTestDexFile(const char * name)519 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
520   return OpenDexFile(GetTestDexFileName(name).c_str());
521 }
522 
GetCoreFileLocation(const char * suffix)523 std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
524   CHECK(suffix != nullptr);
525 
526   std::string location;
527   if (IsHost()) {
528     std::string host_dir = GetAndroidRoot();
529     location = StringPrintf("%s/framework/core.%s", host_dir.c_str(), suffix);
530   } else {
531     location = StringPrintf("/apex/com.android.art/javalib/boot.%s", suffix);
532   }
533 
534   return location;
535 }
536 
CreateClassPath(const std::vector<std::unique_ptr<const DexFile>> & dex_files)537 std::string CommonArtTestImpl::CreateClassPath(
538     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
539   CHECK(!dex_files.empty());
540   std::string classpath = dex_files[0]->GetLocation();
541   for (size_t i = 1; i < dex_files.size(); i++) {
542     classpath += ":" + dex_files[i]->GetLocation();
543   }
544   return classpath;
545 }
546 
CreateClassPathWithChecksums(const std::vector<std::unique_ptr<const DexFile>> & dex_files)547 std::string CommonArtTestImpl::CreateClassPathWithChecksums(
548     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
549   CHECK(!dex_files.empty());
550   std::string classpath = dex_files[0]->GetLocation() + "*" +
551       std::to_string(dex_files[0]->GetLocationChecksum());
552   for (size_t i = 1; i < dex_files.size(); i++) {
553     classpath += ":" + dex_files[i]->GetLocation() + "*" +
554         std::to_string(dex_files[i]->GetLocationChecksum());
555   }
556   return classpath;
557 }
558 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,const OutputHandlerFn & handler)559 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
560     const std::vector<std::string>& argv,
561     const PostForkFn& post_fork,
562     const OutputHandlerFn& handler) {
563   ForkAndExecResult result;
564   result.status_code = 0;
565   result.stage = ForkAndExecResult::kLink;
566 
567   std::vector<const char*> c_args;
568   for (const std::string& str : argv) {
569     c_args.push_back(str.c_str());
570   }
571   c_args.push_back(nullptr);
572 
573   android::base::unique_fd link[2];
574   {
575     int link_fd[2];
576 
577     if (pipe(link_fd) == -1) {
578       return result;
579     }
580     link[0].reset(link_fd[0]);
581     link[1].reset(link_fd[1]);
582   }
583 
584   result.stage = ForkAndExecResult::kFork;
585 
586   pid_t pid = fork();
587   if (pid == -1) {
588     return result;
589   }
590 
591   if (pid == 0) {
592     if (!post_fork()) {
593       LOG(ERROR) << "Failed post-fork function";
594       exit(1);
595       UNREACHABLE();
596     }
597 
598     // Redirect stdout and stderr.
599     dup2(link[1].get(), STDOUT_FILENO);
600     dup2(link[1].get(), STDERR_FILENO);
601 
602     link[0].reset();
603     link[1].reset();
604 
605     execv(c_args[0], const_cast<char* const*>(c_args.data()));
606     exit(1);
607     UNREACHABLE();
608   }
609 
610   result.stage = ForkAndExecResult::kWaitpid;
611   link[1].reset();
612 
613   char buffer[128] = { 0 };
614   ssize_t bytes_read = 0;
615   while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
616     handler(buffer, bytes_read);
617   }
618   handler(buffer, 0u);  // End with a virtual write of zero length to simplify clients.
619 
620   link[0].reset();
621 
622   if (waitpid(pid, &result.status_code, 0) == -1) {
623     return result;
624   }
625 
626   result.stage = ForkAndExecResult::kFinished;
627   return result;
628 }
629 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,std::string * output)630 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
631     const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
632   auto string_collect_fn = [output](char* buf, size_t len) {
633     *output += std::string(buf, len);
634   };
635   return ForkAndExec(argv, post_fork, string_collect_fn);
636 }
637 
638 }  // namespace art
639