/
pyc
executable file
·272 lines (221 loc) · 6.35 KB
/
pyc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env python
import argparse
import sys
import pyc_parser
import pyc_sir
import pyc_asm_list
import pyc_var_analyzer
import pyc_reg_allocator
import pyc_asm_nodes
import pyc_ir
import pyc_localize
import pyc_heapify
import pyc_closure
import pyc_sir_to_py
import pyc_declassify
import pyc_lineage
import pyc_dbg_data
import compiler
from pyc_log import *
import os.path
import time
import resource
import StringIO
g_phases = (
("parse", pyc_parser),
("declassify", pyc_declassify),
("localize", pyc_localize),
("explicate", pyc_ir),
("heapify", pyc_heapify),
("closure", pyc_closure),
("sir-list", pyc_sir),
("asm-node-list", pyc_asm_list)
)
g_allocs = [
"sudoku",
"stack"
]
def opt_parser():
global g_phases
parser = argparse.ArgumentParser(description='compile python to x86 assembly.')
parser.add_argument('file', nargs='?', type=argparse.FileType('r'), help='file to compile')
parser.add_argument('-c', '--code', help='code to compile')
parser.add_argument('-o', '--output', help='output file.')
parser.add_argument('-v', '--verbose', action='store_true', help='print debug output.')
parser.add_argument(
'-p',
'--phase',
help=('stop and print intermediate compiler result. phases: %s' % ", ".join(zip(*g_phases)[0]))
)
parser.add_argument(
'-i',
'--IR',
action='store_true',
help='output intermediate representation python program instead of x86'
)
parser.add_argument(
'-n',
'--code-only',
action='store_true',
help='dont output prefix and suffix for IR python program (for use with --IR)'
)
parser.add_argument(
'-g',
'--graph',
action='store_true',
help='output graph visualization script of the generated AST instead of x86'
)
parser.add_argument(
'--alloc',
help=('choose register allocator algorithm (default: %s). algos: %s' % (g_allocs[0], ", ".join(g_allocs)) )
)
return parser
class MissingOption(Exception):
pass
def validate(options):
if options.file == None and options.code == None:
raise MissingOption('specify either file or code to compile')
def run(options):
global g_phases
#print options
validate(options)
if options.verbose == True:
log_set_verbose()
else:
log_set_quiet()
options.src_type = 'cmdline'
options.src = options.code
if options.src == None:
options.src = options.file.read()
options.src_type = 'file'
if isinstance(options.src, basestring) != True:
raise Exception('invalid src variable. type: %s' % (options.src.__class__.__name__) )
if (not options.phase is None) and options.phase not in zip(*g_phases)[0]:
raise Exception('invalid phase variable: %s' % options.phase)
log(options)
# Increase max stack size from 8MB to 512MB
resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
sys.setrecursionlimit(10**6)
trace = pyc_lineage.Tracer()
iast = pyc_parser.parse(options.src)
if options.phase == 'parse':
pyc_parser.print_astree(iast)
exit(0)
for (phase_name, phase_mod) in g_phases[1:-2]:
log("phase: %s" % phase_name)
iast = getattr(phase_mod, 'txform')(iast, tracer=trace)
if options.phase == phase_name:
pyc_parser.print_astree(iast)
exit(0)
sir_mod = pyc_sir.txform(iast, tracer=trace)
if options.phase == 'sir-list':
#print pyc_sir.sir_list_to_str(sir_mod.body)
pyc_parser.print_astree(sir_mod)
exit(0)
if options.IR:
type = "txt" if options.code_only else "python"
with output_file(options, type) as f:
if not options.code_only:
print >>f, "import sys"
print >>f, "import resource"
print >>f, "sys.path.append(%s)" % repr(os.path.abspath("./pylib"))
print >>f, "sys.path.append(%s)" % repr(os.path.abspath("./."))
print >>f, "from pyc_runtime import *"
print >>f, "resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))"
print >>f, "sys.setrecursionlimit(10**6)"
pyc_sir_to_py.generate(sir_mod, f, line_comments = True)
if not options.code_only:
print >>f, ""
print >>f, "#" + "*"*40 + "#"
print >>f, "exit(main())"
exit(0)
bloc_list = pyc_asm_list.from_sir_mod(sir_mod)
bloc_list_str = lambda : "\n".join([repr(n) for n in bloc_list])
if options.phase == 'asm-node-list':
print bloc_list_str()
exit(0)
flat_bloc_list = []
for bloc in bloc_list:
t0 = time.time()
(adjusted_insns, symtbl) = pyc_reg_allocator.allocate(bloc.insns, options.alloc == 'stack')
#print "allocation time: %d" % (time.time() - t0)
asm_ir = pyc_asm_nodes.AsmFlow.patch(adjusted_insns)
log(lambda : "final bloc: %r" % bloc )
flat_bloc_list.append(pyc_asm_nodes.FlatCodeBloc(
name = bloc.name,
insns = asm_ir,
symtbl = symtbl
))
if options.graph:
with output_file(options, "graph") as f:
pyc_lineage.graph(flat_bloc_list, f)
exit(0)
sir_src = StringIO.StringIO()
pyc_sir_to_py.generate(sir_mod, sir_src)
patched_bloc_list = []
for bloc in flat_bloc_list:
patched_bloc_list.append(bloc.patch())
output(
options,
patched_bloc_list,
pyc_dbg_data.headers(
options.src,
sir_src.getvalue(),
patched_bloc_list
)
)
def asm_headers(debug_headers):
headers = []
headers.extend(debug_headers)
headers.extend([
".text",
])
headers.extend(pyc_asm_nodes.GlobalString.data_headers())
return headers
def output_is_to_stdout(options):
return (options.src_type == 'cmdline' or options.output == '-')
def output_file(options, type):
if output_is_to_stdout(options):
return sys.stdout
else:
if type == 'python' :
ext = 'py-ir'
elif type == 'txt':
ext = 'txt'
elif type == 'graph':
ext = 'graph'
else:
ext = "s"
output_fname = "%s.%s" % (os.path.splitext(options.file.name)[0], ext)
ofile = open(output_fname, 'w')
return ofile
def with_output_file(options, type, bloc):
ofile = output_file(options, type)
bloc(ofile)
ofile.flush()
if ofile != sys.stdout:
ofile.close()
def output(options, patched_bloc_list, debug_headers):
with output_file(options, "asm") as f:
for hdr in asm_headers(debug_headers):
print >>f, (hdr)
print >>f
for bloc in patched_bloc_list:
print >>f
if bloc.name == "main":
print >>f, ".globl %s" % bloc.name
print >>f, ".type %s, @function" % bloc.name
print >>f, "%s:" % bloc.name
bloc.to_asm(f, lambda s: ("\t" + s))
print >>f, ".size %s, .-%s" % (bloc.name, bloc.name)
print >>f
if __name__ == "__main__":
opt_p = opt_parser()
options = opt_p.parse_args()
try:
run(options)
except MissingOption as e:
print e
print
opt_p.print_help()
exit(-1)