Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch from winapi to windows-sys #55

Merged
merged 2 commits into from
Dec 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
rust: [stable, nightly, 1.36.0]
rust: [stable, nightly, 1.48]
exclude:
# TODO(#52): Investigate why this is broken
- os: macos-latest
rust: 1.36.0
rust: 1.48
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
Expand Down
8 changes: 5 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@

- Add formatting with `#![no_std]`
[#44](https://github.com/lambda-fairy/rust-errno/pull/44)

- Update minimum Rust version to 1.36
[#48](https://github.com/lambda-fairy/rust-errno/pull/48)

- Switch from `winapi` to `windows-sys` [#55](https://github.com/lambda-fairy/rust-errno/pull/55)

- Update minimum Rust version to 1.48
[#48](https://github.com/lambda-fairy/rust-errno/pull/48) [#55](https://github.com/lambda-fairy/rust-errno/pull/55)

# [0.2.8] - 2021-10-27

Expand Down
8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ categories = ["no-std", "os"]
[target.'cfg(unix)'.dependencies]
libc = "0.2"

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["errhandlingapi", "minwindef", "ntdef", "winbase"] }
[target.'cfg(windows)'.dependencies.windows-sys]
version = "0.42"
features = [
"Win32_Foundation",
"Win32_System_Diagnostics_Debug",
]

[target.'cfg(target_os="dragonfly")'.dependencies]
errno-dragonfly = "0.1.1"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# errno [![CI](https://github.com/lambda-fairy/rust-errno/actions/workflows/main.yml/badge.svg)](https://github.com/lambda-fairy/rust-errno/actions/workflows/main.yml) [![Cargo](https://img.shields.io/crates/v/errno.svg)](https://crates.io/crates/errno)

Cross-platform interface to the [`errno`][errno] variable. Works on Rust 1.36 or newer.
Cross-platform interface to the [`errno`][errno] variable. Works on Rust 1.48 or newer.

Documentation is available at <https://docs.rs/errno>.

Expand Down
8 changes: 4 additions & 4 deletions src/hermit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

use Errno;

pub fn with_description<F, T>(_err: Errno, callback: F) -> T where
F: FnOnce(Result<&str, Errno>) -> T
pub fn with_description<F, T>(_err: Errno, callback: F) -> T
where
F: FnOnce(Result<&str, Errno>) -> T,
{
callback(Ok("unknown error"))
}
Expand All @@ -28,5 +29,4 @@ pub fn errno() -> Errno {
Errno(0)
}

pub fn set_errno(_: Errno) {
}
pub fn set_errno(_: Errno) {}
39 changes: 28 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@
#[cfg(feature = "std")]
extern crate core;

#[cfg(unix)] extern crate libc;
#[cfg(windows)] extern crate winapi;
#[cfg(target_os = "dragonfly")] extern crate errno_dragonfly;
#[cfg(target_os = "wasi")] extern crate libc;
#[cfg(target_os = "hermit")] extern crate libc;
#[cfg(target_os = "dragonfly")]
extern crate errno_dragonfly;
#[cfg(unix)]
extern crate libc;
#[cfg(target_os = "wasi")]
extern crate libc;
#[cfg(target_os = "hermit")]
extern crate libc;
#[cfg(windows)]
extern crate windows_sys;

#[cfg_attr(unix, path = "unix.rs")]
#[cfg_attr(windows, path = "windows.rs")]
Expand All @@ -37,9 +42,9 @@ mod sys;

use core::fmt;
#[cfg(feature = "std")]
use std::io;
#[cfg(feature = "std")]
use std::error::Error;
#[cfg(feature = "std")]
use std::io;

/// Wraps a platform-specific error code.
///
Expand Down Expand Up @@ -68,8 +73,12 @@ impl fmt::Display for Errno {
sys::with_description(*self, |desc| match desc {
Ok(desc) => fmt.write_str(&desc),
Err(fm_err) => write!(
fmt, "OS error {} ({} returned error {})",
self.0, sys::STRERROR_NAME, fm_err.0),
fmt,
"OS error {} ({} returned error {})",
self.0,
sys::STRERROR_NAME,
fm_err.0
),
})
}
}
Expand Down Expand Up @@ -134,13 +143,21 @@ fn check_description() {
"Operation not permitted"
};

let errno_code = if cfg!(target_os = "haiku") { -2147483633 } else { 1 };
let errno_code = if cfg!(target_os = "haiku") {
-2147483633
} else {
1
};
set_errno(Errno(errno_code));

assert_eq!(errno().to_string(), expect);
assert_eq!(
format!("{:?}", errno()),
format!("Errno {{ code: {}, description: Some({:?}) }}", errno_code, expect));
format!(
"Errno {{ code: {}, description: Some({:?}) }}",
errno_code, expect
)
);
}

#[cfg(feature = "std")]
Expand Down
58 changes: 29 additions & 29 deletions src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,22 @@
// except according to those terms.

use core::str;
use libc::{self, c_char, c_int, strlen};
#[cfg(target_os = "dragonfly")]
use errno_dragonfly::errno_location;
use libc::{self, c_char, c_int, strlen};

use Errno;

fn from_utf8_lossy(input: &[u8]) -> &str {
match str::from_utf8(input) {
Ok(valid) => valid,
Err(error) => unsafe { str::from_utf8_unchecked(&input[.. error.valid_up_to()]) },
Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) },
}
}

pub fn with_description<F, T>(err: Errno, callback: F) -> T where
F: FnOnce(Result<&str, Errno>) -> T
pub fn with_description<F, T>(err: Errno, callback: F) -> T
where
F: FnOnce(Result<&str, Errno>) -> T,
{
let mut buf = [0u8; 1024];
let c_str = unsafe {
Expand All @@ -38,17 +39,15 @@ pub fn with_description<F, T>(err: Errno, callback: F) -> T where
}
}
let c_str_len = strlen(buf.as_ptr() as *const _);
&buf[.. c_str_len]
&buf[..c_str_len]
};
callback(Ok(from_utf8_lossy(c_str)))
}

pub const STRERROR_NAME: &'static str = "strerror_r";

pub fn errno() -> Errno {
unsafe {
Errno(*errno_location())
}
unsafe { Errno(*errno_location()) }
}

pub fn set_errno(Errno(errno): Errno) {
Expand All @@ -57,29 +56,30 @@ pub fn set_errno(Errno(errno): Errno) {
}
}

extern {
extern "C" {
#[cfg(not(target_os = "dragonfly"))]
#[cfg_attr(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"),
link_name = "__error")]
#[cfg_attr(any(target_os = "openbsd",
target_os = "netbsd",
target_os = "bitrig",
target_os = "android"),
link_name = "__errno")]
#[cfg_attr(any(target_os = "solaris",
target_os = "illumos"),
link_name = "___errno")]
#[cfg_attr(target_os = "haiku",
link_name = "_errnop")]
#[cfg_attr(target_os = "linux",
link_name = "__errno_location")]
#[cfg_attr(target_os = "aix",
link_name = "_Errno")]
#[cfg_attr(
any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
link_name = "__error"
)]
#[cfg_attr(
any(
target_os = "openbsd",
target_os = "netbsd",
target_os = "bitrig",
target_os = "android"
),
link_name = "__errno"
)]
#[cfg_attr(
any(target_os = "solaris", target_os = "illumos"),
link_name = "___errno"
)]
#[cfg_attr(target_os = "haiku", link_name = "_errnop")]
#[cfg_attr(target_os = "linux", link_name = "__errno_location")]
#[cfg_attr(target_os = "aix", link_name = "_Errno")]
fn errno_location() -> *mut c_int;

#[cfg_attr(target_os = "linux", link_name = "__xpg_strerror_r")]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
}
18 changes: 8 additions & 10 deletions src/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ use Errno;
fn from_utf8_lossy(input: &[u8]) -> &str {
match str::from_utf8(input) {
Ok(valid) => valid,
Err(error) => unsafe { str::from_utf8_unchecked(&input[.. error.valid_up_to()]) },
Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) },
}
}

pub fn with_description<F, T>(err: Errno, callback: F) -> T where
F: FnOnce(Result<&str, Errno>) -> T
pub fn with_description<F, T>(err: Errno, callback: F) -> T
where
F: FnOnce(Result<&str, Errno>) -> T,
{
let mut buf = [0u8; 1024];
let c_str = unsafe {
Expand All @@ -36,7 +37,7 @@ pub fn with_description<F, T>(err: Errno, callback: F) -> T where
}
}
let c_str_len = strlen(buf.as_ptr() as *const _);
&buf[.. c_str_len]
&buf[..c_str_len]
};
callback(Ok(from_utf8_lossy(c_str)))
}
Expand All @@ -45,9 +46,7 @@ pub const STRERROR_NAME: &'static str = "strerror_r";

pub fn errno() -> Errno {
// libc_errno is thread-local, so simply read its value.
unsafe {
Errno(libc_errno)
}
unsafe { Errno(libc_errno) }
}

pub fn set_errno(Errno(new_errno): Errno) {
Expand All @@ -57,11 +56,10 @@ pub fn set_errno(Errno(new_errno): Errno) {
}
}

extern {
extern "C" {
#[thread_local]
#[link_name = "errno"]
static mut libc_errno: c_int;

fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
}
53 changes: 28 additions & 25 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,48 @@
use core::char::{self, REPLACEMENT_CHARACTER};
use core::ptr;
use core::str;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::WCHAR;
use winapi::um::winbase::{FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS};
use windows_sys::Win32::Foundation::{GetLastError, SetLastError, WIN32_ERROR};
use windows_sys::Win32::System::Diagnostics::Debug::{
FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS,
};

use Errno;

fn from_utf16_lossy<'a>(input: &[u16], output: &'a mut [u8]) -> &'a str {
let mut output_len = 0;
for c in char::decode_utf16(input.iter().copied().take_while(|&x| x != 0)).map(|x| x.unwrap_or(REPLACEMENT_CHARACTER)) {
for c in char::decode_utf16(input.iter().copied().take_while(|&x| x != 0))
.map(|x| x.unwrap_or(REPLACEMENT_CHARACTER))
{
let c_len = c.len_utf8();
if c_len > output.len() - output_len { break; }
c.encode_utf8(&mut output[output_len ..]);
if c_len > output.len() - output_len {
break;
}
c.encode_utf8(&mut output[output_len..]);
output_len += c_len;
}
unsafe { str::from_utf8_unchecked(&output[.. output_len]) }
unsafe { str::from_utf8_unchecked(&output[..output_len]) }
}

pub fn with_description<F, T>(err: Errno, callback: F) -> T where
F: FnOnce(Result<&str, Errno>) -> T
pub fn with_description<F, T>(err: Errno, callback: F) -> T
where
F: FnOnce(Result<&str, Errno>) -> T,
{
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let lang_id = 0x0800 as DWORD;
let lang_id = 0x0800_u32;

let mut buf = [0 as WCHAR; 2048];
let mut buf = [0u16; 2048];

unsafe {
let res = ::winapi::um::winbase::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
err.0 as DWORD,
lang_id,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null_mut());
let res = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
err.0 as u32,
lang_id,
buf.as_mut_ptr(),
buf.len() as u32,
ptr::null_mut(),
);
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like lang_id
let fm_err = errno();
Expand All @@ -67,13 +74,9 @@ pub fn with_description<F, T>(err: Errno, callback: F) -> T where
pub const STRERROR_NAME: &'static str = "FormatMessageW";

pub fn errno() -> Errno {
unsafe {
Errno(::winapi::um::errhandlingapi::GetLastError() as i32)
}
unsafe { Errno(GetLastError() as i32) }
}

pub fn set_errno(Errno(errno): Errno) {
unsafe {
::winapi::um::errhandlingapi::SetLastError(errno as DWORD)
}
unsafe { SetLastError(errno as WIN32_ERROR) }
}