Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

overflow: Introduce struct_offset() to get offset of member

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>

+13 -1
+12
include/linux/overflow.h
··· 459 459 struct_size((type *)NULL, member, count) 460 460 461 461 /** 462 + * struct_offset() - Calculate the offset of a member within a struct 463 + * @p: Pointer to the struct 464 + * @member: Name of the member to get the offset of 465 + * 466 + * Calculates the offset of a particular @member of the structure pointed 467 + * to by @p. 468 + * 469 + * Return: number of bytes to the location of @member. 470 + */ 471 + #define struct_offset(p, member) (offsetof(typeof(*(p)), member)) 472 + 473 + /** 462 474 * __DEFINE_FLEX() - helper macro for DEFINE_FLEX() family. 463 475 * Enables caller macro to pass arbitrary trailing expressions 464 476 *
+1 -1
kernel/trace/trace.c
··· 7642 7642 size_t size; 7643 7643 7644 7644 /* cnt includes both the entry->id and the data behind it. */ 7645 - size = struct_size(entry, buf, cnt - sizeof(entry->id)); 7645 + size = struct_offset(entry, id) + cnt; 7646 7646 7647 7647 buffer = tr->array_buffer.buffer; 7648 7648