blob: 403dd4c0df637b1e29caa41936a68ad1afe4d363 [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]);
75 CHECK_NE(-1, fd);
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
Ian Rogerse63db272014-07-15 15:36:11 -0700120CommonRuntimeTest::CommonRuntimeTest() {}
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800121CommonRuntimeTest::~CommonRuntimeTest() {
122 // Ensure the dex files are cleaned up before the runtime.
123 loaded_dex_files_.clear();
124 runtime_.reset();
125}
Ian Rogerse63db272014-07-15 15:36:11 -0700126
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700127void CommonRuntimeTest::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700128 if (IsHost()) {
129 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
130 // But it needs to be set so that icu4c can find its locale data.
131 const char* android_root_from_env = getenv("ANDROID_ROOT");
132 if (android_root_from_env == nullptr) {
133 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
134 const char* android_host_out = getenv("ANDROID_HOST_OUT");
135 if (android_host_out != nullptr) {
136 setenv("ANDROID_ROOT", android_host_out, 1);
137 } else {
138 // Build it from ANDROID_BUILD_TOP or cwd
139 std::string root;
140 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
141 if (android_build_top != nullptr) {
142 root += android_build_top;
143 } else {
144 // Not set by build server, so default to current directory
145 char* cwd = getcwd(nullptr, 0);
146 setenv("ANDROID_BUILD_TOP", cwd, 1);
147 root += cwd;
148 free(cwd);
149 }
150#if defined(__linux__)
151 root += "/out/host/linux-x86";
152#elif defined(__APPLE__)
153 root += "/out/host/darwin-x86";
154#else
155#error unsupported OS
156#endif
157 setenv("ANDROID_ROOT", root.c_str(), 1);
158 }
159 }
160 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
161
162 // Not set by build server, so default
163 if (getenv("ANDROID_HOST_OUT") == nullptr) {
164 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
165 }
166 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700167}
Ian Rogerse63db272014-07-15 15:36:11 -0700168
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700169void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700170 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700171 if (IsHost()) {
172 const char* tmpdir = getenv("TMPDIR");
173 if (tmpdir != nullptr && tmpdir[0] != 0) {
174 android_data = tmpdir;
175 } else {
176 android_data = "/tmp";
177 }
178 } else {
179 android_data = "/data/dalvik-cache";
180 }
181 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700182 if (mkdtemp(&android_data[0]) == nullptr) {
183 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
184 }
185 setenv("ANDROID_DATA", android_data.c_str(), 1);
186}
187
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700188void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
189 if (fail_on_error) {
190 ASSERT_EQ(rmdir(android_data.c_str()), 0);
191 } else {
192 rmdir(android_data.c_str());
193 }
194}
195
David Srbecky3e52aa42015-04-12 07:45:18 +0100196// Helper - find directory with the following format:
197// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
198static std::string GetAndroidToolsDir(const std::string& subdir1,
199 const std::string& subdir2,
200 const std::string& subdir3) {
201 std::string root;
202 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
203 if (android_build_top != nullptr) {
204 root = android_build_top;
205 } else {
206 // Not set by build server, so default to current directory
207 char* cwd = getcwd(nullptr, 0);
208 setenv("ANDROID_BUILD_TOP", cwd, 1);
209 root = cwd;
210 free(cwd);
211 }
212
213 std::string toolsdir = root + "/" + subdir1;
214 std::string founddir;
215 DIR* dir;
216 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
217 float maxversion = 0;
218 struct dirent* entry;
219 while ((entry = readdir(dir)) != nullptr) {
220 std::string format = subdir2 + "-%f";
221 float version;
222 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
223 if (version > maxversion) {
224 maxversion = version;
225 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
226 }
227 }
228 }
229 closedir(dir);
230 }
231
232 if (founddir.empty()) {
233 ADD_FAILURE() << "Can not find Android tools directory.";
234 }
235 return founddir;
236}
237
238std::string CommonRuntimeTest::GetAndroidHostToolsDir() {
239 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
240 "x86_64-linux-glibc2.15",
241 "x86_64-linux");
242}
243
244std::string CommonRuntimeTest::GetAndroidTargetToolsDir(InstructionSet isa) {
245 switch (isa) {
246 case kArm:
247 case kThumb2:
248 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
249 "arm-linux-androideabi",
250 "arm-linux-androideabi");
251 case kArm64:
252 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
253 "aarch64-linux-android",
254 "aarch64-linux-android");
255 case kX86:
256 case kX86_64:
257 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
258 "x86_64-linux-android",
259 "x86_64-linux-android");
260 case kMips:
261 case kMips64:
262 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
263 "mips64el-linux-android",
264 "mips64el-linux-android");
265 case kNone:
266 break;
267 }
268 ADD_FAILURE() << "Invalid isa " << isa;
269 return "";
270}
271
Igor Murashkin37743352014-11-13 14:38:00 -0800272std::string CommonRuntimeTest::GetCoreArtLocation() {
273 return GetCoreFileLocation("art");
274}
275
276std::string CommonRuntimeTest::GetCoreOatLocation() {
277 return GetCoreFileLocation("oat");
278}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700279
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800280std::unique_ptr<const DexFile> CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
281 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700282 std::string error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800283 MemMap::Init();
Ian Rogerse63db272014-07-15 15:36:11 -0700284 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
285 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800286 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700287 } else {
288 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800289 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700290 }
291}
292
293void CommonRuntimeTest::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700294 SetUpAndroidRoot();
295 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700296 dalvik_cache_.append(android_data_.c_str());
297 dalvik_cache_.append("/dalvik-cache");
298 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
299 ASSERT_EQ(mkdir_result, 0);
300
Ian Rogerse63db272014-07-15 15:36:11 -0700301 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
302 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
303
Ian Rogerse63db272014-07-15 15:36:11 -0700304
305 RuntimeOptions options;
Narayan Kamathd1ef4362015-11-12 11:49:06 +0000306 std::string boot_class_path_string = "-Xbootclasspath";
307 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
308 boot_class_path_string += ":";
309 boot_class_path_string += core_dex_file_name;
310 }
311
Richard Uhlerc2752592015-01-02 13:28:22 -0800312 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700313 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800314 options.push_back(std::make_pair(min_heap_string, nullptr));
315 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700316
317 callbacks_.reset(new NoopCompilerCallbacks());
318
Ian Rogerse63db272014-07-15 15:36:11 -0700319 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800320
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700321 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
322 if (callbacks_.get() != nullptr) {
323 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
324 }
325
Richard Uhler66d874d2015-01-15 09:37:19 -0800326 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700327 if (!Runtime::Create(options, false)) {
328 LOG(FATAL) << "Failed to create runtime";
329 return;
330 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800331 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700332 runtime_.reset(Runtime::Current());
333 class_linker_ = runtime_->GetClassLinker();
334 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700335
Andreas Gampea00f0122015-12-16 16:54:35 -0800336 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
337 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
338 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
339
340 // Get the boot class path from the runtime so it can be used in tests.
341 boot_class_path_ = class_linker_->GetBootClassPath();
342 ASSERT_FALSE(boot_class_path_.empty());
343 java_lang_dex_file_ = boot_class_path_[0];
344
345 FinalizeSetup();
346}
347
348void CommonRuntimeTest::FinalizeSetup() {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700349 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
350 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700351 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700352 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700353 unstarted_initialized_ = true;
354 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700355
Andreas Gampea00f0122015-12-16 16:54:35 -0800356 {
357 ScopedObjectAccess soa(Thread::Current());
358 class_linker_->RunRootClinits();
359 }
Ian Rogerse63db272014-07-15 15:36:11 -0700360
361 // We're back in native, take the opportunity to initialize well known classes.
362 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
363
364 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
365 // pool is created by the runtime.
366 runtime_->GetHeap()->CreateThreadPool();
367 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700368 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
369 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Ian Rogerse63db272014-07-15 15:36:11 -0700370}
371
Alex Lighta59dd802014-07-02 16:28:08 -0700372void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
373 ASSERT_TRUE(dirpath != nullptr);
374 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700375 ASSERT_TRUE(dir != nullptr);
376 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700377 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700378 while ((e = readdir(dir)) != nullptr) {
379 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
380 continue;
381 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700382 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700383 filename.push_back('/');
384 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700385 int stat_result = lstat(filename.c_str(), &s);
386 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
387 if (S_ISDIR(s.st_mode)) {
388 ClearDirectory(filename.c_str());
389 int rmdir_result = rmdir(filename.c_str());
390 ASSERT_EQ(0, rmdir_result) << filename;
391 } else {
392 int unlink_result = unlink(filename.c_str());
393 ASSERT_EQ(0, unlink_result) << filename;
394 }
Ian Rogerse63db272014-07-15 15:36:11 -0700395 }
396 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700397}
398
399void CommonRuntimeTest::TearDown() {
400 const char* android_data = getenv("ANDROID_DATA");
401 ASSERT_TRUE(android_data != nullptr);
402 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700403 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
404 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700405 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700406
407 // icu4c has a fixed 10-element array "gCommonICUDataArray".
408 // If we run > 10 tests, we fill that array and u_setCommonData fails.
409 // There's a function to clear the array, but it's not public...
410 typedef void (*IcuCleanupFn)();
411 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
412 CHECK(sym != nullptr) << dlerror();
413 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
414 (*icu_cleanup_fn)();
415
Ian Rogerse63db272014-07-15 15:36:11 -0700416 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
Yi Kongb8bce052015-11-17 19:22:30 +0000417
418 // Manually closing the JNI libraries.
419 // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
420 // dynamic linking loader so that gtests would not fail.
421 // Bug: 25785594
422 if (runtime_->IsStarted()) {
423 {
424 // We retrieve the handle by calling dlopen on the library. To close it, we need to call
425 // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
426 // See man dlopen.
427 void* handle = dlopen("libjavacore.so", RTLD_LAZY);
428 dlclose(handle);
429 CHECK_EQ(0, dlclose(handle));
430 }
431 {
432 void* handle = dlopen("libopenjdk.so", RTLD_LAZY);
433 dlclose(handle);
434 CHECK_EQ(0, dlclose(handle));
435 }
436 }
Ian Rogerse63db272014-07-15 15:36:11 -0700437}
438
Przemyslaw Szczepaniak5b8e6e32015-09-30 14:40:33 +0100439std::vector<std::string> CommonRuntimeTest::GetLibCoreDexFileNames() {
440 return std::vector<std::string>({GetDexFileName("core-oj"), GetDexFileName("core-libart")});
Ian Rogerse63db272014-07-15 15:36:11 -0700441}
442
443std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
444 if (IsHost()) {
445 const char* host_dir = getenv("ANDROID_HOST_OUT");
446 CHECK(host_dir != nullptr);
447 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
448 }
449 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
450}
451
452std::string CommonRuntimeTest::GetTestAndroidRoot() {
453 if (IsHost()) {
454 const char* host_dir = getenv("ANDROID_HOST_OUT");
455 CHECK(host_dir != nullptr);
456 return host_dir;
457 }
458 return GetAndroidRoot();
459}
460
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700461// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
462#ifdef ART_TARGET
463#ifndef ART_TARGET_NATIVETEST_DIR
464#error "ART_TARGET_NATIVETEST_DIR not set."
465#endif
466// Wrap it as a string literal.
467#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
468#else
469#define ART_TARGET_NATIVETEST_DIR_STRING ""
470#endif
471
Richard Uhler66d874d2015-01-15 09:37:19 -0800472std::string CommonRuntimeTest::GetTestDexFileName(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700473 CHECK(name != nullptr);
474 std::string filename;
475 if (IsHost()) {
476 filename += getenv("ANDROID_HOST_OUT");
477 filename += "/framework/";
478 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700479 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700480 }
481 filename += "art-gtest-";
482 filename += name;
483 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800484 return filename;
485}
486
487std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
488 std::string filename = GetTestDexFileName(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700489 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800490 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700491 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
492 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800493 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700494 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
495 CHECK(dex_file->IsReadOnly());
496 }
Ian Rogerse63db272014-07-15 15:36:11 -0700497 return dex_files;
498}
499
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800500std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
501 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700502 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800503 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700504}
505
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700506std::vector<const DexFile*> CommonRuntimeTest::GetDexFiles(jobject jclass_loader) {
507 std::vector<const DexFile*> ret;
508
509 ScopedObjectAccess soa(Thread::Current());
510
Mathieu Chartierc7853442015-03-27 14:35:38 -0700511 StackHandleScope<2> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700512 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
513 soa.Decode<mirror::ClassLoader*>(jclass_loader));
514
515 DCHECK_EQ(class_loader->GetClass(),
516 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
517 DCHECK_EQ(class_loader->GetParent()->GetClass(),
518 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));
519
520 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
521 // We need to get the DexPathList and loop through it.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700522 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
523 ArtField* dex_file_field =
524 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700525 mirror::Object* dex_path_list =
526 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
527 GetObject(class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700528 if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700529 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
530 mirror::Object* dex_elements_obj =
531 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
532 GetObject(dex_path_list);
533 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
534 // at the mCookie which is a DexFile vector.
535 if (dex_elements_obj != nullptr) {
536 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
537 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
538 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
539 mirror::Object* element = dex_elements->GetWithoutChecks(i);
540 if (element == nullptr) {
541 // Should never happen, fall back to java code to throw a NPE.
542 break;
543 }
544 mirror::Object* dex_file = dex_file_field->GetObject(element);
545 if (dex_file != nullptr) {
546 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
547 DCHECK(long_array != nullptr);
548 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700549 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700550 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
551 long_array->GetWithoutChecks(j)));
552 if (cp_dex_file == nullptr) {
553 LOG(WARNING) << "Null DexFile";
554 continue;
555 }
556 ret.push_back(cp_dex_file);
557 }
558 }
559 }
560 }
561 }
562
563 return ret;
564}
565
566const DexFile* CommonRuntimeTest::GetFirstDexFile(jobject jclass_loader) {
567 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
568 DCHECK(!tmp.empty());
569 const DexFile* ret = tmp[0];
570 DCHECK(ret != nullptr);
571 return ret;
572}
573
Ian Rogerse63db272014-07-15 15:36:11 -0700574jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800575 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
576 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700577 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800578 for (auto& dex_file : dex_files) {
579 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800580 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700581 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700582
Ian Rogers68d8b422014-07-17 11:09:10 -0700583 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700584 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
Mathieu Chartierd37d3642015-11-19 16:05:58 -0800585 class_path,
586 nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700587 self->SetClassLoaderOverride(class_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700588 return class_loader;
589}
590
Igor Murashkin37743352014-11-13 14:38:00 -0800591std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
592 CHECK(suffix != nullptr);
593
594 std::string location;
595 if (IsHost()) {
596 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700597 CHECK(host_dir != nullptr);
Igor Murashkin37743352014-11-13 14:38:00 -0800598 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
599 } else {
600 location = StringPrintf("/data/art-test/core.%s", suffix);
601 }
602
603 return location;
604}
605
Ian Rogerse63db272014-07-15 15:36:11 -0700606CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700607 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700608}
609
610CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700611 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700612 EXPECT_TRUE(actual_.empty()) << actual_;
613}
614
615void CheckJniAbortCatcher::Check(const char* expected_text) {
616 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
617 << "Expected to find: " << expected_text << "\n"
618 << "In the output : " << actual_;
619 actual_.clear();
620}
621
622void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
623 // We use += because when we're hooking the aborts like this, multiple problems can be found.
624 *reinterpret_cast<std::string*>(data) += reason;
625}
626
627} // namespace art
628
629namespace std {
630
631template <typename T>
632std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
633os << ::art::ToString(rhs);
634return os;
635}
636
637} // namespace std