1 /*
2 * Copyright (C) 2011 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 "compiler_driver.h"
18
19 #include <unistd.h>
20
21 #ifndef __APPLE__
22 #include <malloc.h> // For mallinfo
23 #endif
24
25 #include <string_view>
26 #include <vector>
27
28 #include <android-base/logging.h>
29 #include <android-base/strings.h>
30
31 #include "aot_class_linker.h"
32 #include "art_field-inl.h"
33 #include "art_method-inl.h"
34 #include "base/arena_allocator.h"
35 #include "base/array_ref.h"
36 #include "base/bit_vector.h"
37 #include "base/hash_set.h"
38 #include "base/logging.h" // For VLOG
39 #include "base/pointer_size.h"
40 #include "base/stl_util.h"
41 #include "base/systrace.h"
42 #include "base/time_utils.h"
43 #include "base/timing_logger.h"
44 #include "class_linker-inl.h"
45 #include "class_root-inl.h"
46 #include "common_throws.h"
47 #include "compiled_method-inl.h"
48 #include "compiler.h"
49 #include "compiler_callbacks.h"
50 #include "compiler_driver-inl.h"
51 #include "dex/class_accessor-inl.h"
52 #include "dex/descriptors_names.h"
53 #include "dex/dex_file-inl.h"
54 #include "dex/dex_file_annotations.h"
55 #include "dex/dex_file_exception_helpers.h"
56 #include "dex/dex_instruction-inl.h"
57 #include "dex/verification_results.h"
58 #include "driver/compiler_options.h"
59 #include "driver/dex_compilation_unit.h"
60 #include "gc/accounting/card_table-inl.h"
61 #include "gc/accounting/heap_bitmap.h"
62 #include "gc/space/image_space.h"
63 #include "gc/space/space.h"
64 #include "handle_scope-inl.h"
65 #include "intrinsics_enum.h"
66 #include "intrinsics_list.h"
67 #include "jni/jni_internal.h"
68 #include "linker/linker_patch.h"
69 #include "mirror/class-inl.h"
70 #include "mirror/class_loader.h"
71 #include "mirror/dex_cache-inl.h"
72 #include "mirror/object-inl.h"
73 #include "mirror/object-refvisitor-inl.h"
74 #include "mirror/object_array-inl.h"
75 #include "mirror/throwable.h"
76 #include "object_lock.h"
77 #include "profile/profile_compilation_info.h"
78 #include "runtime.h"
79 #include "runtime_intrinsics.h"
80 #include "scoped_thread_state_change-inl.h"
81 #include "thread.h"
82 #include "thread_list.h"
83 #include "thread_pool.h"
84 #include "trampolines/trampoline_compiler.h"
85 #include "utils/atomic_dex_ref_map-inl.h"
86 #include "utils/swap_space.h"
87 #include "vdex_file.h"
88 #include "verifier/class_verifier.h"
89 #include "verifier/verifier_deps.h"
90 #include "verifier/verifier_enums.h"
91 #include "well_known_classes-inl.h"
92
93 namespace art {
94
95 static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
96
97 // Print additional info during profile guided compilation.
98 static constexpr bool kDebugProfileGuidedCompilation = false;
99
100 // Max encoded fields allowed for initializing app image. Hardcode the number for now
101 // because 5000 should be large enough.
102 static constexpr uint32_t kMaxEncodedFields = 5000;
103
Percentage(size_t x,size_t y)104 static double Percentage(size_t x, size_t y) {
105 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
106 }
107
DumpStat(size_t x,size_t y,const char * str)108 static void DumpStat(size_t x, size_t y, const char* str) {
109 if (x == 0 && y == 0) {
110 return;
111 }
112 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
113 }
114
115 class CompilerDriver::AOTCompilationStats {
116 public:
AOTCompilationStats()117 AOTCompilationStats()
118 : stats_lock_("AOT compilation statistics lock") {}
119
Dump()120 void Dump() {
121 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
122 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
123 "static fields resolved");
124 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
125 "static fields local to a class");
126 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
127 // Note, the code below subtracts the stat value so that when added to the stat value we have
128 // 100% of samples. TODO: clean this up.
129 DumpStat(type_based_devirtualization_,
130 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
131 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
132 type_based_devirtualization_,
133 "virtual/interface calls made direct based on type information");
134
135 const size_t total = std::accumulate(
136 class_status_count_,
137 class_status_count_ + static_cast<size_t>(ClassStatus::kLast) + 1,
138 0u);
139 for (size_t i = 0; i <= static_cast<size_t>(ClassStatus::kLast); ++i) {
140 std::ostringstream oss;
141 oss << "classes with status " << static_cast<ClassStatus>(i);
142 DumpStat(class_status_count_[i], total - class_status_count_[i], oss.str().c_str());
143 }
144
145 for (size_t i = 0; i <= kMaxInvokeType; i++) {
146 std::ostringstream oss;
147 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
148 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
149 if (virtual_made_direct_[i] > 0) {
150 std::ostringstream oss2;
151 oss2 << static_cast<InvokeType>(i) << " methods made direct";
152 DumpStat(virtual_made_direct_[i],
153 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
154 oss2.str().c_str());
155 }
156 if (direct_calls_to_boot_[i] > 0) {
157 std::ostringstream oss2;
158 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
159 DumpStat(direct_calls_to_boot_[i],
160 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
161 oss2.str().c_str());
162 }
163 if (direct_methods_to_boot_[i] > 0) {
164 std::ostringstream oss2;
165 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
166 DumpStat(direct_methods_to_boot_[i],
167 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
168 oss2.str().c_str());
169 }
170 }
171 }
172
173 // Allow lossy statistics in non-debug builds.
174 #ifndef NDEBUG
175 #define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
176 #else
177 #define STATS_LOCK()
178 #endif
179
ResolvedInstanceField()180 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
181 STATS_LOCK();
182 resolved_instance_fields_++;
183 }
184
UnresolvedInstanceField()185 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
186 STATS_LOCK();
187 unresolved_instance_fields_++;
188 }
189
ResolvedLocalStaticField()190 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
191 STATS_LOCK();
192 resolved_local_static_fields_++;
193 }
194
ResolvedStaticField()195 void ResolvedStaticField() REQUIRES(!stats_lock_) {
196 STATS_LOCK();
197 resolved_static_fields_++;
198 }
199
UnresolvedStaticField()200 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
201 STATS_LOCK();
202 unresolved_static_fields_++;
203 }
204
205 // Indicate that type information from the verifier led to devirtualization.
PreciseTypeDevirtualization()206 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
207 STATS_LOCK();
208 type_based_devirtualization_++;
209 }
210
211 // A check-cast could be eliminated due to verifier type analysis.
SafeCast()212 void SafeCast() REQUIRES(!stats_lock_) {
213 STATS_LOCK();
214 safe_casts_++;
215 }
216
217 // A check-cast couldn't be eliminated due to verifier type analysis.
NotASafeCast()218 void NotASafeCast() REQUIRES(!stats_lock_) {
219 STATS_LOCK();
220 not_safe_casts_++;
221 }
222
223 // Register a class status.
AddClassStatus(ClassStatus status)224 void AddClassStatus(ClassStatus status) REQUIRES(!stats_lock_) {
225 STATS_LOCK();
226 ++class_status_count_[static_cast<size_t>(status)];
227 }
228
229 private:
230 Mutex stats_lock_;
231
232 size_t resolved_instance_fields_ = 0u;
233 size_t unresolved_instance_fields_ = 0u;
234
235 size_t resolved_local_static_fields_ = 0u;
236 size_t resolved_static_fields_ = 0u;
237 size_t unresolved_static_fields_ = 0u;
238 // Type based devirtualization for invoke interface and virtual.
239 size_t type_based_devirtualization_ = 0u;
240
241 size_t resolved_methods_[kMaxInvokeType + 1] = {};
242 size_t unresolved_methods_[kMaxInvokeType + 1] = {};
243 size_t virtual_made_direct_[kMaxInvokeType + 1] = {};
244 size_t direct_calls_to_boot_[kMaxInvokeType + 1] = {};
245 size_t direct_methods_to_boot_[kMaxInvokeType + 1] = {};
246
247 size_t safe_casts_ = 0u;
248 size_t not_safe_casts_ = 0u;
249
250 size_t class_status_count_[static_cast<size_t>(ClassStatus::kLast) + 1] = {};
251
252 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
253 };
254
CompilerDriver(const CompilerOptions * compiler_options,const VerificationResults * verification_results,size_t thread_count,int swap_fd)255 CompilerDriver::CompilerDriver(
256 const CompilerOptions* compiler_options,
257 const VerificationResults* verification_results,
258 size_t thread_count,
259 int swap_fd)
260 : compiler_options_(compiler_options),
261 verification_results_(verification_results),
262 compiler_(),
263 number_of_soft_verifier_failures_(0),
264 had_hard_verifier_failure_(false),
265 parallel_thread_count_(thread_count),
266 stats_(new AOTCompilationStats),
267 compiled_method_storage_(swap_fd),
268 max_arena_alloc_(0) {
269 DCHECK(compiler_options_ != nullptr);
270
271 compiled_method_storage_.SetDedupeEnabled(compiler_options_->DeduplicateCode());
272 compiler_.reset(Compiler::Create(*compiler_options, &compiled_method_storage_));
273 }
274
~CompilerDriver()275 CompilerDriver::~CompilerDriver() {
276 compiled_methods_.Visit(
277 [this]([[maybe_unused]] const DexFileReference& ref, CompiledMethod* method) {
278 if (method != nullptr) {
279 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(GetCompiledMethodStorage(), method);
280 }
281 });
282 }
283
284
285 #define CREATE_TRAMPOLINE(type, abi, offset) \
286 if (Is64BitInstructionSet(GetCompilerOptions().GetInstructionSet())) { \
287 return CreateTrampoline64(GetCompilerOptions().GetInstructionSet(), \
288 abi, \
289 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
290 } else { \
291 return CreateTrampoline32(GetCompilerOptions().GetInstructionSet(), \
292 abi, \
293 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
294 }
295
CreateJniDlsymLookupTrampoline() const296 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookupTrampoline() const {
297 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
298 }
299
300 std::unique_ptr<const std::vector<uint8_t>>
CreateJniDlsymLookupCriticalTrampoline() const301 CompilerDriver::CreateJniDlsymLookupCriticalTrampoline() const {
302 // @CriticalNative calls do not have the `JNIEnv*` parameter, so this trampoline uses the
303 // architecture-dependent access to `Thread*` using the managed code ABI, i.e. `kQuickAbi`.
304 CREATE_TRAMPOLINE(JNI, kQuickAbi, pDlsymLookupCritical)
305 }
306
CreateQuickGenericJniTrampoline() const307 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
308 const {
309 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
310 }
311
CreateQuickImtConflictTrampoline() const312 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
313 const {
314 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
315 }
316
CreateQuickResolutionTrampoline() const317 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
318 const {
319 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
320 }
321
CreateQuickToInterpreterBridge() const322 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
323 const {
324 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
325 }
326
CreateNterpTrampoline() const327 std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateNterpTrampoline()
328 const {
329 // We use QuickToInterpreterBridge to not waste one word in the Thread object.
330 // The Nterp trampoline gets replaced with the nterp entrypoint when loading
331 // an image.
332 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
333 }
334 #undef CREATE_TRAMPOLINE
335
CompileAll(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)336 void CompilerDriver::CompileAll(jobject class_loader,
337 const std::vector<const DexFile*>& dex_files,
338 TimingLogger* timings) {
339 DCHECK(!Runtime::Current()->IsStarted());
340
341 CheckThreadPools();
342
343 // Compile:
344 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
345 // compilation.
346 if (GetCompilerOptions().IsAnyCompilationEnabled()) {
347 Compile(class_loader, dex_files, timings);
348 }
349 if (GetCompilerOptions().GetDumpStats()) {
350 stats_->Dump();
351 }
352 }
353
354 // Does the runtime for the InstructionSet provide an implementation returned by
355 // GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
InstructionSetHasGenericJniStub(InstructionSet isa)356 static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
357 switch (isa) {
358 case InstructionSet::kArm:
359 case InstructionSet::kArm64:
360 case InstructionSet::kThumb2:
361 case InstructionSet::kX86:
362 case InstructionSet::kX86_64: return true;
363 default: return false;
364 }
365 }
366
367 template <typename CompileFn>
CompileMethodHarness(Thread * self,CompilerDriver * driver,const dex::CodeItem * code_item,uint32_t access_flags,uint16_t class_def_idx,uint32_t method_idx,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache,CompileFn compile_fn)368 static void CompileMethodHarness(
369 Thread* self,
370 CompilerDriver* driver,
371 const dex::CodeItem* code_item,
372 uint32_t access_flags,
373 uint16_t class_def_idx,
374 uint32_t method_idx,
375 Handle<mirror::ClassLoader> class_loader,
376 const DexFile& dex_file,
377 Handle<mirror::DexCache> dex_cache,
378 CompileFn compile_fn) {
379 DCHECK(driver != nullptr);
380 CompiledMethod* compiled_method;
381 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
382 MethodReference method_ref(&dex_file, method_idx);
383
384 compiled_method = compile_fn(self,
385 driver,
386 code_item,
387 access_flags,
388 class_def_idx,
389 method_idx,
390 class_loader,
391 dex_file,
392 dex_cache);
393
394 if (kTimeCompileMethod) {
395 uint64_t duration_ns = NanoTime() - start_ns;
396 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
397 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
398 << " took " << PrettyDuration(duration_ns);
399 }
400 }
401
402 if (compiled_method != nullptr) {
403 driver->AddCompiledMethod(method_ref, compiled_method);
404 }
405
406 if (self->IsExceptionPending()) {
407 ScopedObjectAccess soa(self);
408 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
409 << self->GetException()->Dump();
410 }
411 }
412
413 // Checks whether profile guided compilation is enabled and if the method should be compiled
414 // according to the profile file.
ShouldCompileBasedOnProfile(const CompilerOptions & compiler_options,ProfileCompilationInfo::ProfileIndexType profile_index,MethodReference method_ref)415 static bool ShouldCompileBasedOnProfile(const CompilerOptions& compiler_options,
416 ProfileCompilationInfo::ProfileIndexType profile_index,
417 MethodReference method_ref) {
418 if (profile_index == ProfileCompilationInfo::MaxProfileIndex()) {
419 // No profile for this dex file. Check if we're actually compiling based on a profile.
420 if (!CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter())) {
421 return true;
422 }
423 // Profile-based compilation without profile for this dex file. Do not compile the method.
424 DCHECK(compiler_options.GetProfileCompilationInfo() == nullptr ||
425 compiler_options.GetProfileCompilationInfo()->FindDexFile(*method_ref.dex_file) ==
426 ProfileCompilationInfo::MaxProfileIndex());
427 return false;
428 } else {
429 DCHECK(CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter()));
430 const ProfileCompilationInfo* profile_compilation_info =
431 compiler_options.GetProfileCompilationInfo();
432 DCHECK(profile_compilation_info != nullptr);
433
434 bool result = profile_compilation_info->IsHotMethod(profile_index, method_ref.index);
435
436 // On non-low RAM devices, compile startup methods to potentially speed up
437 // startup.
438 if (!result && !Runtime::Current()->GetHeap()->IsLowMemoryMode()) {
439 result = profile_compilation_info->IsStartupMethod(profile_index, method_ref.index);
440 }
441
442 if (kDebugProfileGuidedCompilation) {
443 LOG(INFO) << "[ProfileGuidedCompilation] "
444 << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
445 }
446
447
448 return result;
449 }
450 }
451
CompileMethodQuick(Thread * self,CompilerDriver * driver,const dex::CodeItem * code_item,uint32_t access_flags,uint16_t class_def_idx,uint32_t method_idx,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache,ProfileCompilationInfo::ProfileIndexType profile_index)452 static void CompileMethodQuick(
453 Thread* self,
454 CompilerDriver* driver,
455 const dex::CodeItem* code_item,
456 uint32_t access_flags,
457 uint16_t class_def_idx,
458 uint32_t method_idx,
459 Handle<mirror::ClassLoader> class_loader,
460 const DexFile& dex_file,
461 Handle<mirror::DexCache> dex_cache,
462 ProfileCompilationInfo::ProfileIndexType profile_index) {
463 auto quick_fn = [profile_index]([[maybe_unused]] Thread* self,
464 CompilerDriver* driver,
465 const dex::CodeItem* code_item,
466 uint32_t access_flags,
467 uint16_t class_def_idx,
468 uint32_t method_idx,
469 Handle<mirror::ClassLoader> class_loader,
470 const DexFile& dex_file,
471 Handle<mirror::DexCache> dex_cache) {
472 DCHECK(driver != nullptr);
473 const VerificationResults* results = driver->GetVerificationResults();
474 DCHECK(results != nullptr);
475 MethodReference method_ref(&dex_file, method_idx);
476 CompiledMethod* compiled_method = nullptr;
477 if (results->IsUncompilableMethod(method_ref)) {
478 return compiled_method;
479 }
480
481 if ((access_flags & kAccNative) != 0) {
482 // Are we extracting only and have support for generic JNI down calls?
483 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
484 if (!compiler_options.IsJniCompilationEnabled() &&
485 InstructionSetHasGenericJniStub(compiler_options.GetInstructionSet())) {
486 // Leaving this empty will trigger the generic JNI version
487 } else {
488 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
489 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
490 dex_file, dex_file.GetClassDef(class_def_idx), method_idx);
491 const void* boot_jni_stub = nullptr;
492 if (!Runtime::Current()->GetHeap()->GetBootImageSpaces().empty()) {
493 // Skip the compilation for native method if found an usable boot JNI stub.
494 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
495 std::string_view shorty = dex_file.GetMethodShortyView(dex_file.GetMethodId(method_idx));
496 boot_jni_stub = class_linker->FindBootJniStub(access_flags, shorty);
497 }
498 if (boot_jni_stub == nullptr) {
499 compiled_method =
500 driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file, dex_cache);
501 CHECK(compiled_method != nullptr);
502 }
503 }
504 } else if ((access_flags & kAccAbstract) != 0) {
505 // Abstract methods don't have code.
506 } else if (annotations::MethodIsNeverCompile(dex_file,
507 dex_file.GetClassDef(class_def_idx),
508 method_idx)) {
509 // Method is annotated with @NeverCompile and should not be compiled.
510 } else {
511 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
512 // Don't compile class initializers unless kEverything.
513 bool compile = (compiler_options.GetCompilerFilter() == CompilerFilter::kEverything) ||
514 ((access_flags & kAccConstructor) == 0) || ((access_flags & kAccStatic) == 0);
515 // Check if we should compile based on the profile.
516 compile = compile && ShouldCompileBasedOnProfile(compiler_options, profile_index, method_ref);
517
518 if (compile) {
519 // NOTE: if compiler declines to compile this method, it will return null.
520 compiled_method = driver->GetCompiler()->Compile(code_item,
521 access_flags,
522 class_def_idx,
523 method_idx,
524 class_loader,
525 dex_file,
526 dex_cache);
527 ProfileMethodsCheck check_type = compiler_options.CheckProfiledMethodsCompiled();
528 if (UNLIKELY(check_type != ProfileMethodsCheck::kNone)) {
529 DCHECK(ShouldCompileBasedOnProfile(compiler_options, profile_index, method_ref));
530 bool violation = (compiled_method == nullptr);
531 if (violation) {
532 std::ostringstream oss;
533 oss << "Failed to compile "
534 << method_ref.dex_file->PrettyMethod(method_ref.index)
535 << "[" << method_ref.dex_file->GetLocation() << "]"
536 << " as expected by profile";
537 switch (check_type) {
538 case ProfileMethodsCheck::kNone:
539 break;
540 case ProfileMethodsCheck::kLog:
541 LOG(ERROR) << oss.str();
542 break;
543 case ProfileMethodsCheck::kAbort:
544 LOG(FATAL_WITHOUT_ABORT) << oss.str();
545 _exit(1);
546 }
547 }
548 }
549 }
550 }
551 return compiled_method;
552 };
553 CompileMethodHarness(self,
554 driver,
555 code_item,
556 access_flags,
557 class_def_idx,
558 method_idx,
559 class_loader,
560 dex_file,
561 dex_cache,
562 quick_fn);
563 }
564
Resolve(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)565 void CompilerDriver::Resolve(jobject class_loader,
566 const std::vector<const DexFile*>& dex_files,
567 TimingLogger* timings) {
568 TimingLogger::ScopedTiming t("Resolve Types", timings);
569 // Resolution allocates classes and needs to run single-threaded to be deterministic.
570 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
571 ThreadPool* resolve_thread_pool = force_determinism
572 ? single_thread_pool_.get()
573 : parallel_thread_pool_.get();
574 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
575
576 for (size_t i = 0; i != dex_files.size(); ++i) {
577 const DexFile* dex_file = dex_files[i];
578 CHECK(dex_file != nullptr);
579 ResolveDexFile(class_loader,
580 *dex_file,
581 resolve_thread_pool,
582 resolve_thread_count,
583 timings);
584 }
585 }
586
ResolveConstStrings(const std::vector<const DexFile * > & dex_files,bool only_startup_strings,TimingLogger * timings)587 void CompilerDriver::ResolveConstStrings(const std::vector<const DexFile*>& dex_files,
588 bool only_startup_strings,
589 TimingLogger* timings) {
590 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
591 const ProfileCompilationInfo* profile_compilation_info =
592 GetCompilerOptions().GetProfileCompilationInfo();
593 if (only_startup_strings && profile_compilation_info == nullptr) {
594 // If there is no profile, don't resolve any strings. Resolving all of the strings in the image
595 // will cause a bloated app image and slow down startup.
596 return;
597 }
598 ScopedObjectAccess soa(Thread::Current());
599 StackHandleScope<1> hs(soa.Self());
600 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
601 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
602 size_t num_instructions = 0u;
603
604 for (const DexFile* dex_file : dex_files) {
605 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
606
607 ProfileCompilationInfo::ProfileIndexType profile_index =
608 ProfileCompilationInfo::MaxProfileIndex();
609 if (profile_compilation_info != nullptr) {
610 profile_index = profile_compilation_info->FindDexFile(*dex_file);
611 if (profile_index == ProfileCompilationInfo::MaxProfileIndex()) {
612 // We have a `ProfileCompilationInfo` but no data for this dex file.
613 // The code below would not find any method to process.
614 continue;
615 }
616 }
617
618 // TODO: Implement a profile-based filter for the boot image. See b/76145463.
619 for (ClassAccessor accessor : dex_file->GetClasses()) {
620 // Skip methods that failed to verify since they may contain invalid Dex code.
621 if (GetClassStatus(ClassReference(dex_file, accessor.GetClassDefIndex())) <
622 ClassStatus::kRetryVerificationAtRuntime) {
623 continue;
624 }
625
626 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
627 if (profile_compilation_info != nullptr) {
628 DCHECK_NE(profile_index, ProfileCompilationInfo::MaxProfileIndex());
629 // There can be at most one class initializer in a class, so we shall not
630 // call `ProfileCompilationInfo::ContainsClass()` more than once per class.
631 constexpr uint32_t kMask = kAccConstructor | kAccStatic;
632 const bool is_startup_clinit =
633 (method.GetAccessFlags() & kMask) == kMask &&
634 profile_compilation_info->ContainsClass(profile_index, accessor.GetClassIdx());
635
636 if (!is_startup_clinit) {
637 uint32_t method_index = method.GetIndex();
638 bool process_method = only_startup_strings
639 ? profile_compilation_info->IsStartupMethod(profile_index, method_index)
640 : profile_compilation_info->IsMethodInProfile(profile_index, method_index);
641 if (!process_method) {
642 continue;
643 }
644 }
645 }
646
647 // Resolve const-strings in the code. Done to have deterministic allocation behavior. Right
648 // now this is single-threaded for simplicity.
649 // TODO: Collect the relevant string indices in parallel, then allocate them sequentially
650 // in a stable order.
651 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
652 switch (inst->Opcode()) {
653 case Instruction::CONST_STRING:
654 case Instruction::CONST_STRING_JUMBO: {
655 dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING)
656 ? inst->VRegB_21c()
657 : inst->VRegB_31c());
658 ObjPtr<mirror::String> string = class_linker->ResolveString(string_index, dex_cache);
659 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
660 ++num_instructions;
661 break;
662 }
663
664 default:
665 break;
666 }
667 }
668 }
669 }
670 }
671 VLOG(compiler) << "Resolved " << num_instructions << " const string instructions";
672 }
673
674 // Initialize type check bit strings for check-cast and instance-of in the code. Done to have
675 // deterministic allocation behavior. Right now this is single-threaded for simplicity.
676 // TODO: Collect the relevant type indices in parallel, then process them sequentially in a
677 // stable order.
678
InitializeTypeCheckBitstrings(CompilerDriver * driver,ClassLinker * class_linker,Handle<mirror::DexCache> dex_cache,const DexFile & dex_file,const ClassAccessor::Method & method)679 static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
680 ClassLinker* class_linker,
681 Handle<mirror::DexCache> dex_cache,
682 const DexFile& dex_file,
683 const ClassAccessor::Method& method)
684 REQUIRES_SHARED(Locks::mutator_lock_) {
685 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
686 switch (inst->Opcode()) {
687 case Instruction::CHECK_CAST:
688 case Instruction::INSTANCE_OF: {
689 dex::TypeIndex type_index(
690 (inst->Opcode() == Instruction::CHECK_CAST) ? inst->VRegB_21c() : inst->VRegC_22c());
691 const char* descriptor = dex_file.GetTypeDescriptor(type_index);
692 // We currently do not use the bitstring type check for array or final (including
693 // primitive) classes. We may reconsider this in future if it's deemed to be beneficial.
694 // And we cannot use it for classes outside the boot image as we do not know the runtime
695 // value of their bitstring when compiling (it may not even get assigned at runtime).
696 if (descriptor[0] == 'L' && driver->GetCompilerOptions().IsImageClass(descriptor)) {
697 ObjPtr<mirror::Class> klass =
698 class_linker->LookupResolvedType(type_index,
699 dex_cache.Get(),
700 /* class_loader= */ nullptr);
701 CHECK(klass != nullptr) << descriptor << " should have been previously resolved.";
702 // Now assign the bitstring if the class is not final. Keep this in sync with sharpening.
703 if (!klass->IsFinal()) {
704 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
705 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureAssigned(klass);
706 }
707 }
708 break;
709 }
710
711 default:
712 break;
713 }
714 }
715 }
716
InitializeTypeCheckBitstrings(CompilerDriver * driver,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)717 static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
718 const std::vector<const DexFile*>& dex_files,
719 TimingLogger* timings) {
720 ScopedObjectAccess soa(Thread::Current());
721 StackHandleScope<1> hs(soa.Self());
722 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
723 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
724
725 for (const DexFile* dex_file : dex_files) {
726 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
727 TimingLogger::ScopedTiming t("Initialize type check bitstrings", timings);
728
729 for (ClassAccessor accessor : dex_file->GetClasses()) {
730 // Direct and virtual methods.
731 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
732 InitializeTypeCheckBitstrings(driver, class_linker, dex_cache, *dex_file, method);
733 }
734 }
735 }
736 }
737
CheckThreadPools()738 inline void CompilerDriver::CheckThreadPools() {
739 DCHECK(parallel_thread_pool_ != nullptr);
740 DCHECK(single_thread_pool_ != nullptr);
741 }
742
EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,const std::vector<const DexFile * > & dex_files)743 static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
744 const std::vector<const DexFile*>& dex_files) {
745 ScopedObjectAccess soa(Thread::Current());
746 StackHandleScope<2> hs(soa.Self());
747 Handle<mirror::ClassLoader> class_loader(
748 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
749 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
750 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
751
752 for (const DexFile* dex_file : dex_files) {
753 for (ClassAccessor accessor : dex_file->GetClasses()) {
754 cls.Assign(
755 class_linker->FindClass(soa.Self(), *dex_file, accessor.GetClassIdx(), class_loader));
756 if (cls == nullptr) {
757 soa.Self()->ClearException();
758 } else if (&cls->GetDexFile() == dex_file) {
759 DCHECK(cls->IsErroneous() ||
760 cls->IsVerified() ||
761 cls->ShouldVerifyAtRuntime() ||
762 cls->IsVerifiedNeedsAccessChecks())
763 << cls->PrettyClass()
764 << " " << cls->GetStatus();
765 }
766 }
767 }
768 }
769
PrepareDexFilesForOatFile(TimingLogger * timings)770 void CompilerDriver::PrepareDexFilesForOatFile([[maybe_unused]] TimingLogger* timings) {
771 compiled_classes_.AddDexFiles(GetCompilerOptions().GetDexFilesForOatFile());
772 }
773
774 class CreateConflictTablesVisitor : public ClassVisitor {
775 public:
CreateConflictTablesVisitor(VariableSizedHandleScope & hs)776 explicit CreateConflictTablesVisitor(VariableSizedHandleScope& hs)
777 : hs_(hs) {}
778
operator ()(ObjPtr<mirror::Class> klass)779 bool operator()(ObjPtr<mirror::Class> klass) override
780 REQUIRES_SHARED(Locks::mutator_lock_) {
781 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
782 return true;
783 }
784 // Collect handles since there may be thread suspension in future EnsureInitialized.
785 to_visit_.push_back(hs_.NewHandle(klass));
786 return true;
787 }
788
FillAllIMTAndConflictTables()789 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
790 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
791 for (Handle<mirror::Class> c : to_visit_) {
792 // Create the conflict tables.
793 FillIMTAndConflictTables(c.Get());
794 }
795 }
796
797 private:
FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)798 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
799 REQUIRES_SHARED(Locks::mutator_lock_) {
800 if (!klass->ShouldHaveImt()) {
801 return;
802 }
803 if (visited_classes_.find(klass.Ptr()) != visited_classes_.end()) {
804 return;
805 }
806 if (klass->HasSuperClass()) {
807 FillIMTAndConflictTables(klass->GetSuperClass());
808 }
809 if (!klass->IsTemp()) {
810 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
811 }
812 visited_classes_.insert(klass.Ptr());
813 }
814
815 VariableSizedHandleScope& hs_;
816 std::vector<Handle<mirror::Class>> to_visit_;
817 HashSet<mirror::Class*> visited_classes_;
818 };
819
PreCompile(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings,HashSet<std::string> * image_classes)820 void CompilerDriver::PreCompile(jobject class_loader,
821 const std::vector<const DexFile*>& dex_files,
822 TimingLogger* timings,
823 /*inout*/ HashSet<std::string>* image_classes) {
824 CheckThreadPools();
825
826 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
827
828 // Precompile:
829 // 1) Load image classes.
830 // 2) Resolve all classes.
831 // 3) For deterministic boot image, resolve strings for const-string instructions.
832 // 4) Attempt to verify all classes.
833 // 5) Attempt to initialize image classes, and trivially initialized classes.
834 // 6) Update the set of image classes.
835 // 7) For deterministic boot image, initialize bitstrings for type checking.
836
837 LoadImageClasses(timings, class_loader, image_classes);
838 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
839
840 if (compiler_options_->AssumeClassesAreVerified()) {
841 VLOG(compiler) << "Verify none mode specified, skipping verification.";
842 SetVerified(class_loader, dex_files, timings);
843 } else {
844 DCHECK(compiler_options_->IsVerificationEnabled());
845
846 if (compiler_options_->IsAnyCompilationEnabled()) {
847 // Avoid adding the dex files in the case where we aren't going to add compiled methods.
848 // This reduces RAM usage for this case.
849 for (const DexFile* dex_file : dex_files) {
850 // Can be already inserted. This happens for gtests.
851 if (!compiled_methods_.HaveDexFile(dex_file)) {
852 compiled_methods_.AddDexFile(dex_file);
853 }
854 }
855 }
856
857 // Resolve eagerly for compilations always, and for verifications only if we are running with
858 // multiple threads.
859 const bool should_resolve_eagerly =
860 compiler_options_->IsAnyCompilationEnabled() ||
861 (!GetCompilerOptions().IsForceDeterminism() && parallel_thread_count_ > 1);
862 if (should_resolve_eagerly) {
863 Resolve(class_loader, dex_files, timings);
864 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
865 }
866
867 Verify(class_loader, dex_files, timings);
868 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
869
870 if (GetCompilerOptions().IsForceDeterminism() &&
871 (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension())) {
872 // Resolve strings from const-string. Do this now to have a deterministic image.
873 ResolveConstStrings(dex_files, /*only_startup_strings=*/ false, timings);
874 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
875 } else if (GetCompilerOptions().ResolveStartupConstStrings()) {
876 ResolveConstStrings(dex_files, /*only_startup_strings=*/ true, timings);
877 }
878
879 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
880 // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
881 // instances of this thread's stack.
882 LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
883 << "in such situations. Please check the log.";
884 _exit(1);
885 } else if (number_of_soft_verifier_failures_ > 0 &&
886 GetCompilerOptions().AbortOnSoftVerifierFailure()) {
887 LOG(FATAL_WITHOUT_ABORT) << "Had " << number_of_soft_verifier_failures_ << " soft failure(s) "
888 << "verifying all classes, and was asked to abort in such situations. "
889 << "Please check the log.";
890 _exit(1);
891 }
892
893 if (GetCompilerOptions().IsAppImage() && had_hard_verifier_failure_) {
894 // Prune erroneous classes and classes that depend on them.
895 UpdateImageClasses(timings, image_classes);
896 VLOG(compiler) << "verify/UpdateImageClasses: " << GetMemoryUsageString(false);
897 }
898 }
899
900 if (GetCompilerOptions().IsGeneratingImage()) {
901 // We can only initialize classes when their verification bit is set.
902 if (compiler_options_->AssumeClassesAreVerified() ||
903 compiler_options_->IsVerificationEnabled()) {
904 if (kIsDebugBuild) {
905 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
906 }
907 InitializeClasses(class_loader, dex_files, timings);
908 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
909 }
910 {
911 // Create conflict tables, as the runtime expects boot image classes to
912 // always have their conflict tables filled.
913 ScopedObjectAccess soa(Thread::Current());
914 VariableSizedHandleScope hs(soa.Self());
915 CreateConflictTablesVisitor visitor(hs);
916 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
917 visitor.FillAllIMTAndConflictTables();
918 }
919
920 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
921 UpdateImageClasses(timings, image_classes);
922 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
923 }
924
925 if (kBitstringSubtypeCheckEnabled &&
926 GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
927 // Initialize type check bit string used by check-cast and instanceof.
928 // Do this now to have a deterministic image.
929 // Note: This is done after UpdateImageClasses() at it relies on the image
930 // classes to be final.
931 InitializeTypeCheckBitstrings(this, dex_files, timings);
932 }
933 }
934 }
935
936 class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
937 public:
ResolveCatchBlockExceptionsClassVisitor(Thread * self)938 explicit ResolveCatchBlockExceptionsClassVisitor(Thread* self)
939 : hs_(self),
940 dex_file_records_(),
941 unprocessed_classes_(),
942 exception_types_to_resolve_(),
943 boot_images_start_(Runtime::Current()->GetHeap()->GetBootImagesStartAddress()),
944 boot_images_size_(Runtime::Current()->GetHeap()->GetBootImagesSize()) {}
945
operator ()(ObjPtr<mirror::Class> c)946 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
947 // Filter out classes from boot images we're compiling against.
948 // These have been processed when we compiled those boot images.
949 if (reinterpret_cast32<uint32_t>(c.Ptr()) - boot_images_start_ < boot_images_size_) {
950 DCHECK(Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(c));
951 return true;
952 }
953 // Filter out classes without methods.
954 // These include primitive types and array types which have no dex file.
955 if (c->GetMethodsPtr() == nullptr) {
956 return true;
957 }
958 auto it = dex_file_records_.find(&c->GetDexFile());
959 if (it != dex_file_records_.end()) {
960 DexFileRecord& record = it->second;
961 DCHECK_EQ(c->GetDexCache(), record.GetDexCache().Get());
962 DCHECK_EQ(c->GetClassLoader(), record.GetClassLoader().Get());
963 if (record.IsProcessedClass(c)) {
964 return true;
965 }
966 }
967 unprocessed_classes_.push_back(c);
968 return true;
969 }
970
FindAndResolveExceptionTypes(Thread * self,ClassLinker * class_linker)971 void FindAndResolveExceptionTypes(Thread* self, ClassLinker* class_linker)
972 REQUIRES_SHARED(Locks::mutator_lock_) {
973 // If we try to resolve any exception types, we need to repeat the process.
974 // Even if we failed to resolve an exception type, we could have resolved its supertype
975 // or some implemented interfaces as a side-effect (the exception type could implement
976 // another unresolved interface) and we need to visit methods of such new resolved
977 // classes as they shall be recorded as image classes.
978 while (FindExceptionTypesToResolve(class_linker)) {
979 ResolveExceptionTypes(self, class_linker);
980 }
981 }
982
983 private:
984 class DexFileRecord {
985 public:
DexFileRecord(Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)986 DexFileRecord(Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader)
987 REQUIRES_SHARED(Locks::mutator_lock_)
988 : dex_cache_(dex_cache),
989 class_loader_(class_loader),
990 processed_classes_(/*start_bits=*/ dex_cache->GetDexFile()->NumClassDefs(),
991 /*expandable=*/ false,
992 Allocator::GetCallocAllocator()),
993 processed_exception_types_(/*start_bits=*/ dex_cache->GetDexFile()->NumTypeIds(),
994 /*expandable=*/ false,
995 Allocator::GetCallocAllocator()) {}
996
GetDexCache()997 Handle<mirror::DexCache> GetDexCache() {
998 return dex_cache_;
999 }
1000
GetClassLoader()1001 Handle<mirror::ClassLoader> GetClassLoader() {
1002 return class_loader_;
1003 }
1004
IsProcessedClass(ObjPtr<mirror::Class> c)1005 bool IsProcessedClass(ObjPtr<mirror::Class> c) REQUIRES_SHARED(Locks::mutator_lock_) {
1006 DCHECK_LT(c->GetDexClassDefIndex(), dex_cache_->GetDexFile()->NumClassDefs());
1007 return processed_classes_.IsBitSet(c->GetDexClassDefIndex());
1008 }
1009
MarkProcessedClass(ObjPtr<mirror::Class> c)1010 void MarkProcessedClass(ObjPtr<mirror::Class> c) REQUIRES_SHARED(Locks::mutator_lock_) {
1011 DCHECK_LT(c->GetDexClassDefIndex(), dex_cache_->GetDexFile()->NumClassDefs());
1012 processed_classes_.SetBit(c->GetDexClassDefIndex());
1013 }
1014
IsProcessedExceptionType(dex::TypeIndex type_idx)1015 bool IsProcessedExceptionType(dex::TypeIndex type_idx) REQUIRES_SHARED(Locks::mutator_lock_) {
1016 DCHECK_LT(type_idx.index_, dex_cache_->GetDexFile()->NumTypeIds());
1017 return processed_exception_types_.IsBitSet(type_idx.index_);
1018 }
1019
MarkProcessedExceptionType(dex::TypeIndex type_idx)1020 void MarkProcessedExceptionType(dex::TypeIndex type_idx) REQUIRES_SHARED(Locks::mutator_lock_) {
1021 DCHECK_LT(type_idx.index_, dex_cache_->GetDexFile()->NumTypeIds());
1022 processed_exception_types_.SetBit(type_idx.index_);
1023 }
1024
1025 private:
1026 Handle<mirror::DexCache> dex_cache_;
1027 Handle<mirror::ClassLoader> class_loader_;
1028 BitVector processed_classes_;
1029 BitVector processed_exception_types_;
1030 };
1031
1032 struct ExceptionTypeReference {
1033 dex::TypeIndex exception_type_idx;
1034 Handle<mirror::DexCache> dex_cache;
1035 Handle<mirror::ClassLoader> class_loader;
1036 };
1037
1038 bool FindExceptionTypesToResolve(ClassLinker* class_linker)
1039 REQUIRES_SHARED(Locks::mutator_lock_);
1040
ResolveExceptionTypes(Thread * self,ClassLinker * class_linker)1041 void ResolveExceptionTypes(Thread* self, ClassLinker* class_linker)
1042 REQUIRES_SHARED(Locks::mutator_lock_) {
1043 DCHECK(!exception_types_to_resolve_.empty());
1044 for (auto [exception_type_idx, dex_cache, class_loader] : exception_types_to_resolve_) {
1045 ObjPtr<mirror::Class> exception_class =
1046 class_linker->ResolveType(exception_type_idx, dex_cache, class_loader);
1047 if (exception_class == nullptr) {
1048 VLOG(compiler) << "Failed to resolve exception class "
1049 << dex_cache->GetDexFile()->GetTypeDescriptorView(exception_type_idx);
1050 self->ClearException();
1051 } else {
1052 DCHECK(GetClassRoot<mirror::Throwable>(class_linker)->IsAssignableFrom(exception_class));
1053 }
1054 }
1055 exception_types_to_resolve_.clear();
1056 }
1057
1058 VariableSizedHandleScope hs_;
1059 SafeMap<const DexFile*, DexFileRecord> dex_file_records_;
1060 std::vector<ObjPtr<mirror::Class>> unprocessed_classes_;
1061 std::vector<ExceptionTypeReference> exception_types_to_resolve_;
1062 const uint32_t boot_images_start_;
1063 const uint32_t boot_images_size_;
1064 };
1065
FindExceptionTypesToResolve(ClassLinker * class_linker)1066 bool ResolveCatchBlockExceptionsClassVisitor::FindExceptionTypesToResolve(
1067 ClassLinker* class_linker) {
1068 // Thread suspension is not allowed while the `ResolveCatchBlockExceptionsClassVisitor`
1069 // is using a `std::vector<ObjPtr<mirror::Class>>`.
1070 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1071 DCHECK(unprocessed_classes_.empty());
1072 class_linker->VisitClasses(this);
1073 if (unprocessed_classes_.empty()) {
1074 return false;
1075 }
1076
1077 DCHECK(exception_types_to_resolve_.empty());
1078 const PointerSize pointer_size = class_linker->GetImagePointerSize();
1079 for (ObjPtr<mirror::Class> klass : unprocessed_classes_) {
1080 const DexFile* dex_file = &klass->GetDexFile();
1081 DexFileRecord& record = dex_file_records_.GetOrCreate(
1082 dex_file,
1083 // NO_THREAD_SAFETY_ANALYSIS: Called from unannotated `SafeMap<>::GetOrCreate()`.
1084 [&]() NO_THREAD_SAFETY_ANALYSIS {
1085 return DexFileRecord(hs_.NewHandle(klass->GetDexCache()),
1086 hs_.NewHandle(klass->GetClassLoader()));
1087 });
1088 DCHECK_EQ(klass->GetDexCache(), record.GetDexCache().Get());
1089 DCHECK_EQ(klass->GetClassLoader(), record.GetClassLoader().Get());
1090 DCHECK(!record.IsProcessedClass(klass));
1091 record.MarkProcessedClass(klass);
1092 for (ArtMethod& method : klass->GetDeclaredMethods(pointer_size)) {
1093 if (method.GetCodeItem() == nullptr) {
1094 continue; // native or abstract method
1095 }
1096 CodeItemDataAccessor accessor(method.DexInstructionData());
1097 if (accessor.TriesSize() == 0) {
1098 continue; // nothing to process
1099 }
1100 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData();
1101 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&handlers_ptr);
1102 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1103 CatchHandlerIterator iterator(handlers_ptr);
1104 for (; iterator.HasNext(); iterator.Next()) {
1105 dex::TypeIndex exception_type_idx = iterator.GetHandlerTypeIndex();
1106 if (exception_type_idx.IsValid() &&
1107 !record.IsProcessedExceptionType(exception_type_idx)) {
1108 record.MarkProcessedExceptionType(exception_type_idx);
1109 // Add to set of types to resolve if not resolved yet.
1110 ObjPtr<mirror::Class> type = class_linker->LookupResolvedType(
1111 exception_type_idx, record.GetDexCache().Get(), record.GetClassLoader().Get());
1112 if (type == nullptr) {
1113 exception_types_to_resolve_.push_back(
1114 {exception_type_idx, record.GetDexCache(), record.GetClassLoader()});
1115 }
1116 }
1117 }
1118 handlers_ptr = iterator.EndDataPointer();
1119 }
1120 }
1121 }
1122 unprocessed_classes_.clear();
1123 return !exception_types_to_resolve_.empty();
1124 }
1125
CanIncludeInCurrentImage(ObjPtr<mirror::Class> klass)1126 static inline bool CanIncludeInCurrentImage(ObjPtr<mirror::Class> klass)
1127 REQUIRES_SHARED(Locks::mutator_lock_) {
1128 DCHECK(klass != nullptr);
1129 gc::Heap* heap = Runtime::Current()->GetHeap();
1130 if (heap->GetBootImageSpaces().empty()) {
1131 return true; // We can include any class when compiling the primary boot image.
1132 }
1133 if (heap->ObjectIsInBootImageSpace(klass)) {
1134 return false; // Already included in the boot image we're compiling against.
1135 }
1136 return AotClassLinker::CanReferenceInBootImageExtensionOrAppImage(klass, heap);
1137 }
1138
1139 class RecordImageClassesVisitor : public ClassVisitor {
1140 public:
RecordImageClassesVisitor(HashSet<std::string> * image_classes)1141 explicit RecordImageClassesVisitor(HashSet<std::string>* image_classes)
1142 : image_classes_(image_classes) {}
1143
operator ()(ObjPtr<mirror::Class> klass)1144 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1145 bool resolved = klass->IsResolved();
1146 DCHECK(resolved || klass->IsErroneousUnresolved());
1147 bool can_include_in_image = LIKELY(resolved) && CanIncludeInCurrentImage(klass);
1148 std::string temp;
1149 std::string_view descriptor(klass->GetDescriptor(&temp));
1150 if (can_include_in_image) {
1151 image_classes_->insert(std::string(descriptor)); // Does nothing if already present.
1152 } else {
1153 auto it = image_classes_->find(descriptor);
1154 if (it != image_classes_->end()) {
1155 VLOG(compiler) << "Removing " << (resolved ? "unsuitable" : "unresolved")
1156 << " class from image classes: " << descriptor;
1157 image_classes_->erase(it);
1158 }
1159 }
1160 return true;
1161 }
1162
1163 private:
1164 HashSet<std::string>* const image_classes_;
1165 };
1166
1167 // Verify that classes which contain intrinsics methods are in the list of image classes.
VerifyClassesContainingIntrinsicsAreImageClasses(HashSet<std::string> * image_classes)1168 static void VerifyClassesContainingIntrinsicsAreImageClasses(HashSet<std::string>* image_classes) {
1169 #define CHECK_INTRINSIC_OWNER_CLASS(_, __, ___, ____, _____, ClassName, ______, _______) \
1170 CHECK(image_classes->find(std::string_view(ClassName)) != image_classes->end());
1171
1172 ART_INTRINSICS_LIST(CHECK_INTRINSIC_OWNER_CLASS)
1173 #undef CHECK_INTRINSIC_OWNER_CLASS
1174 }
1175
1176 // We need to put classes required by app class loaders to the boot image,
1177 // otherwise we would not be able to store app class loaders in app images.
AddClassLoaderClasses(HashSet<std::string> * image_classes)1178 static void AddClassLoaderClasses(/* out */ HashSet<std::string>* image_classes) {
1179 ScopedObjectAccess soa(Thread::Current());
1180 // Well known classes have been loaded and shall be added to image classes
1181 // by the `RecordImageClassesVisitor`. However, there are fields with array
1182 // types which we need to add to the image classes explicitly.
1183 ArtField* class_loader_array_fields[] = {
1184 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders,
1185 // BaseDexClassLoader.sharedLibraryLoadersAfter has the same array type as above.
1186 WellKnownClasses::dalvik_system_DexPathList_dexElements,
1187 };
1188 for (ArtField* field : class_loader_array_fields) {
1189 const char* field_type_descriptor = field->GetTypeDescriptor();
1190 DCHECK_EQ(field_type_descriptor[0], '[');
1191 image_classes->insert(field_type_descriptor);
1192 }
1193 }
1194
VerifyClassLoaderClassesAreImageClasses(HashSet<std::string> * image_classes)1195 static void VerifyClassLoaderClassesAreImageClasses(/* out */ HashSet<std::string>* image_classes) {
1196 ScopedObjectAccess soa(Thread::Current());
1197 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
1198 ObjPtr<mirror::Class> class_loader_classes[] = {
1199 WellKnownClasses::dalvik_system_BaseDexClassLoader.Get(),
1200 WellKnownClasses::dalvik_system_DelegateLastClassLoader.Get(),
1201 WellKnownClasses::dalvik_system_DexClassLoader.Get(),
1202 WellKnownClasses::dalvik_system_DexFile.Get(),
1203 WellKnownClasses::dalvik_system_DexPathList.Get(),
1204 WellKnownClasses::dalvik_system_DexPathList__Element.Get(),
1205 WellKnownClasses::dalvik_system_InMemoryDexClassLoader.Get(),
1206 WellKnownClasses::dalvik_system_PathClassLoader.Get(),
1207 WellKnownClasses::java_lang_BootClassLoader.Get(),
1208 WellKnownClasses::java_lang_ClassLoader.Get(),
1209 };
1210 for (ObjPtr<mirror::Class> klass : class_loader_classes) {
1211 std::string temp;
1212 std::string_view descriptor = klass->GetDescriptor(&temp);
1213 CHECK(image_classes->find(descriptor) != image_classes->end());
1214 }
1215 ArtField* class_loader_fields[] = {
1216 WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList,
1217 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders,
1218 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter,
1219 WellKnownClasses::dalvik_system_DexFile_cookie,
1220 WellKnownClasses::dalvik_system_DexFile_fileName,
1221 WellKnownClasses::dalvik_system_DexPathList_dexElements,
1222 WellKnownClasses::dalvik_system_DexPathList__Element_dexFile,
1223 WellKnownClasses::java_lang_ClassLoader_parent,
1224 };
1225 for (ArtField* field : class_loader_fields) {
1226 std::string_view field_type_descriptor = field->GetTypeDescriptor();
1227 CHECK(image_classes->find(field_type_descriptor) != image_classes->end());
1228 }
1229 }
1230
1231 // Make a list of descriptors for classes to include in the image
LoadImageClasses(TimingLogger * timings,jobject class_loader,HashSet<std::string> * image_classes)1232 void CompilerDriver::LoadImageClasses(TimingLogger* timings,
1233 jobject class_loader,
1234 /*inout*/ HashSet<std::string>* image_classes) {
1235 CHECK(timings != nullptr);
1236 if (!GetCompilerOptions().IsGeneratingImage()) {
1237 return;
1238 }
1239
1240 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
1241
1242 if (GetCompilerOptions().IsBootImage()) {
1243 // Image classes of intrinsics are loaded and shall be added
1244 // to image classes by the `RecordImageClassesVisitor`.
1245 // Add classes needed for storing class loaders in app images.
1246 AddClassLoaderClasses(image_classes);
1247 }
1248
1249 // Make a first pass to load all classes explicitly listed in the profile.
1250 Thread* self = Thread::Current();
1251 ScopedObjectAccess soa(self);
1252 StackHandleScope<2u> hs(self);
1253 Handle<mirror::ClassLoader> loader = hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1254 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1255 CHECK(image_classes != nullptr);
1256 for (auto it = image_classes->begin(), end = image_classes->end(); it != end;) {
1257 const std::string& descriptor(*it);
1258 ObjPtr<mirror::Class> klass =
1259 class_linker->FindClass(self, descriptor.c_str(), descriptor.length(), loader);
1260 if (klass == nullptr) {
1261 VLOG(compiler) << "Failed to find class " << descriptor;
1262 it = image_classes->erase(it); // May cause some descriptors to be revisited.
1263 self->ClearException();
1264 } else {
1265 ++it;
1266 }
1267 }
1268
1269 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1270 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1271 // Do this here so that exception classes appear to have been specified image classes.
1272 ResolveCatchBlockExceptionsClassVisitor resolve_exception_classes_visitor(self);
1273 resolve_exception_classes_visitor.FindAndResolveExceptionTypes(self, class_linker);
1274
1275 // We walk the roots looking for classes so that we'll pick up the
1276 // above classes plus any classes they depend on such super
1277 // classes, interfaces, and the required ClassLinker roots.
1278 RecordImageClassesVisitor visitor(image_classes);
1279 class_linker->VisitClasses(&visitor);
1280
1281 if (kIsDebugBuild && GetCompilerOptions().IsBootImage()) {
1282 VerifyClassesContainingIntrinsicsAreImageClasses(image_classes);
1283 VerifyClassLoaderClassesAreImageClasses(image_classes);
1284 }
1285
1286 if (GetCompilerOptions().IsBootImage()) {
1287 CHECK(!image_classes->empty());
1288 }
1289 }
1290
MaybeAddToImageClasses(Thread * self,ObjPtr<mirror::Class> klass,HashSet<std::string> * image_classes)1291 static void MaybeAddToImageClasses(Thread* self,
1292 ObjPtr<mirror::Class> klass,
1293 HashSet<std::string>* image_classes)
1294 REQUIRES_SHARED(Locks::mutator_lock_) {
1295 DCHECK_EQ(self, Thread::Current());
1296 DCHECK(klass->IsResolved());
1297 Runtime* runtime = Runtime::Current();
1298 gc::Heap* heap = runtime->GetHeap();
1299 if (heap->ObjectIsInBootImageSpace(klass)) {
1300 // We're compiling a boot image extension and the class is already
1301 // in the boot image we're compiling against.
1302 return;
1303 }
1304 const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
1305 std::string temp;
1306 while (!klass->IsObjectClass()) {
1307 const char* descriptor = klass->GetDescriptor(&temp);
1308 if (image_classes->find(std::string_view(descriptor)) != image_classes->end()) {
1309 break; // Previously inserted.
1310 }
1311 image_classes->insert(descriptor);
1312 VLOG(compiler) << "Adding " << descriptor << " to image classes";
1313 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1314 ObjPtr<mirror::Class> interface = klass->GetDirectInterface(i);
1315 DCHECK(interface != nullptr);
1316 MaybeAddToImageClasses(self, interface, image_classes);
1317 }
1318 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1319 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
1320 }
1321 if (klass->IsArrayClass()) {
1322 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
1323 }
1324 klass = klass->GetSuperClass();
1325 }
1326 }
1327
1328 // Keeps all the data for the update together. Also doubles as the reference visitor.
1329 // Note: we can use object pointers because we suspend all threads.
1330 class ClinitImageUpdate {
1331 public:
ClinitImageUpdate(HashSet<std::string> * image_class_descriptors,Thread * self)1332 ClinitImageUpdate(HashSet<std::string>* image_class_descriptors,
1333 Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
1334 : hs_(self),
1335 image_class_descriptors_(image_class_descriptors),
1336 self_(self) {
1337 CHECK(image_class_descriptors != nullptr);
1338
1339 // Make sure nobody interferes with us.
1340 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1341 }
1342
~ClinitImageUpdate()1343 ~ClinitImageUpdate() {
1344 // Allow others to suspend again.
1345 self_->EndAssertNoThreadSuspension(old_cause_);
1346 }
1347
1348 // Visitor for VisitReferences.
operator ()(ObjPtr<mirror::Object> object,MemberOffset field_offset,bool is_static) const1349 void operator()(ObjPtr<mirror::Object> object,
1350 MemberOffset field_offset,
1351 [[maybe_unused]] bool is_static) const REQUIRES_SHARED(Locks::mutator_lock_) {
1352 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1353 if (ref != nullptr) {
1354 VisitClinitClassesObject(ref);
1355 }
1356 }
1357
1358 // java.lang.ref.Reference visitor for VisitReferences.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1359 void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
1360 [[maybe_unused]] ObjPtr<mirror::Reference> ref) const {}
1361
1362 // Ignore class native roots.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1363 void VisitRootIfNonNull(
1364 [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1365 void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
1366
Walk()1367 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
1368 // Find all the already-marked classes.
1369 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
1370 FindImageClassesVisitor visitor(this);
1371 Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
1372
1373 // Use the initial classes as roots for a search.
1374 for (Handle<mirror::Class> klass_root : image_classes_) {
1375 VisitClinitClassesObject(klass_root.Get());
1376 }
1377 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1378 for (Handle<mirror::Class> h_klass : to_insert_) {
1379 MaybeAddToImageClasses(self_, h_klass.Get(), image_class_descriptors_);
1380 }
1381 }
1382
1383 private:
1384 class FindImageClassesVisitor : public ClassVisitor {
1385 public:
FindImageClassesVisitor(ClinitImageUpdate * data)1386 explicit FindImageClassesVisitor(ClinitImageUpdate* data)
1387 : data_(data) {}
1388
operator ()(ObjPtr<mirror::Class> klass)1389 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1390 bool resolved = klass->IsResolved();
1391 DCHECK(resolved || klass->IsErroneousUnresolved());
1392 bool can_include_in_image =
1393 LIKELY(resolved) && LIKELY(!klass->IsErroneous()) && CanIncludeInCurrentImage(klass);
1394 std::string temp;
1395 std::string_view descriptor(klass->GetDescriptor(&temp));
1396 auto it = data_->image_class_descriptors_->find(descriptor);
1397 if (it != data_->image_class_descriptors_->end()) {
1398 if (can_include_in_image) {
1399 data_->image_classes_.push_back(data_->hs_.NewHandle(klass));
1400 } else {
1401 VLOG(compiler) << "Removing " << (resolved ? "unsuitable" : "unresolved")
1402 << " class from image classes: " << descriptor;
1403 data_->image_class_descriptors_->erase(it);
1404 }
1405 } else if (can_include_in_image) {
1406 // Check whether the class is initialized and has a clinit or static fields.
1407 // Such classes must be kept too.
1408 if (klass->IsInitialized() && !klass->IsArrayClass()) {
1409 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1410 if (klass->FindClassInitializer(pointer_size) != nullptr || klass->HasStaticFields()) {
1411 DCHECK(!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass->GetDexCache()))
1412 << klass->PrettyDescriptor();
1413 data_->image_classes_.push_back(data_->hs_.NewHandle(klass));
1414 }
1415 }
1416 }
1417 return true;
1418 }
1419
1420 private:
1421 ClinitImageUpdate* const data_;
1422 };
1423
VisitClinitClassesObject(mirror::Object * object) const1424 void VisitClinitClassesObject(mirror::Object* object) const
1425 REQUIRES_SHARED(Locks::mutator_lock_) {
1426 DCHECK(object != nullptr);
1427 if (marked_objects_.find(object) != marked_objects_.end()) {
1428 // Already processed.
1429 return;
1430 }
1431
1432 // Mark it.
1433 marked_objects_.insert(object);
1434
1435 if (object->IsClass()) {
1436 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1437 // suspensionb is not safe to do in VisitObjects or VisitReferences.
1438 to_insert_.push_back(hs_.NewHandle(object->AsClass()));
1439 } else {
1440 // Else visit the object's class.
1441 VisitClinitClassesObject(object->GetClass());
1442 }
1443
1444 // If it is not a DexCache, visit all references.
1445 if (!object->IsDexCache()) {
1446 object->VisitReferences(*this, *this);
1447 }
1448 }
1449
1450 mutable VariableSizedHandleScope hs_;
1451 mutable std::vector<Handle<mirror::Class>> to_insert_;
1452 mutable HashSet<mirror::Object*> marked_objects_;
1453 HashSet<std::string>* const image_class_descriptors_;
1454 std::vector<Handle<mirror::Class>> image_classes_;
1455 Thread* const self_;
1456 const char* old_cause_;
1457
1458 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1459 };
1460
UpdateImageClasses(TimingLogger * timings,HashSet<std::string> * image_classes)1461 void CompilerDriver::UpdateImageClasses(TimingLogger* timings,
1462 /*inout*/ HashSet<std::string>* image_classes) {
1463 DCHECK(GetCompilerOptions().IsGeneratingImage());
1464 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
1465
1466 // Suspend all threads.
1467 ScopedSuspendAll ssa(__FUNCTION__);
1468
1469 ClinitImageUpdate update(image_classes, Thread::Current());
1470
1471 // Do the marking.
1472 update.Walk();
1473 }
1474
ProcessedInstanceField(bool resolved)1475 void CompilerDriver::ProcessedInstanceField(bool resolved) {
1476 if (!resolved) {
1477 stats_->UnresolvedInstanceField();
1478 } else {
1479 stats_->ResolvedInstanceField();
1480 }
1481 }
1482
ProcessedStaticField(bool resolved,bool local)1483 void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1484 if (!resolved) {
1485 stats_->UnresolvedStaticField();
1486 } else if (local) {
1487 stats_->ResolvedLocalStaticField();
1488 } else {
1489 stats_->ResolvedStaticField();
1490 }
1491 }
1492
ComputeInstanceFieldInfo(uint32_t field_idx,const DexCompilationUnit * mUnit,bool is_put,const ScopedObjectAccess & soa)1493 ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1494 const DexCompilationUnit* mUnit,
1495 bool is_put,
1496 const ScopedObjectAccess& soa) {
1497 // Try to resolve the field and compiling method's class.
1498 ArtField* resolved_field;
1499 ObjPtr<mirror::Class> referrer_class;
1500 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
1501 {
1502 Handle<mirror::ClassLoader> class_loader = mUnit->GetClassLoader();
1503 resolved_field = ResolveField(soa, dex_cache, class_loader, field_idx, /* is_static= */ false);
1504 referrer_class = resolved_field != nullptr
1505 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
1506 }
1507 bool can_link = false;
1508 if (resolved_field != nullptr && referrer_class != nullptr) {
1509 std::pair<bool, bool> fast_path = IsFastInstanceField(
1510 dex_cache.Get(), referrer_class, resolved_field, field_idx);
1511 can_link = is_put ? fast_path.second : fast_path.first;
1512 }
1513 ProcessedInstanceField(can_link);
1514 return can_link ? resolved_field : nullptr;
1515 }
1516
ComputeInstanceFieldInfo(uint32_t field_idx,const DexCompilationUnit * mUnit,bool is_put,MemberOffset * field_offset,bool * is_volatile)1517 bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1518 bool is_put, MemberOffset* field_offset,
1519 bool* is_volatile) {
1520 ScopedObjectAccess soa(Thread::Current());
1521 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
1522
1523 if (resolved_field == nullptr) {
1524 // Conservative defaults.
1525 *is_volatile = true;
1526 *field_offset = MemberOffset(static_cast<size_t>(-1));
1527 return false;
1528 } else {
1529 *is_volatile = resolved_field->IsVolatile();
1530 *field_offset = resolved_field->GetOffset();
1531 return true;
1532 }
1533 }
1534
1535 class CompilationVisitor {
1536 public:
~CompilationVisitor()1537 virtual ~CompilationVisitor() {}
1538 virtual void Visit(size_t index) = 0;
1539 };
1540
1541 class ParallelCompilationManager {
1542 public:
ParallelCompilationManager(ClassLinker * class_linker,jobject class_loader,CompilerDriver * compiler,const DexFile * dex_file,ThreadPool * thread_pool)1543 ParallelCompilationManager(ClassLinker* class_linker,
1544 jobject class_loader,
1545 CompilerDriver* compiler,
1546 const DexFile* dex_file,
1547 ThreadPool* thread_pool)
1548 : index_(0),
1549 class_linker_(class_linker),
1550 class_loader_(class_loader),
1551 compiler_(compiler),
1552 dex_file_(dex_file),
1553 thread_pool_(thread_pool) {}
1554
GetClassLinker() const1555 ClassLinker* GetClassLinker() const {
1556 CHECK(class_linker_ != nullptr);
1557 return class_linker_;
1558 }
1559
GetClassLoader() const1560 jobject GetClassLoader() const {
1561 return class_loader_;
1562 }
1563
GetCompiler() const1564 CompilerDriver* GetCompiler() const {
1565 CHECK(compiler_ != nullptr);
1566 return compiler_;
1567 }
1568
GetDexFile() const1569 const DexFile* GetDexFile() const {
1570 CHECK(dex_file_ != nullptr);
1571 return dex_file_;
1572 }
1573
ForAll(size_t begin,size_t end,CompilationVisitor * visitor,size_t work_units)1574 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1575 REQUIRES(!*Locks::mutator_lock_) {
1576 ForAllLambda(begin, end, [visitor](size_t index) { visitor->Visit(index); }, work_units);
1577 }
1578
1579 template <typename Fn>
ForAllLambda(size_t begin,size_t end,Fn fn,size_t work_units)1580 void ForAllLambda(size_t begin, size_t end, Fn fn, size_t work_units)
1581 REQUIRES(!*Locks::mutator_lock_) {
1582 Thread* self = Thread::Current();
1583 self->AssertNoPendingException();
1584 CHECK_GT(work_units, 0U);
1585
1586 index_.store(begin, std::memory_order_relaxed);
1587 for (size_t i = 0; i < work_units; ++i) {
1588 thread_pool_->AddTask(self, new ForAllClosureLambda<Fn>(this, end, fn));
1589 }
1590 thread_pool_->StartWorkers(self);
1591
1592 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1593 // thread destructor's called below perform join).
1594 CHECK_NE(self->GetState(), ThreadState::kRunnable);
1595
1596 // Wait for all the worker threads to finish.
1597 thread_pool_->Wait(self, true, false);
1598
1599 // And stop the workers accepting jobs.
1600 thread_pool_->StopWorkers(self);
1601 }
1602
NextIndex()1603 size_t NextIndex() {
1604 return index_.fetch_add(1, std::memory_order_seq_cst);
1605 }
1606
1607 private:
1608 template <typename Fn>
1609 class ForAllClosureLambda : public Task {
1610 public:
ForAllClosureLambda(ParallelCompilationManager * manager,size_t end,Fn fn)1611 ForAllClosureLambda(ParallelCompilationManager* manager, size_t end, Fn fn)
1612 : manager_(manager),
1613 end_(end),
1614 fn_(fn) {}
1615
Run(Thread * self)1616 void Run(Thread* self) override {
1617 while (true) {
1618 const size_t index = manager_->NextIndex();
1619 if (UNLIKELY(index >= end_)) {
1620 break;
1621 }
1622 fn_(index);
1623 self->AssertNoPendingException();
1624 }
1625 }
1626
Finalize()1627 void Finalize() override {
1628 delete this;
1629 }
1630
1631 private:
1632 ParallelCompilationManager* const manager_;
1633 const size_t end_;
1634 Fn fn_;
1635 };
1636
1637 AtomicInteger index_;
1638 ClassLinker* const class_linker_;
1639 const jobject class_loader_;
1640 CompilerDriver* const compiler_;
1641 const DexFile* const dex_file_;
1642 ThreadPool* const thread_pool_;
1643
1644 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
1645 };
1646
1647 // A fast version of SkipClass above if the class pointer is available
1648 // that avoids the expensive FindInClassPath search.
SkipClass(jobject class_loader,const DexFile & dex_file,ObjPtr<mirror::Class> klass)1649 static bool SkipClass(jobject class_loader, const DexFile& dex_file, ObjPtr<mirror::Class> klass)
1650 REQUIRES_SHARED(Locks::mutator_lock_) {
1651 DCHECK(klass != nullptr);
1652 const DexFile& original_dex_file = klass->GetDexFile();
1653 if (&dex_file != &original_dex_file) {
1654 if (class_loader == nullptr) {
1655 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
1656 << dex_file.GetLocation() << " previously found in "
1657 << original_dex_file.GetLocation();
1658 }
1659 return true;
1660 }
1661 return false;
1662 }
1663
DCheckResolveException(mirror::Throwable * exception)1664 static void DCheckResolveException(mirror::Throwable* exception)
1665 REQUIRES_SHARED(Locks::mutator_lock_) {
1666 if (!kIsDebugBuild) {
1667 return;
1668 }
1669 std::string temp;
1670 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1671 const char* expected_exceptions[] = {
1672 "Ljava/lang/ClassFormatError;",
1673 "Ljava/lang/ClassCircularityError;",
1674 "Ljava/lang/IllegalAccessError;",
1675 "Ljava/lang/IncompatibleClassChangeError;",
1676 "Ljava/lang/InstantiationError;",
1677 "Ljava/lang/LinkageError;",
1678 "Ljava/lang/NoClassDefFoundError;",
1679 "Ljava/lang/VerifyError;",
1680 };
1681 bool found = false;
1682 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1683 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1684 found = true;
1685 }
1686 }
1687 if (!found) {
1688 LOG(FATAL) << "Unexpected exception " << exception->Dump();
1689 }
1690 }
1691
1692 template <bool kApp>
1693 class ResolveTypeVisitor : public CompilationVisitor {
1694 public:
ResolveTypeVisitor(const ParallelCompilationManager * manager)1695 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1696 }
Visit(size_t index)1697 void Visit(size_t index) override REQUIRES(!Locks::mutator_lock_) {
1698 const DexFile& dex_file = *manager_->GetDexFile();
1699 // For boot images we resolve all referenced types, such as arrays,
1700 // whereas for applications just those with classdefs.
1701 dex::TypeIndex type_idx = kApp ? dex_file.GetClassDef(index).class_idx_ : dex::TypeIndex(index);
1702 ClassLinker* class_linker = manager_->GetClassLinker();
1703 ScopedObjectAccess soa(Thread::Current());
1704 StackHandleScope<kApp ? 4u : 2u> hs(soa.Self());
1705 Handle<mirror::ClassLoader> class_loader(
1706 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
1707 // TODO: Fix tests that require `RegisterDexFile()` and use `FindDexCache()` in all cases.
1708 Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1709 kApp ? class_linker->FindDexCache(soa.Self(), dex_file)
1710 : class_linker->RegisterDexFile(dex_file, class_loader.Get()));
1711 DCHECK(dex_cache != nullptr);
1712
1713 // Resolve the class.
1714 ObjPtr<mirror::Class> klass = class_linker->ResolveType(type_idx, dex_cache, class_loader);
1715 if (klass == nullptr) {
1716 mirror::Throwable* exception = soa.Self()->GetException();
1717 DCHECK(exception != nullptr);
1718 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1719 if (exception->GetClass() == WellKnownClasses::java_lang_OutOfMemoryError.Get()) {
1720 // There's little point continuing compilation if the heap is exhausted.
1721 // Trying to do so would also introduce non-deterministic compilation results.
1722 LOG(FATAL) << "Out of memory during type resolution for compilation";
1723 }
1724 DCheckResolveException(exception);
1725 soa.Self()->ClearException();
1726 } else {
1727 if (kApp && manager_->GetCompiler()->GetCompilerOptions().IsCheckLinkageConditions()) {
1728 Handle<mirror::Class> hklass = hs.NewHandle(klass);
1729 bool is_fatal = manager_->GetCompiler()->GetCompilerOptions().IsCrashOnLinkageViolation();
1730 Handle<mirror::ClassLoader> defining_class_loader = hs.NewHandle(hklass->GetClassLoader());
1731 if (defining_class_loader.Get() != class_loader.Get()) {
1732 // Redefinition via different ClassLoaders.
1733 // This OptStat stuff is to enable logging from the APK scanner.
1734 if (is_fatal)
1735 LOG(FATAL) << "OptStat#" << hklass->PrettyClassAndClassLoader() << ": 1";
1736 else
1737 LOG(ERROR)
1738 << "LINKAGE VIOLATION: "
1739 << hklass->PrettyClassAndClassLoader()
1740 << " was redefined";
1741 }
1742 // Check that the current class is not a subclass of java.lang.ClassLoader.
1743 if (!hklass->IsInterface() &&
1744 hklass->IsSubClass(GetClassRoot<mirror::ClassLoader>(class_linker))) {
1745 // Subclassing of java.lang.ClassLoader.
1746 // This OptStat stuff is to enable logging from the APK scanner.
1747 if (is_fatal) {
1748 LOG(FATAL) << "OptStat#" << hklass->PrettyClassAndClassLoader() << ": 1";
1749 } else {
1750 LOG(ERROR)
1751 << "LINKAGE VIOLATION: "
1752 << hklass->PrettyClassAndClassLoader()
1753 << " is a subclass of java.lang.ClassLoader";
1754 }
1755 }
1756 CHECK(hklass->IsResolved()) << hklass->PrettyClass();
1757 }
1758 }
1759 }
1760
1761 private:
1762 const ParallelCompilationManager* const manager_;
1763 };
1764
ResolveDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)1765 void CompilerDriver::ResolveDexFile(jobject class_loader,
1766 const DexFile& dex_file,
1767 ThreadPool* thread_pool,
1768 size_t thread_count,
1769 TimingLogger* timings) {
1770 ScopedTrace trace(__FUNCTION__);
1771 TimingLogger::ScopedTiming t("Resolve Dex File", timings);
1772 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1773
1774 // TODO: we could resolve strings here, although the string table is largely filled with class
1775 // and method names.
1776
1777 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1778 // For boot images we resolve all referenced types, such as arrays,
1779 // whereas for applications just those with classdefs.
1780 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
1781 ResolveTypeVisitor</*kApp=*/ false> visitor(&context);
1782 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
1783 } else {
1784 ResolveTypeVisitor</*kApp=*/ true> visitor(&context);
1785 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
1786 }
1787 }
1788
SetVerified(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1789 void CompilerDriver::SetVerified(jobject class_loader,
1790 const std::vector<const DexFile*>& dex_files,
1791 TimingLogger* timings) {
1792 // This can be run in parallel.
1793 for (const DexFile* dex_file : dex_files) {
1794 CHECK(dex_file != nullptr);
1795 SetVerifiedDexFile(class_loader,
1796 *dex_file,
1797 parallel_thread_pool_.get(),
1798 parallel_thread_count_,
1799 timings);
1800 }
1801 }
1802
LoadAndUpdateStatus(const ClassAccessor & accessor,ClassStatus status,Handle<mirror::ClassLoader> class_loader,Thread * self)1803 static void LoadAndUpdateStatus(const ClassAccessor& accessor,
1804 ClassStatus status,
1805 Handle<mirror::ClassLoader> class_loader,
1806 Thread* self)
1807 REQUIRES_SHARED(Locks::mutator_lock_) {
1808 StackHandleScope<1> hs(self);
1809 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1810 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1811 class_linker->FindClass(self, accessor.GetDexFile(), accessor.GetClassIdx(), class_loader)));
1812 if (cls != nullptr) {
1813 // Check that the class is resolved with the current dex file. We might get
1814 // a boot image class, or a class in a different dex file for multidex, and
1815 // we should not update the status in that case.
1816 if (&cls->GetDexFile() == &accessor.GetDexFile()) {
1817 VLOG(compiler) << "Updating class status of " << accessor.GetDescriptorView()
1818 << " to " << status;
1819 ObjectLock<mirror::Class> lock(self, cls);
1820 mirror::Class::SetStatus(cls, status, self);
1821 }
1822 } else {
1823 DCHECK(self->IsExceptionPending());
1824 self->ClearException();
1825 }
1826 }
1827
FastVerify(jobject jclass_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1828 bool CompilerDriver::FastVerify(jobject jclass_loader,
1829 const std::vector<const DexFile*>& dex_files,
1830 TimingLogger* timings) {
1831 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
1832 verifier::VerifierDeps* verifier_deps = callbacks->GetVerifierDeps();
1833 // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1834 if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
1835 return false;
1836 }
1837 TimingLogger::ScopedTiming t("Fast Verify", timings);
1838
1839 ScopedObjectAccess soa(Thread::Current());
1840 StackHandleScope<2> hs(soa.Self());
1841 Handle<mirror::ClassLoader> class_loader(
1842 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1843 std::string error_msg;
1844
1845 verifier_deps->ValidateDependenciesAndUpdateStatus(
1846 soa.Self(),
1847 class_loader,
1848 dex_files);
1849
1850 bool compiler_only_verifies =
1851 !GetCompilerOptions().IsAnyCompilationEnabled() &&
1852 !GetCompilerOptions().IsGeneratingImage();
1853
1854 const bool is_generating_image = GetCompilerOptions().IsGeneratingImage();
1855
1856 // We successfully validated the dependencies, now update class status
1857 // of verified classes. Note that the dependencies also record which classes
1858 // could not be fully verified; we could try again, but that would hurt verification
1859 // time. So instead we assume these classes still need to be verified at
1860 // runtime.
1861 for (const DexFile* dex_file : dex_files) {
1862 // Fetch the list of verified classes.
1863 const std::vector<bool>& verified_classes = verifier_deps->GetVerifiedClasses(*dex_file);
1864 DCHECK_EQ(verified_classes.size(), dex_file->NumClassDefs());
1865 for (ClassAccessor accessor : dex_file->GetClasses()) {
1866 ClassStatus status = verified_classes[accessor.GetClassDefIndex()]
1867 ? ClassStatus::kVerifiedNeedsAccessChecks
1868 : ClassStatus::kRetryVerificationAtRuntime;
1869 if (compiler_only_verifies) {
1870 // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1871 // the type.
1872 ClassReference ref(dex_file, accessor.GetClassDefIndex());
1873 const ClassStatus existing = ClassStatus::kNotReady;
1874 // Note: when dex files are compiled inidividually, the class may have
1875 // been verified in a previous stage. This means this insertion can
1876 // fail, but that's OK.
1877 compiled_classes_.Insert(ref, existing, status);
1878 } else {
1879 if (is_generating_image &&
1880 status == ClassStatus::kVerifiedNeedsAccessChecks &&
1881 GetCompilerOptions().IsImageClass(accessor.GetDescriptor())) {
1882 // If the class will be in the image, we can rely on the ArtMethods
1883 // telling that they need access checks.
1884 VLOG(compiler) << "Promoting "
1885 << accessor.GetDescriptorView()
1886 << " from needs access checks to verified given it is an image class";
1887 status = ClassStatus::kVerified;
1888 }
1889 // Update the class status, so later compilation stages know they don't need to verify
1890 // the class.
1891 LoadAndUpdateStatus(accessor, status, class_loader, soa.Self());
1892 }
1893
1894 // Vdex marks class as unverified for two reasons only:
1895 // 1. It has a hard failure, or
1896 // 2. One of its method needs lock counting.
1897 //
1898 // The optimizing compiler expects a method to not have a hard failure before
1899 // compiling it, so for simplicity just disable any compilation of methods
1900 // of these classes.
1901 if (status == ClassStatus::kRetryVerificationAtRuntime) {
1902 ClassReference ref(dex_file, accessor.GetClassDefIndex());
1903 callbacks->AddUncompilableClass(ref);
1904 }
1905 }
1906 }
1907 return true;
1908 }
1909
Verify(jobject jclass_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1910 void CompilerDriver::Verify(jobject jclass_loader,
1911 const std::vector<const DexFile*>& dex_files,
1912 TimingLogger* timings) {
1913 if (FastVerify(jclass_loader, dex_files, timings)) {
1914 return;
1915 }
1916
1917 // If there is no existing `verifier_deps` (because of non-existing vdex), or
1918 // the existing `verifier_deps` is not valid anymore, create a new one. The
1919 // verifier will need it to record the new dependencies. Then dex2oat can update
1920 // the vdex file with these new dependencies.
1921 // Dex2oat creates the verifier deps.
1922 // Create the main VerifierDeps, and set it to this thread.
1923 verifier::VerifierDeps* main_verifier_deps =
1924 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1925 // Verifier deps can be null when unit testing.
1926 if (main_verifier_deps != nullptr) {
1927 Thread::Current()->SetVerifierDeps(main_verifier_deps);
1928 // Create per-thread VerifierDeps to avoid contention on the main one.
1929 // We will merge them after verification.
1930 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1931 worker->GetThread()->SetVerifierDeps(
1932 new verifier::VerifierDeps(GetCompilerOptions().GetDexFilesForOatFile()));
1933 }
1934 }
1935
1936 {
1937 TimingLogger::ScopedTiming t("Verify Classes", timings);
1938 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
1939 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
1940 ThreadPool* verify_thread_pool =
1941 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
1942 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
1943 for (const DexFile* dex_file : dex_files) {
1944 CHECK(dex_file != nullptr);
1945 VerifyDexFile(jclass_loader,
1946 *dex_file,
1947 verify_thread_pool,
1948 verify_thread_count,
1949 timings);
1950 }
1951 }
1952
1953 if (main_verifier_deps != nullptr) {
1954 // Merge all VerifierDeps into the main one.
1955 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1956 std::unique_ptr<verifier::VerifierDeps> thread_deps(worker->GetThread()->GetVerifierDeps());
1957 worker->GetThread()->SetVerifierDeps(nullptr); // We just took ownership.
1958 main_verifier_deps->MergeWith(std::move(thread_deps),
1959 GetCompilerOptions().GetDexFilesForOatFile());
1960 }
1961 Thread::Current()->SetVerifierDeps(nullptr);
1962 }
1963 }
1964
1965 class VerifyClassVisitor : public CompilationVisitor {
1966 public:
VerifyClassVisitor(const ParallelCompilationManager * manager,verifier::HardFailLogMode log_level)1967 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
1968 : manager_(manager),
1969 log_level_(log_level),
1970 sdk_version_(Runtime::Current()->GetTargetSdkVersion()) {}
1971
Visit(size_t class_def_index)1972 void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
1973 ScopedTrace trace(__FUNCTION__);
1974 ScopedObjectAccess soa(Thread::Current());
1975 const DexFile& dex_file = *manager_->GetDexFile();
1976 const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1977 ClassLinker* class_linker = manager_->GetClassLinker();
1978 jobject jclass_loader = manager_->GetClassLoader();
1979 StackHandleScope<3> hs(soa.Self());
1980 Handle<mirror::ClassLoader> class_loader(
1981 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1982 Handle<mirror::Class> klass = hs.NewHandle(
1983 class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
1984 ClassReference ref(manager_->GetDexFile(), class_def_index);
1985 verifier::FailureKind failure_kind;
1986 if (klass == nullptr) {
1987 CHECK(soa.Self()->IsExceptionPending());
1988 soa.Self()->ClearException();
1989
1990 /*
1991 * At compile time, we can still structurally verify the class even if FindClass fails.
1992 * This is to ensure the class is structurally sound for compilation. An unsound class
1993 * will be rejected by the verifier and later skipped during compilation in the compiler.
1994 */
1995 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1996 soa.Self(), dex_file)));
1997 std::string error_msg;
1998 failure_kind =
1999 verifier::ClassVerifier::VerifyClass(soa.Self(),
2000 soa.Self()->GetVerifierDeps(),
2001 &dex_file,
2002 klass,
2003 dex_cache,
2004 class_loader,
2005 class_def,
2006 Runtime::Current()->GetCompilerCallbacks(),
2007 log_level_,
2008 sdk_version_,
2009 &error_msg);
2010 switch (failure_kind) {
2011 case verifier::FailureKind::kHardFailure: {
2012 manager_->GetCompiler()->SetHadHardVerifierFailure();
2013 break;
2014 }
2015 case verifier::FailureKind::kSoftFailure: {
2016 manager_->GetCompiler()->AddSoftVerifierFailure();
2017 break;
2018 }
2019 case verifier::FailureKind::kTypeChecksFailure: {
2020 // Don't record anything, we will do the type checks from the vdex
2021 // file at runtime.
2022 break;
2023 }
2024 case verifier::FailureKind::kAccessChecksFailure: {
2025 manager_->GetCompiler()->RecordClassStatus(ref, ClassStatus::kVerifiedNeedsAccessChecks);
2026 break;
2027 }
2028 case verifier::FailureKind::kNoFailure: {
2029 manager_->GetCompiler()->RecordClassStatus(ref, ClassStatus::kVerified);
2030 break;
2031 }
2032 }
2033 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2034 // Skip a duplicate class (as the resolved class is from another, earlier dex file).
2035 return; // Do not update state.
2036 } else {
2037 CHECK(klass->IsResolved()) << klass->PrettyClass();
2038 failure_kind = class_linker->VerifyClass(soa.Self(),
2039 soa.Self()->GetVerifierDeps(),
2040 klass,
2041 log_level_);
2042
2043 DCHECK_EQ(klass->IsErroneous(), failure_kind == verifier::FailureKind::kHardFailure);
2044 if (failure_kind == verifier::FailureKind::kHardFailure) {
2045 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2046 CHECK(soa.Self()->IsExceptionPending());
2047 soa.Self()->ClearException();
2048 manager_->GetCompiler()->SetHadHardVerifierFailure();
2049 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2050 manager_->GetCompiler()->AddSoftVerifierFailure();
2051 }
2052
2053 CHECK(klass->ShouldVerifyAtRuntime() ||
2054 klass->IsVerifiedNeedsAccessChecks() ||
2055 klass->IsVerified() ||
2056 klass->IsErroneous())
2057 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
2058
2059 // Class has a meaningful status for the compiler now, record it.
2060 ClassStatus status = klass->GetStatus();
2061 if (status == ClassStatus::kInitialized) {
2062 // Initialized classes shall be visibly initialized when loaded from the image.
2063 status = ClassStatus::kVisiblyInitialized;
2064 }
2065 manager_->GetCompiler()->RecordClassStatus(ref, status);
2066
2067 // It is *very* problematic if there are resolution errors in the boot classpath.
2068 //
2069 // It is also bad if classes fail verification. For example, we rely on things working
2070 // OK without verification when the decryption dialog is brought up. It is thus highly
2071 // recommended to compile the boot classpath with
2072 // --abort-on-hard-verifier-error --abort-on-soft-verifier-error
2073 // which is the default build system configuration.
2074 if (kIsDebugBuild) {
2075 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage() ||
2076 manager_->GetCompiler()->GetCompilerOptions().IsBootImageExtension()) {
2077 if (!klass->IsResolved() || klass->IsErroneous()) {
2078 LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
2079 << " failed to resolve/is erroneous: state= " << klass->GetStatus();
2080 UNREACHABLE();
2081 }
2082 }
2083 if (klass->IsVerified()) {
2084 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
2085 } else if (klass->IsVerifiedNeedsAccessChecks()) {
2086 DCHECK_EQ(failure_kind, verifier::FailureKind::kAccessChecksFailure);
2087 } else if (klass->ShouldVerifyAtRuntime()) {
2088 DCHECK_NE(failure_kind, verifier::FailureKind::kHardFailure);
2089 // This could either be due to:
2090 // - kTypeChecksFailure, or
2091 // - kSoftFailure, or
2092 // - the superclass or interfaces not being verified.
2093 } else {
2094 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
2095 }
2096 }
2097 }
2098 verifier::VerifierDeps::MaybeRecordVerificationStatus(soa.Self()->GetVerifierDeps(),
2099 dex_file,
2100 class_def,
2101 failure_kind);
2102 soa.Self()->AssertNoPendingException();
2103 }
2104
2105 private:
2106 const ParallelCompilationManager* const manager_;
2107 const verifier::HardFailLogMode log_level_;
2108 const uint32_t sdk_version_;
2109 };
2110
VerifyDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)2111 void CompilerDriver::VerifyDexFile(jobject class_loader,
2112 const DexFile& dex_file,
2113 ThreadPool* thread_pool,
2114 size_t thread_count,
2115 TimingLogger* timings) {
2116 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2117 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2118 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
2119 bool abort_on_verifier_failures = GetCompilerOptions().AbortOnHardVerifierFailure()
2120 || GetCompilerOptions().AbortOnSoftVerifierFailure();
2121 verifier::HardFailLogMode log_level = abort_on_verifier_failures
2122 ? verifier::HardFailLogMode::kLogInternalFatal
2123 : verifier::HardFailLogMode::kLogWarning;
2124 VerifyClassVisitor visitor(&context, log_level);
2125 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
2126
2127 // Make initialized classes visibly initialized.
2128 class_linker->MakeInitializedClassesVisiblyInitialized(Thread::Current(), /*wait=*/ true);
2129 }
2130
2131 class SetVerifiedClassVisitor : public CompilationVisitor {
2132 public:
SetVerifiedClassVisitor(const ParallelCompilationManager * manager)2133 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2134
Visit(size_t class_def_index)2135 void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
2136 ScopedTrace trace(__FUNCTION__);
2137 ScopedObjectAccess soa(Thread::Current());
2138 const DexFile& dex_file = *manager_->GetDexFile();
2139 const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2140 ClassLinker* class_linker = manager_->GetClassLinker();
2141 jobject jclass_loader = manager_->GetClassLoader();
2142 StackHandleScope<3> hs(soa.Self());
2143 Handle<mirror::ClassLoader> class_loader(
2144 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2145 Handle<mirror::Class> klass = hs.NewHandle(
2146 class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
2147 // Class might have failed resolution. Then don't set it to verified.
2148 if (klass != nullptr) {
2149 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2150 // very wrong.
2151 if (klass->IsResolved() && !klass->IsErroneousResolved()) {
2152 if (klass->GetStatus() < ClassStatus::kVerified) {
2153 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2154 // Set class status to verified.
2155 mirror::Class::SetStatus(klass, ClassStatus::kVerified, soa.Self());
2156 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2157 // access checks.
2158 InstructionSet instruction_set =
2159 manager_->GetCompiler()->GetCompilerOptions().GetInstructionSet();
2160 klass->SetSkipAccessChecksFlagOnAllMethods(GetInstructionSetPointerSize(instruction_set));
2161 }
2162 // Record the final class status if necessary.
2163 ClassReference ref(manager_->GetDexFile(), class_def_index);
2164 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
2165 }
2166 } else {
2167 Thread* self = soa.Self();
2168 DCHECK(self->IsExceptionPending());
2169 self->ClearException();
2170 }
2171 }
2172
2173 private:
2174 const ParallelCompilationManager* const manager_;
2175 };
2176
SetVerifiedDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)2177 void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2178 const DexFile& dex_file,
2179 ThreadPool* thread_pool,
2180 size_t thread_count,
2181 TimingLogger* timings) {
2182 TimingLogger::ScopedTiming t("Set Verified Dex File", timings);
2183 if (!compiled_classes_.HaveDexFile(&dex_file)) {
2184 compiled_classes_.AddDexFile(&dex_file);
2185 }
2186 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2187 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
2188 SetVerifiedClassVisitor visitor(&context);
2189 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
2190 }
2191
2192 class InitializeClassVisitor : public CompilationVisitor {
2193 public:
InitializeClassVisitor(const ParallelCompilationManager * manager)2194 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2195
Visit(size_t class_def_index)2196 void Visit(size_t class_def_index) override {
2197 ScopedTrace trace(__FUNCTION__);
2198 jobject jclass_loader = manager_->GetClassLoader();
2199 const DexFile& dex_file = *manager_->GetDexFile();
2200 const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2201
2202 ScopedObjectAccess soa(Thread::Current());
2203 StackHandleScope<3> hs(soa.Self());
2204 Handle<mirror::ClassLoader> class_loader(
2205 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2206 Handle<mirror::Class> klass = hs.NewHandle(manager_->GetClassLinker()->FindClass(
2207 soa.Self(), dex_file, class_def.class_idx_, class_loader));
2208
2209 if (klass != nullptr) {
2210 if (!SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2211 TryInitializeClass(soa.Self(), klass, class_loader);
2212 }
2213 manager_->GetCompiler()->stats_->AddClassStatus(klass->GetStatus());
2214 }
2215 // Clear any class not found or verification exceptions.
2216 soa.Self()->ClearException();
2217 }
2218
2219 // A helper function for initializing klass.
TryInitializeClass(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ClassLoader> & class_loader)2220 void TryInitializeClass(Thread* self,
2221 Handle<mirror::Class> klass,
2222 Handle<mirror::ClassLoader>& class_loader)
2223 REQUIRES_SHARED(Locks::mutator_lock_) {
2224 const DexFile& dex_file = klass->GetDexFile();
2225 const dex::ClassDef* class_def = klass->GetClassDef();
2226 const dex::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2227 const char* descriptor = dex_file.GetStringData(class_type_id.descriptor_idx_);
2228 StackHandleScope<3> hs(self);
2229 AotClassLinker* const class_linker = down_cast<AotClassLinker*>(manager_->GetClassLinker());
2230 Runtime* const runtime = Runtime::Current();
2231 const CompilerOptions& compiler_options = manager_->GetCompiler()->GetCompilerOptions();
2232 const bool is_boot_image = compiler_options.IsBootImage();
2233 const bool is_boot_image_extension = compiler_options.IsBootImageExtension();
2234 const bool is_app_image = compiler_options.IsAppImage();
2235
2236 // For boot image extension, do not initialize classes defined
2237 // in dex files belonging to the boot image we're compiling against.
2238 if (is_boot_image_extension &&
2239 runtime->GetHeap()->ObjectIsInBootImageSpace(klass->GetDexCache())) {
2240 // Also return early and don't store the class status in the recorded class status.
2241 return;
2242 }
2243 // Do not initialize classes in boot space when compiling app (with or without image).
2244 if ((!is_boot_image && !is_boot_image_extension) && klass->IsBootStrapClassLoaded()) {
2245 // Also return early and don't store the class status in the recorded class status.
2246 return;
2247 }
2248
2249 ClassStatus old_status = klass->GetStatus();
2250 // Only try to initialize classes that were successfully verified.
2251 if (klass->IsVerified()) {
2252 // Attempt to initialize the class but bail if we either need to initialize the super-class
2253 // or static fields.
2254 class_linker->EnsureInitialized(self, klass, false, false);
2255 DCHECK(!self->IsExceptionPending());
2256 old_status = klass->GetStatus();
2257 if (!klass->IsInitialized()) {
2258 // We don't want non-trivial class initialization occurring on multiple threads due to
2259 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2260 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2261 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2262 // after first initializing its parents, whose locks are acquired. This leads to a
2263 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2264 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2265 // than use a special Object for the purpose we use the Class of java.lang.Class.
2266 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2267 ObjectLock<mirror::Class> lock(self, h_klass);
2268 // Attempt to initialize allowing initialization of parent classes but still not static
2269 // fields.
2270 // Initialize dependencies first only for app or boot image extension,
2271 // to make TryInitializeClass() recursive.
2272 bool try_initialize_with_superclasses =
2273 is_boot_image ? true : InitializeDependencies(klass, class_loader, self);
2274 if (try_initialize_with_superclasses) {
2275 class_linker->EnsureInitialized(self, klass, false, true);
2276 DCHECK(!self->IsExceptionPending());
2277 }
2278 // Otherwise it's in app image or boot image extension but superclasses
2279 // cannot be initialized, no need to proceed.
2280 old_status = klass->GetStatus();
2281
2282 ClassAccessor accessor(klass->GetDexFile(), klass->GetDexClassDefIndex());
2283 bool too_many_encoded_fields = (!is_boot_image && !is_boot_image_extension) &&
2284 accessor.NumStaticFields() > kMaxEncodedFields;
2285
2286 bool have_profile = (compiler_options.GetProfileCompilationInfo() != nullptr) &&
2287 !compiler_options.GetProfileCompilationInfo()->IsEmpty();
2288 // If the class was not initialized, we can proceed to see if we can initialize static
2289 // fields. Limit the max number of encoded fields.
2290 if (!klass->IsInitialized() &&
2291 (is_app_image || is_boot_image || is_boot_image_extension) &&
2292 try_initialize_with_superclasses && !too_many_encoded_fields &&
2293 compiler_options.IsImageClass(descriptor) &&
2294 // TODO(b/274077782): remove this test.
2295 (have_profile || !is_boot_image_extension)) {
2296 bool can_init_static_fields = false;
2297 if (is_boot_image || is_boot_image_extension) {
2298 // We need to initialize static fields, we only do this for image classes that aren't
2299 // marked with the $NoPreloadHolder (which implies this should not be initialized
2300 // early).
2301 can_init_static_fields = !std::string_view(descriptor).ends_with("$NoPreloadHolder;");
2302 } else {
2303 CHECK(is_app_image);
2304 // The boot image case doesn't need to recursively initialize the dependencies with
2305 // special logic since the class linker already does this.
2306 // Optimization will be disabled in debuggable build, because in debuggable mode we
2307 // want the <clinit> behavior to be observable for the debugger, so we don't do the
2308 // <clinit> at compile time.
2309 can_init_static_fields =
2310 ClassLinker::kAppImageMayContainStrings &&
2311 !self->IsExceptionPending() &&
2312 !compiler_options.GetDebuggable() &&
2313 (compiler_options.InitializeAppImageClasses() ||
2314 NoClinitInDependency(klass, self, &class_loader));
2315 // TODO The checking for clinit can be removed since it's already
2316 // checked when init superclass. Currently keep it because it contains
2317 // processing of intern strings. Will be removed later when intern strings
2318 // and clinit are both initialized.
2319 }
2320
2321 if (can_init_static_fields) {
2322 VLOG(compiler) << "Initializing: " << descriptor;
2323 // TODO multithreading support. We should ensure the current compilation thread has
2324 // exclusive access to the runtime and the transaction. To achieve this, we could use
2325 // a ReaderWriterMutex but we're holding the mutator lock so we fail the check of mutex
2326 // validity in Thread::AssertThreadSuspensionIsAllowable.
2327
2328 // Resolve and initialize the exception type before enabling the transaction in case
2329 // the transaction aborts and cannot resolve the type.
2330 // TransactionAbortError is not initialized ant not in boot image, needed only by
2331 // compiler and will be pruned by ImageWriter.
2332 Handle<mirror::Class> exception_class =
2333 hs.NewHandle(class_linker->FindSystemClass(self, kTransactionAbortErrorDescriptor));
2334 bool exception_initialized =
2335 class_linker->EnsureInitialized(self, exception_class, true, true);
2336 DCHECK(exception_initialized);
2337
2338 // Run the class initializer in transaction mode.
2339 class_linker->EnterTransactionMode(is_app_image, klass.Get());
2340
2341 bool success = class_linker->EnsureInitialized(self, klass, true, true);
2342 // TODO we detach transaction from runtime to indicate we quit the transactional
2343 // mode which prevents the GC from visiting objects modified during the transaction.
2344 // Ensure GC is not run so don't access freed objects when aborting transaction.
2345
2346 {
2347 ScopedAssertNoThreadSuspension ants("Transaction end");
2348
2349 if (success) {
2350 class_linker->ExitTransactionMode();
2351 DCHECK(!runtime->IsActiveTransaction());
2352
2353 if (is_boot_image || is_boot_image_extension) {
2354 // For boot image and boot image extension, we want to put the updated
2355 // status in the oat class. This is not the case for app image as we
2356 // want to keep the ability to load the oat file without the app image.
2357 old_status = klass->GetStatus();
2358 }
2359 } else {
2360 CHECK(self->IsExceptionPending());
2361 mirror::Throwable* exception = self->GetException();
2362 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2363 << exception->Dump();
2364 std::ostream* file_log = manager_->GetCompiler()->
2365 GetCompilerOptions().GetInitFailureOutput();
2366 if (file_log != nullptr) {
2367 *file_log << descriptor << "\n";
2368 *file_log << exception->Dump() << "\n";
2369 }
2370 self->ClearException();
2371 class_linker->RollbackAllTransactions();
2372 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
2373 }
2374 }
2375
2376 if (!success && (is_boot_image || is_boot_image_extension)) {
2377 // On failure, still intern strings of static fields and seen in <clinit>, as these
2378 // will be created in the zygote. This is separated from the transaction code just
2379 // above as we will allocate strings, so must be allowed to suspend.
2380 // We only need to intern strings for boot image and boot image extension
2381 // because classes that failed to be initialized will not appear in app image.
2382 if (&klass->GetDexFile() == manager_->GetDexFile()) {
2383 InternStrings(klass, class_loader);
2384 } else {
2385 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
2386 }
2387 }
2388 }
2389 }
2390 // Clear exception in case EnsureInitialized has caused one in the code above.
2391 // It's OK to clear the exception here since the compiler is supposed to be fault
2392 // tolerant and will silently not initialize classes that have exceptions.
2393 self->ClearException();
2394
2395 // If the class still isn't initialized, at least try some checks that initialization
2396 // would do so they can be skipped at runtime.
2397 if (!klass->IsInitialized() && class_linker->ValidateSuperClassDescriptors(klass)) {
2398 old_status = ClassStatus::kSuperclassValidated;
2399 } else {
2400 self->ClearException();
2401 }
2402 self->AssertNoPendingException();
2403 }
2404 }
2405 if (old_status == ClassStatus::kInitialized) {
2406 // Initialized classes shall be visibly initialized when loaded from the image.
2407 old_status = ClassStatus::kVisiblyInitialized;
2408 }
2409 // Record the final class status if necessary.
2410 ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2411 // Back up the status before doing initialization for static encoded fields,
2412 // because the static encoded branch wants to keep the status to uninitialized.
2413 manager_->GetCompiler()->RecordClassStatus(ref, old_status);
2414
2415 if (kIsDebugBuild) {
2416 // Make sure the class initialization did not leave any local references.
2417 self->GetJniEnv()->AssertLocalsEmpty();
2418 }
2419
2420 if (!klass->IsInitialized() &&
2421 (is_boot_image || is_boot_image_extension) &&
2422 !compiler_options.IsPreloadedClass(PrettyDescriptor(descriptor))) {
2423 klass->SetInBootImageAndNotInPreloadedClasses();
2424 }
2425
2426 if (compiler_options.CompileArtTest()) {
2427 // For stress testing and unit-testing the clinit check in compiled code feature.
2428 if (kIsDebugBuild || std::string_view(descriptor).ends_with("$NoPreloadHolder;")) {
2429 klass->SetInBootImageAndNotInPreloadedClasses();
2430 }
2431 }
2432 }
2433
2434 private:
InternStrings(Handle<mirror::Class> klass,Handle<mirror::ClassLoader> class_loader)2435 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2436 REQUIRES_SHARED(Locks::mutator_lock_) {
2437 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage() ||
2438 manager_->GetCompiler()->GetCompilerOptions().IsBootImageExtension());
2439 DCHECK(klass->IsVerified());
2440 DCHECK(!klass->IsInitialized());
2441
2442 StackHandleScope<1> hs(Thread::Current());
2443 Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
2444 const dex::ClassDef* class_def = klass->GetClassDef();
2445 ClassLinker* class_linker = manager_->GetClassLinker();
2446
2447 // Check encoded final field values for strings and intern.
2448 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
2449 class_loader,
2450 manager_->GetClassLinker(),
2451 *class_def);
2452 for ( ; value_it.HasNext(); value_it.Next()) {
2453 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2454 // Resolve the string. This will intern the string.
2455 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
2456 dex::StringIndex(value_it.GetJavaValue().i), dex_cache);
2457 CHECK(resolved != nullptr);
2458 }
2459 }
2460
2461 // Intern strings seen in <clinit>.
2462 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2463 if (clinit != nullptr) {
2464 for (const DexInstructionPcPair& inst : clinit->DexInstructions()) {
2465 if (inst->Opcode() == Instruction::CONST_STRING) {
2466 ObjPtr<mirror::String> s = class_linker->ResolveString(
2467 dex::StringIndex(inst->VRegB_21c()), dex_cache);
2468 CHECK(s != nullptr);
2469 } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
2470 ObjPtr<mirror::String> s = class_linker->ResolveString(
2471 dex::StringIndex(inst->VRegB_31c()), dex_cache);
2472 CHECK(s != nullptr);
2473 }
2474 }
2475 }
2476 }
2477
ResolveTypesOfMethods(Thread * self,ArtMethod * m)2478 bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2479 REQUIRES_SHARED(Locks::mutator_lock_) {
2480 // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2481 ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
2482 if (rtn_type == nullptr) {
2483 self->ClearException();
2484 return false;
2485 }
2486 const dex::TypeList* types = m->GetParameterTypeList();
2487 if (types != nullptr) {
2488 for (uint32_t i = 0; i < types->Size(); ++i) {
2489 dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
2490 ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
2491 if (param_type == nullptr) {
2492 self->ClearException();
2493 return false;
2494 }
2495 }
2496 }
2497 return true;
2498 }
2499
2500 // Pre resolve types mentioned in all method signatures before start a transaction
2501 // since ResolveType doesn't work in transaction mode.
PreResolveTypes(Thread * self,const Handle<mirror::Class> & klass)2502 bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2503 REQUIRES_SHARED(Locks::mutator_lock_) {
2504 PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2505 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2506 if (!ResolveTypesOfMethods(self, &m)) {
2507 return false;
2508 }
2509 }
2510 if (klass->IsInterface()) {
2511 return true;
2512 } else if (klass->HasSuperClass()) {
2513 StackHandleScope<1> hs(self);
2514 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2515 for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2516 ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2517 ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2518 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2519 return false;
2520 }
2521 }
2522 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2523 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2524 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2525 uint32_t num_methods = super_klass->NumVirtualMethods();
2526 for (uint32_t j = 0; j < num_methods; ++j) {
2527 ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2528 j, pointer_size);
2529 ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2530 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2531 return false;
2532 }
2533 }
2534 }
2535 }
2536 }
2537 return true;
2538 }
2539
2540 // Initialize the klass's dependencies recursively before initializing itself.
2541 // Checking for interfaces is also necessary since interfaces that contain
2542 // default methods must be initialized before the class.
InitializeDependencies(const Handle<mirror::Class> & klass,Handle<mirror::ClassLoader> class_loader,Thread * self)2543 bool InitializeDependencies(const Handle<mirror::Class>& klass,
2544 Handle<mirror::ClassLoader> class_loader,
2545 Thread* self)
2546 REQUIRES_SHARED(Locks::mutator_lock_) {
2547 if (klass->HasSuperClass()) {
2548 StackHandleScope<1> hs(self);
2549 Handle<mirror::Class> super_class = hs.NewHandle(klass->GetSuperClass());
2550 if (!super_class->IsInitialized()) {
2551 this->TryInitializeClass(self, super_class, class_loader);
2552 if (!super_class->IsInitialized()) {
2553 return false;
2554 }
2555 }
2556 }
2557
2558 if (!klass->IsInterface()) {
2559 size_t num_interfaces = klass->GetIfTableCount();
2560 for (size_t i = 0; i < num_interfaces; ++i) {
2561 StackHandleScope<1> hs(self);
2562 Handle<mirror::Class> iface = hs.NewHandle(klass->GetIfTable()->GetInterface(i));
2563 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
2564 TryInitializeClass(self, iface, class_loader);
2565 if (!iface->IsInitialized()) {
2566 return false;
2567 }
2568 }
2569 }
2570 }
2571
2572 return PreResolveTypes(self, klass);
2573 }
2574
2575 // In this phase the classes containing class initializers are ignored. Make sure no
2576 // clinit appears in klass's super class chain and interfaces.
NoClinitInDependency(const Handle<mirror::Class> & klass,Thread * self,Handle<mirror::ClassLoader> * class_loader)2577 bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2578 Thread* self,
2579 Handle<mirror::ClassLoader>* class_loader)
2580 REQUIRES_SHARED(Locks::mutator_lock_) {
2581 ArtMethod* clinit =
2582 klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2583 if (clinit != nullptr) {
2584 VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2585 return false;
2586 }
2587 if (klass->HasSuperClass()) {
2588 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2589 StackHandleScope<1> hs(self);
2590 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2591 if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2592 return false;
2593 }
2594 }
2595
2596 uint32_t num_if = klass->NumDirectInterfaces();
2597 for (size_t i = 0; i < num_if; i++) {
2598 ObjPtr<mirror::Class> interface = klass->GetDirectInterface(i);
2599 DCHECK(interface != nullptr);
2600 StackHandleScope<1> hs(self);
2601 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2602 if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2603 return false;
2604 }
2605 }
2606
2607 return true;
2608 }
2609
2610 const ParallelCompilationManager* const manager_;
2611 };
2612
InitializeClasses(jobject jni_class_loader,const DexFile & dex_file,TimingLogger * timings)2613 void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2614 const DexFile& dex_file,
2615 TimingLogger* timings) {
2616 TimingLogger::ScopedTiming t("Initialize Classes Dex File", timings);
2617
2618 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2619 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2620 ThreadPool* init_thread_pool = force_determinism
2621 ? single_thread_pool_.get()
2622 : parallel_thread_pool_.get();
2623 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2624
2625 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2626 ParallelCompilationManager context(
2627 class_linker, jni_class_loader, this, &dex_file, init_thread_pool);
2628
2629 if (GetCompilerOptions().IsBootImage() ||
2630 GetCompilerOptions().IsBootImageExtension() ||
2631 GetCompilerOptions().IsAppImage()) {
2632 // Set the concurrency thread to 1 to support initialization for images since transaction
2633 // doesn't support multithreading now.
2634 // TODO: remove this when transactional mode supports multithreading.
2635 init_thread_count = 1U;
2636 }
2637 InitializeClassVisitor visitor(&context);
2638 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
2639
2640 // Make initialized classes visibly initialized.
2641 class_linker->MakeInitializedClassesVisiblyInitialized(Thread::Current(), /*wait=*/ true);
2642 }
2643
InitializeClasses(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)2644 void CompilerDriver::InitializeClasses(jobject class_loader,
2645 const std::vector<const DexFile*>& dex_files,
2646 TimingLogger* timings) {
2647 TimingLogger::ScopedTiming t("Initialize Classes", timings);
2648 for (const DexFile* dex_file : dex_files) {
2649 CHECK(dex_file != nullptr);
2650 InitializeClasses(class_loader, *dex_file, timings);
2651 }
2652 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
2653 // Prune garbage objects created during aborted transactions.
2654 Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ true);
2655 }
2656 }
2657
2658 template <typename CompileFn>
CompileDexFile(CompilerDriver * driver,jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings,const char * timing_name,CompileFn compile_fn)2659 static void CompileDexFile(CompilerDriver* driver,
2660 jobject class_loader,
2661 const DexFile& dex_file,
2662 ThreadPool* thread_pool,
2663 size_t thread_count,
2664 TimingLogger* timings,
2665 const char* timing_name,
2666 CompileFn compile_fn) {
2667 TimingLogger::ScopedTiming t(timing_name, timings);
2668 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(),
2669 class_loader,
2670 driver,
2671 &dex_file,
2672 thread_pool);
2673 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
2674 bool have_profile = (compiler_options.GetProfileCompilationInfo() != nullptr);
2675 bool use_profile = CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter());
2676 ProfileCompilationInfo::ProfileIndexType profile_index = (have_profile && use_profile)
2677 ? compiler_options.GetProfileCompilationInfo()->FindDexFile(dex_file)
2678 : ProfileCompilationInfo::MaxProfileIndex();
2679
2680 auto compile = [&context, &compile_fn, profile_index](size_t class_def_index) {
2681 const DexFile& dex_file = *context.GetDexFile();
2682 SCOPED_TRACE << "compile " << dex_file.GetLocation() << "@" << class_def_index;
2683 ClassLinker* class_linker = context.GetClassLinker();
2684 jobject jclass_loader = context.GetClassLoader();
2685 ClassReference ref(&dex_file, class_def_index);
2686 const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2687 ClassAccessor accessor(dex_file, class_def_index);
2688 CompilerDriver* const driver = context.GetCompiler();
2689 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2690 DCHECK(driver->GetVerificationResults() != nullptr);
2691 if (driver->GetVerificationResults()->IsClassRejected(ref)) {
2692 return;
2693 }
2694 // Use a scoped object access to perform to the quick SkipClass check.
2695 ScopedObjectAccess soa(Thread::Current());
2696 StackHandleScope<3> hs(soa.Self());
2697 Handle<mirror::ClassLoader> class_loader(
2698 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2699 Handle<mirror::Class> klass = hs.NewHandle(
2700 class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
2701 Handle<mirror::DexCache> dex_cache;
2702 if (klass == nullptr) {
2703 soa.Self()->AssertPendingException();
2704 soa.Self()->ClearException();
2705 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2706 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2707 // Skip a duplicate class (as the resolved class is from another, earlier dex file).
2708 return; // Do not update state.
2709 } else {
2710 dex_cache = hs.NewHandle(klass->GetDexCache());
2711 }
2712
2713 // Avoid suspension if there are no methods to compile.
2714 if (accessor.NumDirectMethods() + accessor.NumVirtualMethods() == 0) {
2715 return;
2716 }
2717
2718 // Go to native so that we don't block GC during compilation.
2719 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
2720
2721 // Compile direct and virtual methods.
2722 int64_t previous_method_idx = -1;
2723 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2724 const uint32_t method_idx = method.GetIndex();
2725 if (method_idx == previous_method_idx) {
2726 // smali can create dex files with two encoded_methods sharing the same method_idx
2727 // http://code.google.com/p/smali/issues/detail?id=119
2728 continue;
2729 }
2730 previous_method_idx = method_idx;
2731 compile_fn(soa.Self(),
2732 driver,
2733 method.GetCodeItem(),
2734 method.GetAccessFlags(),
2735 class_def_index,
2736 method_idx,
2737 class_loader,
2738 dex_file,
2739 dex_cache,
2740 profile_index);
2741 }
2742 };
2743 context.ForAllLambda(0, dex_file.NumClassDefs(), compile, thread_count);
2744 }
2745
Compile(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)2746 void CompilerDriver::Compile(jobject class_loader,
2747 const std::vector<const DexFile*>& dex_files,
2748 TimingLogger* timings) {
2749 TimingLogger::ScopedTiming t("Compile Methods", timings);
2750 if (kDebugProfileGuidedCompilation) {
2751 const ProfileCompilationInfo* profile_compilation_info =
2752 GetCompilerOptions().GetProfileCompilationInfo();
2753 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2754 ((profile_compilation_info == nullptr)
2755 ? "null"
2756 : profile_compilation_info->DumpInfo(dex_files));
2757 }
2758
2759 for (const DexFile* dex_file : dex_files) {
2760 CHECK(dex_file != nullptr);
2761 CompileDexFile(this,
2762 class_loader,
2763 *dex_file,
2764 parallel_thread_pool_.get(),
2765 parallel_thread_count_,
2766 timings,
2767 "Compile Dex File Quick",
2768 CompileMethodQuick);
2769 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2770 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2771 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
2772 Runtime::Current()->ReclaimArenaPoolMemory();
2773 }
2774
2775 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
2776 }
2777
AddCompiledMethod(const MethodReference & method_ref,CompiledMethod * const compiled_method)2778 void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2779 CompiledMethod* const compiled_method) {
2780 DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2781 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2782 /*expected*/ nullptr,
2783 compiled_method);
2784 CHECK(result == MethodTable::kInsertResultSuccess);
2785 DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
2786 }
2787
RemoveCompiledMethod(const MethodReference & method_ref)2788 CompiledMethod* CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2789 CompiledMethod* ret = nullptr;
2790 CHECK(compiled_methods_.Remove(method_ref, &ret));
2791 return ret;
2792 }
2793
GetCompiledClass(const ClassReference & ref,ClassStatus * status) const2794 bool CompilerDriver::GetCompiledClass(const ClassReference& ref, ClassStatus* status) const {
2795 DCHECK(status != nullptr);
2796 // The table doesn't know if something wasn't inserted. For this case it will return
2797 // ClassStatus::kNotReady. To handle this, just assume anything we didn't try to verify
2798 // is not compiled.
2799 if (!compiled_classes_.Get(ref, status) ||
2800 *status < ClassStatus::kRetryVerificationAtRuntime) {
2801 return false;
2802 }
2803 return true;
2804 }
2805
GetClassStatus(const ClassReference & ref) const2806 ClassStatus CompilerDriver::GetClassStatus(const ClassReference& ref) const {
2807 ClassStatus status = ClassStatus::kNotReady;
2808 if (!GetCompiledClass(ref, &status)) {
2809 classpath_classes_.Get(ref, &status);
2810 }
2811 return status;
2812 }
2813
RecordClassStatus(const ClassReference & ref,ClassStatus status)2814 void CompilerDriver::RecordClassStatus(const ClassReference& ref, ClassStatus status) {
2815 switch (status) {
2816 case ClassStatus::kErrorResolved:
2817 case ClassStatus::kErrorUnresolved:
2818 case ClassStatus::kNotReady:
2819 case ClassStatus::kResolved:
2820 case ClassStatus::kRetryVerificationAtRuntime:
2821 case ClassStatus::kVerifiedNeedsAccessChecks:
2822 case ClassStatus::kVerified:
2823 case ClassStatus::kSuperclassValidated:
2824 case ClassStatus::kVisiblyInitialized:
2825 break; // Expected states.
2826 default:
2827 LOG(FATAL) << "Unexpected class status for class "
2828 << PrettyDescriptor(
2829 ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
2830 << " of " << status;
2831 }
2832
2833 ClassStateTable::InsertResult result;
2834 ClassStateTable* table = &compiled_classes_;
2835 do {
2836 ClassStatus existing = ClassStatus::kNotReady;
2837 if (!table->Get(ref, &existing)) {
2838 // A classpath class.
2839 if (kIsDebugBuild) {
2840 // Check to make sure it's not a dex file for an oat file we are compiling since these
2841 // should always succeed. These do not include classes in for used libraries.
2842 for (const DexFile* dex_file : GetCompilerOptions().GetDexFilesForOatFile()) {
2843 CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
2844 }
2845 }
2846 if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
2847 // Boot classpath dex file.
2848 return;
2849 }
2850 table = &classpath_classes_;
2851 table->Get(ref, &existing);
2852 }
2853 if (existing >= status) {
2854 // Existing status is already better than we expect, break.
2855 break;
2856 }
2857 // Update the status if we now have a greater one. This happens with vdex,
2858 // which records a class is verified, but does not resolve it.
2859 result = table->Insert(ref, existing, status);
2860 CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
2861 } while (result != ClassStateTable::kInsertResultSuccess);
2862 }
2863
GetCompiledMethod(MethodReference ref) const2864 CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2865 CompiledMethod* compiled_method = nullptr;
2866 compiled_methods_.Get(ref, &compiled_method);
2867 return compiled_method;
2868 }
2869
GetMemoryUsageString(bool extended) const2870 std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
2871 std::ostringstream oss;
2872 const gc::Heap* const heap = Runtime::Current()->GetHeap();
2873 const size_t java_alloc = heap->GetBytesAllocated();
2874 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
2875 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
2876 #if defined(__BIONIC__) || defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
2877 const struct mallinfo info = mallinfo();
2878 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2879 const size_t free_space = static_cast<size_t>(info.fordblks);
2880 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2881 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
2882 #endif
2883 compiled_method_storage_.DumpMemoryUsage(oss, extended);
2884 return oss.str();
2885 }
2886
InitializeThreadPools()2887 void CompilerDriver::InitializeThreadPools() {
2888 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2889 parallel_thread_pool_.reset(
2890 ThreadPool::Create("Compiler driver thread pool", parallel_count));
2891 single_thread_pool_.reset(ThreadPool::Create("Single-threaded Compiler driver thread pool", 0));
2892 }
2893
FreeThreadPools()2894 void CompilerDriver::FreeThreadPools() {
2895 parallel_thread_pool_.reset();
2896 single_thread_pool_.reset();
2897 }
2898
SetClasspathDexFiles(const std::vector<const DexFile * > & dex_files)2899 void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
2900 classpath_classes_.AddDexFiles(dex_files);
2901 }
2902
2903 } // namespace art
2904