def test_watch_address(self): """Exercise SBTarget.WatchAddress() API to set a watchpoint.""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) value = frame0.FindValue('g_char_ptr', lldb.eValueTypeVariableGlobal) pointee = value.CreateValueFromAddress( "pointee", value.GetValueAsUnsigned(0), value.GetType().GetPointeeType()) # Watch for write to *g_char_ptr. error = lldb.SBError() watchpoint = target.WatchAddress(value.GetValueAsUnsigned(), 1, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the pointer and set a watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print watchpoint # Continue. Expect the program to stop due to the variable being written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False, substrs=[self.violating_func])
def test_watch_val(self): """Exercise SBValue.Watch() API to set a watchpoint.""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue("global", lldb.eValueTypeVariableGlobal) error = lldb.SBError() watchpoint = value.Watch(True, True, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print watchpoint # Continue. Expect the program to stop due to the variable being written to. process.Continue() if self.TraceOn(): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Continue. Expect the program to stop due to the variable being read from. process.Continue() if self.TraceOn(): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Continue the process. We don't expect the program to be stopped again. process.Continue() # At this point, the inferior process should have exited. self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
def test_watchpoint_cond_api(self): """Test watchpoint condition API.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) exe = os.path.join(os.getcwd(), self.exe_name) # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) error = lldb.SBError() watchpoint = value.Watch(True, False, True, error) self.assertTrue( value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Now set the condition as "global==5". watchpoint.SetCondition('global==5') self.expect(watchpoint.GetCondition(), exe=False, startstr='global==5') # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print watchpoint # Continue. Expect the program to stop due to the variable being written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Verify that the condition is met. self.assertTrue(value.GetValueAsUnsigned() == 5)
def test_stop_at_outer_inline(self): """Exercise SBFrame.IsInlined() and SBFrame.GetFunctionName().""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by the name of 'inner_inline'. breakpoint = target.BreakpointCreateByName('inner_inline', 'a.out') #print "breakpoint:", breakpoint self.assertTrue(breakpoint and breakpoint.GetNumLocations() > 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) import lldbutil stack_traces1 = lldbutil.print_stacktraces(process, string_buffer=True) if self.TraceOn(): print "Full stack traces when first stopped on the breakpoint 'inner_inline':" print stack_traces1 # The first breakpoint should correspond to an inlined call frame. # If it's an inlined call frame, expect to find, in the stack trace, # that there is a frame which corresponds to the following call site: # # outer_inline (argc); # frame0 = process.GetThreadAtIndex(0).GetFrameAtIndex(0) if frame0.IsInlined(): filename = frame0.GetLineEntry().GetFileSpec().GetFilename() self.assertTrue(filename == self.source) self.expect(stack_traces1, "First stop at %s:%d" % (self.source, self.first_stop), exe=False, substrs=['%s:%d' % (self.source, self.first_stop)]) # Expect to break again for the second time. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) stack_traces2 = lldbutil.print_stacktraces(process, string_buffer=True) if self.TraceOn(): print "Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:" print stack_traces2 self.expect( stack_traces2, "Second stop at %s:%d" % (self.source, self.second_stop), exe=False, substrs=['%s:%d' % (self.source, self.second_stop)])
def test_watchpoint_cond_api(self): """Test watchpoint condition API.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) exe = os.path.join(os.getcwd(), self.exe_name) # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple (None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) error = lldb.SBError(); watchpoint = value.Watch(True, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Now set the condition as "global==5". watchpoint.SetCondition('global==5') self.expect(watchpoint.GetCondition(), exe=False, startstr = 'global==5') # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print(watchpoint) # Continue. Expect the program to stop due to the variable being written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Verify that the condition is met. self.assertTrue(value.GetValueAsUnsigned() == 5)
def test_watch_location(self): """Exercise SBValue.WatchPointee() API to set a watchpoint.""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple (None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) value = frame0.FindValue('g_char_ptr', lldb.eValueTypeVariableGlobal) pointee = value.CreateValueFromAddress("pointee", value.GetValueAsUnsigned(0), value.GetType().GetPointeeType()) # Watch for write to *g_char_ptr. error = lldb.SBError(); watchpoint = value.WatchPointee(True, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the pointer and set a watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print(watchpoint) # Continue. Expect the program to stop due to the variable being written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False, substrs = [self.violating_func])
def do_stop_at_outer_inline(self): """Exercise SBFrame.IsInlined() and SBFrame.GetFunctionName().""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by the name of 'inner_inline'. breakpoint = target.BreakpointCreateByName("inner_inline", "a.out") # print "breakpoint:", breakpoint self.assertTrue(breakpoint and breakpoint.GetNumLocations() > 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) import lldbutil stack_traces1 = lldbutil.print_stacktraces(process, string_buffer=True) if self.TraceOn(): print "Full stack traces when first stopped on the breakpoint 'inner_inline':" print stack_traces1 # The first breakpoint should correspond to an inlined call frame. # If it's an inlined call frame, expect to find, in the stack trace, # that there is a frame which corresponds to the following call site: # # outer_inline (argc); # frame0 = process.GetThreadAtIndex(0).GetFrameAtIndex(0) if frame0.IsInlined(): filename = frame0.GetLineEntry().GetFileSpec().GetFilename() self.assertTrue(filename == self.source) self.expect( stack_traces1, "First stop at %s:%d" % (self.source, self.first_stop), exe=False, substrs=["%s:%d" % (self.source, self.first_stop)], ) # Expect to break again for the second time. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) stack_traces2 = lldbutil.print_stacktraces(process, string_buffer=True) if self.TraceOn(): print "Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:" print stack_traces2 self.expect( stack_traces2, "Second stop at %s:%d" % (self.source, self.second_stop), exe=False, substrs=["%s:%d" % (self.source, self.second_stop)], )
def test_with_process_launch_api(self): """Test the SBCommandInterpreter APIs.""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Retrieve the associated command interpreter from our debugger. ci = self.dbg.GetCommandInterpreter() self.assertTrue(ci, VALID_COMMAND_INTERPRETER) # Exercise some APIs.... self.assertTrue(ci.HasCommands()) self.assertTrue(ci.HasAliases()) self.assertTrue(ci.HasAliasOptions()) self.assertTrue(ci.CommandExists("breakpoint")) self.assertTrue(ci.CommandExists("target")) self.assertTrue(ci.CommandExists("platform")) self.assertTrue(ci.AliasExists("file")) self.assertTrue(ci.AliasExists("run")) self.assertTrue(ci.AliasExists("bt")) res = lldb.SBCommandReturnObject() ci.HandleCommand("breakpoint set -f main.c -l %d" % self.line, res) self.assertTrue(res.Succeeded()) ci.HandleCommand("process launch", res) self.assertTrue(res.Succeeded()) # Boundary conditions should not crash lldb! self.assertFalse(ci.CommandExists(None)) self.assertFalse(ci.AliasExists(None)) ci.HandleCommand(None, res) self.assertFalse(res.Succeeded()) res.AppendMessage("Just appended a message.") res.AppendMessage(None) if self.TraceOn(): print(res) process = ci.GetProcess() self.assertTrue(process) import lldbutil if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) if self.TraceOn(): lldbutil.print_stacktraces(process)
def test_with_process_launch_api(self): """Test the SBCommandInterpreter APIs.""" self.build() exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Retrieve the associated command interpreter from our debugger. ci = self.dbg.GetCommandInterpreter() self.assertTrue(ci, VALID_COMMAND_INTERPRETER) # Exercise some APIs.... self.assertTrue(ci.HasCommands()) self.assertTrue(ci.HasAliases()) self.assertTrue(ci.HasAliasOptions()) self.assertTrue(ci.CommandExists("breakpoint")) self.assertTrue(ci.CommandExists("target")) self.assertTrue(ci.CommandExists("platform")) self.assertTrue(ci.AliasExists("file")) self.assertTrue(ci.AliasExists("run")) self.assertTrue(ci.AliasExists("bt")) res = lldb.SBCommandReturnObject() ci.HandleCommand("breakpoint set -f main.c -l %d" % self.line, res) self.assertTrue(res.Succeeded()) ci.HandleCommand("process launch", res) self.assertTrue(res.Succeeded()) # Boundary conditions should not crash lldb! self.assertFalse(ci.CommandExists(None)) self.assertFalse(ci.AliasExists(None)) ci.HandleCommand(None, res) self.assertFalse(res.Succeeded()) res.AppendMessage("Just appended a message.") res.AppendMessage(None) if self.TraceOn(): print res process = ci.GetProcess() self.assertTrue(process) import lldbutil if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) if self.TraceOn(): lldbutil.print_stacktraces(process)
def break_and_print_stacktraces(self): """Break at main.cpp:68 and do a threads dump""" exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. process = target.LaunchSimple(["abc", "xyz"], None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") import lldbutil if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs=['(int)argc=3'])
def break_and_print_stacktraces(self): """Break at main.cpp:68 and do a threads dump""" exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. process = target.LaunchSimple(["abc", "xyz"], None, os.getcwd()) if not process: self.fail("SBTarget.LaunchProcess() failed") import lldbutil if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['(int)argc=3'])
def test_with_attach_to_process_with_id_api(self): """Create target, spawn a process, and attach to it with process id.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) target = self.dbg.CreateTarget(self.exe) # Spawn a new process popen = self.spawnSubprocess(self.exe, ["abc", "xyz"]) self.addTearDownHook(self.cleanupSubprocesses) # Give the subprocess time to start and wait for user input time.sleep(0.25) listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['main.c:%d' % self.line2, '(int)argc=3'])
def hello_world_attach_with_name_api(self): """Create target, spawn a process, and attach to it by name.""" target = self.dbg.CreateTarget(self.exe) # Spawn a new process popen = self.spawnSubprocess(self.exe, ["abc", "xyz"]) self.addTearDownHook(self.cleanupSubprocesses) listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() # Pass 'False' since we don't want to wait for new instance of "hello_world" to be launched. name = os.path.basename(self.exe) # While we're at it, make sure that passing a None as the process name # does not hang LLDB. target.AttachToProcessWithName(listener, None, False, error) # Also boundary condition test ConnectRemote(), too. target.ConnectRemote(listener, None, None, error) process = target.AttachToProcessWithName(listener, name, False, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Verify that after attach, our selected target indeed matches name. self.expect(self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), exe=False, startstr = name) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['main.c:%d' % self.line2, '(int)argc=3'])
def test_with_attach_to_process_with_id_api(self): """Create target, spawn a process, and attach to it with process id.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) target = self.dbg.CreateTarget(self.exe) # Spawn a new process popen = self.spawnSubprocess(self.exe, ["abc", "xyz"]) self.addTearDownHook(self.cleanupSubprocesses) # Give the subprocess time to start and wait for user input time.sleep(0.25) listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs=['main.c:%d' % self.line2, '(int)argc=3'])
def hello_world_attach_with_id_api(self): """Create target, spawn a process, and attach to it by id.""" target = self.dbg.CreateTarget(self.exe) # Spawn a new process popen = self.spawnSubprocess(self.exe, ["abc", "xyz"]) self.addTearDownHook(self.cleanupSubprocesses) listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['main.c:%d' % self.line2, '(int)argc=3'])
def test_with_attach_to_process_with_name_api(self): """Create target, spawn a process, and attach to it with process name.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) target = self.dbg.CreateTarget(self.exe) # Spawn a new process popen = self.spawnSubprocess(self.exe, ["abc", "xyz"]) self.addTearDownHook(self.cleanupSubprocesses) # Give the subprocess time to start and wait for user input time.sleep(0.25) listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() # Pass 'False' since we don't want to wait for new instance of "hello_world" to be launched. name = os.path.basename(self.exe) # While we're at it, make sure that passing a None as the process name # does not hang LLDB. target.AttachToProcessWithName(listener, None, False, error) # Also boundary condition test ConnectRemote(), too. target.ConnectRemote(listener, None, None, error) process = target.AttachToProcessWithName(listener, name, False, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Verify that after attach, our selected target indeed matches name. self.expect(self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), exe=False, startstr=name) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs=['main.c:%d' % self.line2, '(int)argc=3'])
def hello_world_attach_with_name_api(self): """Create target, spawn a process, and attach to it by name.""" target = self.dbg.CreateTarget(self.exe) # Spawn a new process and don't display the stdout if not in TraceOn() mode. import subprocess popen = subprocess.Popen( [self.exe, "abc", "xyz"], stdout=open(os.devnull, 'w') if not self.TraceOn() else None) #print "pid of spawned process: %d" % popen.pid listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() # Pass 'False' since we don't want to wait for new instance of "hello_world" to be launched. name = os.path.basename(self.exe) # While we're at it, make sure that passing a None as the process name # does not hang LLDB. target.AttachToProcessWithName(listener, None, False, error) # Also boundary condition test ConnectRemote(), too. target.ConnectRemote(listener, None, None, error) process = target.AttachToProcessWithName(listener, name, False, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Verify that after attach, our selected target indeed matches name. self.expect(self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), exe=False, startstr=name) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs=['main.c:%d' % self.line2, '(int)argc=3'])
def hello_world_attach_with_id_api(self): """Create target, spawn a process, and attach to it by id.""" target = self.dbg.CreateTarget(self.exe) # Spawn a new process and don't display the stdout if not in TraceOn() mode. import subprocess popen = subprocess.Popen([self.exe, "abc", "xyz"], stdout = open(os.devnull, 'w') if not self.TraceOn() else None) #print "pid of spawned process: %d" % popen.pid listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['main.c:%d' % self.line2, '(int)argc=3'])
def hello_world_attach_with_id_api(self): """Create target, spawn a process, and attach to it by id.""" target = self.dbg.CreateTarget(self.exe) # Spawn a new process and don't display the stdout if not in TraceOn() mode. import subprocess popen = subprocess.Popen( [self.exe, "abc", "xyz"], stdout=open(os.devnull, 'w') if not self.TraceOn() else None) #print "pid of spawned process: %d" % popen.pid listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs=['main.c:%d' % self.line2, '(int)argc=3'])
def do_watchpoint_iter(self): """Use SBTarget.watchpoint_iter() to do Pythonic iteration on the available watchpoints.""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Create a breakpoint on main.c in order to set our watchpoint later. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, os.getcwd()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) error = lldb.SBError(); watchpoint = value.Watch(True, True, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() # There should be only 1 watchpoint location under the target. self.assertTrue(target.GetNumWatchpoints() == 1) self.assertTrue(watchpoint.IsEnabled()) watch_id = watchpoint.GetID() self.assertTrue(watch_id != 0) # Continue. Expect the program to stop due to the variable being written to. process.Continue() # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() # Print the stack traces. lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # We currently only support hardware watchpoint. Verify that we have a # meaningful hardware index at this point. Exercise the printed repr of # SBWatchpointLocation. print watchpoint self.assertTrue(watchpoint.GetHardwareIndex() != -1) # SBWatchpoint.GetDescription() takes a description level arg. print lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull) # Now disable the 'rw' watchpoint. The program won't stop when it reads # 'global' next. watchpoint.SetEnabled(False) self.assertTrue(watchpoint.GetHardwareIndex() == -1) self.assertFalse(watchpoint.IsEnabled()) # Continue. The program does not stop again when the variable is being # read from because the watchpoint location has been disabled. process.Continue() # At this point, the inferior process should have exited. self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) # Verify some vital statistics and exercise the iterator API. for watchpoint in target.watchpoint_iter(): self.assertTrue(watchpoint) self.assertTrue(watchpoint.GetWatchSize() == 4) self.assertTrue(watchpoint.GetHitCount() == 1) print watchpoint
def do_listen_for_and_print_event(self): """Create a listener and use SBEvent API to print the events received.""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, os.getcwd()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) # Get a handle on the process's broadcaster. broadcaster = process.GetBroadcaster() # Create an empty event object. event = lldb.SBEvent() # Create a listener object and register with the broadcaster. listener = lldb.SBListener("my listener") rc = broadcaster.AddListener(listener, lldb.SBProcess.eBroadcastBitStateChanged) self.assertTrue(rc, "AddListener successfully retruns") traceOn = self.TraceOn() if traceOn: lldbutil.print_stacktraces(process) # Create MyListeningThread class to wait for any kind of event. import threading class MyListeningThread(threading.Thread): def run(self): count = 0 # Let's only try at most 4 times to retrieve any kind of event. # After that, the thread exits. while not count > 3: if traceOn: print "Try wait for event..." if listener.WaitForEventForBroadcasterWithType(5, broadcaster, lldb.SBProcess.eBroadcastBitStateChanged, event): if traceOn: desc = lldbutil.get_description(event) print "Event description:", desc print "Event data flavor:", event.GetDataFlavor() print "Process state:", lldbutil.state_type_to_str(process.GetState()) print else: if traceOn: print "timeout occurred waiting for event..." count = count + 1 return # Let's start the listening thread to retrieve the events. my_thread = MyListeningThread() my_thread.start() # Use Python API to continue the process. The listening thread should be # able to receive the state changed events. process.Continue() # Use Python API to kill the process. The listening thread should be # able to receive the state changed event, too. process.Kill() # Wait until the 'MyListeningThread' terminates. my_thread.join()
def do_set_watchpoint(self): """Use SBFrame.WatchValue() to set a watchpoint and verify that the program stops later due to the watchpoint.""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple (None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) error = lldb.SBError(); watchpoint = value.Watch(True, True, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() print watchpoint # Continue. Expect the program to stop due to the variable being written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Continue. Expect the program to stop due to the variable being read from. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # Continue the process. We don't expect the program to be stopped again. process.Continue() # At this point, the inferior process should have exited. self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
def test_listen_for_and_print_event(self): """Exercise SBEvent API.""" self.build() exe = os.path.join(os.getcwd(), "a.out") self.dbg.SetAsync(True) # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') listener = lldb.SBListener("my listener") # Now launch the process, and do not stop at the entry point. error = lldb.SBError() process = target.Launch (listener, None, # argv None, # envp None, # stdin_path None, # stdout_path None, # stderr_path None, # working directory 0, # launch flags False, # Stop at entry error) # error self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) # Create an empty event object. event = lldb.SBEvent() traceOn = self.TraceOn() if traceOn: lldbutil.print_stacktraces(process) # Create MyListeningThread class to wait for any kind of event. import threading class MyListeningThread(threading.Thread): def run(self): count = 0 # Let's only try at most 4 times to retrieve any kind of event. # After that, the thread exits. while not count > 3: if traceOn: print "Try wait for event..." if listener.WaitForEvent(5, event): if traceOn: desc = lldbutil.get_description(event) print "Event description:", desc print "Event data flavor:", event.GetDataFlavor() print "Process state:", lldbutil.state_type_to_str(process.GetState()) print else: if traceOn: print "timeout occurred waiting for event..." count = count + 1 return # Let's start the listening thread to retrieve the events. my_thread = MyListeningThread() my_thread.start() # Use Python API to continue the process. The listening thread should be # able to receive the state changed events. process.Continue() # Use Python API to kill the process. The listening thread should be # able to receive the state changed event, too. process.Kill() # Wait until the 'MyListeningThread' terminates. my_thread.join()
def do_watchpoint_iter(self): """Use SBTarget.watchpoint_iter() to do Pythonic iteration on the available watchpoints.""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Create a breakpoint on main.c in order to set our watchpoint later. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, os.getcwd()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) watchpoint = value.Watch(True, True, True) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") self.DebugSBValue(value) # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() # There should be only 1 watchpoint location under the target. self.assertTrue(target.GetNumWatchpoints() == 1) self.assertTrue(watchpoint.IsEnabled()) watch_id = watchpoint.GetID() self.assertTrue(watch_id != 0) # Continue. Expect the program to stop due to the variable being written to. process.Continue() # Hide stdout if not running with '-t' option. if not self.TraceOn(): self.HideStdout() # Print the stack traces. lldbutil.print_stacktraces(process) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) # We currently only support hardware watchpoint. Verify that we have a # meaningful hardware index at this point. Exercise the printed repr of # SBWatchpointLocation. print watchpoint self.assertTrue(watchpoint.GetHardwareIndex() != -1) # SBWatchpoint.GetDescription() takes a description level arg. print lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull) # Now disable the 'rw' watchpoint. The program won't stop when it reads # 'global' next. watchpoint.SetEnabled(False) self.assertTrue(watchpoint.GetHardwareIndex() == -1) self.assertFalse(watchpoint.IsEnabled()) # Continue. The program does not stop again when the variable is being # read from because the watchpoint location has been disabled. process.Continue() # At this point, the inferior process should have exited. self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) # Verify some vital statistics and exercise the iterator API. for watchpoint in target.watchpoint_iter(): self.assertTrue(watchpoint) self.assertTrue(watchpoint.GetWatchSize() == 4) self.assertTrue(watchpoint.GetHitCount() == 1) print watchpoint
def do_listen_for_and_print_event(self): """Create a listener and use SBEvent API to print the events received.""" exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, os.getcwd()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) # Get a handle on the process's broadcaster. broadcaster = process.GetBroadcaster() # Create an empty event object. event = lldb.SBEvent() # Create a listener object and register with the broadcaster. listener = lldb.SBListener("my listener") rc = broadcaster.AddListener(listener, lldb.SBProcess.eBroadcastBitStateChanged) self.assertTrue(rc, "AddListener successfully retruns") traceOn = self.TraceOn() if traceOn: lldbutil.print_stacktraces(process) # Create MyListeningThread class to wait for any kind of event. import threading class MyListeningThread(threading.Thread): def run(self): count = 0 # Let's only try at most 4 times to retrieve any kind of event. # After that, the thread exits. while not count > 3: if traceOn: print "Try wait for event..." if listener.WaitForEventForBroadcasterWithType( 5, broadcaster, lldb.SBProcess.eBroadcastBitStateChanged, event): if traceOn: desc = lldbutil.get_description(event) print "Event description:", desc print "Event data flavor:", event.GetDataFlavor() print "Process state:", lldbutil.state_type_to_str( process.GetState()) print else: if traceOn: print "timeout occurred waiting for event..." count = count + 1 return # Let's start the listening thread to retrieve the events. my_thread = MyListeningThread() my_thread.start() # Use Python API to continue the process. The listening thread should be # able to receive the state changed events. process.Continue() # Use Python API to kill the process. The listening thread should be # able to receive the state changed event, too. process.Kill() # Wait until the 'MyListeningThread' terminates. my_thread.join()