Skip to content

Commit 159508b

Browse files
authored
add track_caller to public APIs (#4413) (#4772)
Functions that may panic can be annotated with `#[track_caller]` so that in the event of a panic, the function where the user called the panicking function is shown instead of the file and line within Tokio source. This change adds track caller to all the non-unstable public APIs in Tokio core where the documentation describes how the function may panic due to incorrect context or inputs. Since each internal function needs to be annotated down to the actual panic, it makes sense to start in Tokio core functionality. Tests are needed to ensure that all the annotations remain in place in case internal refactoring occurs. The test installs a panic hook to extract the file location from the `PanicInfo` struct and clone it up to the outer scope to check that the panic was indeed reported from within the test file. The downside to this approach is that the panic hook is global while set and so we need a lot of extra functionality to effectively serialize the tests so that only a single panic can occur at a time. The annotation of `block_on` was removed as it did not work. It appears to be impossible to correctly chain track caller when the call stack to the panic passes through clojures, as the track caller annotation can only be applied to functions. Also, the panic message itself is very descriptive.
1 parent 34b8ebb commit 159508b

File tree

6 files changed

+114
-5
lines changed

6 files changed

+114
-5
lines changed

tokio/src/runtime/builder.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ impl Builder {
287287
///
288288
/// The default value is the number of cores available to the system.
289289
///
290-
/// # Panic
290+
/// # Panics
291291
///
292292
/// When using the `current_thread` runtime this method will panic, since
293293
/// those variants do not allow setting worker thread counts.
@@ -324,9 +324,10 @@ impl Builder {
324324
/// rt.block_on(async move {});
325325
/// ```
326326
///
327-
/// # Panic
327+
/// # Panics
328328
///
329329
/// This will panic if `val` is not larger than `0`.
330+
#[track_caller]
330331
pub fn worker_threads(&mut self, val: usize) -> &mut Self {
331332
assert!(val > 0, "Worker threads cannot be set to 0");
332333
self.worker_threads = Some(val);
@@ -342,7 +343,7 @@ impl Builder {
342343
///
343344
/// The default value is 512.
344345
///
345-
/// # Panic
346+
/// # Panics
346347
///
347348
/// This will panic if `val` is not larger than `0`.
348349
///
@@ -354,6 +355,7 @@ impl Builder {
354355
/// [`spawn_blocking`]: fn@crate::task::spawn_blocking
355356
/// [`worker_threads`]: Self::worker_threads
356357
/// [`thread_keep_alive`]: Self::thread_keep_alive
358+
#[track_caller]
357359
#[cfg_attr(docsrs, doc(alias = "max_threads"))]
358360
pub fn max_blocking_threads(&mut self, val: usize) -> &mut Self {
359361
assert!(val > 0, "Max blocking threads cannot be set to 0");

tokio/src/runtime/context.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ pub(crate) fn try_current() -> Result<Handle, crate::runtime::TryCurrentError> {
1515
}
1616
}
1717

18+
#[track_caller]
1819
pub(crate) fn current() -> Handle {
1920
match try_current() {
2021
Ok(handle) => handle,

tokio/src/runtime/handle.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ impl Handle {
8787

8888
/// Returns a `Handle` view over the currently running `Runtime`.
8989
///
90-
/// # Panic
90+
/// # Panics
9191
///
9292
/// This will panic if called outside the context of a Tokio runtime. That means that you must
9393
/// call this on one of the threads **being run by the runtime**, or from a thread with an active
@@ -129,6 +129,7 @@ impl Handle {
129129
/// # });
130130
/// # }
131131
/// ```
132+
#[track_caller]
132133
pub fn current() -> Self {
133134
context::current()
134135
}

tokio/src/runtime/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,6 @@ cfg_rt! {
472472
/// ```
473473
///
474474
/// [handle]: fn@Handle::block_on
475-
#[track_caller]
476475
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
477476
#[cfg(all(tokio_unstable, feature = "tracing"))]
478477
let future = crate::util::trace::task(future, "block_on", None, task::Id::next().as_u64());

tokio/src/runtime/task/error.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ impl JoinError {
8282
/// }
8383
/// }
8484
/// ```
85+
#[track_caller]
8586
pub fn into_panic(self) -> Box<dyn Any + Send + 'static> {
8687
self.try_into_panic()
8788
.expect("`JoinError` reason is not a panic.")

tokio/tests/rt_panic.rs

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#![warn(rust_2018_idioms)]
2+
#![cfg(feature = "full")]
3+
4+
use futures::future;
5+
use parking_lot::{const_mutex, Mutex};
6+
use std::error::Error;
7+
use std::panic;
8+
use std::sync::Arc;
9+
use tokio::runtime::{Builder, Handle, Runtime};
10+
11+
fn test_panic<Func: FnOnce() + panic::UnwindSafe>(func: Func) -> Option<String> {
12+
static PANIC_MUTEX: Mutex<()> = const_mutex(());
13+
14+
{
15+
let _guard = PANIC_MUTEX.lock();
16+
let panic_file: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
17+
18+
let prev_hook = panic::take_hook();
19+
{
20+
let panic_file = panic_file.clone();
21+
panic::set_hook(Box::new(move |panic_info| {
22+
let panic_location = panic_info.location().unwrap();
23+
panic_file
24+
.lock()
25+
.clone_from(&Some(panic_location.file().to_string()));
26+
}));
27+
}
28+
29+
let result = panic::catch_unwind(func);
30+
// Return to the previously set panic hook (maybe default) so that we get nice error
31+
// messages in the tests.
32+
panic::set_hook(prev_hook);
33+
34+
if result.is_err() {
35+
panic_file.lock().clone()
36+
} else {
37+
None
38+
}
39+
}
40+
}
41+
42+
#[test]
43+
fn current_handle_panic_caller() -> Result<(), Box<dyn Error>> {
44+
let panic_location_file = test_panic(|| {
45+
let _ = Handle::current();
46+
});
47+
48+
// The panic location should be in this file
49+
assert_eq!(&panic_location_file.unwrap(), file!());
50+
51+
Ok(())
52+
}
53+
54+
#[test]
55+
fn into_panic_panic_caller() -> Result<(), Box<dyn Error>> {
56+
let panic_location_file = test_panic(move || {
57+
let rt = basic();
58+
rt.block_on(async {
59+
let handle = tokio::spawn(future::pending::<()>());
60+
61+
handle.abort();
62+
63+
let err = handle.await.unwrap_err();
64+
assert!(!&err.is_panic());
65+
66+
let _ = err.into_panic();
67+
});
68+
});
69+
70+
// The panic location should be in this file
71+
assert_eq!(&panic_location_file.unwrap(), file!());
72+
73+
Ok(())
74+
}
75+
76+
#[test]
77+
fn builder_worker_threads_panic_caller() -> Result<(), Box<dyn Error>> {
78+
let panic_location_file = test_panic(|| {
79+
let _ = Builder::new_multi_thread().worker_threads(0).build();
80+
});
81+
82+
// The panic location should be in this file
83+
assert_eq!(&panic_location_file.unwrap(), file!());
84+
85+
Ok(())
86+
}
87+
88+
#[test]
89+
fn builder_max_blocking_threads_panic_caller() -> Result<(), Box<dyn Error>> {
90+
let panic_location_file = test_panic(|| {
91+
let _ = Builder::new_multi_thread().max_blocking_threads(0).build();
92+
});
93+
94+
// The panic location should be in this file
95+
assert_eq!(&panic_location_file.unwrap(), file!());
96+
97+
Ok(())
98+
}
99+
100+
fn basic() -> Runtime {
101+
tokio::runtime::Builder::new_current_thread()
102+
.enable_all()
103+
.build()
104+
.unwrap()
105+
}

0 commit comments

Comments
 (0)