Skip to content

Commit 2338e94

Browse files
committed
rust: print out errname in impl Debug for Error
Signed-off-by: Gary Guo <[email protected]>
1 parent 7451cda commit 2338e94

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

rust/kernel/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* SPDX-License-Identifier: GPL-2.0 */
22

33
#include <linux/cdev.h>
4+
#include <linux/errname.h>
45
#include <linux/fs.h>
56
#include <linux/module.h>
67
#include <linux/random.h>

rust/kernel/error.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,19 @@
44
//!
55
//! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h)
66
7+
use crate::str::CStr;
78
use crate::{bindings, c_types};
89
use alloc::{alloc::AllocError, collections::TryReserveError};
910
use core::convert::From;
10-
use core::{num::TryFromIntError, str::Utf8Error};
11+
use core::fmt;
12+
use core::num::TryFromIntError;
13+
use core::str::{self, Utf8Error};
1114

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

1922
impl Error {
@@ -61,6 +64,26 @@ impl Error {
6164
}
6265
}
6366

67+
impl fmt::Debug for Error {
68+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69+
// SAFETY: FFI call.
70+
#[cfg(CONFIG_SYMBOLIC_ERRNAME)]
71+
let name = unsafe { crate::bindings::errname(-self.0) };
72+
#[cfg(not(CONFIG_SYMBOLIC_ERRNAME))]
73+
let name: *const c_types::c_char = core::ptr::null();
74+
if !name.is_null() {
75+
// SAFETY: 'static string from C, and is not NULL.
76+
let cstr = unsafe { CStr::from_char_ptr(name) };
77+
// SAFETY: These strings are ASCII-only
78+
let str = unsafe { str::from_utf8_unchecked(&cstr) };
79+
f.debug_tuple(str).finish()
80+
} else {
81+
// Print out number if no name can be found.
82+
f.debug_tuple("Error").field(&-self.0).finish()
83+
}
84+
}
85+
}
86+
6487
impl From<TryFromIntError> for Error {
6588
fn from(_: TryFromIntError) -> Error {
6689
Error::EINVAL

0 commit comments

Comments
 (0)