[PATCH] fs: Replace offsetof() with struct_size()

Xichao Zhao posted 1 patch 1 month ago
fs/namei.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
[PATCH] fs: 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>
---
 fs/namei.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/fs/namei.c b/fs/namei.c
index 10f7caff7f0f..70a71b1b8abc 100644
--- a/fs/namei.c
+++ b/fs/namei.c
@@ -178,7 +178,7 @@ getname_flags(const char __user *filename, int flags)
 	 * userland.
 	 */
 	if (unlikely(len == EMBEDDED_NAME_MAX)) {
-		const size_t size = offsetof(struct filename, iname[1]);
+		const size_t size = struct_size(result, iname, 1);
 		kname = (char *)result;
 
 		/*
@@ -253,7 +253,7 @@ struct filename *getname_kernel(const char * filename)
 	if (len <= EMBEDDED_NAME_MAX) {
 		result->name = (char *)result->iname;
 	} else if (len <= PATH_MAX) {
-		const size_t size = offsetof(struct filename, iname[1]);
+		const size_t size = struct_size(result, iname, 1);
 		struct filename *tmp;
 
 		tmp = kmalloc(size, GFP_KERNEL);
-- 
2.34.1
Re: [PATCH] fs: Replace offsetof() with struct_size()
Posted by Jan Kara 1 month ago
On Fri 29-08-25 18:03:28, 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>

Looks good. Feel free to add:

Reviewed-by: Jan Kara <jack@suse.cz>

								Honza

> ---
>  fs/namei.c | 4 ++--
>  1 file changed, 2 insertions(+), 2 deletions(-)
> 
> diff --git a/fs/namei.c b/fs/namei.c
> index 10f7caff7f0f..70a71b1b8abc 100644
> --- a/fs/namei.c
> +++ b/fs/namei.c
> @@ -178,7 +178,7 @@ getname_flags(const char __user *filename, int flags)
>  	 * userland.
>  	 */
>  	if (unlikely(len == EMBEDDED_NAME_MAX)) {
> -		const size_t size = offsetof(struct filename, iname[1]);
> +		const size_t size = struct_size(result, iname, 1);
>  		kname = (char *)result;
>  
>  		/*
> @@ -253,7 +253,7 @@ struct filename *getname_kernel(const char * filename)
>  	if (len <= EMBEDDED_NAME_MAX) {
>  		result->name = (char *)result->iname;
>  	} else if (len <= PATH_MAX) {
> -		const size_t size = offsetof(struct filename, iname[1]);
> +		const size_t size = struct_size(result, iname, 1);
>  		struct filename *tmp;
>  
>  		tmp = kmalloc(size, GFP_KERNEL);
> -- 
> 2.34.1
> 
-- 
Jan Kara <jack@suse.com>
SUSE Labs, CR