brintos

brintos / llvm-project-archived public Read only

0
0
Text · 10.9 KiB · 8f2cc09 Raw
260 lines · python
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 the4# comments at the beginning of ThreadPlan.h in the lldb sources.  The python5# interface is a reduced version of the full internal mechanism, but captures6# 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 stepping10# operations are stackable.  So for instance if you did a "step over", and in11# 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 would13# 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, so15# now there are two pending step overs.  Etc. with all the other stepping16# 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 new20# stepping operation is requested, a new plan is pushed on the stack.  When the21# 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 get25# asked whether to set the program running freely, or to instruction-single-step26# the current thread.  In the scripted interface, you indicate this by returning27# False or True respectively from the should_step method.28#29# Each time the process stops the thread plan stack for each thread that stopped30# "for a reason", Ii.e. a single-step completed on that thread, or a breakpoint31# was hit), is queried to determine how to proceed, starting from the most32# recently pushed plan, in two stages:33#34# 1) Each plan is asked if it "explains" the stop.  The first plan to claim the35#    stop wins.  In scripted Thread Plans, this is done by returning True from36#    the "explains_stop method.  This is how, for instance, control is returned37#    to the User when the "step-over" plan hits a breakpoint.  The step-over38#    plan doesn't explain the breakpoint stop, so it returns false, and the39#    breakpoint hit is propagated up the stack to the "base" thread plan, which40#    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 do44#    three jobs in should_stop:45#      a) They determine if they have completed their job or not.  If they have46#         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 use50#         the next time the thread continues.51#52#    Note that deciding to return control to the user, and deciding your plan53#    is done, are orthgonal operations.  You could set up the next phase of54#    stepping, and then return True from should_stop, and when the user next55#    "continued" the process your plan would resume control.  Of course, the56#    user might also "step-over" or some other operation that would push a57#    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 the60#    stack was done, then it will be popped and the next plan will take control61#    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 that65#    yet.  For now you should do that at the same time you mark your plan complete.66#67# 3) After the round of negotiation over whether to stop or not is done, all the68#    plans get asked if they are "stale".  If they are say they are stale69#    then they will get popped.  This question is asked with the "is_stale" method.70#71#    This is useful, for instance, in the FinishPrintAndContinue plan.  What might72#    happen here is that after continuing but before the finish is done, the program73#    could hit another breakpoint and stop.  Then the user could use the step74#    command repeatedly until they leave the frame of interest by stepping.75#    In that case, the step plan is the one that will be responsible for stopping,76#    and the finish plan won't be asked should_stop, it will just be asked if it77#    is stale.  In this case, if the step_out plan that the FinishPrintAndContinue78#    plan is driving is stale, so is ours, and it is time to do our printing.79#80# 4) If you implement the "stop_description(SBStream stream)" method in your81#    python class, then that will show up as the "plan completed" reason when82#    your thread plan is complete.83#84# Both examples show stepping through an address range for 20 bytes from the85# current PC.  The first one does it by single stepping and checking a condition.86# It doesn't, however handle the case where you step into another frame while87# still in the current range in the starting frame.88#89# That is better handled in the second example by using the built-in StepOverRange90# thread plan.91#92# To use these stepping modes, you would do:93#94#     (lldb) command script import scripted_step.py95#     (lldb) thread step-scripted -C scripted_step.SimpleStep96# or97#98#     (lldb) thread step-scripted -C scripted_step.StepWithPlan99 100import lldb101 102 103class SimpleStep:104    def __init__(self, thread_plan, dict):105        self.thread_plan = thread_plan106        self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPC()107 108    def explains_stop(self, event):109        # We are stepping, so if we stop for any other reason, it isn't110        # because of us.111        if self.thread_plan.GetThread().GetStopReason() == lldb.eStopReasonTrace:112            return True113        else:114            return False115 116    def should_stop(self, event):117        cur_pc = self.thread_plan.GetThread().GetFrameAtIndex(0).GetPC()118 119        if cur_pc < self.start_address or cur_pc >= self.start_address + 20:120            self.thread_plan.SetPlanComplete(True)121            return True122        else:123            return False124 125    def should_step(self):126        return True127 128    def stop_description(self, stream):129        stream.Print("Simple step completed")130 131 132class StepWithPlan:133    def __init__(self, thread_plan, dict):134        self.thread_plan = thread_plan135        self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPCAddress()136        self.step_thread_plan = thread_plan.QueueThreadPlanForStepOverRange(137            self.start_address, 20138        )139 140    def explains_stop(self, event):141        # Since all I'm doing is running a plan, I will only ever get askedthis142        # if myplan doesn't explain the stop, and in that caseI don'teither.143        return False144 145    def should_stop(self, event):146        if self.step_thread_plan.IsPlanComplete():147            self.thread_plan.SetPlanComplete(True)148            return True149        else:150            return False151 152    def should_step(self):153        return False154 155    def stop_description(self, stream):156        self.step_thread_plan.GetDescription(stream, lldb.eDescriptionLevelBrief)157 158 159# Here's another example which does "step over" through the current function,160# and when it stops at each line, it checks some condition (in this example the161# value of a variable) and stops if that condition is true.162 163 164class StepCheckingCondition:165    def __init__(self, thread_plan, dict):166        self.thread_plan = thread_plan167        self.start_frame = thread_plan.GetThread().GetFrameAtIndex(0)168        self.queue_next_plan()169 170    def queue_next_plan(self):171        cur_frame = self.thread_plan.GetThread().GetFrameAtIndex(0)172        cur_line_entry = cur_frame.GetLineEntry()173        start_address = cur_line_entry.GetStartAddress()174        end_address = cur_line_entry.GetEndAddress()175        line_range = end_address.GetFileAddress() - start_address.GetFileAddress()176        self.step_thread_plan = self.thread_plan.QueueThreadPlanForStepOverRange(177            start_address, line_range178        )179 180    def explains_stop(self, event):181        # We are stepping, so if we stop for any other reason, it isn't182        # because of us.183        return False184 185    def should_stop(self, event):186        if not self.step_thread_plan.IsPlanComplete():187            return False188 189        frame = self.thread_plan.GetThread().GetFrameAtIndex(0)190        if not self.start_frame.IsEqual(frame):191            self.thread_plan.SetPlanComplete(True)192            return True193 194        # This part checks the condition.  In this case we are expecting195        # some integer variable called "a", and will stop when it is 20.196        a_var = frame.FindVariable("a")197 198        if not a_var.IsValid():199            print("A was not valid.")200            return True201 202        error = lldb.SBError()203        a_value = a_var.GetValueAsSigned(error)204        if not error.Success():205            print("A value was not good.")206            return True207 208        if a_value == 20:209            self.thread_plan.SetPlanComplete(True)210            return True211        else:212            self.queue_next_plan()213            return False214 215    def should_step(self):216        return True217 218    def stop_description(self, stream):219        stream.Print(f"Stepped until a == 20")220 221 222# Here's an example that steps out of the current frame, gathers some information223# and then continues.  The information in this case is rax.  Currently the thread224# plans are not a safe place to call lldb command-line commands, so the information225# is gathered through SB API calls.226 227 228class FinishPrintAndContinue:229    def __init__(self, thread_plan, dict):230        self.thread_plan = thread_plan231        self.step_out_thread_plan = thread_plan.QueueThreadPlanForStepOut(0, True)232        self.thread = self.thread_plan.GetThread()233 234    def is_stale(self):235        if self.step_out_thread_plan.IsPlanStale():236            self.do_print()237            return True238        else:239            return False240 241    def explains_stop(self, event):242        return False243 244    def should_stop(self, event):245        if self.step_out_thread_plan.IsPlanComplete():246            self.do_print()247            self.thread_plan.SetPlanComplete(True)248        return False249 250    def do_print(self):251        frame_0 = self.thread.frames[0]252        rax_value = frame_0.FindRegister("rax")253        if rax_value.GetError().Success():254            print("RAX on exit: ", rax_value.GetValue())255        else:256            print("Couldn't get rax value:", rax_value.GetError().GetCString())257 258    def stop_description(self, stream):259        self.step_out_thread_plan.GetDescription(stream, lldb.eDescriptionLevelBrief)260