-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.py
325 lines (271 loc) · 10.2 KB
/
main.py
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# Copyright (C) 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# Monkey-patch the stdlib.
from ctypes import util
fl = util.find_library
def patched_find_library(name):
if name == "c":
return "libc.so.6"
else:
return fl(name)
util.find_library = patched_find_library
import sys
# Abandon all hope, ye whose entrypoint is here.
import macropy.activate
from macropy.core.exporters import SaveExporter
macropy.exporter = SaveExporter("exported", "typhon")
from rpython.jit.codewriter.policy import JitPolicy
from rpython.rlib import rsignal
# from rpython.rlib import rvmprof
from rpython.rlib.debug import debug_print
from rpython.rlib.jit import set_user_param
from typhon import rsodium, ruv
from typhon.arguments import Configuration
from typhon.debug import enableDebugPrint, TyphonJitHooks
from typhon.errors import LoadFailed, UserException
from typhon.importing import obtainModule
from typhon.log import log
from typhon.metrics import globalRecorder
from typhon.nanopass import CompilerFailed
from typhon.objects.auditors import deepFrozenGuard
from typhon.objects.collections.maps import ConstMap, monteMap, unwrapMap
from typhon.objects.constants import NullObject
from typhon.objects.data import IntObject, StrObject, unwrapStr
from typhon.objects.guards import anyGuard
from typhon.objects.refs import resolution
from typhon.objects.root import tieMirandaKnot
from typhon.objects.slots import finalBinding
from typhon.prelude import registerGlobals
from typhon.profile import registerProfileTyphon
from typhon.scopes.boot import bootScope
from typhon.scopes.safe import safeScope
from typhon.scopes.unsafe import unsafeScope
from typhon.vats import Vat, VatManager, scopedVat
# We must do this once and now seems like the best time. ~ C.
tieMirandaKnot()
def dirname(p):
"""Returns the directory component of a pathname"""
i = p.rfind('/') + 1
assert i >= 0, "Proven above but not detectable"
head = p[:i]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head
def loadPrelude(config, recorder, vat):
scope = safeScope()
# For the prelude (and only the prelude), permit the boot scope.
scope.update(bootScope(config.libraryPaths, recorder))
registerGlobals({u"Bool": scope[u"Bool"],
u"Bytes": scope[u"Bytes"],
u"Char": scope[u"Char"],
u"Double": scope[u"Double"],
u"Int": scope[u"Int"],
u"Str": scope[u"Str"],
u"Void": scope[u"Void"]})
with recorder.context(u"mast"):
module = obtainModule(config.libraryPaths, recorder, "prelude")
with recorder.context(u"prelude"):
result = module.eval(scope)[0]
assert result is not None, "Prelude returned None"
assert isinstance(result, ConstMap), "Prelude returned non-Map"
prelude = {}
for key, value in unwrapMap(result).items():
s = unwrapStr(key)
assert s.startswith(u"&&"), "Prelude key doesn't start with &&"
prelude[s[2:]] = value
log(["info", "prelude"], u"Loaded the prelude")
return prelude
def runUntilDone(vatManager, uv_loop, recorder):
# This may take a while.
anyVatHasTurns = vatManager.anyVatHasTurns()
while anyVatHasTurns or ruv.loopAlive(uv_loop):
for vat in vatManager.vats:
if vat.hasTurns():
with scopedVat(vat) as vat:
with recorder.context(u"vatturn"):
vat.takeSomeTurns()
if ruv.loopAlive(uv_loop):
with recorder.context(u"io"):
ruv.cleanup()
try:
if anyVatHasTurns:
# More work to be done, so don't block.
ruv.run(uv_loop, ruv.RUN_NOWAIT)
else:
# No more work to be done, so blocking is fine.
ruv.run(uv_loop, ruv.RUN_ONCE)
except CompilerFailed as cf:
debug_print("Caught fatal exception while reacting:",
cf.formatError())
raise
except UserException as ue:
debug_print("Caught exception while reacting:",
ue.formatError())
anyVatHasTurns = vatManager.anyVatHasTurns()
class profiling(object):
def __init__(self, path, enabled):
self.path = path
self.enabled = enabled
def __enter__(self):
# We can only enter once, since we must register the profile handles,
# and that is a one-time sort of thing.
if not self.enabled:
return
self.handle = open(self.path, "wb")
# Turn on vmprof, and *then* register the profile handles.
# rvmprof.enable(self.handle.fileno(), 0.00042)
registerProfileTyphon()
def __exit__(self, *args):
if not self.enabled:
return
# rvmprof.disable()
self.handle.close()
def cleanUpEverything():
"""
Put back any ambient-authority mutable global state that we may have
altered.
"""
try:
ruv.TTYResetMode()
except ruv.UVError as uve:
print "ruv.TTYResetMode() failed:", uve.repr()
def runTyphon(argv):
# Start metrics.
recorder = globalRecorder()
recorder.start()
# Initialize libsodium.
if rsodium.init() < 0:
print "Couldn't initialize libsodium!"
return 1
config = Configuration(argv)
if config.verbose:
enableDebugPrint()
config.enableLogging()
if len(config.argv) < 2:
print "No file provided?"
return 1
# Pass user configuration to the JIT.
set_user_param(None, config.jit)
# Intialize our loop.
uv_loop = ruv.alloc_loop()
# Usurp SIGPIPE, as libuv does not handle it.
rsignal.pypysig_ignore(rsignal.SIGPIPE)
# Initialize our first vat. It shall be immortal.
vatManager = VatManager()
vat = Vat(vatManager, uv_loop, checkpoints=-1)
vatManager.vats.append(vat)
# Update loop timing information. Until the loop really gets going, we
# have to do this ourselves in order to get the timing correct for early
# timers.
ruv.update_time(uv_loop)
try:
with scopedVat(vat) as vat:
prelude = loadPrelude(config, recorder, vat)
except LoadFailed as lf:
print lf
return 1
except CompilerFailed as cf:
debug_print("Caught exception while importing prelude:",
cf.formatError())
return 1
except UserException as ue:
debug_print("Caught exception while importing prelude:",
ue.formatError())
return 1
registerGlobals(prelude)
scope = safeScope()
scope.update(prelude)
ss = scope.copy()
reflectedSS = monteMap()
for k, b in ss.iteritems():
reflectedSS[StrObject(u"&&" + k)] = b
ss[u"safeScope"] = finalBinding(ConstMap(reflectedSS), deepFrozenGuard)
reflectedSS[StrObject(u"&&safeScope")] = ss[u"safeScope"]
scope[u"safeScope"] = ss[u"safeScope"]
scope.update(unsafeScope(argv, config))
# The initial vat is included as `currentVat` to the first level of
# loading and such.
scope[u"currentVat"] = finalBinding(vat, anyGuard)
reflectedUnsafeScope = monteMap()
unsafeScopeDict = {}
for k, b in scope.iteritems():
reflectedUnsafeScope[StrObject(u"&&" + k)] = b
unsafeScopeDict[k] = b
rus = finalBinding(ConstMap(reflectedUnsafeScope), anyGuard)
reflectedUnsafeScope[StrObject(u"&&unsafeScope")] = rus
unsafeScopeDict[u"unsafeScope"] = rus
try:
module = obtainModule([""], recorder, config.argv[1])
except LoadFailed as lf:
print lf
return 1
if config.loadOnly:
# We are finished.
return 0
with profiling("vmprof.log", config.profile):
# Update loop timing information.
ruv.update_time(uv_loop)
debug_print("Taking initial turn in script...")
result = NullObject
try:
with recorder.context(u"vatturn"):
with scopedVat(vat):
result = module.eval(unsafeScopeDict)[0]
if result is None:
return 1
except UserException as ue:
debug_print("Caught exception while taking initial turn:",
ue.formatError())
return 1
# Exit status code.
exitStatus = 0
# Update loop timing information.
ruv.update_time(uv_loop)
try:
runUntilDone(vatManager, uv_loop, recorder)
rv = resolution(result) if result is not None else NullObject
if isinstance(rv, IntObject):
exitStatus = rv.getInt()
except SystemExit:
pass
# Huh, apparently this doesn't work. Wonder why/why not.
# exitStatus = se.code
finally:
recorder.stop()
if config.metrics:
recorder.printResults()
# Clean up and exit.
cleanUpEverything()
return exitStatus
def entryPoint(argv):
"""
A wrapper that refuses to let errors pass silently.
"""
try:
return runTyphon(argv)
except EnvironmentError as ee:
print "RPython EnvironmentError:", ee.strerror, ee.filename
print "If you can reproduce this, please send me a test case."
raise
except ruv.UVError as uve:
print "RPython UVError:", uve.repr()
print "If you can reproduce this, please send me a test case."
raise
def jitpolicy(driver):
return JitPolicy(TyphonJitHooks())
def target(driver, *args):
driver.exe_name = "mt-typhon"
return entryPoint, None
if __name__ == "__main__":
sys.exit(entryPoint(sys.argv))