Skip to content

Commit a0e7bce

Browse files
committed
Fix Fd::as_raw_fd_or_null_fd: Avoid breaking invariant of Pipe*
Signed-off-by: Jiahao XU <[email protected]>
1 parent 5651daf commit a0e7bce

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/native_mux_impl/stdio.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{stdio::StdioImpl, Error, Stdio};
33
use std::{
44
fs::{File, OpenOptions},
55
io,
6-
os::unix::io::{AsRawFd, RawFd},
6+
os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd},
77
};
88

99
use libc::{c_int, fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
@@ -29,9 +29,7 @@ fn get_null_fd() -> Result<RawFd, Error> {
2929
}
3030

3131
pub(crate) enum Fd {
32-
PipeReadEnd(PipeRead),
33-
PipeWriteEnd(PipeWrite),
34-
32+
Owned(OwnedFd),
3533
Borrowed(RawFd),
3634
Null,
3735
}
@@ -56,9 +54,7 @@ impl Fd {
5654
use Fd::*;
5755

5856
let fd = match self {
59-
PipeReadEnd(fd) => Some(AsRawFd::as_raw_fd(fd)),
60-
PipeWriteEnd(fd) => Some(AsRawFd::as_raw_fd(fd)),
61-
57+
Owned(owned_fd) => Some(owned_fd.as_raw_fd()),
6258
Borrowed(rawfd) => Some(*rawfd),
6359
Null => None,
6460
};
@@ -71,6 +67,12 @@ impl Fd {
7167
get_null_fd()
7268
}
7369
}
70+
71+
fn new_owned<T: IntoRawFd>(fd: T) -> Self {
72+
let raw_fd = fd.into_raw_fd();
73+
// Safety: IntoRawFd::into_raw_fd must return a valid raw fd.
74+
unsafe { Fd::Owned(OwnedFd::from_raw_fd(raw_fd)) }
75+
}
7476
}
7577

7678
impl Stdio {
@@ -80,7 +82,7 @@ impl Stdio {
8082
StdioImpl::Null => Ok((Fd::Null, None)),
8183
StdioImpl::Pipe => {
8284
let (read, write) = create_pipe()?;
83-
Ok((Fd::PipeReadEnd(read), Some(write)))
85+
Ok((Fd::new_owned(read), Some(write)))
8486
}
8587
StdioImpl::Fd(fd) => Ok((Fd::Borrowed(fd.as_raw_fd()), None)),
8688
}
@@ -92,7 +94,7 @@ impl Stdio {
9294
StdioImpl::Null => Ok((Fd::Null, None)),
9395
StdioImpl::Pipe => {
9496
let (read, write) = create_pipe()?;
95-
Ok((Fd::PipeWriteEnd(write), Some(read)))
97+
Ok((Fd::new_owned(write), Some(read)))
9698
}
9799
StdioImpl::Fd(fd) => Ok((Fd::Borrowed(fd.as_raw_fd()), None)),
98100
}

0 commit comments

Comments
 (0)