blob: f64bae66fb83222e1e36a95c7d770288028cdf4d [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
Nick Coghlan7646f7e2010-09-10 12:24:24 +00009__all__ = ["code_info", "dis", "disassemble", "distb", "disco",
Nick Coghlane8814fb2010-09-10 14:08:04 +000010 "findlinestarts", "findlabels", "show_code"] + _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
Nick Coghlan09c81232010-08-17 10:18:16 +000071# The inspect module interrogates this dictionary to build its
72# list of CO_* constants. It is also used by pretty_flags to
73# turn the co_flags field into a human readable list.
74COMPILER_FLAG_NAMES = {
Guido van Rossum3e1b85e2007-05-30 02:07:00 +000075 1: "OPTIMIZED",
76 2: "NEWLOCALS",
77 4: "VARARGS",
78 8: "VARKEYWORDS",
79 16: "NESTED",
80 32: "GENERATOR",
81 64: "NOFREE",
82}
83
84def pretty_flags(flags):
85 """Return pretty representation of code flags."""
86 names = []
87 for i in range(32):
88 flag = 1<<i
89 if flags & flag:
Nick Coghlan09c81232010-08-17 10:18:16 +000090 names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
Guido van Rossum3e1b85e2007-05-30 02:07:00 +000091 flags ^= flag
92 if not flags:
93 break
94 else:
95 names.append(hex(flags))
96 return ", ".join(names)
97
Nick Coghlaneae2da12010-08-17 08:03:36 +000098def code_info(x):
99 """Formatted details of methods, functions, or code."""
100 if hasattr(x, '__func__'): # Method
101 x = x.__func__
102 if hasattr(x, '__code__'): # Function
103 x = x.__code__
104 if isinstance(x, str): # Source code
105 x = _try_compile(x, "<code_info>")
106 if hasattr(x, 'co_code'): # Code object
107 return _format_code_info(x)
108 else:
109 raise TypeError("don't know how to disassemble %s objects" %
110 type(x).__name__)
111
112def _format_code_info(co):
113 lines = []
114 lines.append("Name: %s" % co.co_name)
115 lines.append("Filename: %s" % co.co_filename)
116 lines.append("Argument count: %s" % co.co_argcount)
117 lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
118 lines.append("Number of locals: %s" % co.co_nlocals)
119 lines.append("Stack size: %s" % co.co_stacksize)
120 lines.append("Flags: %s" % pretty_flags(co.co_flags))
121 if co.co_consts:
122 lines.append("Constants:")
123 for i_c in enumerate(co.co_consts):
124 lines.append("%4d: %r" % i_c)
125 if co.co_names:
126 lines.append("Names:")
127 for i_n in enumerate(co.co_names):
128 lines.append("%4d: %s" % i_n)
129 if co.co_varnames:
130 lines.append("Variable names:")
131 for i_n in enumerate(co.co_varnames):
132 lines.append("%4d: %s" % i_n)
133 if co.co_freevars:
134 lines.append("Free variables:")
135 for i_n in enumerate(co.co_freevars):
136 lines.append("%4d: %s" % i_n)
137 if co.co_cellvars:
138 lines.append("Cell variables:")
139 for i_n in enumerate(co.co_cellvars):
140 lines.append("%4d: %s" % i_n)
141 return "\n".join(lines)
142
Guido van Rossum3e1b85e2007-05-30 02:07:00 +0000143def show_code(co):
Nick Coghlane8814fb2010-09-10 14:08:04 +0000144 """Print details of methods, functions, or code to stdout."""
Nick Coghlaneae2da12010-08-17 08:03:36 +0000145 print(code_info(co))
Guido van Rossum3e1b85e2007-05-30 02:07:00 +0000146
Guido van Rossumbd307951997-01-17 20:05:04 +0000147def disassemble(co, lasti=-1):
Tim Peters88869f92001-01-14 23:36:06 +0000148 """Disassemble a code object."""
149 code = co.co_code
150 labels = findlabels(code)
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000151 linestarts = dict(findlinestarts(co))
Tim Peters88869f92001-01-14 23:36:06 +0000152 n = len(code)
153 i = 0
154 extended_arg = 0
Jeremy Hyltona39414b2001-01-25 20:08:47 +0000155 free = None
Tim Peters88869f92001-01-14 23:36:06 +0000156 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000157 op = code[i]
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000158 if i in linestarts:
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000159 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000160 print()
161 print("%3d" % linestarts[i], end=' ')
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000162 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000163 print(' ', end=' ')
Michael W. Hudsondd32a912002-08-15 14:59:02 +0000164
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000165 if i == lasti: print('-->', end=' ')
166 else: print(' ', end=' ')
167 if i in labels: print('>>', end=' ')
168 else: print(' ', end=' ')
169 print(repr(i).rjust(4), end=' ')
170 print(opname[op].ljust(20), end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000171 i = i+1
172 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000173 oparg = code[i] + code[i+1]*256 + extended_arg
Tim Peters88869f92001-01-14 23:36:06 +0000174 extended_arg = 0
175 i = i+2
176 if op == EXTENDED_ARG:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000177 extended_arg = oparg*65536
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000178 print(repr(oparg).rjust(5), end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000179 if op in hasconst:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000180 print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000181 elif op in hasname:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000182 print('(' + co.co_names[oparg] + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000183 elif op in hasjrel:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000184 print('(to ' + repr(i + oparg) + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000185 elif op in haslocal:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000186 print('(' + co.co_varnames[oparg] + ')', end=' ')
Tim Peters88869f92001-01-14 23:36:06 +0000187 elif op in hascompare:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000188 print('(' + cmp_op[oparg] + ')', end=' ')
Jeremy Hyltona39414b2001-01-25 20:08:47 +0000189 elif op in hasfree:
190 if free is None:
191 free = co.co_cellvars + co.co_freevars
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print('(' + free[oparg] + ')', end=' ')
193 print()
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000194
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000195def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
Skip Montanaro19c6ba32003-02-27 21:29:27 +0000196 constants=None):
Tim Peters669454e2003-03-07 17:30:48 +0000197 labels = findlabels(code)
198 n = len(code)
199 i = 0
200 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000201 op = code[i]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000202 if i == lasti: print('-->', end=' ')
203 else: print(' ', end=' ')
204 if i in labels: print('>>', end=' ')
205 else: print(' ', end=' ')
206 print(repr(i).rjust(4), end=' ')
207 print(opname[op].ljust(15), end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000208 i = i+1
209 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000210 oparg = code[i] + code[i+1]*256
Tim Peters669454e2003-03-07 17:30:48 +0000211 i = i+2
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000212 print(repr(oparg).rjust(5), end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000213 if op in hasconst:
214 if constants:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000215 print('(' + repr(constants[oparg]) + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000216 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000217 print('(%d)'%oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000218 elif op in hasname:
219 if names is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000220 print('(' + names[oparg] + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000221 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000222 print('(%d)'%oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000223 elif op in hasjrel:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000224 print('(to ' + repr(i + oparg) + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000225 elif op in haslocal:
226 if varnames:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000227 print('(' + varnames[oparg] + ')', end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000228 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print('(%d)' % oparg, end=' ')
Tim Peters669454e2003-03-07 17:30:48 +0000230 elif op in hascompare:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000231 print('(' + cmp_op[oparg] + ')', end=' ')
232 print()
Skip Montanaro19c6ba32003-02-27 21:29:27 +0000233
Nick Coghlan5c8b54e2010-07-03 07:36:51 +0000234def _disassemble_str(source):
235 """Compile the source string, then disassemble the code object."""
236 disassemble(_try_compile(source, '<dis>'))
237
Tim Peters88869f92001-01-14 23:36:06 +0000238disco = disassemble # XXX For backwards compatibility
Guido van Rossumbd307951997-01-17 20:05:04 +0000239
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000240def findlabels(code):
Tim Peters88869f92001-01-14 23:36:06 +0000241 """Detect all offsets in a byte code which are jump targets.
Guido van Rossum421c2241997-11-18 15:47:55 +0000242
Tim Peters88869f92001-01-14 23:36:06 +0000243 Return the list of offsets.
Guido van Rossum421c2241997-11-18 15:47:55 +0000244
Tim Peters88869f92001-01-14 23:36:06 +0000245 """
246 labels = []
247 n = len(code)
248 i = 0
249 while i < n:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000250 op = code[i]
Tim Peters88869f92001-01-14 23:36:06 +0000251 i = i+1
252 if op >= HAVE_ARGUMENT:
Guido van Rossum75a902d2007-10-19 22:06:24 +0000253 oparg = code[i] + code[i+1]*256
Tim Peters88869f92001-01-14 23:36:06 +0000254 i = i+2
255 label = -1
256 if op in hasjrel:
257 label = i+oparg
258 elif op in hasjabs:
259 label = oparg
260 if label >= 0:
261 if label not in labels:
262 labels.append(label)
263 return labels
Guido van Rossum217a5fa1990-12-26 15:40:07 +0000264
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000265def findlinestarts(code):
266 """Find the offsets in a byte code which are start of lines in the source.
267
268 Generate pairs (offset, lineno) as described in Python/compile.c.
269
270 """
Guido van Rossum75a902d2007-10-19 22:06:24 +0000271 byte_increments = list(code.co_lnotab[0::2])
272 line_increments = list(code.co_lnotab[1::2])
Armin Rigo9c8f7ea2003-10-28 12:17:25 +0000273
274 lastlineno = None
275 lineno = code.co_firstlineno
276 addr = 0
277 for byte_incr, line_incr in zip(byte_increments, line_increments):
278 if byte_incr:
279 if lineno != lastlineno:
280 yield (addr, lineno)
281 lastlineno = lineno
282 addr += byte_incr
283 lineno += line_incr
284 if lineno != lastlineno:
285 yield (addr, lineno)
Guido van Rossum1fdae122000-02-04 17:47:55 +0000286
287def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000288 """Simple test program to disassemble a file."""
289 if sys.argv[1:]:
290 if sys.argv[2:]:
291 sys.stderr.write("usage: python dis.py [-|file]\n")
292 sys.exit(2)
293 fn = sys.argv[1]
294 if not fn or fn == "-":
295 fn = None
296 else:
297 fn = None
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000298 if fn is None:
Tim Peters88869f92001-01-14 23:36:06 +0000299 f = sys.stdin
300 else:
301 f = open(fn)
302 source = f.read()
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000303 if fn is not None:
Tim Peters88869f92001-01-14 23:36:06 +0000304 f.close()
305 else:
306 fn = "<stdin>"
307 code = compile(source, fn, "exec")
308 dis(code)
Guido van Rossum1fdae122000-02-04 17:47:55 +0000309
310if __name__ == "__main__":
Tim Peters88869f92001-01-14 23:36:06 +0000311 _test()