blob: 5b7578920e20ae39a0fcc3e7f76e981e0fc2fb7e [file] [log] [blame]
Johnny Chen14097802011-04-28 21:31:18 +00001#
Johnny Chenc6220052011-04-28 23:53:16 +00002# modify-lldb-python.py
Johnny Chen14097802011-04-28 21:31:18 +00003#
4# This script modifies the lldb module (which was automatically generated via
Johnny Chen22e418a2011-04-29 19:22:24 +00005# running swig) to support iteration and/or equality operations for certain lldb
6# objects, adds a global variable 'debugger_unique_id' and initializes it to 0.
Johnny Chen14097802011-04-28 21:31:18 +00007#
8# It also calls SBDebugger.Initialize() to initialize the lldb debugger
9# subsystem.
10#
11
12import sys, re, StringIO
13
14if len (sys.argv) != 2:
15 output_name = "./lldb.py"
16else:
17 output_name = sys.argv[1] + "/lldb.py"
18
19# print "output_name is '" + output_name + "'"
20
21#
22# lldb_iter() should appear before the our first SB* class definition.
23#
24lldb_iter_def = '''
25# ===================================
26# Iterator for lldb container objects
27# ===================================
28def lldb_iter(obj, getsize, getelem):
29 """A generator adaptor to support iteration for lldb container objects."""
30 size = getattr(obj, getsize)
31 elem = getattr(obj, getelem)
32 for i in range(size()):
33 yield elem(i)
34
35'''
36
Johnny Chen14097802011-04-28 21:31:18 +000037# This supports the iteration protocol.
Johnny Chen14097802011-04-28 21:31:18 +000038iter_def = " def __iter__(self): return lldb_iter(self, '%s', '%s')"
39module_iter = " def module_iter(self): return lldb_iter(self, '%s', '%s')"
40breakpoint_iter = " def breakpoint_iter(self): return lldb_iter(self, '%s', '%s')"
Johnny Chen2077f0d2011-05-17 22:14:39 +000041
Johnny Chena79a21c2011-05-16 20:31:18 +000042# Called to implement the built-in function len().
43# Eligible objects are those containers with unambiguous iteration support.
Johnny Chena79a21c2011-05-16 20:31:18 +000044len_def = " def __len__(self): return self.%s()"
Johnny Chen2077f0d2011-05-17 22:14:39 +000045
Johnny Chen3a3d6592011-04-29 19:03:02 +000046# This supports the rich comparison methods of __eq__ and __ne__.
Johnny Chen7616cb92011-05-02 19:05:52 +000047eq_def = " def __eq__(self, other): return isinstance(other, %s) and %s"
Johnny Chen3a3d6592011-04-29 19:03:02 +000048ne_def = " def __ne__(self, other): return not self.__eq__(other)"
Johnny Chen14097802011-04-28 21:31:18 +000049
Johnny Chen2077f0d2011-05-17 22:14:39 +000050# Called to implement truth value testing and the built-in operation bool();
51# should return False or True, or their integer equivalents 0 or 1.
52# Delegate to self.IsValid() if it is defined for the current lldb object.
53nonzero_def = " def __nonzero__(self): return self.IsValid()"
54
Johnny Chen14097802011-04-28 21:31:18 +000055#
56# The dictionary defines a mapping from classname to (getsize, getelem) tuple.
57#
58d = { 'SBBreakpoint': ('GetNumLocations', 'GetLocationAtIndex'),
59 'SBCompileUnit': ('GetNumLineEntries', 'GetLineEntryAtIndex'),
60 'SBDebugger': ('GetNumTargets', 'GetTargetAtIndex'),
61 'SBModule': ('GetNumSymbols', 'GetSymbolAtIndex'),
62 'SBProcess': ('GetNumThreads', 'GetThreadAtIndex'),
63 'SBThread': ('GetNumFrames', 'GetFrameAtIndex'),
64
65 'SBInstructionList': ('GetSize', 'GetInstructionAtIndex'),
66 'SBStringList': ('GetSize', 'GetStringAtIndex',),
67 'SBSymbolContextList': ('GetSize', 'GetContextAtIndex'),
68 'SBValueList': ('GetSize', 'GetValueAtIndex'),
69
70 'SBType': ('GetNumberChildren', 'GetChildAtIndex'),
71 'SBValue': ('GetNumChildren', 'GetChildAtIndex'),
72
73 'SBTarget': {'module': ('GetNumModules', 'GetModuleAtIndex'),
74 'breakpoint': ('GetNumBreakpoints', 'GetBreakpointAtIndex')
75 }
76 }
77
Johnny Chen3a3d6592011-04-29 19:03:02 +000078#
Johnny Chen7616cb92011-05-02 19:05:52 +000079# This dictionary defines a mapping from classname to equality method name(s).
Johnny Chen3a3d6592011-04-29 19:03:02 +000080#
Johnny Chen7616cb92011-05-02 19:05:52 +000081e = { 'SBBreakpoint': ['GetID'],
82 'SBFileSpec': ['GetFilename', 'GetDirectory'],
83 'SBModule': ['GetFileSpec', 'GetUUIDString']
84 }
85
86def list_to_frag(list):
87 """Transform a list to equality program fragment.
88
89 For example, ['GetID'] is transformed to 'self.GetID() == other.GetID()',
90 and ['GetFilename', 'GetDirectory'] to 'self.GetFilename() == other.GetFilename()
91 and self.GetDirectory() == other.GetDirectory()'.
92 """
93 if not list:
94 raise Exception("list should be non-empty")
95 frag = StringIO.StringIO()
96 for i in range(len(list)):
97 if i > 0:
98 frag.write(" and ")
99 frag.write("self.{0}() == other.{0}()".format(list[i]))
100 return frag.getvalue()
Johnny Chen3a3d6592011-04-29 19:03:02 +0000101
Johnny Chen14097802011-04-28 21:31:18 +0000102# The new content will have the iteration protocol defined for our lldb objects.
103new_content = StringIO.StringIO()
104
105with open(output_name, 'r') as f_in:
106 content = f_in.read()
107
108# The pattern for recognizing the beginning of an SB class definition.
109class_pattern = re.compile("^class (SB.*)\(_object\):$")
110
111# The pattern for recognizing the beginning of the __init__ method definition.
112init_pattern = re.compile("^ def __init__\(self, \*args\):")
113
Johnny Chen2077f0d2011-05-17 22:14:39 +0000114# The pattern for recognizing the beginning of the IsValid method definition.
115isvalid_pattern = re.compile("^ def IsValid\(\*args\):")
116
Johnny Chena79a21c2011-05-16 20:31:18 +0000117# These define the states of our finite state machine.
Johnny Chen14097802011-04-28 21:31:18 +0000118NORMAL = 0
119DEFINING_ITERATOR = 1
Johnny Chen3a3d6592011-04-29 19:03:02 +0000120DEFINING_EQUALITY = 2
Johnny Chen14097802011-04-28 21:31:18 +0000121
122# The lldb_iter_def only needs to be inserted once.
123lldb_iter_defined = False;
124
Johnny Chen2077f0d2011-05-17 22:14:39 +0000125# Our FSM begins its life in the NORMAL state, and transitions to the
126# DEFINING_ITERATOR and/or DEFINING_EQUALITY state whenever it encounters the
127# beginning of certain class definitions, see dictionaries 'd' and 'e' above.
128#
129# Note that the two states DEFINING_ITERATOR and DEFINING_EQUALITY are
130# orthogonal in that our FSM can be in one, the other, or both states at the
131# same time. During such time, the FSM is eagerly searching for the __init__
132# method definition in order to insert the appropriate method(s) into the lldb
133# module.
134#
135# Assuming that SWIG puts out the __init__ method definition before other method
136# definitions, the FSM, while in NORMAL state, also checks the current input for
137# IsValid() definition, and inserts a __nonzero__() method definition to
138# implement truth value testing and the built-in operation bool().
Johnny Chen14097802011-04-28 21:31:18 +0000139state = NORMAL
140for line in content.splitlines():
141 if state == NORMAL:
142 match = class_pattern.search(line)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000143 # Inserts the lldb_iter() definition before the first class definition.
Johnny Chen14097802011-04-28 21:31:18 +0000144 if not lldb_iter_defined and match:
145 print >> new_content, lldb_iter_def
146 lldb_iter_defined = True
Johnny Chen2077f0d2011-05-17 22:14:39 +0000147
148 # If we are at the beginning of the class definitions, prepare to
149 # transition to the DEFINING_ITERATOR/DEFINING_EQUALITY state for the
150 # right class names.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000151 if match:
Johnny Chen14097802011-04-28 21:31:18 +0000152 cls = match.group(1)
Johnny Chen3a3d6592011-04-29 19:03:02 +0000153 if cls in d:
154 # Adding support for iteration for the matched SB class.
155 state = (state | DEFINING_ITERATOR)
156 if cls in e:
157 # Adding support for eq and ne for the matched SB class.
158 state = (state | DEFINING_EQUALITY)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000159 # Look for 'def IsValid(*args):', and once located, add implementation
160 # of truth value testing for objects by delegation.
161 elif isvalid_pattern.search(line):
162 print >> new_content, nonzero_def
Johnny Chen3a3d6592011-04-29 19:03:02 +0000163 elif state > NORMAL:
Johnny Chen14097802011-04-28 21:31:18 +0000164 match = init_pattern.search(line)
165 if match:
166 # We found the beginning of the __init__ method definition.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000167 # This is a good spot to insert the iter and/or eq-ne support.
Johnny Chen14097802011-04-28 21:31:18 +0000168 #
169 # But note that SBTarget has two types of iterations.
170 if cls == "SBTarget":
171 print >> new_content, module_iter % (d[cls]['module'])
172 print >> new_content, breakpoint_iter % (d[cls]['breakpoint'])
173 else:
Johnny Chen3a3d6592011-04-29 19:03:02 +0000174 if (state & DEFINING_ITERATOR):
175 print >> new_content, iter_def % d[cls]
Johnny Chena79a21c2011-05-16 20:31:18 +0000176 print >> new_content, len_def % d[cls][0]
Johnny Chen3a3d6592011-04-29 19:03:02 +0000177 if (state & DEFINING_EQUALITY):
Johnny Chen7616cb92011-05-02 19:05:52 +0000178 print >> new_content, eq_def % (cls, list_to_frag(e[cls]))
Johnny Chen3a3d6592011-04-29 19:03:02 +0000179 print >> new_content, ne_def
Johnny Chena2f86e82011-04-29 19:19:13 +0000180
181 # Next state will be NORMAL.
182 state = NORMAL
Johnny Chen14097802011-04-28 21:31:18 +0000183
Johnny Chen6ea16c72011-05-02 17:53:04 +0000184 # Pass the original line of content to new_content.
Johnny Chen14097802011-04-28 21:31:18 +0000185 print >> new_content, line
186
187with open(output_name, 'w') as f_out:
188 f_out.write(new_content.getvalue())
189 f_out.write("debugger_unique_id = 0\n")
190 f_out.write("SBDebugger.Initialize()\n")