forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.rs
More file actions
349 lines (308 loc) · 10.8 KB
/
Copy pathreport.rs
File metadata and controls
349 lines (308 loc) · 10.8 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use camino::Utf8PathBuf;
use std::{cell::RefCell, sync::OnceLock};
pub fn sanitize_filename(component: &str) -> String {
component
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
.collect()
}
pub fn normalize_report_out_path(out: &Utf8PathBuf) -> Result<Utf8PathBuf, String> {
let s = out.as_str();
if !s.ends_with(".tar.gz") {
return Err(format!(
"report output path must end with `.tar.gz`: `{out}`"
));
}
if !out.exists() {
return Ok(out.clone());
}
let base = s.strip_suffix(".tar.gz").expect("checked .tar.gz suffix");
for idx in 1.. {
let candidate = Utf8PathBuf::from(format!("{base}-{idx}.tar.gz"));
if !candidate.exists() {
return Ok(candidate);
}
}
unreachable!()
}
pub fn create_dir_all_utf8(path: &Utf8PathBuf) -> Result<(), String> {
std::fs::create_dir_all(path).map_err(|err| format!("failed to create dir `{path}`: {err}"))
}
pub fn create_report_staging_dir(base: &str) -> Result<Utf8PathBuf, String> {
let base = Utf8PathBuf::from(base);
let _ = std::fs::create_dir_all(&base);
let pid = std::process::id();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let dir = base.join(format!("report-{pid}-{nanos}"));
create_dir_all_utf8(&dir)?;
Ok(dir)
}
#[derive(Debug, Clone)]
pub struct ReportStaging {
pub root_dir: Utf8PathBuf,
pub temp_dir: Utf8PathBuf,
}
pub fn create_report_staging_root(base: &str, root_name: &str) -> Result<ReportStaging, String> {
let temp_dir = create_report_staging_dir(base)?;
let root_dir = temp_dir.join(root_name);
create_dir_all_utf8(&root_dir)?;
Ok(ReportStaging { root_dir, temp_dir })
}
pub fn tar_gz_dir(staging: &Utf8PathBuf, out: &Utf8PathBuf) -> Result<(), String> {
let parent = staging
.parent()
.ok_or_else(|| "missing staging parent".to_string())?;
let name = staging
.file_name()
.ok_or_else(|| "missing staging basename".to_string())?;
let status = std::process::Command::new("tar")
.arg("-czf")
.arg(out.as_str())
.arg("-C")
.arg(parent.as_str())
.arg(name)
.status()
.map_err(|err| format!("failed to run tar: {err}"))?;
if !status.success() {
return Err(format!("tar exited with status {status}"));
}
Ok(())
}
pub fn copy_input_into_report(input: &Utf8PathBuf, inputs_dir: &Utf8PathBuf) -> Result<(), String> {
if input.is_file() {
let name = input
.file_name()
.map(|s| s.to_string())
.unwrap_or_else(|| "input.fe".to_string());
let dest = inputs_dir.join(name);
std::fs::copy(input, &dest)
.map_err(|err| format!("failed to copy `{input}` to `{dest}`: {err}"))?;
return Ok(());
}
if !input.is_dir() {
return Ok(());
}
// Keep the report small but useful: include `fe.toml` and all `.fe` sources under `src/`.
let fe_toml = input.join("fe.toml");
if fe_toml.is_file() {
let dest = inputs_dir.join("fe.toml");
let _ = std::fs::copy(fe_toml, dest);
}
let src_dir = input.join("src");
if !src_dir.is_dir() {
return Ok(());
}
let dest_src = inputs_dir.join("src");
create_dir_all_utf8(&dest_src)?;
for entry in walkdir::WalkDir::new(src_dir.as_std_path())
.follow_links(false)
.into_iter()
.filter_map(Result::ok)
{
let path = entry.path();
if !path.is_file() {
continue;
}
if path.extension().and_then(|s| s.to_str()) != Some("fe") {
continue;
}
let rel = match path.strip_prefix(src_dir.as_std_path()) {
Ok(rel) => rel,
Err(_) => continue,
};
let rel = match Utf8PathBuf::from_path_buf(rel.to_path_buf()) {
Ok(p) => p,
Err(_) => continue,
};
let dest = dest_src.join(rel);
if let Some(parent) = dest.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::copy(path, dest);
}
Ok(())
}
pub fn panic_payload_to_string(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&'static str>() {
(*s).to_string()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"panic payload is not a string".to_string()
}
}
thread_local! {
static PANIC_REPORT_PATH: RefCell<Option<Utf8PathBuf>> = const { RefCell::new(None) };
}
static PANIC_REPORT_INSTALL: OnceLock<()> = OnceLock::new();
fn install_panic_reporter_once() {
let _ = PANIC_REPORT_INSTALL.get_or_init(|| {
let old = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
// Never panic inside a panic hook: that would abort the process and can prevent reports
// from being written.
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let path = PANIC_REPORT_PATH.with(|p| p.borrow().clone());
if let Some(path) = path {
let bt = std::backtrace::Backtrace::force_capture();
let mut msg = String::new();
msg.push_str("panic while running `fe`\n\n");
msg.push_str(&format!("{info}\n\n"));
msg.push_str(&format!("backtrace:\n{bt:?}\n"));
let _ = std::fs::write(&path, msg);
}
// Keep the default stderr output for interactive runs.
(old)(info);
}));
}));
});
}
pub struct PanicReportGuard {
prev: Option<Utf8PathBuf>,
}
impl Drop for PanicReportGuard {
fn drop(&mut self) {
let prev = self.prev.take();
PANIC_REPORT_PATH.with(|p| {
*p.borrow_mut() = prev;
});
}
}
pub fn enable_panic_report(path: Utf8PathBuf) -> PanicReportGuard {
install_panic_reporter_once();
let prev = PANIC_REPORT_PATH.with(|p| p.borrow().clone());
PANIC_REPORT_PATH.with(|p| {
*p.borrow_mut() = Some(path);
});
PanicReportGuard { prev }
}
fn find_git_repo_root(start: &Utf8PathBuf) -> Option<Utf8PathBuf> {
let mut dir = start.clone();
loop {
if dir.join(".git").exists() {
return Some(dir);
}
let parent = dir.parent()?.to_owned();
if parent == dir {
return None;
}
dir = parent;
}
}
fn capture_cmd(cwd: &Utf8PathBuf, program: &str, args: &[&str]) -> Option<String> {
let output = std::process::Command::new(program)
.args(args)
.current_dir(cwd.as_std_path())
.output()
.ok()?;
let mut text = String::new();
text.push_str(&String::from_utf8_lossy(&output.stdout));
text.push_str(&String::from_utf8_lossy(&output.stderr));
Some(text.trim().to_string())
}
fn write_best_effort(path: &Utf8PathBuf, contents: impl AsRef<[u8]>) {
let _ = std::fs::write(path, contents);
}
pub fn write_report_meta(root: &Utf8PathBuf, kind: &str, suite: Option<&str>) {
let meta = root.join("meta");
let _ = std::fs::create_dir_all(meta.as_std_path());
write_best_effort(&meta.join("kind.txt"), format!("{kind}\n"));
if let Some(suite) = suite {
write_best_effort(&meta.join("suite.txt"), format!("{suite}\n"));
}
if let Ok(cwd) = std::env::current_dir()
&& let Ok(cwd) = Utf8PathBuf::from_path_buf(cwd)
{
write_best_effort(&meta.join("cwd.txt"), format!("{cwd}\n"));
}
let mut args = String::new();
for a in std::env::args() {
args.push_str(&a);
args.push('\n');
}
write_best_effort(&meta.join("args.txt"), args);
let keys = ["RUST_BACKTRACE"];
let mut env_txt = String::new();
for k in keys {
if let Ok(v) = std::env::var(k) {
env_txt.push_str(k);
env_txt.push('=');
env_txt.push_str(&v);
env_txt.push('\n');
}
}
if !env_txt.is_empty() {
write_best_effort(&meta.join("env.txt"), env_txt);
}
if let Ok(manifest_dir) =
Utf8PathBuf::from_path_buf(std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")))
&& let Some(repo) = find_git_repo_root(&manifest_dir)
{
let mut git_txt = String::new();
git_txt.push_str(&format!("fe_repo: {repo}\n"));
if let Some(head) = capture_cmd(&repo, "git", &["rev-parse", "HEAD"]) {
git_txt.push_str(&format!("fe_head: {head}\n"));
}
if let Some(status) = capture_cmd(&repo, "git", &["status", "--porcelain=v1"]) {
let dirty = if status.trim().is_empty() {
"no"
} else {
"yes"
};
git_txt.push_str(&format!("fe_dirty: {dirty}\n"));
}
let sonatina_guess = repo.join("../sonatina");
if sonatina_guess.exists()
&& let Some(sonatina_repo) = find_git_repo_root(&sonatina_guess)
{
git_txt.push_str(&format!("\nsonatina_repo: {sonatina_repo}\n"));
if let Some(head) = capture_cmd(&sonatina_repo, "git", &["rev-parse", "HEAD"]) {
git_txt.push_str(&format!("sonatina_head: {head}\n"));
}
if let Some(status) = capture_cmd(&sonatina_repo, "git", &["status", "--porcelain=v1"])
{
let dirty = if status.trim().is_empty() {
"no"
} else {
"yes"
};
git_txt.push_str(&format!("sonatina_dirty: {dirty}\n"));
}
}
write_best_effort(&meta.join("git.txt"), git_txt);
}
if let Ok(out) = std::process::Command::new("rustc").arg("-Vv").output()
&& out.status.success()
{
let mut txt = String::new();
txt.push_str(&String::from_utf8_lossy(&out.stdout));
txt.push_str(&String::from_utf8_lossy(&out.stderr));
write_best_effort(&meta.join("rustc.txt"), txt);
}
}
pub fn is_verifier_error_text(text: &str) -> bool {
let normalized = text.to_ascii_lowercase();
normalized.contains("verifierfailed")
|| normalized.contains("verificationreport")
|| normalized.contains("verifier failed")
}
#[cfg(test)]
mod tests {
use super::is_verifier_error_text;
#[test]
fn detects_verifier_error_markers() {
assert!(is_verifier_error_text(
"internal error: VerifierFailed { report: VerificationReport { ... } }"
));
assert!(is_verifier_error_text(
"backend verifier failed while compiling module"
));
}
#[test]
fn ignores_non_verifier_errors() {
assert!(!is_verifier_error_text("failed to lower MIR"));
}
}