From 2b41ea6d0cfddac2dfd2adff04bb99919f15972c Mon Sep 17 00:00:00 2001 From: Sam Clegg Date: Fri, 15 Sep 2023 12:09:11 -0700 Subject: [PATCH] Fix wrapping/modifying of single line JS library functions Fixes: #20264 --- src/library.js | 4 +--- src/parseTools.js | 6 ++++-- test/test_other.py | 24 ++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/library.js b/src/library.js index 2ad9dc9c86bc5..d8a4a393dd051 100644 --- a/src/library.js +++ b/src/library.js @@ -1813,9 +1813,7 @@ addToLibrary({ gethostbyname__deps: ['$getHostByName'], gethostbyname__proxy: 'sync', - gethostbyname: (name) => { - return getHostByName(UTF8ToString(name)); - }, + gethostbyname: (name) => getHostByName(UTF8ToString(name)), $getHostByName__deps: ['malloc', '$stringToNewUTF8', '$DNS', '$inetPton4'], $getHostByName: (name) => { diff --git a/src/parseTools.js b/src/parseTools.js index a069d0e2166f3..eef46f68a2a90 100644 --- a/src/parseTools.js +++ b/src/parseTools.js @@ -689,6 +689,7 @@ function modifyJSFunction(text, func) { let async_; let args; let rest; + let oneliner = false; let match = text.match(/^\s*(async\s+)?function\s+([^(]*)?\s*\(([^)]*)\)/); if (match) { async_ = match[1] || ''; @@ -701,6 +702,8 @@ function modifyJSFunction(text, func) { async_ = match[3] || ''; args = match[4]; rest = text.substr(match[0].length); + rest = rest.trim(); + oneliner = rest[0] != '{'; } else { // Match a function without a name (we could probably use a single regex // for both, but it would be more complex). @@ -712,9 +715,8 @@ function modifyJSFunction(text, func) { } } let body = rest; - const bodyStart = rest.indexOf('{'); - let oneliner = bodyStart < 0; if (!oneliner) { + const bodyStart = rest.indexOf('{'); const bodyEnd = rest.lastIndexOf('}'); assert(bodyEnd > 0); body = rest.substring(bodyStart + 1, bodyEnd); diff --git a/test/test_other.py b/test/test_other.py index 87f452519801a..53d157f7388aa 100644 --- a/test/test_other.py +++ b/test/test_other.py @@ -3884,6 +3884,30 @@ def test_js_lib_quoted_key(self): self.do_runf(test_file('hello_world.c'), 'hello, world!', emcc_args=['--js-library', 'lib.js']) + def test_js_lib_proxying(self): + # Regression test for a bug we had where jsifier would find and use + # the inner function in a library function consisting of a single + # line arrow function. + # See https://github.com/emscripten-core/emscripten/issues/20264 + create_file('lib.js', r''' +addToLibrary({ + foo__proxy: 'sync', + foo: () => setTimeout(() => { + console.log('should not see this before "done"'); + }), +}); +''') + create_file('src.c', r''' + #include + void foo(); + int main() { + printf("main\n"); + foo(); + printf("done\n"); + } + ''') + self.do_runf('src.c', 'main\ndone\n', emcc_args=['-sEXIT_RUNTIME', '-pthread', '-sPROXY_TO_PTHREAD', '--js-library', 'lib.js']) + def test_js_lib_exported(self): create_file('lib.js', r''' addToLibrary({