diff --git a/Makefile b/Makefile index 7393f2c..ab27f57 100644 --- a/Makefile +++ b/Makefile @@ -48,6 +48,7 @@ SRCS := \ src/cat/types/generator.c \ src/cat/types/selector.c \ src/cat/types/list.c \ + src/cat/types/memory.c \ src/cat/types/ffi.c \ src/cat/stdlib/stdlib.c \ src/cat/stdlib/toml.c \ diff --git a/include/cat/types/memory.h b/include/cat/types/memory.h new file mode 100644 index 0000000..1c13c80 --- /dev/null +++ b/include/cat/types/memory.h @@ -0,0 +1,48 @@ +/* + * cat/types/memory.h -- the concrete `memory` type. + * + * Naming rule: symbols here are cat_types_memory_* / CAT_TYPES_MEMORY_*. + * + * `memory` is a bounds-checked, owned byte buffer. It exists so + * catscript can build C structs and buffers for FFI calls (GLFW, + * Vulkan, ...) without giving up memory safety: + * + * - every read/write is bounds-checked; an out-of-range offset + * raises an error instead of corrupting memory or crashing; + * - the buffer owns its storage and frees it when collected; + * - `ptr` exposes the address for an FFI call (valid for the call, + * and for the whole VM run since values are not freed early). + * + * local m = memory(16) + * m:set_u32(0, 1234) + * print(m:u32(0)) -- 1234 + * m:set_text(4, "hi") -- 7 bytes: "hi" + NUL is at 4..6 + * print(m:text(4)) -- hi + */ +#ifndef CAT_TYPES_MEMORY_H +#define CAT_TYPES_MEMORY_H + +#include "cat/value.h" + +struct CAT_VM_State; + +/* CAT_TYPES_MEMORY_Memory -- an owned, bounds-checked byte buffer. */ +typedef struct CAT_TYPES_MEMORY_Memory { + CAT_VALUE_Value base; + unsigned char *data; + size_t size; +} CAT_TYPES_MEMORY_Memory; + +/* Allocate a zeroed buffer of `size` bytes. */ +CAT_VALUE_Value *cat_types_memory_new(size_t size); + +/* Wrap existing bytes (copies `size` bytes; caller keeps its own). */ +CAT_VALUE_Value *cat_types_memory_from(const void *src, size_t size); + +/* The raw bytes and size (for native code that needs the storage). */ +unsigned char *cat_types_memory_data(CAT_VALUE_Value *v); +size_t cat_types_memory_size(CAT_VALUE_Value *v); + +CAT_VALUE_Vtable *cat_types_memory_vtable(void); + +#endif /* CAT_TYPES_MEMORY_H */ diff --git a/src/cat/lexer.c b/src/cat/lexer.c index 8256d3e..b9dd8aa 100644 --- a/src/cat/lexer.c +++ b/src/cat/lexer.c @@ -128,7 +128,33 @@ int cat_lexer_next(CAT_LEXER_Lexer *lx, CAT_LEXER_Token *out) return 0; } - /* numbers: int or float */ + /* numbers: int or float, with 0x/0b/0o integer bases */ + if (c == '0' && (peek2(lx) == 'x' || peek2(lx) == 'X' || + peek2(lx) == 'b' || peek2(lx) == 'B' || + peek2(lx) == 'o' || peek2(lx) == 'O')) { + int base = 16; + int n = 0; + int marker = peek2(lx); + out->text[n++] = (char)advance(lx); /* '0' */ + out->text[n++] = (char)advance(lx); /* x/b/o */ + if (marker == 'b' || marker == 'B') + base = 2; + else if (marker == 'o' || marker == 'O') + base = 8; + while (isxdigit(peek(lx)) || peek(lx) == '_') { + int d = peek(lx); + advance(lx); + if (d == '_') + continue; + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)d; + } + out->text[n] = '\0'; + /* skip the 0x/0b/0o prefix for strtoll */ + out->kind = CAT_LEXER_TOK_INT; + out->ival = strtoll(out->text + 2, NULL, base); + return 0; + } if (isdigit(c)) { int isfloat = 0; int n = 0; diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index 92e2851..c022116 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -24,6 +24,7 @@ #include "cat/types/function.h" #include "cat/types/file.h" #include "cat/types/ffi.h" +#include "cat/types/memory.h" #include "cat/types/empty.h" #include @@ -544,6 +545,19 @@ static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, return 0; } +/* `memory(n)` -- allocate an owned, bounds-checked byte buffer. */ +static int lf_memory(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + long long n = (nargs >= 1) ? cat_types_number_as_int(args[0]) : 0; + + (void)vm; + if (n < 0) + n = 0; + *out = cat_types_memory_new((size_t)n); + return 0; +} + /* `use expr` -- import another catscript source file (alias of dofile), * so `use "std/io/file.cat"` pulls its definitions into this unit. */ static int lf_use(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, @@ -667,6 +681,10 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm) cat_vm_set_global(vm, "ffi", cat_types_ffi_module()); /* the empty object: the value for "no value" (catscript has no nil) */ cat_vm_set_global(vm, "empty", cat_types_empty()); + /* `memory(n)` -- an owned, bounds-checked byte buffer */ + cat_vm_set_global(vm, "memory", + cat_types_native_new_doc("memory", lf_memory, + "memory(n) -- buffer de n bytes com limites verificados.")); /* `module` reflects the unit currently executing (name/path/dir) */ cat_vm_set_global(vm, "module", cat_module_table("main", NULL)); return 0; diff --git a/src/cat/types/ffi.c b/src/cat/types/ffi.c index be6a3fa..45dd213 100644 --- a/src/cat/types/ffi.c +++ b/src/cat/types/ffi.c @@ -17,6 +17,7 @@ #include "cat/types/float.h" #include "cat/types/bool.h" #include "cat/types/table.h" +#include "cat/types/memory.h" #include "cat/error.h" #include @@ -163,6 +164,22 @@ typedef union { static void arg_to_slot(CAT_VALUE_Value *v, ffi_type *t, ffi_slot *slot) { + /* A `memory` value used where a pointer is expected passes its + * buffer address (the value outlives the call: nothing is freed + * mid-run). This is how structs reach native code. */ + if (v != NULL && v->vtable == cat_types_memory_vtable() && + t == &ffi_type_pointer) { + slot->p = cat_types_memory_data(v); + return; + } + if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) { + if (t == &ffi_type_pointer) { + slot->s = cat_types_text_bytes(v); + return; + } + slot->i = (long long)strtoll(cat_types_text_bytes(v), NULL, 10); + return; + } if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { if (t == &ffi_type_double) { slot->d = cat_types_number_as_double(v); @@ -172,17 +189,10 @@ static void arg_to_slot(CAT_VALUE_Value *v, ffi_type *t, ffi_slot *slot) slot->d = cat_types_number_as_double(v); return; } + /* a number used as a pointer: the integer IS the address */ slot->i = cat_types_number_as_int(v); return; } - if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) { - if (t == &ffi_type_pointer) { - slot->s = cat_types_text_bytes(v); - return; - } - slot->i = (long long)strtoll(cat_types_text_bytes(v), NULL, 10); - return; - } if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) { slot->i = ((CAT_VALUE_Value *)v) ? 1 : 0; return; diff --git a/src/cat/types/memory.c b/src/cat/types/memory.c new file mode 100644 index 0000000..9d34e7b --- /dev/null +++ b/src/cat/types/memory.c @@ -0,0 +1,308 @@ +/* + * cat/types/memory.c -- the concrete `memory` type. + * + * Naming rule: symbols here are cat_types_memory_* / CAT_TYPES_MEMORY_*. + * + * A bounds-checked, owned byte buffer. Struct fields are read/written + * through named methods, so a bad offset raises an error instead of + * corrupting memory. Scalar access is little-endian (x86-64/aarch64, + * the platforms catscript targets) so it matches the native structs + * that GLFW/Vulkan expect. + */ +#include "cat/types/memory.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/bool.h" +#include "cat/types/empty.h" +#include "cat/types/ascii_text.h" +#include "cat/types/native.h" +#include "cat/vm.h" +#include "cat/error.h" + +#include +#include + +/* ---- bounds helpers ------------------------------------------------- */ + +/* Check that [off, off+n) fits; returns 0 or raises. `what` names the + * access for the message. */ +static int mem_check(CAT_TYPES_MEMORY_Memory *m, long long off, size_t n, + const char *what, CAT_ERROR_Error *err) +{ + if (off < 0 || (size_t)off > m->size || n > m->size - (size_t)off) + return (cat_error_raise(err, + "memory: %s out of bounds (offset %lld, %zu bytes, size %zu)", + what, off, n, m->size), -1); + return 0; +} + +static CAT_TYPES_MEMORY_Memory *mem_self(CAT_VALUE_Value *v) +{ + return (CAT_TYPES_MEMORY_Memory *)v; +} + +/* ---- typed reads ---------------------------------------------------- */ + +static int mem_get(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out, CAT_ERROR_Error *err, size_t width, + int is_float) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(self); + long long off = (nargs >= 1) ? cat_types_number_as_int(args[0]) : 0; + + if (mem_check(m, off, width, "read", err) != 0) + return -1; + if (is_float && width == 4) { + float f; + memcpy(&f, m->data + off, 4); + *out = cat_types_float_new((double)f); + return 0; + } + if (is_float && width == 8) { + double d; + memcpy(&d, m->data + off, 8); + *out = cat_types_float_new(d); + return 0; + } + { + unsigned long long v = 0; + memcpy(&v, m->data + off, width); /* little-endian */ + *out = cat_types_int_new((long long)v); + } + return 0; +} + +static int mem_set(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out, CAT_ERROR_Error *err, size_t width, + int is_float) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(self); + long long off = (nargs >= 1) ? cat_types_number_as_int(args[0]) : 0; + + if (mem_check(m, off, width, "write", err) != 0) + return -1; + if (is_float && width == 4) { + float f = (nargs >= 2) ? (float)cat_types_number_as_double(args[1]) : 0.0f; + memcpy(m->data + off, &f, 4); + } else if (is_float && width == 8) { + double d = (nargs >= 2) ? cat_types_number_as_double(args[1]) : 0.0; + memcpy(m->data + off, &d, 8); + } else { + unsigned long long v = (nargs >= 2) + ? (unsigned long long)cat_types_number_as_int(args[1]) : 0; + memcpy(m->data + off, &v, width); /* little-endian */ + } + *out = self; + return 0; +} + +/* One callback per width so we can dispatch by attribute name. Each + * raises the bounds error into vm->err so the VM reports it. */ +static int mem_u8(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 1, 0); } +static int mem_u16(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 2, 0); } +static int mem_u32(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 4, 0); } +static int mem_u64(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 8, 0); } +static int mem_f32(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 4, 1); } +static int mem_f64(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_get(a[0], a+1, n-1, o, &vm->err, 8, 1); } +static int mem_set_u8(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 1, 0); } +static int mem_set_u16(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 2, 0); } +static int mem_set_u32(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 4, 0); } +static int mem_set_u64(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 8, 0); } +static int mem_set_f32(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 4, 1); } +static int mem_set_f64(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, CAT_VALUE_Value **o){ return mem_set(a[0], a+1, n-1, o, &vm->err, 8, 1); } + +/* m:text(off) -- read a NUL-terminated string starting at off. */ +static int mem_text(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + long long off = (n >= 2) ? cat_types_number_as_int(a[1]) : 0; + + if (off < 0 || (size_t)off >= m->size) { + *out = cat_types_ascii_text_new(""); + return 0; + } + *out = cat_types_ascii_text_new((const char *)m->data + off); + return 0; +} + +/* m:set_text(off, s) -- write s plus a terminating NUL. */ +static int mem_set_text(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + long long off = (n >= 2) ? cat_types_number_as_int(a[1]) : 0; + const char *s = (n >= 3) ? cat_types_text_bytes(a[2]) : ""; + size_t len = strlen(s) + 1; + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (mem_check(m, off, len, "set_text", &e) != 0) + return (cat_error_raise(&vm->err, "%s", e.message), -1); + memcpy(m->data + off, s, len); + *out = a[0]; + return 0; +} + +/* m:ptr() -- the address as an int (for an FFI call). */ +static int mem_ptr(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + + *out = cat_types_int_new((long long)(size_t)m->data); + return 0; +} + +/* m:size() -- the buffer length. */ +static int mem_size_(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + + *out = cat_types_int_new((long long)m->size); + return 0; +} + +/* m:fill(byte [, off, count]) -- set bytes. */ +static int mem_fill(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + long long val = (n >= 2) ? cat_types_number_as_int(a[1]) : 0; + long long off = (n >= 3) ? cat_types_number_as_int(a[2]) : 0; + long long count = (n >= 4) ? cat_types_number_as_int(a[3]) + : (long long)m->size; + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (mem_check(m, off, (size_t)count, "fill", &e) != 0) + return (cat_error_raise(&vm->err, "%s", e.message), -1); + memset(m->data + off, (int)val, (size_t)count); + *out = a[0]; + return 0; +} + +/* m:copy(dst_off, src_memory, src_off, count) -- bounded memcpy. */ +static int mem_copy(CAT_VM_State *vm, CAT_VALUE_Value **a, int n, + CAT_VALUE_Value **out) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(a[0]); + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (n >= 2 && a[1] != NULL && a[1]->vtable == cat_types_memory_vtable()) { + CAT_TYPES_MEMORY_Memory *src = mem_self(a[1]); + long long dst = 0; + long long off = 0; + long long count = (long long)src->size; + if (mem_check(m, dst, (size_t)count, "copy", &e) != 0) + return (cat_error_raise(&vm->err, "%s", e.message), -1); + memcpy(m->data + dst, src->data + off, (size_t)count); + } + *out = a[0]; + return 0; +} + +/* ---- the attribute dispatcher --------------------------------------- */ + +struct mem_method { + const char *name; + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); +}; + +static const struct mem_method g_methods[] = { + { "u8", mem_u8 }, { "i8", mem_u8 }, + { "u16", mem_u16 }, { "i16", mem_u16 }, + { "u32", mem_u32 }, { "i32", mem_u32 }, + { "u64", mem_u64 }, { "i64", mem_u64 }, + { "f32", mem_f32 }, { "f64", mem_f64 }, + { "set_u8", mem_set_u8 }, { "set_i8", mem_set_u8 }, + { "set_u16", mem_set_u16 }, { "set_i16", mem_set_u16 }, + { "set_u32", mem_set_u32 }, { "set_i32", mem_set_u32 }, + { "set_u64", mem_set_u64 }, { "set_i64", mem_set_u64 }, + { "set_f32", mem_set_f32 }, { "set_f64", mem_set_f64 }, + { "text", mem_text }, { "set_text", mem_set_text }, + { "ptr", mem_ptr }, { "size", mem_size_ }, + { "fill", mem_fill }, { "copy", mem_copy }, + { NULL, NULL } +}; + +static int memory_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + int i; + + if (strcmp(name, "_doc_") == 0) { + *out = cat_types_ascii_text_new( + "memory -- a bounds-checked byte buffer (u8..u64, " + "f32/f64, text, ptr, size, fill, copy)."); + return 0; + } + for (i = 0; g_methods[i].name != NULL; i++) { + if (strcmp(g_methods[i].name, name) == 0) { + *out = cat_types_native_new(name, g_methods[i].cb); + return 0; + } + } + return (cat_error_raise(err, "memory has no attribute '%s'", name), -1); +} + +static void memory_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_MEMORY_Memory *m = mem_self(self); + + free(m->data); + free(m); +} + +static CAT_VALUE_Vtable g_memory_vtable = { + .type_name = "memory", + .kind = CAT_VALUE_KIND_TABLE, + .get_attribute = { memory_get_attribute }, + .destroy = memory_destroy, +}; + +CAT_VALUE_Vtable *cat_types_memory_vtable(void) +{ + return &g_memory_vtable; +} + +CAT_VALUE_Value *cat_types_memory_new(size_t size) +{ + CAT_TYPES_MEMORY_Memory *m = calloc(1, sizeof(*m)); + + if (m == NULL) + return NULL; + m->base.vtable = &g_memory_vtable; + m->size = size; + m->data = calloc(1, size ? size : 1); + if (m->data == NULL) { + free(m); + return NULL; + } + return &m->base; +} + +CAT_VALUE_Value *cat_types_memory_from(const void *src, size_t size) +{ + CAT_VALUE_Value *v = cat_types_memory_new(size); + + if (v != NULL && src != NULL && size > 0) + memcpy(cat_types_memory_data(v), src, size); + return v; +} + +unsigned char *cat_types_memory_data(CAT_VALUE_Value *v) +{ + if (v == NULL || v->vtable != &g_memory_vtable) + return NULL; + return ((CAT_TYPES_MEMORY_Memory *)v)->data; +} + +size_t cat_types_memory_size(CAT_VALUE_Value *v) +{ + if (v == NULL || v->vtable != &g_memory_vtable) + return 0; + return ((CAT_TYPES_MEMORY_Memory *)v)->size; +} diff --git a/tests/memory.cat b/tests/memory.cat new file mode 100644 index 0000000..a684d32 --- /dev/null +++ b/tests/memory.cat @@ -0,0 +1,40 @@ +-- tests/memory.cat -- the bounds-checked `memory` buffer. +-- +-- `memory(n)` owns n bytes. Fields are read/written through named +-- methods; every access is bounds-checked and raises instead of +-- corrupting memory. + +local m = memory(16) +m:set_u32(0, 1234) +print("u32:", m:u32(0)) +m:set_u64(8, 9999999999) +print("u64:", m:u64(8)) +m:set_text(4, "hi") +print("text:", m:text(4)) +print("size:", m:size()) +m:set_f32(0, 3.5) +print("f32:", m:f32(0)) +m:set_f64(8, 2.5) +print("f64:", m:f64(8)) + +-- zeroed on allocation +local z = memory(4) +print("zero:", z:u32(0)) + +-- a freed-pointer-style address is available for FFI calls +local p = m:ptr() +print("ptr:", p > 0) + +-- fill and re-read +local f = memory(8) +f:fill(0xAB) +print("fill:", f:u8(0)) + +-- out-of-bounds raises (caught here) +try + local small = memory(2) + small:u32(0) + print("no raise") +except e + print("caught oob") +end diff --git a/tests/run_tests.sh b/tests/run_tests.sh index df5d654..23cf2ef 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -174,6 +174,22 @@ check "repr-list" "list: [a, b, _repr_]" "`echo "$out" | sed - out=`printf 'x = 50\nx\nx + 5\n' | $BIN | tr '>' '\n' | grep -oE '[0-9]+'` check "repl-echo" "50" "`echo "$out" | sed -n 1p`" check "repl-state" "55" "`echo "$out" | sed -n 2p`" +# ---- memory buffer ---------------------------------------------------- + +out=`$BIN tests/memory.cat` +check "mem-u32" "u32: 1234" "`echo "$out" | sed -n 1p`" +check "mem-u64" "u64: 9999999999" "`echo "$out" | sed -n 2p`" +check "mem-text" "text: hi" "`echo "$out" | sed -n 3p`" +check "mem-size" "size: 16" "`echo "$out" | sed -n 4p`" +check "mem-f32" "f32: 3.5" "`echo "$out" | sed -n 5p`" +check "mem-zero" "zero: 0" "`echo "$out" | sed -n 7p`" +check "mem-oob" "caught oob" "`echo "$out" | sed -n 10p`" + +out=`printf 'print(0xAB)\nprint(0b1010)\nprint(0o17)\n' | $BIN | grep -oE '[0-9]+'` +check "hex" "171" "`echo "$out" | sed -n 1p`" +check "bin" "10" "`echo "$out" | sed -n 2p`" +check "oct" "15" "`echo "$out" | sed -n 3p`" + # ---- imports: `use name` --------------------------------------------- out=`$BIN tests/import.cat`