flan/spike/embed/stubs_ml.ml
Joseph Ferano d272a5b1e5 Six probes for whether the OCaml compiler can live in the game's process
Item 12 asks five questions and says to answer them with a spike rather than a
rewrite. spike/embed/ is that spike: one script, six binaries, each one built to
fail loudly at the thing it is asking about. It is deliberately not a dune
target -- the root dune only excludes old-ocaml/, so a dune file here would land
in @default and make the spike part of the build. It drives ocamlfind and clang
by hand against the flan.cmxa dune already produces.

The probes, in the order they would kill the idea: the smallest possible link, a
C main() reaching one OCaml function; the whole compiler linked in and doing
real work; the same again with lib/dynload_stubs.c from the unmerged dlopen
branch, because that is the only C the compiler itself is built from; the game
keeping the main thread while caml_startup happens on a pthread beside it; the
SIGSEGV disposition read on both sides of caml_startup; and an 8 MiB arena
checked byte for byte across a compaction.

No result is written down yet. This is the apparatus.
2026-09-12 20:27:45 +07:00

27 lines
1.2 KiB
OCaml

(* Step 3: the project's own C stubs, in the same link as the compiler.
lib/dynload_stubs.c is taken verbatim from 9e0ae3a (the unmerged dlopen
branch) -- it is the only C the compiler itself is built from, and it is the
case that -output-complete-obj has to carry through. *)
external dl_open : string -> nativeint = "flan_dl_open"
external dl_sym : nativeint -> string -> nativeint = "flan_dl_sym"
external mem_alloc : int -> nativeint = "flan_mem_alloc"
external mem_free : nativeint -> unit = "flan_mem_free"
external poke_i64 : nativeint -> int -> int64 -> unit = "flan_poke_i64"
external peek_i64 : nativeint -> int -> int64 = "flan_peek_i64"
let () =
Callback.register "spike_stubs" (fun () ->
(* peek/poke: the raw memory the marshaller lays a Form image out in. *)
let p = mem_alloc 64 in
poke_i64 p 8 0xfeedfacedeadbeefL;
let got = peek_i64 p 8 in
mem_free p;
(* dlopen from inside the embedded runtime, on the process's own image. *)
let h = dl_open "libm.so.6" in
let s = dl_sym h "sqrt" in
Printf.sprintf "peek/poke %s; dlopen+dlsym %s"
(if got = 0xfeedfacedeadbeefL then "ok" else "WRONG")
(if s <> 0n then "ok" else "WRONG"));
ignore dl_open