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