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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
|
#!/usr/bin/env python
'''
You should normally never use this! Use emcc instead.
This is a small wrapper script around the core JS compiler. This calls that
compiler with the settings given to it. It can also read data from C/C++
header files (so that the JS compiler can see the constants in those
headers, for the libc implementation in JS).
'''
import json
import optparse
import os
import subprocess
import re
import sys
import time
if not os.environ.get('EMSCRIPTEN_SUPPRESS_USAGE_WARNING'):
print >> sys.stderr, '''
==============================================================
WARNING: You should normally never use this! Use emcc instead.
==============================================================
'''
from tools import shared
DEBUG = os.environ.get('EMCC_DEBUG')
__rootpath__ = os.path.abspath(os.path.dirname(__file__))
def path_from_root(*pathelems):
"""Returns the absolute path for which the given path elements are
relative to the emscripten root.
"""
return os.path.join(__rootpath__, *pathelems)
temp_files = shared.TempFiles()
def scan(ll, settings):
# blockaddress(@main, %23)
blockaddrs = []
for blockaddr in re.findall('blockaddress\([^)]*\)', ll):
b = blockaddr.split('(')[1][:-1].split(', ')
blockaddrs.append(b)
if len(blockaddrs) > 0:
settings['NECESSARY_BLOCKADDRS'] = blockaddrs
def process_funcs(args):
i, ll, settings_file, compiler, forwarded_file, libraries = args
funcs_file = temp_files.get('.func_%d.ll' % i).name
open(funcs_file, 'w').write(ll)
out = shared.run_js(compiler, shared.COMPILER_ENGINE, [settings_file, funcs_file, 'funcs', forwarded_file] + libraries, stdout=subprocess.PIPE, cwd=path_from_root('src'))
return out.split('//FORWARDED_DATA:')
def emscript(infile, settings, outfile, libraries=[]):
"""Runs the emscripten LLVM-to-JS compiler. We parallelize as much as possible
Args:
infile: The path to the input LLVM assembly file.
settings: JSON-formatted settings that override the values
defined in src/settings.js.
outfile: The file where the output is written.
"""
compiler = path_from_root('src', 'compiler.js')
# Parallelization: We run 3 phases:
# 1 aka 'pre' : Process types and metadata and so forth, and generate the preamble.
# 2 aka 'funcs': Process functions. We can parallelize this, working on each function independently.
# 3 aka 'post' : Process globals, generate postamble and finishing touches.
if DEBUG: print >> sys.stderr, 'emscript: ll=>js'
# Pre-scan ll and alter settings as necessary
if DEBUG: t = time.time()
ll = open(infile).read()
scan(ll, settings)
ll = None # allow collection
if DEBUG: print >> sys.stderr, ' emscript: scan took %s seconds' % (time.time() - t)
# Split input into the relevant parts for each phase
pre = []
funcs = [] # split up functions here, for parallelism later
meta = [] # needed by each function XXX
post = []
if DEBUG: t = time.time()
in_func = False
ll_lines = open(infile).readlines()
for line in ll_lines:
if in_func:
funcs[-1].append(line)
if line.startswith('}'):
in_func = False
else:
if line.startswith('define '):
in_func = True
funcs.append([line])
elif line.find(' = type { ') > 0:
pre.append(line) # type
elif line.startswith('!'):
meta.append(line) # metadata
else:
post.append(line) # global
pre.append(line) # pre needs it to, so we know about globals in pre and funcs
ll_lines = None
meta = ''.join(meta)
if DEBUG and len(meta) > 1024*1024: print >> sys.stderr, 'emscript warning: large amounts of metadata, will slow things down'
if DEBUG: print >> sys.stderr, ' emscript: split took %s seconds' % (time.time() - t)
#if DEBUG:
# print >> sys.stderr, '========= pre ================\n'
# print >> sys.stderr, ''.join(pre)
# print >> sys.stderr, '========== funcs ===============\n'
# for func in funcs:
# print >> sys.stderr, '\n// ===\n\n', ''.join(func)
# print >> sys.stderr, '========== post ==============\n'
# print >> sys.stderr, ''.join(post)
# print >> sys.stderr, '=========================\n'
# Save settings to a file to work around v8 issue 1579
settings_file = temp_files.get('.txt').name
s = open(settings_file, 'w')
s.write(json.dumps(settings))
s.close()
# Phase 1
if DEBUG: t = time.time()
pre_file = temp_files.get('.pre.ll').name
open(pre_file, 'w').write(''.join(pre) + '\n' + meta)
out = shared.run_js(compiler, shared.COMPILER_ENGINE, [settings_file, pre_file, 'pre'] + libraries, stdout=subprocess.PIPE, cwd=path_from_root('src'))
js, forwarded_data = out.split('//FORWARDED_DATA:')
#print 'js', js
#print >> sys.stderr, 'FORWARDED_DATA 1:', forwarded_data, type(forwarded_data)
forwarded_file = temp_files.get('.json').name
open(forwarded_file, 'w').write(forwarded_data)
if DEBUG: print >> sys.stderr, ' emscript: phase 1 took %s seconds' % (time.time() - t)
# Phase 2
# XXX must coordinate function indexixing data when parallelizing
if DEBUG: t = time.time()
forwarded_json = json.loads(forwarded_data)
indexed_functions = set()
for i in range(len(funcs)):
func = funcs[i]
funcs_js, curr_forwarded_data = process_funcs((i, ''.join(func) + '\n' + meta, settings_file, compiler, forwarded_file, libraries))
js += funcs_js
# merge forwarded data
curr_forwarded_json = json.loads(curr_forwarded_data)
#print >> sys.stderr, 'f', '\n\n' + json.dumps(forwarded_json) + '\n\n'
#print >> sys.stderr, 'c', '\n\n' + json.dumps(curr_forwarded_json) + '\n\n'
forwarded_json['Types']['preciseI64MathUsed'] = forwarded_json['Types']['preciseI64MathUsed'] or curr_forwarded_json['Types']['preciseI64MathUsed']
forwarded_json['Functions']['implementedFunctions'] = forwarded_json['Functions']['implementedFunctions'] or {}
for key, value in curr_forwarded_json['Functions']['implementedFunctions'].iteritems():
forwarded_json['Functions']['implementedFunctions'][key] = value
for key, value in curr_forwarded_json['Functions']['blockAddresses'].iteritems():
forwarded_json['Functions']['blockAddresses'][key] = value
for key in curr_forwarded_json['Functions']['indexedFunctions'].iterkeys():
indexed_functions.add(key)
if DEBUG: print >> sys.stderr, ' emscript: phase 2 took %s seconds' % (time.time() - t)
if DEBUG: t = time.time()
# calculations on merged forwarded data
forwarded_json['Functions']['indexedFunctions'] = {}
#print >> sys.stderr, 'need index', indexed_functions
index_reps = []
i = 2
for indexed in indexed_functions:
index_reps.append((indexed, i))
forwarded_json['Functions']['indexedFunctions'][indexed] = i
i += 2
forwarded_json['Functions']['nextIndex'] = i
def indexize(js):
for indexed, i in index_reps:
js = js.replace('{{{ FI_' + indexed + ' }}}', str(i)) # TODO: optimize, do them all with a regexp replace?
return js
# forward
forwarded_data = json.dumps(forwarded_json)
forwarded_file = temp_files.get('.2.json').name
open(forwarded_file, 'w').write(forwarded_data)
if DEBUG: print >> sys.stderr, ' emscript: phase 2b took %s seconds' % (time.time() - t)
# Phase 3
if DEBUG: t = time.time()
post_file = temp_files.get('.post.ll').name
open(post_file, 'w').write(''.join(post) + '\n' + meta)
out = shared.run_js(compiler, shared.COMPILER_ENGINE, [settings_file, post_file, 'post', forwarded_file] + libraries, stdout=subprocess.PIPE, cwd=path_from_root('src'))
js += out
if DEBUG: print >> sys.stderr, ' emscript: phase 3 took %s seconds' % (time.time() - t)
js = indexize(js)
outfile.write(js) # TODO: write in parts (see previous line though)
outfile.close()
def main(args):
# Prepare settings for serialization to JSON.
settings = {}
for setting in args.settings:
name, value = setting.strip().split('=', 1)
settings[name] = json.loads(value)
# Add header defines to settings
defines = {}
include_root = path_from_root('system', 'include')
headers = args.headers[0].split(',') if len(args.headers) > 0 else []
seen_headers = set()
while len(headers) > 0:
header = headers.pop(0)
if not os.path.isabs(header):
header = os.path.join(include_root, header)
seen_headers.add(header)
for line in open(header, 'r'):
line = line.replace('\t', ' ')
m = re.match('^ *# *define +(?P<name>[-\w_.]+) +\(?(?P<value>[-\w_.|]+)\)?.*', line)
if not m:
# Catch enum defines of a very limited sort
m = re.match('^ +(?P<name>[A-Z_\d]+) += +(?P<value>\d+).*', line)
if m:
if m.group('name') != m.group('value'):
defines[m.group('name')] = m.group('value')
#else:
# print 'Warning: %s #defined to itself' % m.group('name') # XXX this can happen if we are set to be equal to an enum (with the same name)
m = re.match('^ *# *include *["<](?P<name>[\w_.-/]+)[">].*', line)
if m:
# Find this file
found = False
for w in [w for w in os.walk(include_root)]:
for f in w[2]:
curr = os.path.join(w[0], f)
if curr.endswith(m.group('name')) and curr not in seen_headers:
headers.append(curr)
found = True
break
if found: break
#assert found, 'Could not find header: ' + m.group('name')
if len(defines) > 0:
def lookup(value):
try:
while not unicode(value).isnumeric():
value = defines[value]
return value
except:
pass
try: # 0x300 etc.
value = eval(value)
return value
except:
pass
try: # CONST1|CONST2
parts = map(lookup, value.split('|'))
value = reduce(lambda a, b: a|b, map(eval, parts))
return value
except:
pass
return None
for key, value in defines.items():
|