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