mundane/boringssl/
abort.rs

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

//! Macros and functions that abort instead of unwinding.
//!
//! Writing `unsafe` code which retains memory safety in the face of unwinding
//! is [notoriously
//! difficult](https://doc.rust-lang.org/nightly/nomicon/exception-safety.html).
//! This module provides panic-related macros and functions that abort rather
//! than unwind. These are used in place of unwinding-based macros and functions
//! so that we can avoid the high probability of us getting unwind-safe code
//! wrong.

use std::fmt::Debug;

macro_rules! assert_abort {
    ($cond:expr) => ({
        let cond = $cond;
        let cond_str = stringify!($cond);
        assert_abort!(cond, "{}", cond_str);
    });
    ($cond:expr,) => ({
        assert_abort!($cond);
    });
    ($cond:expr, $msg:expr, $($arg:tt)*) => ({
        if !($cond) {
            panic_abort!(concat!("assertion failed: ", $msg), $($arg)*);
        }
    });
}

macro_rules! assert_abort_eq {
    ($left:expr, $right:expr) => ({
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic_abort!(r#"assertion failed: `(left == right)`
  left: `{:?}`,
 right: `{:?}`"#, left_val, right_val)
                }
            }
        }
    });
    ($left:expr, $right:expr,) => ({
        assert_eq!($left, $right)
    });
    ($left:expr, $right:expr, $($arg:tt)+) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic_abort!(r#"assertion failed: `(left == right)`
  left: `{:?}`,
 right: `{:?}`: {}"#, left_val, right_val,
                           format_args!($($arg)+))
                }
            }
        }
    });
}

#[allow(unused)]
macro_rules! unimplemented_abort {
    () => {{
        panic_abort!("not yet implemented")
    }};
}

macro_rules! unreachable_abort {
    () => {{
        panic_abort!("internal error: entered unreachable code")
    }};
}

macro_rules! panic_abort {
    () => ({
        panic_abort!("explicit panic")
    });
    ($msg:expr) => ({
        eprintln!("{}", $msg);
        ::std::process::abort();
    });
    ($msg:expr,) => ({
        panic_abort!($msg)
    });
    ($fmt:expr, $($arg:tt)+) => ({
        panic_abort!(format!($fmt, $($arg)+));
    });
}

// Redefine normal panic/assert macros so their use will cause a compiler error.

#[allow(unused)]
macro_rules! panic {
    ($($x:tt)*) => {
        compile_error!("use panic_abort! instead of panic! in boringssl module")
    };
}

#[allow(unused)]
macro_rules! assert {
    ($($x:tt)*) => {
        compile_error!("use assert_abort! instead of assert! in boringssl module")
    };
}

#[allow(unused)]
macro_rules! assert_eq {
    ($($x:tt)*) => {
        compile_error!("use assert_abort_eq! instead of assert_eq! in boringssl module")
    };
}

#[allow(unused)]
macro_rules! assert_ne {
    ($($x:tt)*) => {
        compile_error!("use assert_abort_ne! instead of assert_ne! in boringssl module")
    };
}

#[allow(unused)]
macro_rules! unimplemented {
    ($($x:tt)*) => {
        compile_error!("use unimplemented_abort! instead of unimplemented! in boringssl module")
    };
}

#[allow(unused)]
macro_rules! unreachable {
    ($($x:tt)*) => {
        compile_error!("use unreachable_abort! instead of unreachable! in boringssl module")
    };
}

// unwrap and expect

// TODO(joshlf): Is there a way (maybe with clippy) that we can cause warnings
// or errors if this module ever uses unwrap or expect?

pub trait UnwrapAbort {
    type Item;

    fn unwrap_abort(self) -> Self::Item;
    fn expect_abort(self, msg: &str) -> Self::Item;
}

// The implementations for Option and Result are adapted from the Rust standard library.
impl<T> UnwrapAbort for Option<T> {
    type Item = T;

    fn unwrap_abort(self) -> T {
        match self {
            Some(val) => val,
            None => panic_abort!("called `Option::unwrap_abort()` on a `None` value"),
        }
    }

    fn expect_abort(self, msg: &str) -> T {
        // This is a separate function to reduce the code size of alloc_expect itself
        #[inline(never)]
        #[cold]
        fn failed(msg: &str) -> ! {
            panic_abort!("{}", msg);
        }

        match self {
            Some(val) => val,
            None => failed(msg),
        }
    }
}

impl<T, E: Debug> UnwrapAbort for Result<T, E> {
    type Item = T;

    fn unwrap_abort(self) -> T {
        match self {
            Ok(val) => val,
            Err(err) => {
                result_unwrap_failed("called `Result::unwrap_abort()` on an `Err` value", err)
            }
        }
    }

    fn expect_abort(self, msg: &str) -> T {
        match self {
            Ok(val) => val,
            Err(err) => result_unwrap_failed(msg, err),
        }
    }
}

// This is a separate function to reduce the code size of alloc_{expect,unwrap}
#[inline(never)]
#[cold]
fn result_unwrap_failed<E: Debug>(msg: &str, err: E) -> ! {
    panic_abort!("{}: {:?}", msg, err)
}