wasmerio / wasmer

🚀 The leading Wasm Runtime supporting WASIX, WASI and Emscripten
https://wasmer.io
MIT License
18.45k stars 789 forks source link

Segmentation Fault when trying to access wasm_module_exports in C api #4773

Open Wulfheart opened 3 months ago

Wulfheart commented 3 months ago

Hello,

I have the following code and I want to get all exports by name. However, when executing it I get a Segmentation Fault. I linked against the ${WASMER_DIR}/lib/libwasmer.so.

Thank you in advance!

#include <cstdio>
#include <iostream>
#include <stdexcept>

#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>

#include "wasm.h"
#include "wasmer.h"

#include "perf.h"

#define ANKERL_NANOBENCH_IMPLEMENT
#include "nanobench.h"

std::string readFile(const char *name) {
  bool fexists = std::filesystem::exists(name);
  if (!fexists) {
    throw new std::invalid_argument("file does not exists");
  }

  std::ifstream watFile;
  watFile.open(name);
  std::stringstream strStream;
  strStream << watFile.rdbuf();
  return strStream.str();
}

int main() {

  printf("Initializing...\n");

  printf("Loading binary...\n");
  auto wats = readFile("./wasm/perf.wat");

  wasm_byte_vec_t wat;
  wasm_byte_vec_new(&wat, wats.length(), wats.c_str());
  wasm_byte_vec_t wasm_bytes;
  wat2wasm(&wat, &wasm_bytes);
  wasm_byte_vec_delete(&wat);

  printf("Creating the store...\n");
  wasm_engine_t *engine = wasm_engine_new();
  wasm_store_t *store = wasm_store_new(engine);

  printf("Compiling module...\n");
  wasm_module_t *module = wasm_module_new(store, &wasm_bytes);

  if (!module) {
    printf("> Error compiling module!\n");

    return 1;
  }

  wasm_byte_vec_delete(&wasm_bytes);

  printf("Creating imports...\n");
  wasm_extern_vec_t import_object = WASM_EMPTY_VEC;

  printf("Instantiating module...\n");
  wasm_instance_t *instance =
      wasm_instance_new(store, module, &import_object, NULL);

  if (!instance) {
    printf("> Error instantiating module!\n");

    return 1;
  }
  wasm_exporttype_vec_t *out;

  wasm_module_exports(module, out);
}
syrusakbary commented 3 months ago

Thanks for providing the example, and apologizes for taking a bit to reply (we've been in a crunch this week!). We'll take a look into this soon