I'm looking at the FromRawFd trait. The method there is unsafe, with a vague explanation that violation of contract to be the sole owner of the file descriptor might trigger memory unsafety:
This function is also unsafe as the primitives currently returned have the contract that they are the sole owner of the file descriptor they are wrapping. Usage of this function could accidentally allow violating this contract which can cause memory unsafety in code that relies on it being true.
However, I can't think of an example where this would happen ‒ if I violate this for eg. a
File, then the same fd can get closed multiple times, due to recycling it after being closed it could close something really unrelated, which is bad, but would still result in
EBADFD returned all over the place, not UB.
The only thing I could find was this really old issue: https://github.com/rust-lang/rfcs/issues/1043. Nevertheless, if I could cause the UB by writing invalid data to the file, I can get to that by opening the same file again, or by using
try_clone on the file.
Does anyone know of an actual problem this might trigger? Should the unsafety be described better? If there's an actual problem, is the write in nix unsound?
The reason why I ask is, I have a function in my library that takes ownership of a raw file descriptor, writes there and eventually closes it. In that regard, it is really similar to this trait and I wonder if it should be unsafe for the same reasons ‒ but I'm not sure if any actual ones exist, or if it is unsafe simply to allow a hypothetical type to rely on the fact it is the sole owner for its own internal data structures.
Thank you for advice and historical links for further my archeological research.