emscripten-core / emscripten-core/emscripten

[JSPI] Wrong order of execution when calling JSPI'ed function from deferred module

Open
#22,500 12 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

Please include the following in your bug report:

**Version of emscripten/emsdk:**
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.65 (7f8a05dd4e37cbd7ffde6d624f91fd545f7b52e3)
clang version 20.0.0git (https:/github.com/llvm/llvm-project 547917aebd1e79a8929b53f0ddf3b5185ee4df74)

**Issue**
I have a code like this
```cpp
#include
#include

extern "C" {
extern void jsPrintSomething(char *);
extern void saveProfileData();
}

void callJsFunc()
{
printf(" ********* Calling JS async function from deferred module ********* \n");
jsPrintSomething("from callJsFunc");
}

void foo() { callJsFunc(); }

extern "C" {
EMSCRIPTEN_KEEPALIVE int main()
{
printf(" ********* Calling JS async function in primary module ********* \n");
jsPrintSomething("from primary module");
saveProfileData();

foo();

printf(" End of main function \n");
return 0;
}
}
```
and the js library as follows:
```javascript
mergeInto(LibraryManager.library, {
jsPrintSomething__sig: "vi",
jsPrintSomething: function(ptr) {
var ptrStr = UTF8ToString(ptr);
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Printing ${ptrStr} after 1000ms`);
resolve();
}, 1000);
});
}
});
```

Build command:
emcc main.cpp -g -sMAIN_MODULE=2 -o index.js --js-library=jslibrary.js -sINCLUDE_FULL_LIBRARY=1 -sSPLIT_MODULE=1 -sJSPI
-sJSPI_IMPORTS=jsPrintSomething

After doing a split module and patching https://github.com/emscripten-core/emscripten/issues/22487, the Actual result I'm getting is
```
********* Calling JS async function in primary module *********
Printing from primary module after 1000ms
Profile data written to local disk
********* Calling JS async function from deferred module *********
End of main function
Printing from callJsFunc after 1000ms
```
Expected result:
```
********* Calling JS async function in primary module *********
Printing from primary module after 1000ms
Profile data written to local disk
********* Calling JS async function from deferred module *********
Printing from callJsFunc after 1000ms <------ Application should pause here and wait for this line to get printed first
End of main function
```

Reproducer:
[jspi_wrong_execution.zip](https://github.com/user-attachments/files/16874709/jspi_wrong_execution.zip)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.