mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH] checkpatch: add ALLOC_UNNECESSARY_ARRAY test
@ 2022-08-20 21:41 Kenneth Lee
  2022-08-21  0:47 ` Joe Perches
  0 siblings, 1 reply; 2+ messages in thread
From: Kenneth Lee @ 2022-08-20 21:41 UTC (permalink / raw)
  To: apw, joe, dwaipayanray1, lukas.bulwahn; +Cc: linux-kernel, Kenneth Lee

Using calloc|malloc_array(1, ...) can be simplified to zalloc|malloc(...)
and improves semantics. This is because we are only allocating one element
so there is no need to use the array version of the methods.

This can be applied to kvmalloc_array, kvcalloc, kcalloc, devm_kcalloc,
and devm_kmalloc_array. Note that there is no devm_kvmalloc_array or
devm_kvcalloc, so the regex does not check for this.

Signed-off-by: Kenneth Lee <klee33@uw.edu>
---
This is my first patch that is not a trivial cleanup, so please let me
know if I am approaching something wrong. Also unsure if the warning
name should be something else besides ALLOC_UNNECESSARY_ARRAY
---
 scripts/checkpatch.pl | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl
index 79e759aac543..83d3a9f308ea 100755
--- a/scripts/checkpatch.pl
+++ b/scripts/checkpatch.pl
@@ -7079,6 +7079,19 @@ sub process {
 			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
 		}
 
+# check for use of unnecessary array alloc methods
+# calloc|malloc_array(1, ...) should be zalloc|malloc(...)
+		if ($line =~ /(\b(?:devm_(?:kcalloc|kmalloc_array))|\b(?:kv|k)(?:calloc|malloc_array))\s*\(\s*1\s*,/) {
+			my $newfunc = "kmalloc";
+			$newfunc = "kvmalloc" if ($1 eq "kvmalloc_array");
+			$newfunc = "kvzalloc" if ($1 eq "kvcalloc");
+			$newfunc = "kzalloc" if ($1 eq "kcalloc");
+			$newfunc = "devm_kzalloc" if ($1 eq "devm_kcalloc");
+			$newfunc = "devm_kmalloc" if ($1 eq "devm_kmalloc_array");
+			WARN("ALLOC_UNNECESSARY_ARRAY",
+			     "$1(1, ...) can be simplified to $newfunc(...)\n" . $herecurr);
+		}
+
 # check for multiple semicolons
 		if ($line =~ /;\s*;\s*$/) {
 			if (WARN("ONE_SEMICOLON",
-- 
2.31.1


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2022-08-21  0:47 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-08-20 21:41 [PATCH] checkpatch: add ALLOC_UNNECESSARY_ARRAY test Kenneth Lee
2022-08-21  0:47 ` Joe Perches

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®