Skip to content

File instance dropped before leaving scope #54494

Closed
@RandomInsano

Description

@RandomInsano

This is tested on 1.26.0-nightly, but may affect other versions.

I found that if I don't let the File instance returned from OpenOptions::open() the File object is drop()ed and the handle is closed before we go out of scope.

#[macro_use]
extern crate nix;
use std::fs::OpenOptions;
use std::os::unix::io::AsRawFd;

const I2C_SLAVE: u16 = 0x0703;
 
ioctl_write_int_bad!(set_i2c_slave_address, I2C_SLAVE);
 
fn main() {
    println!("Let's try some i2c");
    let file_result = OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/i2c-0");
 
    assert!(file_result.is_ok());
 
    let fd = file_result.unwrap().as_raw_fd();
    println!("File descriptor: {}", fd);
 
    unsafe {
        set_i2c_slave_address(fd, 0x34).unwrap();
    }
}

Here's the strace for the above:

open("/dev/i2c-0", O_RDWR|O_LARGEFILE|O_CLOEXEC) = 3
ioctl(3, FIOCLEX)                       = 0
close(3)                                = 0
write(1, "File descriptor: 3\n", 19File descriptor: 3
)    = 19
ioctl(3, 0x703, 0x34)                   = -1 EBADF (Bad file descriptor)

Should objects be dropped before the scope ends if they aren't used? While it makes a certain amount of sense, this was a hard paper cut for me doing some low-level work.

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