blob: 3a784a6e74c548776759514e68aa0d24314f76b0 [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
Johnny Chene5637d22011-05-24 21:05:16 +00006# objects, implements truth value testing for certain lldb objects, and adds a
7# global variable 'debugger_unique_id' which is initialized to 0.
Johnny Chen14097802011-04-28 21:31:18 +00008#
Johnny Chen09e0a422011-07-01 22:14:07 +00009# As a cleanup step, it also removes the 'residues' from the autodoc features of
10# swig. For an example, take a look at SBTarget.h header file, where we take
Johnny Chen2c77fa42011-07-02 20:01:09 +000011# advantage of the already existing doxygen C++-docblock and make it the Python
Johnny Chen09e0a422011-07-01 22:14:07 +000012# docstring for the same method. The 'residues' in this context include the
Johnny Chenf6ce70a2011-07-03 19:55:50 +000013# '#endif', the '#ifdef SWIG', the c comment marker, the trailing blank (SPC's)
14# line, and the doxygen comment start marker.
Johnny Chen09e0a422011-07-01 22:14:07 +000015#
Johnny Chen37811372011-07-06 21:55:45 +000016# In addition to the 'residues' removal during the cleanup step, it also
17# transforms the 'char' data type (which was actually 'char *' but the 'autodoc'
18# feature of swig removes ' *' from it into 'str' (as a Python str type).
19#
Johnny Chen14097802011-04-28 21:31:18 +000020# It also calls SBDebugger.Initialize() to initialize the lldb debugger
21# subsystem.
22#
23
24import sys, re, StringIO
25
26if len (sys.argv) != 2:
27 output_name = "./lldb.py"
28else:
29 output_name = sys.argv[1] + "/lldb.py"
30
31# print "output_name is '" + output_name + "'"
32
Johnny Chen37811372011-07-06 21:55:45 +000033#
Johnny Chen09e0a422011-07-01 22:14:07 +000034# Residues to be removed.
Johnny Chen37811372011-07-06 21:55:45 +000035#
Johnny Chen09e0a422011-07-01 22:14:07 +000036c_endif_swig = "#endif"
37c_ifdef_swig = "#ifdef SWIG"
Johnny Chen2c77fa42011-07-02 20:01:09 +000038c_comment_marker = "//------------"
39# The pattern for recognizing the doxygen comment block line.
Johnny Chenebd63b22011-07-16 21:15:39 +000040doxygen_comment_start = re.compile("^\s*(/// ?)")
Johnny Chenf6ce70a2011-07-03 19:55:50 +000041# The demarcation point for turning on/off residue removal state.
42# When bracketed by the lines, the CLEANUP_DOCSTRING state (see below) is ON.
43toggle_docstring_cleanup_line = ' """'
Johnny Chen09e0a422011-07-01 22:14:07 +000044
Johnny Chen37811372011-07-06 21:55:45 +000045def char_to_str_xform(line):
46 """This transforms the 'char', i.e, 'char *' to 'str', Python string."""
47 line = line.replace(' char', ' str')
48 line = line.replace('char ', 'str ')
Johnny Chen2de7ce62011-07-14 00:17:49 +000049 # Special case handling of 'char **argv' and 'char **envp'.
50 line = line.replace('str argv', 'list argv')
51 line = line.replace('str envp', 'list envp')
Johnny Chen37811372011-07-06 21:55:45 +000052 return line
53
54#
55# The one-liner docstring also needs char_to_str transformation, btw.
56#
Johnny Chen21c0fd12011-07-08 23:57:20 +000057TWO_SPACES = ' ' * 2
58EIGHT_SPACES = ' ' * 8
59one_liner_docstring_pattern = re.compile('^(%s|%s)""".*"""$' % (TWO_SPACES, EIGHT_SPACES))
Johnny Chen37811372011-07-06 21:55:45 +000060
Johnny Chen14097802011-04-28 21:31:18 +000061#
Johnny Chenec5e0a22011-06-01 18:40:11 +000062# lldb_iter() should appear before our first SB* class definition.
Johnny Chen14097802011-04-28 21:31:18 +000063#
64lldb_iter_def = '''
65# ===================================
66# Iterator for lldb container objects
67# ===================================
68def lldb_iter(obj, getsize, getelem):
69 """A generator adaptor to support iteration for lldb container objects."""
70 size = getattr(obj, getsize)
71 elem = getattr(obj, getelem)
72 for i in range(size()):
73 yield elem(i)
74
Johnny Chen81422202011-06-01 19:21:08 +000075# ==============================================================================
76# The modify-python-lldb.py script is responsible for post-processing this SWIG-
77# generated lldb.py module. It is responsible for adding the above lldb_iter()
78# function definition as well as the supports, in the following, for iteration
79# protocol: __iter__, rich comparison methods: __eq__ and __ne__, truth value
80# testing (and built-in operation bool()): __nonzero__, and built-in function
81# len(): __len__.
82# ==============================================================================
Johnny Chen14097802011-04-28 21:31:18 +000083'''
84
Johnny Chenfbebbc92011-07-25 19:32:35 +000085#
Johnny Chende856cc2011-07-25 23:41:08 +000086# linked_list_iter() is a special purpose iterator to treat the SBValue as the
87# head of a list data structure, where you specify the child member name which
88# points to the next item on the list and you specify the end-of-list function
89# which takes an SBValue and returns True if EOL is reached and False if not.
Johnny Chenfbebbc92011-07-25 19:32:35 +000090#
91linked_list_iter_def = '''
92 # ==================================================
93 # Iterator for lldb.SBValue treated as a linked list
94 # ==================================================
Johnny Chen9ed9f8b2011-07-25 23:44:48 +000095 def linked_list_iter(self, next_item_name, end_of_list_test):
Johnny Chende856cc2011-07-25 23:41:08 +000096 """Generator adaptor to support iteration for SBValue as a linked list.
97
98 linked_list_iter() is a special purpose iterator to treat the SBValue as
99 the head of a list data structure, where you specify the child member
100 name which points to the next item on the list and you specify the
101 end-of-list test function which takes an SBValue for an item and returns
102 True if EOL is reached and False if not.
Johnny Chenfbebbc92011-07-25 19:32:35 +0000103
104 For example,
105
Johnny Chenfbebbc92011-07-25 19:32:35 +0000106 def eol(val):
Johnny Chen021cdc22011-07-26 20:20:13 +0000107 \'\'\'Test function to determine end of list.\'\'\'
108 # End of list is reached if either the value object is invalid
109 # or it corresponds to a null pointer.
110 if not val or int(val.GetValue(), 16) == 0:
Johnny Chenfbebbc92011-07-25 19:32:35 +0000111 return True
Johnny Chenfbebbc92011-07-25 19:32:35 +0000112
Johnny Chen021cdc22011-07-26 20:20:13 +0000113 # Otherwise, return False.
114 return False
Johnny Chenfbebbc92011-07-25 19:32:35 +0000115
116 # Get Frame #0.
117 ...
118
119 # Get variable 'task_head'.
120 task_head = frame0.FindVariable('task_head')
121 ...
122
123 for t in task_head.linked_list_iter('next', eol):
124 print t
125 """
126 try:
127 item = self.GetChildMemberWithName(next_item_name)
128 while item:
129 yield item
130 # Prepare for the next iteration.
131 item = item.GetChildMemberWithName(next_item_name)
Johnny Chen9ed9f8b2011-07-25 23:44:48 +0000132 if end_of_list_test(item):
Johnny Chenfbebbc92011-07-25 19:32:35 +0000133 break
134 except:
135 # Exception occurred. Stop the generator.
136 pass
137
138 return
139'''
140
Johnny Chen14097802011-04-28 21:31:18 +0000141# This supports the iteration protocol.
Johnny Chen14097802011-04-28 21:31:18 +0000142iter_def = " def __iter__(self): return lldb_iter(self, '%s', '%s')"
143module_iter = " def module_iter(self): return lldb_iter(self, '%s', '%s')"
144breakpoint_iter = " def breakpoint_iter(self): return lldb_iter(self, '%s', '%s')"
Johnny Chen2077f0d2011-05-17 22:14:39 +0000145
Johnny Chena79a21c2011-05-16 20:31:18 +0000146# Called to implement the built-in function len().
147# Eligible objects are those containers with unambiguous iteration support.
Johnny Chena79a21c2011-05-16 20:31:18 +0000148len_def = " def __len__(self): return self.%s()"
Johnny Chen2077f0d2011-05-17 22:14:39 +0000149
Johnny Chen3a3d6592011-04-29 19:03:02 +0000150# This supports the rich comparison methods of __eq__ and __ne__.
Johnny Chen7616cb92011-05-02 19:05:52 +0000151eq_def = " def __eq__(self, other): return isinstance(other, %s) and %s"
Johnny Chen3a3d6592011-04-29 19:03:02 +0000152ne_def = " def __ne__(self, other): return not self.__eq__(other)"
Johnny Chen14097802011-04-28 21:31:18 +0000153
Johnny Chen2077f0d2011-05-17 22:14:39 +0000154# Called to implement truth value testing and the built-in operation bool();
155# should return False or True, or their integer equivalents 0 or 1.
156# Delegate to self.IsValid() if it is defined for the current lldb object.
157nonzero_def = " def __nonzero__(self): return self.IsValid()"
158
Johnny Chen14097802011-04-28 21:31:18 +0000159#
Johnny Chena6303ef2011-05-24 22:53:03 +0000160# This dictionary defines a mapping from classname to (getsize, getelem) tuple.
Johnny Chen14097802011-04-28 21:31:18 +0000161#
162d = { 'SBBreakpoint': ('GetNumLocations', 'GetLocationAtIndex'),
163 'SBCompileUnit': ('GetNumLineEntries', 'GetLineEntryAtIndex'),
164 'SBDebugger': ('GetNumTargets', 'GetTargetAtIndex'),
165 'SBModule': ('GetNumSymbols', 'GetSymbolAtIndex'),
166 'SBProcess': ('GetNumThreads', 'GetThreadAtIndex'),
167 'SBThread': ('GetNumFrames', 'GetFrameAtIndex'),
168
169 'SBInstructionList': ('GetSize', 'GetInstructionAtIndex'),
170 'SBStringList': ('GetSize', 'GetStringAtIndex',),
171 'SBSymbolContextList': ('GetSize', 'GetContextAtIndex'),
172 'SBValueList': ('GetSize', 'GetValueAtIndex'),
173
174 'SBType': ('GetNumberChildren', 'GetChildAtIndex'),
175 'SBValue': ('GetNumChildren', 'GetChildAtIndex'),
176
Johnny Chen08477f52011-05-24 22:57:42 +0000177 # SBTarget needs special processing, see below.
Johnny Chen14097802011-04-28 21:31:18 +0000178 'SBTarget': {'module': ('GetNumModules', 'GetModuleAtIndex'),
179 'breakpoint': ('GetNumBreakpoints', 'GetBreakpointAtIndex')
180 }
181 }
182
Johnny Chen3a3d6592011-04-29 19:03:02 +0000183#
Johnny Chen7616cb92011-05-02 19:05:52 +0000184# This dictionary defines a mapping from classname to equality method name(s).
Johnny Chen3a3d6592011-04-29 19:03:02 +0000185#
Johnny Chen694cfd02011-06-09 22:04:56 +0000186e = { 'SBAddress': ['GetFileAddress', 'GetModule'],
187 'SBBreakpoint': ['GetID'],
Johnny Chen7616cb92011-05-02 19:05:52 +0000188 'SBFileSpec': ['GetFilename', 'GetDirectory'],
189 'SBModule': ['GetFileSpec', 'GetUUIDString']
190 }
191
192def list_to_frag(list):
193 """Transform a list to equality program fragment.
194
195 For example, ['GetID'] is transformed to 'self.GetID() == other.GetID()',
196 and ['GetFilename', 'GetDirectory'] to 'self.GetFilename() == other.GetFilename()
197 and self.GetDirectory() == other.GetDirectory()'.
198 """
199 if not list:
200 raise Exception("list should be non-empty")
201 frag = StringIO.StringIO()
202 for i in range(len(list)):
203 if i > 0:
204 frag.write(" and ")
205 frag.write("self.{0}() == other.{0}()".format(list[i]))
206 return frag.getvalue()
Johnny Chen3a3d6592011-04-29 19:03:02 +0000207
Johnny Chenebd63b22011-07-16 21:15:39 +0000208class NewContent(StringIO.StringIO):
209 """Simple facade to keep track of the previous line to be committed."""
210 def __init__(self):
211 StringIO.StringIO.__init__(self)
212 self.prev_line = None
213 def add_line(self, a_line):
214 """Add a line to the content, if there is a previous line, commit it."""
215 if self.prev_line != None:
216 print >> self, self.prev_line
217 self.prev_line = a_line
218 def del_line(self):
219 """Forget about the previous line, do not commit it."""
220 self.prev_line = None
221 def del_blank_line(self):
222 """Forget about the previous line if it is a blank line."""
223 if self.prev_line != None and not self.prev_line.strip():
224 self.prev_line = None
225 def finish(self):
226 """Call this when you're finished with populating content."""
227 if self.prev_line != None:
228 print >> self, self.prev_line
229 self.prev_line = None
230
Johnny Chen14097802011-04-28 21:31:18 +0000231# The new content will have the iteration protocol defined for our lldb objects.
Johnny Chenebd63b22011-07-16 21:15:39 +0000232new_content = NewContent()
Johnny Chen14097802011-04-28 21:31:18 +0000233
234with open(output_name, 'r') as f_in:
235 content = f_in.read()
236
237# The pattern for recognizing the beginning of an SB class definition.
238class_pattern = re.compile("^class (SB.*)\(_object\):$")
239
240# The pattern for recognizing the beginning of the __init__ method definition.
241init_pattern = re.compile("^ def __init__\(self, \*args\):")
242
Johnny Chen2077f0d2011-05-17 22:14:39 +0000243# The pattern for recognizing the beginning of the IsValid method definition.
Peter Collingbournef2084532011-06-14 03:55:41 +0000244isvalid_pattern = re.compile("^ def IsValid\(")
Johnny Chen2077f0d2011-05-17 22:14:39 +0000245
Johnny Chena79a21c2011-05-16 20:31:18 +0000246# These define the states of our finite state machine.
Johnny Chen14097802011-04-28 21:31:18 +0000247NORMAL = 0
248DEFINING_ITERATOR = 1
Johnny Chen3a3d6592011-04-29 19:03:02 +0000249DEFINING_EQUALITY = 2
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000250CLEANUP_DOCSTRING = 4
Johnny Chen14097802011-04-28 21:31:18 +0000251
252# The lldb_iter_def only needs to be inserted once.
253lldb_iter_defined = False;
254
Johnny Chen2077f0d2011-05-17 22:14:39 +0000255# Our FSM begins its life in the NORMAL state, and transitions to the
256# DEFINING_ITERATOR and/or DEFINING_EQUALITY state whenever it encounters the
257# beginning of certain class definitions, see dictionaries 'd' and 'e' above.
258#
259# Note that the two states DEFINING_ITERATOR and DEFINING_EQUALITY are
260# orthogonal in that our FSM can be in one, the other, or both states at the
261# same time. During such time, the FSM is eagerly searching for the __init__
262# method definition in order to insert the appropriate method(s) into the lldb
263# module.
264#
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000265# The state CLEANUP_DOCSTRING can be entered from either the NORMAL or the
266# DEFINING_ITERATOR/EQUALITY states. While in this state, the FSM is fixing/
267# cleaning the Python docstrings generated by the swig docstring features.
268#
Johnny Chenb72d1772011-05-24 22:29:49 +0000269# The FSM, in all possible states, also checks the current input for IsValid()
270# definition, and inserts a __nonzero__() method definition to implement truth
271# value testing and the built-in operation bool().
Johnny Chen14097802011-04-28 21:31:18 +0000272state = NORMAL
273for line in content.splitlines():
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000274 # Handle the state transition into CLEANUP_DOCSTRING state as it is possible
275 # to enter this state from either NORMAL or DEFINING_ITERATOR/EQUALITY.
276 #
277 # If ' """' is the sole line, prepare to transition to the
278 # CLEANUP_DOCSTRING state or out of it.
279 if line == toggle_docstring_cleanup_line:
280 if state & CLEANUP_DOCSTRING:
Johnny Chenebd63b22011-07-16 21:15:39 +0000281 # Special handling of the trailing blank line right before the '"""'
282 # end docstring marker.
283 new_content.del_blank_line()
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000284 state ^= CLEANUP_DOCSTRING
285 else:
286 state |= CLEANUP_DOCSTRING
Johnny Chen09e0a422011-07-01 22:14:07 +0000287
Johnny Chen14097802011-04-28 21:31:18 +0000288 if state == NORMAL:
289 match = class_pattern.search(line)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000290 # Inserts the lldb_iter() definition before the first class definition.
Johnny Chen14097802011-04-28 21:31:18 +0000291 if not lldb_iter_defined and match:
Johnny Chenebd63b22011-07-16 21:15:39 +0000292 new_content.add_line(lldb_iter_def)
Johnny Chen14097802011-04-28 21:31:18 +0000293 lldb_iter_defined = True
Johnny Chen2077f0d2011-05-17 22:14:39 +0000294
295 # If we are at the beginning of the class definitions, prepare to
296 # transition to the DEFINING_ITERATOR/DEFINING_EQUALITY state for the
297 # right class names.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000298 if match:
Johnny Chen14097802011-04-28 21:31:18 +0000299 cls = match.group(1)
Johnny Chen3a3d6592011-04-29 19:03:02 +0000300 if cls in d:
301 # Adding support for iteration for the matched SB class.
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000302 state |= DEFINING_ITERATOR
Johnny Chen3a3d6592011-04-29 19:03:02 +0000303 if cls in e:
304 # Adding support for eq and ne for the matched SB class.
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000305 state |= DEFINING_EQUALITY
306
Johnny Chen533ed2f2011-07-15 20:46:19 +0000307 if (state & DEFINING_ITERATOR) or (state & DEFINING_EQUALITY):
Johnny Chen14097802011-04-28 21:31:18 +0000308 match = init_pattern.search(line)
309 if match:
310 # We found the beginning of the __init__ method definition.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000311 # This is a good spot to insert the iter and/or eq-ne support.
Johnny Chen14097802011-04-28 21:31:18 +0000312 #
313 # But note that SBTarget has two types of iterations.
314 if cls == "SBTarget":
Johnny Chenebd63b22011-07-16 21:15:39 +0000315 new_content.add_line(module_iter % (d[cls]['module']))
316 new_content.add_line(breakpoint_iter % (d[cls]['breakpoint']))
Johnny Chen14097802011-04-28 21:31:18 +0000317 else:
Johnny Chen3a3d6592011-04-29 19:03:02 +0000318 if (state & DEFINING_ITERATOR):
Johnny Chenebd63b22011-07-16 21:15:39 +0000319 new_content.add_line(iter_def % d[cls])
320 new_content.add_line(len_def % d[cls][0])
Johnny Chen3a3d6592011-04-29 19:03:02 +0000321 if (state & DEFINING_EQUALITY):
Johnny Chenebd63b22011-07-16 21:15:39 +0000322 new_content.add_line(eq_def % (cls, list_to_frag(e[cls])))
323 new_content.add_line(ne_def)
Johnny Chena2f86e82011-04-29 19:19:13 +0000324
Johnny Chenfbebbc92011-07-25 19:32:35 +0000325 # This special purpose iterator is for SBValue only!!!
326 if cls == "SBValue":
327 new_content.add_line(linked_list_iter_def)
328
Johnny Chena2f86e82011-04-29 19:19:13 +0000329 # Next state will be NORMAL.
330 state = NORMAL
Johnny Chen14097802011-04-28 21:31:18 +0000331
Johnny Chen533ed2f2011-07-15 20:46:19 +0000332 if (state & CLEANUP_DOCSTRING):
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000333 # Cleanse the lldb.py of the autodoc'ed residues.
334 if c_ifdef_swig in line or c_endif_swig in line:
335 continue
Johnny Chenebd63b22011-07-16 21:15:39 +0000336 # As well as the comment marker line.
337 if c_comment_marker in line:
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000338 continue
Johnny Chenebd63b22011-07-16 21:15:39 +0000339
Johnny Chen533ed2f2011-07-15 20:46:19 +0000340 # Also remove the '\a ' and '\b 'substrings.
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000341 line = line.replace('\a ', '')
Johnny Chen533ed2f2011-07-15 20:46:19 +0000342 line = line.replace('\b ', '')
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000343 # And the leading '///' substring.
344 doxygen_comment_match = doxygen_comment_start.match(line)
345 if doxygen_comment_match:
346 line = line.replace(doxygen_comment_match.group(1), '', 1)
347
Johnny Chen37811372011-07-06 21:55:45 +0000348 line = char_to_str_xform(line)
349
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000350 # Note that the transition out of CLEANUP_DOCSTRING is handled at the
351 # beginning of this function already.
352
Johnny Chen37811372011-07-06 21:55:45 +0000353 # This deals with one-liner docstring, for example, SBThread.GetName:
354 # """GetName(self) -> char""".
355 if one_liner_docstring_pattern.match(line):
356 line = char_to_str_xform(line)
357
Johnny Chenb72d1772011-05-24 22:29:49 +0000358 # Look for 'def IsValid(*args):', and once located, add implementation
359 # of truth value testing for this object by delegation.
360 if isvalid_pattern.search(line):
Johnny Chenebd63b22011-07-16 21:15:39 +0000361 new_content.add_line(nonzero_def)
Johnny Chenb72d1772011-05-24 22:29:49 +0000362
Johnny Chen6ea16c72011-05-02 17:53:04 +0000363 # Pass the original line of content to new_content.
Johnny Chenebd63b22011-07-16 21:15:39 +0000364 new_content.add_line(line)
365
366# We are finished with recording new content.
367new_content.finish()
368
Johnny Chen14097802011-04-28 21:31:18 +0000369with open(output_name, 'w') as f_out:
370 f_out.write(new_content.getvalue())
371 f_out.write("debugger_unique_id = 0\n")
372 f_out.write("SBDebugger.Initialize()\n")