blob: ce0d503ce74244cffbe4ca287dc85114341b2bd1 [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.
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;
Narayan Kamathd1ef4362015-11-12 11:49:06 +0000305 std::string boot_class_path_string = "-Xbootclasspath";
306 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
307 boot_class_path_string += ":";
308 boot_class_path_string += core_dex_file_name;
309 }
310
Richard Uhlerc2752592015-01-02 13:28:22 -0800311 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700312 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800313 options.push_back(std::make_pair(min_heap_string, nullptr));
314 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700315
316 callbacks_.reset(new NoopCompilerCallbacks());
317
Ian Rogerse63db272014-07-15 15:36:11 -0700318 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800319
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700320 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
321 if (callbacks_.get() != nullptr) {
322 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
323 }
324
Richard Uhler66d874d2015-01-15 09:37:19 -0800325 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700326 if (!Runtime::Create(options, false)) {
327 LOG(FATAL) << "Failed to create runtime";
328 return;
329 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800330 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700331 runtime_.reset(Runtime::Current());
332 class_linker_ = runtime_->GetClassLinker();
333 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700334
335 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
336 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700337 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700338 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700339 unstarted_initialized_ = true;
340 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700341
Ian Rogerse63db272014-07-15 15:36:11 -0700342 class_linker_->RunRootClinits();
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800343 boot_class_path_ = class_linker_->GetBootClassPath();
344 java_lang_dex_file_ = boot_class_path_[0];
345
Ian Rogerse63db272014-07-15 15:36:11 -0700346
347 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
348 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
349 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
350
351 // We're back in native, take the opportunity to initialize well known classes.
352 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
353
354 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
355 // pool is created by the runtime.
356 runtime_->GetHeap()->CreateThreadPool();
357 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700358 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
359 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Richard Uhlerc2752592015-01-02 13:28:22 -0800360
361 // Get the boot class path from the runtime so it can be used in tests.
362 boot_class_path_ = class_linker_->GetBootClassPath();
363 ASSERT_FALSE(boot_class_path_.empty());
364 java_lang_dex_file_ = boot_class_path_[0];
Ian Rogerse63db272014-07-15 15:36:11 -0700365}
366
Alex Lighta59dd802014-07-02 16:28:08 -0700367void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
368 ASSERT_TRUE(dirpath != nullptr);
369 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700370 ASSERT_TRUE(dir != nullptr);
371 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700372 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700373 while ((e = readdir(dir)) != nullptr) {
374 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
375 continue;
376 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700377 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700378 filename.push_back('/');
379 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700380 int stat_result = lstat(filename.c_str(), &s);
381 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
382 if (S_ISDIR(s.st_mode)) {
383 ClearDirectory(filename.c_str());
384 int rmdir_result = rmdir(filename.c_str());
385 ASSERT_EQ(0, rmdir_result) << filename;
386 } else {
387 int unlink_result = unlink(filename.c_str());
388 ASSERT_EQ(0, unlink_result) << filename;
389 }
Ian Rogerse63db272014-07-15 15:36:11 -0700390 }
391 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700392}
393
394void CommonRuntimeTest::TearDown() {
395 const char* android_data = getenv("ANDROID_DATA");
396 ASSERT_TRUE(android_data != nullptr);
397 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700398 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
399 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700400 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700401
402 // icu4c has a fixed 10-element array "gCommonICUDataArray".
403 // If we run > 10 tests, we fill that array and u_setCommonData fails.
404 // There's a function to clear the array, but it's not public...
405 typedef void (*IcuCleanupFn)();
406 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
407 CHECK(sym != nullptr) << dlerror();
408 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
409 (*icu_cleanup_fn)();
410
Ian Rogerse63db272014-07-15 15:36:11 -0700411 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
Yi Kongb8bce052015-11-17 19:22:30 +0000412
413 // Manually closing the JNI libraries.
414 // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
415 // dynamic linking loader so that gtests would not fail.
416 // Bug: 25785594
417 if (runtime_->IsStarted()) {
418 {
419 // We retrieve the handle by calling dlopen on the library. To close it, we need to call
420 // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
421 // See man dlopen.
422 void* handle = dlopen("libjavacore.so", RTLD_LAZY);
423 dlclose(handle);
424 CHECK_EQ(0, dlclose(handle));
425 }
426 {
427 void* handle = dlopen("libopenjdk.so", RTLD_LAZY);
428 dlclose(handle);
429 CHECK_EQ(0, dlclose(handle));
430 }
431 }
Ian Rogerse63db272014-07-15 15:36:11 -0700432}
433
Przemyslaw Szczepaniak5b8e6e32015-09-30 14:40:33 +0100434std::vector<std::string> CommonRuntimeTest::GetLibCoreDexFileNames() {
435 return std::vector<std::string>({GetDexFileName("core-oj"), GetDexFileName("core-libart")});
Ian Rogerse63db272014-07-15 15:36:11 -0700436}
437
438std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
439 if (IsHost()) {
440 const char* host_dir = getenv("ANDROID_HOST_OUT");
441 CHECK(host_dir != nullptr);
442 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
443 }
444 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
445}
446
447std::string CommonRuntimeTest::GetTestAndroidRoot() {
448 if (IsHost()) {
449 const char* host_dir = getenv("ANDROID_HOST_OUT");
450 CHECK(host_dir != nullptr);
451 return host_dir;
452 }
453 return GetAndroidRoot();
454}
455
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700456// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
457#ifdef ART_TARGET
458#ifndef ART_TARGET_NATIVETEST_DIR
459#error "ART_TARGET_NATIVETEST_DIR not set."
460#endif
461// Wrap it as a string literal.
462#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
463#else
464#define ART_TARGET_NATIVETEST_DIR_STRING ""
465#endif
466
Richard Uhler66d874d2015-01-15 09:37:19 -0800467std::string CommonRuntimeTest::GetTestDexFileName(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700468 CHECK(name != nullptr);
469 std::string filename;
470 if (IsHost()) {
471 filename += getenv("ANDROID_HOST_OUT");
472 filename += "/framework/";
473 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700474 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700475 }
476 filename += "art-gtest-";
477 filename += name;
478 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800479 return filename;
480}
481
482std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
483 std::string filename = GetTestDexFileName(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700484 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800485 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700486 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
487 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800488 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700489 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
490 CHECK(dex_file->IsReadOnly());
491 }
Ian Rogerse63db272014-07-15 15:36:11 -0700492 return dex_files;
493}
494
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800495std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
496 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700497 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800498 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700499}
500
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700501std::vector<const DexFile*> CommonRuntimeTest::GetDexFiles(jobject jclass_loader) {
502 std::vector<const DexFile*> ret;
503
504 ScopedObjectAccess soa(Thread::Current());
505
Mathieu Chartierc7853442015-03-27 14:35:38 -0700506 StackHandleScope<2> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700507 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
508 soa.Decode<mirror::ClassLoader*>(jclass_loader));
509
510 DCHECK_EQ(class_loader->GetClass(),
511 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
512 DCHECK_EQ(class_loader->GetParent()->GetClass(),
513 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));
514
515 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
516 // We need to get the DexPathList and loop through it.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700517 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
518 ArtField* dex_file_field =
519 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700520 mirror::Object* dex_path_list =
521 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
522 GetObject(class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700523 if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700524 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
525 mirror::Object* dex_elements_obj =
526 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
527 GetObject(dex_path_list);
528 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
529 // at the mCookie which is a DexFile vector.
530 if (dex_elements_obj != nullptr) {
531 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
532 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
533 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
534 mirror::Object* element = dex_elements->GetWithoutChecks(i);
535 if (element == nullptr) {
536 // Should never happen, fall back to java code to throw a NPE.
537 break;
538 }
539 mirror::Object* dex_file = dex_file_field->GetObject(element);
540 if (dex_file != nullptr) {
541 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
542 DCHECK(long_array != nullptr);
543 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700544 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700545 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
546 long_array->GetWithoutChecks(j)));
547 if (cp_dex_file == nullptr) {
548 LOG(WARNING) << "Null DexFile";
549 continue;
550 }
551 ret.push_back(cp_dex_file);
552 }
553 }
554 }
555 }
556 }
557
558 return ret;
559}
560
561const DexFile* CommonRuntimeTest::GetFirstDexFile(jobject jclass_loader) {
562 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
563 DCHECK(!tmp.empty());
564 const DexFile* ret = tmp[0];
565 DCHECK(ret != nullptr);
566 return ret;
567}
568
Ian Rogerse63db272014-07-15 15:36:11 -0700569jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800570 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
571 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700572 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800573 for (auto& dex_file : dex_files) {
574 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800575 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700576 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700577
Ian Rogers68d8b422014-07-17 11:09:10 -0700578 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700579 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
Mathieu Chartierd37d3642015-11-19 16:05:58 -0800580 class_path,
581 nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700582 self->SetClassLoaderOverride(class_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700583 return class_loader;
584}
585
Igor Murashkin37743352014-11-13 14:38:00 -0800586std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
587 CHECK(suffix != nullptr);
588
589 std::string location;
590 if (IsHost()) {
591 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700592 CHECK(host_dir != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -0800593 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
594 } else {
595 location = StringPrintf("/data/art-test/core.%s", suffix);
596 }
597
598 return location;
599}
600
Ian Rogerse63db272014-07-15 15:36:11 -0700601CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700602 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700603}
604
605CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700606 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700607 EXPECT_TRUE(actual_.empty()) << actual_;
608}
609
610void CheckJniAbortCatcher::Check(const char* expected_text) {
611 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
612 << "Expected to find: " << expected_text << "\n"
613 << "In the output : " << actual_;
614 actual_.clear();
615}
616
617void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
618 // We use += because when we're hooking the aborts like this, multiple problems can be found.
619 *reinterpret_cast<std::string*>(data) += reason;
620}
621
622} // namespace art
623
624namespace std {
625
626template <typename T>
627std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
628os << ::art::ToString(rhs);
629return os;
630}
631
632} // namespace std