Skip to content

[BUG] Segfault on combo of global ctors, ostream, wasi #33175

Closed
@tqchen

Description

@tqchen

This is an issue for node's WASI integration with emscripten.

both global ctors need to be called, and ostream being used in the WASM standalone mode (emsdk latest upstream).

I have a case where I need to call the global static initializers(need to call _start before running other functions), but also have ostream in the code.

What was happening is that when ostream is being used in the code and it somehow triggers certain things to be added to global ctors, and then calling global ctors resulted in a segfault. So far I only get this error on node14, and I am not sure if it is related to the use of WASI.

C++

#include <emscripten.h>
#include <vector>
#include <sstream>

// static intializer, need to call _start
static std::vector<int> x = {1, 2, 3};

extern "C" {
EMSCRIPTEN_KEEPALIVE
int GetX(int i) {
   // use of ostream somehow makes _start fail.
    std::ostringstream os;
    os << "x";
    return x[i];
}
}
wasm_test.wasm: wasm_test.cc
	@mkdir -p $(@D)
	emcc -O3 -std=c++11 -o $@ $<

NodeJS

const { WASI } = require('wasi');

const wasi = new WASI({
    args: process.argv,
    env: process.env
  });

const binary = require('fs').readFileSync('build/wasm_test.wasm');

WebAssembly.instantiate(binary,
    { env: {}, wasi_snapshot_preview1: wasi.wasiImport }).then(({ instance }) => {
  // trigger ctors
  instance.exports._start();
  // test the static vars are correctly initialized.
  console.log(instance.exports.GetX(0));
});
node --experimental-wasi-unstable-preview1  --experimental-wasm-bigint test_wasm.js 

Relevant issue in the emscripten emscripten-core/emscripten#11001

Metadata

Metadata

Assignees

No one assigned

    Labels

    c++Issues and PRs that require attention from people who are familiar with C++.confirmed-bugIssues with confirmed bugs.wasiIssues and PRs related to the WebAssembly System Interface.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions