def fuzz_obj(obj): obj.GetName() obj.GetMangledName() obj.GetInstructions(lldb.SBTarget()) obj.GetStartAddress() obj.GetEndAddress() obj.GetPrologueByteSize() obj.GetType() obj.GetDescription(lldb.SBStream())
def value(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) expr = "(NSString*)[" + stream.GetData() + " stringValue]" num_children_vo = self.valobj.CreateValueFromExpression("str", expr) if num_children_vo.IsValid(): return num_children_vo.GetSummary() return '<variable is not NSNumber>'
def count(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) expr = "(int)[" + stream.GetData() + " count]" num_children_vo = self.valobj.CreateValueFromExpression("count", expr) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) return '<variable is not NSSet>'
def port(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( "port", "(int)[" + stream.GetData() + " machPort]") if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) return '<variable is not NSMachPort>'
def length(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( "count", "(int)CFBinaryHeapGetCount(" + stream.GetData() + " )") if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) return '<variable is not CFBinaryHeap>'
def name(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) name_vo = self.valobj.CreateValueFromExpression( "name", "(NSString*)[" + stream.GetData() + " name]") if name_vo.IsValid(): return CFString.CFString_SummaryProvider(name_vo, None) return '<variable is not NSNotification>'
def url_text(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) url_text_vo = self.valobj.CreateValueFromExpression( "url", "(NSString*)[" + stream.GetData() + " description]") if url_text_vo.IsValid(): return CFString.CFString_SummaryProvider(url_text_vo, None) return '<variable is not NSURL>'
def url_text(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) expr = "(NSString*)[" + stream.GetData() + " bundlePath]" url_text_vo = self.valobj.CreateValueFromExpression("path", expr) if url_text_vo.IsValid(): return url_text_vo.GetSummary() return '<variable is not NSBundle>'
def asan_tests(self): target = self.createTestTarget() self.registerSanitizerLibrariesWithTarget(target) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread( ).GetStopReason() if stop_reason == lldb.eStopReasonExec: # On OS X 10.10 and older, we need to re-exec to enable # interceptors. self.runCmd("continue") self.expect( "thread list", "Process should be stopped due to ASan report", substrs=['stopped', 'stop reason = Use of deallocated memory']) self.assertEqual( self.dbg.GetSelectedTarget().process.GetSelectedThread(). GetStopReason(), lldb.eStopReasonInstrumentation) self.expect( "bt", "The backtrace should show the crashing line", substrs=['main.c:%d:%d' % (self.line_crash, self.col_crash)]) self.expect( "thread info -s", "The extended stop info should contain the ASan provided fields", substrs=[ "access_size", "access_type", "address", "description", "heap-use-after-free", "pc", ]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) data = json.loads(json_line) self.assertEqual(data["description"], "heap-use-after-free") self.assertEqual(data["instrumentation_class"], "AddressSanitizer") self.assertEqual(data["stop_type"], "fatal_error") # now let's try the SB API process = self.dbg.GetSelectedTarget().process thread = process.GetSelectedThread() s = lldb.SBStream() self.assertTrue(thread.GetStopReasonExtendedInfoAsJSON(s)) s = s.GetData() data2 = json.loads(s) self.assertEqual(data, data2)
def fuzz_obj(obj): obj.SetAsync(True) obj.SetAsync(False) obj.GetAsync() obj.SkipLLDBInitFiles(True) obj.SetInputFileHandle(None, True) obj.SetOutputFileHandle(None, True) obj.SetErrorFileHandle(None, True) obj.GetInputFileHandle() obj.GetOutputFileHandle() obj.GetErrorFileHandle() obj.GetCommandInterpreter() obj.HandleCommand("nothing here") listener = obj.GetListener() try: obj.HandleProcessEvent(lldb.SBProcess(), lldb.SBEvent(), None, None) except Exception: pass obj.CreateTargetWithFileAndTargetTriple("a.out", "A-B-C") obj.CreateTargetWithFileAndArch("b.out", "arm") obj.CreateTarget("c.out") obj.DeleteTarget(lldb.SBTarget()) obj.GetTargetAtIndex(0xffffffff) obj.FindTargetWithProcessID(0) obj.FindTargetWithFileAndArch("a.out", "arm") obj.GetNumTargets() obj.GetSelectedTarget() obj.GetNumPlatforms() obj.GetPlatformAtIndex(0xffffffff) obj.GetNumAvailablePlatforms() obj.GetAvailablePlatformInfoAtIndex(0xffffffff) obj.GetSourceManager() obj.SetSelectedTarget(lldb.SBTarget()) obj.SetCurrentPlatformSDKRoot("tmp/sdk-root") try: obj.DispatchInput(None) except Exception: pass obj.DispatchInputInterrupt() obj.DispatchInputEndOfFile() obj.GetInstanceName() obj.GetDescription(lldb.SBStream()) obj.GetTerminalWidth() obj.SetTerminalWidth(0xffffffff) obj.GetID() obj.GetPrompt() obj.SetPrompt("Hi, Mom!") obj.GetScriptLanguage() obj.SetScriptLanguage(lldb.eScriptLanguageNone) obj.SetScriptLanguage(lldb.eScriptLanguagePython) obj.GetCloseInputOnEOF() obj.SetCloseInputOnEOF(True) obj.SetCloseInputOnEOF(False) obj.Clear() for target in obj: s = str(target)
def do_display_source_python_api(self, use_color, needle_regex, highlight_source=False): self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. args = None envp = None process = target.LaunchSimple(args, envp, self.get_process_working_directory()) self.assertIsNotNone(process) # # Exercise Python APIs to display source lines. # # Setup whether we should use ansi escape sequences, including color # and styles such as underline. self.dbg.SetUseColor(use_color) # Disable syntax highlighting if needed. self.runCmd("settings set highlight-source " + str(highlight_source).lower()) filespec = lldb.SBFileSpec(self.file, False) source_mgr = self.dbg.GetSourceManager() # Use a string stream as the destination. stream = lldb.SBStream() column = self.get_expected_stop_column_number() context_before = 2 context_after = 2 current_line_prefix = "=>" source_mgr.DisplaySourceLinesWithLineNumbersAndColumn( filespec, self.line, column, context_before, context_after, current_line_prefix, stream) # 2 # 3 int main(int argc, char const *argv[]) { # => 4 printf("Hello world.\n"); // Set break point at this line. # 5 return 0; # 6 } self.expect( stream.GetData(), "Source code displayed correctly:\n" + stream.GetData(), exe=False, patterns=['=>', '%d.*Hello world' % self.line, needle_regex]) # Boundary condition testings for SBStream(). LLDB should not crash! stream.Print(None) stream.RedirectToFile(None, True)
def asan_tests (self): exe = os.path.join (os.getcwd(), "a.out") self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) self.runCmd("run") # ASan will relaunch the process to insert its library. self.expect("thread list", "Process should be stopped due to exec.", substrs = ['stopped', 'stop reason = exec']) # no extended info when we have no ASan report thread = self.dbg.GetSelectedTarget().process.GetSelectedThread() s = lldb.SBStream() self.assertFalse(thread.GetStopReasonExtendedInfoAsJSON(s)) self.runCmd("continue") self.expect("thread list", "Process should be stopped due to ASan report", substrs = ['stopped', 'stop reason = Use of deallocated memory detected']) self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) self.expect("bt", "The backtrace should show the crashing line", substrs = ['main.c:%d' % self.line_crash]) self.expect("thread info -s", "The extended stop info should contain the ASan provided fields", substrs = ["access_size", "access_type", "address", "pc", "description", "heap-use-after-free"]) output_lines = self.res.GetOutput().split('\n') json_line = output_lines[2] data = json.loads(json_line) self.assertEqual(data["description"], "heap-use-after-free") self.assertEqual(data["instrumentation_class"], "AddressSanitizer") self.assertEqual(data["stop_type"], "fatal_error") # now let's try the SB API process = self.dbg.GetSelectedTarget().process thread = process.GetSelectedThread() s = lldb.SBStream() self.assertTrue(thread.GetStopReasonExtendedInfoAsJSON(s)) s = s.GetData() data2 = json.loads(s) self.assertEqual(data, data2)
def run_a_single_test(self, filename): insn = lldb.SBInstruction() stream = lldb.SBStream() success = insn.TestEmulation(stream, filename) output = stream.GetData() if self.TraceOn(): print '\nRunning test ' + os.path.basename(filename) print output self.assertTrue(success, 'Emulation test succeeded.')
def fuzz_obj(obj): obj.GetSize() obj.GetInstructionAtIndex(0xffffffff) obj.AppendInstruction(lldb.SBInstruction()) obj.Print(None) obj.GetDescription(lldb.SBStream()) obj.DumpEmulationForAllInstructions("armv7") obj.Clear() for inst in obj: s = str(inst)
def fuzz_obj(obj): obj.GetDataFlavor() obj.GetType() broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.BroadcasterMatchesRef(broadcaster) obj.GetDescription(lldb.SBStream()) obj.Clear()
def make_extra_args(self): json_string = '{"symbol":"break_on_me", "test1": "value1"}' json_stream = lldb.SBStream() json_stream.Print(json_string) extra_args = lldb.SBStructuredData() error = extra_args.SetFromJSON(json_stream) self.assertTrue( error.Success(), "Error making SBStructuredData: %s" % (error.GetCString())) return extra_args
def fuzz_obj(obj): obj.IsInlined() obj.GetInlinedName() obj.GetInlinedCallSiteFile() obj.GetInlinedCallSiteLine() obj.GetInlinedCallSiteColumn() obj.GetParent() obj.GetSibling() obj.GetFirstChild() obj.GetDescription(lldb.SBStream())
def test(self): """ Test lldb's parsing of the <architecture> tag in the target.xml register description packet. """ class MyResponder(MockGDBServerResponder): def haltReason(self): return "T02thread:1ff0d;thread-pcs:10001bc00;" def threadStopInfo(self, threadnum): if threadnum == 0x1ff0d: return "T02thread:1ff0d;thread-pcs:10001bc00;" return "" def setBreakpoint(self, packet): if packet.startswith("Z2,"): return "OK" def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": return """<?xml version="1.0"?> <target version="1.0"> <architecture>i386:x86-64</architecture> <feature name="org.gnu.gdb.i386.core"> <reg name="rip" bitsize="64" regnum="0" type="code_ptr" group="general"/> </feature> </target>""", False else: return None, False self.server.responder = MyResponder() if self.TraceOn(): self.runCmd("log enable gdb-remote packets") self.addTearDownHook( lambda: self.runCmd("log disable gdb-remote packets")) self.dbg.SetDefaultArchitecture("x86_64") target = self.dbg.CreateTargetWithFileAndArch(None, None) process = self.connect(target) if self.TraceOn(): interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() interp.HandleCommand("target list", result) print(result.GetOutput()) err = lldb.SBError() wp = target.WatchAddress(0x100, 8, False, True, err) if self.TraceOn() and (err.Fail() or wp.IsValid == False): strm = lldb.SBStream() err.GetDescription(strm) print("watchpoint failed: %s" % strm.GetData()) self.assertTrue(wp.IsValid())
def fuzz_obj(obj): obj.GetProcess() listener = lldb.SBListener() error = lldb.SBError() obj.Launch(listener, None, None, None, None, None, None, 0, True, error) obj.LaunchSimple(None, None, None) obj.AttachToProcessWithID(listener, 123, error) obj.AttachToProcessWithName(listener, 'lldb', False, error) obj.ConnectRemote(listener, "connect://to/here", None, error) obj.GetExecutable() obj.GetNumModules() obj.GetModuleAtIndex(0xffffffff) obj.GetDebugger() filespec = lldb.SBFileSpec() obj.FindModule(filespec) contextlist = lldb.SBSymbolContextList() obj.FindFunctions("the_func", 0xff, True, contextlist) obj.FindFirstType("dont_care") obj.FindTypes("dont_care") obj.FindFirstType(None) obj.GetInstructions(lldb.SBAddress(), bytearray()) obj.GetSourceManager() obj.FindGlobalVariables("my_global_var", 1) address = obj.ResolveLoadAddress(0xffff) obj.ResolveSymbolContextForAddress(address, 0) obj.BreakpointCreateByLocation("filename", 20) obj.BreakpointCreateByLocation(filespec, 20) obj.BreakpointCreateByName("func", None) obj.BreakpointCreateByRegex("func.", None) obj.BreakpointCreateByAddress(0xf0f0) obj.GetNumBreakpoints() obj.GetBreakpointAtIndex(0) obj.BreakpointDelete(0) obj.FindBreakpointByID(0) obj.EnableAllBreakpoints() obj.DisableAllBreakpoints() obj.DeleteAllBreakpoints() obj.GetNumWatchpoints() obj.GetWatchpointAtIndex(0) obj.DeleteWatchpoint(0) obj.FindWatchpointByID(0) obj.EnableAllWatchpoints() obj.DisableAllWatchpoints() obj.DeleteAllWatchpoints() obj.WatchAddress(123, 8, True, True) obj.GetBroadcaster() obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelBrief) obj.Clear() for module in obj.module_iter(): print module for bp in obj.breakpoint_iter(): print bp for wp in obj.watchpoint_iter(): print wp
def thread_proc(self): while not self.stopping: event = self.event if self.listener.WaitForEvent(1, event): if log.isEnabledFor(logging.DEBUG): descr = lldb.SBStream() event.GetDescription(descr) log.debug('### Debug event: %s %s', event.GetDataFlavor(), descr.GetData()) self.event_sink(event) self.event = lldb.SBEvent()
def do_step(self, step_type, destination_line_entry): expected_stack_depth = self.thread.GetNumFrames() if step_type == "into": expected_stack_depth += 1 self.thread.StepInto() elif step_type == "out": expected_stack_depth -= 1 self.thread.StepOut() elif step_type == "over": self.thread.StepOver() else: self.fail ("Unrecognized step type: " + step_type) threads = lldbutil.get_stopped_threads (self.process, lldb.eStopReasonPlanComplete) if len(threads) != 1: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) self.fail ("Failed to stop due to step " + step_type + " operation stepping to: " + destination_description.GetData()) self.thread = threads[0] stop_line_entry = self.thread.GetFrameAtIndex(0).GetLineEntry() self.assertTrue (stop_line_entry.IsValid(), "Stop line entry was not valid.") # Don't use the line entry equal operator because we don't care about the column number. stop_at_right_place = (stop_line_entry.GetFileSpec() == destination_line_entry.GetFileSpec() and stop_line_entry.GetLine() == destination_line_entry.GetLine()) if stop_at_right_place == False: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) actual_description = lldb.SBStream() stop_line_entry.GetDescription(actual_description) self.fail ("Step " + step_type + " stopped at wrong place: expected: " + destination_description.GetData() + " got: " + actual_description.GetData() + ".") real_stack_depth = self.thread.GetNumFrames() if real_stack_depth != expected_stack_depth: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) self.fail ("Step %s to %s got wrong number of frames, should be: %d was: %d."%(step_type, destination_description.GetData(), expected_stack_depth, real_stack_depth))
def assert_data(self, func, arg, expected): """ Asserts func(SBError error, arg) == expected. """ error = lldb.SBError() result = func(error, arg) if not error.Success(): stream = lldb.SBStream() error.GetDescription(stream) self.assertTrue(error.Success(), "{0!s}(error, {1!s}) did not succeed: {2!s}".format(func.__name__, arg, stream.GetData())) self.assertTrue(expected == result, "{0!s}(error, {1!s}) == {2!s} != {3!s}".format(func.__name__, arg, result, expected))
def fuzz_obj(obj): obj.GetName() obj.GetMangledName() obj.GetInstructions(lldb.SBTarget()) sa = obj.GetStartAddress() ea = obj.GetEndAddress() # Do fuzz testing on the address obj, it should not crash lldb. import sb_address sb_address.fuzz_obj(sa) sb_address.fuzz_obj(ea) obj.GetPrologueByteSize obj.GetDescription(lldb.SBStream())
def assert_data(self, func, arg, expected): """ Asserts func(SBError error, arg) == expected. """ error = lldb.SBError() result = func(error, arg) if not error.Success(): stream = lldb.SBStream() error.GetDescription(stream) self.assertTrue(error.Success(), "%s(error, %s) did not succeed: %s" % (func.__name__, arg, stream.GetData())) self.assertTrue(expected == result, "%s(error, %s) == %s != %s" % (func.__name__, arg, result, expected))
def get_item_dictionary(self): id = self.frame.GetFrameID() name = 'frame #%u' % (id); value = '0x%16.16x' % (self.frame.GetPC()) stream = lldb.SBStream() self.frame.GetDescription(stream) summary = stream.GetData().split("`")[1] return { '#0' : name, 'value': value, 'summary': summary, 'children' : self.frame.GetVariables(True, True, True, True).GetSize() > 0, 'tree-item-delegate' : self }
def do_test(self): """Test that Swift.String formats properly""" self.build() lldbutil.run_to_source_breakpoint( self, 'Set breakpoint here', lldb.SBFileSpec('main.swift')) s1 = self.frame().FindVariable("s1") s2 = self.frame().FindVariable("s2") lldbutil.check_variable(self, s1, summary='"Hello world"') lldbutil.check_variable(self, s2, summary='"ΞΕΛΛΘ"') TheVeryLongOne = self.frame().FindVariable("TheVeryLongOne") summaryOptions = lldb.SBTypeSummaryOptions() summaryOptions.SetCapping(lldb.eTypeSummaryUncapped) uncappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(uncappedSummaryStream, summaryOptions) uncappedSummary = uncappedSummaryStream.GetData() self.assertTrue(uncappedSummary.find("someText") > 0, "uncappedSummary does not include the full string") summaryOptions.SetCapping(lldb.eTypeSummaryCapped) cappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(cappedSummaryStream, summaryOptions) cappedSummary = cappedSummaryStream.GetData() self.assertTrue( cappedSummary.find("someText") <= 0, "cappedSummary includes the full string") IContainZerosASCII = self.frame().FindVariable("IContainZerosASCII") IContainZerosUnicode = self.frame().FindVariable("IContainZerosUnicode") lldbutil.check_variable( self, IContainZerosASCII, summary='"a\\0b\\0c\\0d"') lldbutil.check_variable( self, IContainZerosUnicode, summary='"HFIHЗIHF\\0VЭHVHЗ90HGЭ"')
def description(self): logger = lldb.formatters.Logger.Logger() stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) name_vo = self.valobj.CreateValueFromExpression( "name", "(NSString*)[" + stream.GetData() + " name]") reason_vo = self.valobj.CreateValueFromExpression( "reason", "(NSString*)[" + stream.GetData() + " reason]") if name_vo.IsValid() and reason_vo.IsValid(): return CFString.CFString_SummaryProvider( name_vo, None) + ' ' + CFString.CFString_SummaryProvider( reason_vo, None) return '<variable is not NSException>'
def run(self): value = self.value_for_expression(self.command) stream = lldb.SBStream() value.GetDescription(stream) description = stream.GetData() (description, ) = re.findall(r'^[^=]+= (.*)', description) readable_description = re.findall(r'^0x\w+ (.+)', description) if readable_description: description = readable_description[0] self.result.PutCString(description)
def hit_correct_function(self, thread, pattern): # print "Check if we got to: ", pattern self.correct_stop_reason(thread) name = thread.frames[0].GetFunctionName() line_entry = thread.frames[0].GetLineEntry() desc = lldb.SBStream() if line_entry.IsValid(): line_entry.GetDescription(desc) else: desc.Print(name) self.assertTrue( pattern in name, "Got to '%s' not the expected function '%s'." % (desc.GetData(), pattern))
def length(self): logger = lldb.formatters.Logger.Logger() logger >> "NSDataUnknown_SummaryProvider length" stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) logger >> stream.GetData() num_children_vo = self.valobj.CreateValueFromExpression("count","(int)[" + stream.GetData() + " length]"); logger >> "still in after expression: " + str(num_children_vo) if num_children_vo.IsValid(): logger >> "wow - expr output is valid: " + str(num_children_vo.GetValueAsUnsigned()) return num_children_vo.GetValueAsUnsigned(0) logger >> "invalid expr output - too bad" return '<variable is not NSData>'