• 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 <dirent.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <cstdio>
24 #include "nativehelper/scoped_local_ref.h"
25 
26 #include "android-base/stringprintf.h"
27 
28 #include "art_field-inl.h"
29 #include "base/file_utils.h"
30 #include "base/logging.h"
31 #include "base/macros.h"
32 #include "base/mem_map.h"
33 #include "base/mutex.h"
34 #include "base/os.h"
35 #include "base/runtime_debug.h"
36 #include "base/stl_util.h"
37 #include "base/unix_file/fd_file.h"
38 #include "class_linker.h"
39 #include "class_loader_utils.h"
40 #include "compiler_callbacks.h"
41 #include "dex/art_dex_file_loader.h"
42 #include "dex/dex_file-inl.h"
43 #include "dex/dex_file_loader.h"
44 #include "dex/method_reference.h"
45 #include "dex/primitive.h"
46 #include "dex/type_reference.h"
47 #include "gc/heap.h"
48 #include "gc/space/image_space.h"
49 #include "gc_root-inl.h"
50 #include "gtest/gtest.h"
51 #include "handle_scope-inl.h"
52 #include "interpreter/unstarted_runtime.h"
53 #include "jni/java_vm_ext.h"
54 #include "jni/jni_internal.h"
55 #include "mirror/class-alloc-inl.h"
56 #include "mirror/class-inl.h"
57 #include "mirror/class_loader-inl.h"
58 #include "mirror/object_array-alloc-inl.h"
59 #include "native/dalvik_system_DexFile.h"
60 #include "noop_compiler_callbacks.h"
61 #include "profile/profile_compilation_info.h"
62 #include "runtime-inl.h"
63 #include "runtime_intrinsics.h"
64 #include "scoped_thread_state_change-inl.h"
65 #include "thread.h"
66 #include "well_known_classes.h"
67 
68 namespace art {
69 
70 using android::base::StringPrintf;
71 
72 static bool unstarted_initialized_ = false;
73 
CommonRuntimeTestImpl()74 CommonRuntimeTestImpl::CommonRuntimeTestImpl()
75     : class_linker_(nullptr),
76       java_lang_dex_file_(nullptr),
77       boot_class_path_(),
78       callbacks_(),
79       use_boot_image_(false) {
80 }
81 
~CommonRuntimeTestImpl()82 CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
83   // Ensure the dex files are cleaned up before the runtime.
84   loaded_dex_files_.clear();
85   runtime_.reset();
86 }
87 
SetUp()88 void CommonRuntimeTestImpl::SetUp() {
89   CommonArtTestImpl::SetUp();
90 
91   std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
92   std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
93 
94   RuntimeOptions options;
95   std::string boot_class_path_string =
96       GetClassPathOption("-Xbootclasspath:", GetLibCoreDexFileNames());
97   std::string boot_class_path_locations_string =
98       GetClassPathOption("-Xbootclasspath-locations:", GetLibCoreDexLocations());
99 
100   options.push_back(std::make_pair(boot_class_path_string, nullptr));
101   options.push_back(std::make_pair(boot_class_path_locations_string, nullptr));
102   if (use_boot_image_) {
103     options.emplace_back("-Ximage:" + GetImageLocation(), nullptr);
104   }
105   options.push_back(std::make_pair("-Xcheck:jni", nullptr));
106   options.push_back(std::make_pair(min_heap_string, nullptr));
107   options.push_back(std::make_pair(max_heap_string, nullptr));
108 
109   // Technically this is redundant w/ common_art_test, but still check.
110   options.push_back(std::make_pair("-XX:SlowDebug=true", nullptr));
111   static bool gSlowDebugTestFlag = false;
112   RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
113 
114   callbacks_.reset(new NoopCompilerCallbacks());
115 
116   SetUpRuntimeOptions(&options);
117 
118   // Install compiler-callbacks if SetUpRuntimeOptions hasn't deleted them.
119   if (callbacks_.get() != nullptr) {
120     options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
121   }
122 
123   PreRuntimeCreate();
124   if (!Runtime::Create(options, false)) {
125     LOG(FATAL) << "Failed to create runtime";
126     UNREACHABLE();
127   }
128   PostRuntimeCreate();
129   runtime_.reset(Runtime::Current());
130   class_linker_ = runtime_->GetClassLinker();
131 
132   // Runtime::Create acquired the mutator_lock_ that is normally given away when we
133   // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
134   Thread::Current()->TransitionFromRunnableToSuspended(ThreadState::kNative);
135 
136   // Get the boot class path from the runtime so it can be used in tests.
137   boot_class_path_ = class_linker_->GetBootClassPath();
138   ASSERT_FALSE(boot_class_path_.empty());
139   java_lang_dex_file_ = boot_class_path_[0];
140 
141   FinalizeSetup();
142 
143   if (kIsDebugBuild) {
144     // Ensure that we're really running with debug checks enabled.
145     CHECK(gSlowDebugTestFlag);
146   }
147 }
148 
FinalizeSetup()149 void CommonRuntimeTestImpl::FinalizeSetup() {
150   // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
151   // set up.
152   if (!unstarted_initialized_) {
153     interpreter::UnstartedRuntime::Initialize();
154     unstarted_initialized_ = true;
155   } else {
156     interpreter::UnstartedRuntime::Reinitialize();
157   }
158 
159   {
160     ScopedObjectAccess soa(Thread::Current());
161     runtime_->RunRootClinits(soa.Self());
162   }
163 
164   // We're back in native, take the opportunity to initialize well known classes and ensure
165   // intrinsics are initialized.
166   WellKnownClasses::Init(Thread::Current()->GetJniEnv());
167   InitializeIntrinsics();
168 
169   // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
170   // pool is created by the runtime.
171   runtime_->GetHeap()->CreateThreadPool();
172   runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
173   // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
174   runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
175 }
176 
TearDown()177 void CommonRuntimeTestImpl::TearDown() {
178   CommonArtTestImpl::TearDown();
179   if (runtime_ != nullptr) {
180     runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
181   }
182 }
183 
184 // Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
185 #ifdef ART_TARGET
186 #ifndef ART_TARGET_NATIVETEST_DIR
187 #error "ART_TARGET_NATIVETEST_DIR not set."
188 #endif
189 // Wrap it as a string literal.
190 #define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
191 #else
192 #define ART_TARGET_NATIVETEST_DIR_STRING ""
193 #endif
194 
GetDexFiles(jobject jclass_loader)195 std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
196   ScopedObjectAccess soa(Thread::Current());
197 
198   StackHandleScope<1> hs(soa.Self());
199   Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
200       soa.Decode<mirror::ClassLoader>(jclass_loader));
201   return GetDexFiles(soa, class_loader);
202 }
203 
GetDexFiles(ScopedObjectAccess & soa,Handle<mirror::ClassLoader> class_loader)204 std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(
205     ScopedObjectAccess& soa,
206     Handle<mirror::ClassLoader> class_loader) {
207   DCHECK(
208       (class_loader->GetClass() ==
209           soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader)) ||
210       (class_loader->GetClass() ==
211           soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_DelegateLastClassLoader)));
212 
213   std::vector<const DexFile*> ret;
214   VisitClassLoaderDexFiles(soa,
215                            class_loader,
216                            [&](const DexFile* cp_dex_file) {
217                              if (cp_dex_file == nullptr) {
218                                LOG(WARNING) << "Null DexFile";
219                              } else {
220                                ret.push_back(cp_dex_file);
221                              }
222                              return true;
223                            });
224   return ret;
225 }
226 
GetFirstDexFile(jobject jclass_loader)227 const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
228   std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
229   DCHECK(!tmp.empty());
230   const DexFile* ret = tmp[0];
231   DCHECK(ret != nullptr);
232   return ret;
233 }
234 
LoadMultiDex(const char * first_dex_name,const char * second_dex_name)235 jobject CommonRuntimeTestImpl::LoadMultiDex(const char* first_dex_name,
236                                             const char* second_dex_name) {
237   std::vector<std::unique_ptr<const DexFile>> first_dex_files = OpenTestDexFiles(first_dex_name);
238   std::vector<std::unique_ptr<const DexFile>> second_dex_files = OpenTestDexFiles(second_dex_name);
239   std::vector<const DexFile*> class_path;
240   CHECK_NE(0U, first_dex_files.size());
241   CHECK_NE(0U, second_dex_files.size());
242   for (auto& dex_file : first_dex_files) {
243     class_path.push_back(dex_file.get());
244     loaded_dex_files_.push_back(std::move(dex_file));
245   }
246   for (auto& dex_file : second_dex_files) {
247     class_path.push_back(dex_file.get());
248     loaded_dex_files_.push_back(std::move(dex_file));
249   }
250 
251   Thread* self = Thread::Current();
252   jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
253                                                                                      class_path);
254   self->SetClassLoaderOverride(class_loader);
255   return class_loader;
256 }
257 
LoadDex(const char * dex_name)258 jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
259   jobject class_loader = LoadDexInPathClassLoader(dex_name, nullptr);
260   Thread::Current()->SetClassLoaderOverride(class_loader);
261   return class_loader;
262 }
263 
264 jobject
LoadDexInWellKnownClassLoader(const std::vector<std::string> & dex_names,jclass loader_class,jobject parent_loader,jobject shared_libraries,jobject shared_libraries_after)265 CommonRuntimeTestImpl::LoadDexInWellKnownClassLoader(const std::vector<std::string>& dex_names,
266                                                      jclass loader_class,
267                                                      jobject parent_loader,
268                                                      jobject shared_libraries,
269                                                      jobject shared_libraries_after) {
270   std::vector<const DexFile*> class_path;
271   for (const std::string& dex_name : dex_names) {
272     std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name.c_str());
273     CHECK_NE(0U, dex_files.size());
274     for (auto& dex_file : dex_files) {
275       class_path.push_back(dex_file.get());
276       loaded_dex_files_.push_back(std::move(dex_file));
277     }
278   }
279   Thread* self = Thread::Current();
280   ScopedObjectAccess soa(self);
281 
282   jobject result = Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
283       self,
284       class_path,
285       loader_class,
286       parent_loader,
287       shared_libraries,
288       shared_libraries_after);
289 
290   {
291     // Verify we build the correct chain.
292 
293     ObjPtr<mirror::ClassLoader> actual_class_loader = soa.Decode<mirror::ClassLoader>(result);
294     // Verify that the result has the correct class.
295     CHECK_EQ(soa.Decode<mirror::Class>(loader_class), actual_class_loader->GetClass());
296     // Verify that the parent is not null. The boot class loader will be set up as a
297     // proper object.
298     ObjPtr<mirror::ClassLoader> actual_parent(actual_class_loader->GetParent());
299     CHECK(actual_parent != nullptr);
300 
301     if (parent_loader != nullptr) {
302       // We were given a parent. Verify that it's what we expect.
303       ObjPtr<mirror::ClassLoader> expected_parent = soa.Decode<mirror::ClassLoader>(parent_loader);
304       CHECK_EQ(expected_parent, actual_parent);
305     } else {
306       // No parent given. The parent must be the BootClassLoader.
307       CHECK(Runtime::Current()->GetClassLinker()->IsBootClassLoader(soa, actual_parent));
308     }
309   }
310 
311   return result;
312 }
313 
LoadDexInPathClassLoader(const std::string & dex_name,jobject parent_loader,jobject shared_libraries,jobject shared_libraries_after)314 jobject CommonRuntimeTestImpl::LoadDexInPathClassLoader(const std::string& dex_name,
315                                                         jobject parent_loader,
316                                                         jobject shared_libraries,
317                                                         jobject shared_libraries_after) {
318   return LoadDexInPathClassLoader(std::vector<std::string>{ dex_name },
319                                   parent_loader,
320                                   shared_libraries,
321                                   shared_libraries_after);
322 }
323 
LoadDexInPathClassLoader(const std::vector<std::string> & names,jobject parent_loader,jobject shared_libraries,jobject shared_libraries_after)324 jobject CommonRuntimeTestImpl::LoadDexInPathClassLoader(const std::vector<std::string>& names,
325                                                         jobject parent_loader,
326                                                         jobject shared_libraries,
327                                                         jobject shared_libraries_after) {
328   return LoadDexInWellKnownClassLoader(names,
329                                        WellKnownClasses::dalvik_system_PathClassLoader,
330                                        parent_loader,
331                                        shared_libraries,
332                                        shared_libraries_after);
333 }
334 
LoadDexInDelegateLastClassLoader(const std::string & dex_name,jobject parent_loader)335 jobject CommonRuntimeTestImpl::LoadDexInDelegateLastClassLoader(const std::string& dex_name,
336                                                                 jobject parent_loader) {
337   return LoadDexInWellKnownClassLoader({ dex_name },
338                                        WellKnownClasses::dalvik_system_DelegateLastClassLoader,
339                                        parent_loader);
340 }
341 
LoadDexInInMemoryDexClassLoader(const std::string & dex_name,jobject parent_loader)342 jobject CommonRuntimeTestImpl::LoadDexInInMemoryDexClassLoader(const std::string& dex_name,
343                                                                jobject parent_loader) {
344   return LoadDexInWellKnownClassLoader({ dex_name },
345                                        WellKnownClasses::dalvik_system_InMemoryDexClassLoader,
346                                        parent_loader);
347 }
348 
FillHeap(Thread * self,ClassLinker * class_linker,VariableSizedHandleScope * handle_scope)349 void CommonRuntimeTestImpl::FillHeap(Thread* self,
350                                      ClassLinker* class_linker,
351                                      VariableSizedHandleScope* handle_scope) {
352   DCHECK(handle_scope != nullptr);
353 
354   Runtime::Current()->GetHeap()->SetIdealFootprint(1 * GB);
355 
356   // Class java.lang.Object.
357   Handle<mirror::Class> c(handle_scope->NewHandle(
358       class_linker->FindSystemClass(self, "Ljava/lang/Object;")));
359   // Array helps to fill memory faster.
360   Handle<mirror::Class> ca(handle_scope->NewHandle(
361       class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
362 
363   // Start allocating with ~128K
364   size_t length = 128 * KB;
365   while (length > 40) {
366     const int32_t array_length = length / 4;  // Object[] has elements of size 4.
367     MutableHandle<mirror::Object> h(handle_scope->NewHandle<mirror::Object>(
368         mirror::ObjectArray<mirror::Object>::Alloc(self, ca.Get(), array_length)));
369     if (self->IsExceptionPending() || h == nullptr) {
370       self->ClearException();
371 
372       // Try a smaller length
373       length = length / 2;
374       // Use at most a quarter the reported free space.
375       size_t mem = Runtime::Current()->GetHeap()->GetFreeMemory();
376       if (length * 4 > mem) {
377         length = mem / 4;
378       }
379     }
380   }
381 
382   // Allocate simple objects till it fails.
383   while (!self->IsExceptionPending()) {
384     handle_scope->NewHandle<mirror::Object>(c->AllocObject(self));
385   }
386   self->ClearException();
387 }
388 
SetUpRuntimeOptionsForFillHeap(RuntimeOptions * options)389 void CommonRuntimeTestImpl::SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options) {
390   // Use a smaller heap
391   bool found = false;
392   for (std::pair<std::string, const void*>& pair : *options) {
393     if (pair.first.find("-Xmx") == 0) {
394       pair.first = "-Xmx4M";  // Smallest we can go.
395       found = true;
396     }
397   }
398   if (!found) {
399     options->emplace_back("-Xmx4M", nullptr);
400   }
401 }
402 
MakeInterpreted(ObjPtr<mirror::Class> klass)403 void CommonRuntimeTestImpl::MakeInterpreted(ObjPtr<mirror::Class> klass) {
404   PointerSize pointer_size = class_linker_->GetImagePointerSize();
405   for (ArtMethod& method : klass->GetMethods(pointer_size)) {
406     Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(&method, /*aot_code=*/ nullptr);
407   }
408 }
409 
StartDex2OatCommandLine(std::vector<std::string> * argv,std::string * error_msg,bool use_runtime_bcp_and_image)410 bool CommonRuntimeTestImpl::StartDex2OatCommandLine(/*out*/std::vector<std::string>* argv,
411                                                     /*out*/std::string* error_msg,
412                                                     bool use_runtime_bcp_and_image) {
413   DCHECK(argv != nullptr);
414   DCHECK(argv->empty());
415 
416   Runtime* runtime = Runtime::Current();
417   if (use_runtime_bcp_and_image && runtime->GetHeap()->GetBootImageSpaces().empty()) {
418     *error_msg = "No image location found for Dex2Oat.";
419     return false;
420   }
421 
422   argv->push_back(runtime->GetCompilerExecutable());
423   if (runtime->IsJavaDebuggable()) {
424     argv->push_back("--debuggable");
425   }
426   runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(argv);
427 
428   if (use_runtime_bcp_and_image) {
429     argv->push_back("--runtime-arg");
430     argv->push_back(GetClassPathOption("-Xbootclasspath:", GetLibCoreDexFileNames()));
431     argv->push_back("--runtime-arg");
432     argv->push_back(GetClassPathOption("-Xbootclasspath-locations:", GetLibCoreDexLocations()));
433 
434     const std::vector<gc::space::ImageSpace*>& image_spaces =
435         runtime->GetHeap()->GetBootImageSpaces();
436     DCHECK(!image_spaces.empty());
437     argv->push_back("--boot-image=" + image_spaces[0]->GetImageLocation());
438   }
439 
440   std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
441   argv->insert(argv->end(), compiler_options.begin(), compiler_options.end());
442   return true;
443 }
444 
CompileBootImage(const std::vector<std::string> & extra_args,const std::string & image_file_name_prefix,ArrayRef<const std::string> dex_files,ArrayRef<const std::string> dex_locations,std::string * error_msg,const std::string & use_fd_prefix)445 bool CommonRuntimeTestImpl::CompileBootImage(const std::vector<std::string>& extra_args,
446                                              const std::string& image_file_name_prefix,
447                                              ArrayRef<const std::string> dex_files,
448                                              ArrayRef<const std::string> dex_locations,
449                                              std::string* error_msg,
450                                              const std::string& use_fd_prefix) {
451   Runtime* const runtime = Runtime::Current();
452   std::vector<std::string> argv {
453     runtime->GetCompilerExecutable(),
454     "--runtime-arg",
455     "-Xms64m",
456     "--runtime-arg",
457     "-Xmx64m",
458     "--runtime-arg",
459     "-Xverify:softfail",
460     "--force-determinism",
461   };
462   CHECK_EQ(dex_files.size(), dex_locations.size());
463   for (const std::string& dex_file : dex_files) {
464     argv.push_back("--dex-file=" + dex_file);
465   }
466   for (const std::string& dex_location : dex_locations) {
467     argv.push_back("--dex-location=" + dex_location);
468   }
469   if (runtime->IsJavaDebuggable()) {
470     argv.push_back("--debuggable");
471   }
472   runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
473 
474   if (!kIsTargetBuild) {
475     argv.push_back("--host");
476   }
477 
478   std::unique_ptr<File> art_file;
479   std::unique_ptr<File> vdex_file;
480   std::unique_ptr<File> oat_file;
481   if (!use_fd_prefix.empty()) {
482     art_file.reset(OS::CreateEmptyFile((use_fd_prefix + ".art").c_str()));
483     vdex_file.reset(OS::CreateEmptyFile((use_fd_prefix + ".vdex").c_str()));
484     oat_file.reset(OS::CreateEmptyFile((use_fd_prefix + ".oat").c_str()));
485     argv.push_back("--image-fd=" + std::to_string(art_file->Fd()));
486     argv.push_back("--output-vdex-fd=" + std::to_string(vdex_file->Fd()));
487     argv.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
488     argv.push_back("--oat-location=" + image_file_name_prefix + ".oat");
489   } else {
490     argv.push_back("--image=" + image_file_name_prefix + ".art");
491     argv.push_back("--oat-file=" + image_file_name_prefix + ".oat");
492     argv.push_back("--oat-location=" + image_file_name_prefix + ".oat");
493   }
494 
495   std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
496   argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
497 
498   // We must set --android-root.
499   const char* android_root = getenv("ANDROID_ROOT");
500   CHECK(android_root != nullptr);
501   argv.push_back("--android-root=" + std::string(android_root));
502   argv.insert(argv.end(), extra_args.begin(), extra_args.end());
503 
504   bool result = RunDex2Oat(argv, error_msg);
505   if (art_file != nullptr) {
506     CHECK_EQ(0, art_file->FlushClose());
507   }
508   if (vdex_file != nullptr) {
509     CHECK_EQ(0, vdex_file->FlushClose());
510   }
511   if (oat_file != nullptr) {
512     CHECK_EQ(0, oat_file->FlushClose());
513   }
514   return result;
515 }
516 
RunDex2Oat(const std::vector<std::string> & args,std::string * error_msg)517 bool CommonRuntimeTestImpl::RunDex2Oat(const std::vector<std::string>& args,
518                                        std::string* error_msg) {
519   // We only want fatal logging for the error message.
520   auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:f", 1) == 0; };
521   ForkAndExecResult res = ForkAndExec(args, post_fork_fn, error_msg);
522   if (res.stage != ForkAndExecResult::kFinished) {
523     *error_msg = strerror(errno);
524     return false;
525   }
526   return res.StandardSuccess();
527 }
528 
GetImageLocation()529 std::string CommonRuntimeTestImpl::GetImageLocation() {
530   return GetImageDirectory() + "/boot.art";
531 }
532 
GetSystemImageFile()533 std::string CommonRuntimeTestImpl::GetSystemImageFile() {
534   std::string isa = GetInstructionSetString(kRuntimeISA);
535   return GetImageDirectory() + "/" + isa + "/boot.art";
536 }
537 
EnterTransactionMode()538 void CommonRuntimeTestImpl::EnterTransactionMode() {
539   CHECK(!Runtime::Current()->IsActiveTransaction());
540   Runtime::Current()->EnterTransactionMode(/*strict=*/ false, /*root=*/ nullptr);
541 }
542 
ExitTransactionMode()543 void CommonRuntimeTestImpl::ExitTransactionMode() {
544   Runtime::Current()->ExitTransactionMode();
545   CHECK(!Runtime::Current()->IsActiveTransaction());
546 }
547 
RollbackAndExitTransactionMode()548 void CommonRuntimeTestImpl::RollbackAndExitTransactionMode() {
549   Runtime::Current()->RollbackAndExitTransactionMode();
550   CHECK(!Runtime::Current()->IsActiveTransaction());
551 }
552 
IsTransactionAborted()553 bool CommonRuntimeTestImpl::IsTransactionAborted() {
554   return Runtime::Current()->IsTransactionAborted();
555 }
556 
VisitDexes(ArrayRef<const std::string> dexes,const std::function<void (MethodReference)> & method_visitor,const std::function<void (TypeReference)> & class_visitor,size_t method_frequency,size_t class_frequency)557 void CommonRuntimeTestImpl::VisitDexes(ArrayRef<const std::string> dexes,
558                                        const std::function<void(MethodReference)>& method_visitor,
559                                        const std::function<void(TypeReference)>& class_visitor,
560                                        size_t method_frequency,
561                                        size_t class_frequency) {
562   size_t method_counter = 0;
563   size_t class_counter = 0;
564   for (const std::string& dex : dexes) {
565     std::vector<std::unique_ptr<const DexFile>> dex_files;
566     std::string error_msg;
567     const ArtDexFileLoader dex_file_loader;
568     CHECK(dex_file_loader.Open(dex.c_str(),
569                                dex,
570                                /*verify*/ true,
571                                /*verify_checksum*/ false,
572                                &error_msg,
573                                &dex_files))
574         << error_msg;
575     for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
576       for (size_t i = 0; i < dex_file->NumMethodIds(); ++i) {
577         if (++method_counter % method_frequency == 0) {
578           method_visitor(MethodReference(dex_file.get(), i));
579         }
580       }
581       for (size_t i = 0; i < dex_file->NumTypeIds(); ++i) {
582         if (++class_counter % class_frequency == 0) {
583           class_visitor(TypeReference(dex_file.get(), dex::TypeIndex(i)));
584         }
585       }
586     }
587   }
588 }
589 
GenerateProfile(ArrayRef<const std::string> dexes,File * out_file,size_t method_frequency,size_t type_frequency,bool for_boot_image)590 void CommonRuntimeTestImpl::GenerateProfile(ArrayRef<const std::string> dexes,
591                                             File* out_file,
592                                             size_t method_frequency,
593                                             size_t type_frequency,
594                                             bool for_boot_image) {
595   ProfileCompilationInfo profile(for_boot_image);
596   VisitDexes(
597       dexes,
598       [&profile](MethodReference ref) {
599         uint32_t flags = ProfileCompilationInfo::MethodHotness::kFlagHot |
600             ProfileCompilationInfo::MethodHotness::kFlagStartup;
601         EXPECT_TRUE(profile.AddMethod(
602             ProfileMethodInfo(ref),
603             static_cast<ProfileCompilationInfo::MethodHotness::Flag>(flags)));
604       },
605       [&profile](TypeReference ref) {
606         std::set<dex::TypeIndex> classes;
607         classes.insert(ref.TypeIndex());
608         EXPECT_TRUE(profile.AddClassesForDex(ref.dex_file, classes.begin(), classes.end()));
609       },
610       method_frequency,
611       type_frequency);
612   profile.Save(out_file->Fd());
613   EXPECT_EQ(out_file->Flush(), 0);
614 }
615 
CheckJniAbortCatcher()616 CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
617   vm_->SetCheckJniAbortHook(Hook, &actual_);
618 }
619 
~CheckJniAbortCatcher()620 CheckJniAbortCatcher::~CheckJniAbortCatcher() {
621   vm_->SetCheckJniAbortHook(nullptr, nullptr);
622   EXPECT_TRUE(actual_.empty()) << actual_;
623 }
624 
Check(const std::string & expected_text)625 void CheckJniAbortCatcher::Check(const std::string& expected_text) {
626   Check(expected_text.c_str());
627 }
628 
Check(const char * expected_text)629 void CheckJniAbortCatcher::Check(const char* expected_text) {
630   EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
631       << "Expected to find: " << expected_text << "\n"
632       << "In the output   : " << actual_;
633   actual_.clear();
634 }
635 
Hook(void * data,const std::string & reason)636 void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
637   // We use += because when we're hooking the aborts like this, multiple problems can be found.
638   *reinterpret_cast<std::string*>(data) += reason;
639 }
640 
641 }  // namespace art
642