yallop / ocaml-ctypes

Library for binding to C libraries using pure OCaml
MIT License
363 stars 95 forks source link

Select ctypes primitives at runtime #757

Open benozol opened 8 months ago

benozol commented 8 months ago

(Follow-up to #753)

Executing a program that uses ocaml-ctypes on a different platform from where the OCaml code was compiled can result in memory errors due to the wrong pointer arithmetic. For example, when a program is compiled on a 64-bit machine to OCaml bytecode and the bytecode is then compiled to 32-bit WebAssembly code, the execution of the Wasm program fails because ocaml-types uses 64-bit pointer arithmetic on a 32-bit architecture.

This PR makes the C data model selectable during compilation or runtime using an environment variable, i.e., CTYPES_DATA_MODEL=ILP32 to execute a program on 32-bit WebAssembly.

I can add other data models to this PR, but compiling OCaml bytecode to Wasm32 is I think the only way to trigger the failure, and Wasm32 uses ILP32.