1#############################################################################
2# This script contains two trivial examples of simple "scripted step" classes.
3# To fully understand how the lldb "Thread Plan" architecture works, read the
4# comments at the beginning of ThreadPlan.h in the lldb sources.  The python
5# interface is a reduced version of the full internal mechanism, but captures
6# most of the power with a much simpler interface.
7#
8# But I'll attempt a brief summary here.
9# Stepping in lldb is done independently for each thread.  Moreover, the stepping
10# operations are stackable.  So for instance if you did a "step over", and in
11# the course of stepping over you hit a breakpoint, stopped and stepped again,
12# the first "step-over" would be suspended, and the new step operation would
13# be enqueued.  Then if that step over caused the program to hit another breakpoint,
14# lldb would again suspend the second step and return control to the user, so
15# now there are two pending step overs.  Etc. with all the other stepping
16# operations.  Then if you hit "continue" the bottom-most step-over would complete,
17# and another continue would complete the first "step-over".
18#
19# lldb represents this system with a stack of "Thread Plans".  Each time a new
20# stepping operation is requested, a new plan is pushed on the stack.  When the
21# operation completes, it is pushed off the stack.
22#
23# The bottom-most plan in the stack is the immediate controller of stepping,
24# most importantly, when the process resumes, the bottom most plan will get
25# asked whether to set the program running freely, or to instruction-single-step
26# the current thread.  In the scripted interface, you indicate this by returning
27# False or True respectively from the should_step method.
28#
29# Each time the process stops the thread plan stack for each thread that stopped
30# "for a reason", Ii.e. a single-step completed on that thread, or a breakpoint
31# was hit), is queried to determine how to proceed, starting from the most
32# recently pushed plan, in two stages:
33#
34# 1) Each plan is asked if it "explains" the stop.  The first plan to claim the
35#    stop wins.  In scripted Thread Plans, this is done by returning True from
36#    the "explains_stop method.  This is how, for instance, control is returned
37#    to the User when the "step-over" plan hits a breakpoint.  The step-over
38#    plan doesn't explain the breakpoint stop, so it returns false, and the
39#    breakpoint hit is propagated up the stack to the "base" thread plan, which
40#    is the one that handles random breakpoint hits.
41#
42# 2) Then the plan that won the first round is asked if the process should stop.
43#    This is done in the "should_stop" method.  The scripted plans actually do
44#    three jobs in should_stop:
45#      a) They determine if they have completed their job or not.  If they have
46#         they indicate that by calling SetPlanComplete on their thread plan.
47#      b) They decide whether they want to return control to the user or not.
48#         They do this by returning True or False respectively.
49#      c) If they are not done, they set up whatever machinery they will use
50#         the next time the thread continues.
51#
52#    Note that deciding to return control to the user, and deciding your plan
53#    is done, are orthgonal operations.  You could set up the next phase of
54#    stepping, and then return True from should_stop, and when the user next
55#    "continued" the process your plan would resume control.  Of course, the
56#    user might also "step-over" or some other operation that would push a
57#    different plan, which would take control till it was done.
58#
59#    One other detail you should be aware of, if the plan below you on the
60#    stack was done, then it will be popped and the next plan will take control
61#    and its "should_stop" will be called.
62#
63#    Note also, there should be another method called when your plan is popped,
64#    to allow you to do whatever cleanup is required.  I haven't gotten to that
65#    yet.  For now you should do that at the same time you mark your plan complete.
66#
67# Both examples show stepping through an address range for 20 bytes from the
68# current PC.  The first one does it by single stepping and checking a condition.
69# It doesn't, however handle the case where you step into another frame while
70# still in the current range in the starting frame.
71#
72# That is better handled in the second example by using the built-in StepOverRange
73# thread plan.
74#
75# To use these stepping modes, you would do:
76#
77#     (lldb) command script import scripted_step.py
78#     (lldb) thread step-scripted -C scripted_step.SimpleStep
79# or
80#
81#     (lldb) thread step-scripted -C scripted_step.StepWithPlan
82
83import lldb
84
85class SimpleStep:
86    def __init__ (self, thread_plan, dict):
87        self.thread_plan = thread_plan
88        self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPC()
89
90    def explains_stop (self, event):
91        # We are stepping, so if we stop for any other reason, it isn't
92        # because of us.
93        if self.thread_plan.GetThread().GetStopReason()== lldb.eStopReasonTrace:
94            return True
95        else:
96            return False
97
98    def should_stop (self, event):
99        cur_pc = self.thread_plan.GetThread().GetFrameAtIndex(0).GetPC()
100
101        if cur_pc < self.start_address or cur_pc >= self.start_address + 20:
102            self.thread_plan.SetPlanComplete(True)
103            return True
104        else:
105            return False
106
107    def should_step (self):
108        return True
109
110class StepWithPlan:
111    def __init__ (self, thread_plan, dict):
112        self.thread_plan = thread_plan
113        self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPCAddress()
114        self.step_thread_plan =thread_plan.QueueThreadPlanForStepOverRange(self.start_address, 20);
115
116    def explains_stop (self, event):
117        # Since all I'm doing is running a plan, I will only ever get askedthis
118        # if myplan doesn't explain the stop, and in that caseI don'teither.
119        return False
120
121    def should_stop (self, event):
122        if self.step_thread_plan.IsPlanComplete():
123            self.thread_plan.SetPlanComplete(True)
124            return True
125        else:
126            return False
127
128    def should_step (self):
129        return False
130
131# Here's another example which does "step over" through the current function,
132# and when it stops at each line, it checks some condition (in this example the
133# value of a variable) and stops if that condition is true.
134
135class StepCheckingCondition:
136    def __init__ (self, thread_plan, dict):
137        self.thread_plan = thread_plan
138        self.start_frame = thread_plan.GetThread().GetFrameAtIndex(0)
139        self.queue_next_plan()
140
141    def queue_next_plan (self):
142        cur_frame = self.thread_plan.GetThread().GetFrameAtIndex(0)
143        cur_line_entry = cur_frame.GetLineEntry()
144        start_address = cur_line_entry.GetStartAddress()
145        end_address = cur_line_entry.GetEndAddress()
146        line_range = end_address.GetFileAddress() - start_address.GetFileAddress()
147        self.step_thread_plan = self.thread_plan.QueueThreadPlanForStepOverRange(start_address, line_range)
148
149    def explains_stop (self, event):
150        # We are stepping, so if we stop for any other reason, it isn't
151        # because of us.
152        return False
153
154    def should_stop (self, event):
155        if not self.step_thread_plan.IsPlanComplete():
156            return False
157
158        frame = self.thread_plan.GetThread().GetFrameAtIndex(0)
159        if not self.start_frame.IsEqual(frame):
160            self.thread_plan.SetPlanComplete(True)
161            return True
162
163        # This part checks the condition.  In this case we are expecting
164        # some integer variable called "a", and will stop when it is 20.
165        a_var = frame.FindVariable("a")
166
167        if not a_var.IsValid():
168            print "A was not valid."
169            return True
170
171        error = lldb.SBError()
172        a_value = a_var.GetValueAsSigned (error)
173        if not error.Success():
174            print "A value was not good."
175            return True
176
177        if a_value == 20:
178            self.thread_plan.SetPlanComplete(True)
179            return True
180        else:
181            self.queue_next_plan()
182            return False
183
184    def should_step (self):
185        return True
186
187# Here's an example that steps out of the current frame, gathers some information
188# and then continues.  The information in this case is rax.  Currently the thread
189# plans are not a safe place to call lldb command-line commands, so the information
190# is gathered through SB API calls.
191
192class FinishPrintAndContinue:
193    def __init__ (self, thread_plan, dict):
194        self.thread_plan = thread_plan
195        self.step_out_thread_plan = thread_plan.QueueThreadPlanForStepOut(0, True)
196        self.thread = self.thread_plan.GetThread()
197
198    def explains_stop (self, event):
199        return False
200
201    def should_stop (self, event):
202        if  self.step_out_thread_plan.IsPlanComplete():
203            frame_0 = self.thread.frames[0]
204            rax_value = frame_0.FindRegister("rax")
205            if rax_value.GetError().Success():
206                print "RAX on exit: ", rax_value.GetValue()
207            else:
208                print "Couldn't get rax value:", rax_value.GetError().GetCString()
209
210            self.thread_plan.SetPlanComplete(True)
211        return False
212