-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathExceptionType.cc
More file actions
315 lines (256 loc) · 9.25 KB
/
ExceptionType.cc
File metadata and controls
315 lines (256 loc) · 9.25 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
/**
* @file ExceptionType.cc
* @author Tom Tang (xmader@distributive.network) and Philippe Laporte (philippe@distributive.network)
* @brief Struct for representing Python Exception objects from a corresponding JS Error object
* @date 2023-04-11
*
* @copyright Copyright (c) 2023-2024 Distributive Corp.
*
*/
#include "include/modules/pythonmonkey/pythonmonkey.hh"
#include "include/setSpiderMonkeyException.hh"
#include "include/ExceptionType.hh"
#include "include/StrType.hh"
#include "include/DictType.hh"
#include "include/JSObjectProxy.hh"
#include <jsapi.h>
#include <js/Exception.h>
#include <Python.h>
#include <frameobject.h>
#include "include/pyshim.hh"
PyObject *ExceptionType::getPyObject(JSContext *cx, JS::HandleObject error) {
// Convert the JS Error object to a Python string
JS::RootedValue errValue(cx, JS::ObjectValue(*error)); // err
JS::RootedObject errStack(cx, JS::ExceptionStackOrNull(error)); // err.stack
PyObject *errStr = getExceptionString(cx, JS::ExceptionStack(cx, errValue, errStack), true);
// Construct a new SpiderMonkeyError python object
PyObject *pyObject = PyObject_CallOneArg(SpiderMonkeyError, errStr); // _PyErr_CreateException, https://github.com/python/cpython/blob/3.9/Python/errors.c#L100
Py_XDECREF(errStr);
// Preserve the original JS Error object as the Python Exception's `jsError` attribute for lossless two-way conversion
PyObject *originalJsErrCapsule = DictType::getPyObject(cx, errValue);
PyObject_SetAttrString(pyObject, "jsError", originalJsErrCapsule);
return pyObject;
}
// Generating trace information
#define PyTraceBack_LIMIT 1000
static const int TB_RECURSIVE_CUTOFF = 3;
#if PY_VERSION_HEX >= 0x03090000
static inline int
tb_get_lineno(PyTracebackObject *tb) {
PyFrameObject *frame = tb->tb_frame;
PyCodeObject *code = PyFrame_GetCode(frame);
int lineno = PyCode_Addr2Line(code, tb->tb_lasti);
Py_DECREF(code);
return lineno;
}
#endif
static int
tb_print_line_repeated(_PyUnicodeWriter *writer, long cnt)
{
cnt -= TB_RECURSIVE_CUTOFF;
PyObject *line = PyUnicode_FromFormat(
(cnt > 1)
? "[Previous line repeated %ld more times]\n"
: "[Previous line repeated %ld more time]\n",
cnt);
if (line == NULL) {
return -1;
}
int err = _PyUnicodeWriter_WriteStr(writer, line);
Py_DECREF(line);
return err;
}
JSObject *ExceptionType::toJsError(JSContext *cx, PyObject *exceptionValue, PyObject *traceBack) {
assert(exceptionValue != NULL);
if (PyObject_HasAttrString(exceptionValue, "jsError")) {
PyObject *originalJsErrCapsule = PyObject_GetAttrString(exceptionValue, "jsError");
if (originalJsErrCapsule && PyObject_TypeCheck(originalJsErrCapsule, &JSObjectProxyType)) {
return *((JSObjectProxy *)originalJsErrCapsule)->jsObject;
}
}
// Gather JS context
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-zero-length"
JS_ReportErrorASCII(cx, ""); // throw JS error and gather all details
#pragma GCC diagnostic pop
JS::ExceptionStack exceptionStack(cx);
if (!JS::GetPendingExceptionStack(cx, &exceptionStack)) {
return NULL;
}
JS_ClearPendingException(cx);
std::stringstream stackStream;
JS::RootedObject stackObj(cx, exceptionStack.stack());
if (stackObj.get()) {
JS::RootedString stackStr(cx);
JS::BuildStackString(cx, nullptr, stackObj, &stackStr, 2, js::StackFormat::SpiderMonkey);
JS::UniqueChars stackStrUtf8 = JS_EncodeStringToUTF8(cx, stackStr);
stackStream << "\nJS Stack Trace:\n" << stackStrUtf8.get();
}
// Gather Python context
PyObject *pyErrType = PyObject_Type(exceptionValue);
const char *pyErrTypeName = _PyType_Name((PyTypeObject *)pyErrType);
PyObject *pyErrMsg = PyObject_Str(exceptionValue);
if (traceBack) {
_PyUnicodeWriter writer;
_PyUnicodeWriter_Init(&writer);
PyObject *fileName = NULL;
int lineno = -1;
PyTracebackObject *tb = (PyTracebackObject *)traceBack;
long limit = PyTraceBack_LIMIT;
PyObject *limitv = PySys_GetObject("tracebacklimit");
if (limitv && PyLong_Check(limitv)) {
int overflow;
limit = PyLong_AsLongAndOverflow(limitv, &overflow);
if (overflow > 0) {
limit = LONG_MAX;
}
else if (limit <= 0) {
return NULL;
}
}
PyCodeObject *code = NULL;
Py_ssize_t depth = 0;
PyObject *last_file = NULL;
int last_line = -1;
PyObject *last_name = NULL;
long cnt = 0;
PyTracebackObject *tb1 = tb;
int err = 0;
int res;
PyObject *line = PyUnicode_FromString("Traceback (most recent call last):\n");
if (line == NULL) {
goto error;
}
res = _PyUnicodeWriter_WriteStr(&writer, line);
Py_DECREF(line);
if (res < 0) {
goto error;
}
// TODO should we reverse the stack and put it in the more common, non-python, top-most to bottom-most order? Wait for user feedback on experience
while (tb1 != NULL) {
depth++;
tb1 = tb1->tb_next;
}
while (tb != NULL && depth > limit) {
depth--;
tb = tb->tb_next;
}
#if PY_VERSION_HEX >= 0x03090000
while (tb != NULL) {
code = PyFrame_GetCode(tb->tb_frame);
int tb_lineno = tb->tb_lineno;
if (tb_lineno == -1) {
tb_lineno = tb_get_lineno(tb);
}
if (last_file == NULL ||
code->co_filename != last_file ||
last_line == -1 || tb_lineno != last_line ||
last_name == NULL || code->co_name != last_name) {
if (cnt > TB_RECURSIVE_CUTOFF) {
if (tb_print_line_repeated(&writer, cnt) < 0) {
goto error;
}
}
last_file = code->co_filename;
last_line = tb_lineno;
last_name = code->co_name;
cnt = 0;
}
cnt++;
if (cnt <= TB_RECURSIVE_CUTOFF) {
fileName = code->co_filename;
lineno = tb_lineno;
line = PyUnicode_FromFormat("File \"%U\", line %d, in %U\n", fileName, lineno, code->co_name);
if (line == NULL) {
goto error;
}
int res = _PyUnicodeWriter_WriteStr(&writer, line);
Py_DECREF(line);
if (res < 0) {
goto error;
}
}
Py_CLEAR(code);
tb = tb->tb_next;
}
if (cnt > TB_RECURSIVE_CUTOFF) {
if (tb_print_line_repeated(&writer, cnt) < 0) {
goto error;
}
}
#else
while (tb != NULL && err == 0) {
if (last_file == NULL ||
tb->tb_frame->f_code->co_filename != last_file ||
last_line == -1 || tb->tb_lineno != last_line ||
last_name == NULL || tb->tb_frame->f_code->co_name != last_name) {
if (cnt > TB_RECURSIVE_CUTOFF) {
err = tb_print_line_repeated(&writer, cnt);
}
last_file = tb->tb_frame->f_code->co_filename;
last_line = tb->tb_lineno;
last_name = tb->tb_frame->f_code->co_name;
cnt = 0;
}
cnt++;
if (err == 0 && cnt <= TB_RECURSIVE_CUTOFF) {
fileName = tb->tb_frame->f_code->co_filename;
lineno = tb->tb_lineno;
line = PyUnicode_FromFormat("File \"%U\", line %d, in %U\n", fileName, lineno, tb->tb_frame->f_code->co_name);
if (line == NULL) {
goto error;
}
int res = _PyUnicodeWriter_WriteStr(&writer, line);
Py_DECREF(line);
if (res < 0) {
goto error;
}
}
tb = tb->tb_next;
}
if (err == 0 && cnt > TB_RECURSIVE_CUTOFF) {
err = tb_print_line_repeated(&writer, cnt);
}
if (err) {
goto error;
}
#endif
{
std::stringstream msgStream;
msgStream << "Python " << pyErrTypeName << ": " << PyUnicode_AsUTF8(pyErrMsg) << "\n" << PyUnicode_AsUTF8(_PyUnicodeWriter_Finish(&writer));
msgStream << stackStream.str();
JS::RootedValue rval(cx);
JS::RootedString filename(cx, JS_NewStringCopyZ(cx, PyUnicode_AsUTF8(fileName)));
JS::RootedString message(cx, JS_NewStringCopyZ(cx, msgStream.str().c_str()));
// stack argument cannot be passed in as a string anymore (deprecated), and could not find a proper example using the new argument type
if (!JS::CreateError(cx, JSExnType::JSEXN_ERR, nullptr, filename, lineno, JS::ColumnNumberOneOrigin(1), nullptr, message, JS::NothingHandleValue, &rval)) {
return NULL;
}
Py_DECREF(pyErrType);
Py_DECREF(pyErrMsg);
return rval.toObjectOrNull();
}
error:
_PyUnicodeWriter_Dealloc(&writer);
Py_XDECREF(code);
}
// gather additional JS context details
JS::ErrorReportBuilder reportBuilder(cx);
if (!reportBuilder.init(cx, exceptionStack, JS::ErrorReportBuilder::WithSideEffects)) {
return NULL;
}
JSErrorReport *errorReport = reportBuilder.report();
std::stringstream msgStream;
msgStream << "Python " << pyErrTypeName << ": " << PyUnicode_AsUTF8(pyErrMsg);
msgStream << stackStream.str();
JS::RootedValue rval(cx);
JS::RootedString filename(cx, JS_NewStringCopyZ(cx, "")); // cannot be null or omitted, but is overriden by the errorReport
JS::RootedString message(cx, JS_NewStringCopyZ(cx, msgStream.str().c_str()));
// filename cannot be null
if (!JS::CreateError(cx, JSExnType::JSEXN_ERR, nullptr, filename, 0, JS::ColumnNumberOneOrigin(1), errorReport, message, JS::NothingHandleValue, &rval)) {
return NULL;
}
Py_DECREF(pyErrType);
Py_DECREF(pyErrMsg);
return rval.toObjectOrNull();
}