[PATCH] perf core: Replace offsetof() with struct_size()

Xichao Zhao posted 1 patch 1 month ago
kernel/events/callchain.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH] perf core: Replace offsetof() with struct_size()
Posted by Xichao Zhao 1 month ago
When dealing with structures containing flexible arrays, struct_size()
provides additional compile-time checks compared to offsetof(). This
enhances code robustness and reduces the risk of potential errors.

Signed-off-by: Xichao Zhao <zhao.xichao@vivo.com>
---
 kernel/events/callchain.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/kernel/events/callchain.c b/kernel/events/callchain.c
index 6c83ad674d01..0f88e44af664 100644
--- a/kernel/events/callchain.c
+++ b/kernel/events/callchain.c
@@ -80,7 +80,7 @@ static int alloc_callchain_buffers(void)
 	 * accessed from NMI. Use a temporary manual per cpu allocation
 	 * until that gets sorted out.
 	 */
-	size = offsetof(struct callchain_cpus_entries, cpu_entries[nr_cpu_ids]);
+	size = struct_size(entries, cpu_entries, nr_cpu_ids);
 
 	entries = kzalloc(size, GFP_KERNEL);
 	if (!entries)
-- 
2.34.1
Re: [PATCH] perf core: Replace offsetof() with struct_size()
Posted by Peter Zijlstra 1 month ago
On Tue, Sep 02, 2025 at 11:43:49AM +0800, Xichao Zhao wrote:
> When dealing with structures containing flexible arrays, struct_size()
> provides additional compile-time checks compared to offsetof(). This
> enhances code robustness and reduces the risk of potential errors.
> 
> Signed-off-by: Xichao Zhao <zhao.xichao@vivo.com>
> ---
>  kernel/events/callchain.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/kernel/events/callchain.c b/kernel/events/callchain.c
> index 6c83ad674d01..0f88e44af664 100644
> --- a/kernel/events/callchain.c
> +++ b/kernel/events/callchain.c
> @@ -80,7 +80,7 @@ static int alloc_callchain_buffers(void)
>  	 * accessed from NMI. Use a temporary manual per cpu allocation
>  	 * until that gets sorted out.
>  	 */
> -	size = offsetof(struct callchain_cpus_entries, cpu_entries[nr_cpu_ids]);
> +	size = struct_size(entries, cpu_entries, nr_cpu_ids);

None of this code is needed anymore; that issue with NMI not being able
to access vmalloc memory should be long fixed.