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
//! Efficient, logical 'stack' traces of async functions.
//!
//! ## Usage
//! To use, annotate your async functions with `#[async_backtrace::framed]`,
//! like so:
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     tokio::select! {
//!         _ = tokio::spawn(async_backtrace::frame!(pending())) => {}
//!         _ = foo() => {}
//!     };
//! }
//!
//! #[async_backtrace::framed]
//! async fn pending() {
//!     std::future::pending::<()>().await
//! }
//!
//! #[async_backtrace::framed]
//! async fn foo() {
//!     bar().await;
//! }
//!
//! #[async_backtrace::framed]
//! async fn bar() {
//!     futures::join!(fiz(), buz());
//! }
//!
//! #[async_backtrace::framed]
//! async fn fiz() {
//!     tokio::task::yield_now().await;
//! }
//!
//! #[async_backtrace::framed]
//! async fn buz() {
//!     println!("{}", baz().await);
//! }
//!
//! #[async_backtrace::framed]
//! async fn baz() -> String {
//!     async_backtrace::taskdump_tree(true)
//! }
//! ```
//!
//! This example program will print out something along the lines of:
//!
//! ```text
//! ╼ taskdump::foo::{{closure}} at backtrace/examples/taskdump.rs:20:1
//!   └╼ taskdump::bar::{{closure}} at backtrace/examples/taskdump.rs:25:1
//!      ├╼ taskdump::buz::{{closure}} at backtrace/examples/taskdump.rs:35:1
//!      │  └╼ taskdump::baz::{{closure}} at backtrace/examples/taskdump.rs:40:1
//!      └╼ taskdump::fiz::{{closure}} at backtrace/examples/taskdump.rs:30:1
//! ╼ taskdump::pending::{{closure}} at backtrace/examples/taskdump.rs:15:1
//! ```
//!
//! ## Minimizing Overhead
//! To minimize overhead, ensure that futures you spawn with your async runtime
//! are marked with `#[framed]`.
//!
//! In other words, avoid doing this:
//! ```rust
//! # #[tokio::main] async fn main() {
//! tokio::spawn(async {
//!     foo().await;
//!     bar().await;
//! }).await;
//! # }
//!
//! #[async_backtrace::framed] async fn foo() {}
//! #[async_backtrace::framed] async fn bar() {}
//! ```
//! ...and prefer doing this:
//! ```rust
//! # #[tokio::main] async fn main() {
//! tokio::spawn(async_backtrace::location!().frame(async {
//!     foo().await;
//!     bar().await;
//! })).await;
//! # }
//!
//! #[async_backtrace::framed] async fn foo() {}
//! #[async_backtrace::framed] async fn bar() {}
//! ```
//!
//! ## Estimating Overhead
//! To estimate the overhead of adopting `#[framed]` in your application, refer
//! to the benchmarks and interpretive guidance in
//! `./backtrace/benches/frame_overhead.rs`. You can run these benchmarks with
//! `cargo bench`.

pub(crate) mod frame;
pub(crate) mod framed;
pub(crate) mod linked_list;
pub(crate) mod location;
pub(crate) mod tasks;

pub(crate) use frame::Frame;
pub(crate) use framed::Framed;
pub use location::Location;
pub use tasks::{tasks, Task};

/// Include the annotated async function in backtraces and taskdumps.
///
/// This, for instance:
/// ```
/// # async fn bar() {}
/// # async fn baz() {}
/// #[async_backtrace::framed]
/// async fn foo() {
///     bar().await;
///     baz().await;
/// }
/// ```
/// ...expands, roughly, to:
/// ```
/// # async fn bar() {}
/// # async fn baz() {}
/// async fn foo() {
///     async_backtrace::frame!(async move {
///         bar().await;
///         baz().await;
///     }).await;
/// }
/// ```
pub use async_backtrace_attributes::framed;

/// Include the annotated async expression in backtraces and taskdumps.
///
/// This, for instance:
/// ```
/// # #[tokio::main] async fn main() {
/// # async fn foo() {}
/// # async fn bar() {}
/// tokio::spawn(async_backtrace::frame!(async {
///     foo().await;
///     bar().await;
/// })).await;
/// # }
/// ```
/// ...expands, roughly, to:
/// ```
/// # #[tokio::main] async fn main() {
/// # async fn foo() {}
/// # async fn bar() {}
/// tokio::spawn(async_backtrace::location!().frame(async {
///     foo().await;
///     bar().await;
/// })).await;
/// # }
/// ```
#[macro_export]
macro_rules! frame {
    ($async_expr:expr) => {
        $crate::location!().frame($async_expr)
    };
}

/// Produces a human-readable tree of task states.
///
/// If `wait_for_running_tasks` is `false`, this routine will display only the
/// top-level location of currently-running tasks and a note that they are
/// "POLLING". Otherwise, this routine will wait for currently-running tasks to
/// become idle.
///
/// # Safety
/// If `wait_for_running_tasks` is `true`, this routine may deadlock if any
/// non-async lock is held which may also be held by a Framed task.
pub fn taskdump_tree(wait_for_running_tasks: bool) -> String {
    tasks()
        .map(|task| task.pretty_tree(wait_for_running_tasks))
        .collect::<Vec<String>>()
        .join("\n")
}

/// Produces a backtrace starting at the currently-active frame (if any).
///
/// ## Example
/// ```
/// use async_backtrace::{framed, backtrace, Location};
///
/// #[tokio::main]
/// async fn main() {
///     foo().await;
/// }
///
/// #[async_backtrace::framed]
/// async fn foo() {
///     bar().await;
/// }
///
/// #[async_backtrace::framed]
/// async fn bar() {
///     baz().await;
/// }
///
/// #[async_backtrace::framed]
/// async fn baz() {
/// #   macro_rules! assert_eq { ($l:expr, $r:expr) => { debug_assert_eq!($l.len(), $r.len());} }
///     assert_eq!(&async_backtrace::backtrace().unwrap().iter().map(|l| l.to_string()).collect::<Vec<_>>()[..], &[
///         "rust_out::baz::{{closure}} at src/lib.rs:19:1",
///         "rust_out::bar::{{closure}} at src/lib.rs:14:1",
///         "rust_out::foo::{{closure}} at src/lib.rs:9:1",
///     ]);
/// }
/// ```
pub fn backtrace() -> Option<Box<[Location]>> {
    Frame::with_active(|maybe_frame| maybe_frame.map(Frame::backtrace_locations))
}

pub(crate) mod sync {
    #[cfg(loom)]
    pub(crate) use loom::sync::Mutex;

    #[cfg(not(loom))]
    pub(crate) use std::sync::Mutex;

    pub(crate) use std::sync::TryLockError;
}

pub(crate) mod cell {
    #[cfg(loom)]
    pub(crate) use loom::cell::{Cell, UnsafeCell};

    #[cfg(not(loom))]
    pub(crate) use std::cell::Cell;

    #[cfg(not(loom))]
    #[derive(Debug)]
    #[repr(transparent)]
    pub(crate) struct UnsafeCell<T>(std::cell::UnsafeCell<T>);

    #[cfg(not(loom))]
    impl<T> UnsafeCell<T> {
        pub(crate) fn new(data: T) -> UnsafeCell<T> {
            UnsafeCell(std::cell::UnsafeCell::new(data))
        }

        pub(crate) fn with<R>(&self, f: impl FnOnce(*const T) -> R) -> R {
            f(self.0.get())
        }

        pub(crate) fn with_mut<R>(&self, f: impl FnOnce(*mut T) -> R) -> R {
            f(self.0.get())
        }
    }
}

pub(crate) fn defer<F: FnOnce() -> R, R>(f: F) -> impl Drop {
    struct Defer<F: FnOnce() -> R, R>(Option<F>);

    impl<F: FnOnce() -> R, R> Drop for Defer<F, R> {
        fn drop(&mut self) {
            self.0.take().unwrap()();
        }
    }

    Defer(Some(f))
}

#[doc(hidden)]
/** NOT STABLE! DO NOT USE! */
pub mod ඞ {
    //  ^ kudos to Daniel Henry-Mantilla
    pub use crate::frame::Frame;
}