diff options
author | DongHun Kwak <dh0128.kwak@samsung.com> | 2023-03-02 10:29:40 +0900 |
---|---|---|
committer | DongHun Kwak <dh0128.kwak@samsung.com> | 2023-03-02 10:29:40 +0900 |
commit | af00139639fda4e1c5e8c78ddf7262e8d79beaad (patch) | |
tree | 3004eab9bbc06bf84c2be74ad2e3941eab006e92 | |
download | rust-errno-af00139639fda4e1c5e8c78ddf7262e8d79beaad.tar.gz rust-errno-af00139639fda4e1c5e8c78ddf7262e8d79beaad.tar.bz2 rust-errno-af00139639fda4e1c5e8c78ddf7262e8d79beaad.zip |
Import errno 0.3.0upstream/0.3.0upstream
-rw-r--r-- | .cargo_vcs_info.json | 6 | ||||
-rw-r--r-- | .github/dependabot.yml | 10 | ||||
-rw-r--r-- | .github/workflows/main.yml | 74 | ||||
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | CHANGELOG.md | 30 | ||||
-rw-r--r-- | Cargo.toml | 49 | ||||
-rw-r--r-- | Cargo.toml.orig | 36 | ||||
-rw-r--r-- | LICENSE-APACHE | 201 | ||||
-rw-r--r-- | LICENSE-MIT | 25 | ||||
-rw-r--r-- | README.md | 62 | ||||
-rw-r--r-- | clippy.toml | 1 | ||||
-rw-r--r-- | src/hermit.rs | 32 | ||||
-rw-r--r-- | src/lib.rs | 156 | ||||
-rw-r--r-- | src/unix.rs | 85 | ||||
-rw-r--r-- | src/wasi.rs | 60 | ||||
-rw-r--r-- | src/windows.rs | 81 |
16 files changed, 910 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..487400f --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "e1882701f6d21bd9f45c2941a85416c59fa019ac" + }, + "path_in_vcs": "" +}
\ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..98e44ee --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "weekly" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..9ee02b1 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,74 @@ +on: + push: + branches: + - main + pull_request: + schedule: + - cron: '5 21 * * 5' + workflow_dispatch: + +name: CI + +jobs: + test: + name: Test + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + rust: [stable, nightly, '1.48'] + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - name: Install toolchain + uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + # Workaround link failures if XCode 14 is combined with Rust <= 1.53 + - name: Downgrade to XCode 13 + if: ${{ matrix.os == 'macos-latest' && matrix.rust == '1.48' }} + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: '13' + - name: Setup cache + uses: Swatinem/rust-cache@v2 + - name: Test (no features) + run: cargo test --no-default-features + - name: Test (all features) + run: cargo test --all-features + + + wasi: + name: Test WASI + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - name: Install toolchain + uses: dtolnay/rust-toolchain@nightly + with: + targets: wasm32-wasi + - name: Install wasmtime + run: | + curl https://wasmtime.dev/install.sh -sSf | bash + echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH + - name: Test (no features) + run: CARGO_TARGET_WASM32_WASI_RUNNER=wasmtime cargo test --target wasm32-wasi --no-default-features + - name: Test (all features) + run: CARGO_TARGET_WASM32_WASI_RUNNER=wasmtime cargo test --target wasm32-wasi --all-features + + + lints: + name: Rustfmt & Clippy + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - name: Install toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: Check formatting + run: cargo fmt --check + - name: Check clippy + run: cargo clippy -- -D warnings diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5f59319 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,30 @@ +# [Unreleased] + +# [0.3.0] - 2023-02-12 + +- Add haiku support + [#42](https://github.com/lambda-fairy/rust-errno/pull/42) + +- Add AIX support + [#54](https://github.com/lambda-fairy/rust-errno/pull/54) + +- Add formatting with `#![no_std]` + [#44](https://github.com/lambda-fairy/rust-errno/pull/44) + +- 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) + +- Upgrade to Rust 2018 edition [#59](https://github.com/lambda-fairy/rust-errno/pull/59) + +- wasm32-wasi: Use `__errno_location` instead of `feature(thread_local)`. [#66](https://github.com/lambda-fairy/rust-errno/pull/66) + +# [0.2.8] - 2021-10-27 + +- Optionally support no_std + [#31](https://github.com/lambda-fairy/rust-errno/pull/31) + +[Unreleased]: https://github.com/lambda-fairy/rust-errno/compare/v0.3.0...HEAD +[0.3.0]: https://github.com/lambda-fairy/rust-errno/compare/v0.2.8...v0.3.0 +[0.2.8]: https://github.com/lambda-fairy/rust-errno/compare/v0.2.7...v0.2.8 diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..98668cb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,49 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.48" +name = "errno" +version = "0.3.0" +authors = ["Chris Wong <lambda.fairy@gmail.com>"] +description = "Cross-platform interface to the `errno` variable." +documentation = "https://docs.rs/errno" +readme = "README.md" +categories = [ + "no-std", + "os", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/lambda-fairy/rust-errno" + +[features] +default = ["std"] +std = [] + +[target."cfg(target_os=\"dragonfly\")".dependencies.errno-dragonfly] +version = "0.1.1" + +[target."cfg(target_os=\"hermit\")".dependencies.libc] +version = "0.2" + +[target."cfg(target_os=\"wasi\")".dependencies.libc] +version = "0.2" + +[target."cfg(unix)".dependencies.libc] +version = "0.2" + +[target."cfg(windows)".dependencies.windows-sys] +version = "0.45" +features = [ + "Win32_Foundation", + "Win32_System_Diagnostics_Debug", +] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..bcae399 --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,36 @@ +[package] + +name = "errno" +version = "0.3.0" +authors = ["Chris Wong <lambda.fairy@gmail.com>"] + +license = "MIT OR Apache-2.0" +edition = "2018" +documentation = "https://docs.rs/errno" +repository = "https://github.com/lambda-fairy/rust-errno" +description = "Cross-platform interface to the `errno` variable." +categories = ["no-std", "os"] +rust-version = "1.48" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies.windows-sys] +version = "0.45" +features = [ + "Win32_Foundation", + "Win32_System_Diagnostics_Debug", +] + +[target.'cfg(target_os="dragonfly")'.dependencies] +errno-dragonfly = "0.1.1" + +[target.'cfg(target_os="wasi")'.dependencies] +libc = "0.2" + +[target.'cfg(target_os="hermit")'.dependencies] +libc = "0.2" + +[features] +default = ["std"] +std = [] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..66b6578 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Chris Wong + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..48def10 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# 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.48 or newer. + +Documentation is available at <https://docs.rs/errno>. + +[errno]: https://en.wikipedia.org/wiki/Errno.h + + +## Dependency + +Add to your `Cargo.toml`: + +```toml +[dependencies] +errno = "*" +``` + + +## Comparison with `std::io::Error` + +The standard library provides [`Error::last_os_error`][last_os_error] which fetches `errno` in the same way. + +This crate provides these extra features: + +- No heap allocations +- Optional `#![no_std]` support +- A `set_errno` function + +[last_os_error]: https://doc.rust-lang.org/std/io/struct.Error.html#method.last_os_error + + +## Examples + +```rust +extern crate errno; +use errno::{Errno, errno, set_errno}; + +// Get the current value of errno +let e = errno(); + +// Set the current value of errno +set_errno(e); + +// Extract the error code as an i32 +let code = e.0; + +// Display a human-friendly error message +println!("Error {}: {}", code, e); +``` + + +## `#![no_std]` + +Enable `#![no_std]` support by disabling the default `std` feature: + +```toml +[dependencies] +errno = { version = "*", default-features = false } +``` + +The `Error` impl will be unavailable. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..f691ea3 --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +msrv = "1.48" diff --git a/src/hermit.rs b/src/hermit.rs new file mode 100644 index 0000000..99d4c32 --- /dev/null +++ b/src/hermit.rs @@ -0,0 +1,32 @@ +//! Implementation of `errno` functionality for RustyHermit. +//! +//! Currently, the error handling in RustyHermit isn't clearly +//! defined. At the current stage of RustyHermit, only a placeholder +//! is provided to be compatible to the classical errno interface. + +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Errno; + +pub fn with_description<F, T>(_err: Errno, callback: F) -> T +where + F: FnOnce(Result<&str, Errno>) -> T, +{ + callback(Ok("unknown error")) +} + +pub const STRERROR_NAME: &str = "strerror_r"; + +pub fn errno() -> Errno { + Errno(0) +} + +pub fn set_errno(_: Errno) {} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..20875b5 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,156 @@ +//! Cross-platform interface to the `errno` variable. +//! +//! # Examples +//! ``` +//! use errno::{Errno, errno, set_errno}; +//! +//! // Get the current value of errno +//! let e = errno(); +//! +//! // Set the current value of errno +//! set_errno(e); +//! +//! // Extract the error code as an i32 +//! let code = e.0; +//! +//! // Display a human-friendly error message +//! println!("Error {}: {}", code, e); +//! ``` + +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg_attr(unix, path = "unix.rs")] +#[cfg_attr(windows, path = "windows.rs")] +#[cfg_attr(target_os = "wasi", path = "wasi.rs")] +#[cfg_attr(target_os = "hermit", path = "hermit.rs")] +mod sys; + +use core::fmt; +#[cfg(feature = "std")] +use std::error::Error; +#[cfg(feature = "std")] +use std::io; + +/// Wraps a platform-specific error code. +/// +/// The `Display` instance maps the code to a human-readable string. It +/// calls [`strerror_r`][1] under POSIX, and [`FormatMessageW`][2] on +/// Windows. +/// +/// [1]: http://pubs.opengroup.org/onlinepubs/009695399/functions/strerror.html +/// [2]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351%28v=vs.85%29.aspx +#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Hash)] +pub struct Errno(pub i32); + +impl fmt::Debug for Errno { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + sys::with_description(*self, |desc| { + fmt.debug_struct("Errno") + .field("code", &self.0) + .field("description", &desc.ok()) + .finish() + }) + } +} + +impl fmt::Display for Errno { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + 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 + ), + }) + } +} + +impl From<Errno> for i32 { + fn from(e: Errno) -> Self { + e.0 + } +} + +#[cfg(feature = "std")] +impl Error for Errno { + // TODO: Remove when MSRV >= 1.27 + #[allow(deprecated)] + fn description(&self) -> &str { + "system error" + } +} + +#[cfg(feature = "std")] +impl From<Errno> for io::Error { + fn from(errno: Errno) -> Self { + io::Error::from_raw_os_error(errno.0) + } +} + +/// Returns the platform-specific value of `errno`. +pub fn errno() -> Errno { + sys::errno() +} + +/// Sets the platform-specific value of `errno`. +pub fn set_errno(err: Errno) { + sys::set_errno(err) +} + +#[test] +fn it_works() { + let x = errno(); + set_errno(x); +} + +#[cfg(feature = "std")] +#[test] +fn it_works_with_to_string() { + let x = errno(); + let _ = x.to_string(); +} + +#[cfg(feature = "std")] +#[test] +fn check_description() { + let expect = if cfg!(windows) { + "Incorrect function." + } else if cfg!(target_os = "illumos") { + "Not owner" + } else if cfg!(target_os = "wasi") { + "Argument list too long" + } else if cfg!(target_os = "haiku") { + "Operation not allowed" + } else { + "Operation not permitted" + }; + + 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 + ) + ); +} + +#[cfg(feature = "std")] +#[test] +fn check_error_into_errno() { + const ERROR_CODE: i32 = 1; + + let error = io::Error::from_raw_os_error(ERROR_CODE); + let new_error: io::Error = Errno(ERROR_CODE).into(); + assert_eq!(error.kind(), new_error.kind()); +} diff --git a/src/unix.rs b/src/unix.rs new file mode 100644 index 0000000..c22c587 --- /dev/null +++ b/src/unix.rs @@ -0,0 +1,85 @@ +//! Implementation of `errno` functionality for Unix systems. +//! +//! Adapted from `src/libstd/sys/unix/os.rs` in the Rust distribution. + +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::str; +#[cfg(target_os = "dragonfly")] +use errno_dragonfly::errno_location; +use libc::{self, c_char, c_int, size_t, strlen}; + +use crate::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()]) }, + } +} + +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 { + if strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t) < 0 { + let fm_err = errno(); + if fm_err != Errno(libc::ERANGE) { + return callback(Err(fm_err)); + } + } + let c_str_len = strlen(buf.as_ptr() as *const _); + &buf[..c_str_len] + }; + callback(Ok(from_utf8_lossy(c_str))) +} + +pub const STRERROR_NAME: &str = "strerror_r"; + +pub fn errno() -> Errno { + unsafe { Errno(*errno_location()) } +} + +pub fn set_errno(Errno(errno): Errno) { + unsafe { + *errno_location() = errno; + } +} + +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")] + 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: size_t) -> c_int; +} diff --git a/src/wasi.rs b/src/wasi.rs new file mode 100644 index 0000000..b18fa9b --- /dev/null +++ b/src/wasi.rs @@ -0,0 +1,60 @@ +//! Implementation of `errno` functionality for WASI. +//! +//! Adapted from `unix.rs`. + +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::str; +use libc::{self, c_char, c_int, size_t, strlen}; + +use crate::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()]) }, + } +} + +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 { + if strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t) < 0 { + let fm_err = errno(); + if fm_err != Errno(libc::ERANGE) { + return callback(Err(fm_err)); + } + } + let c_str_len = strlen(buf.as_ptr() as *const _); + &buf[..c_str_len] + }; + callback(Ok(from_utf8_lossy(c_str))) +} + +pub const STRERROR_NAME: &str = "strerror_r"; + +pub fn errno() -> Errno { + unsafe { Errno(*__errno_location()) } +} + +pub fn set_errno(Errno(new_errno): Errno) { + unsafe { + *__errno_location() = new_errno; + } +} + +extern "C" { + fn __errno_location() -> *mut c_int; + fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int; +} diff --git a/src/windows.rs b/src/windows.rs new file mode 100644 index 0000000..9c7c0e4 --- /dev/null +++ b/src/windows.rs @@ -0,0 +1,81 @@ +//! Implementation of `errno` functionality for Windows. +//! +//! Adapted from `src/libstd/sys/windows/os.rs` in the Rust distribution. + +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::char::{self, REPLACEMENT_CHARACTER}; +use core::ptr; +use core::str; +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 crate::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)) + { + let c_len = c.len_utf8(); + 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]) } +} + +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_u32; + + let mut buf = [0u16; 2048]; + + unsafe { + 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(); + return callback(Err(fm_err)); + } + + let mut msg = [0u8; 2048]; + let msg = from_utf16_lossy(&buf[..res as usize], &mut msg[..]); + // Trim trailing CRLF inserted by FormatMessageW + callback(Ok(msg.trim_end())) + } +} + +pub const STRERROR_NAME: &str = "FormatMessageW"; + +pub fn errno() -> Errno { + unsafe { Errno(GetLastError() as i32) } +} + +pub fn set_errno(Errno(errno): Errno) { + unsafe { SetLastError(errno as WIN32_ERROR) } +} |