Skip to content

Commit b75e2ed

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

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

rust/kernel/bindings_helper.h

+1
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

+24-2
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@
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)]
1719
pub struct Error(c_types::c_int);
1820

1921
impl Error {
@@ -61,6 +63,26 @@ impl Error {
6163
}
6264
}
6365

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

0 commit comments

Comments
 (0)