pyodide 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,294 @@
1
+ import ErrorStackParser from "error-stack-parser";
2
+ import { Module, API, Hiwire, Tests } from "./module.js";
3
+
4
+ /**
5
+ * Dump the Python traceback to the browser console.
6
+ *
7
+ * @private
8
+ */
9
+ API.dump_traceback = function () {
10
+ const fd_stdout = 1;
11
+ Module.__Py_DumpTraceback(fd_stdout, Module._PyGILState_GetThisThreadState());
12
+ };
13
+
14
+ let fatal_error_occurred = false;
15
+ /**
16
+ * Signal a fatal error.
17
+ *
18
+ * Dumps the Python traceback, shows a JavaScript traceback, and prints a clear
19
+ * message indicating a fatal error. It then dummies out the public API so that
20
+ * further attempts to use Pyodide will clearly indicate that Pyodide has failed
21
+ * and can no longer be used. pyodide._module is left accessible, and it is
22
+ * possible to continue using Pyodide for debugging purposes if desired.
23
+ *
24
+ * @argument e {Error} The cause of the fatal error.
25
+ * @private
26
+ */
27
+ API.fatal_error = function (e: any) {
28
+ if (e.pyodide_fatal_error) {
29
+ return;
30
+ }
31
+ if (fatal_error_occurred) {
32
+ console.error("Recursive call to fatal_error. Inner error was:");
33
+ console.error(e);
34
+ return;
35
+ }
36
+ if (typeof e === "number") {
37
+ // A C++ exception. Have to do some conversion work.
38
+ e = convertCppException(e);
39
+ } else if (typeof e === "string") {
40
+ e = new Error(e);
41
+ } else if (typeof e !== "object") {
42
+ e = new Error(
43
+ `An object of type ${typeof e} was thrown as an error. toString returns ${e.toString()}`
44
+ );
45
+ }
46
+ // Mark e so we know not to handle it later in EM_JS wrappers
47
+ e.pyodide_fatal_error = true;
48
+ fatal_error_occurred = true;
49
+ console.error(
50
+ "Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers."
51
+ );
52
+ console.error("The cause of the fatal error was:");
53
+ if (API.inTestHoist) {
54
+ // Test hoist won't print the error object in a useful way so convert it to
55
+ // string.
56
+ console.error(e.toString());
57
+ console.error(e.stack);
58
+ } else {
59
+ console.error(e);
60
+ }
61
+ try {
62
+ API.dump_traceback();
63
+ for (let key of Object.keys(API.public_api)) {
64
+ if (key.startsWith("_") || key === "version") {
65
+ continue;
66
+ }
67
+ Object.defineProperty(API.public_api, key, {
68
+ enumerable: true,
69
+ configurable: true,
70
+ get: () => {
71
+ throw new Error(
72
+ "Pyodide already fatally failed and can no longer be used."
73
+ );
74
+ },
75
+ });
76
+ }
77
+ if (API.on_fatal) {
78
+ API.on_fatal(e);
79
+ }
80
+ } catch (err2) {
81
+ console.error("Another error occurred while handling the fatal error:");
82
+ console.error(err2);
83
+ }
84
+ throw e;
85
+ };
86
+
87
+ class CppException extends Error {
88
+ ty: string;
89
+ constructor(ty: string, msg: string) {
90
+ super(msg);
91
+ this.ty = ty;
92
+ }
93
+ }
94
+ Object.defineProperty(CppException.prototype, "name", {
95
+ get() {
96
+ return `${this.constructor.name} ${this.ty}`;
97
+ },
98
+ });
99
+
100
+ /**
101
+ *
102
+ * Return the type name, whether the pointer inherits from exception, and the
103
+ * vtable pointer for the type.
104
+ *
105
+ * This code is based on imitating:
106
+ * 1. the implementation of __cxa_find_matching_catch
107
+ * 2. the disassembly from:
108
+ * ```C++
109
+ * try {
110
+ * ...
111
+ * } catch(exception e){
112
+ * ...
113
+ * }
114
+ *
115
+ * @param ptr
116
+ * @returns
117
+ * exc_type_name : the type name of the exception, as would be reported by
118
+ * `typeid(type).name()` but also demangled.
119
+ *
120
+ * is_exception_subclass : true if the object is a subclass of exception. In
121
+ * this case we will use `exc.what()` to get an error message.
122
+ *
123
+ * adjusted_ptr : The adjusted vtable pointer for the exception to use to invoke
124
+ * exc.what().
125
+ *
126
+ * @private
127
+ */
128
+ function cppExceptionInfo(ptr: number): [string, boolean, number] {
129
+ const base_exception_type = Module._exc_type();
130
+ const ei = new Module.ExceptionInfo(ptr);
131
+ const caught_exception_type = ei.get_type();
132
+ const stackTop = Module.stackSave();
133
+ const exceptionThrowBuf = Module.stackAlloc(4);
134
+ Module.HEAP32[exceptionThrowBuf / 4] = ptr;
135
+ const exc_type_name = Module.demangle(
136
+ Module.UTF8ToString(Module._exc_typename(caught_exception_type))
137
+ );
138
+ const is_exception_subclass = !!Module.___cxa_can_catch(
139
+ base_exception_type,
140
+ caught_exception_type,
141
+ exceptionThrowBuf
142
+ );
143
+ const adjusted_ptr = Module.HEAP32[exceptionThrowBuf / 4];
144
+ Module.stackRestore(stackTop);
145
+ return [exc_type_name, is_exception_subclass, adjusted_ptr];
146
+ }
147
+
148
+ function convertCppException(ptr: number): CppException {
149
+ const [exc_type_name, is_exception_subclass, adjusted_ptr] =
150
+ cppExceptionInfo(ptr);
151
+ let msg;
152
+ if (is_exception_subclass) {
153
+ // If the ptr inherits from exception, we can use exception.what() to
154
+ // generate a message
155
+ const msgPtr = Module._exc_what(adjusted_ptr);
156
+ msg = Module.UTF8ToString(msgPtr);
157
+ } else {
158
+ msg = `The exception is an object of type ${exc_type_name} at address ${ptr} which does not inherit from std::exception`;
159
+ }
160
+ return new CppException(exc_type_name, msg);
161
+ }
162
+ // Expose for testing
163
+ Tests.convertCppException = convertCppException;
164
+
165
+ function isPyodideFrame(frame: ErrorStackParser.StackFrame): boolean {
166
+ const fileName = frame.fileName || "";
167
+ if (fileName.includes("pyodide.asm")) {
168
+ return true;
169
+ }
170
+ if (fileName.includes("wasm-function")) {
171
+ return true;
172
+ }
173
+ if (!fileName.includes("pyodide.js")) {
174
+ return false;
175
+ }
176
+ let funcName = frame.functionName || "";
177
+ if (funcName.startsWith("Object.")) {
178
+ funcName = funcName.slice("Object.".length);
179
+ }
180
+ if (funcName in API.public_api && funcName !== "PythonError") {
181
+ frame.functionName = funcName;
182
+ return false;
183
+ }
184
+ return true;
185
+ }
186
+
187
+ function isErrorStart(frame: ErrorStackParser.StackFrame): boolean {
188
+ if (!isPyodideFrame(frame)) {
189
+ return false;
190
+ }
191
+ const funcName = frame.functionName;
192
+ return funcName === "PythonError" || funcName === "new_error";
193
+ }
194
+
195
+ Module.handle_js_error = function (e: any) {
196
+ if (e.pyodide_fatal_error) {
197
+ throw e;
198
+ }
199
+ if (e instanceof Module._PropagatePythonError) {
200
+ // Python error indicator is already set in this case. If this branch is
201
+ // not taken, Python error indicator should be unset, and we have to set
202
+ // it. In this case we don't want to tamper with the traceback.
203
+ return;
204
+ }
205
+ let restored_error = false;
206
+ if (e instanceof API.PythonError) {
207
+ // Try to restore the original Python exception.
208
+ restored_error = Module._restore_sys_last_exception(e.__error_address);
209
+ }
210
+ if (!restored_error) {
211
+ // Wrap the JavaScript error
212
+ let eidx = Hiwire.new_value(e);
213
+ let err = Module._JsProxy_create(eidx);
214
+ Module._set_error(err);
215
+ Module._Py_DecRef(err);
216
+ Hiwire.decref(eidx);
217
+ }
218
+ let stack = ErrorStackParser.parse(e);
219
+ if (isErrorStart(stack[0])) {
220
+ while (isPyodideFrame(stack[0])) {
221
+ stack.shift();
222
+ }
223
+ }
224
+ // Add the Javascript stack frames to the Python traceback
225
+ for (const frame of stack) {
226
+ if (isPyodideFrame(frame)) {
227
+ break;
228
+ }
229
+ const funcnameAddr = Module.stringToNewUTF8(frame.functionName || "???");
230
+ const fileNameAddr = Module.stringToNewUTF8(frame.fileName || "???.js");
231
+ Module.__PyTraceback_Add(funcnameAddr, fileNameAddr, frame.lineNumber);
232
+ Module._free(funcnameAddr);
233
+ Module._free(fileNameAddr);
234
+ }
235
+ };
236
+
237
+ /**
238
+ * A JavaScript error caused by a Python exception.
239
+ *
240
+ * In order to reduce the risk of large memory leaks, the ``PythonError``
241
+ * contains no reference to the Python exception that caused it. You can find
242
+ * the actual Python exception that caused this error as `sys.last_value
243
+ * <https://docs.python.org/3/library/sys.html#sys.last_value>`_.
244
+ *
245
+ * See :ref:`type-translations-errors` for more information.
246
+ *
247
+ * .. admonition:: Avoid Stack Frames
248
+ * :class: warning
249
+ *
250
+ * If you make a :any:`PyProxy` of ``sys.last_value``, you should be
251
+ * especially careful to :any:`destroy() <PyProxy.destroy>` it when you are
252
+ * done. You may leak a large amount of memory including the local
253
+ * variables of all the stack frames in the traceback if you don't. The
254
+ * easiest way is to only handle the exception in Python.
255
+ */
256
+ export class PythonError extends Error {
257
+ /** The address of the error we are wrapping. We may later compare this
258
+ * against sys.last_value.
259
+ * WARNING: we don't own a reference to this pointer, dereferencing it
260
+ * may be a use-after-free error!
261
+ * @private
262
+ */
263
+ __error_address: number;
264
+
265
+ constructor(message: string, error_address: number) {
266
+ const oldLimit = Error.stackTraceLimit;
267
+ Error.stackTraceLimit = Infinity;
268
+ super(message);
269
+ Error.stackTraceLimit = oldLimit;
270
+ this.__error_address = error_address;
271
+ }
272
+ }
273
+ Object.defineProperty(PythonError.prototype, "name", {
274
+ value: PythonError.name,
275
+ });
276
+ API.PythonError = PythonError;
277
+ // A special marker. If we call a CPython API from an EM_JS function and the
278
+ // CPython API sets an error, we might want to return an error status back to
279
+ // C keeping the current Python error flag. This signals to the EM_JS wrappers
280
+ // that the Python error flag is set and to leave it alone and return the
281
+ // appropriate error value (either NULL or -1).
282
+ class _PropagatePythonError extends Error {
283
+ constructor() {
284
+ API.fail_test = true;
285
+ super(
286
+ "If you are seeing this message, an internal Pyodide error has " +
287
+ "occurred. Please report it to the Pyodide maintainers."
288
+ );
289
+ }
290
+ }
291
+ Object.defineProperty(_PropagatePythonError.prototype, "name", {
292
+ value: _PropagatePythonError.name,
293
+ });
294
+ Module._PropagatePythonError = _PropagatePythonError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pyodide",
3
- "version": "0.19.0",
3
+ "version": "0.19.1",
4
4
  "description": "The Pyodide JavaScript package",
5
5
  "keywords": [
6
6
  "python",