lkml.org 
[lkml]   [2022]   [Aug]   [20]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH] checkpatch: add ALLOC_UNNECESSARY_ARRAY test
Date
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
\
 
 \ /
  Last update: 2022-08-20 23:42    [W:0.046 / U:0.032 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site