1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
macro_rules! fd_guard {
($name:ident, guard: $guard_name:ident, FD: $fd:path, name of FD: $doc:ident) => {
mod $doc {
use crate::ffi::{close, dup, dup2};
use std::fs::OpenOptions;
use std::io;
use std::os::unix::io::IntoRawFd;
use std::os::unix::io::RawFd;
use std::os::unix::prelude::*;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
static IS_REPLACED: AtomicBool = AtomicBool::new(false);
const ORDERING: Ordering = Ordering::SeqCst;
pub struct $guard_name {
original_fd: RawFd,
file_fd: RawFd,
}
pub struct $name;
impl $name {
pub fn override_file<P: AsRef<Path>>(p: P) -> io::Result<$guard_name> {
Self::check_override();
let file = OpenOptions::new().read(true).write(true).append(true).create(true).open(p)?;
let file_fd = file.into_raw_fd();
Self::override_fd(file_fd)
}
pub fn override_raw<FD: AsRawFd>(fd: FD) -> io::Result<$guard_name> {
Self::check_override();
let file_fd = fd.as_raw_fd();
Self::override_fd(file_fd)
}
fn override_fd(file_fd: RawFd) -> io::Result<$guard_name> {
let original_fd = unsafe { dup($fd) }?;
let _ = unsafe { dup2(file_fd, $fd) }?;
IS_REPLACED.store(true, ORDERING);
Ok($guard_name { original_fd, file_fd })
}
fn check_override() {
if IS_REPLACED.load(ORDERING) {
panic!("Tried to override Stdout twice");
}
}
}
impl Drop for $guard_name {
fn drop(&mut self) {
let _ = unsafe { dup2(self.original_fd, $fd) };
let _ = unsafe { close(self.file_fd) };
IS_REPLACED.store(false, ORDERING);
}
}
}
};
}