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