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