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