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