rust: add module to convert between success/-errno and io::Result conventions
Subsystems (2)
v3 cover rust: add module to convert between success/-errno and io::Result conventions
Wrap access to errno, for use in the block layer and character device bindings.
This first version of errno.rs focuses on io::Result. Kevin suggested allowing conversion from io::Error to negative errno. For now, I'd rather avoid that to encourage separation between code that can propagate errors simply with "?", and code at the Rust/C boundary that needs errno::into_neg_errno(). Since Rust code rarely passes or returns Error objects that aren't part of a Result, it is plausible that the same is true of QEMU.
However, if this turns out to be wrong, then it can be changed.
Paolo
Supersedes: <[email protected]>
v2->v3:
- add libc to subprojects/.gitignore
- change subject to reflect the focus to be Result rather than Error
- fix docs
v1->v2:
- use the libc crate
- provide separate From<Errno> implementation for io::ErrorKind
- hide GetErrno trait inside a submodule
- add into_neg_errno() and corresponding tests
- add more doctests
- make Errno field public, so that Errno can have other From<...> implementations (e.g. going from *mut Error to Errno).
Paolo Bonzini (2):
rust: subprojects: add libc crate
rust: add module to convert between success/-errno and io::Result
docs/devel/rust.rst | 1 + rust/Cargo.lock | 7 + rust/qemu-api/Cargo.toml | 1 + rust/qemu-api/meson.build | 4 + rust/qemu-api/src/assertions.rs | 28 ++ rust/qemu-api/src/errno.rs | 343 ++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/prelude.rs | 2 + scripts/archive-source.sh | 2 +- scripts/make-release | 2 +- subprojects/.gitignore | 1 + subprojects/libc-0.2-rs.wrap | 7 + .../packagefiles/libc-0.2-rs/meson.build | 37 ++ 13 files changed, 434 insertions(+), 2 deletions(-) create mode 100644 rust/qemu-api/src/errno.rs create mode 100644 subprojects/libc-0.2-rs.wrap create mode 100644 subprojects/packagefiles/libc-0.2-rs/meson.build
Signature · 1 line
2.48.1
PATCH v3 1/2 rust: subprojects: add libc crate
This allows access to errno values.
--- rust/Cargo.lock | 7 ++++ rust/qemu-api/Cargo.toml | 1 + scripts/archive-source.sh | 2 +- scripts/make-release | 2 +- subprojects/.gitignore | 1 + subprojects/libc-0.2-rs.wrap | 7 ++++ .../packagefiles/libc-0.2-rs/meson.build | 37 +++++++++++++++++++ 7 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 subprojects/libc-0.2-rs.wrap create mode 100644 subprojects/packagefiles/libc-0.2-rs/meson.build
rust/Cargo.lock +7 -0
@@ -54,6 +54,12 @@ dependencies = [ "either", ] +[[package]] +name = "libc" +version = "0.2.162" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" + [[package]] name = "pl011" version = "0.1.0"
@@ -100,6 +106,7 @@ dependencies = [ name = "qemu_api" version = "0.1.0" dependencies = [ + "libc", "qemu_api_macros", "version_check", ]
rust/qemu-api/Cargo.toml +1 -0
@@ -16,6 +16,7 @@ rust-version = "1.63.0" [dependencies] qemu_api_macros = { path = "../qemu-api-macros" } +libc = "0.2.162" [build-dependencies] version_check = "~0.9"
scripts/archive-source.sh +1 -1
@@ -28,7 +28,7 @@ sub_file="${sub_tdir}/submodule.tar" # different to the host OS. subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs - bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs + bilge-impl-0.2-rs either-1-rs itertools-0.11-rs libc-0.2-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs" sub_deinit=""
scripts/make-release +1 -1
@@ -41,7 +41,7 @@ fi # Only include wraps that are invoked with subproject() SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs - bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs + bilge-impl-0.2-rs either-1-rs itertools-0.11-rs libc-0.2-rs proc-macro2-1-rs proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs"
subprojects/.gitignore +1 -0
@@ -11,6 +11,7 @@ /bilge-impl-0.2.0 /either-1.12.0 /itertools-0.11.0 +/libc-0.2.162 /proc-macro-error-1.0.4 /proc-macro-error-attr-1.0.4 /proc-macro2-1.0.84
subprojects/libc-0.2-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = libc-0.2.162 +source_url = https://crates.io/api/v1/crates/libc/0.2.162/download +source_filename = libc-0.2.162.tar.gz +source_hash = 18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398 +#method = cargo +patch_directory = libc-0.2-rs
subprojects/packagefiles/libc-0.2-rs/meson.build new file +37 -0
@@ -0,0 +1,37 @@ +project('libc-0.2-rs', 'rust', + meson_version: '>=1.5.0', + version: '0.2.162', + license: 'MIT OR Apache-2.0', + default_options: []) + +_libc_rs = static_library( + 'libc', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2015', 'build.rust_std=2015'], + rust_abi: 'rust', + rust_args: [ + '--cap-lints', 'allow', + '--cfg', 'freebsd11', + '--cfg', 'libc_priv_mod_use', + '--cfg', 'libc_union', + '--cfg', 'libc_const_size_of', + '--cfg', 'libc_align', + '--cfg', 'libc_int128', + '--cfg', 'libc_core_cvoid', + '--cfg', 'libc_packedN', + '--cfg', 'libc_cfg_target_vendor', + '--cfg', 'libc_non_exhaustive', + '--cfg', 'libc_long_array', + '--cfg', 'libc_ptr_addr_of', + '--cfg', 'libc_underscore_const_names', + '--cfg', 'libc_const_extern_fn', + ], + dependencies: [], +) + +libc_dep = declare_dependency( + link_with: _libc_rs, +) + +meson.override_dependency('libc-0.2-rs', libc_dep)
Signature · 1 line
2.48.1
PATCH v3 2/2 rust: add module to convert between success/-errno and io::Result
In reply to Paolo BonziniIt is a common convention in QEMU to return a positive value in case of success, and a negated errno value in case of error. Unfortunately, using errno portably in Rust is a bit complicated; on Unix the errno values are supported natively by io::Error, but on Windows they are not; so, use the libc crate.
This is a set of utility functions that are used by both chardev and block layer bindings.
--- docs/devel/rust.rst | 1 + rust/qemu-api/meson.build | 4 + rust/qemu-api/src/assertions.rs | 28 +++ rust/qemu-api/src/errno.rs | 343 ++++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/prelude.rs | 2 + 6 files changed, 379 insertions(+) create mode 100644 rust/qemu-api/src/errno.rs
docs/devel/rust.rst +1 -0
@@ -179,6 +179,7 @@ module status ``callbacks`` complete ``cell`` stable ``c_str`` complete +``errno`` complete ``irq`` complete ``memory`` stable ``module`` complete
rust/qemu-api/meson.build +4 -0
@@ -2,6 +2,8 @@ _qemu_api_cfg = run_command(rustc_args, '--config-headers', config_host_h, '--features', files('Cargo.toml'), capture: true, check: true).stdout().strip().splitlines() +libc_dep = dependency('libc-0.2-rs') + # _qemu_api_cfg += ['--cfg', 'feature="allocator"'] if rustc.version().version_compare('>=1.77.0') _qemu_api_cfg += ['--cfg', 'has_offset_of']
@@ -22,6 +24,7 @@ _qemu_api_rs = static_library( 'src/cell.rs', 'src/chardev.rs', 'src/c_str.rs', + 'src/errno.rs', 'src/irq.rs', 'src/memory.rs', 'src/module.rs',
@@ -39,6 +42,7 @@ _qemu_api_rs = static_library( override_options: ['rust_std=2021', 'build.rust_std=2021'], rust_abi: 'rust', rust_args: _qemu_api_cfg, + dependencies: libc_dep, ) rust.test('rust-qemu-api-tests', _qemu_api_rs,
rust/qemu-api/src/assertions.rs +28 -0
@@ -92,3 +92,31 @@ fn types_must_be_equal<T, U>(_: T) }; }; } + +/// Assert that an expression matches a pattern. This can also be +/// useful to compare enums that do not implement `Eq`. +/// +/// # Examples +/// +/// ``` +/// # use qemu_api::assert_match; +/// // JoinHandle does not implement `Eq`, therefore the result +/// // does not either. +/// let result: Result<std::thread::JoinHandle<()>, u32> = Err(42); +/// assert_match!(result, Err(42)); +/// ``` +#[macro_export] +macro_rules! assert_match { + ($a:expr, $b:pat) => { +assert! ( +match $a { + $b =>true , + _ =>false , + }, +"{} = {:?} does not match {}" , +stringify! ($a), + $a, +stringify! ($b) + ); + }; +}
rust/qemu-api/src/errno.rs new file +343 -0
343 lines not on this page · raw message
rust/qemu-api/src/lib.rs +1 -0
@@ -19,6 +19,7 @@pub mod callbacks;pub mod cell;pub mod chardev; +pub mod errno;pub mod irq;pub mod memory;pub mod module;
rust/qemu-api/src/prelude.rs +2 -0
@@ -9,6 +9,8 @@pub use crate ::cell::BqlCell ;pub use crate ::cell::BqlRefCell ; +pub use crate ::errno; +pub use crate ::qdev::DeviceMethods ;pub use crate ::qom::InterfaceType ;
Signature · 1 line
2.48.1
Re: [PATCH v3 2/2] rust: add module to convert between success/-errno and io::Result
Hi Paolo,
Quoted 5 lines
It is a common convention in QEMU to return a positive value in case of success, and a negated errno value in case of error. Unfortunately, using errno portably in Rust is a bit complicated; on Unix the errno values are supported natively by
io::Error, but on Windows they are not; so, use the libc crate.
I'm a bit confused. The doc of error.h just said the negative value for failure:
• integer-valued functions return non-negative / negative.
Why do we need to using libc's -errno for Windows as well?
Converting io::Error::last_os_error().raw_os_error().unwrap() to a negative value seems compatible with Windows, except it returns Windows error codes.
Quoted 2 lines
This is a set of utility functions that are used by both chardev and block layer bindings.
...
rust/qemu-api/src/errno.rs line 22
Quoted 8 lines
rust/qemu-api/src/errno.rs new file +8
-0+// On Unix, from_raw_os_error takes an errno value and OS errors +// are printed using strerror. On Windows however it takes a +// GetLastError() value; therefore we need to convert errno values +// into io::Error by hand. This is the same mapping that the +// standard library uses to retrieve the kind of OS errors +// (`std::sys::pal::unix::decode_error_kind`). +impl From <Errno >for ErrorKind { +fn from (value:Errno ) ->ErrorKind {
What about use ErrorKind::*; to oimt the following "ErrorKind::" prefix?
rust/qemu-api/src/errno.rs line 24
Quoted 2 lines
rust/qemu-api/src/errno.rs new file +2
-0+let Errno (errno) = value; +match i32::from (errno) {
Maybe match i32::from(errno.0) ?
Quoted 7 lines
rust/qemu-api/src/errno.rs new file +7
-0+ libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied, + libc::ENOENT => ErrorKind::NotFound, + libc::EINTR => ErrorKind::Interrupted, + x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock, + libc::ENOMEM => ErrorKind::OutOfMemory, + libc::EEXIST => ErrorKind::AlreadyExists, + libc::EINVAL => ErrorKind::InvalidInput,
rust/qemu-api/src/errno.rs line 41
Quoted 10 lines
rust/qemu-api/src/errno.rs new file +10
-0+ libc::EPIPE => ErrorKind::BrokenPipe, + libc::EADDRINUSE => ErrorKind::AddrInUse, + libc::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable, + libc::ECONNABORTED => ErrorKind::ConnectionAborted, + libc::ECONNREFUSED => ErrorKind::ConnectionRefused, + libc::ECONNRESET => ErrorKind::ConnectionReset, + libc::ENOTCONN => ErrorKind::NotConnected, + libc::ENOTSUP => ErrorKind::Unsupported, + libc::ETIMEDOUT => ErrorKind::TimedOut, + _ => ErrorKind::Other,
Are these errno cases specifically selected? It seems to have fewer than decode_error_kind lists. Why not support all the cases decode_error_kind mentions? Or do we need to try to cover as many errno cases as possible from rust/kernel/error.rs?
rust/qemu-api/src/errno.rs line 48
Quoted 7 lines
rust/qemu-api/src/errno.rs new file +7
-0+ } + } +} + +// This is used on Windows for all io::Errors, but also on Unix if the +// io::Error does not have a raw OS error. This is the reversed +// mapping of the above.
Maybe:
This is the "almost" reversed (except the default case) mapping
?
rust/qemu-api/src/errno.rs line 50
Quoted 2 lines
rust/qemu-api/src/errno.rs new file +2
-0+impl From <io::ErrorKind >for Errno { +fn from (value: io::ErrorKind ) ->Errno {
use ErrorKind::*; could save some words, too.
Quoted 19 lines
rust/qemu-api/src/errno.rs new file +19
-0+let errno =match value { +// can be both EPERM or EACCES :( pick one +ErrorKind ::PermissionDenied => libc::EPERM , +ErrorKind ::NotFound => libc::ENOENT , +ErrorKind ::Interrupted => libc::EINTR , +ErrorKind ::WouldBlock => libc::EAGAIN , +ErrorKind ::OutOfMemory => libc::ENOMEM , +ErrorKind ::AlreadyExists => libc::EEXIST , +ErrorKind ::InvalidInput => libc::EINVAL , +ErrorKind ::BrokenPipe => libc::EPIPE , +ErrorKind ::AddrInUse => libc::EADDRINUSE , +ErrorKind ::AddrNotAvailable => libc::EADDRNOTAVAIL , +ErrorKind ::ConnectionAborted => libc::ECONNABORTED , +ErrorKind ::ConnectionRefused => libc::ECONNREFUSED , +ErrorKind ::ConnectionReset => libc::ECONNRESET , +ErrorKind ::NotConnected => libc::ENOTCONN , +ErrorKind ::Unsupported => libc::ENOTSUP , +ErrorKind ::TimedOut => libc::ETIMEDOUT , + _ => libc::EIO ,
rust/qemu-api/src/errno.rs line 79
Quoted 10 lines
rust/qemu-api/src/errno.rs new file +10
-0+ }; +Errno (errnoas u16 ) + } +} + +impl From <Errno >for io::Error { +#[cfg(unix)] +fn from (value:Errno ) -> io::Error { +let Errno (errno) = value; + io::Error ::from_raw_os_error (errno.into ())
Maybe io::Error::from_raw_os_error(value.0.into())?
rust/qemu-api/src/errno.rs line 85
Quoted 6 lines
rust/qemu-api/src/errno.rs new file +6
-0+ } + +#[cfg(windows)] +fn from (value:Errno ) -> io::Error { +let error_kind:ErrorKind = value.into (); + error_kind.into ()
Even this works:
fn from(value: Errno) -> io::Error {
- let error_kind: ErrorKind = value.into(); - error_kind.into()
+ value.into()
However, it's less readability, so I still prefer your current codes. :-)
Thanks,
Zhao
Re: [PATCH v3 2/2] rust: add module to convert between success/-errno and io::Result
Il ven 21 feb 2025, 11:41 Zhao Liu <[email protected]> ha scritto:
Quoted 8 lines
Hi Paolo,
Quoted 5 lines
It is a common convention in QEMU to return a positive value in case of success, and a negated errno value in case of error. Unfortunately, using errno portably in Rust is a bit complicated; on Unix the errno values are supported natively by
io::Error, but on Windows they are not; so, use the libc crate.
Quoted 7 lines
I'm a bit confused. The doc of
error.hjust said the negative value for failure:• integer-valued functions return non-negative / negative.
Why do we need to using libc's -errno for Windows as well?
error.h doesn't explicitly mention errno because there are functions that return -1 on all errors, but errno is a common convention for negative return values too.
Converting io::Error::last_os_error().raw_os_error().unwrap() to a
Quoted 3 lines
negative value seems compatible with Windows, except it returns Windows error codes.
... but that's not what C functions expect. They might pass it to set error_setg_errno for example.
Quoted 12 lines
+// On Unix,
from_raw_os_errortakes an errno value and OS errorsrust/qemu-api/src/errno.rs line 22
Quoted 7 lines
rust/qemu-api/src/errno.rs new file +7
-0+// are printed using strerror. On Windows however it takes a +// GetLastError() value; therefore we need to convert errno values +// into io::Error by hand. This is the same mapping that the +// standard library uses to retrieve the kind of OS errors +// (`std::sys::pal::unix::decode_error_kind`). +impl From <Errno >for ErrorKind { +fn from (value:Errno ) ->ErrorKind {What about
use ErrorKind::*;to omit the following "ErrorKind::" prefix?
Yeah, that's possible.
Quoted 4 lines
rust/qemu-api/src/errno.rs line 24
Quoted 2 lines
rust/qemu-api/src/errno.rs new file +2
-0+let Errno (errno) = value; +match i32::from (errno) {Maybe
match i32::from(errno.0)?
Well, I don't like .0 too much...
Quoted 19 lines
+
libc::EPERM|libc::EACCES=>ErrorKind::PermissionDenied,rust/qemu-api/src/errno.rs
Quoted 3 lines
rust/qemu-api/src/errno.rs new file +3
-0+ libc::ENOENT => ErrorKind::NotFound, + libc::EINTR => ErrorKind::Interrupted, + x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
ErrorKind::WouldBlock,rust/qemu-api/src/errno.rs line 41
Quoted 13 lines
rust/qemu-api/src/errno.rs new file +13
-0+ libc::ENOMEM => ErrorKind::OutOfMemory, + libc::EEXIST => ErrorKind::AlreadyExists, + libc::EINVAL => ErrorKind::InvalidInput, + libc::EPIPE => ErrorKind::BrokenPipe, + libc::EADDRINUSE => ErrorKind::AddrInUse, + libc::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable, + libc::ECONNABORTED => ErrorKind::ConnectionAborted, + libc::ECONNREFUSED => ErrorKind::ConnectionRefused, + libc::ECONNRESET => ErrorKind::ConnectionReset, + libc::ENOTCONN => ErrorKind::NotConnected, + libc::ENOTSUP => ErrorKind::Unsupported, + libc::ETIMEDOUT => ErrorKind::TimedOut, + _ => ErrorKind::Other,
Quoted 4 lines
Are these errno cases specifically selected? It seems to have fewer than
decode_error_kindlists. Why not support all the casesdecode_error_kind
mentions?
Not all of them are in all Rust versions; see
https://stdrs.dev/nightly/x86_64-unknown-linux-gnu/src/std/io/error.rs.html#179-395
.
Quoted 8 lines
+// This is used on Windows for all
io::Errors, but also on Unix if therust/qemu-api/src/errno.rs line 48
Quoted 2 lines
rust/qemu-api/src/errno.rs new file +2
-0+// io::Error does not have a raw OS error. This is the reversed +// mapping of the above. Maybe:
This is the "almost" reversed (except the default case) mapping
True, thanks.
Paolo