aboutsummaryrefslogtreecommitdiff
path: root/src/start.c
blob: 788a5ad1195b3ced15603d3ebcf977e284cf8d6e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * nanowasm, a tiny WebAssembly/Wasm interpreter
 * Copyright (C) 2023-2025  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 <nanowasm/types.h>
#include <nw/inst.h>
#include <nw/interp.h>
#include <nw/log.h>
#include <nw/routines.h>
#include <stddef.h>

static enum nw_state push(struct nw_interp *const i)
{
    const struct nw_i_sm_exp *const e = &i->sm.export;

    if (e->kind != NW_KIND_FUNCTION)
    {
        static const char *const exc = "unexpected import kind";

        i->exception = exc;
#ifdef NW_LOG
        nwp_log("%s: %d\n", exc, e->kind);
#endif
        return NW_FATAL;
    }

    nwp_call(i, e->index);
    return NW_AGAIN;
}

static enum nw_state find_start(struct nw_inst *const inst)
{
    struct nw_interp *const i = &inst->interp;
    struct nw_interp_cfg cfg;

    cfg = i->cfg;

    if (nwp_interp_start(i, &cfg, NULL))
    {
#ifdef NW_LOG
        nwp_log("nwp_interp_start failed\n");
#endif
        return NW_FATAL;
    }

    nwp_find_export(i, inst->entry, push);
    inst->next = nwp_inst_run;
    return NW_AGAIN;
}

static enum nw_state init_data(struct nw_inst *const i)
{
    nwp_init_data(i, find_start);
    return NW_AGAIN;
}

int nw_start(struct nw_inst *const i, const struct nw_inst_cfg *const icfg)
{
    const struct nw_inst inst = {0};

    *i = inst;
    i->entry = icfg->entry;

    if (nwp_interp_start(&i->interp, &icfg->interp_cfg,
        &nwp_interp_initexpr_set))
    {
#ifdef NW_LOG
        nwp_log("nwp_interp_start failed\n");
#endif
        return -1;
    }

    nwp_init_globals(i, init_data);
    return 0;
}