1 //===-- ThreadPlanStepRange.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/ThreadPlanStepRange.h"
10 #include "lldb/Breakpoint/BreakpointLocation.h"
11 #include "lldb/Breakpoint/BreakpointSite.h"
12 #include "lldb/Core/Disassembler.h"
13 #include "lldb/Symbol/Function.h"
14 #include "lldb/Symbol/Symbol.h"
15 #include "lldb/Target/ExecutionContext.h"
16 #include "lldb/Target/Process.h"
17 #include "lldb/Target/RegisterContext.h"
18 #include "lldb/Target/StopInfo.h"
19 #include "lldb/Target/Target.h"
20 #include "lldb/Target/Thread.h"
21 #include "lldb/Target/ThreadPlanRunToAddress.h"
22 #include "lldb/Utility/Log.h"
23 #include "lldb/Utility/Stream.h"
24 
25 using namespace lldb;
26 using namespace lldb_private;
27 
28 // ThreadPlanStepRange: Step through a stack range, either stepping over or
29 // into based on the value of \a type.
30 
31 ThreadPlanStepRange::ThreadPlanStepRange(ThreadPlanKind kind, const char *name,
32                                          Thread &thread,
33                                          const AddressRange &range,
34                                          const SymbolContext &addr_context,
35                                          lldb::RunMode stop_others,
36                                          bool given_ranges_only)
37     : ThreadPlan(kind, name, thread, eVoteNoOpinion, eVoteNoOpinion),
38       m_addr_context(addr_context), m_address_ranges(),
39       m_stop_others(stop_others), m_stack_id(), m_parent_stack_id(),
40       m_no_more_plans(false), m_first_run_event(true), m_use_fast_step(false),
41       m_given_ranges_only(given_ranges_only) {
42   m_use_fast_step = GetTarget().GetUseFastStepping();
43   AddRange(range);
44   m_stack_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
45   StackFrameSP parent_stack = m_thread.GetStackFrameAtIndex(1);
46   if (parent_stack)
47     m_parent_stack_id = parent_stack->GetStackID();
48 }
49 
50 ThreadPlanStepRange::~ThreadPlanStepRange() { ClearNextBranchBreakpoint(); }
51 
52 void ThreadPlanStepRange::DidPush() {
53   // See if we can find a "next range" breakpoint:
54   SetNextBranchBreakpoint();
55 }
56 
57 bool ThreadPlanStepRange::ValidatePlan(Stream *error) {
58   if (m_could_not_resolve_hw_bp) {
59     if (error)
60       error->PutCString(
61           "Could not create hardware breakpoint for thread plan.");
62     return false;
63   }
64   return true;
65 }
66 
67 Vote ThreadPlanStepRange::ShouldReportStop(Event *event_ptr) {
68   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
69 
70   const Vote vote = IsPlanComplete() ? eVoteYes : eVoteNo;
71   LLDB_LOGF(log, "ThreadPlanStepRange::ShouldReportStop() returning vote %i\n",
72             vote);
73   return vote;
74 }
75 
76 void ThreadPlanStepRange::AddRange(const AddressRange &new_range) {
77   // For now I'm just adding the ranges.  At some point we may want to condense
78   // the ranges if they overlap, though I don't think it is likely to be very
79   // important.
80   m_address_ranges.push_back(new_range);
81 
82   // Fill the slot for this address range with an empty DisassemblerSP in the
83   // instruction ranges. I want the indices to match, but I don't want to do
84   // the work to disassemble this range if I don't step into it.
85   m_instruction_ranges.push_back(DisassemblerSP());
86 }
87 
88 void ThreadPlanStepRange::DumpRanges(Stream *s) {
89   size_t num_ranges = m_address_ranges.size();
90   if (num_ranges == 1) {
91     m_address_ranges[0].Dump(s, m_thread.CalculateTarget().get(),
92                              Address::DumpStyleLoadAddress);
93   } else {
94     for (size_t i = 0; i < num_ranges; i++) {
95       s->Printf(" %" PRIu64 ": ", uint64_t(i));
96       m_address_ranges[i].Dump(s, m_thread.CalculateTarget().get(),
97                                Address::DumpStyleLoadAddress);
98     }
99   }
100 }
101 
102 bool ThreadPlanStepRange::InRange() {
103   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
104   bool ret_value = false;
105 
106   lldb::addr_t pc_load_addr = m_thread.GetRegisterContext()->GetPC();
107 
108   size_t num_ranges = m_address_ranges.size();
109   for (size_t i = 0; i < num_ranges; i++) {
110     ret_value = m_address_ranges[i].ContainsLoadAddress(
111         pc_load_addr, m_thread.CalculateTarget().get());
112     if (ret_value)
113       break;
114   }
115 
116   if (!ret_value && !m_given_ranges_only) {
117     // See if we've just stepped to another part of the same line number...
118     StackFrame *frame = m_thread.GetStackFrameAtIndex(0).get();
119 
120     SymbolContext new_context(
121         frame->GetSymbolContext(eSymbolContextEverything));
122     if (m_addr_context.line_entry.IsValid() &&
123         new_context.line_entry.IsValid()) {
124       if (m_addr_context.line_entry.original_file ==
125           new_context.line_entry.original_file) {
126         if (m_addr_context.line_entry.line == new_context.line_entry.line) {
127           m_addr_context = new_context;
128           const bool include_inlined_functions =
129               GetKind() == eKindStepOverRange;
130           AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange(
131               include_inlined_functions));
132           ret_value = true;
133           if (log) {
134             StreamString s;
135             m_addr_context.line_entry.Dump(&s, m_thread.CalculateTarget().get(),
136                                            true, Address::DumpStyleLoadAddress,
137                                            Address::DumpStyleLoadAddress, true);
138 
139             LLDB_LOGF(
140                 log,
141                 "Step range plan stepped to another range of same line: %s",
142                 s.GetData());
143           }
144         } else if (new_context.line_entry.line == 0) {
145           new_context.line_entry.line = m_addr_context.line_entry.line;
146           m_addr_context = new_context;
147           const bool include_inlined_functions =
148               GetKind() == eKindStepOverRange;
149           AddRange(m_addr_context.line_entry.GetSameLineContiguousAddressRange(
150               include_inlined_functions));
151           ret_value = true;
152           if (log) {
153             StreamString s;
154             m_addr_context.line_entry.Dump(&s, m_thread.CalculateTarget().get(),
155                                            true, Address::DumpStyleLoadAddress,
156                                            Address::DumpStyleLoadAddress, true);
157 
158             LLDB_LOGF(log,
159                       "Step range plan stepped to a range at linenumber 0 "
160                       "stepping through that range: %s",
161                       s.GetData());
162           }
163         } else if (new_context.line_entry.range.GetBaseAddress().GetLoadAddress(
164                        m_thread.CalculateTarget().get()) != pc_load_addr) {
165           // Another thing that sometimes happens here is that we step out of
166           // one line into the MIDDLE of another line.  So far I mostly see
167           // this due to bugs in the debug information. But we probably don't
168           // want to be in the middle of a line range, so in that case reset
169           // the stepping range to the line we've stepped into the middle of
170           // and continue.
171           m_addr_context = new_context;
172           m_address_ranges.clear();
173           AddRange(m_addr_context.line_entry.range);
174           ret_value = true;
175           if (log) {
176             StreamString s;
177             m_addr_context.line_entry.Dump(&s, m_thread.CalculateTarget().get(),
178                                            true, Address::DumpStyleLoadAddress,
179                                            Address::DumpStyleLoadAddress, true);
180 
181             LLDB_LOGF(log,
182                       "Step range plan stepped to the middle of new "
183                       "line(%d): %s, continuing to clear this line.",
184                       new_context.line_entry.line, s.GetData());
185           }
186         }
187       }
188     }
189   }
190 
191   if (!ret_value && log)
192     LLDB_LOGF(log, "Step range plan out of range to 0x%" PRIx64, pc_load_addr);
193 
194   return ret_value;
195 }
196 
197 bool ThreadPlanStepRange::InSymbol() {
198   lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
199   if (m_addr_context.function != nullptr) {
200     return m_addr_context.function->GetAddressRange().ContainsLoadAddress(
201         cur_pc, m_thread.CalculateTarget().get());
202   } else if (m_addr_context.symbol && m_addr_context.symbol->ValueIsAddress()) {
203     AddressRange range(m_addr_context.symbol->GetAddressRef(),
204                        m_addr_context.symbol->GetByteSize());
205     return range.ContainsLoadAddress(cur_pc, m_thread.CalculateTarget().get());
206   }
207   return false;
208 }
209 
210 // FIXME: This should also handle inlining if we aren't going to do inlining in
211 // the
212 // main stack.
213 //
214 // Ideally we should remember the whole stack frame list, and then compare that
215 // to the current list.
216 
217 lldb::FrameComparison ThreadPlanStepRange::CompareCurrentFrameToStartFrame() {
218   FrameComparison frame_order;
219 
220   StackID cur_frame_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
221 
222   if (cur_frame_id == m_stack_id) {
223     frame_order = eFrameCompareEqual;
224   } else if (cur_frame_id < m_stack_id) {
225     frame_order = eFrameCompareYounger;
226   } else {
227     StackFrameSP cur_parent_frame = m_thread.GetStackFrameAtIndex(1);
228     StackID cur_parent_id;
229     if (cur_parent_frame)
230       cur_parent_id = cur_parent_frame->GetStackID();
231     if (m_parent_stack_id.IsValid() && cur_parent_id.IsValid() &&
232         m_parent_stack_id == cur_parent_id)
233       frame_order = eFrameCompareSameParent;
234     else
235       frame_order = eFrameCompareOlder;
236   }
237   return frame_order;
238 }
239 
240 bool ThreadPlanStepRange::StopOthers() {
241   return (m_stop_others == lldb::eOnlyThisThread ||
242           m_stop_others == lldb::eOnlyDuringStepping);
243 }
244 
245 InstructionList *ThreadPlanStepRange::GetInstructionsForAddress(
246     lldb::addr_t addr, size_t &range_index, size_t &insn_offset) {
247   size_t num_ranges = m_address_ranges.size();
248   for (size_t i = 0; i < num_ranges; i++) {
249     if (m_address_ranges[i].ContainsLoadAddress(addr, &GetTarget())) {
250       // Some joker added a zero size range to the stepping range...
251       if (m_address_ranges[i].GetByteSize() == 0)
252         return nullptr;
253 
254       if (!m_instruction_ranges[i]) {
255         // Disassemble the address range given:
256         ExecutionContext exe_ctx(m_thread.GetProcess());
257         const char *plugin_name = nullptr;
258         const char *flavor = nullptr;
259         const bool prefer_file_cache = true;
260         m_instruction_ranges[i] = Disassembler::DisassembleRange(
261             GetTarget().GetArchitecture(), plugin_name, flavor, exe_ctx,
262             m_address_ranges[i], prefer_file_cache);
263       }
264       if (!m_instruction_ranges[i])
265         return nullptr;
266       else {
267         // Find where we are in the instruction list as well.  If we aren't at
268         // an instruction, return nullptr. In this case, we're probably lost,
269         // and shouldn't try to do anything fancy.
270 
271         insn_offset =
272             m_instruction_ranges[i]
273                 ->GetInstructionList()
274                 .GetIndexOfInstructionAtLoadAddress(addr, GetTarget());
275         if (insn_offset == UINT32_MAX)
276           return nullptr;
277         else {
278           range_index = i;
279           return &m_instruction_ranges[i]->GetInstructionList();
280         }
281       }
282     }
283   }
284   return nullptr;
285 }
286 
287 void ThreadPlanStepRange::ClearNextBranchBreakpoint() {
288   if (m_next_branch_bp_sp) {
289     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
290     LLDB_LOGF(log, "Removing next branch breakpoint: %d.",
291               m_next_branch_bp_sp->GetID());
292     GetTarget().RemoveBreakpointByID(m_next_branch_bp_sp->GetID());
293     m_next_branch_bp_sp.reset();
294     m_could_not_resolve_hw_bp = false;
295   }
296 }
297 
298 bool ThreadPlanStepRange::SetNextBranchBreakpoint() {
299   if (m_next_branch_bp_sp)
300     return true;
301 
302   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
303   // Stepping through ranges using breakpoints doesn't work yet, but with this
304   // off we fall back to instruction single stepping.
305   if (!m_use_fast_step)
306     return false;
307 
308   lldb::addr_t cur_addr = GetThread().GetRegisterContext()->GetPC();
309   // Find the current address in our address ranges, and fetch the disassembly
310   // if we haven't already:
311   size_t pc_index;
312   size_t range_index;
313   InstructionList *instructions =
314       GetInstructionsForAddress(cur_addr, range_index, pc_index);
315   if (instructions == nullptr)
316     return false;
317   else {
318     Target &target = GetThread().GetProcess()->GetTarget();
319     const bool ignore_calls = GetKind() == eKindStepOverRange;
320     uint32_t branch_index =
321         instructions->GetIndexOfNextBranchInstruction(pc_index, target,
322                                                       ignore_calls);
323 
324     Address run_to_address;
325 
326     // If we didn't find a branch, run to the end of the range.
327     if (branch_index == UINT32_MAX) {
328       uint32_t last_index = instructions->GetSize() - 1;
329       if (last_index - pc_index > 1) {
330         InstructionSP last_inst =
331             instructions->GetInstructionAtIndex(last_index);
332         size_t last_inst_size = last_inst->GetOpcode().GetByteSize();
333         run_to_address = last_inst->GetAddress();
334         run_to_address.Slide(last_inst_size);
335       }
336     } else if (branch_index - pc_index > 1) {
337       run_to_address =
338           instructions->GetInstructionAtIndex(branch_index)->GetAddress();
339     }
340 
341     if (run_to_address.IsValid()) {
342       const bool is_internal = true;
343       m_next_branch_bp_sp =
344           GetTarget().CreateBreakpoint(run_to_address, is_internal, false);
345       if (m_next_branch_bp_sp) {
346 
347         if (m_next_branch_bp_sp->IsHardware() &&
348             !m_next_branch_bp_sp->HasResolvedLocations())
349           m_could_not_resolve_hw_bp = true;
350 
351         if (log) {
352           lldb::break_id_t bp_site_id = LLDB_INVALID_BREAK_ID;
353           BreakpointLocationSP bp_loc =
354               m_next_branch_bp_sp->GetLocationAtIndex(0);
355           if (bp_loc) {
356             BreakpointSiteSP bp_site = bp_loc->GetBreakpointSite();
357             if (bp_site) {
358               bp_site_id = bp_site->GetID();
359             }
360           }
361           LLDB_LOGF(log,
362                     "ThreadPlanStepRange::SetNextBranchBreakpoint - Setting "
363                     "breakpoint %d (site %d) to run to address 0x%" PRIx64,
364                     m_next_branch_bp_sp->GetID(), bp_site_id,
365                     run_to_address.GetLoadAddress(
366                         &m_thread.GetProcess()->GetTarget()));
367         }
368 
369         m_next_branch_bp_sp->SetThreadID(m_thread.GetID());
370         m_next_branch_bp_sp->SetBreakpointKind("next-branch-location");
371 
372         return true;
373       } else
374         return false;
375     }
376   }
377   return false;
378 }
379 
380 bool ThreadPlanStepRange::NextRangeBreakpointExplainsStop(
381     lldb::StopInfoSP stop_info_sp) {
382   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
383   if (!m_next_branch_bp_sp)
384     return false;
385 
386   break_id_t bp_site_id = stop_info_sp->GetValue();
387   BreakpointSiteSP bp_site_sp =
388       m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id);
389   if (!bp_site_sp)
390     return false;
391   else if (!bp_site_sp->IsBreakpointAtThisSite(m_next_branch_bp_sp->GetID()))
392     return false;
393   else {
394     // If we've hit the next branch breakpoint, then clear it.
395     size_t num_owners = bp_site_sp->GetNumberOfOwners();
396     bool explains_stop = true;
397     // If all the owners are internal, then we are probably just stepping over
398     // this range from multiple threads, or multiple frames, so we want to
399     // continue.  If one is not internal, then we should not explain the stop,
400     // and let the user breakpoint handle the stop.
401     for (size_t i = 0; i < num_owners; i++) {
402       if (!bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint().IsInternal()) {
403         explains_stop = false;
404         break;
405       }
406     }
407     LLDB_LOGF(log,
408               "ThreadPlanStepRange::NextRangeBreakpointExplainsStop - Hit "
409               "next range breakpoint which has %" PRIu64
410               " owners - explains stop: %u.",
411               (uint64_t)num_owners, explains_stop);
412     ClearNextBranchBreakpoint();
413     return explains_stop;
414   }
415 }
416 
417 bool ThreadPlanStepRange::WillStop() { return true; }
418 
419 StateType ThreadPlanStepRange::GetPlanRunState() {
420   if (m_next_branch_bp_sp)
421     return eStateRunning;
422   else
423     return eStateStepping;
424 }
425 
426 bool ThreadPlanStepRange::MischiefManaged() {
427   // If we have pushed some plans between ShouldStop & MischiefManaged, then
428   // we're not done...
429   // I do this check first because we might have stepped somewhere that will
430   // fool InRange into
431   // thinking it needs to step past the end of that line.  This happens, for
432   // instance, when stepping over inlined code that is in the middle of the
433   // current line.
434 
435   if (!m_no_more_plans)
436     return false;
437 
438   bool done = true;
439   if (!IsPlanComplete()) {
440     if (InRange()) {
441       done = false;
442     } else {
443       FrameComparison frame_order = CompareCurrentFrameToStartFrame();
444       done = (frame_order != eFrameCompareOlder) ? m_no_more_plans : true;
445     }
446   }
447 
448   if (done) {
449     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
450     LLDB_LOGF(log, "Completed step through range plan.");
451     ClearNextBranchBreakpoint();
452     ThreadPlan::MischiefManaged();
453     return true;
454   } else {
455     return false;
456   }
457 }
458 
459 bool ThreadPlanStepRange::IsPlanStale() {
460   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
461   FrameComparison frame_order = CompareCurrentFrameToStartFrame();
462 
463   if (frame_order == eFrameCompareOlder) {
464     if (log) {
465       LLDB_LOGF(log, "ThreadPlanStepRange::IsPlanStale returning true, we've "
466                      "stepped out.");
467     }
468     return true;
469   } else if (frame_order == eFrameCompareEqual && InSymbol()) {
470     // If we are not in a place we should step through, we've gotten stale. One
471     // tricky bit here is that some stubs don't push a frame, so we should.
472     // check that we are in the same symbol.
473     if (!InRange()) {
474       // Set plan Complete when we reach next instruction just after the range
475       lldb::addr_t addr = m_thread.GetRegisterContext()->GetPC() - 1;
476       size_t num_ranges = m_address_ranges.size();
477       for (size_t i = 0; i < num_ranges; i++) {
478         bool in_range = m_address_ranges[i].ContainsLoadAddress(
479             addr, m_thread.CalculateTarget().get());
480         if (in_range) {
481           SetPlanComplete();
482         }
483       }
484       return true;
485     }
486   }
487   return false;
488 }
489