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
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Mutex type whose methods panic rather than returning error in case of
//! poison.
//!
//! The Mutex type in this module wraps the standard library Mutex and mirrors
//! the same methods, except that they panic where the standard library would
//! return a PoisonError. This API codifies our error handling strategy around
//! poisoned mutexes in crosvm.
//!
//! - Crosvm releases are built with panic=abort so poisoning never occurs. A panic while a mutex is
//!   held (or ever) takes down the entire process. Thus we would like for code not to have to
//!   consider the possibility of poison.
//!
//! - We could ask developers to always write `.lock().unwrap()` on a standard library mutex.
//!   However, we would like to stigmatize the use of unwrap. It is confusing to permit unwrap but
//!   only on mutex lock results. During code review it may not always be obvious whether a
//!   particular unwrap is unwrapping a mutex lock result or a different error that should be
//!   handled in a more principled way.
//!
//! Developers should feel free to use sync::Mutex anywhere in crosvm that they
//! would otherwise be using std::sync::Mutex.

use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::sync::Mutex as StdMutex;
use std::sync::MutexGuard;
use std::sync::TryLockError;

/// A mutual exclusion primitive useful for protecting shared data.
#[derive(Default)]
pub struct Mutex<T: ?Sized> {
    std: StdMutex<T>,
}

impl<T> Mutex<T> {
    /// Creates a new mutex in an unlocked state ready for use.
    pub const fn new(value: T) -> Mutex<T> {
        Mutex {
            std: StdMutex::new(value),
        }
    }

    /// Consumes this mutex, returning the underlying data.
    pub fn into_inner(self) -> T {
        match self.std.into_inner() {
            Ok(value) => value,
            Err(_) => panic!("mutex is poisoned"),
        }
    }
}

impl<T: ?Sized> Mutex<T> {
    /// Acquires a mutex, blocking the current thread until it is able to do so.
    ///
    /// This function will block the local thread until it is available to
    /// acquire the mutex. Upon returning, the thread is the only thread with
    /// the lock held. An RAII guard is returned to allow scoped unlock of the
    /// lock. When the guard goes out of scope, the mutex will be unlocked.
    pub fn lock(&self) -> MutexGuard<T> {
        match self.std.lock() {
            Ok(guard) => guard,
            Err(_) => panic!("mutex is poisoned"),
        }
    }

    /// Attempts to acquire this lock.
    ///
    /// If the lock could not be acquired at this time, then Err is returned.
    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
    /// guard is dropped.
    ///
    /// This function does not block.
    pub fn try_lock(&self) -> Result<MutexGuard<T>, WouldBlock> {
        match self.std.try_lock() {
            Ok(guard) => Ok(guard),
            Err(TryLockError::Poisoned(_)) => panic!("mutex is poisoned"),
            Err(TryLockError::WouldBlock) => Err(WouldBlock),
        }
    }

    /// Returns a mutable reference to the underlying data.
    ///
    /// Since this call borrows the Mutex mutably, no actual locking needs to
    /// take place -- the mutable borrow statically guarantees no locks exist.
    pub fn get_mut(&mut self) -> &mut T {
        match self.std.get_mut() {
            Ok(value) => value,
            Err(_) => panic!("mutex is poisoned"),
        }
    }
}

impl<T> From<T> for Mutex<T> {
    fn from(value: T) -> Self {
        Mutex {
            std: StdMutex::from(value),
        }
    }
}

impl<T: ?Sized + Debug> Debug for Mutex<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.std, formatter)
    }
}

/// The lock could not be acquired at this time because the operation would
/// otherwise block.
///
/// Error returned by Mutex::try_lock.
#[derive(Debug)]
pub struct WouldBlock;

impl Display for WouldBlock {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&TryLockError::WouldBlock::<()>, formatter)
    }
}

impl std::error::Error for WouldBlock {}