1
// This file is part of Substrate.
2

            
3
// Copyright (C) Parity Technologies (UK) Ltd.
4
// SPDX-License-Identifier: Apache-2.0
5

            
6
// Licensed under the Apache License, Version 2.0 (the "License");
7
// you may not use this file except in compliance with the License.
8
// You may obtain a copy of the License at
9
//
10
// 	http://www.apache.org/licenses/LICENSE-2.0
11
//
12
// Unless required by applicable law or agreed to in writing, software
13
// distributed under the License is distributed on an "AS IS" BASIS,
14
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
// See the License for the specific language governing permissions and
16
// limitations under the License.
17

            
18
//! Custom panic hook with bug report link
19
//!
20
//! This crate provides the [`set`] function, which wraps around [`std::panic::set_hook`] and
21
//! sets up a panic hook that prints a backtrace and invites the user to open an issue to the
22
//! given URL.
23
//!
24
//! By default, the panic handler aborts the process by calling [`std::process::exit`]. This can
25
//! temporarily be disabled by using an [`AbortGuard`].
26

            
27
use backtrace::Backtrace;
28
use regex::Regex;
29
use std::{
30
	cell::Cell,
31
	io::{self, Write},
32
	marker::PhantomData,
33
	panic::{self, PanicInfo},
34
	thread,
35
};
36

            
37
thread_local! {
38
	static ON_PANIC: Cell<OnPanic> = Cell::new(OnPanic::Abort);
39
}
40

            
41
/// Panic action.
42
#[derive(Debug, Clone, Copy, PartialEq)]
43
enum OnPanic {
44
	/// Abort when panic occurs.
45
	Abort,
46
	/// Unwind when panic occurs.
47
	Unwind,
48
	/// Always unwind even if someone changes strategy to Abort afterwards.
49
	NeverAbort,
50
}
51

            
52
/// Set the panic hook.
53
///
54
/// Calls [`std::panic::set_hook`] to set up the panic hook.
55
///
56
/// The `bug_url` parameter is an invitation for users to visit that URL to submit a bug report
57
/// in the case where a panic happens.
58
pub fn set(bug_url: &str, version: &str) {
59
	panic::set_hook(Box::new({
60
		let version = version.to_string();
61
		let bug_url = bug_url.to_string();
62
		move |c| panic_hook(c, &bug_url, &version)
63
	}));
64
}
65

            
66
macro_rules! ABOUT_PANIC {
67
	() => {
68
		"
69
This is a bug. Please report it at:
70

            
71
	{}
72
"
73
	};
74
}
75

            
76
/// Set aborting flag. Returns previous value of the flag.
77
643644
fn set_abort(on_panic: OnPanic) -> OnPanic {
78
643644
	ON_PANIC.with(|val| {
79
643644
		let prev = val.get();
80
643644
		match prev {
81
643644
			OnPanic::Abort | OnPanic::Unwind => val.set(on_panic),
82
			OnPanic::NeverAbort => (),
83
		}
84
643644
		prev
85
643644
	})
86
643644
}
87

            
88
/// RAII guard for whether panics in the current thread should unwind or abort.
89
///
90
/// Sets a thread-local abort flag on construction and reverts to the previous setting when dropped.
91
/// Does not implement `Send` on purpose.
92
///
93
/// > **Note**: Because we restore the previous value when dropped, you are encouraged to leave
94
/// > the `AbortGuard` on the stack and let it destroy itself naturally.
95
pub struct AbortGuard {
96
	/// Value that was in `ABORT` before we created this guard.
97
	previous_val: OnPanic,
98
	/// Marker so that `AbortGuard` doesn't implement `Send`.
99
	_not_send: PhantomData<std::rc::Rc<()>>,
100
}
101

            
102
impl AbortGuard {
103
	/// Create a new guard. While the guard is alive, panics that happen in the current thread will
104
	/// unwind the stack (unless another guard is created afterwards).
105
	pub fn force_unwind() -> AbortGuard {
106
		AbortGuard { previous_val: set_abort(OnPanic::Unwind), _not_send: PhantomData }
107
	}
108

            
109
	/// Create a new guard. While the guard is alive, panics that happen in the current thread will
110
	/// abort the process (unless another guard is created afterwards).
111
321822
	pub fn force_abort() -> AbortGuard {
112
321822
		AbortGuard { previous_val: set_abort(OnPanic::Abort), _not_send: PhantomData }
113
321822
	}
114

            
115
	/// Create a new guard. While the guard is alive, panics that happen in the current thread will
116
	/// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created
117
	/// afterwards).
118
	pub fn never_abort() -> AbortGuard {
119
		AbortGuard { previous_val: set_abort(OnPanic::NeverAbort), _not_send: PhantomData }
120
	}
121
}
122

            
123
impl Drop for AbortGuard {
124
321822
	fn drop(&mut self) {
125
321822
		set_abort(self.previous_val);
126
321822
	}
127
}
128

            
129
// NOTE: When making any changes here make sure to also change this function in `sc-tracing`.
130
fn strip_control_codes(input: &str) -> std::borrow::Cow<str> {
131
	lazy_static::lazy_static! {
132
		static ref RE: Regex = Regex::new(r#"(?x)
133
			\x1b\[[^m]+m|        # VT100 escape codes
134
			[
135
			  \x00-\x09\x0B-\x1F # ASCII control codes / Unicode C0 control codes, except \n
136
			  \x7F               # ASCII delete
137
			  \u{80}-\u{9F}      # Unicode C1 control codes
138
			  \u{202A}-\u{202E}  # Unicode left-to-right / right-to-left control characters
139
			  \u{2066}-\u{2069}  # Same as above
140
			]
141
		"#).expect("regex parsing doesn't fail; qed");
142
	}
143

            
144
	RE.replace_all(input, "")
145
}
146

            
147
/// Function being called when a panic happens.
148
fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) {
149
	let location = info.location();
150
	let file = location.as_ref().map(|l| l.file()).unwrap_or("<unknown>");
151
	let line = location.as_ref().map(|l| l.line()).unwrap_or(0);
152

            
153
	let msg = match info.payload().downcast_ref::<&'static str>() {
154
		Some(s) => *s,
155
		None => match info.payload().downcast_ref::<String>() {
156
			Some(s) => &s[..],
157
			None => "Box<Any>",
158
		},
159
	};
160

            
161
	let msg = strip_control_codes(msg);
162

            
163
	let thread = thread::current();
164
	let name = thread.name().unwrap_or("<unnamed>");
165

            
166
	let backtrace = Backtrace::new();
167

            
168
	let mut stderr = io::stderr();
169

            
170
	let _ = writeln!(stderr);
171
	let _ = writeln!(stderr, "====================");
172
	let _ = writeln!(stderr);
173
	let _ = writeln!(stderr, "Version: {}", version);
174
	let _ = writeln!(stderr);
175
	let _ = writeln!(stderr, "{:?}", backtrace);
176
	let _ = writeln!(stderr);
177
	let _ = writeln!(stderr, "Thread '{}' panicked at '{}', {}:{}", name, msg, file, line);
178

            
179
	let _ = writeln!(stderr, ABOUT_PANIC!(), report_url);
180
	ON_PANIC.with(|val| {
181
		if val.get() == OnPanic::Abort {
182
			::std::process::exit(1);
183
		}
184
	})
185
}
186

            
187
#[cfg(test)]
188
mod tests {
189
	use super::*;
190

            
191
	#[test]
192
	fn does_not_abort() {
193
		set("test", "1.2.3");
194
		let _guard = AbortGuard::force_unwind();
195
		::std::panic::catch_unwind(|| panic!()).ok();
196
	}
197

            
198
	#[test]
199
	fn does_not_abort_after_never_abort() {
200
		set("test", "1.2.3");
201
		let _guard = AbortGuard::never_abort();
202
		let _guard = AbortGuard::force_abort();
203
		std::panic::catch_unwind(|| panic!()).ok();
204
	}
205

            
206
	fn run_test_in_another_process(
207
		test_name: &str,
208
		test_body: impl FnOnce(),
209
	) -> Option<std::process::Output> {
210
		if std::env::var("RUN_FORKED_TEST").is_ok() {
211
			test_body();
212
			None
213
		} else {
214
			let output = std::process::Command::new(std::env::current_exe().unwrap())
215
				.arg(test_name)
216
				.env("RUN_FORKED_TEST", "1")
217
				.output()
218
				.unwrap();
219

            
220
			assert!(output.status.success());
221
			Some(output)
222
		}
223
	}
224

            
225
	#[test]
226
	fn control_characters_are_always_stripped_out_from_the_panic_messages() {
227
		const RAW_LINE: &str = "$$START$$\x1B[1;32mIn\u{202a}\u{202e}\u{2066}\u{2069}ner\n\r\x7ftext!\u{80}\u{9f}\x1B[0m$$END$$";
228
		const SANITIZED_LINE: &str = "$$START$$Inner\ntext!$$END$$";
229

            
230
		let output = run_test_in_another_process(
231
			"control_characters_are_always_stripped_out_from_the_panic_messages",
232
			|| {
233
				set("test", "1.2.3");
234
				let _guard = AbortGuard::force_unwind();
235
				let _ = std::panic::catch_unwind(|| panic!("{}", RAW_LINE));
236
			},
237
		);
238

            
239
		if let Some(output) = output {
240
			let stderr = String::from_utf8(output.stderr).unwrap();
241
			assert!(!stderr.contains(RAW_LINE));
242
			assert!(stderr.contains(SANITIZED_LINE));
243
		}
244
	}
245
}