|
5 | 5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
|
6 | 6 | // option. This file may not be copied, modified, or distributed
|
7 | 7 | // except according to those terms.
|
8 |
| -use core::convert::From; |
9 | 8 | use core::fmt;
|
10 | 9 | use core::num::NonZeroU32;
|
11 | 10 |
|
12 |
| -// A randomly-chosen 24-bit prefix for our codes |
13 |
| -pub(crate) const CODE_PREFIX: u32 = 0x57f4c500; |
14 |
| -const CODE_UNKNOWN: u32 = CODE_PREFIX | 0x00; |
15 |
| -const CODE_UNAVAILABLE: u32 = CODE_PREFIX | 0x01; |
16 |
| - |
17 |
| -/// The error type. |
| 11 | +/// A small and `no_std` compatible error type. |
18 | 12 | ///
|
19 |
| -/// This type is small and no-std compatible. |
| 13 | +/// The [`Error::raw_os_error()`] will indicate if the error is from the OS, and |
| 14 | +/// if so, which error code the OS gave the application. If such an error is |
| 15 | +/// encountered, please consult with your system documentation. |
20 | 16 | #[derive(Copy, Clone, Eq, PartialEq)]
|
21 |
| -pub struct Error(pub(crate) NonZeroU32); |
| 17 | +pub struct Error(NonZeroU32); |
| 18 | + |
| 19 | +// This NonZeroU32 in Error has enough room for two types of errors: |
| 20 | +// - OS Errors: in range [1, 1 << 31) (i.e. positive i32 values) |
| 21 | +// - Custom Errors: in range [1 << 31, 1 << 32) (in blocks of 1 << 16) |
| 22 | +const CUSTOM_START: u32 = 1 << 31; |
| 23 | +const BLOCK_SIZE: u32 = 1 << 16; |
22 | 24 |
|
23 | 25 | impl Error {
|
24 |
| - /// An unknown error. |
25 |
| - pub const UNKNOWN: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNKNOWN) }); |
| 26 | + /// Create a new error from a raw OS error number (errno). |
| 27 | + pub fn from_os_error(errno: i32) -> Self { |
| 28 | + assert!(errno > 0); |
| 29 | + Self(NonZeroU32::new(errno as u32).unwrap()) |
| 30 | + } |
26 | 31 |
|
27 |
| - /// No generator is available. |
28 |
| - pub const UNAVAILABLE: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNAVAILABLE) }); |
| 32 | + /// Crate a custom error in the provided block (group of 2^16 error codes). |
| 33 | + /// The provided block must not be negative, and block 0 is reserved for |
| 34 | + /// custom errors in the `getrandom` crate. |
| 35 | + pub fn custom_error(block: i16, code: u16) -> Self { |
| 36 | + assert!(block >= 0); |
| 37 | + let n = CUSTOM_START + (block as u32) * BLOCK_SIZE + (code as u32); |
| 38 | + Self(NonZeroU32::new(n).unwrap()) |
| 39 | + } |
29 | 40 |
|
30 |
| - /// Extract the error code. |
| 41 | + /// Extract the raw OS error code (if this error came from the OS) |
31 | 42 | ///
|
32 |
| - /// This may equal one of the codes defined in this library or may be a |
33 |
| - /// system error code. |
| 43 | + /// This method is identical to `std::io::Error::raw_os_error()`, except |
| 44 | + /// that it works in `no_std` contexts. If this method returns `None`, the |
| 45 | + /// error value can still be formatted via the `Diplay` implementation. |
| 46 | + pub fn raw_os_error(&self) -> Option<i32> { |
| 47 | + self.try_os_error().ok() |
| 48 | + } |
| 49 | + |
| 50 | + /// Extract the bare error code. |
34 | 51 | ///
|
35 |
| - /// One may attempt to format this error via the `Display` implementation. |
| 52 | + /// This code can either come from the underlying OS, or be a custom error. |
| 53 | + /// Use [`raw_os_error()`] to disambiguate. |
36 | 54 | pub fn code(&self) -> NonZeroU32 {
|
37 | 55 | self.0
|
38 | 56 | }
|
39 | 57 |
|
40 |
| - pub(crate) fn msg(&self) -> Option<&'static str> { |
41 |
| - if let Some(msg) = crate::imp::error_msg_inner(self.0) { |
42 |
| - Some(msg) |
| 58 | + /// Helper method for creating internal errors |
| 59 | + #[allow(dead_code)] |
| 60 | + pub(crate) fn internal(code: u16) -> Self { |
| 61 | + Self::custom_error(0, code) |
| 62 | + } |
| 63 | + |
| 64 | + /// Returns either the OS error or a (block, code) pair |
| 65 | + fn try_os_error(&self) -> Result<i32, (i16, u16)> { |
| 66 | + if self.0.get() < CUSTOM_START { |
| 67 | + Ok(self.0.get() as i32) |
43 | 68 | } else {
|
44 |
| - match *self { |
45 |
| - Error::UNKNOWN => Some("getrandom: unknown error"), |
46 |
| - Error::UNAVAILABLE => Some("getrandom: unavailable"), |
47 |
| - _ => None, |
48 |
| - } |
| 69 | + let offset = self.0.get() - CUSTOM_START; |
| 70 | + Err(((offset / BLOCK_SIZE) as i16, (offset % BLOCK_SIZE) as u16)) |
49 | 71 | }
|
50 | 72 | }
|
51 | 73 | }
|
52 | 74 |
|
| 75 | +#[cfg(any(unix, target_os = "redox"))] |
| 76 | +fn os_err_desc(errno: i32, buf: &mut [u8]) -> Option<&str> { |
| 77 | + let buf_ptr = buf.as_mut_ptr() as *mut libc::c_char; |
| 78 | + if unsafe { libc::strerror_r(errno, buf_ptr, buf.len()) } != 0 { |
| 79 | + return None; |
| 80 | + } |
| 81 | + |
| 82 | + // Take up to trailing null byte |
| 83 | + let idx = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); |
| 84 | + core::str::from_utf8(&buf[..idx]).ok() |
| 85 | +} |
| 86 | + |
| 87 | +#[cfg(not(any(unix, target_os = "redox")))] |
| 88 | +fn os_err_desc(_errno: i32, _buf: &mut [u8]) -> Option<&str> { |
| 89 | + None |
| 90 | +} |
| 91 | + |
53 | 92 | impl fmt::Debug for Error {
|
54 |
| - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
55 |
| - match self.msg() { |
56 |
| - Some(msg) => write!(f, "Error(\"{}\")", msg), |
57 |
| - None => write!(f, "Error(0x{:08X})", self.0), |
| 93 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 94 | + let mut dbg = f.debug_struct("Error"); |
| 95 | + match self.try_os_error() { |
| 96 | + Ok(errno) => { |
| 97 | + dbg.field("os_error", &errno); |
| 98 | + let mut buf = [0u8; 128]; |
| 99 | + if let Some(desc) = os_err_desc(errno, &mut buf) { |
| 100 | + dbg.field("description", &desc); |
| 101 | + } |
| 102 | + } |
| 103 | + Err((0, code)) => { |
| 104 | + dbg.field("internal_code", &code); |
| 105 | + if let Some(desc) = internal_desc(code) { |
| 106 | + dbg.field("description", &desc); |
| 107 | + } |
| 108 | + } |
| 109 | + Err((block, code)) => { |
| 110 | + dbg.field("block", &block); |
| 111 | + dbg.field("custom_code", &code); |
| 112 | + } |
58 | 113 | }
|
| 114 | + dbg.finish() |
59 | 115 | }
|
60 | 116 | }
|
61 | 117 |
|
62 | 118 | impl fmt::Display for Error {
|
63 |
| - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
64 |
| - match self.msg() { |
65 |
| - Some(msg) => write!(f, "{}", msg), |
66 |
| - None => write!(f, "getrandom: unknown code 0x{:08X}", self.0), |
| 119 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 120 | + match self.try_os_error() { |
| 121 | + Ok(errno) => { |
| 122 | + let mut buf = [0u8; 128]; |
| 123 | + match os_err_desc(errno, &mut buf) { |
| 124 | + Some(desc) => f.write_str(desc), |
| 125 | + None => write!(f, "OS Error: {}", errno), |
| 126 | + } |
| 127 | + } |
| 128 | + Err((0, code)) => match internal_desc(code) { |
| 129 | + Some(desc) => f.write_str(desc), |
| 130 | + None => write!(f, "Internal Error: {}", code), |
| 131 | + }, |
| 132 | + Err((block, code)) => write!(f, "Custom Error: block={}, code={}", block, code), |
67 | 133 | }
|
68 | 134 | }
|
69 | 135 | }
|
70 | 136 |
|
71 | 137 | impl From<NonZeroU32> for Error {
|
72 | 138 | fn from(code: NonZeroU32) -> Self {
|
73 |
| - Error(code) |
| 139 | + Self(code) |
74 | 140 | }
|
75 | 141 | }
|
76 | 142 |
|
77 |
| -impl From<&Error> for Error { |
78 |
| - fn from(error: &Error) -> Self { |
79 |
| - *error |
| 143 | +/// Internal Error constants |
| 144 | +pub(crate) const UNSUPPORTED: u16 = 0; |
| 145 | +pub(crate) const UNKNOWN_IO_ERROR: u16 = 1; |
| 146 | +pub(crate) const SEC_RANDOM_FAILED: u16 = 2; |
| 147 | +pub(crate) const RTL_GEN_RANDOM_FAILED: u16 = 3; |
| 148 | +pub(crate) const FAILED_RDRAND: u16 = 4; |
| 149 | +pub(crate) const NO_RDRAND: u16 = 5; |
| 150 | +pub(crate) const BINDGEN_CRYPTO_UNDEF: u16 = 6; |
| 151 | +pub(crate) const BINDGEN_GRV_UNDEF: u16 = 7; |
| 152 | +pub(crate) const STDWEB_NO_RNG: u16 = 8; |
| 153 | +pub(crate) const STDWEB_RNG_FAILED: u16 = 9; |
| 154 | + |
| 155 | +fn internal_desc(code: u16) -> Option<&'static str> { |
| 156 | + match code { |
| 157 | + UNSUPPORTED => Some("getrandom: this target is not supported"), |
| 158 | + UNKNOWN_IO_ERROR => Some("Unknown std::io::Error"), |
| 159 | + SEC_RANDOM_FAILED => Some("SecRandomCopyBytes: call failed"), |
| 160 | + RTL_GEN_RANDOM_FAILED => Some("RtlGenRandom: call failed"), |
| 161 | + FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"), |
| 162 | + NO_RDRAND => Some("RDRAND: instruction not supported"), |
| 163 | + BINDGEN_CRYPTO_UNDEF => Some("wasm-bindgen: self.crypto is undefined"), |
| 164 | + BINDGEN_GRV_UNDEF => Some("wasm-bindgen: crypto.getRandomValues is undefined"), |
| 165 | + STDWEB_NO_RNG => Some("stdweb: no randomness source available"), |
| 166 | + STDWEB_RNG_FAILED => Some("stdweb: failed to get randomness"), |
| 167 | + _ => None, |
80 | 168 | }
|
81 | 169 | }
|
82 | 170 |
|
|
0 commit comments