forked from Distributive-Network/PythonMonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyProxyHandler.cc
More file actions
372 lines (330 loc) · 11.8 KB
/
PyProxyHandler.cc
File metadata and controls
372 lines (330 loc) · 11.8 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/**
* @file PyProxyHandler.cc
* @author Caleb Aikens (caleb@distributive.network)
* @brief Struct for creating JS proxy objects. Used by DictType for object coercion
* @version 0.1
* @date 2023-04-20
*
* Copyright (c) 2023 Distributive Corp.
*
*/
#include "include/PyProxyHandler.hh"
#include "include/jsTypeFactory.hh"
#include "include/pyTypeFactory.hh"
#include "include/ExceptionType.hh"
#include "include/StrType.hh"
#include <jsapi.h>
#include <jsfriendapi.h>
#include <js/Conversions.h>
#include <js/Proxy.h>
#include <Python.h>
PyObject *idToKey(JSContext *cx, JS::HandleId id) {
JS::RootedValue idv(cx, js::IdToValue(id));
JSString *idStr;
if (!id.isSymbol()) { // `JS::ToString` returns `nullptr` for JS symbols
idStr = JS::ToString(cx, idv);
} else {
// TODO (Tom Tang): Revisit this once we have Symbol coercion support
// FIXME (Tom Tang): key collision for symbols without a description string, or pure strings look like "Symbol(xxx)"
idStr = JS_ValueToSource(cx, idv);
}
// We convert all types of property keys to string
return StrType(cx, idStr).getPyObject();
}
bool idToIndex(JSContext *cx, JS::HandleId id, Py_ssize_t *index) {
if (id.isInt()) { // int-like strings have already been automatically converted to ints
*index = id.toInt();
return true;
} else {
return false; // fail
}
}
bool PyDictProxyHandler::ownPropertyKeys(JSContext *cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const {
PyObject *keys = PyDict_Keys(pyObject);
size_t length = PyList_Size(keys);
if (!props.reserve(length)) {
return false; // out of memory
}
for (size_t i = 0; i < length; i++) {
PyObject *key = PyList_GetItem(keys, i);
JS::RootedValue jsKey(cx, jsTypeFactory(cx, key));
JS::RootedId jsId(cx);
if (!JS_ValueToId(cx, jsKey, &jsId)) {
// @TODO (Caleb Aikens) raise exception
}
props.infallibleAppend(jsId);
}
return true;
}
bool PyDictProxyHandler::delete_(JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::ObjectOpResult &result) const {
PyObject *attrName = idToKey(cx, id);
if (PyDict_DelItem(pyObject, attrName) < 0) {
return result.failCantDelete(); // raises JS exception
}
return result.succeed();
}
bool PyDictProxyHandler::has(JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
bool *bp) const {
return hasOwn(cx, proxy, id, bp);
}
bool PyDictProxyHandler::get(JSContext *cx, JS::HandleObject proxy,
JS::HandleValue receiver, JS::HandleId id,
JS::MutableHandleValue vp) const {
PyObject *attrName = idToKey(cx, id);
PyObject *p = PyDict_GetItemWithError(pyObject, attrName);
if (!p) { // NULL if the key is not present
vp.setUndefined(); // JS objects return undefined for nonpresent keys
} else {
vp.set(jsTypeFactory(cx, p));
}
return true;
}
bool PyDictProxyHandler::set(JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::HandleValue v, JS::HandleValue receiver,
JS::ObjectOpResult &result) const {
JS::RootedValue *rootedV = new JS::RootedValue(cx, v);
PyObject *attrName = idToKey(cx, id);
JS::RootedObject *global = new JS::RootedObject(cx, JS::GetNonCCWObjectGlobal(proxy));
if (PyDict_SetItem(pyObject, attrName, pyTypeFactory(cx, global, rootedV)->getPyObject())) {
return result.failCantSetInterposed(); // raises JS exception
}
return result.succeed();
}
bool PyDictProxyHandler::enumerate(JSContext *cx, JS::HandleObject proxy,
JS::MutableHandleIdVector props) const {
return this->ownPropertyKeys(cx, proxy, props);
}
bool PyDictProxyHandler::hasOwn(JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
bool *bp) const {
PyObject *attrName = idToKey(cx, id);
*bp = PyDict_Contains(pyObject, attrName) == 1;
return true;
}
bool PyDictProxyHandler::getOwnEnumerablePropertyKeys(
JSContext *cx, JS::HandleObject proxy,
JS::MutableHandleIdVector props) const {
return this->ownPropertyKeys(cx, proxy, props);
}
// @TODO (Caleb Aikens) implement this
void PyDictProxyHandler::finalize(JS::GCContext *gcx, JSObject *proxy) const {}
bool PyDictProxyHandler::defineProperty(JSContext *cx, JS::HandleObject proxy,
JS::HandleId id,
JS::Handle<JS::PropertyDescriptor> desc,
JS::ObjectOpResult &result) const {
// Block direct `Object.defineProperty` since we already have the `set` method
return result.failInvalidDescriptor();
}
bool PyBaseProxyHandler::getPrototypeIfOrdinary(JSContext *cx, JS::HandleObject proxy,
bool *isOrdinary,
JS::MutableHandleObject protop) const {
// We don't have a custom [[GetPrototypeOf]]
*isOrdinary = true;
protop.set(js::GetStaticPrototype(proxy));
return true;
}
bool PyBaseProxyHandler::preventExtensions(JSContext *cx, JS::HandleObject proxy,
JS::ObjectOpResult &result) const {
result.succeed();
return true;
}
bool PyBaseProxyHandler::isExtensible(JSContext *cx, JS::HandleObject proxy,
bool *extensible) const {
*extensible = false;
return true;
}
bool PyListProxyHandler::getOwnPropertyDescriptor(
JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc
) const {
// We're trying to get the "length" property
bool isLengthProperty;
if (id.isString() && JS_StringEqualsLiteral(cx, id.toString(), "length", &isLengthProperty) && isLengthProperty) {
// proxy.length = len(pyObject)
desc.set(mozilla::Some(
JS::PropertyDescriptor::Data(
JS::Int32Value(PySequence_Size(pyObject))
)
));
return true;
}
// We're trying to get an item
Py_ssize_t index;
PyObject *item;
if (idToIndex(cx, id, &index) && (item = PySequence_GetItem(pyObject, index))) {
desc.set(mozilla::Some(
JS::PropertyDescriptor::Data(
jsTypeFactory(cx, item),
{JS::PropertyAttribute::Writable, JS::PropertyAttribute::Enumerable}
)
));
} else { // item not found in list, or not an int-like property key
desc.set(mozilla::Nothing());
}
return true;
}
bool PyListProxyHandler::defineProperty(
JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult &result
) const {
Py_ssize_t index;
if (!idToIndex(cx, id, &index)) { // not an int-like property key
return result.failBadIndex();
}
if (desc.isAccessorDescriptor()) { // containing getter/setter
return result.failNotDataDescriptor();
}
if (!desc.hasValue()) {
return result.failInvalidDescriptor();
}
// FIXME (Tom Tang): memory leak
JS::RootedObject *global = new JS::RootedObject(cx, JS::GetNonCCWObjectGlobal(proxy));
JS::RootedValue *itemV = new JS::RootedValue(cx, desc.value());
PyObject *item = pyTypeFactory(cx, global, itemV)->getPyObject();
if (PySequence_SetItem(pyObject, index, item) < 0) {
return result.failBadIndex();
}
return result.succeed();
}
bool PyListProxyHandler::ownPropertyKeys(JSContext *cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const {
// Modified from https://hg.mozilla.org/releases/mozilla-esr102/file/3b574e1/dom/base/RemoteOuterWindowProxy.cpp#l137
int32_t length = PySequence_Size(pyObject);
if (!props.reserve(length + 1)) {
return false;
}
// item indexes
for (int32_t i = 0; i < length; ++i) {
props.infallibleAppend(JS::PropertyKey::Int(i));
}
// the "length" property
props.infallibleAppend(JS::PropertyKey::NonIntAtom(JS_AtomizeString(cx, "length")));
return true;
}
bool PyListProxyHandler::delete_(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, JS::ObjectOpResult &result) const {
Py_ssize_t index;
if (!idToIndex(cx, id, &index)) {
return result.failBadIndex(); // report failure
}
// Set to undefined instead of actually deleting it
if (PySequence_SetItem(pyObject, index, Py_None) < 0) {
return result.failCantDelete(); // report failure
}
return result.succeed(); // report success
}
bool PyFuncProxyHandler::getOwnPropertyDescriptor(
JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc
) const {
// We're trying to get an attribute
StrType attrName = StrType(cx, id.toString());
PyObject *item;
if ((item = PyObject_GetAttr(pyObject, attrName.getPyObject()))) {
desc.set(mozilla::Some(
JS::PropertyDescriptor::Data(
jsTypeFactory(cx, item),
{JS::PropertyAttribute::Writable, JS::PropertyAttribute::Enumerable}
)
));
} else { // attribute not found in object
desc.set(mozilla::Nothing());
}
return true;
}
bool PyFuncProxyHandler::defineProperty(
JSContext *cx, JS::HandleObject proxy, JS::HandleId id,
JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult &result
) const {
if (desc.isAccessorDescriptor()) { // containing getter/setter
return result.failNotDataDescriptor();
}
if (!desc.hasValue()) {
return result.failInvalidDescriptor();
}
// @TODO (Caleb Aikens): there is a memory leak here
JS::RootedObject *global = new JS::RootedObject(cx, JS::GetNonCCWObjectGlobal(proxy));
StrType attrName = StrType(cx, id.toString());
JS::RootedValue *itemV = new JS::RootedValue(cx, desc.value());
PyObject *item = pyTypeFactory(cx, global, itemV)->getPyObject();
if (!item) {
return result.failBadIndex();
}
if (PyObject_SetAttr(pyObject, attrName.getPyObject(), item) < 0) {
return result.failBadIndex();
}
return result.succeed();
}
bool PyFuncProxyHandler::ownPropertyKeys(JSContext *cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const {
PyObject **objDict = _PyObject_GetDictPtr(pyObject);
if (!objDict) {
// pyObject has no __dict__
return true;
}
size_t length = PyDict_Size(*objDict);
if (!props.reserve(length)) {
return false; // out of memory
}
PyObject *key;
Py_ssize_t pos = 0;
while (PyDict_Next(*objDict, &pos, &key, NULL)) {
JS::RootedValue jsKey(cx, jsTypeFactory(cx, key));
JS::RootedId jsId(cx);
if (!JS_ValueToId(cx, jsKey, &jsId)) {
// @TODO (Caleb Aikens) raise exception
return false;
}
props.infallibleAppend(jsId);
}
return true;
}
bool PyFuncProxyHandler::delete_(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, JS::ObjectOpResult &result) const {
StrType attrName = StrType(cx, id.toString());
if (PyObject_SetAttr(pyObject, attrName.getPyObject(), NULL) < 0) {
return result.failCantDelete();
}
return result.succeed();
}
void setPyException(JSContext *cx) {
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
JS::RootedObject jsException(cx, ExceptionType(value).toJsError(cx));
JS::RootedValue jsExceptionValue(cx, JS::ObjectValue(*jsException));
JS_SetPendingException(cx, jsExceptionValue);
}
bool PyFuncProxyHandler::call(JSContext *cx, JS::HandleObject proxy, const JS::CallArgs &args) const {
if (JS_IsExceptionPending(cx)) {
return false;
}
if (PyErr_Occurred()) {
setPyException(cx);
return false;
}
JS::RootedObject *thisv = new JS::RootedObject(cx);
JS_ValueToObject(cx, args.thisv(), thisv);
if (!args.length()) {
#if PY_VERSION_HEX >= 0x03090000
PyObject *pyRval = PyObject_CallNoArgs(pyObject);
#else
PyObject *pyRval = _PyObject_CallNoArg(pyFunc); // in Python 3.8, the API is only available under the name with a leading underscore
#endif
if (PyErr_Occurred()) {
setPyException(cx);
return false;
}
args.rval().set(jsTypeFactory(cx, pyRval));
return true;
}
// populate python args tuple
PyObject *pyArgs = PyTuple_New(args.length());
for (size_t i = 0; i < args.length(); i++) {
JS::RootedValue *jsArg = new JS::RootedValue(cx, args[i]);
PyType *pyArg = pyTypeFactory(cx, thisv, jsArg);
PyTuple_SetItem(pyArgs, i, pyArg->getPyObject());
}
PyObject *pyRval = PyObject_Call(pyObject, pyArgs, NULL);
if (PyErr_Occurred()) {
setPyException(cx);
return false;
}
args.rval().set(jsTypeFactory(cx, pyRval));
return true;
}