nix icon indicating copy to clipboard operation
nix copied to clipboard

Wrong type for return value of mmap leads to UB

Open Evian-Zhang opened this issue 1 year ago • 4 comments
trafficstars

From the VERSIONS section in mmap man page:

If the MAP_FIXED flag is specified, and addr is 0 (NULL), then the mapped address will be 0 (NULL).

In this case, the kernel does allocate the requested memory at zero address (and dereferencing the NULL pointer will be OK since then). However, the return type of mmap and mmap_anonymous is designed as NonNull, which will then become UB for evident reasons.

The documentation of such functions refers SAFATY as to "See the mmap(2) man page for detailed requirements", while such man page does not impose any safety requirements on the above case.

So there are two ways to solve this:

  • Change the return type of mmap and mmap_anonymous from NonNull<c_void> to usize (we cannot use *mut c_void since Rust requires pointers to be non-null), which would however lose the provenance.
  • Add documentation to mmap and mmap_anonymous to add the above usage as a UB.

Evian-Zhang avatar Nov 19 '24 00:11 Evian-Zhang