blob: f58af5a8daf25fea7fec48446edd318da6c6ee0a [file] [log] [blame]
Elliott Hugheseb02a122012-06-12 11:35:40 -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
Ian Rogerse63db272014-07-15 15:36:11 -070017#include "common_runtime_test.h"
18
David Srbecky3e52aa42015-04-12 07:45:18 +010019#include <cstdio>
Ian Rogerse63db272014-07-15 15:36:11 -070020#include <dirent.h>
21#include <dlfcn.h>
22#include <fcntl.h>
23#include <ScopedLocalRef.h>
Andreas Gampe369810a2015-01-14 19:53:31 -080024#include <stdlib.h>
Ian Rogerse63db272014-07-15 15:36:11 -070025
26#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "art_field-inl.h"
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -070028#include "base/macros.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Ian Rogerse63db272014-07-15 15:36:11 -070030#include "base/stl_util.h"
31#include "base/stringprintf.h"
32#include "base/unix_file/fd_file.h"
33#include "class_linker.h"
34#include "compiler_callbacks.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070036#include "gc_root-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070037#include "gc/heap.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070038#include "gtest/gtest.h"
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070039#include "handle_scope-inl.h"
Andreas Gampe9b5cba42015-03-11 09:53:50 -070040#include "interpreter/unstarted_runtime.h"
Ian Rogerse63db272014-07-15 15:36:11 -070041#include "jni_internal.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070042#include "mirror/class-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070043#include "mirror/class_loader.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080044#include "mem_map.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070045#include "native/dalvik_system_DexFile.h"
Ian Rogerse63db272014-07-15 15:36:11 -070046#include "noop_compiler_callbacks.h"
47#include "os.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "primitive.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "runtime-inl.h"
50#include "scoped_thread_state_change.h"
51#include "thread.h"
52#include "well_known_classes.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070053
54int main(int argc, char **argv) {
Andreas Gampe369810a2015-01-14 19:53:31 -080055 // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
56 // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
57 // everything else. In case you want to see all messages, comment out the line.
Nicolas Geoffraya7a47592015-11-24 09:17:30 +000058 setenv("ANDROID_LOG_TAGS", "*:e", 1);
Andreas Gampe369810a2015-01-14 19:53:31 -080059
Elliott Hugheseb02a122012-06-12 11:35:40 -070060 art::InitLogging(argv);
Ian Rogersc7dd2952014-10-21 23:31:19 -070061 LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070062 testing::InitGoogleTest(&argc, argv);
63 return RUN_ALL_TESTS();
64}
Ian Rogerse63db272014-07-15 15:36:11 -070065
66namespace art {
67
68ScratchFile::ScratchFile() {
69 // ANDROID_DATA needs to be set
70 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
71 "Are you subclassing RuntimeTest?";
72 filename_ = getenv("ANDROID_DATA");
73 filename_ += "/TmpFile-XXXXXX";
74 int fd = mkstemp(&filename_[0]);
Andreas Gampe29d38e72016-03-23 15:31:51 +000075 CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
Andreas Gampe4303ba92014-11-06 01:00:46 -080076 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070077}
78
79ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
80 filename_ = other.GetFilename();
81 filename_ += suffix;
82 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
83 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080084 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070085}
86
87ScratchFile::ScratchFile(File* file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 CHECK(file != nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -070089 filename_ = file->GetPath();
90 file_.reset(file);
91}
92
93ScratchFile::~ScratchFile() {
94 Unlink();
95}
96
97int ScratchFile::GetFd() const {
98 return file_->Fd();
99}
100
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800101void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800102 if (file_.get() != nullptr) {
103 if (file_->FlushCloseOrErase() != 0) {
104 PLOG(WARNING) << "Error closing scratch file.";
105 }
106 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800107}
108
109void ScratchFile::Unlink() {
110 if (!OS::FileExists(filename_.c_str())) {
111 return;
112 }
113 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700114 int unlink_result = unlink(filename_.c_str());
115 CHECK_EQ(0, unlink_result);
116}
117
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700118static bool unstarted_initialized_ = false;
119
Mathieu Chartier91c91162016-01-15 09:48:15 -0800120CommonRuntimeTestImpl::CommonRuntimeTestImpl() {}
121
122CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800123 // Ensure the dex files are cleaned up before the runtime.
124 loaded_dex_files_.clear();
125 runtime_.reset();
126}
Ian Rogerse63db272014-07-15 15:36:11 -0700127
Mathieu Chartier91c91162016-01-15 09:48:15 -0800128void CommonRuntimeTestImpl::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700129 if (IsHost()) {
130 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
131 // But it needs to be set so that icu4c can find its locale data.
132 const char* android_root_from_env = getenv("ANDROID_ROOT");
133 if (android_root_from_env == nullptr) {
134 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
135 const char* android_host_out = getenv("ANDROID_HOST_OUT");
136 if (android_host_out != nullptr) {
137 setenv("ANDROID_ROOT", android_host_out, 1);
138 } else {
139 // Build it from ANDROID_BUILD_TOP or cwd
140 std::string root;
141 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
142 if (android_build_top != nullptr) {
143 root += android_build_top;
144 } else {
145 // Not set by build server, so default to current directory
146 char* cwd = getcwd(nullptr, 0);
147 setenv("ANDROID_BUILD_TOP", cwd, 1);
148 root += cwd;
149 free(cwd);
150 }
151#if defined(__linux__)
152 root += "/out/host/linux-x86";
153#elif defined(__APPLE__)
154 root += "/out/host/darwin-x86";
155#else
156#error unsupported OS
157#endif
158 setenv("ANDROID_ROOT", root.c_str(), 1);
159 }
160 }
161 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
162
163 // Not set by build server, so default
164 if (getenv("ANDROID_HOST_OUT") == nullptr) {
165 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
166 }
167 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700168}
Ian Rogerse63db272014-07-15 15:36:11 -0700169
Mathieu Chartier91c91162016-01-15 09:48:15 -0800170void CommonRuntimeTestImpl::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700171 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700172 if (IsHost()) {
173 const char* tmpdir = getenv("TMPDIR");
174 if (tmpdir != nullptr && tmpdir[0] != 0) {
175 android_data = tmpdir;
176 } else {
177 android_data = "/tmp";
178 }
179 } else {
180 android_data = "/data/dalvik-cache";
181 }
182 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700183 if (mkdtemp(&android_data[0]) == nullptr) {
184 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
185 }
186 setenv("ANDROID_DATA", android_data.c_str(), 1);
187}
188
Mathieu Chartier91c91162016-01-15 09:48:15 -0800189void CommonRuntimeTestImpl::TearDownAndroidData(const std::string& android_data,
190 bool fail_on_error) {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700191 if (fail_on_error) {
192 ASSERT_EQ(rmdir(android_data.c_str()), 0);
193 } else {
194 rmdir(android_data.c_str());
195 }
196}
197
David Srbecky3e52aa42015-04-12 07:45:18 +0100198// Helper - find directory with the following format:
199// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
200static std::string GetAndroidToolsDir(const std::string& subdir1,
201 const std::string& subdir2,
202 const std::string& subdir3) {
203 std::string root;
204 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
205 if (android_build_top != nullptr) {
206 root = android_build_top;
207 } else {
208 // Not set by build server, so default to current directory
209 char* cwd = getcwd(nullptr, 0);
210 setenv("ANDROID_BUILD_TOP", cwd, 1);
211 root = cwd;
212 free(cwd);
213 }
214
215 std::string toolsdir = root + "/" + subdir1;
216 std::string founddir;
217 DIR* dir;
218 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
219 float maxversion = 0;
220 struct dirent* entry;
221 while ((entry = readdir(dir)) != nullptr) {
222 std::string format = subdir2 + "-%f";
223 float version;
224 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
225 if (version > maxversion) {
226 maxversion = version;
227 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
228 }
229 }
230 }
231 closedir(dir);
232 }
233
234 if (founddir.empty()) {
Roland Levillain91d65e02016-01-19 15:59:16 +0000235 ADD_FAILURE() << "Cannot find Android tools directory.";
David Srbecky3e52aa42015-04-12 07:45:18 +0100236 }
237 return founddir;
238}
239
Mathieu Chartier91c91162016-01-15 09:48:15 -0800240std::string CommonRuntimeTestImpl::GetAndroidHostToolsDir() {
David Srbecky3e52aa42015-04-12 07:45:18 +0100241 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
242 "x86_64-linux-glibc2.15",
243 "x86_64-linux");
244}
245
Mathieu Chartier91c91162016-01-15 09:48:15 -0800246std::string CommonRuntimeTestImpl::GetAndroidTargetToolsDir(InstructionSet isa) {
David Srbecky3e52aa42015-04-12 07:45:18 +0100247 switch (isa) {
248 case kArm:
249 case kThumb2:
250 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
251 "arm-linux-androideabi",
252 "arm-linux-androideabi");
253 case kArm64:
254 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
255 "aarch64-linux-android",
256 "aarch64-linux-android");
257 case kX86:
258 case kX86_64:
259 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
260 "x86_64-linux-android",
261 "x86_64-linux-android");
262 case kMips:
263 case kMips64:
264 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
265 "mips64el-linux-android",
266 "mips64el-linux-android");
267 case kNone:
268 break;
269 }
270 ADD_FAILURE() << "Invalid isa " << isa;
271 return "";
272}
273
Mathieu Chartier91c91162016-01-15 09:48:15 -0800274std::string CommonRuntimeTestImpl::GetCoreArtLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800275 return GetCoreFileLocation("art");
276}
277
Mathieu Chartier91c91162016-01-15 09:48:15 -0800278std::string CommonRuntimeTestImpl::GetCoreOatLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800279 return GetCoreFileLocation("oat");
280}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700281
Mathieu Chartier91c91162016-01-15 09:48:15 -0800282std::unique_ptr<const DexFile> CommonRuntimeTestImpl::LoadExpectSingleDexFile(
283 const char* location) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800284 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700285 std::string error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800286 MemMap::Init();
Ian Rogerse63db272014-07-15 15:36:11 -0700287 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
288 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700290 } else {
291 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800292 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700293 }
294}
295
Mathieu Chartier91c91162016-01-15 09:48:15 -0800296void CommonRuntimeTestImpl::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700297 SetUpAndroidRoot();
298 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700299 dalvik_cache_.append(android_data_.c_str());
300 dalvik_cache_.append("/dalvik-cache");
301 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
302 ASSERT_EQ(mkdir_result, 0);
303
Ian Rogerse63db272014-07-15 15:36:11 -0700304 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
305 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
306
Ian Rogerse63db272014-07-15 15:36:11 -0700307
308 RuntimeOptions options;
Narayan Kamathd1ef4362015-11-12 11:49:06 +0000309 std::string boot_class_path_string = "-Xbootclasspath";
310 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
311 boot_class_path_string += ":";
312 boot_class_path_string += core_dex_file_name;
313 }
314
Richard Uhlerc2752592015-01-02 13:28:22 -0800315 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700316 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800317 options.push_back(std::make_pair(min_heap_string, nullptr));
318 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700319
320 callbacks_.reset(new NoopCompilerCallbacks());
321
Ian Rogerse63db272014-07-15 15:36:11 -0700322 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800323
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700324 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
325 if (callbacks_.get() != nullptr) {
326 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
327 }
328
Richard Uhler66d874d2015-01-15 09:37:19 -0800329 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700330 if (!Runtime::Create(options, false)) {
331 LOG(FATAL) << "Failed to create runtime";
332 return;
333 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800334 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700335 runtime_.reset(Runtime::Current());
336 class_linker_ = runtime_->GetClassLinker();
337 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700338
Andreas Gampea00f0122015-12-16 16:54:35 -0800339 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
340 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
341 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
342
343 // Get the boot class path from the runtime so it can be used in tests.
344 boot_class_path_ = class_linker_->GetBootClassPath();
345 ASSERT_FALSE(boot_class_path_.empty());
346 java_lang_dex_file_ = boot_class_path_[0];
347
348 FinalizeSetup();
349}
350
Mathieu Chartier91c91162016-01-15 09:48:15 -0800351void CommonRuntimeTestImpl::FinalizeSetup() {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700352 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
353 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700354 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700355 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700356 unstarted_initialized_ = true;
357 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700358
Andreas Gampea00f0122015-12-16 16:54:35 -0800359 {
360 ScopedObjectAccess soa(Thread::Current());
361 class_linker_->RunRootClinits();
362 }
Ian Rogerse63db272014-07-15 15:36:11 -0700363
364 // We're back in native, take the opportunity to initialize well known classes.
365 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
366
367 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
368 // pool is created by the runtime.
369 runtime_->GetHeap()->CreateThreadPool();
370 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700371 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
372 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Ian Rogerse63db272014-07-15 15:36:11 -0700373}
374
Mathieu Chartier91c91162016-01-15 09:48:15 -0800375void CommonRuntimeTestImpl::ClearDirectory(const char* dirpath) {
Alex Lighta59dd802014-07-02 16:28:08 -0700376 ASSERT_TRUE(dirpath != nullptr);
377 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700378 ASSERT_TRUE(dir != nullptr);
379 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700380 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700381 while ((e = readdir(dir)) != nullptr) {
382 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
383 continue;
384 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700385 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700386 filename.push_back('/');
387 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700388 int stat_result = lstat(filename.c_str(), &s);
389 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
390 if (S_ISDIR(s.st_mode)) {
391 ClearDirectory(filename.c_str());
392 int rmdir_result = rmdir(filename.c_str());
393 ASSERT_EQ(0, rmdir_result) << filename;
394 } else {
395 int unlink_result = unlink(filename.c_str());
396 ASSERT_EQ(0, unlink_result) << filename;
397 }
Ian Rogerse63db272014-07-15 15:36:11 -0700398 }
399 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700400}
401
Mathieu Chartier91c91162016-01-15 09:48:15 -0800402void CommonRuntimeTestImpl::TearDown() {
Alex Lighta59dd802014-07-02 16:28:08 -0700403 const char* android_data = getenv("ANDROID_DATA");
404 ASSERT_TRUE(android_data != nullptr);
405 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700406 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
407 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700408 TearDownAndroidData(android_data_, true);
Andreas Gampe3f41a012016-02-18 16:53:41 -0800409 dalvik_cache_.clear();
Ian Rogerse63db272014-07-15 15:36:11 -0700410
411 // icu4c has a fixed 10-element array "gCommonICUDataArray".
412 // If we run > 10 tests, we fill that array and u_setCommonData fails.
413 // There's a function to clear the array, but it's not public...
414 typedef void (*IcuCleanupFn)();
415 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
416 CHECK(sym != nullptr) << dlerror();
417 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
418 (*icu_cleanup_fn)();
419
Ian Rogerse63db272014-07-15 15:36:11 -0700420 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
Mathieu Chartier73ad16e2016-05-10 17:31:48 -0700421
422 // Manually closing the JNI libraries.
423 // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
424 // dynamic linking loader so that gtests would not fail.
425 // Bug: 25785594
426 if (runtime_->IsStarted()) {
427 {
428 // We retrieve the handle by calling dlopen on the library. To close it, we need to call
429 // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
430 // See man dlopen.
431 void* handle = dlopen("libjavacore.so", RTLD_LAZY);
432 dlclose(handle);
433 CHECK_EQ(0, dlclose(handle));
434 }
435 {
436 void* handle = dlopen("libopenjdkd.so", RTLD_LAZY);
437 dlclose(handle);
438 CHECK_EQ(0, dlclose(handle));
439 }
440 }
Ian Rogerse63db272014-07-15 15:36:11 -0700441}
442
Andreas Gampec7d4a582015-09-30 11:52:02 -0700443static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
444 std::string path;
445 if (host) {
Ian Rogerse63db272014-07-15 15:36:11 -0700446 const char* host_dir = getenv("ANDROID_HOST_OUT");
447 CHECK(host_dir != nullptr);
Andreas Gampec7d4a582015-09-30 11:52:02 -0700448 path = host_dir;
449 } else {
450 path = GetAndroidRoot();
Ian Rogerse63db272014-07-15 15:36:11 -0700451 }
Andreas Gampec7d4a582015-09-30 11:52:02 -0700452
453 std::string suffix = host
454 ? "-hostdex" // The host version.
455 : "-testdex"; // The unstripped target version.
456
457 return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
458}
459
Mathieu Chartier91c91162016-01-15 09:48:15 -0800460std::vector<std::string> CommonRuntimeTestImpl::GetLibCoreDexFileNames() {
Andreas Gampec7d4a582015-09-30 11:52:02 -0700461 return std::vector<std::string>({GetDexFileName("core-oj", IsHost()),
462 GetDexFileName("core-libart", IsHost())});
Ian Rogerse63db272014-07-15 15:36:11 -0700463}
464
Mathieu Chartier91c91162016-01-15 09:48:15 -0800465std::string CommonRuntimeTestImpl::GetTestAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700466 if (IsHost()) {
467 const char* host_dir = getenv("ANDROID_HOST_OUT");
468 CHECK(host_dir != nullptr);
469 return host_dir;
470 }
471 return GetAndroidRoot();
472}
473
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700474// 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
Mathieu Chartier91c91162016-01-15 09:48:15 -0800485std::string CommonRuntimeTestImpl::GetTestDexFileName(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700486 CHECK(name != nullptr);
487 std::string filename;
488 if (IsHost()) {
489 filename += getenv("ANDROID_HOST_OUT");
490 filename += "/framework/";
491 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700492 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700493 }
494 filename += "art-gtest-";
495 filename += name;
496 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800497 return filename;
498}
499
Mathieu Chartier91c91162016-01-15 09:48:15 -0800500std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTestImpl::OpenTestDexFiles(
501 const char* name) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800502 std::string filename = GetTestDexFileName(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700503 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800504 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700505 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
506 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800507 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700508 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
509 CHECK(dex_file->IsReadOnly());
510 }
Ian Rogerse63db272014-07-15 15:36:11 -0700511 return dex_files;
512}
513
Mathieu Chartier91c91162016-01-15 09:48:15 -0800514std::unique_ptr<const DexFile> CommonRuntimeTestImpl::OpenTestDexFile(const char* name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800515 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700516 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800517 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700518}
519
Mathieu Chartier91c91162016-01-15 09:48:15 -0800520std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700521 std::vector<const DexFile*> ret;
522
523 ScopedObjectAccess soa(Thread::Current());
524
Mathieu Chartierc7853442015-03-27 14:35:38 -0700525 StackHandleScope<2> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700526 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
527 soa.Decode<mirror::ClassLoader*>(jclass_loader));
528
529 DCHECK_EQ(class_loader->GetClass(),
530 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
531 DCHECK_EQ(class_loader->GetParent()->GetClass(),
532 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));
533
534 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
535 // We need to get the DexPathList and loop through it.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700536 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
537 ArtField* dex_file_field =
538 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700539 mirror::Object* dex_path_list =
540 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
541 GetObject(class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700542 if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700543 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
544 mirror::Object* dex_elements_obj =
545 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
546 GetObject(dex_path_list);
547 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
548 // at the mCookie which is a DexFile vector.
549 if (dex_elements_obj != nullptr) {
550 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
551 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
552 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
553 mirror::Object* element = dex_elements->GetWithoutChecks(i);
554 if (element == nullptr) {
555 // Should never happen, fall back to java code to throw a NPE.
556 break;
557 }
558 mirror::Object* dex_file = dex_file_field->GetObject(element);
559 if (dex_file != nullptr) {
560 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
561 DCHECK(long_array != nullptr);
562 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700563 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700564 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
565 long_array->GetWithoutChecks(j)));
566 if (cp_dex_file == nullptr) {
567 LOG(WARNING) << "Null DexFile";
568 continue;
569 }
570 ret.push_back(cp_dex_file);
571 }
572 }
573 }
574 }
575 }
576
577 return ret;
578}
579
Mathieu Chartier91c91162016-01-15 09:48:15 -0800580const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700581 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
582 DCHECK(!tmp.empty());
583 const DexFile* ret = tmp[0];
584 DCHECK(ret != nullptr);
585 return ret;
586}
587
Mathieu Chartier91c91162016-01-15 09:48:15 -0800588jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800589 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
590 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700591 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800592 for (auto& dex_file : dex_files) {
593 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800594 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700595 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700596
Ian Rogers68d8b422014-07-17 11:09:10 -0700597 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700598 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
Mathieu Chartier966878d2016-01-14 14:33:29 -0800599 class_path);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700600 self->SetClassLoaderOverride(class_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700601 return class_loader;
602}
603
Mathieu Chartier91c91162016-01-15 09:48:15 -0800604std::string CommonRuntimeTestImpl::GetCoreFileLocation(const char* suffix) {
Igor Murashkin37743352014-11-13 14:38:00 -0800605 CHECK(suffix != nullptr);
606
607 std::string location;
608 if (IsHost()) {
609 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700610 CHECK(host_dir != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -0800611 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
612 } else {
613 location = StringPrintf("/data/art-test/core.%s", suffix);
614 }
615
616 return location;
617}
618
Ian Rogerse63db272014-07-15 15:36:11 -0700619CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700620 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700621}
622
623CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700624 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700625 EXPECT_TRUE(actual_.empty()) << actual_;
626}
627
628void CheckJniAbortCatcher::Check(const char* expected_text) {
629 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
630 << "Expected to find: " << expected_text << "\n"
631 << "In the output : " << actual_;
632 actual_.clear();
633}
634
635void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
636 // We use += because when we're hooking the aborts like this, multiple problems can be found.
637 *reinterpret_cast<std::string*>(data) += reason;
638}
639
640} // namespace art
641
642namespace std {
643
644template <typename T>
645std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
646os << ::art::ToString(rhs);
647return os;
648}
649
650} // namespace std