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