aboutsummaryrefslogtreecommitdiff
path: root/crates/tor-memtrack/src/drop_bomb.rs
blob: 6a7b55fa63a55674cd85d77e87b907557ae24ad8 (plain)
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Drop bombs, for assurance of postconditions when types are dropped
//!
//! Provides two drop bomb types: [`DropBomb`] and [`DropBombCondition`].
//!
//! These help assure that our algorithms are correct,
//! by detecting when types that contain the bomb are dropped inappropriately.
//!
//! # No-op outside `#[cfg(test)]`
//!
//! When used outside test code, these types are unit ZSTs,
//! and are completely inert.
//! They won't cause panics or detect bugs, in production.
//!
//! # Panics (in tests), and simulation
//!
//! These types work by panicking in drop, when a bug is detected.
//! This will then cause a test failure.
//! Such panics are described as "explodes (panics)" in the documentation.
//!
//! There are also simulated drop bombs, whose explosions do not actually panic.
//! Instead, they record that a panic would have occurred,
//! and print a message to stderr.
//! The constructors provide a handle to allow the caller to enquire about explosions.
//! This allows for testing a containing type's drop bomb logic.
//!
//! Certain misuses result in actual panics, even with simulated bombs.
//! This is described as "panics (actually)".
//!
//! # Choosing a bomb
//!
//! [`DropBomb`] is for assuring the runtime context or appropriate timing of drops
//! (and could be used for implementing general conditions).
//!
//! [`DropBombCondition`] is for assuring the properties of a value that is being dropped.

use crate::internal_prelude::*;

#[cfg(test)]
use std::sync::atomic::{AtomicBool, Ordering};

//---------- macros used in this module, and supporting trait ----------

define_derive_deftly! {
    /// Helper for common impls on bombs
    ///
    ///  * Provides `fn new_armed`
    ///  * Provides `fn new_simulated`
    ///  * Implements `Drop`, using `TestableDrop::drop_impl`
    BombImpls =

    impl $ttype {
        /// Create a new drop bomb, which must be properly disposed of
        pub(crate) const fn new_armed() -> Self {
            let status = Status::ARMED_IN_TESTS;
            $ttype { status }
        }
    }

    #[cfg(test)]
    impl $ttype {
        /// Create a simulated drop bomb
        pub(crate) fn new_simulated() -> (Self, SimulationHandle) {
            let handle = SimulationHandle::new();
            let status = S::ArmedSimulated(handle.clone());
            ($ttype { status }, handle)
        }

        /// Turn an existing armed drop bomb into a simulated one
        ///
        /// This is useful for writing test cases, without having to make a `new_simulated`
        /// constructor for whatever type contains the drop bomb.
        /// Instead, construct it normally, and then reach in and call this on the bomb.
        ///
        /// # Panics
        ///
        /// `self` must be armed.  Otherwise, (actually) panics.
        pub(crate) fn make_simulated(&mut self) -> SimulationHandle {
            let handle = SimulationHandle::new();
            let new_status = S::ArmedSimulated(handle.clone());
            let old_status = mem::replace(&mut self.status, new_status);
            assert!(matches!(old_status, S::Armed));
            handle
        }

        /// Implemnetation of `Drop::drop`, split out for testability.
        ///
        /// Calls `drop_status`, and replaces `self.status` with `S::Disarmed`,
        /// so that `self` can be actually dropped (if we didn't panic).
        fn drop_impl(&mut self) {
            // Do the replacement first, so that if drop_status unwinds, we don't panic in panic.
            let status = mem::replace(&mut self.status, S::Disarmed);
            <$ttype as DropStatus>::drop_status(status);
        }
    }


    #[cfg(test)]
    impl Drop for $ttype {
        fn drop(&mut self) {
            // We don't check for unwinding.
            // We shouldn't drop a nonzero one of these even if we're panicking.
            // If we do, it'll be a double panic => abort.
            self.drop_impl();
        }
    }
}

/// Core of `Drop`, that can be called separately, for testing
///
/// To use: implement this, and derive deftly
/// [`BombImpls`](derive_deftly_template_BombImpls).
trait DropStatus {
    /// Handles dropping of a `Self` with this `status` field value
    fn drop_status(status: Status);
}

//---------- public types ----------

/// Drop bomb: for assuring that drops happen only when expected
///
/// Obtained from [`DropBomb::new_armed()`].
///
/// # Explosions
///
/// Explodes (panicking) if dropped,
/// unless [`.disarm()`](DropBomb::disarm) is called first.
#[derive(Deftly, Debug)]
#[derive_deftly(BombImpls)]
pub(crate) struct DropBomb {
    /// What state are we in
    status: Status,
}

/// Drop condition: for ensuring that a condition is true, on drop
///
/// Obtained from [`DropBombCondition::new_armed()`].
///
/// Instead of dropping this, you must call
/// `drop_bomb_disarm_assert!`
/// (or its internal function `disarm_assert()`.
// rustdoc can't manage to make a link to this crate-private macro or cfg-test item.
///
/// It will often be necessary to add `#[allow(dead_code)]`
/// on the `DropBombCondition` field of a containing type,
/// since outside tests, the `Drop` impl will usually be configured out,
/// and that's the only place this field is actually read.
///
/// # Panics
///
/// Panics (actually) if it is simply dropped.
#[derive(Deftly, Debug)]
#[derive_deftly(BombImpls)]
pub(crate) struct DropBombCondition {
    /// What state are we in
    #[allow(dead_code)] // not read outside tests
    status: Status,
}

/// Handle onto a simulated [`DropBomb`] or [`DropCondition`]
///
/// Can be used to tell whether the bomb "exploded"
/// (ie, whether `drop` would have panicked, if this had been a non-simulated bomb).
#[cfg(test)]
#[derive(Debug)]
pub(crate) struct SimulationHandle {
    exploded: Arc<AtomicBool>,
}

/// Unit token indicating that a simulated drop bomb did explode, and would have panicked
#[cfg(test)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) struct SimulationExploded;

//---------- internal types ----------

/// State of some kind of drop bomb
///
/// This type is inert; the caller is responsible for exploding or panicking.
#[derive(Debug)]
enum Status {
    /// This bomb is disarmed and will not panic.
    ///
    /// This is always the case outside `#[cfg(test)]`
    Disarmed,

    /// This bomb is armed.  It will (or may) panic on drop.
    #[cfg(test)]
    Armed,

    /// This bomb is armed, but we're running in simulation.
    #[cfg(test)]
    ArmedSimulated(SimulationHandle),
}

use Status as S;

//---------- DropBomb impls ----------

impl DropBomb {
    /// Disarm this bomb.
    ///
    /// It will no longer explode (panic) when dropped.
    pub(crate) fn disarm(&mut self) {
        self.status = S::Disarmed;
    }
}

#[cfg(test)]
impl DropStatus for DropBomb {
    fn drop_status(status: Status) {
        match status {
            S::Disarmed => {}
            S::Armed => panic!("DropBomb dropped without a previous call to .disarm()"),
            S::ArmedSimulated(handle) => handle.set_exploded(),
        }
    }
}

//---------- DropCondition impls ----------

/// Check the condition, and disarm the bomb
///
/// If `CONDITION` is true, disarms the bomb; otherwise, explodes (panics).
///
/// # Syntax
///
/// ```
/// drop_bomb_disarm_assert!(BOMB, CONDITION);
/// drop_bomb_disarm_assert!(BOMB, CONDITION, "FORMAT", FORMAT_ARGS..);
/// ```
///
/// where
///
///  * `BOMB: &mut DropCondition` (or something that derefs to that).
///  * `CONDITION: bool`
///
/// # Example
///
/// ```
/// # struct S { drop_bomb: DropCondition };
/// # impl S { fn f(&mut self) {
/// drop_bomb_disarm_assert!(self.drop_bomb, self.raw, Qty(0));
/// # } }
/// ```
///
/// # Explodes
///
/// Explodes unless the condition is satisfied.
//
// This macro has this long name because we can't do scoping of macro-rules macros.
#[cfg(test)] // Should not be used outside tests, since the drop impls should be conditional
macro_rules! drop_bomb_disarm_assert {
    { $bomb:expr, $condition:expr $(,)? } => {
        $bomb.disarm_assert(
            || $condition,
            format_args!(concat!("condition = ", stringify!($condition))),
        )
    };
    { $bomb:expr, $condition:expr, $fmt:literal $($rest:tt)* } => {
        $bomb.disarm_assert(
            || $condition,
            format_args!(concat!("condition = ", stringify!($condition), ": ", $fmt),
                         $($rest)*),
        )
    };
}

impl DropBombCondition {
    /// Check a condition, and disarm the bomb
    ///
    /// If `call()` returns true, disarms the bomb; otherwise, explodes (panics).
    ///
    /// # Explodes
    ///
    /// Explodes unless the condition is satisfied.
    #[inline]
    #[cfg(test)] // Should not be used outside tests, since the drop impls should be conditional
    pub(crate) fn disarm_assert(&mut self, call: impl FnOnce() -> bool, msg: fmt::Arguments) {
        match mem::replace(&mut self.status, S::Disarmed) {
            S::Disarmed => {
                // outside cfg(test), this is the usual path.
                // placate the compiler: we ignore all our arguments
                let _ = call;
                let _ = msg;

                #[cfg(test)]
                panic!("disarm_assert called more than once!");
            }
            #[cfg(test)]
            S::Armed => {
                if !call() {
                    panic!("drop condition violated: dropped, but condition is false: {msg}");
                }
            }
            #[cfg(test)]
            #[allow(clippy::print_stderr)]
            S::ArmedSimulated(handle) => {
                if !call() {
                    eprintln!("drop condition violated in simulation: {msg}");
                    handle.set_exploded();
                }
            }
        }
    }
}

/// Ideally, if you use this, your struct's other default values meet your drop condition!
impl Default for DropBombCondition {
    fn default() -> DropBombCondition {
        Self::new_armed()
    }
}

#[cfg(test)]
impl DropStatus for DropBombCondition {
    fn drop_status(status: Status) {
        assert!(matches!(status, S::Disarmed));
    }
}

//---------- SimulationHandle impls ----------

#[cfg(test)]
impl SimulationHandle {
    /// Determine whether a drop bomb would have been triggered
    ///
    /// If the corresponding [`DropBomb]` or [`DropCondition`]
    /// would have panicked (if we weren't simulating),
    /// returns `Err`.
    ///
    /// # Panics
    ///
    /// The corresponding `DropBomb` or `DropCondition` must have been dropped.
    /// Otherwise, calling `outcome` will (actually) panic.
    pub(crate) fn outcome(mut self) -> Result<(), SimulationExploded> {
        let panicked = Arc::into_inner(mem::take(&mut self.exploded))
            .expect("bomb has not yet been dropped")
            .into_inner();
        if panicked {
            Err(SimulationExploded)
        } else