aboutsummaryrefslogtreecommitdiff
path: root/src/routines/find_function.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/routines/find_function.c')
-rw-r--r--src/routines/find_function.c100
1 files changed, 100 insertions, 0 deletions
diff --git a/src/routines/find_function.c b/src/routines/find_function.c
new file mode 100644
index 0000000..c0273ec
--- /dev/null
+++ b/src/routines/find_function.c
@@ -0,0 +1,100 @@
+/*
+ * 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/interp.h>
+#include <nw/io.h>
+#include <nw/log.h>
+#include <nw/routines.h>
+
+static enum nw_state seek_code(struct nw_interp *const i)
+{
+ const struct nw_i_sm_ffn *const f = &i->sm.ffn;
+ const struct nw_io_cfg *const cfg = &i->cfg.io;
+ const unsigned long fbo = nwp_leuint32(&f->fbo);
+ const enum nw_state n = cfg->seek(fbo, cfg->user);
+
+ if (n)
+ return n;
+
+ f->next(i);
+ return NW_AGAIN;
+}
+
+static enum nw_state get_fbo(struct nw_interp *const i)
+{
+ struct nw_i_sm_ffn *const f = &i->sm.ffn;
+ const struct nw_io_cfg *const cfg = &i->cfg.io;
+ const enum nw_state n = nwp_io_read(cfg, &f->io, cfg->user);
+
+ if (n)
+ return n;
+
+ i->next = seek_code;
+ return NW_AGAIN;
+}
+
+static enum nw_state seek_fbo(struct nw_interp *const i)
+{
+ struct nw_i_sm_ffn *const f = &i->sm.ffn;
+ const struct nw_mod *const m = i->cfg.m;
+ long offset = m->c_sections[NW_CUSTOM_FBO];
+ const struct nw_io_cfg *const cfg = &i->cfg.io;
+ enum nw_state n;
+
+ if (!offset)
+ {
+ static const char *const exc = "nw_fbo section not found";
+
+#ifdef NW_LOG
+ nwp_log("%s\n", exc);
+#endif
+ i->exception = exc;
+ return NW_FATAL;
+ }
+ else if (f->fn.index < m->import_count)
+ {
+ static const char *const exc = "invalid function index";
+
+ i->exception = exc;
+#ifdef NW_LOG
+ nwp_log("%s: %lu\n", exc, (unsigned long)f->fn.index);
+#endif
+ return NW_FATAL;
+ }
+
+ offset += sizeof f->fbo * (f->fn.index - m->import_count);
+
+ if ((n = cfg->seek(offset, cfg->user)))
+ return n;
+ else
+ {
+ struct nw_sm_io io = {0};
+
+ io.buf = &f->fbo;
+ io.n = sizeof f->fbo;
+ f->io = io;
+ i->next = get_fbo;
+ }
+
+ return NW_AGAIN;
+}
+
+void nwp_find_function(struct nw_interp *const i, const struct nw_fn *const fn,
+ void (*const next)(struct nw_interp *))
+{
+ const struct nw_i_sm_ffn f = {0};
+ struct nw_i_sm_ffn *const pf = &i->sm.ffn;
+
+ *pf = f;
+ pf->fn = *fn;
+ pf->next = next;
+ i->next = seek_fbo;
+}