• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 "jit.h"
18 
19 #include <dlfcn.h>
20 
21 #include "art_method-inl.h"
22 #include "base/enums.h"
23 #include "base/file_utils.h"
24 #include "base/logging.h"  // For VLOG.
25 #include "base/memfd.h"
26 #include "base/memory_tool.h"
27 #include "base/runtime_debug.h"
28 #include "base/scoped_flock.h"
29 #include "base/utils.h"
30 #include "class_root-inl.h"
31 #include "compilation_kind.h"
32 #include "debugger.h"
33 #include "dex/type_lookup_table.h"
34 #include "gc/space/image_space.h"
35 #include "entrypoints/entrypoint_utils-inl.h"
36 #include "entrypoints/runtime_asm_entrypoints.h"
37 #include "image-inl.h"
38 #include "interpreter/interpreter.h"
39 #include "jit-inl.h"
40 #include "jit_code_cache.h"
41 #include "jni/java_vm_ext.h"
42 #include "mirror/method_handle_impl.h"
43 #include "mirror/var_handle.h"
44 #include "oat_file.h"
45 #include "oat_file_manager.h"
46 #include "oat_quick_method_header.h"
47 #include "profile/profile_boot_info.h"
48 #include "profile/profile_compilation_info.h"
49 #include "profile_saver.h"
50 #include "runtime.h"
51 #include "runtime_options.h"
52 #include "stack.h"
53 #include "stack_map.h"
54 #include "thread-inl.h"
55 #include "thread_list.h"
56 
57 using android::base::unique_fd;
58 
59 namespace art {
60 namespace jit {
61 
62 static constexpr bool kEnableOnStackReplacement = true;
63 
64 // Maximum permitted threshold value.
65 static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
66 
67 // Different compilation threshold constants. These can be overridden on the command line.
68 
69 // Non-debug default
70 static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
71 // Fast-debug build.
72 static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
73 // Slow-debug build.
74 static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
75 
76 // Different warm-up threshold constants. These default to the equivalent compile thresholds divided
77 // by 2, but can be overridden at the command-line.
78 static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
79 static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
80 static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
81     kJitSlowStressDefaultCompileThreshold / 2;
82 
83 DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
84 
85 // JIT compiler
86 void* Jit::jit_library_handle_ = nullptr;
87 JitCompilerInterface* Jit::jit_compiler_ = nullptr;
88 JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
89 
CreateFromRuntimeArguments(const RuntimeArgumentMap & options)90 JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
91   auto* jit_options = new JitOptions;
92   jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
93   jit_options->use_profiled_jit_compilation_ =
94       options.GetOrDefault(RuntimeArgumentMap::UseProfiledJitCompilation);
95 
96   jit_options->code_cache_initial_capacity_ =
97       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
98   jit_options->code_cache_max_capacity_ =
99       options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
100   jit_options->dump_info_on_shutdown_ =
101       options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
102   jit_options->profile_saver_options_ =
103       options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
104   jit_options->thread_pool_pthread_priority_ =
105       options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
106   jit_options->zygote_thread_pool_pthread_priority_ =
107       options.GetOrDefault(RuntimeArgumentMap::JITZygotePoolThreadPthreadPriority);
108 
109   // Set default compile threshold to aid with checking defaults.
110   jit_options->compile_threshold_ =
111       kIsDebugBuild
112       ? (Jit::kSlowMode
113          ? kJitSlowStressDefaultCompileThreshold
114          : kJitStressDefaultCompileThreshold)
115       : kJitDefaultCompileThreshold;
116 
117   // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
118   const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
119 
120   // Set default warm-up threshold to aid with checking defaults.
121   jit_options->warmup_threshold_ =
122       kIsDebugBuild ? (Jit::kSlowMode
123                        ? kJitSlowStressDefaultWarmUpThreshold
124                        : kJitStressDefaultWarmUpThreshold)
125       : kJitDefaultWarmUpThreshold;
126 
127   // Warmup threshold should be less than compile threshold (so long as compile threshold is not
128   // zero == JIT-on-first-use).
129   DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
130   DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
131             jit_options->warmup_threshold_);
132 
133   if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
134     jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
135   }
136   jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
137 
138   if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
139     jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
140   }
141   jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
142 
143   if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
144     jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
145   } else {
146     jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
147     if (jit_options->osr_threshold_ > kJitMaxThreshold) {
148       jit_options->osr_threshold_ =
149           RoundDown(kJitMaxThreshold, kJitThresholdStep);
150     }
151   }
152   jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
153 
154   // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
155   // threshold is 0).
156   if (jit_options->compile_threshold_ != 0) {
157     // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
158     jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
159                                              2u * kJitThresholdStep,
160                                              RoundDown(kJitMaxThreshold, kJitThresholdStep));
161     jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
162                                                  kJitThresholdStep,
163                                                  jit_options->osr_threshold_ - kJitThresholdStep);
164     jit_options->warmup_threshold_ =
165         std::clamp(jit_options->warmup_threshold_,
166                    0u,
167                    jit_options->compile_threshold_ - kJitThresholdStep);
168   }
169 
170   if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
171     jit_options->priority_thread_weight_ =
172         *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
173     if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
174       LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
175     } else if (jit_options->priority_thread_weight_ == 0) {
176       LOG(FATAL) << "Priority thread weight cannot be 0.";
177     }
178   } else {
179     jit_options->priority_thread_weight_ = std::max(
180         jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
181         static_cast<size_t>(1));
182   }
183 
184   if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
185     jit_options->invoke_transition_weight_ =
186         *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
187     if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
188       LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
189     } else if (jit_options->invoke_transition_weight_  == 0) {
190       LOG(FATAL) << "Invoke transition weight cannot be 0.";
191     }
192   } else {
193     jit_options->invoke_transition_weight_ = std::max(
194         jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
195         static_cast<size_t>(1));
196   }
197 
198   return jit_options;
199 }
200 
DumpInfo(std::ostream & os)201 void Jit::DumpInfo(std::ostream& os) {
202   code_cache_->Dump(os);
203   cumulative_timings_.Dump(os);
204   MutexLock mu(Thread::Current(), lock_);
205   memory_use_.PrintMemoryUse(os);
206 }
207 
DumpForSigQuit(std::ostream & os)208 void Jit::DumpForSigQuit(std::ostream& os) {
209   DumpInfo(os);
210   ProfileSaver::DumpInstanceInfo(os);
211 }
212 
AddTimingLogger(const TimingLogger & logger)213 void Jit::AddTimingLogger(const TimingLogger& logger) {
214   cumulative_timings_.AddLogger(logger);
215 }
216 
Jit(JitCodeCache * code_cache,JitOptions * options)217 Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
218     : code_cache_(code_cache),
219       options_(options),
220       boot_completed_lock_("Jit::boot_completed_lock_"),
221       cumulative_timings_("JIT timings"),
222       memory_use_("Memory used for compilation", 16),
223       lock_("JIT memory use lock"),
224       zygote_mapping_methods_(),
225       fd_methods_(-1),
226       fd_methods_size_(0) {}
227 
Create(JitCodeCache * code_cache,JitOptions * options)228 Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
229   if (jit_load_ == nullptr) {
230     LOG(WARNING) << "Not creating JIT: library not loaded";
231     return nullptr;
232   }
233   jit_compiler_ = (jit_load_)();
234   if (jit_compiler_ == nullptr) {
235     LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
236     return nullptr;
237   }
238   std::unique_ptr<Jit> jit(new Jit(code_cache, options));
239 
240   // If the code collector is enabled, check if that still holds:
241   // With 'perf', we want a 1-1 mapping between an address and a method.
242   // We aren't able to keep method pointers live during the instrumentation method entry trampoline
243   // so we will just disable jit-gc if we are doing that.
244   if (code_cache->GetGarbageCollectCode()) {
245     code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
246         !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
247   }
248 
249   VLOG(jit) << "JIT created with initial_capacity="
250       << PrettySize(options->GetCodeCacheInitialCapacity())
251       << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
252       << ", compile_threshold=" << options->GetCompileThreshold()
253       << ", profile_saver_options=" << options->GetProfileSaverOptions();
254 
255   // We want to know whether the compiler is compiling baseline, as this
256   // affects how we GC ProfilingInfos.
257   for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
258     if (option == "--baseline") {
259       options->SetUseBaselineCompiler();
260       break;
261     }
262   }
263 
264   // Notify native debugger about the classes already loaded before the creation of the jit.
265   jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
266   return jit.release();
267 }
268 
269 template <typename T>
LoadSymbol(T * address,const char * name,std::string * error_msg)270 bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
271   *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
272   if (*address == nullptr) {
273     *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
274     return false;
275   }
276   return true;
277 }
278 
LoadCompilerLibrary(std::string * error_msg)279 bool Jit::LoadCompilerLibrary(std::string* error_msg) {
280   jit_library_handle_ = dlopen(
281       kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
282   if (jit_library_handle_ == nullptr) {
283     std::ostringstream oss;
284     oss << "JIT could not load libart-compiler.so: " << dlerror();
285     *error_msg = oss.str();
286     return false;
287   }
288   if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
289     dlclose(jit_library_handle_);
290     return false;
291   }
292   return true;
293 }
294 
CompileMethod(ArtMethod * method,Thread * self,CompilationKind compilation_kind,bool prejit)295 bool Jit::CompileMethod(ArtMethod* method,
296                         Thread* self,
297                         CompilationKind compilation_kind,
298                         bool prejit) {
299   DCHECK(Runtime::Current()->UseJitCompilation());
300   DCHECK(!method->IsRuntimeMethod());
301 
302   RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
303   // Don't compile the method if it has breakpoints.
304   if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
305     VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
306               << " due to not being safe to jit according to runtime-callbacks. For example, there"
307               << " could be breakpoints in this method.";
308     return false;
309   }
310 
311   if (!method->IsCompilable()) {
312     DCHECK(method->GetDeclaringClass()->IsObsoleteObject() ||
313            method->IsProxyMethod()) << method->PrettyMethod();
314     VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to method being made "
315               << "obsolete while waiting for JIT task to run. This probably happened due to "
316               << "concurrent structural class redefinition.";
317     return false;
318   }
319 
320   // Don't compile the method if we are supposed to be deoptimized.
321   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
322   if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
323     VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
324     return false;
325   }
326 
327   JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
328   if ((compilation_kind == CompilationKind::kOsr) && GetCodeCache()->IsSharedRegion(*region)) {
329     VLOG(jit) << "JIT not osr compiling "
330               << method->PrettyMethod()
331               << " due to using shared region";
332     return false;
333   }
334 
335   // If we get a request to compile a proxy method, we pass the actual Java method
336   // of that proxy method, as the compiler does not expect a proxy method.
337   ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
338   if (!code_cache_->NotifyCompilationOf(method_to_compile, self, compilation_kind, prejit)) {
339     return false;
340   }
341 
342   VLOG(jit) << "Compiling method "
343             << ArtMethod::PrettyMethod(method_to_compile)
344             << " kind=" << compilation_kind;
345   bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, compilation_kind);
346   code_cache_->DoneCompiling(method_to_compile, self, compilation_kind);
347   if (!success) {
348     VLOG(jit) << "Failed to compile method "
349               << ArtMethod::PrettyMethod(method_to_compile)
350               << " kind=" << compilation_kind;
351   }
352   if (kIsDebugBuild) {
353     if (self->IsExceptionPending()) {
354       mirror::Throwable* exception = self->GetException();
355       LOG(FATAL) << "No pending exception expected after compiling "
356                  << ArtMethod::PrettyMethod(method)
357                  << ": "
358                  << exception->Dump();
359     }
360   }
361   return success;
362 }
363 
WaitForWorkersToBeCreated()364 void Jit::WaitForWorkersToBeCreated() {
365   if (thread_pool_ != nullptr) {
366     thread_pool_->WaitForWorkersToBeCreated();
367   }
368 }
369 
DeleteThreadPool()370 void Jit::DeleteThreadPool() {
371   Thread* self = Thread::Current();
372   if (thread_pool_ != nullptr) {
373     std::unique_ptr<ThreadPool> pool;
374     {
375       ScopedSuspendAll ssa(__FUNCTION__);
376       // Clear thread_pool_ field while the threads are suspended.
377       // A mutator in the 'AddSamples' method will check against it.
378       pool = std::move(thread_pool_);
379     }
380 
381     // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
382     if (!kRunningOnMemoryTool) {
383       pool->StopWorkers(self);
384       pool->RemoveAllTasks(self);
385     }
386     // We could just suspend all threads, but we know those threads
387     // will finish in a short period, so it's not worth adding a suspend logic
388     // here. Besides, this is only done for shutdown.
389     pool->Wait(self, false, false);
390   }
391 }
392 
StartProfileSaver(const std::string & profile_filename,const std::vector<std::string> & code_paths,const std::string & ref_profile_filename)393 void Jit::StartProfileSaver(const std::string& profile_filename,
394                             const std::vector<std::string>& code_paths,
395                             const std::string& ref_profile_filename) {
396   if (options_->GetSaveProfilingInfo()) {
397     ProfileSaver::Start(options_->GetProfileSaverOptions(),
398                         profile_filename,
399                         code_cache_,
400                         code_paths,
401                         ref_profile_filename);
402   }
403 }
404 
StopProfileSaver()405 void Jit::StopProfileSaver() {
406   if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
407     ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
408   }
409 }
410 
JitAtFirstUse()411 bool Jit::JitAtFirstUse() {
412   return HotMethodThreshold() == 0;
413 }
414 
CanInvokeCompiledCode(ArtMethod * method)415 bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
416   return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
417 }
418 
~Jit()419 Jit::~Jit() {
420   DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
421   if (options_->DumpJitInfoOnShutdown()) {
422     DumpInfo(LOG_STREAM(INFO));
423     Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
424   }
425   DeleteThreadPool();
426   if (jit_compiler_ != nullptr) {
427     delete jit_compiler_;
428     jit_compiler_ = nullptr;
429   }
430   if (jit_library_handle_ != nullptr) {
431     dlclose(jit_library_handle_);
432     jit_library_handle_ = nullptr;
433   }
434 }
435 
NewTypeLoadedIfUsingJit(mirror::Class * type)436 void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
437   if (!Runtime::Current()->UseJitCompilation()) {
438     // No need to notify if we only use the JIT to save profiles.
439     return;
440   }
441   jit::Jit* jit = Runtime::Current()->GetJit();
442   if (jit->jit_compiler_->GenerateDebugInfo()) {
443     jit_compiler_->TypesLoaded(&type, 1);
444   }
445 }
446 
DumpTypeInfoForLoadedTypes(ClassLinker * linker)447 void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
448   struct CollectClasses : public ClassVisitor {
449     bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
450       classes_.push_back(klass.Ptr());
451       return true;
452     }
453     std::vector<mirror::Class*> classes_;
454   };
455 
456   if (jit_compiler_->GenerateDebugInfo()) {
457     ScopedObjectAccess so(Thread::Current());
458 
459     CollectClasses visitor;
460     linker->VisitClasses(&visitor);
461     jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
462   }
463 }
464 
465 extern "C" void art_quick_osr_stub(void** stack,
466                                    size_t stack_size_in_bytes,
467                                    const uint8_t* native_pc,
468                                    JValue* result,
469                                    const char* shorty,
470                                    Thread* self);
471 
PrepareForOsr(ArtMethod * method,uint32_t dex_pc,uint32_t * vregs)472 OsrData* Jit::PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs) {
473   if (!kEnableOnStackReplacement) {
474     return nullptr;
475   }
476 
477   // Cheap check if the method has been compiled already. That's an indicator that we should
478   // osr into it.
479   if (!GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
480     return nullptr;
481   }
482 
483   // Fetch some data before looking up for an OSR method. We don't want thread
484   // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
485   // method while we are being suspended.
486   CodeItemDataAccessor accessor(method->DexInstructionData());
487   const size_t number_of_vregs = accessor.RegistersSize();
488   std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
489   OsrData* osr_data = nullptr;
490 
491   {
492     ScopedAssertNoThreadSuspension sts("Holding OSR method");
493     const OatQuickMethodHeader* osr_method = GetCodeCache()->LookupOsrMethodHeader(method);
494     if (osr_method == nullptr) {
495       // No osr method yet, just return to the interpreter.
496       return nullptr;
497     }
498 
499     CodeInfo code_info(osr_method);
500 
501     // Find stack map starting at the target dex_pc.
502     StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc);
503     if (!stack_map.IsValid()) {
504       // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
505       // hope that the next branch has one.
506       return nullptr;
507     }
508 
509     // We found a stack map, now fill the frame with dex register values from the interpreter's
510     // shadow frame.
511     DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
512     DCHECK_EQ(vreg_map.size(), number_of_vregs);
513 
514     size_t frame_size = osr_method->GetFrameSizeInBytes();
515 
516     // Allocate memory to put shadow frame values. The osr stub will copy that memory to
517     // stack.
518     // Note that we could pass the shadow frame to the stub, and let it copy the values there,
519     // but that is engineering complexity not worth the effort for something like OSR.
520     osr_data = reinterpret_cast<OsrData*>(malloc(sizeof(OsrData) + frame_size));
521     if (osr_data == nullptr) {
522       return nullptr;
523     }
524     memset(osr_data, 0, sizeof(OsrData) + frame_size);
525     osr_data->frame_size = frame_size;
526 
527     // Art ABI: ArtMethod is at the bottom of the stack.
528     osr_data->memory[0] = method;
529 
530     if (vreg_map.empty()) {
531       // If we don't have a dex register map, then there are no live dex registers at
532       // this dex pc.
533     } else {
534       for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
535         DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
536         if (location == DexRegisterLocation::Kind::kNone) {
537           // Dex register is dead or uninitialized.
538           continue;
539         }
540 
541         if (location == DexRegisterLocation::Kind::kConstant) {
542           // We skip constants because the compiled code knows how to handle them.
543           continue;
544         }
545 
546         DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
547 
548         int32_t vreg_value = vregs[vreg];
549         int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
550         DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
551         DCHECK_GT(slot_offset, 0);
552         (reinterpret_cast<int32_t*>(osr_data->memory))[slot_offset / sizeof(int32_t)] = vreg_value;
553       }
554     }
555 
556     osr_data->native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
557         osr_method->GetEntryPoint();
558     VLOG(jit) << "Jumping to "
559               << method_name
560               << "@"
561               << std::hex << reinterpret_cast<uintptr_t>(osr_data->native_pc);
562   }
563   return osr_data;
564 }
565 
MaybeDoOnStackReplacement(Thread * thread,ArtMethod * method,uint32_t dex_pc,int32_t dex_pc_offset,JValue * result)566 bool Jit::MaybeDoOnStackReplacement(Thread* thread,
567                                     ArtMethod* method,
568                                     uint32_t dex_pc,
569                                     int32_t dex_pc_offset,
570                                     JValue* result) {
571   Jit* jit = Runtime::Current()->GetJit();
572   if (jit == nullptr) {
573     return false;
574   }
575 
576   if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
577     // Don't attempt to do an OSR if we are close to the stack limit. Since
578     // the interpreter frames are still on stack, OSR has the potential
579     // to stack overflow even for a simple loop.
580     // b/27094810.
581     return false;
582   }
583 
584   // Get the actual Java method if this method is from a proxy class. The compiler
585   // and the JIT code cache do not expect methods from proxy classes.
586   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
587 
588   // Before allowing the jump, make sure no code is actively inspecting the method to avoid
589   // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
590   // disable OSR when single stepping, but that's currently hard to know at this point.
591   if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
592     return false;
593   }
594 
595   ShadowFrame* shadow_frame = thread->GetManagedStack()->GetTopShadowFrame();
596   OsrData* osr_data = jit->PrepareForOsr(method,
597                                          dex_pc + dex_pc_offset,
598                                          shadow_frame->GetVRegArgs(0));
599 
600   if (osr_data == nullptr) {
601     return false;
602   }
603 
604   {
605     thread->PopShadowFrame();
606     ManagedStack fragment;
607     thread->PushManagedStackFragment(&fragment);
608     (*art_quick_osr_stub)(osr_data->memory,
609                           osr_data->frame_size,
610                           osr_data->native_pc,
611                           result,
612                           method->GetShorty(),
613                           thread);
614 
615     if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
616       thread->DeoptimizeWithDeoptimizationException(result);
617     }
618     thread->PopManagedStackFragment(fragment);
619   }
620   free(osr_data);
621   thread->PushShadowFrame(shadow_frame);
622   VLOG(jit) << "Done running OSR code for " << method->PrettyMethod();
623   return true;
624 }
625 
AddMemoryUsage(ArtMethod * method,size_t bytes)626 void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
627   if (bytes > 4 * MB) {
628     LOG(INFO) << "Compiler allocated "
629               << PrettySize(bytes)
630               << " to compile "
631               << ArtMethod::PrettyMethod(method);
632   }
633   MutexLock mu(Thread::Current(), lock_);
634   memory_use_.AddValue(bytes);
635 }
636 
NotifyZygoteCompilationDone()637 void Jit::NotifyZygoteCompilationDone() {
638   if (fd_methods_ == -1) {
639     return;
640   }
641 
642   size_t offset = 0;
643   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
644     const ImageHeader& header = space->GetImageHeader();
645     const ImageSection& section = header.GetMethodsSection();
646     // Because mremap works at page boundaries, we can only handle methods
647     // within a page range. For methods that falls above or below the range,
648     // the child processes will copy their contents to their private mapping
649     // in `child_mapping_methods`. See `MapBootImageMethods`.
650     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
651     uint8_t* page_end =
652         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
653     if (page_end > page_start) {
654       uint64_t capacity = page_end - page_start;
655       memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
656       offset += capacity;
657     }
658   }
659 
660   // Do an msync to ensure we are not affected by writes still being in caches.
661   if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
662     PLOG(WARNING) << "Failed to sync boot image methods memory";
663     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
664     return;
665   }
666 
667   // We don't need the shared mapping anymore, and we need to drop it in case
668   // the file hasn't been sealed writable.
669   zygote_mapping_methods_ = MemMap::Invalid();
670 
671   // Seal writes now. Zygote and children will map the memory private in order
672   // to write to it.
673   if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
674     PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
675     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
676     return;
677   }
678 
679   std::string error_str;
680   MemMap child_mapping_methods = MemMap::MapFile(
681       fd_methods_size_,
682       PROT_READ | PROT_WRITE,
683       MAP_PRIVATE,
684       fd_methods_,
685       /* start= */ 0,
686       /* low_4gb= */ false,
687       "boot-image-methods",
688       &error_str);
689 
690   if (!child_mapping_methods.IsValid()) {
691     LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
692     code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
693     return;
694   }
695 
696   // Ensure the contents are the same as before: there was a window between
697   // the memcpy and the sealing where other processes could have changed the
698   // contents.
699   // Note this would not be needed if we could have used F_SEAL_FUTURE_WRITE,
700   // see b/143833776.
701   offset = 0;
702   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
703     const ImageHeader& header = space->GetImageHeader();
704     const ImageSection& section = header.GetMethodsSection();
705     // Because mremap works at page boundaries, we can only handle methods
706     // within a page range. For methods that falls above or below the range,
707     // the child processes will copy their contents to their private mapping
708     // in `child_mapping_methods`. See `MapBootImageMethods`.
709     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
710     uint8_t* page_end =
711         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
712     if (page_end > page_start) {
713       uint64_t capacity = page_end - page_start;
714       if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
715         LOG(WARNING) << "Contents differ in boot image methods data";
716         code_cache_->GetZygoteMap()->SetCompilationState(
717             ZygoteCompilationState::kNotifiedFailure);
718         return;
719       }
720       offset += capacity;
721     }
722   }
723 
724   // Future spawned processes don't need the fd anymore.
725   fd_methods_.reset();
726 
727   // In order to have the zygote and children share the memory, we also remap
728   // the memory into the zygote process.
729   offset = 0;
730   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
731     const ImageHeader& header = space->GetImageHeader();
732     const ImageSection& section = header.GetMethodsSection();
733     // Because mremap works at page boundaries, we can only handle methods
734     // within a page range. For methods that falls above or below the range,
735     // the child processes will copy their contents to their private mapping
736     // in `child_mapping_methods`. See `MapBootImageMethods`.
737     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
738     uint8_t* page_end =
739         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
740     if (page_end > page_start) {
741       uint64_t capacity = page_end - page_start;
742       if (mremap(child_mapping_methods.Begin() + offset,
743                  capacity,
744                  capacity,
745                  MREMAP_FIXED | MREMAP_MAYMOVE,
746                  page_start) == MAP_FAILED) {
747         // Failing to remap is safe as the process will just use the old
748         // contents.
749         PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
750       }
751       offset += capacity;
752     }
753   }
754 
755   LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
756 
757   // Mark that compilation of boot classpath is done, and memory can now be
758   // shared. Other processes will pick up this information.
759   code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
760 
761   // The private mapping created for this process has been mremaped. We can
762   // reset it.
763   child_mapping_methods.Reset();
764 }
765 
766 class JitCompileTask final : public Task {
767  public:
768   enum class TaskKind {
769     kCompile,
770     kPreCompile,
771   };
772 
JitCompileTask(ArtMethod * method,TaskKind task_kind,CompilationKind compilation_kind)773   JitCompileTask(ArtMethod* method, TaskKind task_kind, CompilationKind compilation_kind)
774       : method_(method), kind_(task_kind), compilation_kind_(compilation_kind), klass_(nullptr) {
775     ScopedObjectAccess soa(Thread::Current());
776     // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
777     // until compilation is done.
778     // When we precompile, this is either with boot classpath methods, or main
779     // class loader methods, so we don't need to keep a global reference.
780     if (method->GetDeclaringClass()->GetClassLoader() != nullptr &&
781         kind_ != TaskKind::kPreCompile) {
782       klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
783       CHECK(klass_ != nullptr);
784     }
785   }
786 
~JitCompileTask()787   ~JitCompileTask() {
788     if (klass_ != nullptr) {
789       ScopedObjectAccess soa(Thread::Current());
790       soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
791     }
792   }
793 
Run(Thread * self)794   void Run(Thread* self) override {
795     {
796       ScopedObjectAccess soa(self);
797       switch (kind_) {
798         case TaskKind::kCompile:
799         case TaskKind::kPreCompile: {
800           Runtime::Current()->GetJit()->CompileMethod(
801               method_,
802               self,
803               compilation_kind_,
804               /* prejit= */ (kind_ == TaskKind::kPreCompile));
805           break;
806         }
807       }
808     }
809     ProfileSaver::NotifyJitActivity();
810   }
811 
Finalize()812   void Finalize() override {
813     delete this;
814   }
815 
816  private:
817   ArtMethod* const method_;
818   const TaskKind kind_;
819   const CompilationKind compilation_kind_;
820   jobject klass_;
821 
822   DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
823 };
824 
GetProfileFile(const std::string & dex_location)825 static std::string GetProfileFile(const std::string& dex_location) {
826   // Hardcoded assumption where the profile file is.
827   // TODO(ngeoffray): this is brittle and we would need to change change if we
828   // wanted to do more eager JITting of methods in a profile. This is
829   // currently only for system server.
830   return dex_location + ".prof";
831 }
832 
GetBootProfileFile(const std::string & profile)833 static std::string GetBootProfileFile(const std::string& profile) {
834   // The boot profile can be found next to the compilation profile, with a
835   // different extension.
836   return ReplaceFileExtension(profile, "bprof");
837 }
838 
839 /**
840  * A JIT task to run after all profile compilation is done.
841  */
842 class JitDoneCompilingProfileTask final : public SelfDeletingTask {
843  public:
JitDoneCompilingProfileTask(const std::vector<const DexFile * > & dex_files)844   explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
845       : dex_files_(dex_files) {}
846 
Run(Thread * self ATTRIBUTE_UNUSED)847   void Run(Thread* self ATTRIBUTE_UNUSED) override {
848     // Madvise DONTNEED dex files now that we're done compiling methods.
849     for (const DexFile* dex_file : dex_files_) {
850       if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
851         int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
852                              RoundUp(dex_file->Size(), kPageSize),
853                              MADV_DONTNEED);
854         if (result == -1) {
855           PLOG(WARNING) << "Madvise failed";
856         }
857       }
858     }
859 
860     if (Runtime::Current()->IsZygote()) {
861       // Record that we are done compiling the profile.
862       Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
863           ZygoteCompilationState::kDone);
864     }
865   }
866 
867  private:
868   std::vector<const DexFile*> dex_files_;
869 
870   DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
871 };
872 
873 /**
874  * A JIT task to run Java verification of boot classpath classes that were not
875  * verified at compile-time.
876  */
877 class ZygoteVerificationTask final : public Task {
878  public:
ZygoteVerificationTask()879   ZygoteVerificationTask() {}
880 
Run(Thread * self)881   void Run(Thread* self) override {
882     // We are going to load class and run verification, which may also need to load
883     // classes. If the thread cannot load classes (typically when the runtime is
884     // debuggable), then just return.
885     if (!self->CanLoadClasses()) {
886       return;
887     }
888     Runtime* runtime = Runtime::Current();
889     ClassLinker* linker = runtime->GetClassLinker();
890     const std::vector<const DexFile*>& boot_class_path =
891         runtime->GetClassLinker()->GetBootClassPath();
892     ScopedObjectAccess soa(self);
893     StackHandleScope<1> hs(self);
894     MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
895     uint64_t start_ns = ThreadCpuNanoTime();
896     uint64_t number_of_classes = 0;
897     for (const DexFile* dex_file : boot_class_path) {
898       if (dex_file->GetOatDexFile() != nullptr &&
899           dex_file->GetOatDexFile()->GetOatFile() != nullptr) {
900         // If backed by an .oat file, we have already run verification at
901         // compile-time. Note that some classes may still have failed
902         // verification there if they reference updatable mainline module
903         // classes.
904         continue;
905       }
906       for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
907         const dex::ClassDef& class_def = dex_file->GetClassDef(i);
908         const char* descriptor = dex_file->GetClassDescriptor(class_def);
909         ScopedNullHandle<mirror::ClassLoader> null_loader;
910         klass.Assign(linker->FindClass(self, descriptor, null_loader));
911         if (klass == nullptr) {
912           self->ClearException();
913           LOG(WARNING) << "Could not find " << descriptor;
914           continue;
915         }
916         ++number_of_classes;
917         if (linker->VerifyClass(self, /* verifier_deps= */ nullptr, klass) ==
918                 verifier::FailureKind::kHardFailure) {
919           DCHECK(self->IsExceptionPending());
920           LOG(FATAL) << "Methods in the boot classpath failed to verify: "
921                      << self->GetException()->Dump();
922         }
923         CHECK(!self->IsExceptionPending());
924       }
925     }
926     LOG(INFO) << "Verified "
927               << number_of_classes
928               << " classes from mainline modules in "
929               << PrettyDuration(ThreadCpuNanoTime() - start_ns);
930   }
931 };
932 
933 class ZygoteTask final : public Task {
934  public:
ZygoteTask()935   ZygoteTask() {}
936 
Run(Thread * self)937   void Run(Thread* self) override {
938     Runtime* runtime = Runtime::Current();
939     uint32_t added_to_queue = 0;
940     for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
941       const std::string& profile_file = space->GetProfileFile();
942       if (profile_file.empty()) {
943         continue;
944       }
945       LOG(INFO) << "JIT Zygote looking at profile " << profile_file;
946 
947       const std::vector<const DexFile*>& boot_class_path =
948           runtime->GetClassLinker()->GetBootClassPath();
949       ScopedNullHandle<mirror::ClassLoader> null_handle;
950       // We add to the queue for zygote so that we can fork processes in-between
951       // compilations.
952       if (Runtime::Current()->IsPrimaryZygote()) {
953         std::string boot_profile = GetBootProfileFile(profile_file);
954         // We avoid doing compilation at boot for the secondary zygote, as apps
955         // forked from it are not critical for boot.
956         added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
957             self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
958       }
959       added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
960           self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
961     }
962 
963     JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
964     code_cache->GetZygoteMap()->Initialize(added_to_queue);
965   }
966 
Finalize()967   void Finalize() override {
968     delete this;
969   }
970 
971  private:
972   DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
973 };
974 
975 class JitProfileTask final : public Task {
976  public:
JitProfileTask(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)977   JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
978                  jobject class_loader) {
979     ScopedObjectAccess soa(Thread::Current());
980     StackHandleScope<1> hs(soa.Self());
981     Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
982         soa.Decode<mirror::ClassLoader>(class_loader)));
983     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
984     for (const auto& dex_file : dex_files) {
985       dex_files_.push_back(dex_file.get());
986       // Register the dex file so that we can guarantee it doesn't get deleted
987       // while reading it during the task.
988       class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
989     }
990     // We also create our own global ref to use this class loader later.
991     class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
992   }
993 
Run(Thread * self)994   void Run(Thread* self) override {
995     ScopedObjectAccess soa(self);
996     StackHandleScope<1> hs(self);
997     Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
998         soa.Decode<mirror::ClassLoader>(class_loader_));
999 
1000     std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
1001     std::string boot_profile = GetBootProfileFile(profile);
1002 
1003     Jit* jit = Runtime::Current()->GetJit();
1004 
1005     jit->CompileMethodsFromBootProfile(
1006         self,
1007         dex_files_,
1008         boot_profile,
1009         loader,
1010         /* add_to_queue= */ false);
1011 
1012     jit->CompileMethodsFromProfile(
1013         self,
1014         dex_files_,
1015         profile,
1016         loader,
1017         /* add_to_queue= */ true);
1018   }
1019 
Finalize()1020   void Finalize() override {
1021     delete this;
1022   }
1023 
~JitProfileTask()1024   ~JitProfileTask() {
1025     ScopedObjectAccess soa(Thread::Current());
1026     soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
1027   }
1028 
1029  private:
1030   std::vector<const DexFile*> dex_files_;
1031   jobject class_loader_;
1032 
1033   DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
1034 };
1035 
CopyIfDifferent(void * s1,const void * s2,size_t n)1036 static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
1037   if (memcmp(s1, s2, n) != 0) {
1038     memcpy(s1, s2, n);
1039   }
1040 }
1041 
MapBootImageMethods()1042 void Jit::MapBootImageMethods() {
1043   if (Runtime::Current()->IsJavaDebuggable()) {
1044     LOG(INFO) << "Not mapping boot image methods due to process being debuggable";
1045     return;
1046   }
1047   CHECK_NE(fd_methods_.get(), -1);
1048   if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
1049     LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
1050     // We don't need the fd anymore.
1051     fd_methods_.reset();
1052     return;
1053   }
1054 
1055   std::string error_str;
1056   MemMap child_mapping_methods = MemMap::MapFile(
1057       fd_methods_size_,
1058       PROT_READ | PROT_WRITE,
1059       MAP_PRIVATE,
1060       fd_methods_,
1061       /* start= */ 0,
1062       /* low_4gb= */ false,
1063       "boot-image-methods",
1064       &error_str);
1065 
1066   // We don't need the fd anymore.
1067   fd_methods_.reset();
1068 
1069   if (!child_mapping_methods.IsValid()) {
1070     LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
1071     return;
1072   }
1073   //  We are going to mremap the child mapping into the image:
1074   //
1075   //                            ImageSection       ChildMappingMethods
1076   //
1077   //         section start -->  -----------
1078   //                            |         |
1079   //                            |         |
1080   //            page_start -->  |         |   <-----   -----------
1081   //                            |         |            |         |
1082   //                            |         |            |         |
1083   //                            |         |            |         |
1084   //                            |         |            |         |
1085   //                            |         |            |         |
1086   //                            |         |            |         |
1087   //                            |         |            |         |
1088   //             page_end  -->  |         |   <-----   -----------
1089   //                            |         |
1090   //         section end   -->  -----------
1091   //
1092   size_t offset = 0;
1093   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1094     const ImageHeader& header = space->GetImageHeader();
1095     const ImageSection& section = header.GetMethodsSection();
1096     uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1097     uint8_t* page_end =
1098         AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1099     if (page_end <= page_start) {
1100       // Section doesn't contain one aligned entire page.
1101       continue;
1102     }
1103     uint64_t capacity = page_end - page_start;
1104     // Walk over methods in the boot image, and check for:
1105     // 1) methods whose class is not initialized in the process, but are in the
1106     // zygote process. For such methods, we need their entrypoints to be stubs
1107     // that do the initialization check.
1108     // 2) native methods whose data pointer is different than the one in the
1109     // zygote. Such methods may have had custom native implementation provided
1110     // by JNI RegisterNatives.
1111     header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
1112       // Methods in the boot image should never have their single
1113       // implementation flag set (and therefore never have a `data_` pointing
1114       // to an ArtMethod for single implementation).
1115       CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
1116       if (method.IsRuntimeMethod()) {
1117         return;
1118       }
1119 
1120       // Pointer to the method we're currently using.
1121       uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1122       // The data pointer of that method that we want to keep.
1123       uint8_t* data_pointer = pointer + ArtMethod::DataOffset(kRuntimePointerSize).Int32Value();
1124       if (method.IsNative() && data_pointer >= page_start && data_pointer < page_end) {
1125         // The data pointer of the ArtMethod in the shared memory we are going to remap into our
1126         // own mapping. This is the data that we will see after the remap.
1127         uint8_t* new_data_pointer =
1128             child_mapping_methods.Begin() + offset + (data_pointer - page_start);
1129         CopyIfDifferent(new_data_pointer, data_pointer, sizeof(void*));
1130       }
1131 
1132       // The entrypoint of the method we're currently using and that we want to
1133       // keep.
1134       uint8_t* entry_point_pointer = pointer +
1135           ArtMethod::EntryPointFromQuickCompiledCodeOffset(kRuntimePointerSize).Int32Value();
1136       if (!method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() &&
1137           method.IsStatic() &&
1138           !method.IsConstructor() &&
1139           entry_point_pointer >= page_start &&
1140           entry_point_pointer < page_end) {
1141         // The entry point of the ArtMethod in the shared memory we are going to remap into our
1142         // own mapping. This is the entrypoint that we will see after the remap.
1143         uint8_t* new_entry_point_pointer =
1144             child_mapping_methods.Begin() + offset + (entry_point_pointer - page_start);
1145         CopyIfDifferent(new_entry_point_pointer, entry_point_pointer, sizeof(void*));
1146       }
1147     }, space->Begin(), kRuntimePointerSize);
1148 
1149     // Map the memory in the boot image range.
1150     if (mremap(child_mapping_methods.Begin() + offset,
1151                capacity,
1152                capacity,
1153                MREMAP_FIXED | MREMAP_MAYMOVE,
1154                page_start) == MAP_FAILED) {
1155       PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1156     }
1157     offset += capacity;
1158   }
1159 
1160   // The private mapping created for this process has been mremaped. We can
1161   // reset it.
1162   child_mapping_methods.Reset();
1163   LOG(INFO) << "Successfully mapped boot image methods";
1164 }
1165 
1166 // Return whether a boot image has a profile. This means we'll need to pre-JIT
1167 // methods in that profile for performance.
HasImageWithProfile()1168 static bool HasImageWithProfile() {
1169   for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1170     if (!space->GetProfileFile().empty()) {
1171       return true;
1172     }
1173   }
1174   return false;
1175 }
1176 
InZygoteUsingJit()1177 bool Jit::InZygoteUsingJit() {
1178   Runtime* runtime = Runtime::Current();
1179   return runtime->IsZygote() && HasImageWithProfile() && runtime->UseJitCompilation();
1180 }
1181 
CreateThreadPool()1182 void Jit::CreateThreadPool() {
1183   // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1184   // is not null when we instrument.
1185 
1186   // We need peers as we may report the JIT thread, e.g., in the debugger.
1187   constexpr bool kJitPoolNeedsPeers = true;
1188   thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1189 
1190   Runtime* runtime = Runtime::Current();
1191   thread_pool_->SetPthreadPriority(
1192       runtime->IsZygote()
1193           ? options_->GetZygoteThreadPoolPthreadPriority()
1194           : options_->GetThreadPoolPthreadPriority());
1195   Start();
1196 
1197   if (runtime->IsZygote()) {
1198     // To speed up class lookups, generate a type lookup table for
1199     // dex files not backed by oat file.
1200     for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
1201       if (dex_file->GetOatDexFile() == nullptr) {
1202         TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1203         type_lookup_tables_.push_back(
1204             std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1205         dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1206       }
1207     }
1208 
1209     // Add a task that will verify boot classpath jars that were not
1210     // pre-compiled.
1211     thread_pool_->AddTask(Thread::Current(), new ZygoteVerificationTask());
1212   }
1213 
1214   if (InZygoteUsingJit()) {
1215     // If we have an image with a profile, request a JIT task to
1216     // compile all methods in that profile.
1217     thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
1218 
1219     // And create mappings to share boot image methods memory from the zygote to
1220     // child processes.
1221 
1222     // Compute the total capacity required for the boot image methods.
1223     uint64_t total_capacity = 0;
1224     for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1225       const ImageHeader& header = space->GetImageHeader();
1226       const ImageSection& section = header.GetMethodsSection();
1227       // Mappings need to be at the page level.
1228       uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1229       uint8_t* page_end =
1230           AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1231       if (page_end > page_start) {
1232         total_capacity += (page_end - page_start);
1233       }
1234     }
1235 
1236     // Create the child and zygote mappings to the boot image methods.
1237     if (total_capacity > 0) {
1238       // Start with '/boot' and end with '.art' to match the pattern recognized
1239       // by android_os_Debug.cpp for boot images.
1240       const char* name = "/boot-image-methods.art";
1241       unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
1242       if (mem_fd.get() == -1) {
1243         PLOG(WARNING) << "Could not create boot image methods file descriptor";
1244         return;
1245       }
1246       if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1247         PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1248         return;
1249       }
1250       std::string error_str;
1251 
1252       // Create the shared mapping eagerly, as this prevents other processes
1253       // from adding the writable seal.
1254       zygote_mapping_methods_ = MemMap::MapFile(
1255         total_capacity,
1256         PROT_READ | PROT_WRITE,
1257         MAP_SHARED,
1258         mem_fd,
1259         /* start= */ 0,
1260         /* low_4gb= */ false,
1261         "boot-image-methods",
1262         &error_str);
1263 
1264       if (!zygote_mapping_methods_.IsValid()) {
1265         LOG(WARNING) << "Failed to create zygote mapping of boot image methods:  " << error_str;
1266         return;
1267       }
1268       if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1269         LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1270         zygote_mapping_methods_ = MemMap();
1271         return;
1272       }
1273 
1274       // We should use the F_SEAL_FUTURE_WRITE flag, but this has unexpected
1275       // behavior on private mappings after fork (the mapping becomes shared between
1276       // parent and children), see b/143833776.
1277       // We will seal the write once we are done writing to the shared mapping.
1278       if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1279         PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1280         zygote_mapping_methods_ = MemMap();
1281         return;
1282       }
1283       fd_methods_ = unique_fd(mem_fd.release());
1284       fd_methods_size_ = total_capacity;
1285     }
1286   }
1287 }
1288 
RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)1289 void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
1290                            jobject class_loader) {
1291   if (dex_files.empty()) {
1292     return;
1293   }
1294   Runtime* runtime = Runtime::Current();
1295   // If the runtime is debuggable, no need to precompile methods.
1296   if (runtime->IsSystemServer() &&
1297       UseJitCompilation() &&
1298       options_->UseProfiledJitCompilation() &&
1299       HasImageWithProfile() &&
1300       !runtime->IsJavaDebuggable()) {
1301     thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1302   }
1303 }
1304 
CompileMethodFromProfile(Thread * self,ClassLinker * class_linker,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool add_to_queue,bool compile_after_boot)1305 bool Jit::CompileMethodFromProfile(Thread* self,
1306                                    ClassLinker* class_linker,
1307                                    uint32_t method_idx,
1308                                    Handle<mirror::DexCache> dex_cache,
1309                                    Handle<mirror::ClassLoader> class_loader,
1310                                    bool add_to_queue,
1311                                    bool compile_after_boot) {
1312   ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1313       method_idx, dex_cache, class_loader);
1314   if (method == nullptr) {
1315     self->ClearException();
1316     return false;
1317   }
1318   if (!method->IsCompilable() || !method->IsInvokable()) {
1319     return false;
1320   }
1321   if (method->IsPreCompiled()) {
1322     // Already seen by another profile.
1323     return false;
1324   }
1325   const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1326   if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1327       class_linker->IsQuickGenericJniStub(entry_point) ||
1328       (entry_point == interpreter::GetNterpEntryPoint()) ||
1329       // We explicitly check for the stub. The trampoline is for methods backed by
1330       // a .oat file that has a compiled version of the method.
1331       (entry_point == GetQuickResolutionStub())) {
1332     method->SetPreCompiled();
1333     if (!add_to_queue) {
1334       CompileMethod(method, self, CompilationKind::kOptimized, /* prejit= */ true);
1335     } else {
1336       Task* task = new JitCompileTask(
1337           method, JitCompileTask::TaskKind::kPreCompile, CompilationKind::kOptimized);
1338       if (compile_after_boot) {
1339         MutexLock mu(Thread::Current(), boot_completed_lock_);
1340         if (!boot_completed_) {
1341           tasks_after_boot_.push_back(task);
1342           return true;
1343         }
1344         DCHECK(tasks_after_boot_.empty());
1345       }
1346       thread_pool_->AddTask(self, task);
1347       return true;
1348     }
1349   }
1350   return false;
1351 }
1352 
CompileMethodsFromBootProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1353 uint32_t Jit::CompileMethodsFromBootProfile(
1354     Thread* self,
1355     const std::vector<const DexFile*>& dex_files,
1356     const std::string& profile_file,
1357     Handle<mirror::ClassLoader> class_loader,
1358     bool add_to_queue) {
1359   unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1360 
1361   if (profile.Fd() == -1) {
1362     PLOG(WARNING) << "No boot profile: " << profile_file;
1363     return 0u;
1364   }
1365 
1366   ProfileBootInfo profile_info;
1367   if (!profile_info.Load(profile.Fd(), dex_files)) {
1368     LOG(ERROR) << "Could not load profile file: " << profile_file;
1369     return 0u;
1370   }
1371 
1372   ScopedObjectAccess soa(self);
1373   VariableSizedHandleScope handles(self);
1374   std::vector<Handle<mirror::DexCache>> dex_caches;
1375   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1376   for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1377     dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1378   }
1379 
1380   uint32_t added_to_queue = 0;
1381   for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1382     if (CompileMethodFromProfile(self,
1383                                  class_linker,
1384                                  pair.second,
1385                                  dex_caches[pair.first],
1386                                  class_loader,
1387                                  add_to_queue,
1388                                  /*compile_after_boot=*/false)) {
1389       ++added_to_queue;
1390     }
1391   }
1392   return added_to_queue;
1393 }
1394 
CompileMethodsFromProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1395 uint32_t Jit::CompileMethodsFromProfile(
1396     Thread* self,
1397     const std::vector<const DexFile*>& dex_files,
1398     const std::string& profile_file,
1399     Handle<mirror::ClassLoader> class_loader,
1400     bool add_to_queue) {
1401 
1402   if (profile_file.empty()) {
1403     LOG(WARNING) << "Expected a profile file in JIT zygote mode";
1404     return 0u;
1405   }
1406 
1407   // We don't generate boot profiles on device, therefore we don't
1408   // need to lock the file.
1409   unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1410 
1411   if (profile.Fd() == -1) {
1412     PLOG(WARNING) << "No profile: " << profile_file;
1413     return 0u;
1414   }
1415 
1416   ProfileCompilationInfo profile_info;
1417   if (!profile_info.Load(profile.Fd())) {
1418     LOG(ERROR) << "Could not load profile file";
1419     return 0u;
1420   }
1421   ScopedObjectAccess soa(self);
1422   StackHandleScope<1> hs(self);
1423   MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
1424   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1425   uint32_t added_to_queue = 0u;
1426   for (const DexFile* dex_file : dex_files) {
1427     if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1428       // The ART module jars are already preopted.
1429       continue;
1430     }
1431 
1432     std::set<dex::TypeIndex> class_types;
1433     std::set<uint16_t> all_methods;
1434     if (!profile_info.GetClassesAndMethods(*dex_file,
1435                                            &class_types,
1436                                            &all_methods,
1437                                            &all_methods,
1438                                            &all_methods)) {
1439       // This means the profile file did not reference the dex file, which is the case
1440       // if there's no classes and methods of that dex file in the profile.
1441       continue;
1442     }
1443     dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1444     CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
1445 
1446     for (uint16_t method_idx : all_methods) {
1447       if (CompileMethodFromProfile(self,
1448                                    class_linker,
1449                                    method_idx,
1450                                    dex_cache,
1451                                    class_loader,
1452                                    add_to_queue,
1453                                    /*compile_after_boot=*/true)) {
1454         ++added_to_queue;
1455       }
1456     }
1457   }
1458 
1459   // Add a task to run when all compilation is done.
1460   JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
1461   MutexLock mu(Thread::Current(), boot_completed_lock_);
1462   if (!boot_completed_) {
1463     tasks_after_boot_.push_back(task);
1464   } else {
1465     DCHECK(tasks_after_boot_.empty());
1466     thread_pool_->AddTask(self, task);
1467   }
1468   return added_to_queue;
1469 }
1470 
IgnoreSamplesForMethod(ArtMethod * method)1471 bool Jit::IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1472   if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
1473     // We do not want to compile such methods.
1474     return true;
1475   }
1476   if (method->IsNative()) {
1477     ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1478     if (klass == GetClassRoot<mirror::MethodHandle>() ||
1479         klass == GetClassRoot<mirror::VarHandle>()) {
1480       // MethodHandle and VarHandle invocation methods are required to throw an
1481       // UnsupportedOperationException if invoked reflectively. We achieve this by having native
1482       // implementations that raise the exception. We need to disable JIT compilation of these JNI
1483       // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1484       // stubs. Since these stubs have different stack representations we can then crash in stack
1485       // walking (b/78151261).
1486       return true;
1487     }
1488   }
1489   return false;
1490 }
1491 
MaybeCompileMethod(Thread * self,ArtMethod * method,uint32_t old_count,uint32_t new_count,bool with_backedges)1492 bool Jit::MaybeCompileMethod(Thread* self,
1493                              ArtMethod* method,
1494                              uint32_t old_count,
1495                              uint32_t new_count,
1496                              bool with_backedges) {
1497   if (thread_pool_ == nullptr) {
1498     return false;
1499   }
1500   if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
1501     if (!NeedsClinitCheckBeforeCall(method) ||
1502         method->GetDeclaringClass()->IsVisiblyInitialized()) {
1503       const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1504       if (entry_point != nullptr) {
1505         Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1506         return true;
1507       }
1508     }
1509   }
1510 
1511   if (IgnoreSamplesForMethod(method)) {
1512     return false;
1513   }
1514   if (HotMethodThreshold() == 0) {
1515     // Tests might request JIT on first use (compiled synchronously in the interpreter).
1516     return false;
1517   }
1518   DCHECK_GT(WarmMethodThreshold(), 0);
1519   DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1520   DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1521   DCHECK_GE(PriorityThreadWeight(), 1);
1522   DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
1523 
1524   if (UseJitCompilation()) {
1525     if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1526       if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1527         DCHECK(thread_pool_ != nullptr);
1528         thread_pool_->AddTask(
1529             self,
1530             new JitCompileTask(
1531                 method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
1532       }
1533     }
1534     if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
1535       if (!with_backedges) {
1536         return false;
1537       }
1538       DCHECK(!method->IsNative());  // No back edges reported for native methods.
1539       if (!code_cache_->IsOsrCompiled(method)) {
1540         DCHECK(thread_pool_ != nullptr);
1541         thread_pool_->AddTask(
1542             self,
1543             new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1544       }
1545     }
1546   }
1547   return true;
1548 }
1549 
EnqueueOptimizedCompilation(ArtMethod * method,Thread * self)1550 void Jit::EnqueueOptimizedCompilation(ArtMethod* method, Thread* self) {
1551   if (thread_pool_ == nullptr) {
1552     return;
1553   }
1554   // We arrive here after a baseline compiled code has reached its baseline
1555   // hotness threshold. If we're not only using the baseline compiler, enqueue a compilation
1556   // task that will compile optimize the method.
1557   if (!options_->UseBaselineCompiler()) {
1558     thread_pool_->AddTask(
1559         self,
1560         new JitCompileTask(method,
1561                            JitCompileTask::TaskKind::kCompile,
1562                            CompilationKind::kOptimized));
1563   }
1564 }
1565 
1566 class ScopedSetRuntimeThread {
1567  public:
ScopedSetRuntimeThread(Thread * self)1568   explicit ScopedSetRuntimeThread(Thread* self)
1569       : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1570     self_->SetIsRuntimeThread(true);
1571   }
1572 
~ScopedSetRuntimeThread()1573   ~ScopedSetRuntimeThread() {
1574     self_->SetIsRuntimeThread(was_runtime_thread_);
1575   }
1576 
1577  private:
1578   Thread* self_;
1579   bool was_runtime_thread_;
1580 };
1581 
MethodEntered(Thread * thread,ArtMethod * method)1582 void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
1583   Runtime* runtime = Runtime::Current();
1584   if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
1585     ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
1586     if (np_method->IsCompilable()) {
1587       // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1588       // conflicts with jitzygote optimizations.
1589       JitCompileTask compile_task(
1590           method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOptimized);
1591       // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1592       ScopedSetRuntimeThread ssrt(thread);
1593       compile_task.Run(thread);
1594     }
1595     return;
1596   }
1597 
1598   AddSamples(thread, method, 1, /* with_backedges= */false);
1599 }
1600 
WaitForCompilationToFinish(Thread * self)1601 void Jit::WaitForCompilationToFinish(Thread* self) {
1602   if (thread_pool_ != nullptr) {
1603     thread_pool_->Wait(self, false, false);
1604   }
1605 }
1606 
Stop()1607 void Jit::Stop() {
1608   Thread* self = Thread::Current();
1609   // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1610   WaitForCompilationToFinish(self);
1611   GetThreadPool()->StopWorkers(self);
1612   WaitForCompilationToFinish(self);
1613 }
1614 
Start()1615 void Jit::Start() {
1616   GetThreadPool()->StartWorkers(Thread::Current());
1617 }
1618 
ScopedJitSuspend()1619 ScopedJitSuspend::ScopedJitSuspend() {
1620   jit::Jit* jit = Runtime::Current()->GetJit();
1621   was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1622   if (was_on_) {
1623     jit->Stop();
1624   }
1625 }
1626 
~ScopedJitSuspend()1627 ScopedJitSuspend::~ScopedJitSuspend() {
1628   if (was_on_) {
1629     DCHECK(Runtime::Current()->GetJit() != nullptr);
1630     DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
1631     Runtime::Current()->GetJit()->Start();
1632   }
1633 }
1634 
RunPollingThread(void * arg)1635 static void* RunPollingThread(void* arg) {
1636   Jit* jit = reinterpret_cast<Jit*>(arg);
1637   do {
1638     sleep(10);
1639   } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
1640 
1641   // We will suspend other threads: we can only do that if we're attached to the
1642   // runtime.
1643   Runtime* runtime = Runtime::Current();
1644   bool thread_attached = runtime->AttachCurrentThread(
1645       "BootImagePollingThread",
1646       /* as_daemon= */ true,
1647       /* thread_group= */ nullptr,
1648       /* create_peer= */ false);
1649   CHECK(thread_attached);
1650 
1651   {
1652     // Prevent other threads from running while we are remapping the boot image
1653     // ArtMethod's. Native threads might still be running, but they cannot
1654     // change the contents of ArtMethod's.
1655     ScopedSuspendAll ssa(__FUNCTION__);
1656     runtime->GetJit()->MapBootImageMethods();
1657   }
1658 
1659   Runtime::Current()->DetachCurrentThread();
1660   return nullptr;
1661 }
1662 
PostForkChildAction(bool is_system_server,bool is_zygote)1663 void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
1664   // Clear the potential boot tasks inherited from the zygote.
1665   {
1666     MutexLock mu(Thread::Current(), boot_completed_lock_);
1667     tasks_after_boot_.clear();
1668   }
1669 
1670   Runtime* const runtime = Runtime::Current();
1671   // Check if we'll need to remap the boot image methods.
1672   if (!is_zygote && fd_methods_ != -1) {
1673     // Create a thread that will poll the status of zygote compilation, and map
1674     // the private mapping of boot image methods.
1675     // For child zygote, we instead query IsCompilationNotified() post zygote fork.
1676     zygote_mapping_methods_.ResetInForkedProcess();
1677     pthread_t polling_thread;
1678     pthread_attr_t attr;
1679     CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1680     CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1681                        "PTHREAD_CREATE_DETACHED");
1682     CHECK_PTHREAD_CALL(
1683         pthread_create,
1684         (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1685         "Methods maps thread");
1686   }
1687 
1688   if (is_zygote || runtime->IsSafeMode()) {
1689     // Delete the thread pool, we are not going to JIT.
1690     thread_pool_.reset(nullptr);
1691     return;
1692   }
1693   // At this point, the compiler options have been adjusted to the particular configuration
1694   // of the forked child. Parse them again.
1695   jit_compiler_->ParseCompilerOptions();
1696 
1697   // Adjust the status of code cache collection: the status from zygote was to not collect.
1698   code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
1699       !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
1700 
1701   if (is_system_server && HasImageWithProfile()) {
1702     // Disable garbage collection: we don't want it to delete methods we're compiling
1703     // through boot and system server profiles.
1704     // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1705     code_cache_->SetGarbageCollectCode(false);
1706   }
1707 
1708   // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1709   // applies to a child.
1710   NativeDebugInfoPostFork();
1711 }
1712 
PreZygoteFork()1713 void Jit::PreZygoteFork() {
1714   if (thread_pool_ == nullptr) {
1715     return;
1716   }
1717   thread_pool_->DeleteThreads();
1718 
1719   NativeDebugInfoPreFork();
1720 }
1721 
PostZygoteFork()1722 void Jit::PostZygoteFork() {
1723   Runtime* runtime = Runtime::Current();
1724   if (thread_pool_ == nullptr) {
1725     // If this is a child zygote, check if we need to remap the boot image
1726     // methods.
1727     if (runtime->IsZygote() &&
1728         fd_methods_ != -1 &&
1729         code_cache_->GetZygoteMap()->IsCompilationNotified()) {
1730       ScopedSuspendAll ssa(__FUNCTION__);
1731       MapBootImageMethods();
1732     }
1733     return;
1734   }
1735   if (runtime->IsZygote() && code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1736     // Copy the boot image methods data to the mappings we created to share
1737     // with the children. We do this here as we are the only thread running and
1738     // we don't risk other threads concurrently updating the ArtMethod's.
1739     CHECK_EQ(GetTaskCount(), 1);
1740     NotifyZygoteCompilationDone();
1741     CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1742   }
1743   thread_pool_->CreateThreads();
1744   thread_pool_->SetPthreadPriority(
1745       runtime->IsZygote()
1746           ? options_->GetZygoteThreadPoolPthreadPriority()
1747           : options_->GetThreadPoolPthreadPriority());
1748 }
1749 
BootCompleted()1750 void Jit::BootCompleted() {
1751   Thread* self = Thread::Current();
1752   std::deque<Task*> tasks;
1753   {
1754     MutexLock mu(self, boot_completed_lock_);
1755     tasks = std::move(tasks_after_boot_);
1756     boot_completed_ = true;
1757   }
1758   for (Task* task : tasks) {
1759     thread_pool_->AddTask(self, task);
1760   }
1761 }
1762 
CanEncodeMethod(ArtMethod * method,bool is_for_shared_region) const1763 bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1764   return !is_for_shared_region ||
1765       Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
1766 }
1767 
CanEncodeClass(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1768 bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1769   return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
1770 }
1771 
CanEncodeString(ObjPtr<mirror::String> string,bool is_for_shared_region) const1772 bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
1773   return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
1774 }
1775 
CanAssumeInitialized(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1776 bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1777   if (!is_for_shared_region) {
1778     return cls->IsInitialized();
1779   } else {
1780     // Look up the class status in the oat file.
1781     const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1782     const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1783     // In case we run without an image there won't be a backing oat file.
1784     if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1785       return false;
1786     }
1787     uint16_t class_def_index = cls->GetDexClassDefIndex();
1788     return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1789   }
1790 }
1791 
EnqueueCompilationFromNterp(ArtMethod * method,Thread * self)1792 void Jit::EnqueueCompilationFromNterp(ArtMethod* method, Thread* self) {
1793   if (thread_pool_ == nullptr) {
1794     return;
1795   }
1796   if (GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1797     // If we already have compiled code for it, nterp may be stuck in a loop.
1798     // Compile OSR.
1799     thread_pool_->AddTask(
1800         self,
1801         new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1802     return;
1803   }
1804   if (GetCodeCache()->CanAllocateProfilingInfo()) {
1805     thread_pool_->AddTask(
1806         self,
1807         new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
1808   } else {
1809     thread_pool_->AddTask(
1810         self,
1811         new JitCompileTask(method,
1812                            JitCompileTask::TaskKind::kCompile,
1813                            CompilationKind::kOptimized));
1814   }
1815 }
1816 
1817 }  // namespace jit
1818 }  // namespace art
1819