Skip to content

Commit

Permalink
Merge pull request torvalds#287 from nbdd0121/rust
Browse files Browse the repository at this point in the history
Print out errname in `impl Debug for Error`
  • Loading branch information
ojeda authored May 26, 2021
2 parents bcd1464 + 34c1d99 commit e71e2ab
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions rust/kernel/bindings_helper.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* SPDX-License-Identifier: GPL-2.0 */

#include <linux/cdev.h>
#include <linux/errname.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/random.h>
Expand Down
28 changes: 26 additions & 2 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@
//!
//! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h)

use crate::str::CStr;
use crate::{bindings, c_types};
use alloc::{alloc::AllocError, collections::TryReserveError};
use core::convert::From;
use core::{num::TryFromIntError, str::Utf8Error};
use core::fmt;
use core::num::TryFromIntError;
use core::str::{self, Utf8Error};

/// Generic integer kernel error.
///
/// The kernel defines a set of integer generic error codes based on C and
/// POSIX ones. These codes may have a more specific meaning in some contexts.
#[derive(Debug)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Error(c_types::c_int);

impl Error {
Expand Down Expand Up @@ -61,6 +64,27 @@ impl Error {
}
}

impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// SAFETY: FFI call.
#[cfg(CONFIG_SYMBOLIC_ERRNAME)]
let name = unsafe { crate::bindings::errname(-self.0) };
#[cfg(not(CONFIG_SYMBOLIC_ERRNAME))]
let name: *const c_types::c_char = core::ptr::null();

if name.is_null() {
// Print out number if no name can be found.
return f.debug_tuple("Error").field(&-self.0).finish();
}

// SAFETY: `'static` string from C, and is not NULL.
let cstr = unsafe { CStr::from_char_ptr(name) };
// SAFETY: These strings are ASCII-only.
let str = unsafe { str::from_utf8_unchecked(&cstr) };
f.debug_tuple(str).finish()
}
}

impl From<TryFromIntError> for Error {
fn from(_: TryFromIntError) -> Error {
Error::EINVAL
Expand Down

0 comments on commit e71e2ab

Please sign in to comment.