ffi: call native code (ctypes/CDLL-like) via libffi

- new ffi library: ffi.load(path) dlopen()s a shared object
- lib:func(name, sig) dlsym()s a symbol and prepares a libffi call
- signature grammar RET(ARG,...): void/bool/char/int*/uint*/long/
  float/double/string/pointers; ABI-correct call via ffi_prep_cif
- selector type scaffolding for () [] . {} dispatch (runtime wired)
- examples/ffi.cat (pow, sqrt, getpid, strlen, abs); 53/53 tests
- Makefile: -lffi -ldl
This commit is contained in:
Minus committed 2026-11-16 03:42:43 +00:00
1 parent ef305e7824
commit c319a0986d
10 files changed
+687 -1

No files matched your search

+3
View File
@@ -20,6 +20,7 @@
#include "cat/types/table.h"
#include "cat/types/native.h"
#include "cat/types/file.h"
#include "cat/types/ffi.h"
#include <stdio.h>
#include <stdlib.h>
@@ -433,5 +434,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
cat_types_native_new("StringIO", lf_stringio));
cat_vm_set_global(vm, "BytesIO",
cat_types_native_new("BytesIO", lf_bytesio));
/* the `ffi` library: call native code (ctypes/CDLL-like) */
cat_vm_set_global(vm, "ffi", cat_types_ffi_module());
return 0;
}
+378
View File
@@ -0,0 +1,378 @@
/*
* cat/types/ffi.c -- the `ffi` library: call native code (ctypes/CDLL-like).
*
* Naming rule: symbols here are cat_types_ffi_* / CAT_TYPES_FFI_*.
*
* `ffi.load(path)` dlopen()s a shared object. `lib:func(name, sig)`
* dlsym()s a symbol and prepares a libffi call from the signature, e.g.
* "double(double,double)". Calling the result makes the ABI-correct
* native call and converts the result back to a catscript value.
*/
#include "cat/types/ffi.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/native.h"
#include "cat/types/nil.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/bool.h"
#include "cat/types/table.h"
#include "cat/error.h"
#include <dlfcn.h>
#include <ffi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ---- type names -> ffi_type / kind ---------------------------------- */
static ffi_type *type_for(const char *t)
{
if (strcmp(t, "void") == 0) return &ffi_type_void;
if (strcmp(t, "bool") == 0) return &ffi_type_uint8;
if (strcmp(t, "char") == 0) return &ffi_type_schar;
if (strcmp(t, "int8") == 0) return &ffi_type_sint8;
if (strcmp(t, "uint8") == 0) return &ffi_type_uint8;
if (strcmp(t, "int16") == 0) return &ffi_type_sint16;
if (strcmp(t, "uint16") == 0) return &ffi_type_uint16;
if (strcmp(t, "int") == 0) return &ffi_type_sint32;
if (strcmp(t, "int32") == 0) return &ffi_type_sint32;
if (strcmp(t, "uint32") == 0) return &ffi_type_uint32;
if (strcmp(t, "long") == 0) return &ffi_type_slong;
if (strcmp(t, "ulong") == 0) return &ffi_type_ulong;
if (strcmp(t, "int64") == 0) return &ffi_type_sint64;
if (strcmp(t, "uint64") == 0) return &ffi_type_uint64;
if (strcmp(t, "longlong") == 0) return &ffi_type_sint64;
if (strcmp(t, "float") == 0) return &ffi_type_float;
if (strcmp(t, "double") == 0) return &ffi_type_double;
if (strcmp(t, "string") == 0) return &ffi_type_pointer;
if (strcmp(t, "char*") == 0) return &ffi_type_pointer;
if (strcmp(t, "void*") == 0) return &ffi_type_pointer;
if (strcmp(t, "ptr") == 0) return &ffi_type_pointer;
if (strcmp(t, "pointer") == 0) return &ffi_type_pointer;
/* any unknown base name followed by '*' is a pointer */
if (t[strlen(t) - 1] == '*')
return &ffi_type_pointer;
return NULL;
}
static int ret_kind_for(const char *t)
{
if (strcmp(t, "void") == 0) return CAT_TYPES_FFI_RET_VOID;
if (strcmp(t, "double") == 0 || strcmp(t, "float") == 0)
return CAT_TYPES_FFI_RET_DOUBLE;
if (strcmp(t, "string") == 0 || strcmp(t, "char*") == 0)
return CAT_TYPES_FFI_RET_STRING;
return CAT_TYPES_FFI_RET_INT;
}
/* Parse "RET(A,B,...)" into the function's cif/argtypes. Returns 0 on
* success, -1 on a malformed signature. */
static int prepare(CAT_TYPES_FFI_Function *f, const char *sig)
{
char ret[32];
char args[512];
const char *lp, *rp;
ffi_type **at;
int n;
char *p, *tok;
if (sig == NULL)
return -1;
lp = strchr(sig, '(');
rp = (lp != NULL) ? strrchr(sig, ')') : NULL;
if (lp == NULL || rp == NULL || rp < lp)
return -1;
if ((size_t)(lp - sig) >= sizeof(ret))
return -1;
memcpy(ret, sig, (size_t)(lp - sig));
ret[lp - sig] = '\0';
if ((size_t)(rp - lp - 1) >= sizeof(args))
return -1;
memcpy(args, lp + 1, (size_t)(rp - lp - 1));
args[rp - lp - 1] = '\0';
f->rtype = type_for(ret);
f->ret_kind = ret_kind_for(ret);
if (f->rtype == NULL)
return -1;
at = calloc(16, sizeof(*at));
n = 0;
p = args;
while (*p != '\0' && n < 16) {
while (*p == ' ' || *p == '\t' || *p == ',')
p++;
if (*p == '\0')
break;
tok = p;
while (*p != ',' && *p != '\0')
p++;
if (*p == ',')
*p++ = '\0';
{
size_t tl = strlen(tok);
while (tl > 0 && (tok[tl - 1] == ' ' || tok[tl - 1] == '\t'))
tok[--tl] = '\0';
}
if (tok[0] == '\0')
continue;
at[n] = type_for(tok);
if (at[n] == NULL) {
free(at);
return -1;
}
n++;
}
f->argtypes = at;
f->nargs = n;
{
ffi_cif *cif = calloc(1, sizeof(*cif));
if (cif == NULL || ffi_prep_cif(cif, FFI_DEFAULT_ABI, (unsigned)n,
f->rtype, at) != FFI_OK) {
free(cif);
free(at);
return -1;
}
f->cif = cif;
}
return 0;
}
static void function_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FFI_Function *f = (CAT_TYPES_FFI_Function *)self;
free(f->cif);
free(f->argtypes);
free(f->name);
free(f->sig);
free(f);
}
/* ---- converting catscript args to native storage -------------------- */
typedef union {
long long i;
double d;
const char *s;
void *p;
} ffi_slot;
static void arg_to_slot(CAT_VALUE_Value *v, ffi_type *t, ffi_slot *slot)
{
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);
return;
}
if (t == &ffi_type_float) {
slot->d = cat_types_number_as_double(v);
return;
}
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;
}
slot->i = 0;
}
static int function_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_FFI_Function *f = (CAT_TYPES_FFI_Function *)self;
ffi_slot slots[16];
void *aptr[16];
ffi_slot ret;
int base = 0; /* args[0] is the receiver when sent with ':' */
int n = nargs - base;
int i;
if (n > 16)
return (cat_error_raise(err, "ffi: too many arguments"), -1);
if (n != f->nargs)
return (cat_error_raise(err,
"ffi: %s expects %d args, got %d", f->name, f->nargs, n), -1);
for (i = 0; i < n; i++) {
arg_to_slot(args[base + i], ((ffi_type **)f->argtypes)[i], &slots[i]);
aptr[i] = &slots[i];
}
memset(&ret, 0, sizeof(ret));
ffi_call((ffi_cif *)f->cif, FFI_FN(f->sym), &ret, aptr);
switch (f->ret_kind) {
case CAT_TYPES_FFI_RET_VOID:
*out = cat_types_nil_get();
break;
case CAT_TYPES_FFI_RET_DOUBLE:
*out = cat_types_float_new(ret.d);
break;
case CAT_TYPES_FFI_RET_STRING:
*out = cat_types_ascii_text_new(ret.s ? ret.s : "");
break;
default:
*out = cat_types_int_new(ret.i);
break;
}
return 0;
}
static CAT_VALUE_Vtable g_function_vtable = {
.type_name = "ffi.Function",
.kind = CAT_VALUE_KIND_FUNCTION,
.call = { function_call },
.destroy = function_destroy,
};
CAT_VALUE_Vtable *cat_types_ffi_function_vtable(void)
{
return &g_function_vtable;
}
/* ---- the Library value ---------------------------------------------- */
/* lib:func(name, sig) -- the explicit form that carries the signature. */
static int lib_method_func(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_VALUE_Value *lib = nargs >= 1 ? args[0] : NULL;
const char *name = (nargs >= 2) ? cat_types_text_bytes(args[1]) : NULL;
const char *sig = (nargs >= 3) ? cat_types_text_bytes(args[2]) : NULL;
(void)vm;
*out = cat_types_ffi_bind(lib, name, sig);
return 0;
}
static int library_get_attr_full(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (strcmp(name, "func") == 0) {
*out = cat_types_native_new("func", lib_method_func);
return 0;
}
return (cat_error_raise(err, "ffi.Library has no '%s'", name), -1);
}
static int library_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
/* Calling a library directly: lib("name", "sig") == lib:func(...) */
CAT_VALUE_Value *callargs[4];
callargs[0] = self;
callargs[1] = nargs >= 1 ? args[0] : cat_types_nil_get();
callargs[2] = nargs >= 2 ? args[1] : cat_types_nil_get();
callargs[3] = cat_types_nil_get();
return lib_method_func(NULL, callargs, 3, out);
}
static void library_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FFI_Library *l = (CAT_TYPES_FFI_Library *)self;
if (l->handle != NULL)
dlclose(l->handle);
free(l->path);
free(l);
}
static CAT_VALUE_Vtable g_library_vtable = {
.type_name = "ffi.Library",
.kind = CAT_VALUE_KIND_TABLE,
.call = { library_call },
.get_attribute = { library_get_attr_full },
.destroy = library_destroy,
};
CAT_VALUE_Vtable *cat_types_ffi_library_vtable(void)
{
return &g_library_vtable;
}
/* ---- constructors --------------------------------------------------- */
CAT_VALUE_Value *cat_types_ffi_load(const char *path)
{
CAT_TYPES_FFI_Library *l;
void *h;
if (path == NULL)
return cat_types_nil_get();
h = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
if (h == NULL)
return cat_types_nil_get();
l = calloc(1, sizeof(*l));
if (l == NULL) {
dlclose(h);
return cat_types_nil_get();
}
l->base.vtable = &g_library_vtable;
l->handle = h;
l->path = strdup(path);
return &l->base;
}
CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name,
const char *sig)
{
CAT_TYPES_FFI_Library *l;
CAT_TYPES_FFI_Function *f;
void *sym;
if (lib == NULL || lib->vtable != &g_library_vtable || name == NULL)
return cat_types_nil_get();
l = (CAT_TYPES_FFI_Library *)lib;
sym = dlsym(l->handle, name);
if (sym == NULL)
return cat_types_nil_get();
f = calloc(1, sizeof(*f));
if (f == NULL)
return cat_types_nil_get();
f->base.vtable = &g_function_vtable;
f->sym = sym;
f->name = strdup(name);
f->sig = sig ? strdup(sig) : NULL;
if (prepare(f, sig) != 0) {
function_destroy(&f->base);
return cat_types_nil_get();
}
return &f->base;
}
/* `ffi.load(path)` module function. */
static int ffi_load_native(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
(void)vm;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
*out = cat_types_ffi_load(cat_types_text_bytes(args[0]));
return 0;
}
CAT_VALUE_Value *cat_types_ffi_module(void)
{
CAT_VALUE_Value *m = cat_types_table_new();
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(m, "load",
cat_types_native_new("load", ffi_load_native), &e);
return m;
}
+123
View File
@@ -0,0 +1,123 @@
/*
* cat/types/selector.c -- default selector implementations.
*
* Naming rule: symbols here are cat_types_selector_* / CAT_TYPES_SELECTOR_*.
*
* Each selector is a bound default method. When a program sends
* `obj:_dot_(k)` and the object does not define `_dot_`, the attribute
* dispatcher hands back one of these instead, and calling it performs the
* raw built-in access. This is what lets the compiler drop the special
* GETATTR/SETATTR/GETIDX/SETIDX/CALL cases: they are all just `:` sends.
*/
#include "cat/types/selector.h"
#include "cat/types/text.h"
#include "cat/types/number.h"
#include "cat/types/nil.h"
#include "cat/types/table.h"
#include "cat/error.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Turn a key/index value into the string an object stores it under. */
static void sel_key(CAT_VALUE_Value *v, char *buf, size_t n)
{
if (v == NULL) {
buf[0] = '\0';
return;
}
if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER)
snprintf(buf, n, "%lld", cat_types_number_as_int(v));
else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT)
snprintf(buf, n, "%s", cat_types_text_bytes(v));
else
buf[0] = '\0';
}
/* A selector is called as `receiver:_sel_(...)`, so args[0] is the
* receiver and args[1..] are the selector's own arguments. */
static int selector_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_SELECTOR_Selector *s = (CAT_TYPES_SELECTOR_Selector *)self;
CAT_VALUE_Value *rx = (nargs >= 1) ? args[0] : NULL;
char key[64];
switch (s->kind) {
case CAT_TYPES_SELECTOR_DOT: /* _dot_(key) */
sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key));
return cat_value_get_attribute(rx, key, out, err);
case CAT_TYPES_SELECTOR_DOT_SET: /* _dot_set_(key, value) */
sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key));
cat_value_set_attribute(rx, key, nargs >= 3 ? args[2] : NULL, err);
*out = nargs >= 3 ? args[2] : cat_types_nil_get();
return 0;
case CAT_TYPES_SELECTOR_SQ: /* _squarebrackets_(idx) */
sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key));
return cat_value_get_attribute(rx, key, out, err);
case CAT_TYPES_SELECTOR_SQ_SET: /* _squarebrackets_set_(idx, value) */
sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key));
cat_value_set_attribute(rx, key, nargs >= 3 ? args[2] : NULL, err);
*out = nargs >= 3 ? args[2] : cat_types_nil_get();
return 0;
case CAT_TYPES_SELECTOR_PAREN: /* _parenthesis_(args...) */
return cat_value_call(rx, nargs >= 1 ? &args[1] : args,
nargs >= 1 ? nargs - 1 : 0, out, err);
case CAT_TYPES_SELECTOR_CURLY: /* _curlybrackets_() */
*out = cat_types_table_new();
return 0;
default:
return (cat_error_raise(err, "unknown selector"), -1);
}
}
static CAT_VALUE_Vtable g_selector_vtable = {
.type_name = "selector",
.kind = CAT_VALUE_KIND_FUNCTION,
.call = { selector_call },
};
CAT_VALUE_Vtable *cat_types_selector_vtable(void)
{
return &g_selector_vtable;
}
/* Static singletons: one per selector kind (no per-lookup allocation). */
static CAT_TYPES_SELECTOR_Selector g_sel[] = {
{ { NULL }, CAT_TYPES_SELECTOR_DOT },
{ { NULL }, CAT_TYPES_SELECTOR_DOT_SET },
{ { NULL }, CAT_TYPES_SELECTOR_SQ },
{ { NULL }, CAT_TYPES_SELECTOR_SQ_SET },
{ { NULL }, CAT_TYPES_SELECTOR_PAREN },
{ { NULL }, CAT_TYPES_SELECTOR_CURLY },
};
CAT_VALUE_Value *cat_types_selector_lookup(const char *name)
{
int i;
char key[64];
if (name == NULL)
return NULL;
/* accept both `_dot_` and `.` spellings of a selector */
for (i = 0; i < (int)(sizeof(g_sel) / sizeof(g_sel[0])); i++) {
if (g_sel[i].base.vtable == NULL)
g_sel[i].base.vtable = &g_selector_vtable;
}
strncpy(key, name, sizeof(key) - 1);
key[sizeof(key) - 1] = '\0';
if (strcmp(key, "_dot_") == 0 || strcmp(key, ".") == 0)
return &g_sel[0].base;
if (strcmp(key, "_dot_set_") == 0)
return &g_sel[1].base;
if (strcmp(key, "_squarebrackets_") == 0 || strcmp(key, "[]") == 0)
return &g_sel[2].base;
if (strcmp(key, "_squarebrackets_set_") == 0)
return &g_sel[3].base;
if (strcmp(key, "_parenthesis_") == 0 || strcmp(key, "()") == 0)
return &g_sel[4].base;
if (strcmp(key, "_curlybrackets_") == 0 || strcmp(key, "{}") == 0)
return &g_sel[5].base;
return NULL;
}
+12
View File
@@ -6,6 +6,7 @@
#include "cat/types/table.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/selector.h"
#include <stdlib.h>
#include <string.h>
@@ -27,6 +28,17 @@ static int table_get_attribute(CAT_VALUE_Value *self, const char *name,
if (cat_types_table_get(self, "__index", &base, &local) == 0 &&
base != NULL && base != self)
return cat_value_get_attribute(base, name, out, err);
/* Selector fallback: () [] . {} are not special operators, they are
* sends to well-known selector names. An object that does not define
* one still works because the dispatcher hands back the default
* implementation of that selector here. */
{
CAT_VALUE_Value *sel = cat_types_selector_lookup(name);
if (sel != NULL) {
*out = sel;
return 0;
}
}
return (cat_error_raise(err, "table has no key '%s'", name), -1);
}