forked from cloudflare/stpyv8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSTPyV8.py
333 lines (243 loc) · 8.45 KB
/
STPyV8.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
326
327
328
329
330
331
332
333
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
from __future__ import print_function
import re
import collections.abc
import _STPyV8
__version__ = _STPyV8.JSEngine.version
__all__ = ["ReadOnly",
"DontEnum",
"DontDelete",
"Internal",
"JSError",
"JSObject",
"JSNull",
"JSUndefined",
"JSArray",
"JSFunction",
"JSClass",
"JSEngine",
"JSContext",
"JSIsolate",
"JSStackTrace",
"JSStackFrame",
"JSScript",
"JSLocker",
"JSUnlocker",
"JSPlatform"]
class JSAttribute:
def __init__(self, name):
self.name = name
def __call__(self, func):
setattr(func, f"__{self.name}__", True)
return func
ReadOnly = JSAttribute(name = 'readonly')
DontEnum = JSAttribute(name = 'dontenum')
DontDelete = JSAttribute(name = 'dontdel')
Internal = JSAttribute(name = 'internal')
class JSError(Exception):
def __init__(self, impl):
Exception.__init__(self)
self._impl = impl
def __str__(self):
return str(self._impl)
def __getattribute__(self, attr):
impl = super().__getattribute__("_impl")
try:
return getattr(impl, attr)
except AttributeError:
return super().__getattribute__(attr)
RE_FRAME = re.compile(r"\s+at\s(?:new\s)?(?P<func>.+)\s\((?P<file>[^:]+):?(?P<row>\d+)?:?(?P<col>\d+)?\)")
RE_FUNC = re.compile(r"\s+at\s(?:new\s)?(?P<func>.+)\s\((?P<file>[^\)]+)\)")
RE_FILE = re.compile(r"\s+at\s(?P<file>[^:]+):?(?P<row>\d+)?:?(?P<col>\d+)?")
@staticmethod
def parse_stack(value):
stack = []
def int_or_nul(value):
return int(value) if value else None
for line in value.split('\n')[1:]:
m = JSError.RE_FRAME.match(line)
if m:
stack.append((m.group('func'), m.group('file'), int_or_nul(m.group('row')), int_or_nul(m.group('col'))))
continue
m = JSError.RE_FUNC.match(line)
if m:
stack.append((m.group('func'), m.group('file'), None, None))
continue
m = JSError.RE_FILE.match(line)
if m:
stack.append((None, m.group('file'), int_or_nul(m.group('row')), int_or_nul(m.group('col'))))
continue
assert line
return stack
@property
def frames(self):
return self.parse_stack(self.stackTrace)
_STPyV8._JSError._jsclass = JSError # pylint:disable=protected-access
JSObject = _STPyV8.JSObject
JSNull = _STPyV8.JSNull
JSUndefined = _STPyV8.JSUndefined
JSArray = _STPyV8.JSArray
JSFunction = _STPyV8.JSFunction
JSPlatform = _STPyV8.JSPlatform
class JSLocker(_STPyV8.JSLocker):
def __enter__(self):
self.enter()
if JSContext.entered:
self.leave()
raise RuntimeError("Lock should be acquired before entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
if JSContext.entered:
self.leave()
raise RuntimeError("Lock should be released after leaving the context")
self.leave()
def __bool__(self):
return self.entered()
class JSUnlocker(_STPyV8.JSUnlocker):
def __enter__(self):
self.enter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.leave()
def __bool__(self):
return self.entered()
class JSClass:
__properties__ = {}
__watchpoints__ = {}
def __getattr__(self, name):
if name == 'constructor':
return JSClassConstructor(self.__class__)
if name == 'prototype':
return JSClassPrototype(self.__class__)
prop = self.__dict__.setdefault('__properties__', {}).get(name, None)
if prop and isinstance(prop[0], collections.abc.Callable):
return prop[0]()
raise AttributeError(name)
def __setattr__(self, name, value):
prop = self.__dict__.setdefault('__properties__', {}).get(name, None)
if prop and isinstance(prop[1], collections.abc.Callable):
return prop[1](value)
return object.__setattr__(self, name, value)
def toString(self):
"""
Return the string representation of the object
"""
return f"[object {self.__class__.__name__}]"
def toLocaleString(self):
"""
Return the string representation of the object as a string value
appropriate to the environment current locale
"""
return self.toString()
def valueOf(self):
"""
Return the primitive value of the object
"""
return self
def hasOwnProperty(self, name):
"""
Return a boolean value indicating whether the object has a property
with the specified name
"""
return hasattr(self, name)
def isPrototypeOf(self, obj):
"""
Return a boolean value indicating whether the object exists in the
prototype chain of another object
"""
raise NotImplementedError()
def __defineGetter__(self, name, getter):
"""
Bind the object property to a function to be called when that property
is looked up
"""
self.__properties__[name] = (getter, self.__lookupSetter__(name))
def __lookupGetter__(self, name):
"""
Return the function bound as a getter to the specified property
"""
return self.__properties__.get(name, (None, None))[0]
def __defineSetter__(self, name, setter):
"""
Bind the object property to a function to be called when an attempt
is made to set that property
"""
self.__properties__[name] = (self.__lookupGetter__(name), setter)
def __lookupSetter__(self, name):
"""
Return the function bound as setter to the specified property
"""
return self.__properties__.get(name, (None, None))[1]
def watch(self, prop, handler):
"""
Watch for a property to be assigned a value and runs a function when
such assignment occurs
"""
self.__watchpoints__[prop] = handler
def unwatch(self, prop):
"""
Remove a watchpoint set with the watch method
"""
del self.__watchpoints__[prop]
class JSClassConstructor(JSClass): # pylint:disable=abstract-method
def __init__(self, cls):
self.cls = cls
@property
def name(self):
return self.cls.__name__
def toString(self):
return f"function {self.name}() {{\n [native code]\n}}"
def __call__(self, *args, **kwds):
return self.cls(*args, **kwds)
class JSClassPrototype(JSClass): # pylint:disable=abstract-method
def __init__(self, cls):
self.cls = cls
@property
def constructor(self):
return JSClassConstructor(self.cls)
@property
def name(self):
return self.cls.__name__
class JSEngine(_STPyV8.JSEngine):
def __init__(self):
_STPyV8.JSEngine.__init__(self)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
del self
JSScript = _STPyV8.JSScript
JSStackTrace = _STPyV8.JSStackTrace
JSStackTrace.Options = _STPyV8.JSStackTraceOptions
JSStackTrace.GetCurrentStackTrace = staticmethod(lambda frame_limit, # pylint:disable=unnecessary-lambda
options: _STPyV8.JSIsolate.current.GetCurrentStackTrace(frame_limit, options))
JSStackFrame = _STPyV8.JSStackFrame
class JSIsolate(_STPyV8.JSIsolate):
def __enter__(self):
self.enter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.leave()
del self
class JSContext(_STPyV8.JSContext):
def __init__(self, obj = None, ctxt = None):
self.lock = JSLocker()
self.lock.enter()
if ctxt:
_STPyV8.JSContext.__init__(self, ctxt)
else:
_STPyV8.JSContext.__init__(self, obj)
def __enter__(self):
self.enter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.leave()
if hasattr(JSLocker, 'lock'):
self.lock.leave()
self.lock = None
del self
v8_default_platform = JSPlatform()
v8_default_platform.init()
v8_default_isolate = JSIsolate()
v8_default_isolate.enter()