Skip to content

Commit 47a6568

Browse files
committed
Initial file structure
1 parent aada23b commit 47a6568

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

bytecode_reader.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import dis
2+
import marshal
3+
import types
4+
5+
ifPtr = open("input.pyc", 'rb')
6+
header = ifPtr.read(8)
7+
codeObject = marshal.load(ifPtr)
8+
ifPtr.close()
9+
10+
11+
def parse_code_object(code_object):
12+
co_argcount = code_object.co_argcount
13+
co_nlocals = code_object.co_nlocals
14+
co_stacksize = code_object.co_stacksize
15+
co_flags = code_object.co_flags
16+
17+
insBytes = bytearray(code_object.co_code)
18+
19+
i = 0
20+
while i < len(insBytes):
21+
opcode = insBytes[i]
22+
if opcode not in dis.opmap.values():
23+
print(str(i) + ":", "NOT EXISTING INSTRUCTION")
24+
i += 1
25+
elif opcode < dis.HAVE_ARGUMENT:
26+
print(str(i) + " : ", dis.opname[opcode], opcode, 0, 1)
27+
i += 1
28+
elif opcode >= dis.HAVE_ARGUMENT:
29+
if len(insBytes) > i + 2:
30+
arg = (insBytes[i + 2] << 8) | insBytes[i + 1]
31+
else:
32+
arg = -1
33+
print(str(i) + " : ", dis.opname[opcode], opcode, arg, 3)
34+
i += 3
35+
36+
co_names = code_object.co_names
37+
38+
co_varnames = code_object.co_varnames
39+
co_filename = code_object.co_filename
40+
co_name = code_object.co_name
41+
co_firstlineno = code_object.co_firstlineno
42+
co_lnotab = code_object.co_lnotab
43+
44+
mod_const = []
45+
for const in code_object.co_consts:
46+
if isinstance(const, types.CodeType):
47+
mod_const.append(parse_code_object(const))
48+
pass
49+
else:
50+
mod_const.append(const)
51+
co_constants = tuple(mod_const)
52+
53+
return types.CodeType(co_argcount, co_nlocals, co_stacksize, co_flags,
54+
str(insBytes), co_constants, co_names, co_varnames,
55+
co_filename, co_name, co_firstlineno, co_lnotab)
56+
57+
58+
ofPtr = open('output.pyc', 'wb')
59+
ofPtr.write(header)
60+
marshal.dump(parse_code_object(codeObject), ofPtr)
61+
62+
ofPtr.close()

0 commit comments

Comments
 (0)