1 /*
2 * Copyright (C) 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 "quick_exception_handler.h"
18
19 #include <ios>
20 #include <queue>
21 #include <sstream>
22
23 #include "arch/context.h"
24 #include "art_method-inl.h"
25 #include "base/array_ref.h"
26 #include "base/enums.h"
27 #include "base/globals.h"
28 #include "base/logging.h" // For VLOG_IS_ON.
29 #include "base/systrace.h"
30 #include "dex/dex_file_types.h"
31 #include "dex/dex_instruction.h"
32 #include "entrypoints/entrypoint_utils.h"
33 #include "entrypoints/quick/quick_entrypoints_enum.h"
34 #include "entrypoints/runtime_asm_entrypoints.h"
35 #include "handle_scope-inl.h"
36 #include "interpreter/shadow_frame-inl.h"
37 #include "jit/jit.h"
38 #include "jit/jit_code_cache.h"
39 #include "mirror/class-inl.h"
40 #include "mirror/class_loader.h"
41 #include "mirror/throwable.h"
42 #include "nterp_helpers.h"
43 #include "oat_quick_method_header.h"
44 #include "stack.h"
45 #include "stack_map.h"
46
47 namespace art {
48
49 static constexpr bool kDebugExceptionDelivery = false;
50 static constexpr size_t kInvalidFrameDepth = 0xffffffff;
51
QuickExceptionHandler(Thread * self,bool is_deoptimization)52 QuickExceptionHandler::QuickExceptionHandler(Thread* self, bool is_deoptimization)
53 : self_(self),
54 context_(self->GetLongJumpContext()),
55 is_deoptimization_(is_deoptimization),
56 handler_quick_frame_(nullptr),
57 handler_quick_frame_pc_(0),
58 handler_method_header_(nullptr),
59 handler_quick_arg0_(0),
60 clear_exception_(false),
61 handler_frame_depth_(kInvalidFrameDepth),
62 full_fragment_done_(false) {}
63
64 // Finds catch handler.
65 class CatchBlockStackVisitor final : public StackVisitor {
66 public:
CatchBlockStackVisitor(Thread * self,Context * context,Handle<mirror::Throwable> * exception,QuickExceptionHandler * exception_handler,uint32_t skip_frames,bool skip_top_unwind_callback)67 CatchBlockStackVisitor(Thread* self,
68 Context* context,
69 Handle<mirror::Throwable>* exception,
70 QuickExceptionHandler* exception_handler,
71 uint32_t skip_frames,
72 bool skip_top_unwind_callback)
73 REQUIRES_SHARED(Locks::mutator_lock_)
74 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
75 exception_(exception),
76 exception_handler_(exception_handler),
77 skip_frames_(skip_frames),
78 skip_unwind_callback_(skip_top_unwind_callback) {
79 DCHECK_IMPLIES(skip_unwind_callback_, skip_frames_ == 0);
80 }
81
VisitFrame()82 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
83 ArtMethod* method = GetMethod();
84 exception_handler_->SetHandlerFrameDepth(GetFrameDepth());
85 if (method == nullptr) {
86 DCHECK_EQ(skip_frames_, 0u)
87 << "We tried to skip an upcall! We should have returned to the upcall to finish delivery";
88 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
89 exception_handler_->SetHandlerQuickFramePc(GetCurrentQuickFramePc());
90 exception_handler_->SetHandlerQuickFrame(GetCurrentQuickFrame());
91 return false; // End stack walk.
92 }
93 if (skip_frames_ != 0) {
94 skip_frames_--;
95 return true;
96 }
97 if (method->IsRuntimeMethod()) {
98 // Ignore callee save method.
99 DCHECK(method->IsCalleeSaveMethod());
100 return true;
101 }
102 bool continue_stack_walk = HandleTryItems(method);
103 // Collect methods for which MethodUnwind callback needs to be invoked. MethodUnwind callback
104 // can potentially throw, so we want to call these after we find the catch block.
105 // We stop the stack walk when we find the catch block. If we are ending the stack walk we don't
106 // have to unwind this method so don't record it.
107 if (continue_stack_walk && !skip_unwind_callback_) {
108 // Skip unwind callback is only used when method exit callback has thrown an exception. In
109 // that case, we should have runtime method (artMethodExitHook) on top of stack and the
110 // second should be the method for which method exit was called.
111 DCHECK_IMPLIES(skip_unwind_callback_, GetFrameDepth() == 2);
112 unwound_methods_.push(method);
113 }
114 skip_unwind_callback_ = false;
115 return continue_stack_walk;
116 }
117
GetUnwoundMethods()118 std::queue<ArtMethod*>& GetUnwoundMethods() {
119 return unwound_methods_;
120 }
121
122 private:
HandleTryItems(ArtMethod * method)123 bool HandleTryItems(ArtMethod* method)
124 REQUIRES_SHARED(Locks::mutator_lock_) {
125 uint32_t dex_pc = dex::kDexNoIndex;
126 if (!method->IsNative()) {
127 dex_pc = GetDexPc();
128 }
129 if (dex_pc != dex::kDexNoIndex) {
130 bool clear_exception = false;
131 StackHandleScope<1> hs(GetThread());
132 Handle<mirror::Class> to_find(hs.NewHandle((*exception_)->GetClass()));
133 uint32_t found_dex_pc = method->FindCatchBlock(to_find, dex_pc, &clear_exception);
134 exception_handler_->SetClearException(clear_exception);
135 if (found_dex_pc != dex::kDexNoIndex) {
136 exception_handler_->SetHandlerDexPcList(ComputeDexPcList(found_dex_pc));
137 uint32_t stack_map_row = -1;
138 exception_handler_->SetHandlerQuickFramePc(
139 GetCurrentOatQuickMethodHeader()->ToNativeQuickPcForCatchHandlers(
140 method, exception_handler_->GetHandlerDexPcList(), &stack_map_row));
141 exception_handler_->SetCatchStackMapRow(stack_map_row);
142 exception_handler_->SetHandlerQuickFrame(GetCurrentQuickFrame());
143 exception_handler_->SetHandlerMethodHeader(GetCurrentOatQuickMethodHeader());
144 return false; // End stack walk.
145 } else if (UNLIKELY(GetThread()->HasDebuggerShadowFrames())) {
146 // We are going to unwind this frame. Did we prepare a shadow frame for debugging?
147 size_t frame_id = GetFrameId();
148 ShadowFrame* frame = GetThread()->FindDebuggerShadowFrame(frame_id);
149 if (frame != nullptr) {
150 // We will not execute this shadow frame so we can safely deallocate it.
151 GetThread()->RemoveDebuggerShadowFrameMapping(frame_id);
152 ShadowFrame::DeleteDeoptimizedFrame(frame);
153 }
154 }
155 }
156 return true; // Continue stack walk.
157 }
158
159 // The exception we're looking for the catch block of.
160 Handle<mirror::Throwable>* exception_;
161 // The quick exception handler we're visiting for.
162 QuickExceptionHandler* const exception_handler_;
163 // The number of frames to skip searching for catches in.
164 uint32_t skip_frames_;
165 // The list of methods we would skip to reach the catch block. We record these to call
166 // MethodUnwind callbacks.
167 std::queue<ArtMethod*> unwound_methods_;
168 // Specifies if the unwind callback should be ignored for method at the top of the stack.
169 bool skip_unwind_callback_;
170
171 DISALLOW_COPY_AND_ASSIGN(CatchBlockStackVisitor);
172 };
173
174 // Finds the appropriate exception catch after calling all method exit instrumentation functions.
175 // Note that this might change the exception being thrown. If is_method_exit_exception is true
176 // skip the method unwind call for the method on top of the stack as the exception was thrown by
177 // method exit callback.
FindCatch(ObjPtr<mirror::Throwable> exception,bool is_method_exit_exception)178 void QuickExceptionHandler::FindCatch(ObjPtr<mirror::Throwable> exception,
179 bool is_method_exit_exception) {
180 DCHECK(!is_deoptimization_);
181 instrumentation::Instrumentation* instr = Runtime::Current()->GetInstrumentation();
182 // The number of total frames we have so far popped.
183 uint32_t already_popped = 0;
184 bool popped_to_top = true;
185 StackHandleScope<1> hs(self_);
186 MutableHandle<mirror::Throwable> exception_ref(hs.NewHandle(exception));
187 bool skip_top_unwind_callback = is_method_exit_exception;
188 // Sending the instrumentation events (done by the InstrumentationStackPopper) can cause new
189 // exceptions to be thrown which will override the current exception. Therefore we need to perform
190 // the search for a catch in a loop until we have successfully popped all the way to a catch or
191 // the top of the stack.
192 do {
193 if (kDebugExceptionDelivery) {
194 ObjPtr<mirror::String> msg = exception_ref->GetDetailMessage();
195 std::string str_msg(msg != nullptr ? msg->ToModifiedUtf8() : "");
196 self_->DumpStack(LOG_STREAM(INFO) << "Delivering exception: " << exception_ref->PrettyTypeOf()
197 << ": " << str_msg << "\n");
198 }
199
200 // Walk the stack to find catch handler.
201 CatchBlockStackVisitor visitor(self_,
202 context_,
203 &exception_ref,
204 this,
205 /*skip_frames=*/already_popped,
206 skip_top_unwind_callback);
207 visitor.WalkStack(true);
208 skip_top_unwind_callback = false;
209
210 uint32_t new_pop_count = handler_frame_depth_;
211 DCHECK_GE(new_pop_count, already_popped);
212 already_popped = new_pop_count;
213
214 if (kDebugExceptionDelivery) {
215 if (*handler_quick_frame_ == nullptr) {
216 LOG(INFO) << "Handler is upcall";
217 }
218 if (GetHandlerMethod() != nullptr) {
219 const DexFile* dex_file = GetHandlerMethod()->GetDexFile();
220 DCHECK(handler_dex_pc_list_.has_value());
221 DCHECK_GE(handler_dex_pc_list_->size(), 1u);
222 int line_number = annotations::GetLineNumFromPC(
223 dex_file, GetHandlerMethod(), handler_dex_pc_list_->front());
224
225 // We may have an inlined method. If so, we can add some extra logging.
226 std::stringstream ss;
227 ArtMethod* maybe_inlined_method = visitor.GetMethod();
228 if (maybe_inlined_method != GetHandlerMethod()) {
229 const DexFile* inlined_dex_file = maybe_inlined_method->GetDexFile();
230 DCHECK_GE(handler_dex_pc_list_->size(), 2u);
231 int inlined_line_number = annotations::GetLineNumFromPC(
232 inlined_dex_file, maybe_inlined_method, handler_dex_pc_list_->back());
233 ss << " which ends up calling inlined method " << maybe_inlined_method->PrettyMethod()
234 << " (line: " << inlined_line_number << ")";
235 }
236
237 LOG(INFO) << "Handler: " << GetHandlerMethod()->PrettyMethod() << " (line: "
238 << line_number << ")" << ss.str();
239 }
240 }
241 // Exception was cleared as part of delivery.
242 DCHECK(!self_->IsExceptionPending());
243 // If the handler is in optimized code, we need to set the catch environment.
244 if (*handler_quick_frame_ != nullptr &&
245 handler_method_header_ != nullptr &&
246 handler_method_header_->IsOptimized()) {
247 SetCatchEnvironmentForOptimizedHandler(&visitor);
248 }
249 popped_to_top = instr->ProcessMethodUnwindCallbacks(self_,
250 visitor.GetUnwoundMethods(),
251 exception_ref);
252 } while (!popped_to_top);
253
254 if (!clear_exception_) {
255 // Put exception back in root set with clear throw location.
256 self_->SetException(exception_ref.Get());
257 }
258 }
259
ToVRegKind(DexRegisterLocation::Kind kind)260 static VRegKind ToVRegKind(DexRegisterLocation::Kind kind) {
261 // Slightly hacky since we cannot map DexRegisterLocationKind and VRegKind
262 // one to one. However, StackVisitor::GetVRegFromOptimizedCode only needs to
263 // distinguish between core/FPU registers and low/high bits on 64-bit.
264 switch (kind) {
265 case DexRegisterLocation::Kind::kConstant:
266 case DexRegisterLocation::Kind::kInStack:
267 // VRegKind is ignored.
268 return VRegKind::kUndefined;
269
270 case DexRegisterLocation::Kind::kInRegister:
271 // Selects core register. For 64-bit registers, selects low 32 bits.
272 return VRegKind::kLongLoVReg;
273
274 case DexRegisterLocation::Kind::kInRegisterHigh:
275 // Selects core register. For 64-bit registers, selects high 32 bits.
276 return VRegKind::kLongHiVReg;
277
278 case DexRegisterLocation::Kind::kInFpuRegister:
279 // Selects FPU register. For 64-bit registers, selects low 32 bits.
280 return VRegKind::kDoubleLoVReg;
281
282 case DexRegisterLocation::Kind::kInFpuRegisterHigh:
283 // Selects FPU register. For 64-bit registers, selects high 32 bits.
284 return VRegKind::kDoubleHiVReg;
285
286 default:
287 LOG(FATAL) << "Unexpected vreg location " << kind;
288 UNREACHABLE();
289 }
290 }
291
SetCatchEnvironmentForOptimizedHandler(StackVisitor * stack_visitor)292 void QuickExceptionHandler::SetCatchEnvironmentForOptimizedHandler(StackVisitor* stack_visitor) {
293 DCHECK(!is_deoptimization_);
294 DCHECK(*handler_quick_frame_ != nullptr) << "Method should not be called on upcall exceptions";
295 DCHECK(GetHandlerMethod() != nullptr && handler_method_header_->IsOptimized());
296
297 if (kDebugExceptionDelivery) {
298 self_->DumpStack(LOG_STREAM(INFO) << "Setting catch phis: ");
299 }
300
301 CodeInfo code_info(handler_method_header_);
302
303 // Find stack map of the catch block.
304 ArrayRef<const uint32_t> dex_pc_list = GetHandlerDexPcList();
305 DCHECK_GE(dex_pc_list.size(), 1u);
306 StackMap catch_stack_map = code_info.GetStackMapAt(GetCatchStackMapRow());
307 DCHECK(catch_stack_map.IsValid());
308 DCHECK_EQ(catch_stack_map.Row(), code_info.GetCatchStackMapForDexPc(dex_pc_list).Row());
309 const uint32_t catch_depth = dex_pc_list.size() - 1;
310 const size_t number_of_registers = stack_visitor->GetNumberOfRegisters(&code_info, catch_depth);
311 DexRegisterMap catch_vreg_map =
312 code_info.GetDexRegisterMapOf(catch_stack_map, /* first= */ 0, number_of_registers);
313
314 if (!catch_vreg_map.HasAnyLiveDexRegisters()) {
315 return;
316 }
317
318 // Find stack map of the throwing instruction.
319 StackMap throw_stack_map =
320 code_info.GetStackMapForNativePcOffset(stack_visitor->GetNativePcOffset());
321 DCHECK(throw_stack_map.IsValid());
322 const uint32_t throw_depth = stack_visitor->InlineDepth();
323 DCHECK_EQ(throw_depth, catch_depth);
324 DexRegisterMap throw_vreg_map =
325 code_info.GetDexRegisterMapOf(throw_stack_map, /* first= */ 0, number_of_registers);
326 DCHECK_EQ(throw_vreg_map.size(), catch_vreg_map.size());
327
328 // First vreg that it is part of the catch's environment.
329 const size_t catch_vreg_start = catch_depth == 0
330 ? 0
331 : stack_visitor->GetNumberOfRegisters(&code_info, catch_depth - 1);
332
333 // We don't need to copy anything in the parent's environment.
334 for (size_t vreg = 0; vreg < catch_vreg_start; ++vreg) {
335 DexRegisterLocation::Kind catch_location_kind = catch_vreg_map[vreg].GetKind();
336 DCHECK(catch_location_kind == DexRegisterLocation::Kind::kNone ||
337 catch_location_kind == DexRegisterLocation::Kind::kConstant ||
338 catch_location_kind == DexRegisterLocation::Kind::kInStack)
339 << "Unexpected catch_location_kind: " << catch_location_kind;
340 }
341
342 // Copy values between the throw and the catch.
343 for (size_t vreg = catch_vreg_start; vreg < catch_vreg_map.size(); ++vreg) {
344 DexRegisterLocation::Kind catch_location_kind = catch_vreg_map[vreg].GetKind();
345 if (catch_location_kind == DexRegisterLocation::Kind::kNone) {
346 continue;
347 }
348
349 // Consistency checks.
350 DCHECK_EQ(catch_location_kind, DexRegisterLocation::Kind::kInStack);
351 uint32_t vreg_value;
352 VRegKind vreg_kind = ToVRegKind(throw_vreg_map[vreg].GetKind());
353 DCHECK_NE(vreg_kind, kReferenceVReg)
354 << "The fast path in GetVReg doesn't expect a kReferenceVReg.";
355
356 // Get vreg value from its current location.
357 bool get_vreg_success = stack_visitor->GetVReg(stack_visitor->GetMethod(),
358 vreg,
359 vreg_kind,
360 &vreg_value,
361 throw_vreg_map[vreg],
362 /* need_full_register_list= */ true);
363 CHECK(get_vreg_success) << "VReg " << vreg << " was optimized out ("
364 << "method=" << ArtMethod::PrettyMethod(stack_visitor->GetMethod())
365 << ", dex_pc=" << stack_visitor->GetDexPc() << ", "
366 << "native_pc_offset=" << stack_visitor->GetNativePcOffset() << ")";
367
368 // Copy value to the catch phi's stack slot.
369 int32_t slot_offset = catch_vreg_map[vreg].GetStackOffsetInBytes();
370 ArtMethod** frame_top = stack_visitor->GetCurrentQuickFrame();
371 uint8_t* slot_address = reinterpret_cast<uint8_t*>(frame_top) + slot_offset;
372 uint32_t* slot_ptr = reinterpret_cast<uint32_t*>(slot_address);
373 *slot_ptr = vreg_value;
374 }
375 }
376
377 // Prepares deoptimization.
378 class DeoptimizeStackVisitor final : public StackVisitor {
379 public:
DeoptimizeStackVisitor(Thread * self,Context * context,QuickExceptionHandler * exception_handler,bool single_frame,bool skip_method_exit_callbacks)380 DeoptimizeStackVisitor(Thread* self,
381 Context* context,
382 QuickExceptionHandler* exception_handler,
383 bool single_frame,
384 bool skip_method_exit_callbacks) REQUIRES_SHARED(Locks::mutator_lock_)
385 : StackVisitor(self, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
386 exception_handler_(exception_handler),
387 prev_shadow_frame_(nullptr),
388 stacked_shadow_frame_pushed_(false),
389 single_frame_deopt_(single_frame),
390 single_frame_done_(false),
391 single_frame_deopt_method_(nullptr),
392 single_frame_deopt_quick_method_header_(nullptr),
393 callee_method_(nullptr),
394 skip_method_exit_callbacks_(skip_method_exit_callbacks) {}
395
GetSingleFrameDeoptMethod() const396 ArtMethod* GetSingleFrameDeoptMethod() const {
397 return single_frame_deopt_method_;
398 }
399
GetSingleFrameDeoptQuickMethodHeader() const400 const OatQuickMethodHeader* GetSingleFrameDeoptQuickMethodHeader() const {
401 return single_frame_deopt_quick_method_header_;
402 }
403
FinishStackWalk()404 void FinishStackWalk() REQUIRES_SHARED(Locks::mutator_lock_) {
405 // This is the upcall, or the next full frame in single-frame deopt, or the
406 // code isn't deoptimizeable. We remember the frame and last pc so that we
407 // may long jump to them.
408 exception_handler_->SetHandlerQuickFramePc(GetCurrentQuickFramePc());
409 exception_handler_->SetHandlerQuickFrame(GetCurrentQuickFrame());
410 exception_handler_->SetHandlerMethodHeader(GetCurrentOatQuickMethodHeader());
411 if (!stacked_shadow_frame_pushed_) {
412 // In case there is no deoptimized shadow frame for this upcall, we still
413 // need to push a nullptr to the stack since there is always a matching pop after
414 // the long jump.
415 GetThread()->PushStackedShadowFrame(nullptr,
416 StackedShadowFrameType::kDeoptimizationShadowFrame);
417 stacked_shadow_frame_pushed_ = true;
418 }
419 if (GetMethod() == nullptr) {
420 exception_handler_->SetFullFragmentDone(true);
421 } else {
422 CHECK(callee_method_ != nullptr) << GetMethod()->PrettyMethod(false);
423 exception_handler_->SetHandlerQuickArg0(reinterpret_cast<uintptr_t>(callee_method_));
424 }
425 }
426
VisitFrame()427 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
428 exception_handler_->SetHandlerFrameDepth(GetFrameDepth());
429 ArtMethod* method = GetMethod();
430 VLOG(deopt) << "Deoptimizing stack: depth: " << GetFrameDepth()
431 << " at method " << ArtMethod::PrettyMethod(method);
432 if (method == nullptr || single_frame_done_) {
433 FinishStackWalk();
434 return false; // End stack walk.
435 } else if (method->IsRuntimeMethod()) {
436 // Ignore callee save method.
437 DCHECK(method->IsCalleeSaveMethod());
438 return true;
439 } else if (method->IsNative()) {
440 // If we return from JNI with a pending exception and want to deoptimize, we need to skip
441 // the native method. The top method is a runtime method, the native method comes next.
442 // We also deoptimize due to method instrumentation reasons from method entry / exit
443 // callbacks. In these cases native method is at the top of stack.
444 CHECK((GetFrameDepth() == 1U) || (GetFrameDepth() == 0U));
445 callee_method_ = method;
446 return true;
447 } else if (!single_frame_deopt_ &&
448 !Runtime::Current()->IsAsyncDeoptimizeable(GetOuterMethod(),
449 GetCurrentQuickFramePc())) {
450 // We hit some code that's not deoptimizeable. However, Single-frame deoptimization triggered
451 // from compiled code is always allowed since HDeoptimize always saves the full environment.
452 LOG(WARNING) << "Got request to deoptimize un-deoptimizable method "
453 << method->PrettyMethod();
454 FinishStackWalk();
455 return false; // End stack walk.
456 } else {
457 // Check if a shadow frame already exists for debugger's set-local-value purpose.
458 const size_t frame_id = GetFrameId();
459 ShadowFrame* new_frame = GetThread()->FindDebuggerShadowFrame(frame_id);
460 const bool* updated_vregs;
461 CodeItemDataAccessor accessor(method->DexInstructionData());
462 const size_t num_regs = accessor.RegistersSize();
463 if (new_frame == nullptr) {
464 new_frame = ShadowFrame::CreateDeoptimizedFrame(num_regs, method, GetDexPc());
465 updated_vregs = nullptr;
466 } else {
467 updated_vregs = GetThread()->GetUpdatedVRegFlags(frame_id);
468 DCHECK(updated_vregs != nullptr);
469 }
470 if (GetCurrentOatQuickMethodHeader()->IsNterpMethodHeader()) {
471 HandleNterpDeoptimization(method, new_frame, updated_vregs);
472 } else {
473 HandleOptimizingDeoptimization(method, new_frame, updated_vregs);
474 }
475 // Update if method exit event needs to be reported. We should report exit event only if we
476 // have reported an entry event. So tell interpreter if/ an entry event was reported.
477 bool supports_exit_events =
478 Runtime::Current()->GetInstrumentation()->MethodSupportsExitEvents(
479 method, GetCurrentOatQuickMethodHeader());
480 new_frame->SetSkipMethodExitEvents(!supports_exit_events);
481 // If we are deoptimizing after method exit callback we shouldn't call the method exit
482 // callbacks again for the top frame. We may have to deopt after the callback if the callback
483 // either throws or performs other actions that require a deopt.
484 // We only need to skip for the top frame and the rest of the frames should still run the
485 // callbacks. So only do this check for the top frame.
486 if (GetFrameDepth() == 0U && skip_method_exit_callbacks_) {
487 new_frame->SetSkipMethodExitEvents(true);
488 // This exception was raised by method exit callbacks and we shouldn't report it to
489 // listeners for these exceptions.
490 if (GetThread()->IsExceptionPending()) {
491 new_frame->SetSkipNextExceptionEvent(true);
492 }
493 }
494 if (updated_vregs != nullptr) {
495 // Calling Thread::RemoveDebuggerShadowFrameMapping will also delete the updated_vregs
496 // array so this must come after we processed the frame.
497 GetThread()->RemoveDebuggerShadowFrameMapping(frame_id);
498 DCHECK(GetThread()->FindDebuggerShadowFrame(frame_id) == nullptr);
499 }
500 if (prev_shadow_frame_ != nullptr) {
501 prev_shadow_frame_->SetLink(new_frame);
502 } else {
503 // Will be popped after the long jump after DeoptimizeStack(),
504 // right before interpreter::EnterInterpreterFromDeoptimize().
505 stacked_shadow_frame_pushed_ = true;
506 GetThread()->PushStackedShadowFrame(
507 new_frame, StackedShadowFrameType::kDeoptimizationShadowFrame);
508 }
509 prev_shadow_frame_ = new_frame;
510
511 if (single_frame_deopt_ && !IsInInlinedFrame()) {
512 // Single-frame deopt ends at the first non-inlined frame and needs to store that method.
513 single_frame_done_ = true;
514 single_frame_deopt_method_ = method;
515 single_frame_deopt_quick_method_header_ = GetCurrentOatQuickMethodHeader();
516 }
517 callee_method_ = method;
518 return true;
519 }
520 }
521
522 private:
HandleNterpDeoptimization(ArtMethod * m,ShadowFrame * new_frame,const bool * updated_vregs)523 void HandleNterpDeoptimization(ArtMethod* m,
524 ShadowFrame* new_frame,
525 const bool* updated_vregs)
526 REQUIRES_SHARED(Locks::mutator_lock_) {
527 ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
528 StackReference<mirror::Object>* vreg_ref_base =
529 reinterpret_cast<StackReference<mirror::Object>*>(NterpGetReferenceArray(cur_quick_frame));
530 int32_t* vreg_int_base =
531 reinterpret_cast<int32_t*>(NterpGetRegistersArray(cur_quick_frame));
532 CodeItemDataAccessor accessor(m->DexInstructionData());
533 const uint16_t num_regs = accessor.RegistersSize();
534 // An nterp frame has two arrays: a dex register array and a reference array
535 // that shadows the dex register array but only containing references
536 // (non-reference dex registers have nulls). See nterp_helpers.cc.
537 for (size_t reg = 0; reg < num_regs; ++reg) {
538 if (updated_vregs != nullptr && updated_vregs[reg]) {
539 // Keep the value set by debugger.
540 continue;
541 }
542 StackReference<mirror::Object>* ref_addr = vreg_ref_base + reg;
543 mirror::Object* ref = ref_addr->AsMirrorPtr();
544 if (ref != nullptr) {
545 new_frame->SetVRegReference(reg, ref);
546 } else {
547 new_frame->SetVReg(reg, vreg_int_base[reg]);
548 }
549 }
550 }
551
HandleOptimizingDeoptimization(ArtMethod * m,ShadowFrame * new_frame,const bool * updated_vregs)552 void HandleOptimizingDeoptimization(ArtMethod* m,
553 ShadowFrame* new_frame,
554 const bool* updated_vregs)
555 REQUIRES_SHARED(Locks::mutator_lock_) {
556 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
557 CodeInfo code_info(method_header);
558 uintptr_t native_pc_offset = method_header->NativeQuickPcOffset(GetCurrentQuickFramePc());
559 StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
560 CodeItemDataAccessor accessor(m->DexInstructionData());
561 const size_t number_of_vregs = accessor.RegistersSize();
562 uint32_t register_mask = code_info.GetRegisterMaskOf(stack_map);
563 BitMemoryRegion stack_mask = code_info.GetStackMaskOf(stack_map);
564 DexRegisterMap vreg_map = IsInInlinedFrame()
565 ? code_info.GetInlineDexRegisterMapOf(stack_map, GetCurrentInlinedFrame())
566 : code_info.GetDexRegisterMapOf(stack_map);
567
568 if (kIsDebugBuild || UNLIKELY(Runtime::Current()->IsJavaDebuggable())) {
569 CHECK_EQ(vreg_map.size(), number_of_vregs) << *Thread::Current()
570 << "Deopting: " << m->PrettyMethod()
571 << " inlined? "
572 << std::boolalpha << IsInInlinedFrame();
573 }
574 if (vreg_map.empty()) {
575 return;
576 }
577
578 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
579 if (updated_vregs != nullptr && updated_vregs[vreg]) {
580 // Keep the value set by debugger.
581 continue;
582 }
583
584 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
585 static constexpr uint32_t kDeadValue = 0xEBADDE09;
586 uint32_t value = kDeadValue;
587 bool is_reference = false;
588
589 switch (location) {
590 case DexRegisterLocation::Kind::kInStack: {
591 const int32_t offset = vreg_map[vreg].GetStackOffsetInBytes();
592 const uint8_t* addr = reinterpret_cast<const uint8_t*>(GetCurrentQuickFrame()) + offset;
593 value = *reinterpret_cast<const uint32_t*>(addr);
594 uint32_t bit = (offset >> 2);
595 if (bit < stack_mask.size_in_bits() && stack_mask.LoadBit(bit)) {
596 is_reference = true;
597 }
598 break;
599 }
600 case DexRegisterLocation::Kind::kInRegister:
601 case DexRegisterLocation::Kind::kInRegisterHigh:
602 case DexRegisterLocation::Kind::kInFpuRegister:
603 case DexRegisterLocation::Kind::kInFpuRegisterHigh: {
604 uint32_t reg = vreg_map[vreg].GetMachineRegister();
605 bool result = GetRegisterIfAccessible(reg, location, &value);
606 CHECK(result);
607 if (location == DexRegisterLocation::Kind::kInRegister) {
608 if (((1u << reg) & register_mask) != 0) {
609 is_reference = true;
610 }
611 }
612 break;
613 }
614 case DexRegisterLocation::Kind::kConstant: {
615 value = vreg_map[vreg].GetConstant();
616 if (value == 0) {
617 // Make it a reference for extra safety.
618 is_reference = true;
619 }
620 break;
621 }
622 case DexRegisterLocation::Kind::kNone: {
623 break;
624 }
625 default: {
626 LOG(FATAL) << "Unexpected location kind " << vreg_map[vreg].GetKind();
627 UNREACHABLE();
628 }
629 }
630 if (is_reference) {
631 new_frame->SetVRegReference(vreg, reinterpret_cast<mirror::Object*>(value));
632 } else {
633 new_frame->SetVReg(vreg, value);
634 }
635 }
636 }
637
GetVRegKind(uint16_t reg,const std::vector<int32_t> & kinds)638 static VRegKind GetVRegKind(uint16_t reg, const std::vector<int32_t>& kinds) {
639 return static_cast<VRegKind>(kinds[reg * 2]);
640 }
641
642 QuickExceptionHandler* const exception_handler_;
643 ShadowFrame* prev_shadow_frame_;
644 bool stacked_shadow_frame_pushed_;
645 const bool single_frame_deopt_;
646 bool single_frame_done_;
647 ArtMethod* single_frame_deopt_method_;
648 const OatQuickMethodHeader* single_frame_deopt_quick_method_header_;
649 ArtMethod* callee_method_;
650 // This specifies if method exit callbacks should be skipped for the top frame. We may request
651 // a deopt after running method exit callbacks if the callback throws or requests events that
652 // need a deopt.
653 bool skip_method_exit_callbacks_;
654
655 DISALLOW_COPY_AND_ASSIGN(DeoptimizeStackVisitor);
656 };
657
PrepareForLongJumpToInvokeStubOrInterpreterBridge()658 void QuickExceptionHandler::PrepareForLongJumpToInvokeStubOrInterpreterBridge() {
659 if (full_fragment_done_) {
660 // Restore deoptimization exception. When returning from the invoke stub,
661 // ArtMethod::Invoke() will see the special exception to know deoptimization
662 // is needed.
663 self_->SetException(Thread::GetDeoptimizationException());
664 } else {
665 // PC needs to be of the quick-to-interpreter bridge.
666 int32_t offset;
667 offset = GetThreadOffset<kRuntimePointerSize>(kQuickQuickToInterpreterBridge).Int32Value();
668 handler_quick_frame_pc_ = *reinterpret_cast<uintptr_t*>(
669 reinterpret_cast<uint8_t*>(self_) + offset);
670 }
671 }
672
DeoptimizeStack(bool skip_method_exit_callbacks)673 void QuickExceptionHandler::DeoptimizeStack(bool skip_method_exit_callbacks) {
674 DCHECK(is_deoptimization_);
675 if (kDebugExceptionDelivery) {
676 self_->DumpStack(LOG_STREAM(INFO) << "Deoptimizing: ");
677 }
678
679 DeoptimizeStackVisitor visitor(self_, context_, this, false, skip_method_exit_callbacks);
680 visitor.WalkStack(true);
681 PrepareForLongJumpToInvokeStubOrInterpreterBridge();
682 }
683
DeoptimizeSingleFrame(DeoptimizationKind kind)684 void QuickExceptionHandler::DeoptimizeSingleFrame(DeoptimizationKind kind) {
685 DCHECK(is_deoptimization_);
686
687 // This deopt is requested while still executing the method. We haven't run method exit callbacks
688 // yet, so don't skip them.
689 DeoptimizeStackVisitor visitor(
690 self_, context_, this, true, /* skip_method_exit_callbacks= */ false);
691 visitor.WalkStack(true);
692
693 // Compiled code made an explicit deoptimization.
694 ArtMethod* deopt_method = visitor.GetSingleFrameDeoptMethod();
695 SCOPED_TRACE << "Deoptimizing "
696 << deopt_method->PrettyMethod()
697 << ": " << GetDeoptimizationKindName(kind);
698
699 DCHECK(deopt_method != nullptr);
700 if (VLOG_IS_ON(deopt) || kDebugExceptionDelivery) {
701 LOG(INFO) << "Single-frame deopting: "
702 << deopt_method->PrettyMethod()
703 << " due to "
704 << GetDeoptimizationKindName(kind);
705 DumpFramesWithType(self_, /* details= */ true);
706 }
707 // When deoptimizing for debug support the optimized code is still valid and
708 // can be reused when debugging support (like breakpoints) are no longer
709 // needed fot this method.
710 if (Runtime::Current()->UseJitCompilation() && (kind != DeoptimizationKind::kDebugging)) {
711 Runtime::Current()->GetJit()->GetCodeCache()->InvalidateCompiledCodeFor(
712 deopt_method, visitor.GetSingleFrameDeoptQuickMethodHeader());
713 } else {
714 Runtime::Current()->GetInstrumentation()->InitializeMethodsCode(
715 deopt_method, /*aot_code=*/ nullptr);
716 }
717
718 PrepareForLongJumpToInvokeStubOrInterpreterBridge();
719 }
720
DeoptimizePartialFragmentFixup()721 void QuickExceptionHandler::DeoptimizePartialFragmentFixup() {
722 CHECK(handler_quick_frame_ != nullptr);
723 // Architecture-dependent work. This is to get the LR right for x86 and x86-64.
724 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
725 // On x86, the return address is on the stack, so just reuse it. Otherwise we would have to
726 // change how longjump works.
727 handler_quick_frame_ = reinterpret_cast<ArtMethod**>(
728 reinterpret_cast<uintptr_t>(handler_quick_frame_) - sizeof(void*));
729 }
730 }
731
DoLongJump(bool smash_caller_saves)732 void QuickExceptionHandler::DoLongJump(bool smash_caller_saves) {
733 // Place context back on thread so it will be available when we continue.
734 self_->ReleaseLongJumpContext(context_);
735 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
736 CHECK_NE(handler_quick_frame_pc_, 0u);
737 context_->SetPC(handler_quick_frame_pc_);
738 context_->SetArg0(handler_quick_arg0_);
739 if (smash_caller_saves) {
740 context_->SmashCallerSaves();
741 }
742 if (!is_deoptimization_ &&
743 handler_method_header_ != nullptr &&
744 handler_method_header_->IsNterpMethodHeader()) {
745 // Interpreter procceses one method at a time i.e. not inlining
746 DCHECK(handler_dex_pc_list_.has_value());
747 DCHECK_EQ(handler_dex_pc_list_->size(), 1u) << "We shouldn't have any inlined frames.";
748 context_->SetNterpDexPC(reinterpret_cast<uintptr_t>(
749 GetHandlerMethod()->DexInstructions().Insns() + handler_dex_pc_list_->front()));
750 }
751 // Clear the dex_pc list so as not to leak memory.
752 handler_dex_pc_list_.reset();
753 context_->DoLongJump();
754 UNREACHABLE();
755 }
756
DumpFramesWithType(Thread * self,bool details)757 void QuickExceptionHandler::DumpFramesWithType(Thread* self, bool details) {
758 StackVisitor::WalkStack(
759 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
760 ArtMethod* method = stack_visitor->GetMethod();
761 if (details) {
762 LOG(INFO) << "|> pc = " << std::hex << stack_visitor->GetCurrentQuickFramePc();
763 LOG(INFO) << "|> addr = " << std::hex
764 << reinterpret_cast<uintptr_t>(stack_visitor->GetCurrentQuickFrame());
765 if (stack_visitor->GetCurrentQuickFrame() != nullptr && method != nullptr) {
766 LOG(INFO) << "|> ret = " << std::hex << stack_visitor->GetReturnPc();
767 }
768 }
769 if (method == nullptr) {
770 // Transition, do go on, we want to unwind over bridges, all the way.
771 if (details) {
772 LOG(INFO) << "N <transition>";
773 }
774 return true;
775 } else if (method->IsRuntimeMethod()) {
776 if (details) {
777 LOG(INFO) << "R " << method->PrettyMethod(true);
778 }
779 return true;
780 } else {
781 bool is_shadow = stack_visitor->GetCurrentShadowFrame() != nullptr;
782 LOG(INFO) << (is_shadow ? "S" : "Q")
783 << ((!is_shadow && stack_visitor->IsInInlinedFrame()) ? "i" : " ")
784 << " "
785 << method->PrettyMethod(true);
786 return true; // Go on.
787 }
788 },
789 self,
790 /* context= */ nullptr,
791 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
792 }
793
794 } // namespace art
795