Skip to content

Bad return value from WASM function with Asyncify and fibers #13302

@vagran

Description

@vagran

I have tried to implement my threads using Fibers API. It works in general but at least one major issue found. When calling asynchronous WASM function (which has context switch) from JS, the returned promise is resolved with some random values, usually undefined. Here is the minimal example:

emscripten_fiber_t thisCtx, otherCtx;
size_t stackSize = 2 * 1024 * 1024;
void *curStack = malloc(stackSize),
     *otherStack = malloc(stackSize),
     *otherCStack = malloc(stackSize);

void
ThreadFunc(void *)
{
    emscripten_sleep(2000);//<<< may be removed, then 0 is returned
    emscripten_fiber_swap(&otherCtx, &thisCtx);
}

int
Main()
{
    emscripten_fiber_init_from_current_context(&thisCtx, curStack, stackSize);
    emscripten_fiber_init(&otherCtx, ThreadFunc, nullptr, otherCStack, stackSize,
                          otherCStack, stackSize);
    emscripten_fiber_swap(&thisCtx, &otherCtx);
    return 42;
}

In JS:

lib.cwrap("Main", "number", [], { async: true })().then(rc => console.log("Main async rc", rc))

I expect output Main async rc 42, but it is either 0 or undefined. If Main() function does not have fibers switch, and use, for example, emscripten_sleep(), then correct result is returned. I suspect that pure fiber-based asynchronous code is not properly handled when obtaining returned value. Or I miss something when using fibers API?

emcc -v
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 2.0.11
clang version 12.0.0 (/b/s/w/ir/cache/git/chromium.googlesource.com-external-github.com-llvm-llvm--project f4c8b80318005ca61bfed9b40ee9e6039194159b)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /opt/emsdk/upstream/bin
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7.5.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/8
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Candidate multilib: .;@m64
Selected multilib: .;@m64
shared:INFO: (Emscripten: Running sanity checks)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions