relay: Fix type mismatch when allocating memory in relay_create_buf()

Message ID 20221129092002.3538384-1-Ilia.Gavrilov@infotecs.ru
State New
Headers
Series relay: Fix type mismatch when allocating memory in relay_create_buf() |

Commit Message

Gavrilov Ilia Nov. 29, 2022, 9:23 a.m. UTC
  The 'padding' field of the 'rchan_buf' structure is an array of 'size_t'
elements, but the memory is allocated for an array of 'size_t *' elements.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Fixes: b86ff981a825 ("[PATCH] relay: migrate from relayfs to a generic relay API")
Signed-off-by: Ilia.Gavrilov <Ilia.Gavrilov@infotecs.ru>
---
 kernel/relay.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
  

Comments

Andrew Morton Nov. 29, 2022, 11:30 p.m. UTC | #1
On Tue, 29 Nov 2022 09:23:38 +0000 Gavrilov Ilia <Ilia.Gavrilov@infotecs.ru> wrote:

> The 'padding' field of the 'rchan_buf' structure is an array of 'size_t'
> elements, but the memory is allocated for an array of 'size_t *' elements.
> 
> Found by Linux Verification Center (linuxtesting.org) with SVACE.
> 
> --- a/kernel/relay.c
> +++ b/kernel/relay.c
> @@ -148,13 +148,13 @@ static struct rchan_buf *relay_create_buf(struct rchan *chan)
>  {
>  	struct rchan_buf *buf;
>  
> -	if (chan->n_subbufs > KMALLOC_MAX_SIZE / sizeof(size_t *))
> +	if (chan->n_subbufs > KMALLOC_MAX_SIZE / sizeof(size_t))
>  		return NULL;
>  
>  	buf = kzalloc(sizeof(struct rchan_buf), GFP_KERNEL);
>  	if (!buf)
>  		return NULL;
> -	buf->padding = kmalloc_array(chan->n_subbufs, sizeof(size_t *),
> +	buf->padding = kmalloc_array(chan->n_subbufs, sizeof(size_t),
>  				     GFP_KERNEL);

This is why I prefer kmalloc_array(N, sizeof(*(buf->padding)), ...)

Because the reviewer doesn't have to go check that the types match up,
and because the code doesn't need changing if the type of
*(buf->padding) is changed.

Others don't like this practice, but I forget why.
  

Patch

diff --git a/kernel/relay.c b/kernel/relay.c
index d7edc934c56d..88bcb09f0a1f 100644
--- a/kernel/relay.c
+++ b/kernel/relay.c
@@ -148,13 +148,13 @@  static struct rchan_buf *relay_create_buf(struct rchan *chan)
 {
 	struct rchan_buf *buf;
 
-	if (chan->n_subbufs > KMALLOC_MAX_SIZE / sizeof(size_t *))
+	if (chan->n_subbufs > KMALLOC_MAX_SIZE / sizeof(size_t))
 		return NULL;
 
 	buf = kzalloc(sizeof(struct rchan_buf), GFP_KERNEL);
 	if (!buf)
 		return NULL;
-	buf->padding = kmalloc_array(chan->n_subbufs, sizeof(size_t *),
+	buf->padding = kmalloc_array(chan->n_subbufs, sizeof(size_t),
 				     GFP_KERNEL);
 	if (!buf->padding)
 		goto free_buf;