106 lines
2.2 KiB
C
106 lines
2.2 KiB
C
/*
|
|
* nanowasm, a tiny WebAssembly/Wasm interpreter
|
|
* Copyright (C) 2023-2024 Xavier Del Campo Romero
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
|
|
#include <nanowasm/nw.h>
|
|
#include <stddef.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
static int proc_exit(const struct nw_args *const params,
|
|
union nw_value *const ret, void *const user)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
static const struct nw_import imports[] =
|
|
{
|
|
{
|
|
.kind = NW_KIND_FUNCTION,
|
|
.module = "wasi_snapshot_preview1",
|
|
.field = "proc_exit",
|
|
.u.function =
|
|
{
|
|
.signature = "i32()",
|
|
.fn = proc_exit
|
|
}
|
|
}
|
|
};
|
|
|
|
static const struct nw_mod_cfg cfg =
|
|
{
|
|
.path = "example.wasm",
|
|
.imports = imports,
|
|
.n_imports = sizeof imports / sizeof *imports
|
|
};
|
|
|
|
struct nw_mod m;
|
|
|
|
if (nw_load(&cfg, &m))
|
|
{
|
|
fprintf(stderr, "%s: nw_load failed\n", __func__);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
const struct nw_inst_cfg icfg =
|
|
{
|
|
.interp =
|
|
{
|
|
.stack = NW_BUF(256),
|
|
.heap = NW_BUF(2048),
|
|
.global = NW_BUF(24),
|
|
.m = &m
|
|
}
|
|
};
|
|
|
|
struct nw_inst inst;
|
|
|
|
if (nw_start(&icfg, &inst))
|
|
{
|
|
fprintf(stderr, "%s: nw_start failed\n", __func__);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
const union nw_inst_state *s = &inst.state;
|
|
int ret = EXIT_FAILURE;
|
|
|
|
again:
|
|
|
|
switch (nw_run(&inst))
|
|
{
|
|
case NW_STATE_AGAIN:
|
|
goto again;
|
|
|
|
case NW_STATE_RETURNED:
|
|
fprintf(stderr, "instance returned %ld\n", s->retval);
|
|
break;
|
|
|
|
case NW_STATE_EXCEPTION:
|
|
fprintf(stderr, "exception: %s\n", s->exception);
|
|
goto end;
|
|
|
|
case NW_STATE_FATAL:
|
|
goto end;
|
|
}
|
|
|
|
ret = EXIT_SUCCESS;
|
|
|
|
end:
|
|
|
|
if (nw_stop(&inst))
|
|
{
|
|
fprintf(stderr, "%s: nw_stop failed\n", __func__);
|
|
ret = EXIT_FAILURE;
|
|
}
|
|
|
|
return ret;
|
|
}
|