Skip to content

Segfault on combo of global ctors, ostream, wasi #11001

@tqchen

Description

@tqchen

Dear developers. I encountered an interesting case when 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 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions