Re: [RFC][PATCH 4/4] pstore: Replace classic kmalloc code pattern with typed argument

From: Przemek Kitszel
Date: Tue Jul 09 2024 - 03:07:25 EST


On 7/8/24 21:18, Kees Cook wrote:
Using a short Coccinelle script, it is possible to replace the classic
kmalloc code patterns with the typed information:

@alloc@
type TYPE;
TYPE *P;
expression GFP;
identifier ALLOC =~ "k[mz]alloc";
@@

P = ALLOC(
- \(sizeof(*P)\|sizeof(TYPE)\), GFP)
+ P, GFP)

Show this just for kmalloc/kzalloc usage in fs/pstore as an example.

Doing this for all allocator calls in the kernel touches much more:

11941 files changed, 22459 insertions(+), 22345 deletions(-)

And obviously requires some more wrappers for kv*alloc, devm_*alloc,
etc.

Signed-off-by: Kees Cook <kees@xxxxxxxxxx>
---
Cc: Tony Luck <tony.luck@xxxxxxxxx>
Cc: "Guilherme G. Piccoli" <gpiccoli@xxxxxxxxxx>
Cc: linux-hardening@xxxxxxxxxxxxxxx
---
fs/pstore/blk.c | 2 +-
fs/pstore/platform.c | 2 +-
fs/pstore/ram.c | 3 +--
fs/pstore/ram_core.c | 2 +-
fs/pstore/zone.c | 2 +-
5 files changed, 5 insertions(+), 6 deletions(-)

diff --git a/fs/pstore/blk.c b/fs/pstore/blk.c
index de8cf5d75f34..7bb9cacb380f 100644
--- a/fs/pstore/blk.c
+++ b/fs/pstore/blk.c
@@ -297,7 +297,7 @@ static int __init __best_effort_init(void)
return -EINVAL;
}
- best_effort_dev = kzalloc(sizeof(*best_effort_dev), GFP_KERNEL);
+ best_effort_dev = kzalloc(best_effort_dev, GFP_KERNEL);
if (!best_effort_dev)
return -ENOMEM;
I expect raised eyebrows and typical vocalizations of amusement :D -
IOW: we should consider changing the name of the macro, although I like
it as is :)

other:
you repeat the pointer name twice, and code is magic anyway, so perhaps:
kzalloc_me(best_effort_dev, GFP_KERNEL);
and another variant to cover declaration-with-init.