blob: 278203da2356de5e5bc64545ad66d4ba65566114 [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>
22#include <stdlib.h>
23#include <cstdio>
24#include "nativehelper/scoped_local_ref.h"
25
26#include "android-base/stringprintf.h"
Vladimir Marko7a85e702018-12-03 18:47:23 +000027#include "android-base/strings.h"
Andreas Gampe38aa0b52018-07-10 23:26:55 -070028#include "android-base/unique_fd.h"
David Sehrd5f8de82018-04-27 14:12:03 -070029#include <unicode/uvernum.h>
30
31#include "art_field-inl.h"
32#include "base/file_utils.h"
33#include "base/logging.h"
34#include "base/macros.h"
35#include "base/mem_map.h"
36#include "base/mutex.h"
37#include "base/os.h"
38#include "base/runtime_debug.h"
39#include "base/stl_util.h"
40#include "base/unix_file/fd_file.h"
41#include "dex/art_dex_file_loader.h"
42#include "dex/dex_file-inl.h"
43#include "dex/dex_file_loader.h"
44#include "dex/primitive.h"
45#include "gtest/gtest.h"
46
47namespace art {
48
49using android::base::StringPrintf;
50
51ScratchFile::ScratchFile() {
52 // ANDROID_DATA needs to be set
53 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
54 "Are you subclassing RuntimeTest?";
55 filename_ = getenv("ANDROID_DATA");
56 filename_ += "/TmpFile-XXXXXX";
57 int fd = mkstemp(&filename_[0]);
58 CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
59 file_.reset(new File(fd, GetFilename(), true));
60}
61
62ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
63 : ScratchFile(other.GetFilename() + suffix) {}
64
65ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -070066 int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
David Sehrd5f8de82018-04-27 14:12:03 -070067 CHECK_NE(-1, fd);
68 file_.reset(new File(fd, GetFilename(), true));
69}
70
71ScratchFile::ScratchFile(File* file) {
72 CHECK(file != nullptr);
73 filename_ = file->GetPath();
74 file_.reset(file);
75}
76
Andreas Gampe44b31742018-10-01 19:30:57 -070077ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -070078 *this = std::move(other);
79}
80
Andreas Gampe44b31742018-10-01 19:30:57 -070081ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
David Sehrd5f8de82018-04-27 14:12:03 -070082 if (GetFile() != other.GetFile()) {
83 std::swap(filename_, other.filename_);
84 std::swap(file_, other.file_);
85 }
86 return *this;
87}
88
89ScratchFile::~ScratchFile() {
90 Unlink();
91}
92
93int ScratchFile::GetFd() const {
94 return file_->Fd();
95}
96
97void ScratchFile::Close() {
98 if (file_.get() != nullptr) {
99 if (file_->FlushCloseOrErase() != 0) {
100 PLOG(WARNING) << "Error closing scratch file.";
101 }
102 }
103}
104
105void ScratchFile::Unlink() {
106 if (!OS::FileExists(filename_.c_str())) {
107 return;
108 }
109 Close();
110 int unlink_result = unlink(filename_.c_str());
111 CHECK_EQ(0, unlink_result);
112}
113
Neil Fuller26c43772018-11-23 17:56:43 +0000114void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
David Sehrd5f8de82018-04-27 14:12:03 -0700115 if (IsHost()) {
Neil Fuller26c43772018-11-23 17:56:43 +0000116 // Make sure that ANDROID_BUILD_TOP is set. If not, set it from CWD.
117 const char* android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
118 if (android_build_top_from_env == nullptr) {
119 // Not set by build server, so default to current directory.
120 char* cwd = getcwd(nullptr, 0);
121 setenv("ANDROID_BUILD_TOP", cwd, 1);
122 free(cwd);
123 android_build_top_from_env = getenv("ANDROID_BUILD_TOP");
124 }
125
126 const char* android_host_out_from_env = getenv("ANDROID_HOST_OUT");
127 if (android_host_out_from_env == nullptr) {
128 // Not set by build server, so default to the usual value of
129 // ANDROID_HOST_OUT.
130 std::string android_host_out = android_build_top_from_env;
David Sehrd5f8de82018-04-27 14:12:03 -0700131#if defined(__linux__)
Neil Fuller26c43772018-11-23 17:56:43 +0000132 android_host_out += "/out/host/linux-x86";
David Sehrd5f8de82018-04-27 14:12:03 -0700133#elif defined(__APPLE__)
Neil Fuller26c43772018-11-23 17:56:43 +0000134 android_host_out += "/out/host/darwin-x86";
David Sehrd5f8de82018-04-27 14:12:03 -0700135#else
136#error unsupported OS
137#endif
Neil Fuller26c43772018-11-23 17:56:43 +0000138 setenv("ANDROID_HOST_OUT", android_host_out.c_str(), 1);
139 android_host_out_from_env = getenv("ANDROID_HOST_OUT");
David Sehrd5f8de82018-04-27 14:12:03 -0700140 }
David Sehrd5f8de82018-04-27 14:12:03 -0700141
Neil Fuller26c43772018-11-23 17:56:43 +0000142 // Environment variable ANDROID_ROOT is set on the device, but not
143 // necessarily on the host.
144 const char* android_root_from_env = getenv("ANDROID_ROOT");
145 if (android_root_from_env == nullptr) {
146 // Use ANDROID_HOST_OUT for ANDROID_ROOT.
147 setenv("ANDROID_ROOT", android_host_out_from_env, 1);
148 android_root_from_env = getenv("ANDROID_ROOT");
David Sehrd5f8de82018-04-27 14:12:03 -0700149 }
Neil Fuller26c43772018-11-23 17:56:43 +0000150
151 // Environment variable ANDROID_RUNTIME_ROOT is set on the device, but not
152 // necessarily on the host. It needs to be set so that various libraries
153 // like icu4c can find their data files.
154 const char* android_runtime_root_from_env = getenv("ANDROID_RUNTIME_ROOT");
155 if (android_runtime_root_from_env == nullptr) {
156 // Use ${ANDROID_HOST_OUT}/com.android.runtime for ANDROID_RUNTIME_ROOT.
157 std::string android_runtime_root = android_host_out_from_env;
158 android_runtime_root += "/com.android.runtime";
159 setenv("ANDROID_RUNTIME_ROOT", android_runtime_root.c_str(), 1);
160 }
161
162 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
David Sehrd5f8de82018-04-27 14:12:03 -0700163 }
164}
165
Neil Fuller26c43772018-11-23 17:56:43 +0000166void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
David Sehrd5f8de82018-04-27 14:12:03 -0700167 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
168 if (IsHost()) {
169 const char* tmpdir = getenv("TMPDIR");
170 if (tmpdir != nullptr && tmpdir[0] != 0) {
171 android_data = tmpdir;
172 } else {
173 android_data = "/tmp";
174 }
175 } else {
176 android_data = "/data/dalvik-cache";
177 }
178 android_data += "/art-data-XXXXXX";
179 if (mkdtemp(&android_data[0]) == nullptr) {
180 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
181 }
182 setenv("ANDROID_DATA", android_data.c_str(), 1);
183}
184
185void CommonArtTestImpl::SetUp() {
Neil Fuller26c43772018-11-23 17:56:43 +0000186 SetUpAndroidRootEnvVars();
187 SetUpAndroidDataDir(android_data_);
David Sehrd5f8de82018-04-27 14:12:03 -0700188 dalvik_cache_.append(android_data_.c_str());
189 dalvik_cache_.append("/dalvik-cache");
190 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
191 ASSERT_EQ(mkdir_result, 0);
192}
193
Neil Fuller26c43772018-11-23 17:56:43 +0000194void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
195 bool fail_on_error) {
David Sehrd5f8de82018-04-27 14:12:03 -0700196 if (fail_on_error) {
197 ASSERT_EQ(rmdir(android_data.c_str()), 0);
198 } else {
199 rmdir(android_data.c_str());
200 }
201}
202
203// Helper - find directory with the following format:
204// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
205std::string CommonArtTestImpl::GetAndroidToolsDir(const std::string& subdir1,
206 const std::string& subdir2,
207 const std::string& subdir3) {
208 std::string root;
209 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
210 if (android_build_top != nullptr) {
211 root = android_build_top;
212 } else {
213 // Not set by build server, so default to current directory
214 char* cwd = getcwd(nullptr, 0);
215 setenv("ANDROID_BUILD_TOP", cwd, 1);
216 root = cwd;
217 free(cwd);
218 }
219
220 std::string toolsdir = root + "/" + subdir1;
221 std::string founddir;
222 DIR* dir;
223 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
224 float maxversion = 0;
225 struct dirent* entry;
226 while ((entry = readdir(dir)) != nullptr) {
227 std::string format = subdir2 + "-%f";
228 float version;
229 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
230 if (version > maxversion) {
231 maxversion = version;
232 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
233 }
234 }
235 }
236 closedir(dir);
237 }
238
239 if (founddir.empty()) {
240 ADD_FAILURE() << "Cannot find Android tools directory.";
241 }
242 return founddir;
243}
244
245std::string CommonArtTestImpl::GetAndroidHostToolsDir() {
246 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
247 "x86_64-linux-glibc2.15",
248 "x86_64-linux");
249}
250
251std::string CommonArtTestImpl::GetCoreArtLocation() {
252 return GetCoreFileLocation("art");
253}
254
255std::string CommonArtTestImpl::GetCoreOatLocation() {
256 return GetCoreFileLocation("oat");
257}
258
259std::unique_ptr<const DexFile> CommonArtTestImpl::LoadExpectSingleDexFile(const char* location) {
260 std::vector<std::unique_ptr<const DexFile>> dex_files;
261 std::string error_msg;
262 MemMap::Init();
263 static constexpr bool kVerifyChecksum = true;
264 const ArtDexFileLoader dex_file_loader;
265 if (!dex_file_loader.Open(
Andreas Gampe0de385f2018-10-11 11:11:13 -0700266 location, location, /* verify= */ true, kVerifyChecksum, &error_msg, &dex_files)) {
David Sehrd5f8de82018-04-27 14:12:03 -0700267 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
268 UNREACHABLE();
269 } else {
270 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
271 return std::move(dex_files[0]);
272 }
273}
274
275void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
276 ASSERT_TRUE(dirpath != nullptr);
277 DIR* dir = opendir(dirpath);
278 ASSERT_TRUE(dir != nullptr);
279 dirent* e;
280 struct stat s;
281 while ((e = readdir(dir)) != nullptr) {
282 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
283 continue;
284 }
285 std::string filename(dirpath);
286 filename.push_back('/');
287 filename.append(e->d_name);
288 int stat_result = lstat(filename.c_str(), &s);
289 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
290 if (S_ISDIR(s.st_mode)) {
291 if (recursive) {
292 ClearDirectory(filename.c_str());
293 int rmdir_result = rmdir(filename.c_str());
294 ASSERT_EQ(0, rmdir_result) << filename;
295 }
296 } else {
297 int unlink_result = unlink(filename.c_str());
298 ASSERT_EQ(0, unlink_result) << filename;
299 }
300 }
301 closedir(dir);
302}
303
304void CommonArtTestImpl::TearDown() {
305 const char* android_data = getenv("ANDROID_DATA");
306 ASSERT_TRUE(android_data != nullptr);
307 ClearDirectory(dalvik_cache_.c_str());
308 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
309 ASSERT_EQ(0, rmdir_cache_result);
Neil Fuller26c43772018-11-23 17:56:43 +0000310 TearDownAndroidDataDir(android_data_, true);
David Sehrd5f8de82018-04-27 14:12:03 -0700311 dalvik_cache_.clear();
312}
313
314static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
315 std::string path;
316 if (host) {
317 const char* host_dir = getenv("ANDROID_HOST_OUT");
318 CHECK(host_dir != nullptr);
319 path = host_dir;
320 } else {
321 path = GetAndroidRoot();
322 }
323
324 std::string suffix = host
325 ? "-hostdex" // The host version.
326 : "-testdex"; // The unstripped target version.
327
328 return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
329}
330
331std::vector<std::string> CommonArtTestImpl::GetLibCoreDexFileNames() {
Vladimir Marko7a85e702018-12-03 18:47:23 +0000332 // Note: This must match the TEST_CORE_JARS in Android.common_path.mk
333 // because that's what we use for compiling the core.art image.
334 static const char* const kLibcoreModules[] = {
335 "core-oj",
336 "core-libart",
337 "core-simple",
338 "conscrypt",
339 "okhttp",
340 "bouncycastle",
341 };
342
343 std::vector<std::string> result;
344 result.reserve(arraysize(kLibcoreModules));
345 for (const char* module : kLibcoreModules) {
346 result.push_back(GetDexFileName(module, IsHost()));
347 }
348 return result;
349}
350
351std::vector<std::string> CommonArtTestImpl::GetLibCoreDexLocations() {
352 std::vector<std::string> result = GetLibCoreDexFileNames();
353 if (IsHost()) {
354 // Strip the ANDROID_BUILD_TOP directory including the directory separator '/'.
355 const char* host_dir = getenv("ANDROID_BUILD_TOP");
356 CHECK(host_dir != nullptr);
357 std::string prefix = host_dir;
358 CHECK(!prefix.empty());
359 if (prefix.back() != '/') {
360 prefix += '/';
361 }
362 for (std::string& location : result) {
363 CHECK_GT(location.size(), prefix.size());
364 CHECK_EQ(location.compare(0u, prefix.size(), prefix), 0);
365 location.erase(0u, prefix.size());
366 }
367 }
368 return result;
369}
370
371std::string CommonArtTestImpl::GetClassPathOption(const char* option,
372 const std::vector<std::string>& class_path) {
373 return option + android::base::Join(class_path, ':');
David Sehrd5f8de82018-04-27 14:12:03 -0700374}
375
376std::string CommonArtTestImpl::GetTestAndroidRoot() {
377 if (IsHost()) {
378 const char* host_dir = getenv("ANDROID_HOST_OUT");
379 CHECK(host_dir != nullptr);
380 return host_dir;
381 }
382 return GetAndroidRoot();
383}
384
385// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
386#ifdef ART_TARGET
387#ifndef ART_TARGET_NATIVETEST_DIR
388#error "ART_TARGET_NATIVETEST_DIR not set."
389#endif
390// Wrap it as a string literal.
391#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
392#else
393#define ART_TARGET_NATIVETEST_DIR_STRING ""
394#endif
395
396std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
397 CHECK(name != nullptr);
398 std::string filename;
399 if (IsHost()) {
400 filename += getenv("ANDROID_HOST_OUT");
401 filename += "/framework/";
402 } else {
403 filename += ART_TARGET_NATIVETEST_DIR_STRING;
404 }
405 filename += "art-gtest-";
406 filename += name;
407 filename += ".jar";
408 return filename;
409}
410
David Sehr7d432422018-05-25 10:49:02 -0700411std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
412 static constexpr bool kVerify = true;
David Sehrd5f8de82018-04-27 14:12:03 -0700413 static constexpr bool kVerifyChecksum = true;
414 std::string error_msg;
415 const ArtDexFileLoader dex_file_loader;
416 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr7d432422018-05-25 10:49:02 -0700417 bool success = dex_file_loader.Open(filename,
418 filename,
419 kVerify,
David Sehrd5f8de82018-04-27 14:12:03 -0700420 kVerifyChecksum,
David Sehr7d432422018-05-25 10:49:02 -0700421 &error_msg,
422 &dex_files);
David Sehrd5f8de82018-04-27 14:12:03 -0700423 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
424 for (auto& dex_file : dex_files) {
425 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
426 CHECK(dex_file->IsReadOnly());
427 }
428 return dex_files;
429}
430
David Sehr7d432422018-05-25 10:49:02 -0700431std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
432 const char* name) {
433 return OpenDexFiles(GetTestDexFileName(name).c_str());
434}
435
David Sehrd5f8de82018-04-27 14:12:03 -0700436std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
437 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
438 EXPECT_EQ(1U, vector.size());
439 return std::move(vector[0]);
440}
441
442std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
443 CHECK(suffix != nullptr);
444
445 std::string location;
446 if (IsHost()) {
447 const char* host_dir = getenv("ANDROID_HOST_OUT");
448 CHECK(host_dir != nullptr);
449 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
450 } else {
451 location = StringPrintf("/data/art-test/core.%s", suffix);
452 }
453
454 return location;
455}
456
457std::string CommonArtTestImpl::CreateClassPath(
458 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
459 CHECK(!dex_files.empty());
460 std::string classpath = dex_files[0]->GetLocation();
461 for (size_t i = 1; i < dex_files.size(); i++) {
462 classpath += ":" + dex_files[i]->GetLocation();
463 }
464 return classpath;
465}
466
467std::string CommonArtTestImpl::CreateClassPathWithChecksums(
468 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
469 CHECK(!dex_files.empty());
470 std::string classpath = dex_files[0]->GetLocation() + "*" +
471 std::to_string(dex_files[0]->GetLocationChecksum());
472 for (size_t i = 1; i < dex_files.size(); i++) {
473 classpath += ":" + dex_files[i]->GetLocation() + "*" +
474 std::to_string(dex_files[i]->GetLocationChecksum());
475 }
476 return classpath;
477}
478
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700479CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
480 const std::vector<std::string>& argv,
481 const PostForkFn& post_fork,
482 const OutputHandlerFn& handler) {
483 ForkAndExecResult result;
484 result.status_code = 0;
485 result.stage = ForkAndExecResult::kLink;
486
487 std::vector<const char*> c_args;
488 for (const std::string& str : argv) {
489 c_args.push_back(str.c_str());
490 }
491 c_args.push_back(nullptr);
492
493 android::base::unique_fd link[2];
494 {
495 int link_fd[2];
496
497 if (pipe(link_fd) == -1) {
498 return result;
499 }
500 link[0].reset(link_fd[0]);
501 link[1].reset(link_fd[1]);
502 }
503
504 result.stage = ForkAndExecResult::kFork;
505
506 pid_t pid = fork();
507 if (pid == -1) {
508 return result;
509 }
510
511 if (pid == 0) {
512 if (!post_fork()) {
513 LOG(ERROR) << "Failed post-fork function";
514 exit(1);
515 UNREACHABLE();
516 }
517
518 // Redirect stdout and stderr.
519 dup2(link[1].get(), STDOUT_FILENO);
520 dup2(link[1].get(), STDERR_FILENO);
521
522 link[0].reset();
523 link[1].reset();
524
525 execv(c_args[0], const_cast<char* const*>(c_args.data()));
526 exit(1);
527 UNREACHABLE();
528 }
529
530 result.stage = ForkAndExecResult::kWaitpid;
531 link[1].reset();
532
533 char buffer[128] = { 0 };
534 ssize_t bytes_read = 0;
535 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
536 handler(buffer, bytes_read);
537 }
538 handler(buffer, 0u); // End with a virtual write of zero length to simplify clients.
539
540 link[0].reset();
541
542 if (waitpid(pid, &result.status_code, 0) == -1) {
543 return result;
544 }
545
546 result.stage = ForkAndExecResult::kFinished;
547 return result;
548}
549
550CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
551 const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
552 auto string_collect_fn = [output](char* buf, size_t len) {
553 *output += std::string(buf, len);
554 };
555 return ForkAndExec(argv, post_fork, string_collect_fn);
556}
557
David Sehrd5f8de82018-04-27 14:12:03 -0700558} // namespace art