blob: 8e634ff5b5b9ae87712a39b8bba02b36b1fa9c5b [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 Srbecky4a88a5a2020-05-05 16:21:57 +010023#include <libgen.h>
David Sehrd5f8de82018-04-27 14:12:03 -070024#include <stdlib.h>
Jiakai Zhang19c766b2022-07-04 14:24:06 +010025#include <sys/capability.h>
Alex Light55153102019-05-08 17:03:10 -070026#include <unistd.h>
Jiakai Zhang5514c8e2021-10-19 05:40:32 +000027
28#include <cstdio>
29#include <filesystem>
Jiakai Zhang19c766b2022-07-04 14:24:06 +010030#include <functional>
Jiakai Zhang5514c8e2021-10-19 05:40:32 +000031
Alex Light55153102019-05-08 17:03:10 -070032#include "android-base/file.h"
33#include "android-base/logging.h"
Jiakai Zhang5514c8e2021-10-19 05:40:32 +000034#include "android-base/process.h"
Jiakai Zhang19c766b2022-07-04 14:24:06 +010035#include "android-base/scopeguard.h"
David Sehrd5f8de82018-04-27 14:12:03 -070036#include "android-base/stringprintf.h"
Vladimir Marko7a85e702018-12-03 18:47:23 +000037#include "android-base/strings.h"
Andreas Gampe38aa0b52018-07-10 23:26:55 -070038#include "android-base/unique_fd.h"
David Sehrd5f8de82018-04-27 14:12:03 -070039#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"
Jiakai Zhang6c68c742022-07-19 18:01:19 +010047#include "base/scoped_cap.h"
David Sehrd5f8de82018-04-27 14:12:03 -070048#include "base/stl_util.h"
David Srbeckye2a9bb72020-09-28 12:24:39 +010049#include "base/string_view_cpp20.h"
Jiakai Zhangd539f862022-02-08 14:56:05 +000050#include "base/testing.h"
David Sehrd5f8de82018-04-27 14:12:03 -070051#include "base/unix_file/fd_file.h"
52#include "dex/art_dex_file_loader.h"
53#include "dex/dex_file-inl.h"
54#include "dex/dex_file_loader.h"
55#include "dex/primitive.h"
56#include "gtest/gtest.h"
Jiakai Zhang5514c8e2021-10-19 05:40:32 +000057#include "nativehelper/scoped_local_ref.h"
David Sehrd5f8de82018-04-27 14:12:03 -070058
59namespace art {
60
61using android::base::StringPrintf;
62
David Srbeckyd6e14e02020-07-01 13:19:17 +010063ScratchDir::ScratchDir(bool keep_files) : keep_files_(keep_files) {
David Srbeckycf0c6ef2020-02-05 16:25:36 +000064 // ANDROID_DATA needs to be set
65 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
66 "Are you subclassing RuntimeTest?";
67 path_ = getenv("ANDROID_DATA");
68 path_ += "/tmp-XXXXXX";
69 bool ok = (mkdtemp(&path_[0]) != nullptr);
70 CHECK(ok) << strerror(errno) << " for " << path_;
71 path_ += "/";
72}
73
74ScratchDir::~ScratchDir() {
David Srbeckyd6e14e02020-07-01 13:19:17 +010075 if (!keep_files_) {
Jiakai Zhang74216032022-09-29 15:53:14 +010076 std::filesystem::remove_all(path_);
David Srbeckyd6e14e02020-07-01 13:19:17 +010077 }
David Srbeckycf0c6ef2020-02-05 16:25:36 +000078}
79
David Sehrd5f8de82018-04-27 14:12:03 -070080ScratchFile::ScratchFile() {
81 // ANDROID_DATA needs to be set
82 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
83 "Are you subclassing RuntimeTest?";
84 filename_ = getenv("ANDROID_DATA");
85 filename_ += "/TmpFile-XXXXXX";
86 int fd = mkstemp(&filename_[0]);
87 CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
88 file_.reset(new File(fd, GetFilename(), true));
89}
90
91ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
92 : ScratchFile(other.GetFilename() + suffix) {}
93
94ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -070095 int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
David Sehrd5f8de82018-04-27 14:12:03 -070096 CHECK_NE(-1, fd);
97 file_.reset(new File(fd, GetFilename(), true));
98}
99
100ScratchFile::ScratchFile(File* file) {
101 CHECK(file != nullptr);
102 filename_ = file->GetPath();
103 file_.reset(file);
104}
105
Andreas Gampe44b31742018-10-01 19:30:57 -0700106ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -0700107 *this = std::move(other);
108}
109
Andreas Gampe44b31742018-10-01 19:30:57 -0700110ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -0700111 if (GetFile() != other.GetFile()) {
112 std::swap(filename_, other.filename_);
113 std::swap(file_, other.file_);
114 }
115 return *this;
116}
117
118ScratchFile::~ScratchFile() {
119 Unlink();
120}
121
122int ScratchFile::GetFd() const {
123 return file_->Fd();
124}
125
126void ScratchFile::Close() {
Vladimir Markoa2209802021-04-23 13:28:29 +0000127 if (file_ != nullptr) {
David Sehrd5f8de82018-04-27 14:12:03 -0700128 if (file_->FlushCloseOrErase() != 0) {
129 PLOG(WARNING) << "Error closing scratch file.";
130 }
Vladimir Markoa2209802021-04-23 13:28:29 +0000131 file_.reset();
David Sehrd5f8de82018-04-27 14:12:03 -0700132 }
133}
134
135void 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
Jiakai Zhang19c766b2022-07-04 14:24:06 +0100144// Temporarily drops all root capabilities when the test is run as root. This is a noop otherwise.
145android::base::ScopeGuard<std::function<void()>> ScopedUnroot() {
146 ScopedCap old_cap(cap_get_proc());
Jiakai Zhang6c68c742022-07-19 18:01:19 +0100147 CHECK_NE(old_cap.Get(), nullptr);
Jiakai Zhang19c766b2022-07-04 14:24:06 +0100148 ScopedCap new_cap(cap_dup(old_cap.Get()));
Jiakai Zhang6c68c742022-07-19 18:01:19 +0100149 CHECK_NE(new_cap.Get(), nullptr);
Jiakai Zhang19c766b2022-07-04 14:24:06 +0100150 CHECK_EQ(cap_clear_flag(new_cap.Get(), CAP_EFFECTIVE), 0);
151 CHECK_EQ(cap_set_proc(new_cap.Get()), 0);
152 // `old_cap` is actually not shared with anyone else, but we have to wrap it with a `shared_ptr`
153 // because `std::function` requires captures to be copyable.
154 return android::base::make_scope_guard(
155 [old_cap = std::make_shared<ScopedCap>(std::move(old_cap))]() {
156 CHECK_EQ(cap_set_proc(old_cap->Get()), 0);
157 });
158}
159
160// Temporarily drops write permission on a file/directory.
161android::base::ScopeGuard<std::function<void()>> ScopedInaccessible(const std::string& path) {
162 std::filesystem::perms old_perms = std::filesystem::status(path).permissions();
163 std::filesystem::permissions(path, std::filesystem::perms::none);
164 return android::base::make_scope_guard([=]() { std::filesystem::permissions(path, old_perms); });
165}
166
David Srbecky194f5552020-07-07 01:10:07 +0100167std::string CommonArtTestImpl::GetAndroidBuildTop() {
168 CHECK(IsHost());
169 std::string android_build_top;
170
171 // Look at how we were invoked to find the expected directory.
172 std::string argv;
173 if (android::base::ReadFileToString("/proc/self/cmdline", &argv)) {
174 // /proc/self/cmdline is the programs 'argv' with elements delimited by '\0'.
175 std::filesystem::path path(argv.substr(0, argv.find('\0')));
176 path = std::filesystem::absolute(path);
177 // Walk up until we find the one of the well-known directories.
178 for (; path.parent_path() != path; path = path.parent_path()) {
179 // We are running tests from out/host/linux-x86 on developer machine.
180 if (path.filename() == std::filesystem::path("linux-x86")) {
181 android_build_top = path.parent_path().parent_path().parent_path();
182 break;
183 }
184 // We are running tests from testcases (extracted from zip) on tradefed.
David Srbeckye2a9bb72020-09-28 12:24:39 +0100185 // The first path is for remote runs and the second path for local runs.
186 if (path.filename() == std::filesystem::path("testcases") ||
187 StartsWith(path.filename().string(), "host_testcases")) {
David Srbecky194f5552020-07-07 01:10:07 +0100188 android_build_top = path.append("art_common");
189 break;
Alex Light55153102019-05-08 17:03:10 -0700190 }
David Sehrd5f8de82018-04-27 14:12:03 -0700191 }
David Srbecky194f5552020-07-07 01:10:07 +0100192 }
193 CHECK(!android_build_top.empty());
194
195 // Check that the expected directory matches the environment variable.
196 const char* android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
Alex Light75c8b632020-07-14 15:31:02 -0700197 android_build_top = std::filesystem::path(android_build_top).string();
198 CHECK(!android_build_top.empty());
David Srbecky194f5552020-07-07 01:10:07 +0100199 if (android_build_top_from_env != nullptr) {
Alex Light1faacf52020-08-31 15:48:25 -0700200 if (std::filesystem::weakly_canonical(android_build_top).string() !=
201 std::filesystem::weakly_canonical(android_build_top_from_env).string()) {
202 LOG(WARNING) << "Execution path (" << argv << ") not below ANDROID_BUILD_TOP ("
203 << android_build_top_from_env << ")! Using env-var.";
204 android_build_top = android_build_top_from_env;
205 }
David Srbecky194f5552020-07-07 01:10:07 +0100206 } else {
207 setenv("ANDROID_BUILD_TOP", android_build_top.c_str(), /*overwrite=*/0);
208 }
209 if (android_build_top.back() != '/') {
210 android_build_top += '/';
211 }
212 return android_build_top;
213}
214
215std::string CommonArtTestImpl::GetAndroidHostOut() {
216 CHECK(IsHost());
David Srbecky194f5552020-07-07 01:10:07 +0100217
218 // Check that the expected directory matches the environment variable.
Alex Light75c8b632020-07-14 15:31:02 -0700219 // ANDROID_HOST_OUT is set by envsetup or unset and is the full path to host binaries/libs
David Srbecky194f5552020-07-07 01:10:07 +0100220 const char* android_host_out_from_env = getenv("ANDROID_HOST_OUT");
Alex Light75c8b632020-07-14 15:31:02 -0700221 // OUT_DIR is a user-settable ENV_VAR that controls where soong puts build artifacts. It can
222 // either be relative to ANDROID_BUILD_TOP or a concrete path.
223 const char* android_out_dir = getenv("OUT_DIR");
224 // Take account of OUT_DIR setting.
225 if (android_out_dir == nullptr) {
226 android_out_dir = "out";
227 }
228 std::string android_host_out;
229 if (android_out_dir[0] == '/') {
230 android_host_out = (std::filesystem::path(android_out_dir) / "host" / "linux-x86").string();
231 } else {
232 android_host_out =
233 (std::filesystem::path(GetAndroidBuildTop()) / android_out_dir / "host" / "linux-x86")
234 .string();
235 }
236 std::filesystem::path expected(android_host_out);
David Srbecky194f5552020-07-07 01:10:07 +0100237 if (android_host_out_from_env != nullptr) {
Alex Light75c8b632020-07-14 15:31:02 -0700238 std::filesystem::path from_env(std::filesystem::weakly_canonical(android_host_out_from_env));
Alex Light27349992020-10-06 15:26:58 -0700239 if (std::filesystem::weakly_canonical(expected).string() != from_env.string()) {
240 LOG(WARNING) << "Execution path (" << expected << ") not below ANDROID_HOST_OUT ("
241 << from_env << ")! Using env-var.";
242 expected = from_env;
243 }
David Srbecky194f5552020-07-07 01:10:07 +0100244 } else {
245 setenv("ANDROID_HOST_OUT", android_host_out.c_str(), /*overwrite=*/0);
246 }
Alex Light75c8b632020-07-14 15:31:02 -0700247 return expected.string();
David Srbecky194f5552020-07-07 01:10:07 +0100248}
249
250void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
251 if (IsHost()) {
252 std::string android_host_out = GetAndroidHostOut();
David Sehrd5f8de82018-04-27 14:12:03 -0700253
Neil Fuller26c43772018-11-23 17:56:43 +0000254 // Environment variable ANDROID_ROOT is set on the device, but not
255 // necessarily on the host.
256 const char* android_root_from_env = getenv("ANDROID_ROOT");
257 if (android_root_from_env == nullptr) {
258 // Use ANDROID_HOST_OUT for ANDROID_ROOT.
David Srbecky194f5552020-07-07 01:10:07 +0100259 setenv("ANDROID_ROOT", android_host_out.c_str(), 1);
Neil Fuller26c43772018-11-23 17:56:43 +0000260 android_root_from_env = getenv("ANDROID_ROOT");
David Sehrd5f8de82018-04-27 14:12:03 -0700261 }
Neil Fuller26c43772018-11-23 17:56:43 +0000262
Victor Chang64611242019-07-05 16:32:41 +0100263 // Environment variable ANDROID_I18N_ROOT is set on the device, but not
264 // necessarily on the host. It needs to be set so that various libraries
265 // like libcore / icu4j / icu4c can find their data files.
266 const char* android_i18n_root_from_env = getenv("ANDROID_I18N_ROOT");
267 if (android_i18n_root_from_env == nullptr) {
268 // Use ${ANDROID_I18N_OUT}/com.android.i18n for ANDROID_I18N_ROOT.
David Srbecky194f5552020-07-07 01:10:07 +0100269 std::string android_i18n_root = android_host_out.c_str();
Victor Chang64611242019-07-05 16:32:41 +0100270 android_i18n_root += "/com.android.i18n";
271 setenv("ANDROID_I18N_ROOT", android_i18n_root.c_str(), 1);
272 }
273
Martin Stjernholme58624f2019-09-20 15:53:40 +0100274 // Environment variable ANDROID_ART_ROOT is set on the device, but not
Neil Fuller26c43772018-11-23 17:56:43 +0000275 // necessarily on the host. It needs to be set so that various libraries
Neil Fuller90ffe122019-06-06 17:25:48 +0100276 // like libcore / icu4j / icu4c can find their data files.
Martin Stjernholme58624f2019-09-20 15:53:40 +0100277 const char* android_art_root_from_env = getenv("ANDROID_ART_ROOT");
278 if (android_art_root_from_env == nullptr) {
279 // Use ${ANDROID_HOST_OUT}/com.android.art for ANDROID_ART_ROOT.
David Srbecky194f5552020-07-07 01:10:07 +0100280 std::string android_art_root = android_host_out.c_str();
Martin Stjernholme58624f2019-09-20 15:53:40 +0100281 android_art_root += "/com.android.art";
282 setenv("ANDROID_ART_ROOT", android_art_root.c_str(), 1);
Neil Fuller26c43772018-11-23 17:56:43 +0000283 }
284
Neil Fuller26a5dd62019-03-13 15:16:35 +0000285 // Environment variable ANDROID_TZDATA_ROOT is set on the device, but not
286 // necessarily on the host. It needs to be set so that various libraries
Neil Fuller90ffe122019-06-06 17:25:48 +0100287 // like libcore / icu4j / icu4c can find their data files.
Neil Fuller26a5dd62019-03-13 15:16:35 +0000288 const char* android_tzdata_root_from_env = getenv("ANDROID_TZDATA_ROOT");
289 if (android_tzdata_root_from_env == nullptr) {
290 // Use ${ANDROID_HOST_OUT}/com.android.tzdata for ANDROID_TZDATA_ROOT.
David Srbecky194f5552020-07-07 01:10:07 +0100291 std::string android_tzdata_root = android_host_out.c_str();
Neil Fuller26a5dd62019-03-13 15:16:35 +0000292 android_tzdata_root += "/com.android.tzdata";
293 setenv("ANDROID_TZDATA_ROOT", android_tzdata_root.c_str(), 1);
294 }
295
Neil Fuller26c43772018-11-23 17:56:43 +0000296 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
David Sehrd5f8de82018-04-27 14:12:03 -0700297 }
298}
299
Neil Fuller26c43772018-11-23 17:56:43 +0000300void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
David Sehrd5f8de82018-04-27 14:12:03 -0700301 if (IsHost()) {
302 const char* tmpdir = getenv("TMPDIR");
303 if (tmpdir != nullptr && tmpdir[0] != 0) {
304 android_data = tmpdir;
305 } else {
306 android_data = "/tmp";
307 }
308 } else {
Roland Levillain7ffab812021-06-30 11:13:19 +0100309 // On target, we cannot use `/mnt/sdcard` because it is mounted `noexec`,
310 // nor `/data/dalvik-cache` as it is not accessible on `user` builds.
311 // Instead, use `/data/local/tmp`, which does not require any special
312 // permission.
313 android_data = "/data/local/tmp";
David Sehrd5f8de82018-04-27 14:12:03 -0700314 }
315 android_data += "/art-data-XXXXXX";
316 if (mkdtemp(&android_data[0]) == nullptr) {
317 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
318 }
319 setenv("ANDROID_DATA", android_data.c_str(), 1);
320}
321
322void CommonArtTestImpl::SetUp() {
Alex Light7302a742021-02-05 09:31:14 -0800323 // Some tests clear these and when running with --no_isolate this can cause
324 // later tests to fail
325 Locks::Init();
326 MemMap::Init();
Neil Fuller26c43772018-11-23 17:56:43 +0000327 SetUpAndroidRootEnvVars();
328 SetUpAndroidDataDir(android_data_);
Chris Gross5477b8e2020-04-24 09:36:45 -0700329
330 // Re-use the data temporary directory for /system_ext tests
331 android_system_ext_.append(android_data_.c_str());
332 android_system_ext_.append("/system_ext");
333 int mkdir_result = mkdir(android_system_ext_.c_str(), 0700);
334 ASSERT_EQ(mkdir_result, 0);
Victor Hsieh5ff45d62022-09-21 10:00:11 -0700335 setenv("SYSTEM_EXT_ROOT", android_system_ext_.c_str(), 1);
Chris Gross5477b8e2020-04-24 09:36:45 -0700336
337 std::string system_ext_framework = android_system_ext_ + "/framework";
338 mkdir_result = mkdir(system_ext_framework.c_str(), 0700);
339 ASSERT_EQ(mkdir_result, 0);
340
David Sehrd5f8de82018-04-27 14:12:03 -0700341 dalvik_cache_.append(android_data_.c_str());
342 dalvik_cache_.append("/dalvik-cache");
Chris Gross5477b8e2020-04-24 09:36:45 -0700343 mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
David Sehrd5f8de82018-04-27 14:12:03 -0700344 ASSERT_EQ(mkdir_result, 0);
Andreas Gampe591b1d22019-06-25 13:08:16 -0700345
Roland Levillainf0409142021-03-22 15:45:03 +0000346 if (kIsDebugBuild) {
347 static bool gSlowDebugTestFlag = false;
348 RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
349 SetRuntimeDebugFlagsEnabled(true);
350 CHECK(gSlowDebugTestFlag);
351 }
David Sehrd5f8de82018-04-27 14:12:03 -0700352}
353
Neil Fuller26c43772018-11-23 17:56:43 +0000354void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
355 bool fail_on_error) {
David Sehrd5f8de82018-04-27 14:12:03 -0700356 if (fail_on_error) {
357 ASSERT_EQ(rmdir(android_data.c_str()), 0);
358 } else {
359 rmdir(android_data.c_str());
360 }
361}
362
David Srbecky194f5552020-07-07 01:10:07 +0100363// Get prebuilt binary tool.
364// The paths need to be updated when Android prebuilts update.
David Srbeckyb461b532020-07-13 17:45:22 +0000365std::string CommonArtTestImpl::GetAndroidTool(const char* name, InstructionSet) {
David Srbeckyc6070922020-07-16 11:06:32 +0100366#ifndef ART_CLANG_PATH
David Srbecky7400a542020-07-09 13:40:57 +0100367 UNUSED(name);
David Srbeckyc6070922020-07-16 11:06:32 +0100368 LOG(FATAL) << "There are no prebuilt tools available.";
David Srbecky7400a542020-07-09 13:40:57 +0100369 UNREACHABLE();
370#else
371 std::string path = GetAndroidBuildTop() + ART_CLANG_PATH + "/bin/";
David Srbecky194f5552020-07-07 01:10:07 +0100372 CHECK(OS::DirectoryExists(path.c_str())) << path;
373 path += name;
374 CHECK(OS::FileExists(path.c_str())) << path;
375 return path;
David Srbecky7400a542020-07-09 13:40:57 +0100376#endif
David Sehrd5f8de82018-04-27 14:12:03 -0700377}
378
379std::string CommonArtTestImpl::GetCoreArtLocation() {
380 return GetCoreFileLocation("art");
381}
382
383std::string CommonArtTestImpl::GetCoreOatLocation() {
384 return GetCoreFileLocation("oat");
385}
386
387std::unique_ptr<const DexFile> CommonArtTestImpl::LoadExpectSingleDexFile(const char* location) {
388 std::vector<std::unique_ptr<const DexFile>> dex_files;
389 std::string error_msg;
390 MemMap::Init();
391 static constexpr bool kVerifyChecksum = true;
392 const ArtDexFileLoader dex_file_loader;
David Srbecky7400a542020-07-09 13:40:57 +0100393 std::string filename(IsHost() ? GetAndroidBuildTop() + location : location);
David Srbecky0c0f3022020-02-13 15:53:01 +0000394 if (!dex_file_loader.Open(filename.c_str(),
395 std::string(location),
396 /* verify= */ true,
397 kVerifyChecksum,
398 &error_msg,
399 &dex_files)) {
400 LOG(FATAL) << "Could not open .dex file '" << filename << "': " << error_msg << "\n";
David Sehrd5f8de82018-04-27 14:12:03 -0700401 UNREACHABLE();
David Sehrd5f8de82018-04-27 14:12:03 -0700402 }
David Srbecky0c0f3022020-02-13 15:53:01 +0000403 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << filename;
404 return std::move(dex_files[0]);
David Sehrd5f8de82018-04-27 14:12:03 -0700405}
406
407void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
408 ASSERT_TRUE(dirpath != nullptr);
409 DIR* dir = opendir(dirpath);
410 ASSERT_TRUE(dir != nullptr);
411 dirent* e;
412 struct stat s;
413 while ((e = readdir(dir)) != nullptr) {
414 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
415 continue;
416 }
417 std::string filename(dirpath);
418 filename.push_back('/');
419 filename.append(e->d_name);
420 int stat_result = lstat(filename.c_str(), &s);
421 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
422 if (S_ISDIR(s.st_mode)) {
423 if (recursive) {
424 ClearDirectory(filename.c_str());
425 int rmdir_result = rmdir(filename.c_str());
426 ASSERT_EQ(0, rmdir_result) << filename;
427 }
428 } else {
429 int unlink_result = unlink(filename.c_str());
430 ASSERT_EQ(0, unlink_result) << filename;
431 }
432 }
433 closedir(dir);
434}
435
436void CommonArtTestImpl::TearDown() {
437 const char* android_data = getenv("ANDROID_DATA");
438 ASSERT_TRUE(android_data != nullptr);
439 ClearDirectory(dalvik_cache_.c_str());
440 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
441 ASSERT_EQ(0, rmdir_cache_result);
Chris Gross5477b8e2020-04-24 09:36:45 -0700442 ClearDirectory(android_system_ext_.c_str(), true);
443 rmdir_cache_result = rmdir(android_system_ext_.c_str());
444 ASSERT_EQ(0, rmdir_cache_result);
Neil Fuller26c43772018-11-23 17:56:43 +0000445 TearDownAndroidDataDir(android_data_, true);
David Sehrd5f8de82018-04-27 14:12:03 -0700446 dalvik_cache_.clear();
Chris Gross5477b8e2020-04-24 09:36:45 -0700447 android_system_ext_.clear();
David Sehrd5f8de82018-04-27 14:12:03 -0700448}
449
Vladimir Markob9c29f62019-03-20 14:22:51 +0000450std::vector<std::string> CommonArtTestImpl::GetLibCoreModuleNames() const {
Jiakai Zhangd539f862022-02-08 14:56:05 +0000451 return art::testing::GetLibCoreModuleNames();
Vladimir Markob9c29f62019-03-20 14:22:51 +0000452}
Vladimir Marko7a85e702018-12-03 18:47:23 +0000453
Vladimir Markob9c29f62019-03-20 14:22:51 +0000454std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames(
455 const std::vector<std::string>& modules) const {
Jiakai Zhangd539f862022-02-08 14:56:05 +0000456 return art::testing::GetLibCoreDexFileNames(modules);
Vladimir Marko7a85e702018-12-03 18:47:23 +0000457}
458
Vladimir Markob9c29f62019-03-20 14:22:51 +0000459std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames() const {
460 std::vector<std::string> modules = GetLibCoreModuleNames();
Jiakai Zhangd539f862022-02-08 14:56:05 +0000461 return art::testing::GetLibCoreDexFileNames(modules);
Vladimir Markob9c29f62019-03-20 14:22:51 +0000462}
463
464std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations(
465 const std::vector<std::string>& modules) const {
466 std::vector<std::string> result = GetLibCoreDexFileNames(modules);
Vladimir Marko7a85e702018-12-03 18:47:23 +0000467 if (IsHost()) {
David Srbeckyd31def52020-03-30 17:57:10 +0100468 // Strip the ANDROID_BUILD_TOP directory including the directory separator '/'.
469 std::string prefix = GetAndroidBuildTop();
Vladimir Marko7a85e702018-12-03 18:47:23 +0000470 for (std::string& location : result) {
471 CHECK_GT(location.size(), prefix.size());
David Srbecky883c1342020-05-11 23:30:29 +0000472 CHECK_EQ(location.compare(0u, prefix.size(), prefix), 0)
473 << " prefix=" << prefix << " location=" << location;
Vladimir Marko7a85e702018-12-03 18:47:23 +0000474 location.erase(0u, prefix.size());
475 }
476 }
477 return result;
478}
479
Vladimir Markob9c29f62019-03-20 14:22:51 +0000480std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations() const {
481 std::vector<std::string> modules = GetLibCoreModuleNames();
482 return GetLibCoreDexLocations(modules);
483}
484
Vladimir Marko7a85e702018-12-03 18:47:23 +0000485std::string CommonArtTestImpl::GetClassPathOption(const char* option,
486 const std::vector<std::string>& class_path) {
487 return option + android::base::Join(class_path, ':');
David Sehrd5f8de82018-04-27 14:12:03 -0700488}
489
David Sehrd5f8de82018-04-27 14:12:03 -0700490// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
491#ifdef ART_TARGET
492#ifndef ART_TARGET_NATIVETEST_DIR
493#error "ART_TARGET_NATIVETEST_DIR not set."
494#endif
495// Wrap it as a string literal.
496#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
497#else
498#define ART_TARGET_NATIVETEST_DIR_STRING ""
499#endif
500
501std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
502 CHECK(name != nullptr);
David Srbecky4a88a5a2020-05-05 16:21:57 +0100503 // The needed jar files for gtest are located next to the gtest binary itself.
Jiakai Zhangd539f862022-02-08 14:56:05 +0000504 std::string executable_dir = android::base::GetExecutableDirectory();
David Srbeckyedda3ca2020-07-08 00:41:08 +0100505 for (auto ext : {".jar", ".dex"}) {
506 std::string path = executable_dir + "/art-gtest-jars-" + name + ext;
507 if (OS::FileExists(path.c_str())) {
508 return path;
509 }
510 }
511 LOG(FATAL) << "Test file " << name << " not found";
512 UNREACHABLE();
David Sehrd5f8de82018-04-27 14:12:03 -0700513}
514
David Sehr7d432422018-05-25 10:49:02 -0700515std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
516 static constexpr bool kVerify = true;
David Sehrd5f8de82018-04-27 14:12:03 -0700517 static constexpr bool kVerifyChecksum = true;
518 std::string error_msg;
519 const ArtDexFileLoader dex_file_loader;
520 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7d432422018-05-25 10:49:02 -0700521 bool success = dex_file_loader.Open(filename,
522 filename,
523 kVerify,
David Sehrd5f8de82018-04-27 14:12:03 -0700524 kVerifyChecksum,
David Sehr7d432422018-05-25 10:49:02 -0700525 &error_msg,
526 &dex_files);
David Sehrd5f8de82018-04-27 14:12:03 -0700527 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
528 for (auto& dex_file : dex_files) {
529 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
530 CHECK(dex_file->IsReadOnly());
531 }
532 return dex_files;
533}
534
Mathieu Chartierc2109c62019-03-20 13:34:39 -0700535std::unique_ptr<const DexFile> CommonArtTestImpl::OpenDexFile(const char* filename) {
536 std::vector<std::unique_ptr<const DexFile>> dex_files(OpenDexFiles(filename));
537 CHECK_EQ(dex_files.size(), 1u) << "Expected only one dex file";
538 return std::move(dex_files[0]);
539}
540
David Sehr7d432422018-05-25 10:49:02 -0700541std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
542 const char* name) {
543 return OpenDexFiles(GetTestDexFileName(name).c_str());
544}
545
David Sehrd5f8de82018-04-27 14:12:03 -0700546std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
Mathieu Chartierc2109c62019-03-20 13:34:39 -0700547 return OpenDexFile(GetTestDexFileName(name).c_str());
David Sehrd5f8de82018-04-27 14:12:03 -0700548}
549
Martin Stjernholm9fde2db2020-10-15 16:03:29 +0100550std::string CommonArtTestImpl::GetImageDirectory() {
Martin Stjernholm9fde2db2020-10-15 16:03:29 +0100551 if (IsHost()) {
552 const char* host_dir = getenv("ANDROID_HOST_OUT");
553 CHECK(host_dir != nullptr);
Jiakai Zhanga3293452022-01-12 20:04:11 +0000554 return std::string(host_dir) + "/apex/art_boot_images/javalib";
Martin Stjernholm9fde2db2020-10-15 16:03:29 +0100555 }
Jiakai Zhangd539f862022-02-08 14:56:05 +0000556 // On device, the boot image is generated by `generate-boot-image`.
557 // In a standalone test, the boot image is located next to the gtest binary itself.
558 std::string path = android::base::GetExecutableDirectory() + "/art_boot_images";
559 if (OS::DirectoryExists(path.c_str())) {
560 return path;
561 }
Jiakai Zhang61c0d222022-02-16 10:28:38 +0000562 // In a chroot environment prepared by scripts, the boot image is located in a predefined
563 // location on /system.
564 path = "/system/framework/art_boot_images";
565 if (OS::DirectoryExists(path.c_str())) {
566 return path;
567 }
568 // In art-target-gtest-chroot, the boot image is located in a predefined location on /data because
569 // /system is a mount point that replicates the real one on device.
Jiakai Zhangd539f862022-02-08 14:56:05 +0000570 path = "/data/local/tmp/art_boot_images";
571 if (OS::DirectoryExists(path.c_str())) {
572 return path;
573 }
574 LOG(FATAL) << "Boot image not found";
575 UNREACHABLE();
Martin Stjernholm9fde2db2020-10-15 16:03:29 +0100576}
577
David Sehrd5f8de82018-04-27 14:12:03 -0700578std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
579 CHECK(suffix != nullptr);
Martin Stjernholm9fde2db2020-10-15 16:03:29 +0100580 return GetImageDirectory() + "/boot." + suffix;
David Sehrd5f8de82018-04-27 14:12:03 -0700581}
582
583std::string CommonArtTestImpl::CreateClassPath(
584 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
585 CHECK(!dex_files.empty());
586 std::string classpath = dex_files[0]->GetLocation();
587 for (size_t i = 1; i < dex_files.size(); i++) {
588 classpath += ":" + dex_files[i]->GetLocation();
589 }
590 return classpath;
591}
592
593std::string CommonArtTestImpl::CreateClassPathWithChecksums(
594 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
595 CHECK(!dex_files.empty());
596 std::string classpath = dex_files[0]->GetLocation() + "*" +
597 std::to_string(dex_files[0]->GetLocationChecksum());
598 for (size_t i = 1; i < dex_files.size(); i++) {
599 classpath += ":" + dex_files[i]->GetLocation() + "*" +
600 std::to_string(dex_files[i]->GetLocationChecksum());
601 }
602 return classpath;
603}
604
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700605CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
606 const std::vector<std::string>& argv,
607 const PostForkFn& post_fork,
608 const OutputHandlerFn& handler) {
609 ForkAndExecResult result;
610 result.status_code = 0;
611 result.stage = ForkAndExecResult::kLink;
612
613 std::vector<const char*> c_args;
Stefano Cianciullid59d4d12023-01-11 11:21:59 +0000614 c_args.reserve(argv.size() + 1);
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700615 for (const std::string& str : argv) {
616 c_args.push_back(str.c_str());
617 }
618 c_args.push_back(nullptr);
619
620 android::base::unique_fd link[2];
621 {
622 int link_fd[2];
623
624 if (pipe(link_fd) == -1) {
625 return result;
626 }
627 link[0].reset(link_fd[0]);
628 link[1].reset(link_fd[1]);
629 }
630
631 result.stage = ForkAndExecResult::kFork;
632
633 pid_t pid = fork();
634 if (pid == -1) {
635 return result;
636 }
637
638 if (pid == 0) {
639 if (!post_fork()) {
640 LOG(ERROR) << "Failed post-fork function";
641 exit(1);
642 UNREACHABLE();
643 }
644
645 // Redirect stdout and stderr.
646 dup2(link[1].get(), STDOUT_FILENO);
647 dup2(link[1].get(), STDERR_FILENO);
648
649 link[0].reset();
650 link[1].reset();
651
652 execv(c_args[0], const_cast<char* const*>(c_args.data()));
653 exit(1);
654 UNREACHABLE();
655 }
656
657 result.stage = ForkAndExecResult::kWaitpid;
658 link[1].reset();
659
660 char buffer[128] = { 0 };
661 ssize_t bytes_read = 0;
662 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
663 handler(buffer, bytes_read);
664 }
665 handler(buffer, 0u); // End with a virtual write of zero length to simplify clients.
666
667 link[0].reset();
668
669 if (waitpid(pid, &result.status_code, 0) == -1) {
670 return result;
671 }
672
673 result.stage = ForkAndExecResult::kFinished;
674 return result;
675}
676
677CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
678 const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
679 auto string_collect_fn = [output](char* buf, size_t len) {
680 *output += std::string(buf, len);
681 };
682 return ForkAndExec(argv, post_fork, string_collect_fn);
683}
684
Jiakai Zhang5514c8e2021-10-19 05:40:32 +0000685std::vector<pid_t> GetPidByName(const std::string& process_name) {
686 std::vector<pid_t> results;
687 for (pid_t pid : android::base::AllPids{}) {
Jiakai Zhangc7ea9b12021-12-24 19:49:51 +0000688 std::string cmdline;
689 if (!android::base::ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline)) {
Jiakai Zhang5514c8e2021-10-19 05:40:32 +0000690 continue;
691 }
Jiakai Zhangc7ea9b12021-12-24 19:49:51 +0000692 // Take the first argument.
693 size_t pos = cmdline.find('\0');
694 if (pos != std::string::npos) {
695 cmdline.resize(pos);
696 }
697 if (cmdline == process_name) {
Jiakai Zhang5514c8e2021-10-19 05:40:32 +0000698 results.push_back(pid);
699 }
700 }
701 return results;
702}
703
David Sehrd5f8de82018-04-27 14:12:03 -0700704} // namespace art