]> git.ipfire.org Git - thirdparty/kernel/stable.git/commitdiff
overflow: Introduce struct_offset() to get offset of member
authorSteven Rostedt <rostedt@goodmis.org>
Wed, 26 Nov 2025 19:52:49 +0000 (14:52 -0500)
committerSteven Rostedt (Google) <rostedt@goodmis.org>
Fri, 28 Nov 2025 01:18:05 +0000 (20:18 -0500)
The trace_marker_raw file in tracefs takes a buffer from user space that
contains an id as well as a raw data string which is usually a binary
structure. The structure used has the following:

struct raw_data_entry {
struct trace_entry ent;
unsigned int id;
char buf[];
};

Since the passed in "cnt" variable is both the size of buf as well as the
size of id, the code to allocate the location on the ring buffer had:

   size = struct_size(entry, buf, cnt - sizeof(entry->id));

Which is quite ugly and hard to understand. Instead, add a helper macro
called struct_offset() which then changes the above to a simple and easy
to understand:

   size = struct_offset(entry, id) + cnt;

This will likely come in handy for other use cases too.

Link: https://lore.kernel.org/all/CAHk-=whYZVoEdfO1PmtbirPdBMTV9Nxt9f09CK0k6S+HJD3Zmg@mail.gmail.com/
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: "Gustavo A. R. Silva" <gustavoars@kernel.org>
Link: https://patch.msgid.link/20251126145249.05b1770a@gandalf.local.home
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Reviewed-by: Kees Cook <kees@kernel.org>
Signed-off-by: Steven Rostedt (Google) <rostedt@goodmis.org>
include/linux/overflow.h
kernel/trace/trace.c

index 725f95f7e4164b68cb110294e099f5815030f5e2..736f633b2d5fb1d8618b2deadf9d0ef90368d1aa 100644 (file)
@@ -458,6 +458,18 @@ static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
 #define struct_size_t(type, member, count)                                     \
        struct_size((type *)NULL, member, count)
 
+/**
+ * struct_offset() - Calculate the offset of a member within a struct
+ * @p: Pointer to the struct
+ * @member: Name of the member to get the offset of
+ *
+ * Calculates the offset of a particular @member of the structure pointed
+ * to by @p.
+ *
+ * Return: number of bytes to the location of @member.
+ */
+#define struct_offset(p, member) (offsetof(typeof(*(p)), member))
+
 /**
  * __DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
  * Enables caller macro to pass arbitrary trailing expressions
index 73f8b79f1b0c875ff3fd64f4eac7fe5520811585..3d433a426e5f4c27519f0c1492440601866a3466 100644 (file)
@@ -7642,7 +7642,7 @@ static ssize_t write_raw_marker_to_buffer(struct trace_array *tr,
        size_t size;
 
        /* cnt includes both the entry->id and the data behind it. */
-       size = struct_size(entry, buf, cnt - sizeof(entry->id));
+       size = struct_offset(entry, id) + cnt;
 
        buffer = tr->array_buffer.buffer;