Debian Codegraph @

debian/rust-vendor/filedescriptor/src/unix.rs

raw
1 use crate::{
2 AsRawFileDescriptor, AsRawSocketDescriptor, Error, FileDescriptor, FromRawFileDescriptor,
3 FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe,
4 Result, StdioDescriptor,
5 };
6 use std::os::unix::prelude::*;
7
8 pub(crate) type HandleType = ();
9
10 /// `RawFileDescriptor` is a platform independent type alias for the
11 /// underlying platform file descriptor type. It is primarily useful
12 /// for avoiding using `cfg` blocks in platform independent code.
13 pub type RawFileDescriptor = RawFd;
14
15 /// `SocketDescriptor` is a platform independent type alias for the
16 /// underlying platform socket descriptor type. It is primarily useful
17 /// for avoiding using `cfg` blocks in platform independent code.
18 pub type SocketDescriptor = RawFd;
19
20 impl<T: AsRawFd> AsRawFileDescriptor for T {
21 fn as_raw_file_descriptor(&self) -> RawFileDescriptor {
22 self.as_raw_fd()
23 }
24 }
25
26 impl<T: IntoRawFd> IntoRawFileDescriptor for T {
27 fn into_raw_file_descriptor(self) -> RawFileDescriptor {
28 self.into_raw_fd()
29 }
30 }
31
32 impl<T: FromRawFd> FromRawFileDescriptor for T {
33 unsafe fn from_raw_file_descriptor(fd: RawFileDescriptor) -> Self {
34 Self::from_raw_fd(fd)
35 }
36 }
37
38 impl<T: AsRawFd> AsRawSocketDescriptor for T {
39 fn as_socket_descriptor(&self) -> SocketDescriptor {
40 self.as_raw_fd()
41 }
42 }
43
44 impl<T: IntoRawFd> IntoRawSocketDescriptor for T {
45 fn into_socket_descriptor(self) -> SocketDescriptor {
46 self.into_raw_fd()
47 }
48 }
49
50 impl<T: FromRawFd> FromRawSocketDescriptor for T {
51 unsafe fn from_socket_descriptor(fd: SocketDescriptor) -> Self {
52 Self::from_raw_fd(fd)
53 }
54 }
55
56 impl Drop for OwnedHandle {
57 fn drop(&mut self) {
58 unsafe {
59 libc::close(self.handle);
60 }
61 }
62 }
63
64 impl std::os::fd::AsFd for OwnedHandle {
65 fn as_fd(&self) -> std::os::fd::BorrowedFd {
66 unsafe { std::os::fd::BorrowedFd::borrow_raw(self.handle) }
67 }
68 }
69
70 impl AsRawFd for OwnedHandle {
71 fn as_raw_fd(&self) -> RawFd {
72 self.handle
73 }
74 }
75
76 impl IntoRawFd for OwnedHandle {
77 fn into_raw_fd(self) -> RawFd {
78 let fd = self.handle;
79 std::mem::forget(self);
80 fd
81 }
82 }
83
84 impl FromRawFd for OwnedHandle {
85 unsafe fn from_raw_fd(fd: RawFd) -> Self {
86 Self {
87 handle: fd,
88 handle_type: (),
89 }
90 }
91 }
92
93 impl OwnedHandle {
94 /// Helper function to set the close-on-exec flag for a raw descriptor
95 fn cloexec(&mut self) -> Result<()> {
96 let flags = unsafe { libc::fcntl(self.handle, libc::F_GETFD) };
97 if flags == -1 {
98 return Err(Error::Fcntl(std::io::Error::last_os_error()));
99 }
100 let result = unsafe { libc::fcntl(self.handle, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
101 if result == -1 {
102 Err(Error::Cloexec(std::io::Error::last_os_error()))
103 } else {
104 Ok(())
105 }
106 }
107
108 fn non_atomic_dup(fd: RawFd) -> Result<Self> {
109 let duped = unsafe { libc::dup(fd) };
110 if duped == -1 {
111 Err(Error::Dup {
112 fd: fd.into(),
113 source: std::io::Error::last_os_error(),
114 })
115 } else {
116 let mut owned = OwnedHandle {
117 handle: duped,
118 handle_type: (),
119 };
120 owned.cloexec()?;
121 Ok(owned)
122 }
123 }
124
125 fn non_atomic_dup2(fd: RawFd, dest_fd: RawFd) -> Result<Self> {
126 let duped = unsafe { libc::dup2(fd, dest_fd) };
127 if duped == -1 {
128 Err(Error::Dup2 {
129 src_fd: fd.into(),
130 dest_fd: dest_fd.into(),
131 source: std::io::Error::last_os_error(),
132 })
133 } else {
134 let mut owned = OwnedHandle {
135 handle: duped,
136 handle_type: (),
137 };
138 owned.cloexec()?;
139 Ok(owned)
140 }
141 }
142
143 #[inline]
144 pub(crate) fn dup_impl<F: AsRawFileDescriptor>(
145 fd: &F,
146 handle_type: HandleType,
147 ) -> Result<Self> {
148 let fd = fd.as_raw_file_descriptor();
149 let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
150 if duped == -1 {
151 let err = std::io::Error::last_os_error();
152 if let Some(libc::EINVAL) = err.raw_os_error() {
153 // We may be running on eg: WSL or an old kernel that
154 // doesn't support F_DUPFD_CLOEXEC; fall back.
155 Self::non_atomic_dup(fd)
156 } else {
157 Err(Error::Dup {
158 fd: fd.into(),
159 source: err,
160 })
161 }
162 } else {
163 Ok(OwnedHandle {
164 handle: duped,
165 handle_type,
166 })
167 }
168 }
169
170 #[inline]
171 pub(crate) unsafe fn dup2_impl<F: AsRawFileDescriptor>(fd: &F, dest_fd: RawFd) -> Result<Self> {
172 let fd = fd.as_raw_file_descriptor();
173
174 #[cfg(not(target_os = "linux"))]
175 return Self::non_atomic_dup2(fd, dest_fd);
176
177 #[cfg(target_os = "linux")]
178 {
179 let duped = libc::dup3(fd, dest_fd, libc::O_CLOEXEC);
180
181 if duped == -1 {
182 let err = std::io::Error::last_os_error();
183 if let Some(libc::EINVAL) = err.raw_os_error() {
184 // We may be running on eg: WSL or an old kernel that
185 // doesn't support O_CLOEXEC; fall back.
186 Self::non_atomic_dup2(fd, dest_fd)
187 } else {
188 Err(Error::Dup2 {
189 src_fd: fd.into(),
190 dest_fd: dest_fd.into(),
191 source: err,
192 })
193 }
194 } else {
195 Ok(OwnedHandle {
196 handle: duped,
197 handle_type: (),
198 })
199 }
200 }
201 }
202
203 pub(crate) fn probe_handle_type(_handle: RawFileDescriptor) -> HandleType {
204 ()
205 }
206 }
207
208 impl std::io::Read for FileDescriptor {
209 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
210 let size = unsafe { libc::read(self.handle.handle, buf.as_mut_ptr() as *mut _, buf.len()) };
211 if size == -1 {
212 Err(std::io::Error::last_os_error())
213 } else {
214 Ok(size as usize)
215 }
216 }
217 }
218
219 impl std::io::Write for FileDescriptor {
220 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
221 let size = unsafe { libc::write(self.handle.handle, buf.as_ptr() as *const _, buf.len()) };
222 if size == -1 {
223 Err(std::io::Error::last_os_error())
224 } else {
225 Ok(size as usize)
226 }
227 }
228 fn flush(&mut self) -> std::io::Result<()> {
229 Ok(())
230 }
231 }
232
233 impl std::os::fd::AsFd for FileDescriptor {
234 fn as_fd(&self) -> std::os::fd::BorrowedFd {
235 self.handle.as_fd()
236 }
237 }
238
239 impl AsRawFd for FileDescriptor {
240 fn as_raw_fd(&self) -> RawFd {
241 self.handle.as_raw_fd()
242 }
243 }
244
245 impl IntoRawFd for FileDescriptor {
246 fn into_raw_fd(self) -> RawFd {
247 self.handle.into_raw_fd()
248 }
249 }
250
251 impl FromRawFd for FileDescriptor {
252 unsafe fn from_raw_fd(fd: RawFd) -> Self {
253 Self {
254 handle: OwnedHandle::from_raw_fd(fd),
255 }
256 }
257 }
258
259 impl FileDescriptor {
260 #[inline]
261 pub(crate) fn as_stdio_impl(&self) -> Result<std::process::Stdio> {
262 let duped = OwnedHandle::dup(self)?;
263 let fd = duped.into_raw_fd();
264 let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) };
265 Ok(stdio)
266 }
267
268 #[inline]
269 pub(crate) fn as_file_impl(&self) -> Result<std::fs::File> {
270 let duped = OwnedHandle::dup(self)?;
271 let fd = duped.into_raw_fd();
272 let stdio = unsafe { std::fs::File::from_raw_fd(fd) };
273 Ok(stdio)
274 }
275
276 #[inline]
277 pub(crate) fn set_non_blocking_impl(&mut self, non_blocking: bool) -> Result<()> {
278 let on = if non_blocking { 1 } else { 0 };
279 let res = unsafe { libc::ioctl(self.handle.as_raw_file_descriptor(), libc::FIONBIO, &on) };
280 if res != 0 {
281 Err(Error::FionBio(std::io::Error::last_os_error()))
282 } else {
283 Ok(())
284 }
285 }
286
287 /// Attempt to duplicate the underlying handle from an object that is
288 /// representable as the system `RawFileDescriptor` type and assign it to
289 /// a destination file descriptor. It then returns a `FileDescriptor`
290 /// wrapped around the duplicate. Since the duplication requires kernel
291 /// resources that may not be available, this is a potentially fallible operation.
292 /// The returned handle has a separate lifetime from the source, but
293 /// references the same object at the kernel level.
294 pub unsafe fn dup2<F: AsRawFileDescriptor>(f: &F, dest_fd: RawFd) -> Result<Self> {
295 OwnedHandle::dup2_impl(f, dest_fd).map(|handle| Self { handle })
296 }
297
298 /// Helper function to unset the close-on-exec flag for a raw descriptor
299 fn no_cloexec(fd: RawFd) -> Result<()> {
300 let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
301 if flags == -1 {
302 return Err(Error::Fcntl(std::io::Error::last_os_error()));
303 }
304 let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) };
305 if result == -1 {
306 Err(Error::Cloexec(std::io::Error::last_os_error()))
307 } else {
308 Ok(())
309 }
310 }
311
312 pub(crate) fn redirect_stdio_impl<F: AsRawFileDescriptor>(
313 f: &F,
314 stdio: StdioDescriptor,
315 ) -> Result<Self> {
316 let std_descriptor = match stdio {
317 StdioDescriptor::Stdin => libc::STDIN_FILENO,
318 StdioDescriptor::Stdout => libc::STDOUT_FILENO,
319 StdioDescriptor::Stderr => libc::STDERR_FILENO,
320 };
321
322 let std_original = FileDescriptor::dup(&std_descriptor)?;
323 // Assign f into std_descriptor, then convert to an fd so that
324 // we don't close it when the returned FileDescriptor is dropped.
325 // Then we discard/ignore the fd because it is nominally owned by
326 // the stdio machinery for the process
327 let _ = unsafe { FileDescriptor::dup2(f, std_descriptor) }?.into_raw_fd();
328 Self::no_cloexec(std_descriptor)?;
329
330 Ok(std_original)
331 }
332 }
333
334 impl Pipe {
335 #[cfg(target_os = "linux")]
336 pub fn new() -> Result<Pipe> {
337 let mut fds = [-1i32; 2];
338 let res = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
339 if res == -1 {
340 Err(Error::Pipe(std::io::Error::last_os_error()))
341 } else {
342 let read = FileDescriptor {
343 handle: OwnedHandle {
344 handle: fds[0],
345 handle_type: (),
346 },
347 };
348 let write = FileDescriptor {
349 handle: OwnedHandle {
350 handle: fds[1],
351 handle_type: (),
352 },
353 };
354 Ok(Pipe { read, write })
355 }
356 }
357
358 #[cfg(not(target_os = "linux"))]
359 pub fn new() -> Result<Pipe> {
360 let mut fds = [-1i32; 2];
361 let res = unsafe { libc::pipe(fds.as_mut_ptr()) };
362 if res == -1 {
363 Err(Error::Pipe(std::io::Error::last_os_error()))
364 } else {
365 let mut read = FileDescriptor {
366 handle: OwnedHandle {
367 handle: fds[0],
368 handle_type: (),
369 },
370 };
371 let mut write = FileDescriptor {
372 handle: OwnedHandle {
373 handle: fds[1],
374 handle_type: (),
375 },
376 };
377 read.handle.cloexec()?;
378 write.handle.cloexec()?;
379 Ok(Pipe { read, write })
380 }
381 }
382 }
383
384 #[cfg(target_os = "linux")]
385 #[doc(hidden)]
386 pub fn socketpair_impl() -> Result<(FileDescriptor, FileDescriptor)> {
387 let mut fds = [-1i32; 2];
388 let res = unsafe {
389 libc::socketpair(
390 libc::PF_LOCAL,
391 libc::SOCK_STREAM | libc::SOCK_CLOEXEC,
392 0,
393 fds.as_mut_ptr(),
394 )
395 };
396 if res == -1 {
397 Err(Error::Socketpair(std::io::Error::last_os_error()))
398 } else {
399 let read = FileDescriptor {
400 handle: OwnedHandle {
401 handle: fds[0],
402 handle_type: (),
403 },
404 };
405 let write = FileDescriptor {
406 handle: OwnedHandle {
407 handle: fds[1],
408 handle_type: (),
409 },
410 };
411 Ok((read, write))
412 }
413 }
414
415 #[cfg(not(target_os = "linux"))]
416 #[doc(hidden)]
417 pub fn socketpair_impl() -> Result<(FileDescriptor, FileDescriptor)> {
418 let mut fds = [-1i32; 2];
419 let res = unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, fds.as_mut_ptr()) };
420 if res == -1 {
421 Err(Error::Socketpair(std::io::Error::last_os_error()))
422 } else {
423 let mut read = FileDescriptor {
424 handle: OwnedHandle {
425 handle: fds[0],
426 handle_type: (),
427 },
428 };
429 let mut write = FileDescriptor {
430 handle: OwnedHandle {
431 handle: fds[1],
432 handle_type: (),
433 },
434 };
435 read.handle.cloexec()?;
436 write.handle.cloexec()?;
437 Ok((read, write))
438 }
439 }
440
441 pub use libc::{pollfd, POLLERR, POLLHUP, POLLIN, POLLOUT};
442 use std::time::Duration;
443
444 #[cfg(not(target_os = "macos"))]
445 #[doc(hidden)]
446 pub fn poll_impl(pfd: &mut [pollfd], duration: Option<Duration>) -> Result<usize> {
447 let poll_result = unsafe {
448 libc::poll(
449 pfd.as_mut_ptr(),
450 pfd.len() as _,
451 duration
452 .map(|wait| wait.as_millis() as libc::c_int)
453 .unwrap_or(-1),
454 )
455 };
456 if poll_result < 0 {
457 Err(Error::Poll(std::io::Error::last_os_error()))
458 } else {
459 Ok(poll_result as usize)
460 }
461 }
462
463 // macOS has a broken poll(2) implementation, so we introduce a layer to deal with that here
464 #[cfg(target_os = "macos")]
465 mod macos {
466 use super::*;
467 use libc::{fd_set, timeval, FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, POLLERR, POLLIN, POLLOUT};
468 use std::os::unix::io::RawFd;
469
470 struct FdSet {
471 set: fd_set,
472 }
473
474 #[inline]
475 fn check_fd(fd: RawFd) -> Result<()> {
476 if fd < 0 {
477 return Err(Error::IllegalFdValue(fd.into()));
478 }
479 if fd as usize >= FD_SETSIZE {
480 return Err(Error::FdValueOutsideFdSetSize(fd.into()));
481 }
482 Ok(())
483 }
484
485 impl FdSet {
486 pub fn new() -> Self {
487 unsafe {
488 let mut set = std::mem::MaybeUninit::uninit();
489 FD_ZERO(set.as_mut_ptr());
490 Self {
491 set: set.assume_init(),
492 }
493 }
494 }
495
496 pub fn add(&mut self, fd: RawFd) -> Result<()> {
497 check_fd(fd)?;
498 unsafe {
499 FD_SET(fd, &mut self.set);
500 }
501 Ok(())
502 }
503
504 pub fn contains(&mut self, fd: RawFd) -> bool {
505 check_fd(fd).unwrap();
506 unsafe { FD_ISSET(fd, &mut self.set) }
507 }
508 }
509
510 fn materialize(set: &mut Option<FdSet>) -> &mut FdSet {
511 set.get_or_insert_with(FdSet::new)
512 }
513
514 fn set_ptr(set: &mut Option<FdSet>) -> *mut fd_set {
515 set.as_mut()
516 .map(|s| &mut s.set as *mut _)
517 .unwrap_or_else(std::ptr::null_mut)
518 }
519
520 fn is_set(set: &mut Option<FdSet>, fd: RawFd) -> bool {
521 set.as_mut().map(|s| s.contains(fd)).unwrap_or(false)
522 }
523
524 pub fn poll_impl(pfd: &mut [pollfd], duration: Option<Duration>) -> Result<usize> {
525 let mut read_set = None;
526 let mut write_set = None;
527 let mut exception_set = None;
528 let mut nfds = 0;
529
530 for item in pfd.iter_mut() {
531 item.revents = 0;
532
533 nfds = nfds.max(item.fd);
534
535 if item.events & POLLIN != 0 {
536 materialize(&mut read_set).add(item.fd)?;
537 }
538 if item.events & POLLOUT != 0 {
539 materialize(&mut write_set).add(item.fd)?;
540 }
541 materialize(&mut exception_set).add(item.fd)?;
542 }
543
544 let mut timeout = duration.map(|d| timeval {
545 tv_sec: d.as_secs() as _,
546 tv_usec: d.subsec_micros() as _,
547 });
548
549 let res = unsafe {
550 libc::select(
551 nfds + 1,
552 set_ptr(&mut read_set),
553 set_ptr(&mut write_set),
554 set_ptr(&mut exception_set),
555 timeout
556 .as_mut()
557 .map(|t| t as *mut _)
558 .unwrap_or_else(std::ptr::null_mut),
559 )
560 };
561
562 if res < 0 {
563 Err(std::io::Error::last_os_error().into())
564 } else {
565 for item in pfd.iter_mut() {
566 if is_set(&mut read_set, item.fd) {
567 item.revents |= POLLIN;
568 }
569 if is_set(&mut write_set, item.fd) {
570 item.revents |= POLLOUT;
571 }
572 if is_set(&mut exception_set, item.fd) {
573 item.revents |= POLLERR;
574 }
575 }
576
577 Ok(res as usize)
578 }
579 }
580 }
581
582 #[cfg(target_os = "macos")]
583 #[doc(hidden)]
584 pub use macos::poll_impl;