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