Skip to content

I/O safety of unistd::close taking IntoRawFd #2707

@hanna-kruppe

Description

@hanna-kruppe

PR #2495 marked unistd::close as safe. I don't think that's sound w.r.t. I/O safety since it accepts any T: IntoRawFd including T = RawFd = c_int. The I/O safety documentation explicitly says:

To uphold I/O safety, it is crucial that no code acts on file descriptors it does not own or borrow, and no code closes file descriptors it does not own. In other words, a safe function that takes a regular integer, treats it as a file descriptor, and acts on it, is unsound.

... and that's exactly what unistd::close allows by accepting any T: IntoRawFd. For example, the following program compiles and runs (producing no output since stdout is closed prematurely) without any unsafe:

use nix; // version 0.30.1

fn main() {
    let _ = nix::unistd::close(1);
    println!("Hello, world!");
}

I'm no expert on this but I think the options here are:

  1. Keep T: IntoRawFd but make the function unsafe again, or
  2. Accept T: Into<OwnedFd> and require callers who only have a RawFd or the like to unsafely assert ownership by other means. (Questionably useful for callers who already have an OwnedFd, as the documentation notes.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions