1 //===-- ThreadPlanStepOut.cpp -----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "lldb/Target/ThreadPlanStepOut.h"
10 #include "lldb/Breakpoint/Breakpoint.h"
11 #include "lldb/Core/Value.h"
12 #include "lldb/Core/ValueObjectConstResult.h"
13 #include "lldb/Symbol/Block.h"
14 #include "lldb/Symbol/Function.h"
15 #include "lldb/Symbol/Symbol.h"
16 #include "lldb/Symbol/Type.h"
17 #include "lldb/Target/ABI.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/RegisterContext.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/ThreadPlanStepOverRange.h"
23 #include "lldb/Target/ThreadPlanStepThrough.h"
24 #include "lldb/Utility/Log.h"
25
26 #include <memory>
27
28 using namespace lldb;
29 using namespace lldb_private;
30
31 uint32_t ThreadPlanStepOut::s_default_flag_values = 0;
32
33 // ThreadPlanStepOut: Step out of the current frame
ThreadPlanStepOut(Thread & thread,SymbolContext * context,bool first_insn,bool stop_others,Vote stop_vote,Vote run_vote,uint32_t frame_idx,LazyBool step_out_avoids_code_without_debug_info,bool continue_to_next_branch,bool gather_return_value)34 ThreadPlanStepOut::ThreadPlanStepOut(
35 Thread &thread, SymbolContext *context, bool first_insn, bool stop_others,
36 Vote stop_vote, Vote run_vote, uint32_t frame_idx,
37 LazyBool step_out_avoids_code_without_debug_info,
38 bool continue_to_next_branch, bool gather_return_value)
39 : ThreadPlan(ThreadPlan::eKindStepOut, "Step out", thread, stop_vote,
40 run_vote),
41 ThreadPlanShouldStopHere(this), m_step_from_insn(LLDB_INVALID_ADDRESS),
42 m_return_bp_id(LLDB_INVALID_BREAK_ID),
43 m_return_addr(LLDB_INVALID_ADDRESS), m_stop_others(stop_others),
44 m_immediate_step_from_function(nullptr),
45 m_calculate_return_value(gather_return_value) {
46 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
47 SetFlagsToDefault();
48 SetupAvoidNoDebug(step_out_avoids_code_without_debug_info);
49
50 m_step_from_insn = m_thread.GetRegisterContext()->GetPC(0);
51
52 uint32_t return_frame_index = frame_idx + 1;
53 StackFrameSP return_frame_sp(
54 m_thread.GetStackFrameAtIndex(return_frame_index));
55 StackFrameSP immediate_return_from_sp(
56 m_thread.GetStackFrameAtIndex(frame_idx));
57
58 if (!return_frame_sp || !immediate_return_from_sp)
59 return; // we can't do anything here. ValidatePlan() will return false.
60
61 // While stepping out, behave as-if artificial frames are not present.
62 while (return_frame_sp->IsArtificial()) {
63 m_stepped_past_frames.push_back(return_frame_sp);
64
65 ++return_frame_index;
66 return_frame_sp = m_thread.GetStackFrameAtIndex(return_frame_index);
67
68 // We never expect to see an artificial frame without a regular ancestor.
69 // If this happens, log the issue and defensively refuse to step out.
70 if (!return_frame_sp) {
71 LLDB_LOG(log, "Can't step out of frame with artificial ancestors");
72 return;
73 }
74 }
75
76 m_step_out_to_id = return_frame_sp->GetStackID();
77 m_immediate_step_from_id = immediate_return_from_sp->GetStackID();
78
79 // If the frame directly below the one we are returning to is inlined, we
80 // have to be a little more careful. It is non-trivial to determine the real
81 // "return code address" for an inlined frame, so we have to work our way to
82 // that frame and then step out.
83 if (immediate_return_from_sp->IsInlined()) {
84 if (frame_idx > 0) {
85 // First queue a plan that gets us to this inlined frame, and when we get
86 // there we'll queue a second plan that walks us out of this frame.
87 m_step_out_to_inline_plan_sp = std::make_shared<ThreadPlanStepOut>(
88 m_thread, nullptr, false, stop_others, eVoteNoOpinion, eVoteNoOpinion,
89 frame_idx - 1, eLazyBoolNo, continue_to_next_branch);
90 static_cast<ThreadPlanStepOut *>(m_step_out_to_inline_plan_sp.get())
91 ->SetShouldStopHereCallbacks(nullptr, nullptr);
92 m_step_out_to_inline_plan_sp->SetPrivate(true);
93 } else {
94 // If we're already at the inlined frame we're stepping through, then
95 // just do that now.
96 QueueInlinedStepPlan(false);
97 }
98 } else {
99 // Find the return address and set a breakpoint there:
100 // FIXME - can we do this more securely if we know first_insn?
101
102 Address return_address(return_frame_sp->GetFrameCodeAddress());
103 if (continue_to_next_branch) {
104 SymbolContext return_address_sc;
105 AddressRange range;
106 Address return_address_decr_pc = return_address;
107 if (return_address_decr_pc.GetOffset() > 0)
108 return_address_decr_pc.Slide(-1);
109
110 return_address_decr_pc.CalculateSymbolContext(
111 &return_address_sc, lldb::eSymbolContextLineEntry);
112 if (return_address_sc.line_entry.IsValid()) {
113 const bool include_inlined_functions = false;
114 range = return_address_sc.line_entry.GetSameLineContiguousAddressRange(
115 include_inlined_functions);
116 if (range.GetByteSize() > 0) {
117 return_address =
118 m_thread.GetProcess()->AdvanceAddressToNextBranchInstruction(
119 return_address, range);
120 }
121 }
122 }
123 m_return_addr =
124 return_address.GetLoadAddress(&m_thread.GetProcess()->GetTarget());
125
126 if (m_return_addr == LLDB_INVALID_ADDRESS)
127 return;
128
129 // Perform some additional validation on the return address.
130 uint32_t permissions = 0;
131 if (!m_thread.GetProcess()->GetLoadAddressPermissions(m_return_addr,
132 permissions)) {
133 m_constructor_errors.Printf("Return address (0x%" PRIx64
134 ") permissions not found.",
135 m_return_addr);
136 LLDB_LOGF(log, "ThreadPlanStepOut(%p): %s", static_cast<void *>(this),
137 m_constructor_errors.GetData());
138 return;
139 } else if (!(permissions & ePermissionsExecutable)) {
140 m_constructor_errors.Printf("Return address (0x%" PRIx64
141 ") did not point to executable memory.",
142 m_return_addr);
143 LLDB_LOGF(log, "ThreadPlanStepOut(%p): %s", static_cast<void *>(this),
144 m_constructor_errors.GetData());
145 return;
146 }
147
148 Breakpoint *return_bp = m_thread.CalculateTarget()
149 ->CreateBreakpoint(m_return_addr, true, false)
150 .get();
151
152 if (return_bp != nullptr) {
153 if (return_bp->IsHardware() && !return_bp->HasResolvedLocations())
154 m_could_not_resolve_hw_bp = true;
155 return_bp->SetThreadID(m_thread.GetID());
156 m_return_bp_id = return_bp->GetID();
157 return_bp->SetBreakpointKind("step-out");
158 }
159
160 if (immediate_return_from_sp) {
161 const SymbolContext &sc =
162 immediate_return_from_sp->GetSymbolContext(eSymbolContextFunction);
163 if (sc.function) {
164 m_immediate_step_from_function = sc.function;
165 }
166 }
167 }
168 }
169
SetupAvoidNoDebug(LazyBool step_out_avoids_code_without_debug_info)170 void ThreadPlanStepOut::SetupAvoidNoDebug(
171 LazyBool step_out_avoids_code_without_debug_info) {
172 bool avoid_nodebug = true;
173 switch (step_out_avoids_code_without_debug_info) {
174 case eLazyBoolYes:
175 avoid_nodebug = true;
176 break;
177 case eLazyBoolNo:
178 avoid_nodebug = false;
179 break;
180 case eLazyBoolCalculate:
181 avoid_nodebug = m_thread.GetStepOutAvoidsNoDebug();
182 break;
183 }
184 if (avoid_nodebug)
185 GetFlags().Set(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
186 else
187 GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
188 }
189
DidPush()190 void ThreadPlanStepOut::DidPush() {
191 if (m_step_out_to_inline_plan_sp)
192 m_thread.QueueThreadPlan(m_step_out_to_inline_plan_sp, false);
193 else if (m_step_through_inline_plan_sp)
194 m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
195 }
196
~ThreadPlanStepOut()197 ThreadPlanStepOut::~ThreadPlanStepOut() {
198 if (m_return_bp_id != LLDB_INVALID_BREAK_ID)
199 m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
200 }
201
GetDescription(Stream * s,lldb::DescriptionLevel level)202 void ThreadPlanStepOut::GetDescription(Stream *s,
203 lldb::DescriptionLevel level) {
204 if (level == lldb::eDescriptionLevelBrief)
205 s->Printf("step out");
206 else {
207 if (m_step_out_to_inline_plan_sp)
208 s->Printf("Stepping out to inlined frame so we can walk through it.");
209 else if (m_step_through_inline_plan_sp)
210 s->Printf("Stepping out by stepping through inlined function.");
211 else {
212 s->Printf("Stepping out from ");
213 Address tmp_address;
214 if (tmp_address.SetLoadAddress(m_step_from_insn, &GetTarget())) {
215 tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
216 Address::DumpStyleLoadAddress);
217 } else {
218 s->Printf("address 0x%" PRIx64 "", (uint64_t)m_step_from_insn);
219 }
220
221 // FIXME: find some useful way to present the m_return_id, since there may
222 // be multiple copies of the
223 // same function on the stack.
224
225 s->Printf(" returning to frame at ");
226 if (tmp_address.SetLoadAddress(m_return_addr, &GetTarget())) {
227 tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
228 Address::DumpStyleLoadAddress);
229 } else {
230 s->Printf("address 0x%" PRIx64 "", (uint64_t)m_return_addr);
231 }
232
233 if (level == eDescriptionLevelVerbose)
234 s->Printf(" using breakpoint site %d", m_return_bp_id);
235 }
236 }
237
238 s->Printf("\n");
239 for (StackFrameSP frame_sp : m_stepped_past_frames) {
240 s->Printf("Stepped out past: ");
241 frame_sp->DumpUsingSettingsFormat(s);
242 }
243 }
244
ValidatePlan(Stream * error)245 bool ThreadPlanStepOut::ValidatePlan(Stream *error) {
246 if (m_step_out_to_inline_plan_sp)
247 return m_step_out_to_inline_plan_sp->ValidatePlan(error);
248
249 if (m_step_through_inline_plan_sp)
250 return m_step_through_inline_plan_sp->ValidatePlan(error);
251
252 if (m_could_not_resolve_hw_bp) {
253 if (error)
254 error->PutCString(
255 "Could not create hardware breakpoint for thread plan.");
256 return false;
257 }
258
259 if (m_return_bp_id == LLDB_INVALID_BREAK_ID) {
260 if (error) {
261 error->PutCString("Could not create return address breakpoint.");
262 if (m_constructor_errors.GetSize() > 0) {
263 error->PutCString(" ");
264 error->PutCString(m_constructor_errors.GetString());
265 }
266 }
267 return false;
268 }
269
270 return true;
271 }
272
DoPlanExplainsStop(Event * event_ptr)273 bool ThreadPlanStepOut::DoPlanExplainsStop(Event *event_ptr) {
274 // If the step out plan is done, then we just need to step through the
275 // inlined frame.
276 if (m_step_out_to_inline_plan_sp) {
277 return m_step_out_to_inline_plan_sp->MischiefManaged();
278 } else if (m_step_through_inline_plan_sp) {
279 if (m_step_through_inline_plan_sp->MischiefManaged()) {
280 CalculateReturnValue();
281 SetPlanComplete();
282 return true;
283 } else
284 return false;
285 } else if (m_step_out_further_plan_sp) {
286 return m_step_out_further_plan_sp->MischiefManaged();
287 }
288
289 // We don't explain signals or breakpoints (breakpoints that handle stepping
290 // in or out will be handled by a child plan.
291
292 StopInfoSP stop_info_sp = GetPrivateStopInfo();
293 if (stop_info_sp) {
294 StopReason reason = stop_info_sp->GetStopReason();
295 if (reason == eStopReasonBreakpoint) {
296 // If this is OUR breakpoint, we're fine, otherwise we don't know why
297 // this happened...
298 BreakpointSiteSP site_sp(
299 m_thread.GetProcess()->GetBreakpointSiteList().FindByID(
300 stop_info_sp->GetValue()));
301 if (site_sp && site_sp->IsBreakpointAtThisSite(m_return_bp_id)) {
302 bool done;
303
304 StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
305
306 if (m_step_out_to_id == frame_zero_id)
307 done = true;
308 else if (m_step_out_to_id < frame_zero_id) {
309 // Either we stepped past the breakpoint, or the stack ID calculation
310 // was incorrect and we should probably stop.
311 done = true;
312 } else {
313 done = (m_immediate_step_from_id < frame_zero_id);
314 }
315
316 if (done) {
317 if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
318 CalculateReturnValue();
319 SetPlanComplete();
320 }
321 }
322
323 // If there was only one owner, then we're done. But if we also hit
324 // some user breakpoint on our way out, we should mark ourselves as
325 // done, but also not claim to explain the stop, since it is more
326 // important to report the user breakpoint than the step out
327 // completion.
328
329 if (site_sp->GetNumberOfOwners() == 1)
330 return true;
331 }
332 return false;
333 } else if (IsUsuallyUnexplainedStopReason(reason))
334 return false;
335 else
336 return true;
337 }
338 return true;
339 }
340
ShouldStop(Event * event_ptr)341 bool ThreadPlanStepOut::ShouldStop(Event *event_ptr) {
342 if (IsPlanComplete())
343 return true;
344
345 bool done = false;
346 if (m_step_out_to_inline_plan_sp) {
347 if (m_step_out_to_inline_plan_sp->MischiefManaged()) {
348 // Now step through the inlined stack we are in:
349 if (QueueInlinedStepPlan(true)) {
350 // If we can't queue a plan to do this, then just call ourselves done.
351 m_step_out_to_inline_plan_sp.reset();
352 SetPlanComplete(false);
353 return true;
354 } else
355 done = true;
356 } else
357 return m_step_out_to_inline_plan_sp->ShouldStop(event_ptr);
358 } else if (m_step_through_inline_plan_sp) {
359 if (m_step_through_inline_plan_sp->MischiefManaged())
360 done = true;
361 else
362 return m_step_through_inline_plan_sp->ShouldStop(event_ptr);
363 } else if (m_step_out_further_plan_sp) {
364 if (m_step_out_further_plan_sp->MischiefManaged())
365 m_step_out_further_plan_sp.reset();
366 else
367 return m_step_out_further_plan_sp->ShouldStop(event_ptr);
368 }
369
370 if (!done) {
371 StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
372 done = !(frame_zero_id < m_step_out_to_id);
373 }
374
375 // The normal step out computations think we are done, so all we need to do
376 // is consult the ShouldStopHere, and we are done.
377
378 if (done) {
379 if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
380 CalculateReturnValue();
381 SetPlanComplete();
382 } else {
383 m_step_out_further_plan_sp =
384 QueueStepOutFromHerePlan(m_flags, eFrameCompareOlder, m_status);
385 done = false;
386 }
387 }
388
389 return done;
390 }
391
StopOthers()392 bool ThreadPlanStepOut::StopOthers() { return m_stop_others; }
393
GetPlanRunState()394 StateType ThreadPlanStepOut::GetPlanRunState() { return eStateRunning; }
395
DoWillResume(StateType resume_state,bool current_plan)396 bool ThreadPlanStepOut::DoWillResume(StateType resume_state,
397 bool current_plan) {
398 if (m_step_out_to_inline_plan_sp || m_step_through_inline_plan_sp)
399 return true;
400
401 if (m_return_bp_id == LLDB_INVALID_BREAK_ID)
402 return false;
403
404 if (current_plan) {
405 Breakpoint *return_bp =
406 m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
407 if (return_bp != nullptr)
408 return_bp->SetEnabled(true);
409 }
410 return true;
411 }
412
WillStop()413 bool ThreadPlanStepOut::WillStop() {
414 if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
415 Breakpoint *return_bp =
416 m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
417 if (return_bp != nullptr)
418 return_bp->SetEnabled(false);
419 }
420
421 return true;
422 }
423
MischiefManaged()424 bool ThreadPlanStepOut::MischiefManaged() {
425 if (IsPlanComplete()) {
426 // Did I reach my breakpoint? If so I'm done.
427 //
428 // I also check the stack depth, since if we've blown past the breakpoint
429 // for some
430 // reason and we're now stopping for some other reason altogether, then
431 // we're done with this step out operation.
432
433 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
434 if (log)
435 LLDB_LOGF(log, "Completed step out plan.");
436 if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
437 m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
438 m_return_bp_id = LLDB_INVALID_BREAK_ID;
439 }
440
441 ThreadPlan::MischiefManaged();
442 return true;
443 } else {
444 return false;
445 }
446 }
447
QueueInlinedStepPlan(bool queue_now)448 bool ThreadPlanStepOut::QueueInlinedStepPlan(bool queue_now) {
449 // Now figure out the range of this inlined block, and set up a "step through
450 // range" plan for that. If we've been provided with a context, then use the
451 // block in that context.
452 StackFrameSP immediate_return_from_sp(m_thread.GetStackFrameAtIndex(0));
453 if (!immediate_return_from_sp)
454 return false;
455
456 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
457 if (log) {
458 StreamString s;
459 immediate_return_from_sp->Dump(&s, true, false);
460 LLDB_LOGF(log, "Queuing inlined frame to step past: %s.", s.GetData());
461 }
462
463 Block *from_block = immediate_return_from_sp->GetFrameBlock();
464 if (from_block) {
465 Block *inlined_block = from_block->GetContainingInlinedBlock();
466 if (inlined_block) {
467 size_t num_ranges = inlined_block->GetNumRanges();
468 AddressRange inline_range;
469 if (inlined_block->GetRangeAtIndex(0, inline_range)) {
470 SymbolContext inlined_sc;
471 inlined_block->CalculateSymbolContext(&inlined_sc);
472 inlined_sc.target_sp = GetTarget().shared_from_this();
473 RunMode run_mode =
474 m_stop_others ? lldb::eOnlyThisThread : lldb::eAllThreads;
475 const LazyBool avoid_no_debug = eLazyBoolNo;
476
477 m_step_through_inline_plan_sp =
478 std::make_shared<ThreadPlanStepOverRange>(
479 m_thread, inline_range, inlined_sc, run_mode, avoid_no_debug);
480 ThreadPlanStepOverRange *step_through_inline_plan_ptr =
481 static_cast<ThreadPlanStepOverRange *>(
482 m_step_through_inline_plan_sp.get());
483 m_step_through_inline_plan_sp->SetPrivate(true);
484
485 step_through_inline_plan_ptr->SetOkayToDiscard(true);
486 StreamString errors;
487 if (!step_through_inline_plan_ptr->ValidatePlan(&errors)) {
488 // FIXME: Log this failure.
489 delete step_through_inline_plan_ptr;
490 return false;
491 }
492
493 for (size_t i = 1; i < num_ranges; i++) {
494 if (inlined_block->GetRangeAtIndex(i, inline_range))
495 step_through_inline_plan_ptr->AddRange(inline_range);
496 }
497
498 if (queue_now)
499 m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
500 return true;
501 }
502 }
503 }
504
505 return false;
506 }
507
CalculateReturnValue()508 void ThreadPlanStepOut::CalculateReturnValue() {
509 if (m_return_valobj_sp)
510 return;
511
512 if (!m_calculate_return_value)
513 return;
514
515 if (m_immediate_step_from_function != nullptr) {
516 CompilerType return_compiler_type =
517 m_immediate_step_from_function->GetCompilerType()
518 .GetFunctionReturnType();
519 if (return_compiler_type) {
520 lldb::ABISP abi_sp = m_thread.GetProcess()->GetABI();
521 if (abi_sp)
522 m_return_valobj_sp =
523 abi_sp->GetReturnValueObject(m_thread, return_compiler_type);
524 }
525 }
526 }
527
IsPlanStale()528 bool ThreadPlanStepOut::IsPlanStale() {
529 // If we are still lower on the stack than the frame we are returning to,
530 // then there's something for us to do. Otherwise, we're stale.
531
532 StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
533 return !(frame_zero_id < m_step_out_to_id);
534 }
535