rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def reorderVV(node, align, model):
def reorderVV(node, align, model, bDebug):
def reorderVV(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ):
if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.append(extra)
def reorderVV(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ):
if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.append(extra)
def reorderVV(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ):
if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra)
def reorderVV(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ):
if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra)
def reorderVV(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ):
def reorderNN(node, align, model):
def reorderNN(node, align, model, bDebug):
def reorderNN(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos == 'DEC' or left_child.pos == 'DEG': if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): reorderDE(left_child, align, model)
if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra)
def reorderNN(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos == 'DEC' or left_child.pos == 'DEG': if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): reorderDE(left_child, align, model)
if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra)
def reorderNN(node, align, model): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos == 'DEC' or left_child.pos == 'DEG': if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): reorderDE(left_child, align, model)
def reorderNode(node, align, model):
def reorderNode(node, align, model, bDebug):
def reorderNode(node, align, model): # recursion for left_child in node.left_children: reorderNode(left_child, align, model) for right_child in node.right_children: reorderNode(right_child, align, model) # ver if node.pos == 'VV': reorderVV(node, align, model) # n. elif node.pos in ['NN', 'NR']: reorderNN(node, align, model) # lc elif node.pos == 'LC': reorderLC(node, align, model)
reorderNode(left_child, align, model)
reorderNode(left_child, align, model, bDebug)
def reorderNode(node, align, model): # recursion for left_child in node.left_children: reorderNode(left_child, align, model) for right_child in node.right_children: reorderNode(right_child, align, model) # ver if node.pos == 'VV': reorderVV(node, align, model) # n. elif node.pos in ['NN', 'NR']: reorderNN(node, align, model) # lc elif node.pos == 'LC': reorderLC(node, align, model)
reorderNode(right_child, align, model)
reorderNode(right_child, align, model, bDebug)
def reorderNode(node, align, model): # recursion for left_child in node.left_children: reorderNode(left_child, align, model) for right_child in node.right_children: reorderNode(right_child, align, model) # ver if node.pos == 'VV': reorderVV(node, align, model) # n. elif node.pos in ['NN', 'NR']: reorderNN(node, align, model) # lc elif node.pos == 'LC': reorderLC(node, align, model)
reorderVV(node, align, model)
reorderVV(node, align, model, bDebug)
def reorderNode(node, align, model): # recursion for left_child in node.left_children: reorderNode(left_child, align, model) for right_child in node.right_children: reorderNode(right_child, align, model) # ver if node.pos == 'VV': reorderVV(node, align, model) # n. elif node.pos in ['NN', 'NR']: reorderNN(node, align, model) # lc elif node.pos == 'LC': reorderLC(node, align, model)
reorderNN(node, align, model)
reorderNN(node, align, model, bDebug)
def reorderNode(node, align, model): # recursion for left_child in node.left_children: reorderNode(left_child, align, model) for right_child in node.right_children: reorderNode(right_child, align, model) # ver if node.pos == 'VV': reorderVV(node, align, model) # n. elif node.pos in ['NN', 'NR']: reorderNN(node, align, model) # lc elif node.pos == 'LC': reorderLC(node, align, model)
def reorder(tree, align, model): reorderNode(tree.root, align, model)
def reorder(tree, align, model, bDebug): reorderNode(tree.root, align, model, bDebug)
def reorder(tree, align, model): reorderNode(tree.root, align, model) updateIndex(tree)
opts, args = getopt.getopt(sys.argv[1:], "o:i:")
opts, args = getopt.getopt(sys.argv[1:], "o:i:d")
def deg(node): assert node.pos == 'DEG' for left_child in node.left_children: if left_child.pos == 'JJ': return False return True
print 'adapt [-ia|c] [-oi|r|p|d] input model [align]'
print 'adapt [-ia|c] [-oi|r|p|d] [-d] input model [align]'
def deg(node): assert node.pos == 'DEG' for left_child in node.left_children: if left_child.pos == 'JJ': return False return True
reorder(dept, align, model)
reorder(dept, align, model, bDebug)
def deg(node): assert node.pos == 'DEG' for left_child in node.left_children: if left_child.pos == 'JJ': return False return True
print "sys.path[0] =", testPath
def setupSysPath(): testPath = sys.path[0] print "sys.path[0] =", testPath rem = re.match("(^.*/)test$", testPath) if not rem: print "This script expects to reside in .../test." sys.exit(-1) lldbBasePath = rem.group(1) lldbDebugPythonPath = "build/Debug/LLDB.framework/Resources/Python" lldbReleasePythonPath = "build/Release/LLDB.framework/Resources/Python" lldbPythonPath = None if os.path.isfile(lldbDebugPythonPath + "/lldb.py"): lldbPythonPath = lldbDebugPythonPath if os.path.isfile(lldbReleasePythonPath + "/lldb.py"): lldbPythonPath = lldbReleasePythonPath if not lldbPythonPath: print "This script requires lldb.py to be in either " + lldbDebugPythonPath, print "or" + lldbReleasePythonPath sys.exit(-1) sys.path.append(lldbPythonPath)
else: if running: time.sleep(self.timeWait)
def runCmd(self, cmd, msg=None, check=True, trace=False, setCookie=True): """ Ask the command interpreter to handle the command and then check its return status. """ # Fail fast if 'cmd' is not meaningful. if not cmd or len(cmd) == 0: raise Exception("Bad 'cmd' parameter encountered")
f, l, c = c_void_p(), c_uint(), c_uint()
f, l, c = c_object_p(), c_uint(), c_uint()
def init(self): """ Initialize the source location, setting its file, line and column. """ f, l, c = c_void_p(), c_uint(), c_uint() SourceLocation_loc(self, byref(f), byref(l), byref(c)) self.file, self.line, self.column = File(f), l, c return self
self.file, self.line, self.column = File(f), l, c
f = File(f) if f else None self.file, self.line, self.column = f, int(l.value), int(c.value)
def init(self): """ Initialize the source location, setting its file, line and column. """ f, l, c = c_void_p(), c_uint(), c_uint() SourceLocation_loc(self, byref(f), byref(l), byref(c)) self.file, self.line, self.column = File(f), l, c return self
The File class... """ def __init__(self, obj): ClangObject.__init__(self, obj) @property def is_valid(self): return self.obj is not None
The File class represents a particular source file that is part of a translation unit. """
def parse(ix, path, args = []): """ Construct a translation unit from the given source file, applying the given command line argument. """ # TODO: Support unsaved files. argc, argv = len(args), create_string_vector(args) ptr = TranslationUnit_parse(ix, path, argc, byref(argv), 0, 0) return TranslationUnit(ptr, True) if ptr else None
return File_name(self) if self.obj else ""
return File_name(self)
def name(self): """Return the name of the file, if valid. Otherwise, an empty string.""" return File_name(self) if self.obj else ""
return File_time(self) if self.obj else -1
return File_time(self)
def time(self): """Return the time of the file, if valid. Otherwise, -1.""" return File_time(self) if self.obj else -1
SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_void_p), c_uint_p, c_uint_p]
SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), c_uint_p, c_uint_p]
def load(self, fun, data = None): """ Recursively visit any elements declared or referenced within this declaration. """ f = lambda d, c, x: fun(Declaration(d), c, x) Declaration_load(self, Callback(f), data)
SourceRange_start.argtypes = [SourceLocation] SourceRange_start.restype = SourceRange
SourceRange_start.argtypes = [SourceRange] SourceRange_start.restype = SourceLocation
def load(self, fun, data = None): """ Recursively visit any elements declared or referenced within this declaration. """ f = lambda d, c, x: fun(Declaration(d), c, x) Declaration_load(self, Callback(f), data)
SourceRange_end.argtypes = [SourceLocation] SourceRange_end.restype = SourceRange
SourceRange_end.argtypes = [SourceRange] SourceRange_end.restype = SourceLocation
def load(self, fun, data = None): """ Recursively visit any elements declared or referenced within this declaration. """ f = lambda d, c, x: fun(Declaration(d), c, x) Declaration_load(self, Callback(f), data)
@unittest2.expectedFailure
def test_help_should_not_hang_emacsshell(self): """Command 'settings set term-width 0' should not hang the help command.""" self.runCmd("settings set term-width 0") self.expect("help", startstr = 'The following is a list of built-in, permanent debugger commands')
'clang_type = "@interface NSString@end"'])
'clang_type = "@interface NSString'])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
'clang_type = "@interface MyString'])
'clang_type = "@interface MyString', 'NSString * str;', 'NSDate * date;'])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.expect("expr -o -- self", "Object description displayed correctly", startstr = "Hello from ", substrs = ["a.out", "with timestamp: "]) self.expect("expr self->non_existent_member", COMMAND_FAILED_AS_EXPECTED, error=True, startstr = "error: 'MyString' does not have a member named 'non_existent_member'")
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.expect("frame variable *self", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["(MyString *) self", "(NSString *) str", "(NSDate *) date"]) self.expect("expr self->non_existent_member", COMMAND_FAILED_AS_EXPECTED, error=True, startstr = "error: 'MyString' does not have a member named 'non_existent_member'")
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint delete") self.expect("breakpoint set -f main.m -l %d" % self.line, BREAKPOINT_CREATED, startstr = "Breakpoint created: 2: file ='main.m', line = %d, locations = 1" % self.line) self.runCmd("process continue") self.expect("expr -o -- my", "Object description displayed correctly", startstr = "Hello from ", substrs = ["a.out", "with timestamp: "])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
@unittest2.expectedFailure
def test_with_dsym_and_run_command(self): """Create target, breakpoint, launch a process, and then kill it.
self.breakAfterLaunch(process, "main")
def hello_world_python(self, useLaunchAPI): """Create target, breakpoint, launch a process, and then kill it."""
if old_stdout.name != '<stderr>' and config.get('split_stderr'):
if old_stdout.name != '<stdout>' and config.get('split_stdout'):
def lldbLoggings(): """Check and do lldb loggings if necessary.""" # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is # defined. Use ${LLDB_LOG} to specify the log file. ci = lldb.DBG.GetCommandInterpreter() res = lldb.SBCommandReturnObject() if ("LLDB_LOG" in os.environ): if ("LLDB_LOG_OPTION" in os.environ): lldb_log_option = os.environ["LLDB_LOG_OPTION"] else: lldb_log_option = "event process" ci.HandleCommand( "log enable -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option, res) if not res.Succeeded(): raise Exception('log enable failed (check LLDB_LOG env variable.') # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined. # Use ${GDB_REMOTE_LOG} to specify the log file. if ("GDB_REMOTE_LOG" in os.environ): if ("GDB_REMOTE_LOG_OPTION" in os.environ): gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"] else: gdb_remote_log_option = "packets" ci.HandleCommand( "log enable -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote " + gdb_remote_log_option, res) if not res.Succeeded(): raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
substrs = ["@interface NSString : NSObject@end"])
substrs = ['name = "NSString"', 'clang_type = "@interface NSString@end"'])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
substrs = ["@interface MyString : NSObject", "NSString * str;", "NSDate * date;"])
substrs = ['name = "MyString"', 'clang_type = "@interface MyString'])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.ci.HandleCommand("help", res, False)
self.ci.HandleCommand("help", res) self.assertTrue(res.Succeeded()) self.assertTrue(res.GetOutput().startswith( 'The following is a list of built-in, permanent debugger commands')) def test_help_should_not_hang_emacsshell(self): """'set term-width 0' should not hang the help command.""" res = lldb.SBCommandReturnObject() self.ci.HandleCommand("set term-width 0", res) self.assertTrue(res.Succeeded()) self.ci.HandleCommand("help", res)
def test_simplehelp(self): """A simple test of 'help' command and its output.""" res = lldb.SBCommandReturnObject() self.ci.HandleCommand("help", res, False) self.assertTrue(res.Succeeded()) self.assertTrue(res.GetOutput().startswith( 'The following is a list of built-in, permanent debugger commands')) #print res.GetOutput()
self.runCmd(str, trace = (True if trace else False), check = not error)
self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
def expect(self, str, msg=None, patterns=None, startstr=None, substrs=None, trace=False, error=False, matching=True, exe=True): """ Similar to runCmd; with additional expect style output matching ability.
self.runCmd("expression i = \\'b\\'")
self.runCmd("expression i = 'b'")
def set_values(self): """Test settings and readings of program variables.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
def test_with_dsym(self):
def test_with_dsym_python(self):
def test_with_dsym(self): """Exercise some thread and frame APIs to break if c() is called by a().""" self.buildDsym() self.do_conditional_break()
def test_with_dwarf(self):
def test_with_dwarf_python(self):
def test_with_dwarf(self): """Exercise some thread and frame APIs to break if c() is called by a().""" self.buildDwarf() self.do_conditional_break()
fname = os.path.join(dname, "%s.log" % self.id())
fname = os.path.join(dname, "%s-%s.log" % (prefix, self.id()))
def dumpSessionInfo(self): """ Dump the debugger interactions leading to a test error/failure. This allows for more convenient postmortem analysis.
output.find('main.c:40') > 0 and
def test_dead_strip(self): """Test breakpoint works correctly with dead-code stripping.""" res = self.res exe = os.path.join(os.getcwd(), "a.out") self.ci.HandleCommand("file " + exe, res) self.assertTrue(res.Succeeded())
main_bp = target.BreakpointCreateByName ("main", "a.out");
main_bp = target.BreakpointCreateByName ("main", sys.argv[1]);
def disassemble_instructions (insts): for i in range(0, insts.GetSize()): print insts.GetInstructionAtIndex(i)
process = target.LaunchProcess (sys.argv[2:], [''], "dev/stdout", 0, False)
process = target.LaunchProcess (sys.argv[2:], [''], "/dev/stdout", 0, False)
def disassemble_instructions (insts): for i in range(0, insts.GetSize()): print insts.GetInstructionAtIndex(i)
@unittest2.expectedFailure
def test_break_with_dwarf(self): """Test setting objc breakpoints using 'regexp-break' and 'breakpoint set'.""" self.buildDwarf() self.break_on_objc_methods()
@unittest2.expectedFailure
def test_data_type_and_expr_with_dsym(self): """Lookup objective-c data types and evaluate expressions.""" self.buildDsym() self.data_type_and_expr_objc()
startstr = "Hello from ", substrs = ["a.out", "with timestamp: "])
patterns = ["Hello from.*a.out.*with timestamp: "])
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.runCmd("disassemble")
self.runCmd("disassemble -f")
def do_simple_disasm(self): """Do a bunch of simple disassemble commands.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
if substrs:
if substrs and matched:
def expect(self, cmd, msg=None, startstr=None, substrs=None, trace=False): """ Similar to runCmd; with additional expect style output matching ability.
self.test_sub_dir = str(test_sub_dir).split(';')
self.test_sub_dir = os.path.normcase(str(test_sub_dir)).split(';')
def __init__(self, test_sub_dir, test_suffix): self.test_sub_dir = str(test_sub_dir).split(';') self.test_suffix = str(test_suffix)
if not filename in self.test_sub_dir:
if not os.path.normcase(filename) in self.test_sub_dir:
def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig): source_path = testSuite.getSourcePath(path_in_suite) for filename in os.listdir(source_path): # Check for the one subdirectory (build directory) tests will be in. if not filename in self.test_sub_dir: continue
def test_with_dsym_and_run_command(self): """Test 'frame variable var_name' on some variables with array types."""
def test_with_dsym_and_python_api(self): """Test stepping through ObjC method dispatch in various forms."""
def test_with_dsym_and_run_command(self): """Test 'frame variable var_name' on some variables with array types.""" self.buildDsym() self.objc_stepping()
@unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin") def test_with_dsym_and_python_api(self): """Use Python APIs to inspect variables with array types.""" self.buildDsym()
def test_with_dward_and_python_api(self): """Test stepping through ObjC method dispatch in various forms.""" self.buildDwarf()
def test_with_dsym_and_run_command(self): """Test 'frame variable var_name' on some variables with array types.""" self.buildDsym() self.objc_stepping()
self.runCmd('settings set process.run-args A B C') self.runCmd('settings set process.env-vars ["MY_ENV_VAR"]=YES')
self.runCmd('settings set target.process.run-args A B C') self.runCmd('settings set target.process.env-vars ["MY_ENV_VAR"]=YES')
def pass_run_args_and_env_vars(self): """Test that run-args and env-vars are passed to the launched process.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.runCmd("settings set process.output-path 'stdout.txt'") self.expect("settings show process.output-path", startstr = "process.output-path (string) = 'stdout.txt'")
self.runCmd("settings set target.process.output-path 'stdout.txt'") self.expect("settings show target.process.output-path", startstr = "target.process.output-path (string) = 'stdout.txt'")
def test_set_output_path(self): """Test that setting process.output-path for the launched process works.""" self.buildDefault()
self.ci.HandleCommand("run", res) time.sleep(1)
def test_step_into_stl(self): """Test that we can successfully step into an STL function.""" res = self.res exe = os.path.join(os.getcwd(), "a.out") # The following two lines, if uncommented, will enable loggings. #self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res) #self.assertTrue(res.Succeeded()) self.ci.HandleCommand("file " + exe, res) self.assertTrue(res.Succeeded())
time.sleep(1)
time.sleep(0.1)
def test_step_into_stl(self): """Test that we can successfully step into an STL function.""" res = self.res exe = os.path.join(os.getcwd(), "a.out") # The following two lines, if uncommented, will enable loggings. #self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res) #self.assertTrue(res.Succeeded()) self.ci.HandleCommand("file " + exe, res) self.assertTrue(res.Succeeded())
for i in range(1, len(sys.argv)):
while index < len(sys.argv):
def parseOptionsAndInitTestdirs(): """Initialize the list of directories containing our unittest scripts. '-h/--help as the first option prints out usage info and exit the program. """ global configFile global delay global filterspec global fs4all global ignore global skipLongRunningTest global regexp global verbose global testdirs if len(sys.argv) == 1: return # Process possible trace and/or verbose flag, among other things. index = 1 for i in range(1, len(sys.argv)): if not sys.argv[index].startswith('-'): # End of option processing. break if sys.argv[index].find('-h') != -1: usage() elif sys.argv[index].startswith('-c'): # Increment by 1 to fetch the config file name option argument. index += 1 if index >= len(sys.argv) or sys.argv[index].startswith('-'): usage() configFile = sys.argv[index] if not os.path.isfile(configFile): print "Config file:", configFile, "does not exist!" usage() index += 1 elif sys.argv[index].startswith('-d'): delay = True index += 1 elif sys.argv[index].startswith('-f'): # Increment by 1 to fetch the filter spec. index += 1 if index >= len(sys.argv) or sys.argv[index].startswith('-'): usage() filterspec = sys.argv[index] index += 1 elif sys.argv[index].startswith('-g'): fs4all = True index += 1 elif sys.argv[index].startswith('-i'): ignore = True index += 1 elif sys.argv[index].startswith('-l'): skipLongRunningTest = False index += 1 elif sys.argv[index].startswith('-p'): # Increment by 1 to fetch the reg exp pattern argument. index += 1 if index >= len(sys.argv) or sys.argv[index].startswith('-'): usage() regexp = sys.argv[index] index += 1 elif sys.argv[index].startswith('-t'): os.environ["LLDB_COMMAND_TRACE"] = "YES" index += 1 elif sys.argv[index].startswith('-v'): verbose = 2 index += 1 elif sys.argv[index].startswith('-w'): os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES' index += 1 else: print "Unknown option: ", sys.argv[index] usage() # Gather all the dirs passed on the command line. if len(sys.argv) > index: testdirs = map(os.path.abspath, sys.argv[index:]) # Source the configFile if specified. # The side effect, if any, will be felt from this point on. An example # config file may be these simple two lines: # # sys.stderr = open("/tmp/lldbtest-stderr", "w") # sys.stdout = open("/tmp/lldbtest-stdout", "w") # # which will reassign the two file objects to sys.stderr and sys.stdout, # respectively. # # See also lldb-trunk/example/test/usage-config. global config if configFile: # Pass config (a dictionary) as the locals namespace for side-effect. execfile(configFile, globals(), config) #print "config:", config #print "sys.stderr:", sys.stderr #print "sys.stdout:", sys.stdout
'a.c:14',
def test_load_unload(self): """Test breakpoint by name works correctly with dlopen'ing."""
self.runCmd("continue") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, substrs = ['state is Stopped', 'a_function', 'stop reason = breakpoint']) self.expect("breakpoint list", BREAKPOINT_HIT_ONCE, substrs = [' resolved, hit count = 2'])
def test_load_unload(self): """Test breakpoint by name works correctly with dlopen'ing."""
if (temp_str.lower() == "quit()"):
if (temp_str.lower() == "quit()" or temp_str.lower() == "exit()"):
def process_input (self, in_str): # Canonicalize the format of the input string temp_str = in_str temp_str.strip(' \t') words = temp_str.split() temp_str = ('').join(words)
self.expect("expression (int)[id length]",
self.expect("expression (int)[str_id length]",
def NSString_expr(self): """Test expression commands for NSString.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.expect("expression [str description]") self.expect("expression [id description]")
self.expect("expression [str description]", patterns = ["\(id\) \$.* = 0x"]) self.expect("expression [str_id description]", patterns = ["\(id\) \$.* = 0x"])
def NSString_expr(self): """Test expression commands for NSString.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
self.expect("expression id.description")
self.expect("expression str_id.description")
def NSString_expr(self): """Test expression commands for NSString.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
@unittest2.expectedFailure
def test_set_prompt(self): """Test that 'set prompt' actually changes the prompt."""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
def lldbLoggings(): """Check and do lldb loggings if necessary.""" # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is # defined. Use ${LLDB_LOG} to specify the log file. ci = lldb.DBG.GetCommandInterpreter() res = lldb.SBCommandReturnObject() if ("LLDB_LOG" in os.environ): if ("LLDB_LOG_OPTION" in os.environ): lldb_log_option = os.environ["LLDB_LOG_OPTION"] else: lldb_log_option = "event process" ci.HandleCommand( "log enable -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option, res) if not res.Succeeded(): raise Exception('log enable failed (check LLDB_LOG env variable.') # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined. # Use ${GDB_REMOTE_LOG} to specify the log file. if ("GDB_REMOTE_LOG" in os.environ): if ("GDB_REMOTE_LOG_OPTION" in os.environ): gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"] else: gdb_remote_log_option = "packets" ci.HandleCommand( "log enable -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote " + gdb_remote_log_option, res) if not res.Succeeded(): raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
breakpoint = target.BreakpointCreateByLocation("main.cpp", 68)
breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
def break_and_print_stacktraces(self): """Break at main.cpp:68 and do a threads dump""" exe = os.path.join(os.getcwd(), "a.out")
def test_hellp_world_python(self):
def test_hello_world_python(self):
def test_hellp_world_python(self): """Create target, breakpoint, launch a process, and then kill it."""
@unittest2.expectedFailure
def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.')
ln = ln.replace(a,b)
ln = re.sub(a, b, ln)
def processLine(ln): # Apply substitutions for a,b in substitutions: ln = ln.replace(a,b)
pass if not res.Succeeded(): raise Exception('log enable failed (check your LLDB_LOG env variable...')
if not res.Succeeded(): raise Exception('log enable failed (check your LLDB_LOG env variable...')
def visit(prefix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" global suite for name in names: if os.path.isdir(os.path.join(dir, name)): continue if '.py' == os.path.splitext(name)[1] and name.startswith(prefix): # We found a pattern match for our test case. Add it to the suite. if not sys.path.count(dir): sys.path.append(dir) base = os.path.splitext(name)[0] suite.addTests(unittest.defaultTestLoader.loadTestsFromName(base))
@unittest2.expectedFailure
def test_with_dwarf_and_python_api(self): """Use Python APIs to create a breakpoint by (filespec, line).""" self.buildDwarf() self.breakpoint_creation_by_filespec_python()
@unittest2.expectedFailure
def test_with_dsym_and_expr_parser(self): """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" self.buildDsym() self.class_types_expr_parser()
startstr = '(class C *const) this = ')
substrs = ['C *const) this = '])
def class_types(self): """Test 'frame variable this' when stopped on a class constructor.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
print 'This script requires lldb.py to be in either ' + dbgPath, print ' or' + relPath
print 'This script requires lldb.py to be in either ' + dbgPath + ',', print relPath + ', or ' + baiPath
def setupSysPath(): """Add LLDB.framework/Resources/Python to the search paths for modules.""" # Get the directory containing the current script. scriptPath = sys.path[0] if not scriptPath.endswith('test'): print "This script expects to reside in lldb's test directory." sys.exit(-1) os.environ["LLDB_TEST"] = scriptPath pluginPath = os.path.join(scriptPath, 'plugins') base = os.path.abspath(os.path.join(scriptPath, os.pardir)) dbgPath = os.path.join(base, 'build', 'Debug', 'LLDB.framework', 'Resources', 'Python') relPath = os.path.join(base, 'build', 'Release', 'LLDB.framework', 'Resources', 'Python') lldbPath = None if os.path.isfile(os.path.join(dbgPath, 'lldb.py')): lldbPath = dbgPath elif os.path.isfile(os.path.join(relPath, 'lldb.py')): lldbPath = relPath if not lldbPath: print 'This script requires lldb.py to be in either ' + dbgPath, print ' or' + relPath sys.exit(-1) sys.path.append(lldbPath) sys.path.append(scriptPath) sys.path.append(pluginPath)
def test_with_dsym_python(self):
def test_with_dsym_and_run_command(self):
def test_with_dsym_python(self): """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" self.buildDsym() self.breakpoint_conditions()
def test_with_dwarf_python(self):
def test_with_dwarf_and_run_command(self):
def test_with_dwarf_python(self): """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" self.buildDwarf() self.breakpoint_conditions()
def print_var_value (v, file, frame): if v.GetNumChildren() > 0: for c in range(v.GetNumChildren()): if v.GetChildAtIndex(c) is None: file.write("None") else: if (v.GetChildAtIndex(c).GetName()) is None: file.write("None") else: file.write(v.GetChildAtIndex(c).GetName()) file.write('=') print_var_value(v.GetChildAtIndex(c), file, frame) file.write(',') else: if v.GetValue(frame) is None: file.write("None") else: file.write(v.GetValue(frame))
class BreakPoint: def __init__(self, bp_name): self.name = bp_name self.values = {}
def print_var_value (v, file, frame): if v.GetNumChildren() > 0: for c in range(v.GetNumChildren()): if v.GetChildAtIndex(c) is None: file.write("None") else: if (v.GetChildAtIndex(c).GetName()) is None: file.write("None") else: file.write(v.GetChildAtIndex(c).GetName()) file.write('=') print_var_value(v.GetChildAtIndex(c), file, frame) file.write(',') else: if v.GetValue(frame) is None: file.write("None") else: file.write(v.GetValue(frame))
def print_vars (vars, fname, line, file, frame, target, thread): count = thread.GetStopReasonDataCount() bid = 0 tid = 0 for i in range(count): id = thread.GetStopReasonDataAtIndex(i) bp = target.FindBreakpointByID(id) if bp.IsValid(): if bp.IsEnabled() == True: bid = bp.GetID() tid = bp.GetThreadID() bp.SetEnabled(False) else: bp_loc = bp.FindLocationByID(thread.GetStopReasonDataAtIndex(i+1)) if bp_loc.IsValid(): bid = bp_loc.GetBreakPoint().GetID() tid = bp_loc.ThreadGetID() bp_loc.SetEnabled(False);
def __cmp__(self, other): return cmp(self.values, other.values)
def print_vars (vars, fname, line, file, frame, target, thread): # disable this thread. count = thread.GetStopReasonDataCount() bid = 0 tid = 0 for i in range(count): id = thread.GetStopReasonDataAtIndex(i) bp = target.FindBreakpointByID(id) if bp.IsValid(): if bp.IsEnabled() == True: bid = bp.GetID() tid = bp.GetThreadID() bp.SetEnabled(False) else: bp_loc = bp.FindLocationByID(thread.GetStopReasonDataAtIndex(i+1)) if bp_loc.IsValid(): bid = bp_loc.GetBreakPoint().GetID() tid = bp_loc.ThreadGetID() # print " { ", bp_loc.ThreadGetID(), " : ", bp_loc.GetBreakPoint().GetID(), " }} " bp_loc.SetEnabled(False); for i in range(vars.GetSize()): file.write("#Argument ") file.write(fname) file.write(':') file.write(str(line)) file.write(' ') file.write(str(tid)) file.write(':') file.write(str(bid)) file.write(' ') v = vars.GetValueAtIndex(i) file.write(v.GetName()) file.write(' ') print_var_value (v, file, frame) file.write('\n')
for i in range(vars.GetSize()): file.write(" file.write(fname) file.write(':') file.write(str(line)) file.write(' ') file.write(str(tid)) file.write(':') file.write(str(bid)) file.write(' ') v = vars.GetValueAtIndex(i) file.write(v.GetName()) file.write(' ') print_var_value (v, file, frame) file.write('\n') def set_breakpoints (target, breakpoint_filename): f = open(breakpoint_filename, "r")
def read_input(filename, dict): f = open(filename, "r")
def print_vars (vars, fname, line, file, frame, target, thread): # disable this thread. count = thread.GetStopReasonDataCount() bid = 0 tid = 0 for i in range(count): id = thread.GetStopReasonDataAtIndex(i) bp = target.FindBreakpointByID(id) if bp.IsValid(): if bp.IsEnabled() == True: bid = bp.GetID() tid = bp.GetThreadID() bp.SetEnabled(False) else: bp_loc = bp.FindLocationByID(thread.GetStopReasonDataAtIndex(i+1)) if bp_loc.IsValid(): bid = bp_loc.GetBreakPoint().GetID() tid = bp_loc.ThreadGetID() # print " { ", bp_loc.ThreadGetID(), " : ", bp_loc.GetBreakPoint().GetID(), " }} " bp_loc.SetEnabled(False); for i in range(vars.GetSize()): file.write("#Argument ") file.write(fname) file.write(':') file.write(str(line)) file.write(' ') file.write(str(tid)) file.write(':') file.write(str(bid)) file.write(' ') v = vars.GetValueAtIndex(i) file.write(v.GetName()) file.write(' ') print_var_value (v, file, frame) file.write('\n')
bp = target.BreakpointCreateByLocation (str(c[0]), int(c[1]))
if c[0] == " bp = dict.get(c[2]) if bp is None: bp = BreakPoint(c[1]) dict[c[2]] = bp bp.recordArgument(c[3], c[4])
def set_breakpoints (target, breakpoint_filename): f = open(breakpoint_filename, "r") lines = f.readlines() for l in range(len(lines)): c = lines[l].split() # print "setting break point - ", c bp = target.BreakpointCreateByLocation (str(c[0]), int(c[1])) f.close()
def stop_at_breakpoint (process): if process.IsValid(): state = process.GetState() if state != lldb.eStateStopped: return lldb.eStateInvalid thread = process.GetThreadAtIndex(0) if thread.IsValid(): if thread.GetStopReason() == lldb.eStopReasonBreakpoint: return lldb.eStateStopped else: return lldb.eStateInvalid else: return lldb.eStateInvalid
f1_breakpoints = {} read_input(sys.argv[1], f1_breakpoints) f1_items = f1_breakpoints.items() f2_breakpoints = {} read_input(sys.argv[2], f2_breakpoints) f2_items = f2_breakpoints.items() mismatch = 0 for f2bp in range(len(f2_items)): id = f2_items[f2bp][0] bp = f2_items[f2bp][1] bp1 = f1_breakpoints.get(id) if bp1 is None: print "bp is missing"
def stop_at_breakpoint (process): if process.IsValid(): state = process.GetState() if state != lldb.eStateStopped: return lldb.eStateInvalid thread = process.GetThreadAtIndex(0) if thread.IsValid(): if thread.GetStopReason() == lldb.eStopReasonBreakpoint: return lldb.eStateStopped else: return lldb.eStateInvalid else: return lldb.eStateInvalid else: return lldb.eStateInvalid
return lldb.eStateInvalid
if bp1 != bp: mismatch = mismatch + 1
def stop_at_breakpoint (process): if process.IsValid(): state = process.GetState() if state != lldb.eStateStopped: return lldb.eStateInvalid thread = process.GetThreadAtIndex(0) if thread.IsValid(): if thread.GetStopReason() == lldb.eStopReasonBreakpoint: return lldb.eStateStopped else: return lldb.eStateInvalid else: return lldb.eStateInvalid else: return lldb.eStateInvalid
debugger = lldb.SBDebugger.Create() debugger.SetAsync (False) target = debugger.CreateTargetWithFileAndArch (sys.argv[1], lldb.LLDB_ARCH_DEFAULT) if target.IsValid(): set_breakpoints (target, sys.argv[2]) process = target.LaunchProcess ([''], [''], "/dev/stdout", 0, False) file=open(str(sys.argv[3]), 'w') while stop_at_breakpoint(process) == lldb.eStateStopped: thread = process.GetThreadAtIndex (0) frame = thread.GetFrameAtIndex (0) if frame.IsValid(): function = frame.GetFunction() if function.IsValid(): fname = function.GetMangledName() if fname is None: fname = function.GetName() vars = frame.GetVariables(1,0,0,0) line = frame.GetLineEntry().GetLine() print_vars (vars, fname, line, file, frame, target, thread) process.Continue() file.close() lldb.SBDebugger.Terminate()
l2 = len(f2_items) print "==========" if l2 != 0: print sys.argv[3]," success rate is", (l2-mismatch)*100/l2,"%" else: print sys.argv[3]," success rate is 100%" print "=========="
def stop_at_breakpoint (process): if process.IsValid(): state = process.GetState() if state != lldb.eStateStopped: return lldb.eStateInvalid thread = process.GetThreadAtIndex(0) if thread.IsValid(): if thread.GetStopReason() == lldb.eStopReasonBreakpoint: return lldb.eStateStopped else: return lldb.eStateInvalid else: return lldb.eStateInvalid else: return lldb.eStateInvalid
@unittest2.skip("rdar://problem/8648070 'expression *bar_ptr' seg faults")
def test_with_dsym_and_run_command(self): """Display *bar_ptr when stopped on a function with forward declaration of struct bar.""" self.buildDsym() self.forward_declaration()
@unittest2.expectedFailure
def test_with_dsym(self): """Test that we can successfully step into an STL function.""" self.buildDsym() self.step_into_stl()
lldb.SBDebugger.Initialize()
def disassemble_instructions (insts): for i in range(insts.GetSize()): print insts.GetInstructionAtIndex(i)
@unittest2.expectedFailure
def test_with_dsym_and_python_api(self): """Use Python APIs to inspect a bitfields variable.""" self.buildDsym() self.bitfields_variable_python()
try: dt = re.match("^\$[0-9]+ = \((.*)\)", output).group(1) except: self.fail("Data type from expression parser is parsed correctly")
def generic_type_expr_tester(self, atoms, quotedDisplay=False): """Test that variable expressions with basic types are evaluated correctly."""
self.expect(dt, "Display type: '%s' must contain the type atoms: '%s'" % (dt, atoms), exe=False, substrs = list(atoms))
def generic_type_expr_tester(self, atoms, quotedDisplay=False): """Test that variable expressions with basic types are evaluated correctly."""
valPart = ("'%s'" if quotedDisplay else "%s") % val self.expect(output, Msg(var, val), exe=False, substrs = [valPart])
def generic_type_expr_tester(self, atoms, quotedDisplay=False): """Test that variable expressions with basic types are evaluated correctly."""
import lldb
import lldb, atexit
def visit(prefix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" global suite for name in names: if os.path.isdir(os.path.join(dir, name)): continue if '.py' == os.path.splitext(name)[1] and name.startswith(prefix): # We found a pattern match for our test case. Add it to the suite. if not sys.path.count(dir): sys.path.append(dir) base = os.path.splitext(name)[0] suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
unittest2.TextTestRunner(verbosity=verbose).run(suite)
result = unittest2.TextTestRunner(verbosity=verbose).run(suite)
def visit(prefix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" global suite for name in names: if os.path.isdir(os.path.join(dir, name)): continue if '.py' == os.path.splitext(name)[1] and name.startswith(prefix): # We found a pattern match for our test case. Add it to the suite. if not sys.path.count(dir): sys.path.append(dir) base = os.path.splitext(name)[0] suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
time.sleep(1) lldb.SBDebugger.Terminate()
sys.exit(not result.wasSuccessful)
def visit(prefix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" global suite for name in names: if os.path.isdir(os.path.join(dir, name)): continue if '.py' == os.path.splitext(name)[1] and name.startswith(prefix): # We found a pattern match for our test case. Add it to the suite. if not sys.path.count(dir): sys.path.append(dir) base = os.path.splitext(name)[0] suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
lldb.SBDebugger.SetAsync(True) self.m_commandInterpreter = lldb.SBDebugger.GetCommandInterpreter()
debugger = lldb.SBDebugger.Create() debugger.SetAsync(True) self.m_commandInterpreter = debugger.GetCommandInterpreter()
def setUp(self): lldb.SBDebugger.SetAsync(True) self.m_commandInterpreter = lldb.SBDebugger.GetCommandInterpreter() if not self.m_commandInterpreter: print "Couldn't get the command interpreter" sys.exit(-1)
print ret
def runTest(self): ret = self.runCommand("show arch", "show-arch") print ret
self.expect("breakpoint list", "Expect all 3 breakpoints with hit count of 2", patterns = ["1\.1: .+ resolved, hit count = 2 +Options: disabled", "1\.2: .+ resolved, hit count = 2", "1\.3: .+ resolved, hit count = 2"])
self.expect("breakpoint list", "The breakpoints should report correct hit counts", patterns = ["1\.1: .+ unresolved, hit count = 0 +Options: disabled", "1\.2: .+ resolved, hit count = 1", "1\.3: .+ resolved, hit count = 1"])
def breakpoint_locations_test(self): """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)