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