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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::borrow::Cow;
use std::convert::TryInto;
use std::env::current_dir;
use std::env::set_current_dir;
use std::env::temp_dir;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::num::TryFromIntError;
use std::panic::set_hook;
use std::panic::take_hook;
use std::path::Path;
use std::process::id as pid;
use libc::getrlimit;
use libc::kill;
use libc::rlimit;
use libc::RLIMIT_CORE;
use libc::setrlimit;
use libc::SIGQUIT;
type Str = Cow<'static, str>;
#[derive(Debug)]
pub enum Error {
Io(IoError),
Int(TryFromIntError),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
Error::Io(err) => write!(f, "{}", err),
Error::Int(err) => write!(f, "{}", err),
}
}
}
impl From<IoError> for Error {
fn from(e: IoError) -> Self {
Error::Io(e)
}
}
impl From<TryFromIntError> for Error {
fn from(e: TryFromIntError) -> Self {
Error::Int(e)
}
}
trait WithCtx<T>
where
Self: Sized,
{
type E;
fn ctx<F, S>(self, ctx: F) -> Result<T, (Str, Self::E)>
where
F: Fn() -> S,
S: Into<Str>;
}
impl<T, E> WithCtx<T> for Result<T, E> {
type E = E;
fn ctx<F, S>(self, ctx: F) -> Result<T, (Str, Self::E)>
where
F: Fn() -> S,
S: Into<Str>,
{
self.map_err(|e| (ctx().into(), e))
}
}
fn check<T>(result: T, error: T) -> Result<(), Error>
where
T: Copy + PartialOrd<T>,
{
if result == error {
Err(IoError::last_os_error())?;
}
Ok(())
}
fn dump_core() -> Result<(), (Str, Error)> {
let pid = pid();
let pid = pid.try_into().map_err(Error::from).ctx(|| {
format!(
"unable to dump core: PID {} is not a valid unsigned value",
pid
)
})?;
check(unsafe { kill(pid, SIGQUIT) }, -1).ctx(|| "failed to send SIGQUIT")?;
Ok(())
}
fn dump_core_and_quit(dir: &Path) -> Result<(), (Str, Error)> {
let cur_dir = current_dir()
.map_err(Error::from)
.ctx(|| "failed to retrieve current directory")?;
set_current_dir(dir)
.map_err(Error::from)
.ctx(|| format!("failed to change working directory to {}", dir.display()))?;
if let Err(err) = dump_core() {
let _ = set_current_dir(cur_dir);
Err(err)
} else {
Err(IoError::new(ErrorKind::Other, "SIGQUIT did not kill the process").into())
.ctx(|| "failed to force core dump")
}
}
fn enable_core_dumps() -> Result<(), (Str, Error)> {
let mut limit = rlimit {
rlim_cur: 0,
rlim_max: 0,
};
check(unsafe { getrlimit(RLIMIT_CORE, &mut limit) }, -1)
.ctx(|| "failed to retrieve core file size limit")?;
if limit.rlim_max == 0 {
Err(IoError::new(ErrorKind::Other, "hard limit is zero").into())
.ctx(|| "failed to adjust core file size limit")?;
}
limit.rlim_cur = limit.rlim_max;
check(unsafe { setrlimit(RLIMIT_CORE, &limit) }, -1)
.ctx(|| "failed to adjust core file size limit")?;
Ok(())
}
pub fn register_panic_handler() -> Result<(), (Str, Error)> {
enable_core_dumps()?;
let default_panic = take_hook();
set_hook(Box::new(move |panic_info| {
default_panic(panic_info);
if let Err((ctx, err)) = dump_core_and_quit(&temp_dir()) {
eprintln!("failed to dump core: {}: {}", ctx, err);
}
}));
Ok(())
}