1 //! Implementation of `errno` functionality for WASI.
2 //!
3 //! Adapted from `unix.rs`.
4 
5 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
6 // file at the top-level directory of this distribution and at
7 // http://rust-lang.org/COPYRIGHT.
8 //
9 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
10 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
11 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
12 // option. This file may not be copied, modified, or distributed
13 // except according to those terms.
14 
15 use core::str;
16 use libc::{self, c_int, size_t, strerror_r, strlen};
17 
18 use crate::Errno;
19 
from_utf8_lossy(input: &[u8]) -> &str20 fn from_utf8_lossy(input: &[u8]) -> &str {
21     match str::from_utf8(input) {
22         Ok(valid) => valid,
23         Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) },
24     }
25 }
26 
with_description<F, T>(err: Errno, callback: F) -> T where F: FnOnce(Result<&str, Errno>) -> T,27 pub fn with_description<F, T>(err: Errno, callback: F) -> T
28 where
29     F: FnOnce(Result<&str, Errno>) -> T,
30 {
31     let mut buf = [0u8; 1024];
32     let c_str = unsafe {
33         let rc = strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t);
34         if rc != 0 {
35             let fm_err = Errno(rc);
36             if fm_err != Errno(libc::ERANGE) {
37                 return callback(Err(fm_err));
38             }
39         }
40         let c_str_len = strlen(buf.as_ptr() as *const _);
41         &buf[..c_str_len]
42     };
43     callback(Ok(from_utf8_lossy(c_str)))
44 }
45 
46 pub const STRERROR_NAME: &str = "strerror_r";
47 
errno() -> Errno48 pub fn errno() -> Errno {
49     unsafe { Errno(*__errno_location()) }
50 }
51 
set_errno(Errno(new_errno): Errno)52 pub fn set_errno(Errno(new_errno): Errno) {
53     unsafe {
54         *__errno_location() = new_errno;
55     }
56 }
57 
58 extern "C" {
__errno_location() -> *mut c_int59     fn __errno_location() -> *mut c_int;
60 }
61