[PATCH 1/4] debugfs: return EINVAL if write to unsigned simple files exceed storage.

From: chris hyser
Date: Tue May 30 2023 - 15:40:45 EST


Writes to the debug files created by "debugfs_create_*" (u8/u16/u32/u64),
(x8/x16/x32/x64) should not silently succeed if the value exceeds the
storage space for the type and upper written bits are lost. Absent an
error, a read should return the last written value. Current behaviour is
to down cast the storage type thus losing upper bits (thus u64/x64
files are unaffected).

This patch ensures the written value fits into the specified storage space
returning EINVAL on error.

Signed-off-by: Chris Hyser <chris.hyser@xxxxxxxxxx>
---
Documentation/filesystems/debugfs.rst | 7 ++++---
fs/debugfs/file.c | 6 ++++++
2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/Documentation/filesystems/debugfs.rst b/Documentation/filesystems/debugfs.rst
index dc35da8b8792..6f1ac8d7f108 100644
--- a/Documentation/filesystems/debugfs.rst
+++ b/Documentation/filesystems/debugfs.rst
@@ -85,9 +85,10 @@ created with any of::
struct dentry *parent, u64 *value);

These files support both reading and writing the given value; if a specific
-file should not be written to, simply set the mode bits accordingly. The
-values in these files are in decimal; if hexadecimal is more appropriate,
-the following functions can be used instead::
+file should not be written to, simply set the mode bits accordingly. Written
+values that exceed the storage for the type return EINVAL. The values in these
+files are in decimal; if hexadecimal is more appropriate, the following
+functions can be used instead::

void debugfs_create_x8(const char *name, umode_t mode,
struct dentry *parent, u8 *value);
diff --git a/fs/debugfs/file.c b/fs/debugfs/file.c
index 1f971c880dde..743ddd04f8d8 100644
--- a/fs/debugfs/file.c
+++ b/fs/debugfs/file.c
@@ -429,6 +429,8 @@ static struct dentry *debugfs_create_mode_unsafe(const char *name, umode_t mode,

static int debugfs_u8_set(void *data, u64 val)
{
+ if (val > (1 << sizeof(u8) * 8) - 1)
+ return -EINVAL;
*(u8 *)data = val;
return 0;
}
@@ -465,6 +467,8 @@ EXPORT_SYMBOL_GPL(debugfs_create_u8);

static int debugfs_u16_set(void *data, u64 val)
{
+ if (val > (1 << sizeof(u16) * 8) - 1)
+ return -EINVAL;
*(u16 *)data = val;
return 0;
}
@@ -501,6 +505,8 @@ EXPORT_SYMBOL_GPL(debugfs_create_u16);

static int debugfs_u32_set(void *data, u64 val)
{
+ if (val > (1ull << sizeof(u32) * 8) - 1)
+ return -EINVAL;
*(u32 *)data = val;
return 0;
}
--
2.31.1