yallop / ocaml-ctypes

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

Memory errors on Wasm32 due to wrong pointer size #755

Open benozol opened 9 months ago

benozol commented 9 months ago

(follow up to https://github.com/yallop/ocaml-ctypes/pull/753)

Executing a program that uses ocaml-ctypes on a platform where the word size differs from the word size of the platform where the program was originally compiled results in memory errors due to the wrong pointer arithmetic. We ran into this issue after first compiling an OCaml program on a 64-bit platform to OCaml bytecode and then compiling the OCaml bytecode to 32-bit WebAssembly (in our case using wasicaml, but the same issue is expected using wasm_of_ocaml).

In #753 we experimented with deriving sizes and alignments of pointers (and size_t) from Sys.word_size, but this isn't enough in general (the size of other C types might differ too, also depending on the compiler).

benozol commented 9 months ago

Retrieving the sizes from the C implementation is problematic for Wasm, because gen_c_primitives won't run as is on Wasm (and even a simplified form would require a Wasm toolchain to compile the library). One alternative might be to pre-define sizes and alignments for specific, non-native platforms (like Wasm32), and select that at runtime (e.g. using an environment variable CTYPES_PLATFORM=WASM32).