Skip to content

Commit

Permalink
webassembly/api: Allocate code data on C heap when running Python code.
Browse files Browse the repository at this point in the history
Otherwise Emscripten allocates it on the Emscripten C stack, which will
overflow for large amounts of code.

Fixes issue #14307.

Signed-off-by: Damien George <damien@micropython.org>
  • Loading branch information
dpgeorge committed Apr 24, 2024
1 parent 45848f7 commit 9c7f065
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 12 additions & 4 deletions ports/webassembly/api.js
Expand Up @@ -127,23 +127,31 @@ export async function loadMicroPython(options) {
},
pyimport: pyimport,
runPython(code) {
const len = Module.lengthBytesUTF8(code);
const buf = Module._malloc(len + 1);
Module.stringToUTF8(code, buf, len + 1);
const value = Module._malloc(3 * 4);
Module.ccall(
"mp_js_do_exec",
"number",
["string", "pointer"],
[code, value],
["pointer", "number", "pointer"],
[buf, len, value],
);
Module._free(buf);
return proxy_convert_mp_to_js_obj_jsside_with_free(value);
},
runPythonAsync(code) {
const len = Module.lengthBytesUTF8(code);
const buf = Module._malloc(len + 1);
Module.stringToUTF8(code, buf, len + 1);
const value = Module._malloc(3 * 4);
Module.ccall(
"mp_js_do_exec_async",
"number",
["string", "pointer"],
[code, value],
["pointer", "number", "pointer"],
[buf, len, value],
);
Module._free(buf);
return proxy_convert_mp_to_js_obj_jsside_with_free(value);
},
replInit() {
Expand Down
8 changes: 4 additions & 4 deletions ports/webassembly/main.c
Expand Up @@ -104,15 +104,15 @@ void mp_js_do_import(const char *name, uint32_t *out) {
}
}

void mp_js_do_exec(const char *src, uint32_t *out) {
void mp_js_do_exec(const char *src, size_t len, uint32_t *out) {
// Collect at the top-level, where there are no root pointers from stack/registers.
gc_collect_start();
gc_collect_end();

mp_parse_input_kind_t input_kind = MP_PARSE_FILE_INPUT;
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_lexer_t *lex = mp_lexer_new_from_str_len_dedent(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
mp_lexer_t *lex = mp_lexer_new_from_str_len_dedent(MP_QSTR__lt_stdin_gt_, src, len, 0);
qstr source_name = lex->source_name;
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
mp_obj_t module_fun = mp_compile(&parse_tree, source_name, false);
Expand All @@ -125,9 +125,9 @@ void mp_js_do_exec(const char *src, uint32_t *out) {
}
}

void mp_js_do_exec_async(const char *src, uint32_t *out) {
void mp_js_do_exec_async(const char *src, size_t len, uint32_t *out) {
mp_compile_allow_top_level_await = true;
mp_js_do_exec(src, out);
mp_js_do_exec(src, len, out);
mp_compile_allow_top_level_await = false;
}

Expand Down

0 comments on commit 9c7f065

Please sign in to comment.