blob: 56c5d1a2c3b7bbd314c857d4e5db5e2f3b21ba2d [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"
Ian Rogerse63db272014-07-15 15:36:11 -070045#include "noop_compiler_callbacks.h"
46#include "os.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070047#include "primitive.h"
Ian Rogerse63db272014-07-15 15:36:11 -070048#include "runtime-inl.h"
49#include "scoped_thread_state_change.h"
50#include "thread.h"
51#include "well_known_classes.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070052
53int main(int argc, char **argv) {
Andreas Gampe369810a2015-01-14 19:53:31 -080054 // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
55 // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
56 // everything else. In case you want to see all messages, comment out the line.
Richard Uhler892fc962015-03-10 16:57:05 +000057 setenv("ANDROID_LOG_TAGS", "*:e", 1);
Andreas Gampe369810a2015-01-14 19:53:31 -080058
Elliott Hugheseb02a122012-06-12 11:35:40 -070059 art::InitLogging(argv);
Ian Rogersc7dd2952014-10-21 23:31:19 -070060 LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070061 testing::InitGoogleTest(&argc, argv);
62 return RUN_ALL_TESTS();
63}
Ian Rogerse63db272014-07-15 15:36:11 -070064
65namespace art {
66
67ScratchFile::ScratchFile() {
68 // ANDROID_DATA needs to be set
69 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
70 "Are you subclassing RuntimeTest?";
71 filename_ = getenv("ANDROID_DATA");
72 filename_ += "/TmpFile-XXXXXX";
73 int fd = mkstemp(&filename_[0]);
74 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080075 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070076}
77
78ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
79 filename_ = other.GetFilename();
80 filename_ += suffix;
81 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
82 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080083 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070084}
85
86ScratchFile::ScratchFile(File* file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070087 CHECK(file != nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -070088 filename_ = file->GetPath();
89 file_.reset(file);
90}
91
92ScratchFile::~ScratchFile() {
93 Unlink();
94}
95
96int ScratchFile::GetFd() const {
97 return file_->Fd();
98}
99
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800100void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800101 if (file_.get() != nullptr) {
102 if (file_->FlushCloseOrErase() != 0) {
103 PLOG(WARNING) << "Error closing scratch file.";
104 }
105 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800106}
107
108void ScratchFile::Unlink() {
109 if (!OS::FileExists(filename_.c_str())) {
110 return;
111 }
112 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700113 int unlink_result = unlink(filename_.c_str());
114 CHECK_EQ(0, unlink_result);
115}
116
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700117static bool unstarted_initialized_ = false;
118
Ian Rogerse63db272014-07-15 15:36:11 -0700119CommonRuntimeTest::CommonRuntimeTest() {}
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800120CommonRuntimeTest::~CommonRuntimeTest() {
121 // Ensure the dex files are cleaned up before the runtime.
122 loaded_dex_files_.clear();
123 runtime_.reset();
124}
Ian Rogerse63db272014-07-15 15:36:11 -0700125
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700126void CommonRuntimeTest::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700127 if (IsHost()) {
128 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
129 // But it needs to be set so that icu4c can find its locale data.
130 const char* android_root_from_env = getenv("ANDROID_ROOT");
131 if (android_root_from_env == nullptr) {
132 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
133 const char* android_host_out = getenv("ANDROID_HOST_OUT");
134 if (android_host_out != nullptr) {
135 setenv("ANDROID_ROOT", android_host_out, 1);
136 } else {
137 // Build it from ANDROID_BUILD_TOP or cwd
138 std::string root;
139 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
140 if (android_build_top != nullptr) {
141 root += android_build_top;
142 } else {
143 // Not set by build server, so default to current directory
144 char* cwd = getcwd(nullptr, 0);
145 setenv("ANDROID_BUILD_TOP", cwd, 1);
146 root += cwd;
147 free(cwd);
148 }
149#if defined(__linux__)
150 root += "/out/host/linux-x86";
151#elif defined(__APPLE__)
152 root += "/out/host/darwin-x86";
153#else
154#error unsupported OS
155#endif
156 setenv("ANDROID_ROOT", root.c_str(), 1);
157 }
158 }
159 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
160
161 // Not set by build server, so default
162 if (getenv("ANDROID_HOST_OUT") == nullptr) {
163 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
164 }
165 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700166}
Ian Rogerse63db272014-07-15 15:36:11 -0700167
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700168void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700169 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700170 if (IsHost()) {
171 const char* tmpdir = getenv("TMPDIR");
172 if (tmpdir != nullptr && tmpdir[0] != 0) {
173 android_data = tmpdir;
174 } else {
175 android_data = "/tmp";
176 }
177 } else {
178 android_data = "/data/dalvik-cache";
179 }
180 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700181 if (mkdtemp(&android_data[0]) == nullptr) {
182 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
183 }
184 setenv("ANDROID_DATA", android_data.c_str(), 1);
185}
186
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700187void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
188 if (fail_on_error) {
189 ASSERT_EQ(rmdir(android_data.c_str()), 0);
190 } else {
191 rmdir(android_data.c_str());
192 }
193}
194
David Srbecky3e52aa42015-04-12 07:45:18 +0100195// Helper - find directory with the following format:
196// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
197static std::string GetAndroidToolsDir(const std::string& subdir1,
198 const std::string& subdir2,
199 const std::string& subdir3) {
200 std::string root;
201 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
202 if (android_build_top != nullptr) {
203 root = android_build_top;
204 } else {
205 // Not set by build server, so default to current directory
206 char* cwd = getcwd(nullptr, 0);
207 setenv("ANDROID_BUILD_TOP", cwd, 1);
208 root = cwd;
209 free(cwd);
210 }
211
212 std::string toolsdir = root + "/" + subdir1;
213 std::string founddir;
214 DIR* dir;
215 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
216 float maxversion = 0;
217 struct dirent* entry;
218 while ((entry = readdir(dir)) != nullptr) {
219 std::string format = subdir2 + "-%f";
220 float version;
221 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
222 if (version > maxversion) {
223 maxversion = version;
224 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
225 }
226 }
227 }
228 closedir(dir);
229 }
230
231 if (founddir.empty()) {
232 ADD_FAILURE() << "Can not find Android tools directory.";
233 }
234 return founddir;
235}
236
237std::string CommonRuntimeTest::GetAndroidHostToolsDir() {
238 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
239 "x86_64-linux-glibc2.15",
240 "x86_64-linux");
241}
242
243std::string CommonRuntimeTest::GetAndroidTargetToolsDir(InstructionSet isa) {
244 switch (isa) {
245 case kArm:
246 case kThumb2:
247 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
248 "arm-linux-androideabi",
249 "arm-linux-androideabi");
250 case kArm64:
251 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
252 "aarch64-linux-android",
253 "aarch64-linux-android");
254 case kX86:
255 case kX86_64:
256 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
257 "x86_64-linux-android",
258 "x86_64-linux-android");
259 case kMips:
260 case kMips64:
261 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
262 "mips64el-linux-android",
263 "mips64el-linux-android");
264 case kNone:
265 break;
266 }
267 ADD_FAILURE() << "Invalid isa " << isa;
268 return "";
269}
270
Igor Murashkin37743352014-11-13 14:38:00 -0800271std::string CommonRuntimeTest::GetCoreArtLocation() {
272 return GetCoreFileLocation("art");
273}
274
275std::string CommonRuntimeTest::GetCoreOatLocation() {
276 return GetCoreFileLocation("oat");
277}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700278
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800279std::unique_ptr<const DexFile> CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
280 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700281 std::string error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800282 MemMap::Init();
Ian Rogerse63db272014-07-15 15:36:11 -0700283 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
284 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800285 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700286 } else {
287 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800288 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700289 }
290}
291
292void CommonRuntimeTest::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700293 SetUpAndroidRoot();
294 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700295 dalvik_cache_.append(android_data_.c_str());
296 dalvik_cache_.append("/dalvik-cache");
297 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
298 ASSERT_EQ(mkdir_result, 0);
299
Ian Rogerse63db272014-07-15 15:36:11 -0700300 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
301 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
302
Ian Rogerse63db272014-07-15 15:36:11 -0700303
304 RuntimeOptions options;
Richard Uhlerc2752592015-01-02 13:28:22 -0800305 std::string boot_class_path_string = "-Xbootclasspath:" + GetLibCoreDexFileName();
306 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700307 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800308 options.push_back(std::make_pair(min_heap_string, nullptr));
309 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700310
311 callbacks_.reset(new NoopCompilerCallbacks());
312
Ian Rogerse63db272014-07-15 15:36:11 -0700313 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800314
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700315 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
316 if (callbacks_.get() != nullptr) {
317 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
318 }
319
Richard Uhler66d874d2015-01-15 09:37:19 -0800320 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700321 if (!Runtime::Create(options, false)) {
322 LOG(FATAL) << "Failed to create runtime";
323 return;
324 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800325 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700326 runtime_.reset(Runtime::Current());
327 class_linker_ = runtime_->GetClassLinker();
328 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700329
330 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
331 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700332 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700333 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700334 unstarted_initialized_ = true;
335 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700336
Ian Rogerse63db272014-07-15 15:36:11 -0700337 class_linker_->RunRootClinits();
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800338 boot_class_path_ = class_linker_->GetBootClassPath();
339 java_lang_dex_file_ = boot_class_path_[0];
340
Ian Rogerse63db272014-07-15 15:36:11 -0700341
342 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
343 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
344 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
345
346 // We're back in native, take the opportunity to initialize well known classes.
347 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
348
349 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
350 // pool is created by the runtime.
351 runtime_->GetHeap()->CreateThreadPool();
352 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700353 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
354 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Richard Uhlerc2752592015-01-02 13:28:22 -0800355
356 // Get the boot class path from the runtime so it can be used in tests.
357 boot_class_path_ = class_linker_->GetBootClassPath();
358 ASSERT_FALSE(boot_class_path_.empty());
359 java_lang_dex_file_ = boot_class_path_[0];
Ian Rogerse63db272014-07-15 15:36:11 -0700360}
361
Alex Lighta59dd802014-07-02 16:28:08 -0700362void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
363 ASSERT_TRUE(dirpath != nullptr);
364 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700365 ASSERT_TRUE(dir != nullptr);
366 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700367 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700368 while ((e = readdir(dir)) != nullptr) {
369 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
370 continue;
371 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700372 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700373 filename.push_back('/');
374 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700375 int stat_result = lstat(filename.c_str(), &s);
376 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
377 if (S_ISDIR(s.st_mode)) {
378 ClearDirectory(filename.c_str());
379 int rmdir_result = rmdir(filename.c_str());
380 ASSERT_EQ(0, rmdir_result) << filename;
381 } else {
382 int unlink_result = unlink(filename.c_str());
383 ASSERT_EQ(0, unlink_result) << filename;
384 }
Ian Rogerse63db272014-07-15 15:36:11 -0700385 }
386 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700387}
388
389void CommonRuntimeTest::TearDown() {
390 const char* android_data = getenv("ANDROID_DATA");
391 ASSERT_TRUE(android_data != nullptr);
392 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700393 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
394 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700395 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700396
397 // icu4c has a fixed 10-element array "gCommonICUDataArray".
398 // If we run > 10 tests, we fill that array and u_setCommonData fails.
399 // There's a function to clear the array, but it's not public...
400 typedef void (*IcuCleanupFn)();
401 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
402 CHECK(sym != nullptr) << dlerror();
403 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
404 (*icu_cleanup_fn)();
405
Ian Rogerse63db272014-07-15 15:36:11 -0700406 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
407}
408
409std::string CommonRuntimeTest::GetLibCoreDexFileName() {
410 return GetDexFileName("core-libart");
411}
412
413std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
414 if (IsHost()) {
415 const char* host_dir = getenv("ANDROID_HOST_OUT");
416 CHECK(host_dir != nullptr);
417 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
418 }
419 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
420}
421
422std::string CommonRuntimeTest::GetTestAndroidRoot() {
423 if (IsHost()) {
424 const char* host_dir = getenv("ANDROID_HOST_OUT");
425 CHECK(host_dir != nullptr);
426 return host_dir;
427 }
428 return GetAndroidRoot();
429}
430
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700431// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
432#ifdef ART_TARGET
433#ifndef ART_TARGET_NATIVETEST_DIR
434#error "ART_TARGET_NATIVETEST_DIR not set."
435#endif
436// Wrap it as a string literal.
437#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
438#else
439#define ART_TARGET_NATIVETEST_DIR_STRING ""
440#endif
441
Richard Uhler66d874d2015-01-15 09:37:19 -0800442std::string CommonRuntimeTest::GetTestDexFileName(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700443 CHECK(name != nullptr);
444 std::string filename;
445 if (IsHost()) {
446 filename += getenv("ANDROID_HOST_OUT");
447 filename += "/framework/";
448 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700449 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700450 }
451 filename += "art-gtest-";
452 filename += name;
453 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800454 return filename;
455}
456
457std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
458 std::string filename = GetTestDexFileName(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700459 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800460 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700461 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
462 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800463 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700464 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
465 CHECK(dex_file->IsReadOnly());
466 }
Ian Rogerse63db272014-07-15 15:36:11 -0700467 return dex_files;
468}
469
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800470std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
471 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700472 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800473 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700474}
475
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700476std::vector<const DexFile*> CommonRuntimeTest::GetDexFiles(jobject jclass_loader) {
477 std::vector<const DexFile*> ret;
478
479 ScopedObjectAccess soa(Thread::Current());
480
Mathieu Chartierc7853442015-03-27 14:35:38 -0700481 StackHandleScope<2> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700482 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
483 soa.Decode<mirror::ClassLoader*>(jclass_loader));
484
485 DCHECK_EQ(class_loader->GetClass(),
486 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
487 DCHECK_EQ(class_loader->GetParent()->GetClass(),
488 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));
489
490 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
491 // We need to get the DexPathList and loop through it.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700492 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
493 ArtField* dex_file_field =
494 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700495 mirror::Object* dex_path_list =
496 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
497 GetObject(class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700498 if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700499 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
500 mirror::Object* dex_elements_obj =
501 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
502 GetObject(dex_path_list);
503 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
504 // at the mCookie which is a DexFile vector.
505 if (dex_elements_obj != nullptr) {
506 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
507 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
508 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
509 mirror::Object* element = dex_elements->GetWithoutChecks(i);
510 if (element == nullptr) {
511 // Should never happen, fall back to java code to throw a NPE.
512 break;
513 }
514 mirror::Object* dex_file = dex_file_field->GetObject(element);
515 if (dex_file != nullptr) {
516 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
517 DCHECK(long_array != nullptr);
518 int32_t long_array_size = long_array->GetLength();
519 for (int32_t j = 0; j < long_array_size; ++j) {
520 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
521 long_array->GetWithoutChecks(j)));
522 if (cp_dex_file == nullptr) {
523 LOG(WARNING) << "Null DexFile";
524 continue;
525 }
526 ret.push_back(cp_dex_file);
527 }
528 }
529 }
530 }
531 }
532
533 return ret;
534}
535
536const DexFile* CommonRuntimeTest::GetFirstDexFile(jobject jclass_loader) {
537 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
538 DCHECK(!tmp.empty());
539 const DexFile* ret = tmp[0];
540 DCHECK(ret != nullptr);
541 return ret;
542}
543
Ian Rogerse63db272014-07-15 15:36:11 -0700544jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800545 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
546 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700547 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800548 for (auto& dex_file : dex_files) {
549 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800550 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700551 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700552
Ian Rogers68d8b422014-07-17 11:09:10 -0700553 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700554 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
555 class_path);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700556 self->SetClassLoaderOverride(class_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700557 return class_loader;
558}
559
Igor Murashkin37743352014-11-13 14:38:00 -0800560std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
561 CHECK(suffix != nullptr);
562
563 std::string location;
564 if (IsHost()) {
565 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700566 CHECK(host_dir != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -0800567 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
568 } else {
569 location = StringPrintf("/data/art-test/core.%s", suffix);
570 }
571
572 return location;
573}
574
Ian Rogerse63db272014-07-15 15:36:11 -0700575CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700576 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700577}
578
579CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700580 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700581 EXPECT_TRUE(actual_.empty()) << actual_;
582}
583
584void CheckJniAbortCatcher::Check(const char* expected_text) {
585 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
586 << "Expected to find: " << expected_text << "\n"
587 << "In the output : " << actual_;
588 actual_.clear();
589}
590
591void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
592 // We use += because when we're hooking the aborts like this, multiple problems can be found.
593 *reinterpret_cast<std::string*>(data) += reason;
594}
595
596} // namespace art
597
598namespace std {
599
600template <typename T>
601std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
602os << ::art::ToString(rhs);
603return os;
604}
605
606} // namespace std