blob: b4159e04f0d12fde226b7097bf67262325d4f6c6 [file] [log] [blame]
Guido van Rossum421c2241997-11-18 15:47:55 +00001"""Disassembler of Python byte code into mnemonics."""
Guido van Rossum217a5fa1990-12-26 15:40:07 +00002
3import sys
Guido van Rossum18aef3c1997-03-14 04:15:43 +00004import types
Guido van Rossum217a5fa1990-12-26 15:40:07 +00005
Skip Montanaro19c6ba32003-02-27 21:29:27 +00006from opcode import *
7from opcode import __all__ as _opcodes_all
8
Benjamin Peterson75edad02009-01-01 15:05:06 +00009__all__ = ["dis", "disassemble", "distb", "disco",
10 "findlinestarts", "findlabels"] + _opcodes_all
Skip Montanaro19c6ba32003-02-27 21:29:27 +000011del _opcodes_all
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000012
Benjamin Peterson6ef9a842010-04-04 23:26:50 +000013_have_code = (types.MethodType, types.FunctionType, types.CodeType, type)
14
Nick Coghlan5c8b54e2010-07-03 07:36:51 +000015def _try_compile(source, name):
16 """Attempts to compile the given source, first as an expression and
17 then as a statement if the first approach fails.
18
19 Utility function to accept strings in functions that otherwise
20 expect code objects
21 """
Nick Coghlan5c8b54e2010-07-03 07:36:51 +000022 try:
23 c = compile(source, name, 'eval')
24 except SyntaxError:
25 c = compile(source, name, 'exec')
26 return c
27
Guido van Rossumbd307951997-01-17 20:05:04 +000028def dis(x=None):
Tim Peters88869f92001-01-14 23:36:06 +000029 """Disassemble classes, methods, functions, or code.
Guido van Rossum421c2241997-11-18 15:47:55 +000030
Tim Peters88869f92001-01-14 23:36:06 +000031 With no argument, disassemble the last traceback.
Guido van Rossum421c2241997-11-18 15:47:55 +000032
Tim Peters88869f92001-01-14 23:36:06 +000033 """
Raymond Hettinger0f4940c2002-06-01 00:57:55 +000034 if x is None:
Tim Peters88869f92001-01-14 23:36:06 +000035 distb()
36 return
Nick Coghlaneae2da12010-08-17 08:03:36 +000037 if hasattr(x, '__func__'): # Method
Christian Heimesff737952007-11-27 10:40:20 +000038 x = x.__func__
Nick Coghlaneae2da12010-08-17 08:03:36 +000039 if hasattr(x, '__code__'): # Function
Neal Norwitz221085d2007-02-25 20:55:47 +000040 x = x.__code__
Nick Coghlaneae2da12010-08-17 08:03:36 +000041 if hasattr(x, '__dict__'): # Class or module
Guido van Rossume7ba4952007-06-06 23:52:48 +000042 items = sorted(x.__dict__.items())
Tim Peters88869f92001-01-14 23:36:06 +000043 for name, x1 in items:
Benjamin Peterson6ef9a842010-04-04 23:26:50 +000044 if isinstance(x1, _have_code):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000045 print("Disassembly of %s:" % name)
Tim Peters88869f92001-01-14 23:36:06 +000046 try:
47 dis(x1)
Guido van Rossumb940e112007-01-10 16:19:56 +000048 except TypeError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000049 print("Sorry:", msg)
50 print()
Nick Coghlaneae2da12010-08-17 08:03:36 +000051 elif hasattr(x, 'co_code'): # Code object
Guido van Rossumfc53c132001-01-19 02:41:41 +000052 disassemble(x)
Nick Coghlaneae2da12010-08-17 08:03:36 +000053 elif isinstance(x, (bytes, bytearray)): # Raw bytecode
Nick Coghlan5c8b54e2010-07-03 07:36:51 +000054 _disassemble_bytes(x)
Nick Coghlaneae2da12010-08-17 08:03:36 +000055 elif isinstance(x, str): # Source code
Nick Coghlan5c8b54e2010-07-03 07:36:51 +000056 _disassemble_str(x)
Tim Peters88869f92001-01-14 23:36:06 +000057 else:
Guido van Rossume7ba4952007-06-06 23:52:48 +000058 raise TypeError("don't know how to disassemble %s objects" %
59 type(x).__name__)
Guido van Rossum217a5fa1990-12-26 15:40:07 +000060
Guido van Rossumbd307951997-01-17 20:05:04 +000061def distb(tb=None):
Tim Peters88869f92001-01-14 23:36:06 +000062 """Disassemble a traceback (default: last traceback)."""
Raymond Hettinger0f4940c2002-06-01 00:57:55 +000063 if tb is None:
Tim Peters88869f92001-01-14 23:36:06 +000064 try:
65 tb = sys.last_traceback
66 except AttributeError:
Collin Winterce36ad82007-08-30 01:19:48 +000067 raise RuntimeError("no last traceback to disassemble")
Tim Peters88869f92001-01-14 23:36:06 +000068 while tb.tb_next: tb = tb.tb_next
69 disassemble(tb.tb_frame.f_code, tb.tb_lasti)
Guido van Rossum217a5fa1990-12-26 15:40:07 +000070
Guido van Rossum3e1b85e2007-05-30 02:07:00 +000071# XXX This duplicates information from code.h, also duplicated in inspect.py.
72# XXX Maybe this ought to be put in a central location, like opcode.py?
73flag2name = {
74 1: "OPTIMIZED",
75 2: "NEWLOCALS",
76 4: "VARARGS",
77 8: "VARKEYWORDS",
78 16: "NESTED",
79 32: "GENERATOR",
80 64: "NOFREE",
81}
82
83def pretty_flags(flags):
84 """Return pretty representation of code flags."""
85 names = []
86 for i in range(32):
87 flag = 1<<i
88 if flags & flag:
89 names.append(flag2name.get(flag, hex(flag)))
90 flags ^= flag
91 if not flags:
92 break
93 else:
94 names.append(hex(flags))
95 return ", ".join(names)
96
Nick Coghlaneae2da12010-08-17 08:03:36 +000097def code_info(x):
98 """Formatted details of methods, functions, or code."""
99 if hasattr(x, '__func__'): # Method
100 x = x.__func__
101 if hasattr(x, '__code__'): # Function
102 x = x.__code__
103 if isinstance(x, str): # Source code
104 x = _try_compile(x, "<code_info>")
105 if hasattr(x, 'co_code'): # Code object
106 return _format_code_info(x)
107 else:
108 raise TypeError("don't know how to disassemble %s objects" %
109 type(x).__name__)
110
111def _format_code_info(co):
112 lines = []
113 lines.append("Name: %s" % co.co_name)
114 lines.append("Filename: %s" % co.co_filename)
115 lines.append("Argument count: %s" % co.co_argcount)
116 lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
117 lines.append("Number of locals: %s" % co.co_nlocals)
118 lines.append("Stack size: %s" % co.co_stacksize)
119 lines.append("Flags: %s" % pretty_flags(co.co_flags))
120 if co.co_consts:
121 lines.append("Constants:")
122 for i_c in enumerate(co.co_consts):
123 lines.append("%4d: %r" % i_c)
124 if co.co_names:
125 lines.append("Names:")
126 for i_n in enumerate(co.co_names):
127 lines.append("%4d: %s" % i_n)
128 if co.co_varnames:
129 lines.append("Variable names:")
130 for i_n in enumerate(co.co_varnames):
131 lines.append("%4d: %s" % i_n)
132 if co.co_freevars:
133 lines.append("Free variables:")
134 for i_n in enumerate(co.co_freevars):
135 lines.append("%4d: %s" % i_n)
136 if co.co_cellvars:
137 lines.append("Cell variables:")
138 for i_n in enumerate(co.co_cellvars):
139 lines.append("%4d: %s" % i_n)
140 return "\n".join(lines)
141
Guido van Rossum3e1b85e2007-05-30 02:07:00 +0000142def show_code(co):
143 """Show details about a code object."""
Nick Coghlaneae2da12010-08-17 08:03:36 +0000144 print(code_info(co))
Guido van Rossum3e1b85e2007-05-30 02:07:00 +0000145
Guido van Rossumbd307951997-01-17 20:05:04 +0000146def disassemble(co, lasti=-1):
Tim Peters88869f92001-01-14 23:36:06 +0000147 """Disassemble a code object."""
148 code = co.co_code
149 labels = findlabels(code)
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000150 linestarts = dict(findlinestarts(co))
Tim Peters88869f92001-01-14 23:36:06 +0000151 n = len(code)
152 i = 0
153 extended_arg = 0
Jeremy Hyltona39414b2001-01-25 20:08:47 +0000154 free = None
Tim Peters88869f92001-01-14 23:36:06 +0000155 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000156 op = code[i]
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000157 if i in linestarts:
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000158 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000159 print()
160 print("%3d" % linestarts[i], end=' ')
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000161 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000162 print(' ', end=' ')
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000163
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000164 if i == lasti: print('-->', end=' ')
165 else: print(' ', end=' ')
166 if i in labels: print('>>', end=' ')
167 else: print(' ', end=' ')
168 print(repr(i).rjust(4), end=' ')
169 print(opname[op].ljust(20), end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000170 i = i+1
171 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000172 oparg = code[i] + code[i+1]*256 + extended_arg
Tim Peters88869f92001-01-14 23:36:06 +0000173 extended_arg = 0
174 i = i+2
175 if op == EXTENDED_ARG:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000176 extended_arg = oparg*65536
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000177 print(repr(oparg).rjust(5), end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000178 if op in hasconst:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000179 print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000180 elif op in hasname:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000181 print('(' + co.co_names[oparg] + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000182 elif op in hasjrel:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000183 print('(to ' + repr(i + oparg) + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000184 elif op in haslocal:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000185 print('(' + co.co_varnames[oparg] + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000186 elif op in hascompare:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print('(' + cmp_op[oparg] + ')', end=' ')
Jeremy Hyltona39414b2001-01-25 20:08:47 +0000188 elif op in hasfree:
189 if free is None:
190 free = co.co_cellvars + co.co_freevars
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000191 print('(' + free[oparg] + ')', end=' ')
192 print()
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000193
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000194def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
Skip Montanaro19c6ba32003-02-27 21:29:27 +0000195 constants=None):
Tim Peters669454e2003-03-07 17:30:48 +0000196 labels = findlabels(code)
197 n = len(code)
198 i = 0
199 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000200 op = code[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000201 if i == lasti: print('-->', end=' ')
202 else: print(' ', end=' ')
203 if i in labels: print('>>', end=' ')
204 else: print(' ', end=' ')
205 print(repr(i).rjust(4), end=' ')
206 print(opname[op].ljust(15), end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000207 i = i+1
208 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000209 oparg = code[i] + code[i+1]*256
Tim Peters669454e2003-03-07 17:30:48 +0000210 i = i+2
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000211 print(repr(oparg).rjust(5), end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000212 if op in hasconst:
213 if constants:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000214 print('(' + repr(constants[oparg]) + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000215 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000216 print('(%d)'%oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000217 elif op in hasname:
218 if names is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000219 print('(' + names[oparg] + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000220 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print('(%d)'%oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000222 elif op in hasjrel:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000223 print('(to ' + repr(i + oparg) + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000224 elif op in haslocal:
225 if varnames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000226 print('(' + varnames[oparg] + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000227 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000228 print('(%d)' % oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000229 elif op in hascompare:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000230 print('(' + cmp_op[oparg] + ')', end=' ')
231 print()
Skip Montanaro19c6ba32003-02-27 21:29:27 +0000232
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000233def _disassemble_str(source):
234 """Compile the source string, then disassemble the code object."""
235 disassemble(_try_compile(source, '<dis>'))
236
Tim Peters88869f92001-01-14 23:36:06 +0000237disco = disassemble # XXX For backwards compatibility
Guido van Rossumbd307951997-01-17 20:05:04 +0000238
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000239def findlabels(code):
Tim Peters88869f92001-01-14 23:36:06 +0000240 """Detect all offsets in a byte code which are jump targets.
Guido van Rossum421c2241997-11-18 15:47:55 +0000241
Tim Peters88869f92001-01-14 23:36:06 +0000242 Return the list of offsets.
Guido van Rossum421c2241997-11-18 15:47:55 +0000243
Tim Peters88869f92001-01-14 23:36:06 +0000244 """
245 labels = []
246 n = len(code)
247 i = 0
248 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000249 op = code[i]
Tim Peters88869f92001-01-14 23:36:06 +0000250 i = i+1
251 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000252 oparg = code[i] + code[i+1]*256
Tim Peters88869f92001-01-14 23:36:06 +0000253 i = i+2
254 label = -1
255 if op in hasjrel:
256 label = i+oparg
257 elif op in hasjabs:
258 label = oparg
259 if label >= 0:
260 if label not in labels:
261 labels.append(label)
262 return labels
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000263
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000264def findlinestarts(code):
265 """Find the offsets in a byte code which are start of lines in the source.
266
267 Generate pairs (offset, lineno) as described in Python/compile.c.
268
269 """
Guido van Rossum75a902d2007-10-19 22:06:24 +0000270 byte_increments = list(code.co_lnotab[0::2])
271 line_increments = list(code.co_lnotab[1::2])
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000272
273 lastlineno = None
274 lineno = code.co_firstlineno
275 addr = 0
276 for byte_incr, line_incr in zip(byte_increments, line_increments):
277 if byte_incr:
278 if lineno != lastlineno:
279 yield (addr, lineno)
280 lastlineno = lineno
281 addr += byte_incr
282 lineno += line_incr
283 if lineno != lastlineno:
284 yield (addr, lineno)
Guido van Rossum1fdae122000-02-04 17:47:55 +0000285
286def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000287 """Simple test program to disassemble a file."""
288 if sys.argv[1:]:
289 if sys.argv[2:]:
290 sys.stderr.write("usage: python dis.py [-|file]\n")
291 sys.exit(2)
292 fn = sys.argv[1]
293 if not fn or fn == "-":
294 fn = None
295 else:
296 fn = None
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000297 if fn is None:
Tim Peters88869f92001-01-14 23:36:06 +0000298 f = sys.stdin
299 else:
300 f = open(fn)
301 source = f.read()
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000302 if fn is not None:
Tim Peters88869f92001-01-14 23:36:06 +0000303 f.close()
304 else:
305 fn = "<stdin>"
306 code = compile(source, fn, "exec")
307 dis(code)
Guido van Rossum1fdae122000-02-04 17:47:55 +0000308
309if __name__ == "__main__":
Tim Peters88869f92001-01-14 23:36:06 +0000310 _test()