1 //===-- ThreadPlanStepUntil.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/ThreadPlanStepUntil.h"
10 
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Symbol/SymbolContextScope.h"
13 #include "lldb/Target/Process.h"
14 #include "lldb/Target/RegisterContext.h"
15 #include "lldb/Target/StopInfo.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Utility/Log.h"
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 
22 //----------------------------------------------------------------------
23 // ThreadPlanStepUntil: Run until we reach a given line number or step out of
24 // the current frame
25 //----------------------------------------------------------------------
26 
27 ThreadPlanStepUntil::ThreadPlanStepUntil(Thread &thread,
28                                          lldb::addr_t *address_list,
29                                          size_t num_addresses, bool stop_others,
30                                          uint32_t frame_idx)
31     : ThreadPlan(ThreadPlan::eKindStepUntil, "Step until", thread,
32                  eVoteNoOpinion, eVoteNoOpinion),
33       m_step_from_insn(LLDB_INVALID_ADDRESS),
34       m_return_bp_id(LLDB_INVALID_BREAK_ID),
35       m_return_addr(LLDB_INVALID_ADDRESS), m_stepped_out(false),
36       m_should_stop(false), m_ran_analyze(false), m_explains_stop(false),
37       m_until_points(), m_stop_others(stop_others) {
38   // Stash away our "until" addresses:
39   TargetSP target_sp(m_thread.CalculateTarget());
40 
41   StackFrameSP frame_sp(m_thread.GetStackFrameAtIndex(frame_idx));
42   if (frame_sp) {
43     m_step_from_insn = frame_sp->GetStackID().GetPC();
44     lldb::user_id_t thread_id = m_thread.GetID();
45 
46     // Find the return address and set a breakpoint there:
47     // FIXME - can we do this more securely if we know first_insn?
48 
49     StackFrameSP return_frame_sp(m_thread.GetStackFrameAtIndex(frame_idx + 1));
50     if (return_frame_sp) {
51       // TODO: add inline functionality
52       m_return_addr = return_frame_sp->GetStackID().GetPC();
53       Breakpoint *return_bp =
54           target_sp->CreateBreakpoint(m_return_addr, true, false).get();
55 
56       if (return_bp != nullptr) {
57         if (return_bp->IsHardware() && !return_bp->HasResolvedLocations())
58           m_could_not_resolve_hw_bp = true;
59         return_bp->SetThreadID(thread_id);
60         m_return_bp_id = return_bp->GetID();
61         return_bp->SetBreakpointKind("until-return-backstop");
62       }
63     }
64 
65     m_stack_id = frame_sp->GetStackID();
66 
67     // Now set breakpoints on all our return addresses:
68     for (size_t i = 0; i < num_addresses; i++) {
69       Breakpoint *until_bp =
70           target_sp->CreateBreakpoint(address_list[i], true, false).get();
71       if (until_bp != nullptr) {
72         until_bp->SetThreadID(thread_id);
73         m_until_points[address_list[i]] = until_bp->GetID();
74         until_bp->SetBreakpointKind("until-target");
75       } else {
76         m_until_points[address_list[i]] = LLDB_INVALID_BREAK_ID;
77       }
78     }
79   }
80 }
81 
82 ThreadPlanStepUntil::~ThreadPlanStepUntil() { Clear(); }
83 
84 void ThreadPlanStepUntil::Clear() {
85   TargetSP target_sp(m_thread.CalculateTarget());
86   if (target_sp) {
87     if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
88       target_sp->RemoveBreakpointByID(m_return_bp_id);
89       m_return_bp_id = LLDB_INVALID_BREAK_ID;
90     }
91 
92     until_collection::iterator pos, end = m_until_points.end();
93     for (pos = m_until_points.begin(); pos != end; pos++) {
94       target_sp->RemoveBreakpointByID((*pos).second);
95     }
96   }
97   m_until_points.clear();
98   m_could_not_resolve_hw_bp = false;
99 }
100 
101 void ThreadPlanStepUntil::GetDescription(Stream *s,
102                                          lldb::DescriptionLevel level) {
103   if (level == lldb::eDescriptionLevelBrief) {
104     s->Printf("step until");
105     if (m_stepped_out)
106       s->Printf(" - stepped out");
107   } else {
108     if (m_until_points.size() == 1)
109       s->Printf("Stepping from address 0x%" PRIx64 " until we reach 0x%" PRIx64
110                 " using breakpoint %d",
111                 (uint64_t)m_step_from_insn,
112                 (uint64_t)(*m_until_points.begin()).first,
113                 (*m_until_points.begin()).second);
114     else {
115       until_collection::iterator pos, end = m_until_points.end();
116       s->Printf("Stepping from address 0x%" PRIx64 " until we reach one of:",
117                 (uint64_t)m_step_from_insn);
118       for (pos = m_until_points.begin(); pos != end; pos++) {
119         s->Printf("\n\t0x%" PRIx64 " (bp: %d)", (uint64_t)(*pos).first,
120                   (*pos).second);
121       }
122     }
123     s->Printf(" stepped out address is 0x%" PRIx64 ".",
124               (uint64_t)m_return_addr);
125   }
126 }
127 
128 bool ThreadPlanStepUntil::ValidatePlan(Stream *error) {
129   if (m_could_not_resolve_hw_bp) {
130     if (error)
131       error->PutCString(
132           "Could not create hardware breakpoint for thread plan.");
133     return false;
134   } else if (m_return_bp_id == LLDB_INVALID_BREAK_ID) {
135     if (error)
136       error->PutCString("Could not create return breakpoint.");
137     return false;
138   } else {
139     until_collection::iterator pos, end = m_until_points.end();
140     for (pos = m_until_points.begin(); pos != end; pos++) {
141       if (!LLDB_BREAK_ID_IS_VALID((*pos).second))
142         return false;
143     }
144     return true;
145   }
146 }
147 
148 void ThreadPlanStepUntil::AnalyzeStop() {
149   if (m_ran_analyze)
150     return;
151 
152   StopInfoSP stop_info_sp = GetPrivateStopInfo();
153   m_should_stop = true;
154   m_explains_stop = false;
155 
156   if (stop_info_sp) {
157     StopReason reason = stop_info_sp->GetStopReason();
158 
159     if (reason == eStopReasonBreakpoint) {
160       // If this is OUR breakpoint, we're fine, otherwise we don't know why
161       // this happened...
162       BreakpointSiteSP this_site =
163           m_thread.GetProcess()->GetBreakpointSiteList().FindByID(
164               stop_info_sp->GetValue());
165       if (!this_site) {
166         m_explains_stop = false;
167         return;
168       }
169 
170       if (this_site->IsBreakpointAtThisSite(m_return_bp_id)) {
171         // If we are at our "step out" breakpoint, and the stack depth has
172         // shrunk, then this is indeed our stop. If the stack depth has grown,
173         // then we've hit our step out breakpoint recursively. If we are the
174         // only breakpoint at that location, then we do explain the stop, and
175         // we'll just continue. If there was another breakpoint here, then we
176         // don't explain the stop, but we won't mark ourselves Completed,
177         // because maybe that breakpoint will continue, and then we'll finish
178         // the "until".
179         bool done;
180         StackID cur_frame_zero_id;
181 
182         done = (m_stack_id < cur_frame_zero_id);
183 
184         if (done) {
185           m_stepped_out = true;
186           SetPlanComplete();
187         } else
188           m_should_stop = false;
189 
190         if (this_site->GetNumberOfOwners() == 1)
191           m_explains_stop = true;
192         else
193           m_explains_stop = false;
194         return;
195       } else {
196         // Check if we've hit one of our "until" breakpoints.
197         until_collection::iterator pos, end = m_until_points.end();
198         for (pos = m_until_points.begin(); pos != end; pos++) {
199           if (this_site->IsBreakpointAtThisSite((*pos).second)) {
200             // If we're at the right stack depth, then we're done.
201 
202             bool done;
203             StackID frame_zero_id =
204                 m_thread.GetStackFrameAtIndex(0)->GetStackID();
205 
206             if (frame_zero_id == m_stack_id)
207               done = true;
208             else if (frame_zero_id < m_stack_id)
209               done = false;
210             else {
211               StackFrameSP older_frame_sp = m_thread.GetStackFrameAtIndex(1);
212 
213               // But if we can't even unwind one frame we should just get out
214               // of here & stop...
215               if (older_frame_sp) {
216                 const SymbolContext &older_context =
217                     older_frame_sp->GetSymbolContext(eSymbolContextEverything);
218                 SymbolContext stack_context;
219                 m_stack_id.GetSymbolContextScope()->CalculateSymbolContext(
220                     &stack_context);
221 
222                 done = (older_context == stack_context);
223               } else
224                 done = false;
225             }
226 
227             if (done)
228               SetPlanComplete();
229             else
230               m_should_stop = false;
231 
232             // Otherwise we've hit this breakpoint recursively.  If we're the
233             // only breakpoint here, then we do explain the stop, and we'll
234             // continue. If not then we should let higher plans handle this
235             // stop.
236             if (this_site->GetNumberOfOwners() == 1)
237               m_explains_stop = true;
238             else {
239               m_should_stop = true;
240               m_explains_stop = false;
241             }
242             return;
243           }
244         }
245       }
246       // If we get here we haven't hit any of our breakpoints, so let the
247       // higher plans take care of the stop.
248       m_explains_stop = false;
249       return;
250     } else if (IsUsuallyUnexplainedStopReason(reason)) {
251       m_explains_stop = false;
252     } else {
253       m_explains_stop = true;
254     }
255   }
256 }
257 
258 bool ThreadPlanStepUntil::DoPlanExplainsStop(Event *event_ptr) {
259   // We don't explain signals or breakpoints (breakpoints that handle stepping
260   // in or out will be handled by a child plan.
261   AnalyzeStop();
262   return m_explains_stop;
263 }
264 
265 bool ThreadPlanStepUntil::ShouldStop(Event *event_ptr) {
266   // If we've told our self in ExplainsStop that we plan to continue, then do
267   // so here.  Otherwise, as long as this thread has stopped for a reason, we
268   // will stop.
269 
270   StopInfoSP stop_info_sp = GetPrivateStopInfo();
271   if (!stop_info_sp || stop_info_sp->GetStopReason() == eStopReasonNone)
272     return false;
273 
274   AnalyzeStop();
275   return m_should_stop;
276 }
277 
278 bool ThreadPlanStepUntil::StopOthers() { return m_stop_others; }
279 
280 StateType ThreadPlanStepUntil::GetPlanRunState() { return eStateRunning; }
281 
282 bool ThreadPlanStepUntil::DoWillResume(StateType resume_state,
283                                        bool current_plan) {
284   if (current_plan) {
285     TargetSP target_sp(m_thread.CalculateTarget());
286     if (target_sp) {
287       Breakpoint *return_bp =
288           target_sp->GetBreakpointByID(m_return_bp_id).get();
289       if (return_bp != nullptr)
290         return_bp->SetEnabled(true);
291 
292       until_collection::iterator pos, end = m_until_points.end();
293       for (pos = m_until_points.begin(); pos != end; pos++) {
294         Breakpoint *until_bp =
295             target_sp->GetBreakpointByID((*pos).second).get();
296         if (until_bp != nullptr)
297           until_bp->SetEnabled(true);
298       }
299     }
300   }
301 
302   m_should_stop = true;
303   m_ran_analyze = false;
304   m_explains_stop = false;
305   return true;
306 }
307 
308 bool ThreadPlanStepUntil::WillStop() {
309   TargetSP target_sp(m_thread.CalculateTarget());
310   if (target_sp) {
311     Breakpoint *return_bp = target_sp->GetBreakpointByID(m_return_bp_id).get();
312     if (return_bp != nullptr)
313       return_bp->SetEnabled(false);
314 
315     until_collection::iterator pos, end = m_until_points.end();
316     for (pos = m_until_points.begin(); pos != end; pos++) {
317       Breakpoint *until_bp = target_sp->GetBreakpointByID((*pos).second).get();
318       if (until_bp != nullptr)
319         until_bp->SetEnabled(false);
320     }
321   }
322   return true;
323 }
324 
325 bool ThreadPlanStepUntil::MischiefManaged() {
326   // I'm letting "PlanExplainsStop" do all the work, and just reporting that
327   // here.
328   bool done = false;
329   if (IsPlanComplete()) {
330     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
331     if (log)
332       log->Printf("Completed step until plan.");
333 
334     Clear();
335     done = true;
336   }
337   if (done)
338     ThreadPlan::MischiefManaged();
339 
340   return done;
341 }
342