1 //===-- ThreadPlanStepOverRange.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/ThreadPlanStepOverRange.h"
10 #include "lldb/Symbol/Block.h"
11 #include "lldb/Symbol/CompileUnit.h"
12 #include "lldb/Symbol/Function.h"
13 #include "lldb/Symbol/LineTable.h"
14 #include "lldb/Target/Process.h"
15 #include "lldb/Target/RegisterContext.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Target/Thread.h"
18 #include "lldb/Target/ThreadPlanStepOut.h"
19 #include "lldb/Target/ThreadPlanStepThrough.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Stream.h"
22 
23 using namespace lldb_private;
24 using namespace lldb;
25 
26 uint32_t ThreadPlanStepOverRange::s_default_flag_values = 0;
27 
28 //----------------------------------------------------------------------
29 // ThreadPlanStepOverRange: Step through a stack range, either stepping over or
30 // into based on the value of \a type.
31 //----------------------------------------------------------------------
32 
33 ThreadPlanStepOverRange::ThreadPlanStepOverRange(
34     Thread &thread, const AddressRange &range,
35     const SymbolContext &addr_context, lldb::RunMode stop_others,
36     LazyBool step_out_avoids_code_without_debug_info)
37     : ThreadPlanStepRange(ThreadPlan::eKindStepOverRange,
38                           "Step range stepping over", thread, range,
39                           addr_context, stop_others),
40       ThreadPlanShouldStopHere(this), m_first_resume(true) {
41   SetFlagsToDefault();
42   SetupAvoidNoDebug(step_out_avoids_code_without_debug_info);
43 }
44 
45 ThreadPlanStepOverRange::~ThreadPlanStepOverRange() = default;
46 
47 void ThreadPlanStepOverRange::GetDescription(Stream *s,
48                                              lldb::DescriptionLevel level) {
49   auto PrintFailureIfAny = [&]() {
50     if (m_status.Success())
51       return;
52     s->Printf(" failed (%s)", m_status.AsCString());
53   };
54 
55   if (level == lldb::eDescriptionLevelBrief) {
56     s->Printf("step over");
57     PrintFailureIfAny();
58     return;
59   }
60 
61   s->Printf("Stepping over");
62   bool printed_line_info = false;
63   if (m_addr_context.line_entry.IsValid()) {
64     s->Printf(" line ");
65     m_addr_context.line_entry.DumpStopContext(s, false);
66     printed_line_info = true;
67   }
68 
69   if (!printed_line_info || level == eDescriptionLevelVerbose) {
70     s->Printf(" using ranges: ");
71     DumpRanges(s);
72   }
73 
74   PrintFailureIfAny();
75 
76   s->PutChar('.');
77 }
78 
79 void ThreadPlanStepOverRange::SetupAvoidNoDebug(
80     LazyBool step_out_avoids_code_without_debug_info) {
81   bool avoid_nodebug = true;
82   switch (step_out_avoids_code_without_debug_info) {
83   case eLazyBoolYes:
84     avoid_nodebug = true;
85     break;
86   case eLazyBoolNo:
87     avoid_nodebug = false;
88     break;
89   case eLazyBoolCalculate:
90     avoid_nodebug = m_thread.GetStepOutAvoidsNoDebug();
91     break;
92   }
93   if (avoid_nodebug)
94     GetFlags().Set(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
95   else
96     GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
97   // Step Over plans should always avoid no-debug on step in.  Seems like you
98   // shouldn't have to say this, but a tail call looks more like a step in that
99   // a step out, so we want to catch this case.
100   GetFlags().Set(ThreadPlanShouldStopHere::eStepInAvoidNoDebug);
101 }
102 
103 bool ThreadPlanStepOverRange::IsEquivalentContext(
104     const SymbolContext &context) {
105   // Match as much as is specified in the m_addr_context: This is a fairly
106   // loose sanity check.  Note, sometimes the target doesn't get filled in so I
107   // left out the target check.  And sometimes the module comes in as the .o
108   // file from the inlined range, so I left that out too...
109   if (m_addr_context.comp_unit) {
110     if (m_addr_context.comp_unit != context.comp_unit)
111       return false;
112     if (m_addr_context.function) {
113       if (m_addr_context.function != context.function)
114         return false;
115       // It is okay to return to a different block of a straight function, we
116       // only have to be more careful if returning from one inlined block to
117       // another.
118       if (m_addr_context.block->GetInlinedFunctionInfo() == nullptr &&
119           context.block->GetInlinedFunctionInfo() == nullptr)
120         return true;
121       return m_addr_context.block == context.block;
122     }
123   }
124   // Fall back to symbol if we have no decision from comp_unit/function/block.
125   return m_addr_context.symbol && m_addr_context.symbol == context.symbol;
126 }
127 
128 bool ThreadPlanStepOverRange::ShouldStop(Event *event_ptr) {
129   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
130 
131   if (log) {
132     StreamString s;
133     s.Address(
134         m_thread.GetRegisterContext()->GetPC(),
135         m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());
136     log->Printf("ThreadPlanStepOverRange reached %s.", s.GetData());
137   }
138 
139   // If we're out of the range but in the same frame or in our caller's frame
140   // then we should stop. When stepping out we only stop others if we are
141   // forcing running one thread.
142   bool stop_others = (m_stop_others == lldb::eOnlyThisThread);
143   ThreadPlanSP new_plan_sp;
144   FrameComparison frame_order = CompareCurrentFrameToStartFrame();
145 
146   if (frame_order == eFrameCompareOlder) {
147     // If we're in an older frame then we should stop.
148     //
149     // A caveat to this is if we think the frame is older but we're actually in
150     // a trampoline.
151     // I'm going to make the assumption that you wouldn't RETURN to a
152     // trampoline.  So if we are in a trampoline we think the frame is older
153     // because the trampoline confused the backtracer. As below, we step
154     // through first, and then try to figure out how to get back out again.
155 
156     new_plan_sp = m_thread.QueueThreadPlanForStepThrough(m_stack_id, false,
157                                                          stop_others, m_status);
158 
159     if (new_plan_sp && log)
160       log->Printf(
161           "Thought I stepped out, but in fact arrived at a trampoline.");
162   } else if (frame_order == eFrameCompareYounger) {
163     // Make sure we really are in a new frame.  Do that by unwinding and seeing
164     // if the start function really is our start function...
165     for (uint32_t i = 1;; ++i) {
166       StackFrameSP older_frame_sp = m_thread.GetStackFrameAtIndex(i);
167       if (!older_frame_sp) {
168         // We can't unwind the next frame we should just get out of here &
169         // stop...
170         break;
171       }
172 
173       const SymbolContext &older_context =
174           older_frame_sp->GetSymbolContext(eSymbolContextEverything);
175       if (IsEquivalentContext(older_context)) {
176         new_plan_sp = m_thread.QueueThreadPlanForStepOutNoShouldStop(
177             false, nullptr, true, stop_others, eVoteNo, eVoteNoOpinion, 0,
178             m_status, true);
179         break;
180       } else {
181         new_plan_sp = m_thread.QueueThreadPlanForStepThrough(
182             m_stack_id, false, stop_others, m_status);
183         // If we found a way through, then we should stop recursing.
184         if (new_plan_sp)
185           break;
186       }
187     }
188   } else {
189     // If we're still in the range, keep going.
190     if (InRange()) {
191       SetNextBranchBreakpoint();
192       return false;
193     }
194 
195     if (!InSymbol()) {
196       // This one is a little tricky.  Sometimes we may be in a stub or
197       // something similar, in which case we need to get out of there.  But if
198       // we are in a stub then it's likely going to be hard to get out from
199       // here.  It is probably easiest to step into the stub, and then it will
200       // be straight-forward to step out.
201       new_plan_sp = m_thread.QueueThreadPlanForStepThrough(
202           m_stack_id, false, stop_others, m_status);
203     } else {
204       // The current clang (at least through 424) doesn't always get the
205       // address range for the DW_TAG_inlined_subroutines right, so that when
206       // you leave the inlined range the line table says you are still in the
207       // source file of the inlining function.  This is bad, because now you
208       // are missing the stack frame for the function containing the inlining,
209       // and if you sensibly do "finish" to get out of this function you will
210       // instead exit the containing function. To work around this, we check
211       // whether we are still in the source file we started in, and if not
212       // assume it is an error, and push a plan to get us out of this line and
213       // back to the containing file.
214 
215       if (m_addr_context.line_entry.IsValid()) {
216         SymbolContext sc;
217         StackFrameSP frame_sp = m_thread.GetStackFrameAtIndex(0);
218         sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
219         if (sc.line_entry.IsValid()) {
220           if (sc.line_entry.original_file !=
221                   m_addr_context.line_entry.original_file &&
222               sc.comp_unit == m_addr_context.comp_unit &&
223               sc.function == m_addr_context.function) {
224             // Okay, find the next occurrence of this file in the line table:
225             LineTable *line_table = m_addr_context.comp_unit->GetLineTable();
226             if (line_table) {
227               Address cur_address = frame_sp->GetFrameCodeAddress();
228               uint32_t entry_idx;
229               LineEntry line_entry;
230               if (line_table->FindLineEntryByAddress(cur_address, line_entry,
231                                                      &entry_idx)) {
232                 LineEntry next_line_entry;
233                 bool step_past_remaining_inline = false;
234                 if (entry_idx > 0) {
235                   // We require the previous line entry and the current line
236                   // entry come from the same file. The other requirement is
237                   // that the previous line table entry be part of an inlined
238                   // block, we don't want to step past cases where people have
239                   // inlined some code fragment by using #include <source-
240                   // fragment.c> directly.
241                   LineEntry prev_line_entry;
242                   if (line_table->GetLineEntryAtIndex(entry_idx - 1,
243                                                       prev_line_entry) &&
244                       prev_line_entry.original_file ==
245                           line_entry.original_file) {
246                     SymbolContext prev_sc;
247                     Address prev_address =
248                         prev_line_entry.range.GetBaseAddress();
249                     prev_address.CalculateSymbolContext(&prev_sc);
250                     if (prev_sc.block) {
251                       Block *inlined_block =
252                           prev_sc.block->GetContainingInlinedBlock();
253                       if (inlined_block) {
254                         AddressRange inline_range;
255                         inlined_block->GetRangeContainingAddress(prev_address,
256                                                                  inline_range);
257                         if (!inline_range.ContainsFileAddress(cur_address)) {
258 
259                           step_past_remaining_inline = true;
260                         }
261                       }
262                     }
263                   }
264                 }
265 
266                 if (step_past_remaining_inline) {
267                   uint32_t look_ahead_step = 1;
268                   while (line_table->GetLineEntryAtIndex(
269                       entry_idx + look_ahead_step, next_line_entry)) {
270                     // Make sure we haven't wandered out of the function we
271                     // started from...
272                     Address next_line_address =
273                         next_line_entry.range.GetBaseAddress();
274                     Function *next_line_function =
275                         next_line_address.CalculateSymbolContextFunction();
276                     if (next_line_function != m_addr_context.function)
277                       break;
278 
279                     if (next_line_entry.original_file ==
280                         m_addr_context.line_entry.original_file) {
281                       const bool abort_other_plans = false;
282                       const RunMode stop_other_threads = RunMode::eAllThreads;
283                       lldb::addr_t cur_pc = m_thread.GetStackFrameAtIndex(0)
284                                                 ->GetRegisterContext()
285                                                 ->GetPC();
286                       AddressRange step_range(
287                           cur_pc,
288                           next_line_address.GetLoadAddress(&GetTarget()) -
289                               cur_pc);
290 
291                       new_plan_sp = m_thread.QueueThreadPlanForStepOverRange(
292                           abort_other_plans, step_range, sc, stop_other_threads,
293                           m_status);
294                       break;
295                     }
296                     look_ahead_step++;
297                   }
298                 }
299               }
300             }
301           }
302         }
303       }
304     }
305   }
306 
307   // If we get to this point, we're not going to use a previously set "next
308   // branch" breakpoint, so delete it:
309   ClearNextBranchBreakpoint();
310 
311   // If we haven't figured out something to do yet, then ask the ShouldStopHere
312   // callback:
313   if (!new_plan_sp) {
314     new_plan_sp = CheckShouldStopHereAndQueueStepOut(frame_order, m_status);
315   }
316 
317   if (!new_plan_sp)
318     m_no_more_plans = true;
319   else {
320     // Any new plan will be an implementation plan, so mark it private:
321     new_plan_sp->SetPrivate(true);
322     m_no_more_plans = false;
323   }
324 
325   if (!new_plan_sp) {
326     // For efficiencies sake, we know we're done here so we don't have to do
327     // this calculation again in MischiefManaged.
328     SetPlanComplete(m_status.Success());
329     return true;
330   } else
331     return false;
332 }
333 
334 bool ThreadPlanStepOverRange::DoPlanExplainsStop(Event *event_ptr) {
335   // For crashes, breakpoint hits, signals, etc, let the base plan (or some
336   // plan above us) handle the stop.  That way the user can see the stop, step
337   // around, and then when they are done, continue and have their step
338   // complete.  The exception is if we've hit our "run to next branch"
339   // breakpoint. Note, unlike the step in range plan, we don't mark ourselves
340   // complete if we hit an unexplained breakpoint/crash.
341 
342   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
343   StopInfoSP stop_info_sp = GetPrivateStopInfo();
344   bool return_value;
345 
346   if (stop_info_sp) {
347     StopReason reason = stop_info_sp->GetStopReason();
348 
349     if (reason == eStopReasonTrace) {
350       return_value = true;
351     } else if (reason == eStopReasonBreakpoint) {
352       return_value = NextRangeBreakpointExplainsStop(stop_info_sp);
353     } else {
354       if (log)
355         log->PutCString("ThreadPlanStepInRange got asked if it explains the "
356                         "stop for some reason other than step.");
357       return_value = false;
358     }
359   } else
360     return_value = true;
361 
362   return return_value;
363 }
364 
365 bool ThreadPlanStepOverRange::DoWillResume(lldb::StateType resume_state,
366                                            bool current_plan) {
367   if (resume_state != eStateSuspended && m_first_resume) {
368     m_first_resume = false;
369     if (resume_state == eStateStepping && current_plan) {
370       // See if we are about to step over an inlined call in the middle of the
371       // inlined stack, if so figure out its extents and reset our range to
372       // step over that.
373       bool in_inlined_stack = m_thread.DecrementCurrentInlinedDepth();
374       if (in_inlined_stack) {
375         Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
376         if (log)
377           log->Printf("ThreadPlanStepInRange::DoWillResume: adjusting range to "
378                       "the frame at inlined depth %d.",
379                       m_thread.GetCurrentInlinedDepth());
380         StackFrameSP stack_sp = m_thread.GetStackFrameAtIndex(0);
381         if (stack_sp) {
382           Block *frame_block = stack_sp->GetFrameBlock();
383           lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();
384           AddressRange my_range;
385           if (frame_block->GetRangeContainingLoadAddress(
386                   curr_pc, m_thread.GetProcess()->GetTarget(), my_range)) {
387             m_address_ranges.clear();
388             m_address_ranges.push_back(my_range);
389             if (log) {
390               StreamString s;
391               const InlineFunctionInfo *inline_info =
392                   frame_block->GetInlinedFunctionInfo();
393               const char *name;
394               if (inline_info)
395                 name =
396                     inline_info
397                         ->GetName(frame_block->CalculateSymbolContextFunction()
398                                       ->GetLanguage())
399                         .AsCString();
400               else
401                 name = "<unknown-notinlined>";
402 
403               s.Printf(
404                   "Stepping over inlined function \"%s\" in inlined stack: ",
405                   name);
406               DumpRanges(&s);
407               log->PutString(s.GetString());
408             }
409           }
410         }
411       }
412     }
413   }
414 
415   return true;
416 }
417