1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common_runtime_test.h"
18
19 #include <cstdio>
20 #include <dirent.h>
21 #include <dlfcn.h>
22 #include <fcntl.h>
23 #include <ScopedLocalRef.h>
24 #include <stdlib.h>
25
26 #include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
27 #include "art_field-inl.h"
28 #include "base/macros.h"
29 #include "base/logging.h"
30 #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"
35 #include "dex_file-inl.h"
36 #include "gc_root-inl.h"
37 #include "gc/heap.h"
38 #include "gtest/gtest.h"
39 #include "handle_scope-inl.h"
40 #include "interpreter/unstarted_runtime.h"
41 #include "jni_internal.h"
42 #include "mirror/class-inl.h"
43 #include "mirror/class_loader.h"
44 #include "mem_map.h"
45 #include "native/dalvik_system_DexFile.h"
46 #include "noop_compiler_callbacks.h"
47 #include "os.h"
48 #include "primitive.h"
49 #include "runtime-inl.h"
50 #include "scoped_thread_state_change.h"
51 #include "thread.h"
52 #include "well_known_classes.h"
53
main(int argc,char ** argv)54 int main(int argc, char **argv) {
55 // 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.
58 setenv("ANDROID_LOG_TAGS", "*:e", 1);
59
60 art::InitLogging(argv);
61 LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
62 testing::InitGoogleTest(&argc, argv);
63 return RUN_ALL_TESTS();
64 }
65
66 namespace art {
67
ScratchFile()68 ScratchFile::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) << strerror(errno) << " for " << filename_;
76 file_.reset(new File(fd, GetFilename(), true));
77 }
78
ScratchFile(const ScratchFile & other,const char * suffix)79 ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
80 : ScratchFile(other.GetFilename() + suffix) {}
81
ScratchFile(const std::string & filename)82 ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
83 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
84 CHECK_NE(-1, fd);
85 file_.reset(new File(fd, GetFilename(), true));
86 }
87
ScratchFile(File * file)88 ScratchFile::ScratchFile(File* file) {
89 CHECK(file != nullptr);
90 filename_ = file->GetPath();
91 file_.reset(file);
92 }
93
ScratchFile(ScratchFile && other)94 ScratchFile::ScratchFile(ScratchFile&& other) {
95 *this = std::move(other);
96 }
97
operator =(ScratchFile && other)98 ScratchFile& ScratchFile::operator=(ScratchFile&& other) {
99 if (GetFile() != other.GetFile()) {
100 std::swap(filename_, other.filename_);
101 std::swap(file_, other.file_);
102 }
103 return *this;
104 }
105
~ScratchFile()106 ScratchFile::~ScratchFile() {
107 Unlink();
108 }
109
GetFd() const110 int ScratchFile::GetFd() const {
111 return file_->Fd();
112 }
113
Close()114 void ScratchFile::Close() {
115 if (file_.get() != nullptr) {
116 if (file_->FlushCloseOrErase() != 0) {
117 PLOG(WARNING) << "Error closing scratch file.";
118 }
119 }
120 }
121
Unlink()122 void ScratchFile::Unlink() {
123 if (!OS::FileExists(filename_.c_str())) {
124 return;
125 }
126 Close();
127 int unlink_result = unlink(filename_.c_str());
128 CHECK_EQ(0, unlink_result);
129 }
130
131 static bool unstarted_initialized_ = false;
132
CommonRuntimeTestImpl()133 CommonRuntimeTestImpl::CommonRuntimeTestImpl() {}
134
~CommonRuntimeTestImpl()135 CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
136 // Ensure the dex files are cleaned up before the runtime.
137 loaded_dex_files_.clear();
138 runtime_.reset();
139 }
140
SetUpAndroidRoot()141 void CommonRuntimeTestImpl::SetUpAndroidRoot() {
142 if (IsHost()) {
143 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
144 // But it needs to be set so that icu4c can find its locale data.
145 const char* android_root_from_env = getenv("ANDROID_ROOT");
146 if (android_root_from_env == nullptr) {
147 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
148 const char* android_host_out = getenv("ANDROID_HOST_OUT");
149 if (android_host_out != nullptr) {
150 setenv("ANDROID_ROOT", android_host_out, 1);
151 } else {
152 // Build it from ANDROID_BUILD_TOP or cwd
153 std::string root;
154 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
155 if (android_build_top != nullptr) {
156 root += android_build_top;
157 } else {
158 // Not set by build server, so default to current directory
159 char* cwd = getcwd(nullptr, 0);
160 setenv("ANDROID_BUILD_TOP", cwd, 1);
161 root += cwd;
162 free(cwd);
163 }
164 #if defined(__linux__)
165 root += "/out/host/linux-x86";
166 #elif defined(__APPLE__)
167 root += "/out/host/darwin-x86";
168 #else
169 #error unsupported OS
170 #endif
171 setenv("ANDROID_ROOT", root.c_str(), 1);
172 }
173 }
174 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
175
176 // Not set by build server, so default
177 if (getenv("ANDROID_HOST_OUT") == nullptr) {
178 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
179 }
180 }
181 }
182
SetUpAndroidData(std::string & android_data)183 void CommonRuntimeTestImpl::SetUpAndroidData(std::string& android_data) {
184 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
185 if (IsHost()) {
186 const char* tmpdir = getenv("TMPDIR");
187 if (tmpdir != nullptr && tmpdir[0] != 0) {
188 android_data = tmpdir;
189 } else {
190 android_data = "/tmp";
191 }
192 } else {
193 android_data = "/data/dalvik-cache";
194 }
195 android_data += "/art-data-XXXXXX";
196 if (mkdtemp(&android_data[0]) == nullptr) {
197 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
198 }
199 setenv("ANDROID_DATA", android_data.c_str(), 1);
200 }
201
TearDownAndroidData(const std::string & android_data,bool fail_on_error)202 void CommonRuntimeTestImpl::TearDownAndroidData(const std::string& android_data,
203 bool fail_on_error) {
204 if (fail_on_error) {
205 ASSERT_EQ(rmdir(android_data.c_str()), 0);
206 } else {
207 rmdir(android_data.c_str());
208 }
209 }
210
211 // Helper - find directory with the following format:
212 // ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
GetAndroidToolsDir(const std::string & subdir1,const std::string & subdir2,const std::string & subdir3)213 static std::string GetAndroidToolsDir(const std::string& subdir1,
214 const std::string& subdir2,
215 const std::string& subdir3) {
216 std::string root;
217 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
218 if (android_build_top != nullptr) {
219 root = android_build_top;
220 } else {
221 // Not set by build server, so default to current directory
222 char* cwd = getcwd(nullptr, 0);
223 setenv("ANDROID_BUILD_TOP", cwd, 1);
224 root = cwd;
225 free(cwd);
226 }
227
228 std::string toolsdir = root + "/" + subdir1;
229 std::string founddir;
230 DIR* dir;
231 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
232 float maxversion = 0;
233 struct dirent* entry;
234 while ((entry = readdir(dir)) != nullptr) {
235 std::string format = subdir2 + "-%f";
236 float version;
237 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
238 if (version > maxversion) {
239 maxversion = version;
240 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
241 }
242 }
243 }
244 closedir(dir);
245 }
246
247 if (founddir.empty()) {
248 ADD_FAILURE() << "Cannot find Android tools directory.";
249 }
250 return founddir;
251 }
252
GetAndroidHostToolsDir()253 std::string CommonRuntimeTestImpl::GetAndroidHostToolsDir() {
254 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
255 "x86_64-linux-glibc2.15",
256 "x86_64-linux");
257 }
258
GetAndroidTargetToolsDir(InstructionSet isa)259 std::string CommonRuntimeTestImpl::GetAndroidTargetToolsDir(InstructionSet isa) {
260 switch (isa) {
261 case kArm:
262 case kThumb2:
263 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
264 "arm-linux-androideabi",
265 "arm-linux-androideabi");
266 case kArm64:
267 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
268 "aarch64-linux-android",
269 "aarch64-linux-android");
270 case kX86:
271 case kX86_64:
272 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
273 "x86_64-linux-android",
274 "x86_64-linux-android");
275 case kMips:
276 case kMips64:
277 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
278 "mips64el-linux-android",
279 "mips64el-linux-android");
280 case kNone:
281 break;
282 }
283 ADD_FAILURE() << "Invalid isa " << isa;
284 return "";
285 }
286
GetCoreArtLocation()287 std::string CommonRuntimeTestImpl::GetCoreArtLocation() {
288 return GetCoreFileLocation("art");
289 }
290
GetCoreOatLocation()291 std::string CommonRuntimeTestImpl::GetCoreOatLocation() {
292 return GetCoreFileLocation("oat");
293 }
294
LoadExpectSingleDexFile(const char * location)295 std::unique_ptr<const DexFile> CommonRuntimeTestImpl::LoadExpectSingleDexFile(
296 const char* location) {
297 std::vector<std::unique_ptr<const DexFile>> dex_files;
298 std::string error_msg;
299 MemMap::Init();
300 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
301 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
302 UNREACHABLE();
303 } else {
304 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
305 return std::move(dex_files[0]);
306 }
307 }
308
SetUp()309 void CommonRuntimeTestImpl::SetUp() {
310 SetUpAndroidRoot();
311 SetUpAndroidData(android_data_);
312 dalvik_cache_.append(android_data_.c_str());
313 dalvik_cache_.append("/dalvik-cache");
314 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
315 ASSERT_EQ(mkdir_result, 0);
316
317 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
318 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
319
320
321 RuntimeOptions options;
322 std::string boot_class_path_string = "-Xbootclasspath";
323 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
324 boot_class_path_string += ":";
325 boot_class_path_string += core_dex_file_name;
326 }
327
328 options.push_back(std::make_pair(boot_class_path_string, nullptr));
329 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
330 options.push_back(std::make_pair(min_heap_string, nullptr));
331 options.push_back(std::make_pair(max_heap_string, nullptr));
332
333 callbacks_.reset(new NoopCompilerCallbacks());
334
335 SetUpRuntimeOptions(&options);
336
337 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
338 if (callbacks_.get() != nullptr) {
339 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
340 }
341
342 PreRuntimeCreate();
343 if (!Runtime::Create(options, false)) {
344 LOG(FATAL) << "Failed to create runtime";
345 return;
346 }
347 PostRuntimeCreate();
348 runtime_.reset(Runtime::Current());
349 class_linker_ = runtime_->GetClassLinker();
350 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
351
352 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
353 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
354 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
355
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];
360
361 FinalizeSetup();
362 }
363
FinalizeSetup()364 void CommonRuntimeTestImpl::FinalizeSetup() {
365 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
366 // set up.
367 if (!unstarted_initialized_) {
368 interpreter::UnstartedRuntime::Initialize();
369 unstarted_initialized_ = true;
370 }
371
372 {
373 ScopedObjectAccess soa(Thread::Current());
374 class_linker_->RunRootClinits();
375 }
376
377 // We're back in native, take the opportunity to initialize well known classes.
378 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
379
380 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
381 // pool is created by the runtime.
382 runtime_->GetHeap()->CreateThreadPool();
383 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
384 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
385 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
386 }
387
ClearDirectory(const char * dirpath)388 void CommonRuntimeTestImpl::ClearDirectory(const char* dirpath) {
389 ASSERT_TRUE(dirpath != nullptr);
390 DIR* dir = opendir(dirpath);
391 ASSERT_TRUE(dir != nullptr);
392 dirent* e;
393 struct stat s;
394 while ((e = readdir(dir)) != nullptr) {
395 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
396 continue;
397 }
398 std::string filename(dirpath);
399 filename.push_back('/');
400 filename.append(e->d_name);
401 int stat_result = lstat(filename.c_str(), &s);
402 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
403 if (S_ISDIR(s.st_mode)) {
404 ClearDirectory(filename.c_str());
405 int rmdir_result = rmdir(filename.c_str());
406 ASSERT_EQ(0, rmdir_result) << filename;
407 } else {
408 int unlink_result = unlink(filename.c_str());
409 ASSERT_EQ(0, unlink_result) << filename;
410 }
411 }
412 closedir(dir);
413 }
414
TearDown()415 void CommonRuntimeTestImpl::TearDown() {
416 const char* android_data = getenv("ANDROID_DATA");
417 ASSERT_TRUE(android_data != nullptr);
418 ClearDirectory(dalvik_cache_.c_str());
419 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
420 ASSERT_EQ(0, rmdir_cache_result);
421 TearDownAndroidData(android_data_, true);
422 dalvik_cache_.clear();
423
424 // icu4c has a fixed 10-element array "gCommonICUDataArray".
425 // If we run > 10 tests, we fill that array and u_setCommonData fails.
426 // There's a function to clear the array, but it's not public...
427 typedef void (*IcuCleanupFn)();
428 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
429 CHECK(sym != nullptr) << dlerror();
430 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
431 (*icu_cleanup_fn)();
432
433 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
434 }
435
GetDexFileName(const std::string & jar_prefix,bool host)436 static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
437 std::string path;
438 if (host) {
439 const char* host_dir = getenv("ANDROID_HOST_OUT");
440 CHECK(host_dir != nullptr);
441 path = host_dir;
442 } else {
443 path = GetAndroidRoot();
444 }
445
446 std::string suffix = host
447 ? "-hostdex" // The host version.
448 : "-testdex"; // The unstripped target version.
449
450 return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
451 }
452
GetLibCoreDexFileNames()453 std::vector<std::string> CommonRuntimeTestImpl::GetLibCoreDexFileNames() {
454 return std::vector<std::string>({GetDexFileName("core-oj", IsHost()),
455 GetDexFileName("core-libart", IsHost())});
456 }
457
GetTestAndroidRoot()458 std::string CommonRuntimeTestImpl::GetTestAndroidRoot() {
459 if (IsHost()) {
460 const char* host_dir = getenv("ANDROID_HOST_OUT");
461 CHECK(host_dir != nullptr);
462 return host_dir;
463 }
464 return GetAndroidRoot();
465 }
466
467 // Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
468 #ifdef ART_TARGET
469 #ifndef ART_TARGET_NATIVETEST_DIR
470 #error "ART_TARGET_NATIVETEST_DIR not set."
471 #endif
472 // Wrap it as a string literal.
473 #define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
474 #else
475 #define ART_TARGET_NATIVETEST_DIR_STRING ""
476 #endif
477
GetTestDexFileName(const char * name) const478 std::string CommonRuntimeTestImpl::GetTestDexFileName(const char* name) const {
479 CHECK(name != nullptr);
480 std::string filename;
481 if (IsHost()) {
482 filename += getenv("ANDROID_HOST_OUT");
483 filename += "/framework/";
484 } else {
485 filename += ART_TARGET_NATIVETEST_DIR_STRING;
486 }
487 filename += "art-gtest-";
488 filename += name;
489 filename += ".jar";
490 return filename;
491 }
492
OpenTestDexFiles(const char * name)493 std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTestImpl::OpenTestDexFiles(
494 const char* name) {
495 std::string filename = GetTestDexFileName(name);
496 std::string error_msg;
497 std::vector<std::unique_ptr<const DexFile>> dex_files;
498 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
499 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
500 for (auto& dex_file : dex_files) {
501 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
502 CHECK(dex_file->IsReadOnly());
503 }
504 return dex_files;
505 }
506
OpenTestDexFile(const char * name)507 std::unique_ptr<const DexFile> CommonRuntimeTestImpl::OpenTestDexFile(const char* name) {
508 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
509 EXPECT_EQ(1U, vector.size());
510 return std::move(vector[0]);
511 }
512
GetDexFiles(jobject jclass_loader)513 std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
514 std::vector<const DexFile*> ret;
515
516 ScopedObjectAccess soa(Thread::Current());
517
518 StackHandleScope<2> hs(soa.Self());
519 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
520 soa.Decode<mirror::ClassLoader*>(jclass_loader));
521
522 DCHECK_EQ(class_loader->GetClass(),
523 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
524 DCHECK_EQ(class_loader->GetParent()->GetClass(),
525 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));
526
527 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
528 // We need to get the DexPathList and loop through it.
529 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
530 ArtField* dex_file_field =
531 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
532 mirror::Object* dex_path_list =
533 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
534 GetObject(class_loader.Get());
535 if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
536 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
537 mirror::Object* dex_elements_obj =
538 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
539 GetObject(dex_path_list);
540 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
541 // at the mCookie which is a DexFile vector.
542 if (dex_elements_obj != nullptr) {
543 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
544 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
545 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
546 mirror::Object* element = dex_elements->GetWithoutChecks(i);
547 if (element == nullptr) {
548 // Should never happen, fall back to java code to throw a NPE.
549 break;
550 }
551 mirror::Object* dex_file = dex_file_field->GetObject(element);
552 if (dex_file != nullptr) {
553 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
554 DCHECK(long_array != nullptr);
555 int32_t long_array_size = long_array->GetLength();
556 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
557 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
558 long_array->GetWithoutChecks(j)));
559 if (cp_dex_file == nullptr) {
560 LOG(WARNING) << "Null DexFile";
561 continue;
562 }
563 ret.push_back(cp_dex_file);
564 }
565 }
566 }
567 }
568 }
569
570 return ret;
571 }
572
GetFirstDexFile(jobject jclass_loader)573 const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
574 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
575 DCHECK(!tmp.empty());
576 const DexFile* ret = tmp[0];
577 DCHECK(ret != nullptr);
578 return ret;
579 }
580
LoadDex(const char * dex_name)581 jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
582 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
583 std::vector<const DexFile*> class_path;
584 CHECK_NE(0U, dex_files.size());
585 for (auto& dex_file : dex_files) {
586 class_path.push_back(dex_file.get());
587 loaded_dex_files_.push_back(std::move(dex_file));
588 }
589
590 Thread* self = Thread::Current();
591 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
592 class_path);
593 self->SetClassLoaderOverride(class_loader);
594 return class_loader;
595 }
596
GetCoreFileLocation(const char * suffix)597 std::string CommonRuntimeTestImpl::GetCoreFileLocation(const char* suffix) {
598 CHECK(suffix != nullptr);
599
600 std::string location;
601 if (IsHost()) {
602 const char* host_dir = getenv("ANDROID_HOST_OUT");
603 CHECK(host_dir != nullptr);
604 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
605 } else {
606 location = StringPrintf("/data/art-test/core.%s", suffix);
607 }
608
609 return location;
610 }
611
CheckJniAbortCatcher()612 CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
613 vm_->SetCheckJniAbortHook(Hook, &actual_);
614 }
615
~CheckJniAbortCatcher()616 CheckJniAbortCatcher::~CheckJniAbortCatcher() {
617 vm_->SetCheckJniAbortHook(nullptr, nullptr);
618 EXPECT_TRUE(actual_.empty()) << actual_;
619 }
620
Check(const char * expected_text)621 void CheckJniAbortCatcher::Check(const char* expected_text) {
622 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
623 << "Expected to find: " << expected_text << "\n"
624 << "In the output : " << actual_;
625 actual_.clear();
626 }
627
Hook(void * data,const std::string & reason)628 void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
629 // We use += because when we're hooking the aborts like this, multiple problems can be found.
630 *reinterpret_cast<std::string*>(data) += reason;
631 }
632
633 } // namespace art
634
635 namespace std {
636
637 template <typename T>
operator <<(std::ostream & os,const std::vector<T> & rhs)638 std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
639 os << ::art::ToString(rhs);
640 return os;
641 }
642
643 } // namespace std
644