不論是Python標準庫中內建的dis,還是我們之前看到的sdis,都只能一次對一段代碼進行反組譯碼,對於Cobra來說,這還不是很方便。為了在Cobra的GUI介面中顯示對一個.py檔案完整的反組譯碼結果,我們還需要一個比sdis更加強大的反組譯碼工具,這就是disassemble。
disassemble能一次性地對一個.py檔案進行完整的反組譯碼,同時將反組譯碼結果以使用者用好的方式嵌入到源檔案中,從而為Cobra的顯示提供了基礎。
下面是利用disassemble來反組譯碼某個.py檔案的例子:
>>> from core.disassemble import Disassemble
>>> dis = Disassemble()
>>> result = dis.parsePyFile('../demo.py')
>>> print >> open('demo_dised.ppy', 'w'), result
下面是源檔案和反組譯碼的結果檔案:
【源檔案:demo.py】
def f():
pass
def g():
print 'hello world'
def fun():
pass
class MyClass(object):
def __init__(self):
pass
a = 1
a += 1
print a
【反組譯碼結果檔案:demo_dised.py】
def f():
##1 0 LOAD_CONST 0 (<code object f at 00B47608, file "../demo.py", line 1>)
##1 3 MAKE_FUNCTION 0
##1 6 STORE_NAME 0 (f)
pass
##2 0 LOAD_CONST 0 (None)
##2 3 RETURN_VALUE
def g():
##4 9 LOAD_CONST 1 (<code object g at 00B51380, file "../demo.py", line 4>)
##4 12 MAKE_FUNCTION 0
##4 15 STORE_NAME 1 (g)
print 'hello world'
##5 0 LOAD_CONST 1 ('hello world')
##5 3 PRINT_ITEM
##5 4 PRINT_NEWLINE
def fun():
##6 5 LOAD_CONST 2 (<code object fun at 00B516E0, file "../demo.py", line 6>)
##6 8 MAKE_FUNCTION 0
##6 11 STORE_FAST 0 (fun)
##6 14 LOAD_CONST 0 (None)
##6 17 RETURN_VALUE
pass
##7 0 LOAD_CONST 0 (None)
##7 3 RETURN_VALUE
class MyClass(object):
##9 0 LOAD_NAME 0 (__name__)
##9 3 STORE_NAME 1 (__module__)
##9 18 LOAD_CONST 2 ('MyClass')
##9 21 LOAD_NAME 2 (object)
##9 24 BUILD_TUPLE 1
##9 27 LOAD_CONST 3 (<code object MyClass at 00B514A0, file "../demo.py", line 9>)
##9 30 MAKE_FUNCTION 0
##9 33 CALL_FUNCTION 0
##9 36 BUILD_CLASS
##9 37 STORE_NAME 3 (MyClass)
def __init__(self):
##10 6 LOAD_CONST 0 (<code object __init__ at 00B512F0, file "../demo.py", line 10>)
##10 9 MAKE_FUNCTION 0
##10 12 STORE_NAME 2 (__init__)
##10 15 LOAD_LOCALS
##10 16 RETURN_VALUE
pass
##11 0 LOAD_CONST 0 (None)
##11 3 RETURN_VALUE
a = 1
##13 40 LOAD_CONST 4 (1)
##13 43 STORE_NAME 4 (a)
a += 1
##14 46 LOAD_NAME 4 (a)
##14 49 LOAD_CONST 4 (1)
##14 52 INPLACE_ADD
##14 53 STORE_NAME 4 (a)
print a
##15 56 LOAD_NAME 4 (a)
##15 59 PRINT_ITEM
##15 60 PRINT_NEWLINE
##15 61 LOAD_CONST 5 (None)
##15 64 RETURN_VALUE