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