Skip to content

Commit e71e2ab

Browse files
authored
Merge pull request #287 from nbdd0121/rust
Print out errname in `impl Debug for Error`
2 parents bcd1464 + 34c1d99 commit e71e2ab

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-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: 26 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,27 @@ 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+
75+
if name.is_null() {
76+
// Print out number if no name can be found.
77+
return f.debug_tuple("Error").field(&-self.0).finish();
78+
}
79+
80+
// SAFETY: `'static` string from C, and is not NULL.
81+
let cstr = unsafe { CStr::from_char_ptr(name) };
82+
// SAFETY: These strings are ASCII-only.
83+
let str = unsafe { str::from_utf8_unchecked(&cstr) };
84+
f.debug_tuple(str).finish()
85+
}
86+
}
87+
6488
impl From<TryFromIntError> for Error {
6589
fn from(_: TryFromIntError) -> Error {
6690
Error::EINVAL

0 commit comments

Comments
 (0)