/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef BIN_TYPES_H
#define BIN_TYPES_H

#include <bin/wasi.h>
#include <caio.h>
#include <fs/fs.h>
#include <dynstr.h>
#include <nanowasm/nw.h>
#include <nanowasm/dbg.h>
#include <sys/types.h>
#include <stdbool.h>

enum {BIN_IMPORTS = 10};

struct bin_dbg
{
    char b;
    bool running, step;
    struct nw_dbg dbg;
    struct dynstr dstr;
    struct aio *aio;
    struct fs_fd fd;
    long *bkpt, offset;
    size_t n_bkpt;
};

struct bin_stack
{
    struct page *page;
    size_t sz, pi, n;
};

struct bin_global
{
    void *buf;
    size_t sz;
};

struct bin_proc_fd
{
    int fd, flags;
    struct fs_fd fs_fd;
};

struct bin_proc
{
    const struct bin_mod *mod;
    struct nw_inst instance;
    union nw_value args[6];
    struct bin_dbg dbg;
    struct caio *caio;
    char *path, **argv;
    size_t argc;
    pid_t pid, parent;
    uid_t uid;
    gid_t gid;
    mode_t umask;
    char header[sizeof "asm"];
    size_t i;
    long retval;
    struct bin_stack stack;
    struct bin_global global;
    void *import;
    struct page *linear;
    struct fs_stdstreams ss;
    struct bin_proc_fd *fds;
    size_t n_fds;
    struct bin_proc *prev, *next;
};

struct bin_mod
{
    char *path;
    struct caio *caio;
    struct nw_mod mod;
    struct nw_mod_out mod_out;
    struct nw_import_index import_indexes[BIN_IMPORTS];
    struct bin_mod *prev, *next;
};

struct bin
{
    struct bin_mod *mod_head, *mod_tail;
    struct bin_proc *proc_head, *proc_tail;
};

extern struct bin bin_active, bin_pending, bin_locked, bin_zombie;

#endif
