blob: a7675f415bcdd9633707d13f0a85d3d6576ddd8a [file] [log] [blame]
David Sehrd5f8de82018-04-27 14:12:03 -07001/*
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>
David Srbeckycf0c6ef2020-02-05 16:25:36 +000022#include <ftw.h>
David Sehrd5f8de82018-04-27 14:12:03 -070023#include <stdlib.h>
Alex Light55153102019-05-08 17:03:10 -070024#include <unistd.h>
David Sehrd5f8de82018-04-27 14:12:03 -070025#include <cstdio>
Alex Light55153102019-05-08 17:03:10 -070026#include <filesystem>
27#include "android-base/file.h"
28#include "android-base/logging.h"
David Sehrd5f8de82018-04-27 14:12:03 -070029#include "nativehelper/scoped_local_ref.h"
30
31#include "android-base/stringprintf.h"
Vladimir Marko7a85e702018-12-03 18:47:23 +000032#include "android-base/strings.h"
Andreas Gampe38aa0b52018-07-10 23:26:55 -070033#include "android-base/unique_fd.h"
David Sehrd5f8de82018-04-27 14:12:03 -070034
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
51namespace art {
52
53using android::base::StringPrintf;
54
David Srbeckycf0c6ef2020-02-05 16:25:36 +000055ScratchDir::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
66ScratchDir::~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
David Sehrd5f8de82018-04-27 14:12:03 -070078ScratchFile::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
89ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
90 : ScratchFile(other.GetFilename() + suffix) {}
91
92ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -070093 int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
David Sehrd5f8de82018-04-27 14:12:03 -070094 CHECK_NE(-1, fd);
95 file_.reset(new File(fd, GetFilename(), true));
96}
97
98ScratchFile::ScratchFile(File* file) {
99 CHECK(file != nullptr);
100 filename_ = file->GetPath();
101 file_.reset(file);
102}
103
Andreas Gampe44b31742018-10-01 19:30:57 -0700104ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -0700105 *this = std::move(other);
106}
107
Andreas Gampe44b31742018-10-01 19:30:57 -0700108ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -0700109 if (GetFile() != other.GetFile()) {
110 std::swap(filename_, other.filename_);
111 std::swap(file_, other.file_);
112 }
113 return *this;
114}
115
116ScratchFile::~ScratchFile() {
117 Unlink();
118}
119
120int ScratchFile::GetFd() const {
121 return file_->Fd();
122}
123
124void ScratchFile::Close() {
125 if (file_.get() != nullptr) {
126 if (file_->FlushCloseOrErase() != 0) {
127 PLOG(WARNING) << "Error closing scratch file.";
128 }
129 }
130}
131
132void 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
Neil Fuller26c43772018-11-23 17:56:43 +0000141void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
David Sehrd5f8de82018-04-27 14:12:03 -0700142 if (IsHost()) {
Neil Fuller26c43772018-11-23 17:56:43 +0000143 // 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.
Alex Light55153102019-05-08 17:03:10 -0700157 std::string android_host_out;
David Sehrd5f8de82018-04-27 14:12:03 -0700158#if defined(__linux__)
Alex Light55153102019-05-08 17:03:10 -0700159 // 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 }
David Sehrd5f8de82018-04-27 14:12:03 -0700182#elif defined(__APPLE__)
Alex Light55153102019-05-08 17:03:10 -0700183 android_host_out = std::string(android_build_top_from_env) + "/out/host/darwin-x86";
David Sehrd5f8de82018-04-27 14:12:03 -0700184#else
185#error unsupported OS
186#endif
Neil Fuller26c43772018-11-23 17:56:43 +0000187 setenv("ANDROID_HOST_OUT", android_host_out.c_str(), 1);
188 android_host_out_from_env = getenv("ANDROID_HOST_OUT");
David Sehrd5f8de82018-04-27 14:12:03 -0700189 }
David Sehrd5f8de82018-04-27 14:12:03 -0700190
Neil Fuller26c43772018-11-23 17:56:43 +0000191 // 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");
David Sehrd5f8de82018-04-27 14:12:03 -0700198 }
Neil Fuller26c43772018-11-23 17:56:43 +0000199
Victor Chang64611242019-07-05 16:32:41 +0100200 // 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
Martin Stjernholme58624f2019-09-20 15:53:40 +0100211 // Environment variable ANDROID_ART_ROOT is set on the device, but not
Neil Fuller26c43772018-11-23 17:56:43 +0000212 // necessarily on the host. It needs to be set so that various libraries
Neil Fuller90ffe122019-06-06 17:25:48 +0100213 // like libcore / icu4j / icu4c can find their data files.
Martin Stjernholme58624f2019-09-20 15:53:40 +0100214 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);
Neil Fuller26c43772018-11-23 17:56:43 +0000220 }
221
Neil Fuller26a5dd62019-03-13 15:16:35 +0000222 // 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
Neil Fuller90ffe122019-06-06 17:25:48 +0100224 // like libcore / icu4j / icu4c can find their data files.
Neil Fuller26a5dd62019-03-13 15:16:35 +0000225 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
Neil Fuller26c43772018-11-23 17:56:43 +0000233 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
David Sehrd5f8de82018-04-27 14:12:03 -0700234 }
235}
236
Neil Fuller26c43772018-11-23 17:56:43 +0000237void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
David Sehrd5f8de82018-04-27 14:12:03 -0700238 // 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
256void CommonArtTestImpl::SetUp() {
Neil Fuller26c43772018-11-23 17:56:43 +0000257 SetUpAndroidRootEnvVars();
258 SetUpAndroidDataDir(android_data_);
David Sehrd5f8de82018-04-27 14:12:03 -0700259 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);
Andreas Gampe591b1d22019-06-25 13:08:16 -0700263
264 static bool gSlowDebugTestFlag = false;
265 RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
266 SetRuntimeDebugFlagsEnabled(true);
267 CHECK(gSlowDebugTestFlag);
David Sehrd5f8de82018-04-27 14:12:03 -0700268}
269
Neil Fuller26c43772018-11-23 17:56:43 +0000270void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
271 bool fail_on_error) {
David Sehrd5f8de82018-04-27 14:12:03 -0700272 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/
281std::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
321std::string CommonArtTestImpl::GetAndroidHostToolsDir() {
322 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
Nicolas Geoffrayde3e70f2019-02-22 12:07:29 +0000323 "x86_64-linux-glibc2.17",
David Sehrd5f8de82018-04-27 14:12:03 -0700324 "x86_64-linux");
325}
326
327std::string CommonArtTestImpl::GetCoreArtLocation() {
328 return GetCoreFileLocation("art");
329}
330
331std::string CommonArtTestImpl::GetCoreOatLocation() {
332 return GetCoreFileLocation("oat");
333}
334
335std::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;
David Srbecky0c0f3022020-02-13 15:53:01 +0000341 std::string prefix = IsHost() ? GetAndroidRoot() : "";
342 std::string filename = prefix + location;
343 if (!dex_file_loader.Open(filename.c_str(),
344 std::string(location),
345 /* verify= */ true,
346 kVerifyChecksum,
347 &error_msg,
348 &dex_files)) {
349 LOG(FATAL) << "Could not open .dex file '" << filename << "': " << error_msg << "\n";
David Sehrd5f8de82018-04-27 14:12:03 -0700350 UNREACHABLE();
David Sehrd5f8de82018-04-27 14:12:03 -0700351 }
David Srbecky0c0f3022020-02-13 15:53:01 +0000352 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << filename;
353 return std::move(dex_files[0]);
David Sehrd5f8de82018-04-27 14:12:03 -0700354}
355
356void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
357 ASSERT_TRUE(dirpath != nullptr);
358 DIR* dir = opendir(dirpath);
359 ASSERT_TRUE(dir != nullptr);
360 dirent* e;
361 struct stat s;
362 while ((e = readdir(dir)) != nullptr) {
363 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
364 continue;
365 }
366 std::string filename(dirpath);
367 filename.push_back('/');
368 filename.append(e->d_name);
369 int stat_result = lstat(filename.c_str(), &s);
370 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
371 if (S_ISDIR(s.st_mode)) {
372 if (recursive) {
373 ClearDirectory(filename.c_str());
374 int rmdir_result = rmdir(filename.c_str());
375 ASSERT_EQ(0, rmdir_result) << filename;
376 }
377 } else {
378 int unlink_result = unlink(filename.c_str());
379 ASSERT_EQ(0, unlink_result) << filename;
380 }
381 }
382 closedir(dir);
383}
384
385void CommonArtTestImpl::TearDown() {
386 const char* android_data = getenv("ANDROID_DATA");
387 ASSERT_TRUE(android_data != nullptr);
388 ClearDirectory(dalvik_cache_.c_str());
389 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
390 ASSERT_EQ(0, rmdir_cache_result);
Neil Fuller26c43772018-11-23 17:56:43 +0000391 TearDownAndroidDataDir(android_data_, true);
David Sehrd5f8de82018-04-27 14:12:03 -0700392 dalvik_cache_.clear();
393}
394
395static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
David Srbecky0c0f3022020-02-13 15:53:01 +0000396 std::string prefix(host ? GetAndroidRoot() : "");
397 const char* apexPath = (jar_prefix == "conscrypt")
398 ? kAndroidConscryptApexDefaultPath
399 : kAndroidArtApexDefaultPath;
400 return StringPrintf("%s%s/javalib/%s.jar", prefix.c_str(), apexPath, jar_prefix.c_str());
David Sehrd5f8de82018-04-27 14:12:03 -0700401}
402
Vladimir Markob9c29f62019-03-20 14:22:51 +0000403std::vector<std::string> CommonArtTestImpl::GetLibCoreModuleNames() const {
Vladimir Marko0ace5632018-12-14 11:11:47 +0000404 // Note: This must start with the CORE_IMG_JARS in Android.common_path.mk
Vladimir Marko7a85e702018-12-03 18:47:23 +0000405 // because that's what we use for compiling the core.art image.
Vladimir Marko0ace5632018-12-14 11:11:47 +0000406 // It may contain additional modules from TEST_CORE_JARS.
Vladimir Markob9c29f62019-03-20 14:22:51 +0000407 return {
Vladimir Marko0ace5632018-12-14 11:11:47 +0000408 // CORE_IMG_JARS modules.
Vladimir Marko7a85e702018-12-03 18:47:23 +0000409 "core-oj",
410 "core-libart",
Victor Chang759845f2019-08-06 16:04:36 +0100411 "core-icu4j",
Vladimir Marko7a85e702018-12-03 18:47:23 +0000412 "okhttp",
413 "bouncycastle",
Vladimir Markoea65b212018-12-13 13:32:13 +0000414 "apache-xml",
Vladimir Marko0ace5632018-12-14 11:11:47 +0000415 // Additional modules.
416 "conscrypt",
Vladimir Marko7a85e702018-12-03 18:47:23 +0000417 };
Vladimir Markob9c29f62019-03-20 14:22:51 +0000418}
Vladimir Marko7a85e702018-12-03 18:47:23 +0000419
Vladimir Markob9c29f62019-03-20 14:22:51 +0000420std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames(
421 const std::vector<std::string>& modules) const {
Vladimir Marko7a85e702018-12-03 18:47:23 +0000422 std::vector<std::string> result;
Vladimir Markob9c29f62019-03-20 14:22:51 +0000423 result.reserve(modules.size());
424 for (const std::string& module : modules) {
Vladimir Marko7a85e702018-12-03 18:47:23 +0000425 result.push_back(GetDexFileName(module, IsHost()));
426 }
427 return result;
428}
429
Vladimir Markob9c29f62019-03-20 14:22:51 +0000430std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames() const {
431 std::vector<std::string> modules = GetLibCoreModuleNames();
432 return GetLibCoreDexFileNames(modules);
433}
434
435std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations(
436 const std::vector<std::string>& modules) const {
437 std::vector<std::string> result = GetLibCoreDexFileNames(modules);
Vladimir Marko7a85e702018-12-03 18:47:23 +0000438 if (IsHost()) {
David Srbecky0c0f3022020-02-13 15:53:01 +0000439 // Strip the build directory prefix (e.g. .../host/linux-x86)
440 std::string prefix = GetAndroidRoot();
Vladimir Marko7a85e702018-12-03 18:47:23 +0000441 for (std::string& location : result) {
442 CHECK_GT(location.size(), prefix.size());
443 CHECK_EQ(location.compare(0u, prefix.size(), prefix), 0);
444 location.erase(0u, prefix.size());
445 }
446 }
447 return result;
448}
449
Vladimir Markob9c29f62019-03-20 14:22:51 +0000450std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations() const {
451 std::vector<std::string> modules = GetLibCoreModuleNames();
452 return GetLibCoreDexLocations(modules);
453}
454
Vladimir Marko7a85e702018-12-03 18:47:23 +0000455std::string CommonArtTestImpl::GetClassPathOption(const char* option,
456 const std::vector<std::string>& class_path) {
457 return option + android::base::Join(class_path, ':');
David Sehrd5f8de82018-04-27 14:12:03 -0700458}
459
David Sehrd5f8de82018-04-27 14:12:03 -0700460// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
461#ifdef ART_TARGET
462#ifndef ART_TARGET_NATIVETEST_DIR
463#error "ART_TARGET_NATIVETEST_DIR not set."
464#endif
465// Wrap it as a string literal.
466#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
467#else
468#define ART_TARGET_NATIVETEST_DIR_STRING ""
469#endif
470
471std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
472 CHECK(name != nullptr);
473 std::string filename;
474 if (IsHost()) {
Roland Levillaindd8e2222019-04-05 15:31:55 +0100475 filename += GetAndroidRoot() + "/framework/";
David Sehrd5f8de82018-04-27 14:12:03 -0700476 } else {
477 filename += ART_TARGET_NATIVETEST_DIR_STRING;
478 }
479 filename += "art-gtest-";
480 filename += name;
481 filename += ".jar";
482 return filename;
483}
484
David Sehr7d432422018-05-25 10:49:02 -0700485std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
486 static constexpr bool kVerify = true;
David Sehrd5f8de82018-04-27 14:12:03 -0700487 static constexpr bool kVerifyChecksum = true;
488 std::string error_msg;
489 const ArtDexFileLoader dex_file_loader;
490 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7d432422018-05-25 10:49:02 -0700491 bool success = dex_file_loader.Open(filename,
492 filename,
493 kVerify,
David Sehrd5f8de82018-04-27 14:12:03 -0700494 kVerifyChecksum,
David Sehr7d432422018-05-25 10:49:02 -0700495 &error_msg,
496 &dex_files);
David Sehrd5f8de82018-04-27 14:12:03 -0700497 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
498 for (auto& dex_file : dex_files) {
499 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
500 CHECK(dex_file->IsReadOnly());
501 }
502 return dex_files;
503}
504
Mathieu Chartierc2109c62019-03-20 13:34:39 -0700505std::unique_ptr<const DexFile> CommonArtTestImpl::OpenDexFile(const char* filename) {
506 std::vector<std::unique_ptr<const DexFile>> dex_files(OpenDexFiles(filename));
507 CHECK_EQ(dex_files.size(), 1u) << "Expected only one dex file";
508 return std::move(dex_files[0]);
509}
510
David Sehr7d432422018-05-25 10:49:02 -0700511std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
512 const char* name) {
513 return OpenDexFiles(GetTestDexFileName(name).c_str());
514}
515
David Sehrd5f8de82018-04-27 14:12:03 -0700516std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
Mathieu Chartierc2109c62019-03-20 13:34:39 -0700517 return OpenDexFile(GetTestDexFileName(name).c_str());
David Sehrd5f8de82018-04-27 14:12:03 -0700518}
519
520std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
521 CHECK(suffix != nullptr);
David Srbecky0c0f3022020-02-13 15:53:01 +0000522 std::string prefix(IsHost() ? GetAndroidRoot() : "");
523 return StringPrintf("%s%s/javalib/boot.%s", prefix.c_str(), kAndroidArtApexDefaultPath, suffix);
David Sehrd5f8de82018-04-27 14:12:03 -0700524}
525
526std::string CommonArtTestImpl::CreateClassPath(
527 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
528 CHECK(!dex_files.empty());
529 std::string classpath = dex_files[0]->GetLocation();
530 for (size_t i = 1; i < dex_files.size(); i++) {
531 classpath += ":" + dex_files[i]->GetLocation();
532 }
533 return classpath;
534}
535
536std::string CommonArtTestImpl::CreateClassPathWithChecksums(
537 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
538 CHECK(!dex_files.empty());
539 std::string classpath = dex_files[0]->GetLocation() + "*" +
540 std::to_string(dex_files[0]->GetLocationChecksum());
541 for (size_t i = 1; i < dex_files.size(); i++) {
542 classpath += ":" + dex_files[i]->GetLocation() + "*" +
543 std::to_string(dex_files[i]->GetLocationChecksum());
544 }
545 return classpath;
546}
547
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700548CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
549 const std::vector<std::string>& argv,
550 const PostForkFn& post_fork,
551 const OutputHandlerFn& handler) {
552 ForkAndExecResult result;
553 result.status_code = 0;
554 result.stage = ForkAndExecResult::kLink;
555
556 std::vector<const char*> c_args;
557 for (const std::string& str : argv) {
558 c_args.push_back(str.c_str());
559 }
560 c_args.push_back(nullptr);
561
562 android::base::unique_fd link[2];
563 {
564 int link_fd[2];
565
566 if (pipe(link_fd) == -1) {
567 return result;
568 }
569 link[0].reset(link_fd[0]);
570 link[1].reset(link_fd[1]);
571 }
572
573 result.stage = ForkAndExecResult::kFork;
574
575 pid_t pid = fork();
576 if (pid == -1) {
577 return result;
578 }
579
580 if (pid == 0) {
581 if (!post_fork()) {
582 LOG(ERROR) << "Failed post-fork function";
583 exit(1);
584 UNREACHABLE();
585 }
586
587 // Redirect stdout and stderr.
588 dup2(link[1].get(), STDOUT_FILENO);
589 dup2(link[1].get(), STDERR_FILENO);
590
591 link[0].reset();
592 link[1].reset();
593
594 execv(c_args[0], const_cast<char* const*>(c_args.data()));
595 exit(1);
596 UNREACHABLE();
597 }
598
599 result.stage = ForkAndExecResult::kWaitpid;
600 link[1].reset();
601
602 char buffer[128] = { 0 };
603 ssize_t bytes_read = 0;
604 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
605 handler(buffer, bytes_read);
606 }
607 handler(buffer, 0u); // End with a virtual write of zero length to simplify clients.
608
609 link[0].reset();
610
611 if (waitpid(pid, &result.status_code, 0) == -1) {
612 return result;
613 }
614
615 result.stage = ForkAndExecResult::kFinished;
616 return result;
617}
618
619CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
620 const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
621 auto string_collect_fn = [output](char* buf, size_t len) {
622 *output += std::string(buf, len);
623 };
624 return ForkAndExec(argv, post_fork, string_collect_fn);
625}
626
David Sehrd5f8de82018-04-27 14:12:03 -0700627} // namespace art