|
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. |
| 12 | +/// |
| 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. |
18 | 16 | ///
|
19 |
| -/// This type is small and no-std compatible. |
| 17 | +/// Internally this type is a NonZeroU32, with certain values reserved for |
| 18 | +/// certain purposes, see [`Error::INTERNAL_START`] and [`Error::CUSTOM_START`]. |
20 | 19 | #[derive(Copy, Clone, Eq, PartialEq)]
|
21 |
| -pub struct Error(pub(crate) NonZeroU32); |
| 20 | +pub struct Error(NonZeroU32); |
22 | 21 |
|
23 | 22 | impl Error {
|
24 |
| - /// An unknown error. |
25 |
| - pub const UNKNOWN: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNKNOWN) }); |
| 23 | + #[deprecated(since = "0.1.7")] |
| 24 | + pub const UNKNOWN: Error = UNSUPPORTED; |
| 25 | + #[deprecated(since = "0.1.7")] |
| 26 | + pub const UNAVAILABLE: Error = UNSUPPORTED; |
| 27 | + |
| 28 | + /// Codes below this point represent OS Errors (i.e. positive i32 values). |
| 29 | + /// Codes at or above this point, but below [`Error::CUSTOM_START`] are |
| 30 | + /// reserved for use by the `rand` and `getrandom` crates. |
| 31 | + pub const INTERNAL_START: u32 = 1 << 31; |
26 | 32 |
|
27 |
| - /// No generator is available. |
28 |
| - pub const UNAVAILABLE: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNAVAILABLE) }); |
| 33 | + /// Codes at or above this point can be used by users to define their own |
| 34 | + /// custom errors. |
| 35 | + pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30); |
29 | 36 |
|
30 |
| - /// Extract the error code. |
| 37 | + /// Extract the raw OS error code (if this error came from the OS) |
31 | 38 | ///
|
32 |
| - /// This may equal one of the codes defined in this library or may be a |
33 |
| - /// system error code. |
| 39 | + /// This method is identical to `std::io::Error::raw_os_error()`, except |
| 40 | + /// that it works in `no_std` contexts. If this method returns `None`, the |
| 41 | + /// error value can still be formatted via the `Diplay` implementation. |
| 42 | + #[inline] |
| 43 | + pub fn raw_os_error(&self) -> Option<i32> { |
| 44 | + if self.0.get() < Self::INTERNAL_START { |
| 45 | + Some(self.0.get() as i32) |
| 46 | + } else { |
| 47 | + None |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /// Extract the bare error code. |
34 | 52 | ///
|
35 |
| - /// One may attempt to format this error via the `Display` implementation. |
| 53 | + /// This code can either come from the underlying OS, or be a custom error. |
| 54 | + /// Use [`Error::raw_os_error()`] to disambiguate. |
| 55 | + #[inline] |
36 | 56 | pub fn code(&self) -> NonZeroU32 {
|
37 | 57 | self.0
|
38 | 58 | }
|
| 59 | +} |
39 | 60 |
|
40 |
| - pub(crate) fn msg(&self) -> Option<&'static str> { |
41 |
| - if let Some(msg) = crate::imp::error_msg_inner(self.0) { |
42 |
| - Some(msg) |
43 |
| - } else { |
44 |
| - match *self { |
45 |
| - Error::UNKNOWN => Some("getrandom: unknown error"), |
46 |
| - Error::UNAVAILABLE => Some("getrandom: unavailable"), |
47 |
| - _ => None, |
48 |
| - } |
49 |
| - } |
| 61 | +#[cfg(any(unix, target_os = "redox"))] |
| 62 | +fn os_err_desc(errno: i32, buf: &mut [u8]) -> Option<&str> { |
| 63 | + let buf_ptr = buf.as_mut_ptr() as *mut libc::c_char; |
| 64 | + if unsafe { libc::strerror_r(errno, buf_ptr, buf.len()) } != 0 { |
| 65 | + return None; |
50 | 66 | }
|
| 67 | + |
| 68 | + // Take up to trailing null byte |
| 69 | + let idx = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); |
| 70 | + core::str::from_utf8(&buf[..idx]).ok() |
| 71 | +} |
| 72 | + |
| 73 | +#[cfg(not(any(unix, target_os = "redox")))] |
| 74 | +fn os_err_desc(_errno: i32, _buf: &mut [u8]) -> Option<&str> { |
| 75 | + None |
51 | 76 | }
|
52 | 77 |
|
53 | 78 | 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), |
| 79 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 80 | + let mut dbg = f.debug_struct("Error"); |
| 81 | + if let Some(errno) = self.raw_os_error() { |
| 82 | + dbg.field("os_error", &errno); |
| 83 | + let mut buf = [0u8; 128]; |
| 84 | + if let Some(desc) = os_err_desc(errno, &mut buf) { |
| 85 | + dbg.field("description", &desc); |
| 86 | + } |
| 87 | + } else if let Some(desc) = internal_desc(*self) { |
| 88 | + dbg.field("internal_code", &self.0.get()); |
| 89 | + dbg.field("description", &desc); |
| 90 | + } else { |
| 91 | + dbg.field("unknown_code", &self.0.get()); |
58 | 92 | }
|
| 93 | + dbg.finish() |
59 | 94 | }
|
60 | 95 | }
|
61 | 96 |
|
62 | 97 | 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), |
| 98 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 99 | + if let Some(errno) = self.raw_os_error() { |
| 100 | + let mut buf = [0u8; 128]; |
| 101 | + match os_err_desc(errno, &mut buf) { |
| 102 | + Some(desc) => f.write_str(desc), |
| 103 | + None => write!(f, "OS Error: {}", errno), |
| 104 | + } |
| 105 | + } else if let Some(desc) = internal_desc(*self) { |
| 106 | + f.write_str(desc) |
| 107 | + } else { |
| 108 | + write!(f, "Unknown Error: {}", self.0.get()) |
67 | 109 | }
|
68 | 110 | }
|
69 | 111 | }
|
70 | 112 |
|
71 | 113 | impl From<NonZeroU32> for Error {
|
72 | 114 | fn from(code: NonZeroU32) -> Self {
|
73 |
| - Error(code) |
| 115 | + Self(code) |
74 | 116 | }
|
75 | 117 | }
|
76 | 118 |
|
77 |
| -impl From<&Error> for Error { |
78 |
| - fn from(error: &Error) -> Self { |
79 |
| - *error |
| 119 | +// TODO: Convert to a function when min_version >= 1.33 |
| 120 | +macro_rules! internal_error { |
| 121 | + ($n:expr) => { |
| 122 | + Error(unsafe { NonZeroU32::new_unchecked(Error::INTERNAL_START + $n as u16 as u32) }) |
| 123 | + }; |
| 124 | +} |
| 125 | + |
| 126 | +/// Internal Error constants |
| 127 | +pub(crate) const UNSUPPORTED: Error = internal_error!(0); |
| 128 | +pub(crate) const ERRNO_NOT_POSITIVE: Error = internal_error!(1); |
| 129 | +pub(crate) const UNKNOWN_IO_ERROR: Error = internal_error!(2); |
| 130 | +pub(crate) const SEC_RANDOM_FAILED: Error = internal_error!(3); |
| 131 | +pub(crate) const RTL_GEN_RANDOM_FAILED: Error = internal_error!(4); |
| 132 | +pub(crate) const FAILED_RDRAND: Error = internal_error!(5); |
| 133 | +pub(crate) const NO_RDRAND: Error = internal_error!(6); |
| 134 | +pub(crate) const BINDGEN_CRYPTO_UNDEF: Error = internal_error!(7); |
| 135 | +pub(crate) const BINDGEN_GRV_UNDEF: Error = internal_error!(8); |
| 136 | +pub(crate) const STDWEB_NO_RNG: Error = internal_error!(9); |
| 137 | +pub(crate) const STDWEB_RNG_FAILED: Error = internal_error!(10); |
| 138 | + |
| 139 | +fn internal_desc(error: Error) -> Option<&'static str> { |
| 140 | + match error { |
| 141 | + UNSUPPORTED => Some("getrandom: this target is not supported"), |
| 142 | + ERRNO_NOT_POSITIVE => Some("errno: did not return a positive value"), |
| 143 | + UNKNOWN_IO_ERROR => Some("Unknown std::io::Error"), |
| 144 | + SEC_RANDOM_FAILED => Some("SecRandomCopyBytes: call failed"), |
| 145 | + RTL_GEN_RANDOM_FAILED => Some("RtlGenRandom: call failed"), |
| 146 | + FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"), |
| 147 | + NO_RDRAND => Some("RDRAND: instruction not supported"), |
| 148 | + BINDGEN_CRYPTO_UNDEF => Some("wasm-bindgen: self.crypto is undefined"), |
| 149 | + BINDGEN_GRV_UNDEF => Some("wasm-bindgen: crypto.getRandomValues is undefined"), |
| 150 | + STDWEB_NO_RNG => Some("stdweb: no randomness source available"), |
| 151 | + STDWEB_RNG_FAILED => Some("stdweb: failed to get randomness"), |
| 152 | + _ => None, |
80 | 153 | }
|
81 | 154 | }
|
82 | 155 |
|
|
0 commit comments