#ifndef AMAL_PROGRAM_H #define AMAL_PROGRAM_H #include "std/buffer.h" #include "std/hash_map.h" #include "std/arena_allocator.h" #include "bytecode/bytecode.h" #include "../executor/executor.h" /* TODO: Remove all these errors and move program decoding and execution to another process (crash sandbox) */ #define AMAL_PROGRAM_OK 0 #define AMAL_PROGRAM_ERR -1 #define AMAL_PROGRAM_INVALID_HEADER -16 #define AMAL_PROGRAM_INVALID_MAGIC_NUMBER -2 #define AMAL_PROGRAM_INCOMPATIBLE -3 #define AMAL_PROGRAM_INVALID_INTERMEDIATES -4 #define AMAL_PROGRAM_INVALID_INTERMEDIATES_SIZE -5 #define AMAL_PROGRAM_INVALID_STRINGS -6 #define AMAL_PROGRAM_INVALID_STRINGS_SIZE -7 #define AMAL_PROGRAM_ALLOC_FAILURE -8 #define AMAL_PROGRAM_INVALID_INSTRUCTIONS_SIZE -9 #define AMAL_PROGRAM_INVALID_INSTRUCTION -10 #define AMAL_PROGRAM_INSTRUCTION_INVALID_INTERMEDIATE_INDEX -11 #define AMAL_PROGRAM_INSTRUCTION_INVALID_DATA_INDEX -12 #define AMAL_PROGRAM_INSTRUCTION_STACK_OVERFLOW -13 #define AMAL_PROGRAM_INSTRUCTION_STACK_OOM -14 #define AMAL_PROGRAM_INSTRUCTION_ILLEGAL_JUMP_TARGET -15 #define AMAL_PROGRAM_INVALID_FUNCTIONS -16 #define AMAL_PROGRAM_INVALID_EXTERNAL_FUNCTIONS -17 #define AMAL_PROGRAM_INVALID_EXTERNAL_FUNCTIONS_SIZE -18 #define AMAL_PROGRAM_INSTRUCTION_INVALID_EXTERN_FUNC_INDEX -19 #define AMAL_PROGRAM_NO_SUCH_EXTERNAL_FUNCTION -20 #define AMAL_PROGRAM_EXTERN_FUNC_ALREADY_EXISTS -21 #define AMAL_PROGRAM_MAGIC_NUMBER (u32)0xdec05eba #define AMAL_PROGRAM_MAJOR_VERSION 1 #define AMAL_PROGRAM_MINOR_VERSION 0 #define AMAL_PROGRAM_PATCH_VERSION 0 #define AMAL_PROGRAM_NUM_REGISTERS 256 #define AMAL_PROGRAM_ARGS_SIZE_VARARGS -1 typedef struct { void *func; int args_byte_size; /* -1 if varargs (AMAL_PROGRAM_ARGS_SIZE_VARARGS) */ } ProgramExternFunc; typedef struct { Buffer/*<...>*/ data; u32 *string_indices; u32 *extern_func_indices; u8 *intermediates_start; /* Reference inside @data */ u8 *strings_start; /* Reference inside @data */ u8 *extern_funcs_start; /* Reference inside @data */ usize read_index; u16 num_intermediates; u16 num_strings; u16 num_functions; u16 num_extern_functions; ArenaAllocator allocator; /* Owned. Used by @extern_funcs_map */ HashMapType(BufferView, ProgramExternFunc) extern_funcs_map; } amal_program; CHECK_RESULT int amal_program_init(amal_program *self); void amal_program_deinit(amal_program *self); /* returns @AMAL_PROGRAM_EXTERN_FUNC_ALREADY_EXISTS if a function with the name @name already exists in the program */ CHECK_RESULT int amal_program_add_extern_func(amal_program *self, BufferView name, void *func_ptr, int args_byte_size); CHECK_RESULT int amal_program_append_bytecode(amal_program *self, Bytecode *bytecode); CHECK_RESULT int amal_program_run(amal_program *self); CHECK_RESULT int amal_program_save(amal_program *self, const char *filepath); #endif