rust-lang / rfcs

RFCs for changes to Rust
https://rust-lang.github.io/rfcs/
Apache License 2.0
5.9k stars 1.57k forks source link

RawOs marker traits #1256

Open Stebalien opened 9 years ago

Stebalien commented 9 years ago

Currently, the {As,From}Raw{Fd,Handle} traits don't provide any information about how the file descriptors might safely be used (and don't even guarantee that the file descriptor is valid). Therefore, I would like to propose traits like:

/// Can safely write
unsafe trait RawOsWrite {}
/// Can safely read
unsafe trait RawOsRead {}
/// Can safely seek
unsafe trait RawOsSeek {}
/// Can safely access metadata. May not be necessary (always safe)?
unsafe trait RawOsMeta {}

These traits, when implemented on a type implementing one of the AsRaw/IntoRaw traits, would guarantee that the specified operation can be performed on the file descriptor/handle without causing memory unsafety. This doesn't mean that the operation will succeed, just that it won't be unsafe.

Unresolved: For AsRaw*, it's unclear when this guarantee expires. Personally, I'd like to say that the guarantee holds until the file descriptor owner is dropped but I don't know if that's reasonable.

Diggsey commented 9 years ago

I like this idea, but might not the guarantees be more subtle than these traits would be able to express? For example, safety might depend on certain runtime state, such as how the file was opened, whether a buffer has been flushed, or even whether the access is concurrent or not.

Stebalien commented 9 years ago

For example, safety might depend on certain runtime state, such as how the file was opened, whether a buffer has been flushed, or even whether the access is concurrent or not.

That's why I said "memory safe" operations (or, more conservatively, operations that will not break type safety). How a file is opened is irrelevant because, if a file is opened read-only, writing to it will fail (but won't cause memory unsafety). A buffered reader/writer should probably only implement RawOsMeta, if anything.

sfackler commented 9 years ago

What memory safety issues would arise from writing or reading directly to the underlying file descriptor inside of a buffered reader or writer?

Stebalien commented 9 years ago

What memory safety issues would arise from writing or reading directly to the underlying file descriptor inside of a buffered reader or writer?

The problem isn't first-order bugs but second-order bugs. Type A fails to behave properly but isn't "memory unsafe". Type B uses type A in some unsafe code expecting it to conform to some specification and it doesn't leading to memory unsafety. That's why I prefer "operations that will not break type safety/guarantees" over "memory safety".

For example, I've been wanting to implement a more efficient IO copy function that uses sendfile. Out of order writes (due to buffering) to a trusted/private file could lead to memory unsafety on read.