Why don't the AsRaw{Fd, Handle, Socket} traits require a mutable receiver?

Allowing an extraction of the underlying OS representation from an immutable reference seems like a violation of Rust’s mutability rules.

For example, consider giving an immutable reference to a std::fs::File handle so that it can extract some metadata or get the path to the file (both do not require a mutable reference). That code, however, can use libc::write on the raw fd/handle and mutate the file even though the caller may not intend extending that ability.

Are there any use cases that require access to the underlying fd/handle via immutable handle? I didn’t find much in the compiler/stdlibs but do any external libraries depend on this?

If there aren’t any explicit use cases, perhaps these traits should be changed to require a mutable receiver which would better reflect the implications of using them.

It doesn’t because file descriptors are just numbers. If you actually want to do anything based on a file descriptor, you need to do so from within an unsafe block so ensuring memory safety becomes your problem. Even wrapping the File in a tuple struct won’t prevent a user from accessing the underlying file descriptor because they can just use mem::transmute to get the File out.

The FromRawFd trait, however, should probably be marked unsafe (because it violates the above).

Even wrapping the File in a tuple struct won't prevent a user from accessing the underlying file descriptor because they can just use mem::transmute to get the File out.

I was thinking along the lines of requiring a mutable receiver would prevent someone else from messing with the internals (even if they opt into the unsafety), but I suppose mem::transmute still allows an escape hatch from that.

EDIT: Actually the current implementation of std::fs::File isn't just a simple wrapper over a file descriptor/handle, so mem::transmute won't actually work for extracting the fd/handle

What if they're trying to get the fd in order to query state rather than mutate it? There's no reason why I should require a mutable File in order to e.g. call fcntl() with F_GETPATH on the underlying fd.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.