yallop / ocaml-ctypes

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

Size and align of `size_t` and pointer based on `Sys.word_size` #753

Closed benozol closed 9 months ago

benozol commented 10 months ago

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).

This PR uses Sys.word_size / 8 for the size and align of size_t and pointers, which resolves the issue (the program runs as bytecode and as Wasm).

My questions are 1) if this is valid for all supported platforms and 2) if ctypes_primitives.h requires corresponding modifications.

yallop commented 9 months ago

Is there something special about size_t that means it should be treated differently to other integer types? int, long, etc., can vary in size from platform to platform, too.

In any case, I think we should retrieve the size of these types from the C implementation, not use OCaml's Sys.word_size.

benozol commented 9 months ago

Agreed, I didn't realize just how few assumptions can be made about the bit-sizes of most C types.

I am going to close this PR and open an issue to continue the discussion.