1 //===-- ThreadPlanStepOut.cpp ---------------------------------------------===//
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
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     } else if (!(permissions & ePermissionsExecutable)) {
139       m_constructor_errors.Printf("Return address (0x%" PRIx64
140                                   ") did not point to executable memory.",
141                                   m_return_addr);
142       LLDB_LOGF(log, "ThreadPlanStepOut(%p): %s", static_cast<void *>(this),
143                 m_constructor_errors.GetData());
144       return;
145     }
146 
147     Breakpoint *return_bp = m_thread.CalculateTarget()
148                                 ->CreateBreakpoint(m_return_addr, true, false)
149                                 .get();
150 
151     if (return_bp != nullptr) {
152       if (return_bp->IsHardware() && !return_bp->HasResolvedLocations())
153         m_could_not_resolve_hw_bp = true;
154       return_bp->SetThreadID(m_thread.GetID());
155       m_return_bp_id = return_bp->GetID();
156       return_bp->SetBreakpointKind("step-out");
157     }
158 
159     if (immediate_return_from_sp) {
160       const SymbolContext &sc =
161           immediate_return_from_sp->GetSymbolContext(eSymbolContextFunction);
162       if (sc.function) {
163         m_immediate_step_from_function = sc.function;
164       }
165     }
166   }
167 }
168 
169 void ThreadPlanStepOut::SetupAvoidNoDebug(
170     LazyBool step_out_avoids_code_without_debug_info) {
171   bool avoid_nodebug = true;
172   switch (step_out_avoids_code_without_debug_info) {
173   case eLazyBoolYes:
174     avoid_nodebug = true;
175     break;
176   case eLazyBoolNo:
177     avoid_nodebug = false;
178     break;
179   case eLazyBoolCalculate:
180     avoid_nodebug = m_thread.GetStepOutAvoidsNoDebug();
181     break;
182   }
183   if (avoid_nodebug)
184     GetFlags().Set(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
185   else
186     GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
187 }
188 
189 void ThreadPlanStepOut::DidPush() {
190   if (m_step_out_to_inline_plan_sp)
191     m_thread.QueueThreadPlan(m_step_out_to_inline_plan_sp, false);
192   else if (m_step_through_inline_plan_sp)
193     m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
194 }
195 
196 ThreadPlanStepOut::~ThreadPlanStepOut() {
197   if (m_return_bp_id != LLDB_INVALID_BREAK_ID)
198     m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
199 }
200 
201 void ThreadPlanStepOut::GetDescription(Stream *s,
202                                        lldb::DescriptionLevel level) {
203   if (level == lldb::eDescriptionLevelBrief)
204     s->Printf("step out");
205   else {
206     if (m_step_out_to_inline_plan_sp)
207       s->Printf("Stepping out to inlined frame so we can walk through it.");
208     else if (m_step_through_inline_plan_sp)
209       s->Printf("Stepping out by stepping through inlined function.");
210     else {
211       s->Printf("Stepping out from ");
212       Address tmp_address;
213       if (tmp_address.SetLoadAddress(m_step_from_insn, &GetTarget())) {
214         tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
215                          Address::DumpStyleLoadAddress);
216       } else {
217         s->Printf("address 0x%" PRIx64 "", (uint64_t)m_step_from_insn);
218       }
219 
220       // FIXME: find some useful way to present the m_return_id, since there may
221       // be multiple copies of the
222       // same function on the stack.
223 
224       s->Printf(" returning to frame at ");
225       if (tmp_address.SetLoadAddress(m_return_addr, &GetTarget())) {
226         tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
227                          Address::DumpStyleLoadAddress);
228       } else {
229         s->Printf("address 0x%" PRIx64 "", (uint64_t)m_return_addr);
230       }
231 
232       if (level == eDescriptionLevelVerbose)
233         s->Printf(" using breakpoint site %d", m_return_bp_id);
234     }
235   }
236 
237   s->Printf("\n");
238   for (StackFrameSP frame_sp : m_stepped_past_frames) {
239     s->Printf("Stepped out past: ");
240     frame_sp->DumpUsingSettingsFormat(s);
241   }
242 }
243 
244 bool ThreadPlanStepOut::ValidatePlan(Stream *error) {
245   if (m_step_out_to_inline_plan_sp)
246     return m_step_out_to_inline_plan_sp->ValidatePlan(error);
247 
248   if (m_step_through_inline_plan_sp)
249     return m_step_through_inline_plan_sp->ValidatePlan(error);
250 
251   if (m_could_not_resolve_hw_bp) {
252     if (error)
253       error->PutCString(
254           "Could not create hardware breakpoint for thread plan.");
255     return false;
256   }
257 
258   if (m_return_bp_id == LLDB_INVALID_BREAK_ID) {
259     if (error) {
260       error->PutCString("Could not create return address breakpoint.");
261       if (m_constructor_errors.GetSize() > 0) {
262         error->PutCString(" ");
263         error->PutCString(m_constructor_errors.GetString());
264       }
265     }
266     return false;
267   }
268 
269   return true;
270 }
271 
272 bool ThreadPlanStepOut::DoPlanExplainsStop(Event *event_ptr) {
273   // If the step out plan is done, then we just need to step through the
274   // inlined frame.
275   if (m_step_out_to_inline_plan_sp) {
276     return m_step_out_to_inline_plan_sp->MischiefManaged();
277   } else if (m_step_through_inline_plan_sp) {
278     if (m_step_through_inline_plan_sp->MischiefManaged()) {
279       CalculateReturnValue();
280       SetPlanComplete();
281       return true;
282     } else
283       return false;
284   } else if (m_step_out_further_plan_sp) {
285     return m_step_out_further_plan_sp->MischiefManaged();
286   }
287 
288   // We don't explain signals or breakpoints (breakpoints that handle stepping
289   // in or out will be handled by a child plan.
290 
291   StopInfoSP stop_info_sp = GetPrivateStopInfo();
292   if (stop_info_sp) {
293     StopReason reason = stop_info_sp->GetStopReason();
294     if (reason == eStopReasonBreakpoint) {
295       // If this is OUR breakpoint, we're fine, otherwise we don't know why
296       // this happened...
297       BreakpointSiteSP site_sp(
298           m_thread.GetProcess()->GetBreakpointSiteList().FindByID(
299               stop_info_sp->GetValue()));
300       if (site_sp && site_sp->IsBreakpointAtThisSite(m_return_bp_id)) {
301         bool done;
302 
303         StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
304 
305         if (m_step_out_to_id == frame_zero_id)
306           done = true;
307         else if (m_step_out_to_id < frame_zero_id) {
308           // Either we stepped past the breakpoint, or the stack ID calculation
309           // was incorrect and we should probably stop.
310           done = true;
311         } else {
312           done = (m_immediate_step_from_id < frame_zero_id);
313         }
314 
315         if (done) {
316           if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
317             CalculateReturnValue();
318             SetPlanComplete();
319           }
320         }
321 
322         // If there was only one owner, then we're done.  But if we also hit
323         // some user breakpoint on our way out, we should mark ourselves as
324         // done, but also not claim to explain the stop, since it is more
325         // important to report the user breakpoint than the step out
326         // completion.
327 
328         if (site_sp->GetNumberOfOwners() == 1)
329           return true;
330       }
331       return false;
332     } else if (IsUsuallyUnexplainedStopReason(reason))
333       return false;
334     else
335       return true;
336   }
337   return true;
338 }
339 
340 bool ThreadPlanStepOut::ShouldStop(Event *event_ptr) {
341   if (IsPlanComplete())
342     return true;
343 
344   bool done = false;
345   if (m_step_out_to_inline_plan_sp) {
346     if (m_step_out_to_inline_plan_sp->MischiefManaged()) {
347       // Now step through the inlined stack we are in:
348       if (QueueInlinedStepPlan(true)) {
349         // If we can't queue a plan to do this, then just call ourselves done.
350         m_step_out_to_inline_plan_sp.reset();
351         SetPlanComplete(false);
352         return true;
353       } else
354         done = true;
355     } else
356       return m_step_out_to_inline_plan_sp->ShouldStop(event_ptr);
357   } else if (m_step_through_inline_plan_sp) {
358     if (m_step_through_inline_plan_sp->MischiefManaged())
359       done = true;
360     else
361       return m_step_through_inline_plan_sp->ShouldStop(event_ptr);
362   } else if (m_step_out_further_plan_sp) {
363     if (m_step_out_further_plan_sp->MischiefManaged())
364       m_step_out_further_plan_sp.reset();
365     else
366       return m_step_out_further_plan_sp->ShouldStop(event_ptr);
367   }
368 
369   if (!done) {
370     StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
371     done = !(frame_zero_id < m_step_out_to_id);
372   }
373 
374   // The normal step out computations think we are done, so all we need to do
375   // is consult the ShouldStopHere, and we are done.
376 
377   if (done) {
378     if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
379       CalculateReturnValue();
380       SetPlanComplete();
381     } else {
382       m_step_out_further_plan_sp =
383           QueueStepOutFromHerePlan(m_flags, eFrameCompareOlder, m_status);
384       done = false;
385     }
386   }
387 
388   return done;
389 }
390 
391 bool ThreadPlanStepOut::StopOthers() { return m_stop_others; }
392 
393 StateType ThreadPlanStepOut::GetPlanRunState() { return eStateRunning; }
394 
395 bool ThreadPlanStepOut::DoWillResume(StateType resume_state,
396                                      bool current_plan) {
397   if (m_step_out_to_inline_plan_sp || m_step_through_inline_plan_sp)
398     return true;
399 
400   if (m_return_bp_id == LLDB_INVALID_BREAK_ID)
401     return false;
402 
403   if (current_plan) {
404     Breakpoint *return_bp =
405         m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
406     if (return_bp != nullptr)
407       return_bp->SetEnabled(true);
408   }
409   return true;
410 }
411 
412 bool ThreadPlanStepOut::WillStop() {
413   if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
414     Breakpoint *return_bp =
415         m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
416     if (return_bp != nullptr)
417       return_bp->SetEnabled(false);
418   }
419 
420   return true;
421 }
422 
423 bool ThreadPlanStepOut::MischiefManaged() {
424   if (IsPlanComplete()) {
425     // Did I reach my breakpoint?  If so I'm done.
426     //
427     // I also check the stack depth, since if we've blown past the breakpoint
428     // for some
429     // reason and we're now stopping for some other reason altogether, then
430     // we're done with this step out operation.
431 
432     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
433     if (log)
434       LLDB_LOGF(log, "Completed step out plan.");
435     if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
436       m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
437       m_return_bp_id = LLDB_INVALID_BREAK_ID;
438     }
439 
440     ThreadPlan::MischiefManaged();
441     return true;
442   } else {
443     return false;
444   }
445 }
446 
447 bool ThreadPlanStepOut::QueueInlinedStepPlan(bool queue_now) {
448   // Now figure out the range of this inlined block, and set up a "step through
449   // range" plan for that.  If we've been provided with a context, then use the
450   // block in that context.
451   StackFrameSP immediate_return_from_sp(m_thread.GetStackFrameAtIndex(0));
452   if (!immediate_return_from_sp)
453     return false;
454 
455   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
456   if (log) {
457     StreamString s;
458     immediate_return_from_sp->Dump(&s, true, false);
459     LLDB_LOGF(log, "Queuing inlined frame to step past: %s.", s.GetData());
460   }
461 
462   Block *from_block = immediate_return_from_sp->GetFrameBlock();
463   if (from_block) {
464     Block *inlined_block = from_block->GetContainingInlinedBlock();
465     if (inlined_block) {
466       size_t num_ranges = inlined_block->GetNumRanges();
467       AddressRange inline_range;
468       if (inlined_block->GetRangeAtIndex(0, inline_range)) {
469         SymbolContext inlined_sc;
470         inlined_block->CalculateSymbolContext(&inlined_sc);
471         inlined_sc.target_sp = GetTarget().shared_from_this();
472         RunMode run_mode =
473             m_stop_others ? lldb::eOnlyThisThread : lldb::eAllThreads;
474         const LazyBool avoid_no_debug = eLazyBoolNo;
475 
476         m_step_through_inline_plan_sp =
477             std::make_shared<ThreadPlanStepOverRange>(
478                 m_thread, inline_range, inlined_sc, run_mode, avoid_no_debug);
479         ThreadPlanStepOverRange *step_through_inline_plan_ptr =
480             static_cast<ThreadPlanStepOverRange *>(
481                 m_step_through_inline_plan_sp.get());
482         m_step_through_inline_plan_sp->SetPrivate(true);
483 
484         step_through_inline_plan_ptr->SetOkayToDiscard(true);
485         StreamString errors;
486         if (!step_through_inline_plan_ptr->ValidatePlan(&errors)) {
487           // FIXME: Log this failure.
488           delete step_through_inline_plan_ptr;
489           return false;
490         }
491 
492         for (size_t i = 1; i < num_ranges; i++) {
493           if (inlined_block->GetRangeAtIndex(i, inline_range))
494             step_through_inline_plan_ptr->AddRange(inline_range);
495         }
496 
497         if (queue_now)
498           m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
499         return true;
500       }
501     }
502   }
503 
504   return false;
505 }
506 
507 void ThreadPlanStepOut::CalculateReturnValue() {
508   if (m_return_valobj_sp)
509     return;
510 
511   if (!m_calculate_return_value)
512     return;
513 
514   if (m_immediate_step_from_function != nullptr) {
515     CompilerType return_compiler_type =
516         m_immediate_step_from_function->GetCompilerType()
517             .GetFunctionReturnType();
518     if (return_compiler_type) {
519       lldb::ABISP abi_sp = m_thread.GetProcess()->GetABI();
520       if (abi_sp)
521         m_return_valobj_sp =
522             abi_sp->GetReturnValueObject(m_thread, return_compiler_type);
523     }
524   }
525 }
526 
527 bool ThreadPlanStepOut::IsPlanStale() {
528   // If we are still lower on the stack than the frame we are returning to,
529   // then there's something for us to do.  Otherwise, we're stale.
530 
531   StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
532   return !(frame_zero_id < m_step_out_to_id);
533 }
534