blob: c2efdbcd5073fdcd3d2deaba31c45339ad2778b2 [file] [log] [blame]
Martin Roth387dec82017-09-17 19:20:46 -06001#!/usr/bin/env perl
Martin Roth60915b32018-08-10 21:04:05 -06002# SPDX-License-Identifier: GPL-2.0
3#
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004# (c) 2001, Dave Jones. (the file handling bit)
5# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
Martin Roth60915b32018-08-10 21:04:05 -06008# (c) 2010-2018 Joe Perches <joe@perches.com>
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01009
10use strict;
Martin Roth387dec82017-09-17 19:20:46 -060011use warnings;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010012use POSIX;
13use File::Basename;
14use Cwd 'abs_path';
Stefan Reinauerc6080c62016-07-29 16:01:40 -070015use Term::ANSIColor qw(:constants);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010016
17my $P = $0;
18my $D = dirname(abs_path($P));
19
20my $V = '0.32';
21
22use Getopt::Long qw(:config no_auto_abbrev);
23
24my $quiet = 0;
Elyes Haouas84ef4fb2022-04-07 09:40:15 +020025my $verbose = 0;
26my %verbose_messages = ();
27my %verbose_emitted = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010028my $tree = 1;
29my $chk_signoff = 1;
30my $chk_patch = 1;
31my $tst_only;
32my $emacs = 0;
33my $terse = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070034my $showfile = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010035my $file = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070036my $git = 0;
37my %git_commits = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010038my $check = 0;
39my $check_orig = 0;
40my $summary = 1;
41my $mailback = 0;
42my $summary_file = 0;
43my $show_types = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070044my $list_types = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010045my $fix = 0;
46my $fix_inplace = 0;
Martin Rothedd591d2017-03-14 10:16:29 -060047my $root = $P; #coreboot
Elyes HAOUAS18ef5202022-01-29 08:27:14 +010048my $gitroot = $ENV{'GIT_DIR'};
49$gitroot = ".git" if !defined($gitroot);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010050my %debug;
51my %camelcase = ();
52my %use_type = ();
53my @use = ();
54my %ignore_type = ();
55my @ignore = ();
Martin Rothedd591d2017-03-14 10:16:29 -060056my @exclude = (); #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010057my $help = 0;
58my $configuration_file = ".checkpatch.conf";
Elyes Haouas0b1a03c2022-04-07 10:13:54 +020059my $max_line_length = 100;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010060my $ignore_perl_version = 0;
61my $minimum_perl_version = 5.10.0;
62my $min_conf_desc_length = 4;
63my $spelling_file = "$D/spelling.txt";
Stefan Reinauerc6080c62016-07-29 16:01:40 -070064my $codespell = 0;
65my $codespellfile = "/usr/share/codespell/dictionary.txt";
Elyes Haouas84ef4fb2022-04-07 09:40:15 +020066my $user_codespellfile = "";
Martin Rothedd591d2017-03-14 10:16:29 -060067my $conststructsfile = "$D/const_structs.checkpatch";
Elyes Haouas46b07e52022-04-07 10:07:34 +020068my $docsfile = "";
69my $typedefsfile;
Martin Roth387dec82017-09-17 19:20:46 -060070my $color = "auto";
Elyes Haouas8f599602022-04-12 12:55:43 +020071my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +010072my $git_command ='git'; # coreboot
Elyes HAOUAS96771bf2022-01-29 07:28:45 +010073my $tabsize = 8;
Elyes Haouasf62a9892022-04-12 12:17:50 +020074my ${CONFIG_} = "CONFIG_";
Martin Roth1f3daea2017-08-30 13:53:58 -060075# For coreboot jenkins
76# If taint mode is enabled, Untaint the path - files must be in /bin, /usr/bin or /usr/local/bin
77if ( ${^TAINT} ) {
78 $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
79 delete @ENV{ 'IFS', 'CDPATH', 'ENV', 'BASH_ENV' };
80}
81
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010082sub help {
83 my ($exitcode) = @_;
84
85 print << "EOM";
86Usage: $P [OPTION]... [FILE]...
87Version: $V
88
89Options:
90 -q, --quiet quiet
Elyes Haouas46b07e52022-04-07 10:07:34 +020091 -v, --verbose verbose mode
Stefan Reinauerc6080c62016-07-29 16:01:40 -070092 --no-tree run without a kernel tree
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010093 --no-signoff do not check for 'Signed-off-by' line
94 --patch treat FILE as patchfile (default)
95 --emacs emacs compile window format
96 --terse one line per report
Stefan Reinauerc6080c62016-07-29 16:01:40 -070097 --showfile emit diffed file position, not input file position
98 -g, --git treat FILE as a single commit or git revision range
99 single git commit with:
100 <rev>
101 <rev>^
102 <rev>~n
103 multiple git commits with:
104 <rev1>..<rev2>
105 <rev1>...<rev2>
106 <rev>-<count>
107 git merges are ignored
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100108 -f, --file treat FILE as regular source file
109 --subjective, --strict enable more subjective tests
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700110 --list-types list the possible message types
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100111 --types TYPE(,TYPE2...) show only these comma separated message types
112 --ignore TYPE(,TYPE2...) ignore various comma separated message types
Martin Rotha3cac872017-03-04 18:17:35 -0700113 --exclude DIR(,DIR22...) exclude directories
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700114 --show-types show the specific message type in the output
Elyes Haouas0b1a03c2022-04-07 10:13:54 +0200115 --max-line-length=n set the maximum line length, (default $max_line_length)
116 if exceeded, warn on patches
117 requires --strict for use with --file
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100118 --min-conf-desc-length=n set the min description length, if shorter, warn
Elyes Haouas41d43f52022-04-12 19:54:37 +0200119 --tab-size=n set the number of spaces for tab (default $tabsize)
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700120 --root=PATH PATH to the kernel tree root
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100121 --no-summary suppress the per-file summary
122 --mailback only produce a report in case of warnings/errors
123 --summary-file include the filename in summary
124 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
125 'values', 'possible', 'type', and 'attr' (default
126 is all off)
127 --test-only=WORD report only warnings/errors containing WORD
128 literally
129 --fix EXPERIMENTAL - may create horrible results
130 If correctable single-line errors exist, create
131 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
132 with potential errors corrected to the preferred
133 checkpatch style
134 --fix-inplace EXPERIMENTAL - may create horrible results
135 Is the same as --fix, but overwrites the input
136 file. It's your fault if there's no backup or git
137 --ignore-perl-version override checking of perl version. expect
138 runtime errors.
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700139 --codespell Use the codespell dictionary for spelling/typos
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200140 (default:$codespellfile)
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700141 --codespellfile Use this codespell dictionary
Martin Roth387dec82017-09-17 19:20:46 -0600142 --typedefsfile Read additional types from this file
143 --color[=WHEN] Use colors 'always', 'never', or only when output
144 is a terminal ('auto'). Default is 'auto'.
Elyes Haouasf62a9892022-04-12 12:17:50 +0200145 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
146 ${CONFIG_})
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100147 -h, --help, --version display this help and exit
148
149When FILE is - read standard input.
150EOM
151
152 exit($exitcode);
153}
154
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700155sub uniq {
156 my %seen;
157 return grep { !$seen{$_}++ } @_;
158}
159
160sub list_types {
161 my ($exitcode) = @_;
162
163 my $count = 0;
164
165 local $/ = undef;
166
167 open(my $script, '<', abs_path($P)) or
168 die "$P: Can't read '$P' $!\n";
169
170 my $text = <$script>;
171 close($script);
172
Elyes Haouas46b07e52022-04-07 10:07:34 +0200173 my %types = ();
Martin Roth387dec82017-09-17 19:20:46 -0600174 # Also catch when type or level is passed through a variable
Elyes Haouas46b07e52022-04-07 10:07:34 +0200175 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
176 if (defined($1)) {
177 if (exists($types{$2})) {
178 $types{$2} .= ",$1" if ($types{$2} ne $1);
179 } else {
180 $types{$2} = $1;
181 }
182 } else {
183 $types{$2} = "UNDETERMINED";
184 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700185 }
Elyes Haouas46b07e52022-04-07 10:07:34 +0200186
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700187 print("#\tMessage type\n\n");
Elyes Haouas46b07e52022-04-07 10:07:34 +0200188 if ($color) {
189 print(" ( Color coding: ");
190 print(RED . "ERROR" . RESET);
191 print(" | ");
192 print(YELLOW . "WARNING" . RESET);
193 print(" | ");
194 print(GREEN . "CHECK" . RESET);
195 print(" | ");
196 print("Multiple levels / Undetermined");
197 print(" )\n\n");
198 }
199
200 foreach my $type (sort keys %types) {
201 my $orig_type = $type;
202 if ($color) {
203 my $level = $types{$type};
204 if ($level eq "ERROR") {
205 $type = RED . $type . RESET;
206 } elsif ($level eq "WARN") {
207 $type = YELLOW . $type . RESET;
208 } elsif ($level eq "CHK") {
209 $type = GREEN . $type . RESET;
210 }
211 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700212 print(++$count . "\t" . $type . "\n");
Elyes Haouas46b07e52022-04-07 10:07:34 +0200213 if ($verbose && exists($verbose_messages{$orig_type})) {
214 my $message = $verbose_messages{$orig_type};
215 $message =~ s/\n/\n\t/g;
216 print("\t" . $message . "\n\n");
217 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700218 }
219
220 exit($exitcode);
221}
222
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100223my $conf = which_conf($configuration_file);
224if (-f $conf) {
225 my @conf_args;
226 open(my $conffile, '<', "$conf")
227 or warn "$P: Can't find a readable $configuration_file file $!\n";
228
229 while (<$conffile>) {
230 my $line = $_;
231
232 $line =~ s/\s*\n?$//g;
233 $line =~ s/^\s*//g;
234 $line =~ s/\s+/ /g;
235
236 next if ($line =~ m/^\s*#/);
237 next if ($line =~ m/^\s*$/);
238
239 my @words = split(" ", $line);
240 foreach my $word (@words) {
241 last if ($word =~ m/^#/);
242 push (@conf_args, $word);
243 }
244 }
245 close($conffile);
246 unshift(@ARGV, @conf_args) if @conf_args;
247}
248
Elyes Haouas46b07e52022-04-07 10:07:34 +0200249sub load_docs {
250 open(my $docs, '<', "$docsfile")
251 or warn "$P: Can't read the documentation file $docsfile $!\n";
252
253 my $type = '';
254 my $desc = '';
255 my $in_desc = 0;
256
257 while (<$docs>) {
258 chomp;
259 my $line = $_;
260 $line =~ s/\s+$//;
261
262 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
263 if ($desc ne '') {
264 $verbose_messages{$type} = trim($desc);
265 }
266 $type = $1;
267 $desc = '';
268 $in_desc = 1;
269 } elsif ($in_desc) {
270 if ($line =~ /^(?:\s{4,}|$)/) {
271 $line =~ s/^\s{4}//;
272 $desc .= $line;
273 $desc .= "\n";
274 } else {
275 $verbose_messages{$type} = trim($desc);
276 $type = '';
277 $desc = '';
278 $in_desc = 0;
279 }
280 }
281 }
282
283 if ($desc ne '') {
284 $verbose_messages{$type} = trim($desc);
285 }
286 close($docs);
287}
288
Martin Roth387dec82017-09-17 19:20:46 -0600289# Perl's Getopt::Long allows options to take optional arguments after a space.
290# Prevent --color by itself from consuming other arguments
291foreach (@ARGV) {
292 if ($_ eq "--color" || $_ eq "-color") {
293 $_ = "--color=$color";
294 }
295}
296
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100297GetOptions(
298 'q|quiet+' => \$quiet,
Elyes Haouas46b07e52022-04-07 10:07:34 +0200299 'v|verbose!' => \$verbose,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100300 'tree!' => \$tree,
301 'signoff!' => \$chk_signoff,
302 'patch!' => \$chk_patch,
303 'emacs!' => \$emacs,
304 'terse!' => \$terse,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700305 'showfile!' => \$showfile,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100306 'f|file!' => \$file,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700307 'g|git!' => \$git,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100308 'subjective!' => \$check,
309 'strict!' => \$check,
310 'ignore=s' => \@ignore,
Martin Rothedd591d2017-03-14 10:16:29 -0600311 'exclude=s' => \@exclude, #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100312 'types=s' => \@use,
313 'show-types!' => \$show_types,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700314 'list-types!' => \$list_types,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100315 'max-line-length=i' => \$max_line_length,
316 'min-conf-desc-length=i' => \$min_conf_desc_length,
Elyes Haouas41d43f52022-04-12 19:54:37 +0200317 'tab-size=i' => \$tabsize,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100318 'root=s' => \$root,
319 'summary!' => \$summary,
320 'mailback!' => \$mailback,
321 'summary-file!' => \$summary_file,
322 'fix!' => \$fix,
323 'fix-inplace!' => \$fix_inplace,
324 'ignore-perl-version!' => \$ignore_perl_version,
325 'debug=s' => \%debug,
326 'test-only=s' => \$tst_only,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700327 'codespell!' => \$codespell,
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200328 'codespellfile=s' => \$user_codespellfile,
Martin Roth387dec82017-09-17 19:20:46 -0600329 'typedefsfile=s' => \$typedefsfile,
330 'color=s' => \$color,
331 'no-color' => \$color, #keep old behaviors of -nocolor
332 'nocolor' => \$color, #keep old behaviors of -nocolor
Elyes Haouasf62a9892022-04-12 12:17:50 +0200333 'kconfig-prefix=s' => \${CONFIG_},
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100334 'h|help' => \$help,
335 'version' => \$help
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200336) or $help = 2;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100337
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200338if ($user_codespellfile) {
339 # Use the user provided codespell file unconditionally
340 $codespellfile = $user_codespellfile;
341} elsif (!(-f $codespellfile)) {
342 # If /usr/share/codespell/dictionary.txt is not present, try to find it
343 # under codespell's install directory: <codespell_root>/data/dictionary.txt
344 if (($codespell || $help) && which("python3") ne "") {
345 my $python_codespell_dict = << "EOF";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100346
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200347import os.path as op
348import codespell_lib
349codespell_dir = op.dirname(codespell_lib.__file__)
350codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
351print(codespell_file, end='')
352EOF
353
354 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
355 $codespellfile = $codespell_dict if (-f $codespell_dict);
356 }
357}
358
359# $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
360# $help is 2 if invalid option is passed - exitcode: 1
361help($help - 1) if ($help);
362
363die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
364die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
365
366if ($color =~ /^[01]$/) {
367 $color = !$color;
368} elsif ($color =~ /^always$/i) {
369 $color = 1;
370} elsif ($color =~ /^never$/i) {
371 $color = 0;
372} elsif ($color =~ /^auto$/i) {
373 $color = (-t STDOUT);
374} else {
375 die "$P: Invalid color mode: $color\n";
376}
377
378load_docs() if ($verbose);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700379list_types(0) if ($list_types);
380
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100381$fix = 1 if ($fix_inplace);
382$check_orig = $check;
383
384my $exit = 0;
385
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100386my $perl_version_ok = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100387if ($^V && $^V lt $minimum_perl_version) {
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100388 $perl_version_ok = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100389 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100390 exit(1) if (!$ignore_perl_version);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100391}
392
Martin Rothedd591d2017-03-14 10:16:29 -0600393#if no filenames are given, push '-' to read patch from stdin
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100394if ($#ARGV < 0) {
Martin Rothedd591d2017-03-14 10:16:29 -0600395 push(@ARGV, '-');
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100396}
397
Elyes Haouas41d43f52022-04-12 19:54:37 +0200398# skip TAB size 1 to avoid additional checks on $tabsize - 1
399die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
400
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100401sub hash_save_array_words {
402 my ($hashRef, $arrayRef) = @_;
403
404 my @array = split(/,/, join(',', @$arrayRef));
405 foreach my $word (@array) {
406 $word =~ s/\s*\n?$//g;
407 $word =~ s/^\s*//g;
408 $word =~ s/\s+/ /g;
409 $word =~ tr/[a-z]/[A-Z]/;
410
411 next if ($word =~ m/^\s*#/);
412 next if ($word =~ m/^\s*$/);
413
414 $hashRef->{$word}++;
415 }
416}
417
418sub hash_show_words {
419 my ($hashRef, $prefix) = @_;
420
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700421 if (keys %$hashRef) {
422 print "\nNOTE: $prefix message types:";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100423 foreach my $word (sort keys %$hashRef) {
424 print " $word";
425 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700426 print "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100427 }
428}
429
430hash_save_array_words(\%ignore_type, \@ignore);
431hash_save_array_words(\%use_type, \@use);
432
433my $dbg_values = 0;
434my $dbg_possible = 0;
435my $dbg_type = 0;
436my $dbg_attr = 0;
437for my $key (keys %debug) {
438 ## no critic
439 eval "\${dbg_$key} = '$debug{$key}';";
440 die "$@" if ($@);
441}
442
443my $rpt_cleaners = 0;
444
445if ($terse) {
446 $emacs = 1;
447 $quiet++;
448}
449
450if ($tree) {
451 if (defined $root) {
452 if (!top_of_kernel_tree($root)) {
453 die "$P: $root: --root does not point at a valid tree\n";
454 }
455 } else {
456 if (top_of_kernel_tree('.')) {
457 $root = '.';
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700458 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100459 top_of_kernel_tree($1)) {
460 $root = $1;
461 }
462 }
463
464 if (!defined $root) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700465 print "Must be run from the top-level dir. of a kernel tree\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100466 exit(2);
467 }
468}
469
470my $emitted_corrupt = 0;
471
472our $Ident = qr{
473 [A-Za-z_][A-Za-z\d_]*
474 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
475 }x;
476our $Storage = qr{extern|static|asmlinkage};
477our $Sparse = qr{
478 __user|
479 __kernel|
480 __force|
481 __iomem|
482 __must_check|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100483 __kprobes|
484 __ref|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200485 __refconst|
486 __refdata|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700487 __rcu|
488 __private
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100489 }x;
490our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
491our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
492our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
493our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
494our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
495
496# Notes to $Attribute:
497# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
498our $Attribute = qr{
499 const|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200500 volatile|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100501 __percpu|
502 __nocast|
503 __safe|
Martin Rothedd591d2017-03-14 10:16:29 -0600504 __bitwise|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100505 __packed__|
506 __packed2__|
507 __naked|
508 __maybe_unused|
509 __always_unused|
510 __noreturn|
511 __used|
512 __cold|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700513 __pure|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100514 __noclone|
515 __deprecated|
516 __read_mostly|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200517 __ro_after_init|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100518 __kprobes|
519 $InitAttribute|
520 ____cacheline_aligned|
521 ____cacheline_aligned_in_smp|
522 ____cacheline_internodealigned_in_smp|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200523 __weak|
524 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100525 }x;
526our $Modifier;
527our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
528our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
529our $Lval = qr{$Ident(?:$Member)*};
530
531our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
532our $Binary = qr{(?i)0b[01]+$Int_type?};
533our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
534our $Int = qr{[0-9]+$Int_type?};
535our $Octal = qr{0[0-7]+$Int_type?};
Elyes Haouas26e0b942022-05-22 11:11:11 +0200536our $String = qr{(?:\b[Lu])?"[X\t]*"};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100537our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
538our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
539our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
540our $Float = qr{$Float_hex|$Float_dec|$Float_int};
541our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
542our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
543our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
544our $Arithmetic = qr{\+|-|\*|\/|%};
545our $Operators = qr{
546 <=|>=|==|!=|
547 =>|->|<<|>>|<|>|!|~|
548 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
549 }x;
550
551our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
552
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700553our $BasicType;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100554our $NonptrType;
555our $NonptrTypeMisordered;
556our $NonptrTypeWithAttr;
557our $Type;
558our $TypeMisordered;
559our $Declare;
560our $DeclareMisordered;
561
562our $NON_ASCII_UTF8 = qr{
563 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
564 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
565 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
566 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
567 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
568 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
569 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
570}x;
571
572our $UTF8 = qr{
573 [\x09\x0A\x0D\x20-\x7E] # ASCII
574 | $NON_ASCII_UTF8
575}x;
576
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700577our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
578our $typeOtherOSTypedefs = qr{(?x:
579 u_(?:char|short|int|long) | # bsd
580 u(?:nchar|short|int|long) # sysv
581)};
582our $typeKernelTypedefs = qr{(?x:
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100583 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
584 atomic_t
585)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700586our $typeTypedefs = qr{(?x:
587 $typeC99Typedefs\b|
588 $typeOtherOSTypedefs\b|
589 $typeKernelTypedefs\b
590)};
591
592our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100593
594our $logFunctions = qr{(?x:
Martin Rothedd591d2017-03-14 10:16:29 -0600595 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100596 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
Martin Roth60915b32018-08-10 21:04:05 -0600597 TP_printk|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100598 WARN(?:_RATELIMIT|_ONCE|)|
599 panic|
600 MODULE_[A-Z_]+|
601 seq_vprintf|seq_printf|seq_puts
602)};
603
Elyes Haouasa7b0d382022-05-23 18:33:15 +0200604our $allocFunctions = qr{(?x:
605 (?:(?:devm_)?
606 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
607 kstrdup(?:_const)? |
608 kmemdup(?:_nul)?) |
609 (?:\w+)?alloc_skb(?:_ip_align)? |
610 # dev_alloc_skb/netdev_alloc_skb, et al
611 dma_alloc_coherent
612)};
613
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100614our $signature_tags = qr{(?xi:
615 Signed-off-by:|
616 Acked-by:|
617 Tested-by:|
618 Reviewed-by:|
619 Reported-by:|
620 Suggested-by:|
Michael Niewöhner8cfd3f82022-11-02 18:17:57 +0100621 Co-authored-by:|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100622 To:|
623 Cc:
624)};
625
626our @typeListMisordered = (
627 qr{char\s+(?:un)?signed},
628 qr{int\s+(?:(?:un)?signed\s+)?short\s},
629 qr{int\s+short(?:\s+(?:un)?signed)},
630 qr{short\s+int(?:\s+(?:un)?signed)},
631 qr{(?:un)?signed\s+int\s+short},
632 qr{short\s+(?:un)?signed},
633 qr{long\s+int\s+(?:un)?signed},
634 qr{int\s+long\s+(?:un)?signed},
635 qr{long\s+(?:un)?signed\s+int},
636 qr{int\s+(?:un)?signed\s+long},
637 qr{int\s+(?:un)?signed},
638 qr{int\s+long\s+long\s+(?:un)?signed},
639 qr{long\s+long\s+int\s+(?:un)?signed},
640 qr{long\s+long\s+(?:un)?signed\s+int},
641 qr{long\s+long\s+(?:un)?signed},
642 qr{long\s+(?:un)?signed},
643);
644
645our @typeList = (
646 qr{void},
647 qr{(?:(?:un)?signed\s+)?char},
648 qr{(?:(?:un)?signed\s+)?short\s+int},
649 qr{(?:(?:un)?signed\s+)?short},
650 qr{(?:(?:un)?signed\s+)?int},
651 qr{(?:(?:un)?signed\s+)?long\s+int},
652 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
653 qr{(?:(?:un)?signed\s+)?long\s+long},
654 qr{(?:(?:un)?signed\s+)?long},
655 qr{(?:un)?signed},
656 qr{float},
657 qr{double},
658 qr{bool},
659 qr{struct\s+$Ident},
660 qr{union\s+$Ident},
661 qr{enum\s+$Ident},
662 qr{${Ident}_t},
663 qr{${Ident}_handler},
664 qr{${Ident}_handler_fn},
665 @typeListMisordered,
666);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700667
668our $C90_int_types = qr{(?x:
669 long\s+long\s+int\s+(?:un)?signed|
670 long\s+long\s+(?:un)?signed\s+int|
671 long\s+long\s+(?:un)?signed|
672 (?:(?:un)?signed\s+)?long\s+long\s+int|
673 (?:(?:un)?signed\s+)?long\s+long|
674 int\s+long\s+long\s+(?:un)?signed|
675 int\s+(?:(?:un)?signed\s+)?long\s+long|
676
677 long\s+int\s+(?:un)?signed|
678 long\s+(?:un)?signed\s+int|
679 long\s+(?:un)?signed|
680 (?:(?:un)?signed\s+)?long\s+int|
681 (?:(?:un)?signed\s+)?long|
682 int\s+long\s+(?:un)?signed|
683 int\s+(?:(?:un)?signed\s+)?long|
684
685 int\s+(?:un)?signed|
686 (?:(?:un)?signed\s+)?int
687)};
688
689our @typeListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100690our @typeListWithAttr = (
691 @typeList,
692 qr{struct\s+$InitAttribute\s+$Ident},
693 qr{union\s+$InitAttribute\s+$Ident},
694);
695
696our @modifierList = (
697 qr{fastcall},
698);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700699our @modifierListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100700
701our @mode_permission_funcs = (
702 ["module_param", 3],
703 ["module_param_(?:array|named|string)", 4],
704 ["module_param_array_named", 5],
705 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
706 ["proc_create(?:_data|)", 2],
Martin Rothedd591d2017-03-14 10:16:29 -0600707 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
708 ["IIO_DEV_ATTR_[A-Z_]+", 1],
709 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
710 ["SENSOR_TEMPLATE(?:_2|)", 3],
711 ["__ATTR", 2],
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100712);
713
Elyes Haouas84083a22022-04-12 12:28:32 +0200714my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
715
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100716#Create a search pattern for all these functions to speed up a loop below
717our $mode_perms_search = "";
718foreach my $entry (@mode_permission_funcs) {
719 $mode_perms_search .= '|' if ($mode_perms_search ne "");
720 $mode_perms_search .= $entry->[0];
721}
Martin Roth60915b32018-08-10 21:04:05 -0600722$mode_perms_search = "(?:${mode_perms_search})";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100723
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700724our $mode_perms_world_writable = qr{
725 S_IWUGO |
726 S_IWOTH |
727 S_IRWXUGO |
728 S_IALLUGO |
729 0[0-7][0-7][2367]
730}x;
731
Martin Rothedd591d2017-03-14 10:16:29 -0600732our %mode_permission_string_types = (
733 "S_IRWXU" => 0700,
734 "S_IRUSR" => 0400,
735 "S_IWUSR" => 0200,
736 "S_IXUSR" => 0100,
737 "S_IRWXG" => 0070,
738 "S_IRGRP" => 0040,
739 "S_IWGRP" => 0020,
740 "S_IXGRP" => 0010,
741 "S_IRWXO" => 0007,
742 "S_IROTH" => 0004,
743 "S_IWOTH" => 0002,
744 "S_IXOTH" => 0001,
745 "S_IRWXUGO" => 0777,
746 "S_IRUGO" => 0444,
747 "S_IWUGO" => 0222,
748 "S_IXUGO" => 0111,
749);
750
751#Create a search pattern for all these strings to speed up a loop below
752our $mode_perms_string_search = "";
753foreach my $entry (keys %mode_permission_string_types) {
754 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
755 $mode_perms_string_search .= $entry;
756}
Martin Roth60915b32018-08-10 21:04:05 -0600757our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
758our $multi_mode_perms_string_search = qr{
759 ${single_mode_perms_string_search}
760 (?:\s*\|\s*${single_mode_perms_string_search})*
761}x;
762
763sub perms_to_octal {
764 my ($string) = @_;
765
766 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
767
768 my $val = "";
769 my $oval = "";
770 my $to = 0;
771 my $curpos = 0;
772 my $lastpos = 0;
773 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
774 $curpos = pos($string);
775 my $match = $2;
776 my $omatch = $1;
777 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
778 $lastpos = $curpos;
779 $to |= $mode_permission_string_types{$match};
780 $val .= '\s*\|\s*' if ($val ne "");
781 $val .= $match;
782 $oval .= $omatch;
783 }
784 $oval =~ s/^\s*\|\s*//;
785 $oval =~ s/\s*\|\s*$//;
786 return sprintf("%04o", $to);
787}
Martin Rothedd591d2017-03-14 10:16:29 -0600788
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100789our $allowed_asm_includes = qr{(?x:
790 irq|
791 memory|
792 time|
793 reboot
794)};
795# memory.h: ARM has a custom one
796
797# Load common spelling mistakes and build regular expression list.
798my $misspellings;
799my %spelling_fix;
800
801if (open(my $spelling, '<', $spelling_file)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100802 while (<$spelling>) {
803 my $line = $_;
804
805 $line =~ s/\s*\n?$//g;
806 $line =~ s/^\s*//g;
807
808 next if ($line =~ m/^\s*#/);
809 next if ($line =~ m/^\s*$/);
810
811 my ($suspect, $fix) = split(/\|\|/, $line);
812
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100813 $spelling_fix{$suspect} = $fix;
814 }
815 close($spelling);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100816} else {
817 warn "No typos will be found - file '$spelling_file': $!\n";
818}
819
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700820if ($codespell) {
821 if (open(my $spelling, '<', $codespellfile)) {
822 while (<$spelling>) {
823 my $line = $_;
824
825 $line =~ s/\s*\n?$//g;
826 $line =~ s/^\s*//g;
827
828 next if ($line =~ m/^\s*#/);
829 next if ($line =~ m/^\s*$/);
830 next if ($line =~ m/, disabled/i);
831
832 $line =~ s/,.*$//;
833
834 my ($suspect, $fix) = split(/->/, $line);
835
836 $spelling_fix{$suspect} = $fix;
837 }
838 close($spelling);
839 } else {
840 warn "No codespell typos will be found - file '$codespellfile': $!\n";
841 }
842}
843
844$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
845
Martin Roth387dec82017-09-17 19:20:46 -0600846sub read_words {
847 my ($wordsRef, $file) = @_;
Martin Rothedd591d2017-03-14 10:16:29 -0600848
Martin Roth387dec82017-09-17 19:20:46 -0600849 if (open(my $words, '<', $file)) {
850 while (<$words>) {
851 my $line = $_;
Martin Rothedd591d2017-03-14 10:16:29 -0600852
Martin Roth387dec82017-09-17 19:20:46 -0600853 $line =~ s/\s*\n?$//g;
854 $line =~ s/^\s*//g;
855
856 next if ($line =~ m/^\s*#/);
857 next if ($line =~ m/^\s*$/);
858 if ($line =~ /\s/) {
859 print("$file: '$line' invalid - ignored\n");
860 next;
861 }
862
Elyes Haouas14c49e32022-05-08 10:11:40 +0200863 $$wordsRef .= '|' if (defined $$wordsRef);
Martin Roth387dec82017-09-17 19:20:46 -0600864 $$wordsRef .= $line;
Martin Rothedd591d2017-03-14 10:16:29 -0600865 }
Martin Roth387dec82017-09-17 19:20:46 -0600866 close($file);
867 return 1;
Martin Rothedd591d2017-03-14 10:16:29 -0600868 }
Martin Roth387dec82017-09-17 19:20:46 -0600869
870 return 0;
Martin Rothedd591d2017-03-14 10:16:29 -0600871}
872
Elyes Haouas43529c82022-04-12 13:19:50 +0200873my $const_structs;
874if (show_type("CONST_STRUCT")) {
875 read_words(\$const_structs, $conststructsfile)
876 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
877}
Martin Roth387dec82017-09-17 19:20:46 -0600878
Elyes Haouas26e0b942022-05-22 11:11:11 +0200879if (defined($typedefsfile)) {
880 my $typeOtherTypedefs;
Martin Roth387dec82017-09-17 19:20:46 -0600881 read_words(\$typeOtherTypedefs, $typedefsfile)
882 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
Elyes Haouas26e0b942022-05-22 11:11:11 +0200883 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
Martin Roth387dec82017-09-17 19:20:46 -0600884}
Martin Roth387dec82017-09-17 19:20:46 -0600885
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100886sub build_types {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700887 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
888 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100889 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
890 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
891 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700892 $BasicType = qr{
893 (?:$typeTypedefs\b)|
894 (?:${all}\b)
895 }x;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100896 $NonptrType = qr{
897 (?:$Modifier\s+|const\s+)*
898 (?:
899 (?:typeof|__typeof__)\s*\([^\)]*\)|
900 (?:$typeTypedefs\b)|
901 (?:${all}\b)
902 )
903 (?:\s+$Modifier|\s+const)*
904 }x;
905 $NonptrTypeMisordered = qr{
906 (?:$Modifier\s+|const\s+)*
907 (?:
908 (?:${Misordered}\b)
909 )
910 (?:\s+$Modifier|\s+const)*
911 }x;
912 $NonptrTypeWithAttr = qr{
913 (?:$Modifier\s+|const\s+)*
914 (?:
915 (?:typeof|__typeof__)\s*\([^\)]*\)|
916 (?:$typeTypedefs\b)|
917 (?:${allWithAttr}\b)
918 )
919 (?:\s+$Modifier|\s+const)*
920 }x;
921 $Type = qr{
922 $NonptrType
Elyes Haouas26e0b942022-05-22 11:11:11 +0200923 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100924 (?:\s+$Inline|\s+$Modifier)*
925 }x;
926 $TypeMisordered = qr{
927 $NonptrTypeMisordered
Elyes Haouas26e0b942022-05-22 11:11:11 +0200928 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100929 (?:\s+$Inline|\s+$Modifier)*
930 }x;
931 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
932 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
933}
934build_types();
935
936our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
937
938# Using $balanced_parens, $LvalOrFunc, or $FuncArg
939# requires at least perl version v5.10.0
940# Any use must be runtime checked with $^V
941
942our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
943our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700944our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100945
946our $declaration_macros = qr{(?x:
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700947 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
Martin Roth387dec82017-09-17 19:20:46 -0600948 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
Elyes Haouasd27b2e82022-09-05 11:50:48 +0200949 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
950 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100951)};
952
Elyes Haouas84083a22022-04-12 12:28:32 +0200953our %allow_repeated_words = (
954 add => '',
955 added => '',
956 bad => '',
957 be => '',
958);
959
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100960sub deparenthesize {
961 my ($string) = @_;
962 return "" if (!defined($string));
963
964 while ($string =~ /^\s*\(.*\)\s*$/) {
965 $string =~ s@^\s*\(\s*@@;
966 $string =~ s@\s*\)\s*$@@;
967 }
968
969 $string =~ s@\s+@ @g;
970
971 return $string;
972}
973
974sub seed_camelcase_file {
975 my ($file) = @_;
976
977 return if (!(-f $file));
978
979 local $/;
980
981 open(my $include_file, '<', "$file")
982 or warn "$P: Can't read '$file' $!\n";
983 my $text = <$include_file>;
984 close($include_file);
985
986 my @lines = split('\n', $text);
987
988 foreach my $line (@lines) {
989 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
990 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
991 $camelcase{$1} = 1;
992 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
993 $camelcase{$1} = 1;
994 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
995 $camelcase{$1} = 1;
996 }
997 }
998}
999
Martin Rothedd591d2017-03-14 10:16:29 -06001000sub is_maintained_obsolete {
1001 my ($filename) = @_;
1002
1003 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1004
1005 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1006
1007 return $status =~ /obsolete/i;
1008}
1009
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001010my $camelcase_seeded = 0;
1011sub seed_camelcase_includes {
1012 return if ($camelcase_seeded);
1013
1014 my $files;
1015 my $camelcase_cache = "";
1016 my @include_files = ();
1017
1018 $camelcase_seeded = 1;
1019
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001020 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001021 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001022 chomp $git_last_include_commit;
1023 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1024 } else {
1025 my $last_mod_date = 0;
1026 $files = `find $root/include -name "*.h"`;
1027 @include_files = split('\n', $files);
1028 foreach my $file (@include_files) {
1029 my $date = POSIX::strftime("%Y%m%d%H%M",
1030 localtime((stat $file)[9]));
1031 $last_mod_date = $date if ($last_mod_date < $date);
1032 }
1033 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1034 }
1035
1036 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1037 open(my $camelcase_file, '<', "$camelcase_cache")
1038 or warn "$P: Can't read '$camelcase_cache' $!\n";
1039 while (<$camelcase_file>) {
1040 chomp;
1041 $camelcase{$_} = 1;
1042 }
1043 close($camelcase_file);
1044
1045 return;
1046 }
1047
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001048 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001049 $files = `${git_command} ls-files "include/*.h"`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001050 @include_files = split('\n', $files);
1051 }
1052
1053 foreach my $file (@include_files) {
1054 seed_camelcase_file($file);
1055 }
1056
1057 if ($camelcase_cache ne "") {
1058 unlink glob ".checkpatch-camelcase.*";
1059 open(my $camelcase_file, '>', "$camelcase_cache")
1060 or warn "$P: Can't write '$camelcase_cache' $!\n";
1061 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1062 print $camelcase_file ("$_\n");
1063 }
1064 close($camelcase_file);
1065 }
1066}
1067
1068sub git_commit_info {
1069 my ($commit, $id, $desc) = @_;
1070
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001071 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001072
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001073 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001074 $output =~ s/^\s*//gm;
1075 my @lines = split("\n", $output);
1076
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001077 return ($id, $desc) if ($#lines < 0);
1078
Elyes Haouas26e0b942022-05-22 11:11:11 +02001079 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001080# Maybe one day convert this block of bash into something that returns
1081# all matching commit ids, but it's very slow...
1082#
1083# echo "checking commits $1..."
1084# git rev-list --remotes | grep -i "^$1" |
1085# while read line ; do
1086# git log --format='%H %s' -1 $line |
1087# echo "commit $(cut -c 1-12,41-)"
1088# done
Elyes Haouas26e0b942022-05-22 11:11:11 +02001089 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1090 $lines[0] =~ /^fatal: bad object $commit/) {
Martin Roth387dec82017-09-17 19:20:46 -06001091 $id = undef;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001092 } else {
1093 $id = substr($lines[0], 0, 12);
1094 $desc = substr($lines[0], 41);
1095 }
1096
1097 return ($id, $desc);
1098}
1099
1100$chk_signoff = 0 if ($file);
1101
1102my @rawlines = ();
1103my @lines = ();
1104my @fixed = ();
1105my @fixed_inserted = ();
1106my @fixed_deleted = ();
1107my $fixlinenr = -1;
1108
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001109# If input is git commits, extract all commits from the commit expressions.
1110# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001111die "$P: No git repository found\n" if ($git && !-e "$gitroot");
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001112
1113if ($git) {
1114 my @commits = ();
1115 foreach my $commit_expr (@ARGV) {
1116 my $git_range;
1117 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1118 $git_range = "-$2 $1";
1119 } elsif ($commit_expr =~ m/\.\./) {
1120 $git_range = "$commit_expr";
1121 } else {
1122 $git_range = "-1 $commit_expr";
1123 }
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001124 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001125 foreach my $line (split(/\n/, $lines)) {
1126 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1127 next if (!defined($1) || !defined($2));
1128 my $sha1 = $1;
1129 my $subject = $2;
1130 unshift(@commits, $sha1);
1131 $git_commits{$sha1} = $subject;
1132 }
1133 }
1134 die "$P: no git commits after extraction!\n" if (@commits == 0);
1135 @ARGV = @commits;
1136}
1137
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001138my $vname;
Elyes Haouas8f599602022-04-12 12:55:43 +02001139$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
Martin Roth387dec82017-09-17 19:20:46 -06001140for my $filename (@ARGV) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001141 my $FILE;
Martin Rotha9868b22018-01-27 17:31:42 -07001142
1143 # coreboot: Mark filename as untainted
1144 $filename =~ /^(.*)$/s or die; $filename = $1;
1145
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001146 if ($git) {
1147 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1148 die "$P: $filename: git format-patch failed - $!\n";
1149 } elsif ($file) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001150 open($FILE, '-|', "diff -u /dev/null $filename") ||
1151 die "$P: $filename: diff failed - $!\n";
1152 } elsif ($filename eq '-') {
1153 open($FILE, '<&STDIN');
1154 } else {
1155 open($FILE, '<', "$filename") ||
1156 die "$P: $filename: open failed - $!\n";
1157 }
1158 if ($filename eq '-') {
1159 $vname = 'Your patch';
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001160 } elsif ($git) {
1161 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001162 } else {
1163 $vname = $filename;
1164 }
1165 while (<$FILE>) {
1166 chomp;
1167 push(@rawlines, $_);
1168 }
1169 close($FILE);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001170
1171 if ($#ARGV > 0 && $quiet == 0) {
1172 print '-' x length($vname) . "\n";
1173 print "$vname\n";
1174 print '-' x length($vname) . "\n";
1175 }
1176
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001177 if (!process($filename)) {
1178 $exit = 1;
1179 }
1180 @rawlines = ();
1181 @lines = ();
1182 @fixed = ();
1183 @fixed_inserted = ();
1184 @fixed_deleted = ();
1185 $fixlinenr = -1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001186 @modifierListFile = ();
1187 @typeListFile = ();
1188 build_types();
1189}
1190
1191if (!$quiet) {
1192 hash_show_words(\%use_type, "Used");
1193 hash_show_words(\%ignore_type, "Ignored");
1194
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001195 if (!$perl_version_ok) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001196 print << "EOM"
1197
1198NOTE: perl $^V is not modern enough to detect all possible issues.
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001199 An upgrade to at least perl $minimum_perl_version is suggested.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001200EOM
1201 }
1202 if ($exit) {
1203 print << "EOM"
1204
1205NOTE: If any of the errors are false positives, please report
1206 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1207EOM
1208 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001209}
1210
1211exit($exit);
1212
1213sub top_of_kernel_tree {
1214 my ($root) = @_;
1215
1216 my @tree_check = (
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001217 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1218 "README", "Documentation", "arch", "include", "drivers",
1219 "fs", "init", "ipc", "kernel", "lib", "scripts",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001220 );
1221
1222 foreach my $check (@tree_check) {
1223 if (! -e $root . '/' . $check) {
1224 return 0;
1225 }
1226 }
1227 return 1;
1228}
1229
1230sub parse_email {
1231 my ($formatted_email) = @_;
1232
1233 my $name = "";
1234 my $address = "";
1235 my $comment = "";
1236
1237 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1238 $name = $1;
1239 $address = $2;
1240 $comment = $3 if defined $3;
1241 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1242 $address = $1;
1243 $comment = $2 if defined $2;
1244 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1245 $address = $1;
1246 $comment = $2 if defined $2;
Martin Roth60915b32018-08-10 21:04:05 -06001247 $formatted_email =~ s/\Q$address\E.*$//;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001248 $name = $formatted_email;
1249 $name = trim($name);
1250 $name =~ s/^\"|\"$//g;
1251 # If there's a name left after stripping spaces and
1252 # leading quotes, and the address doesn't have both
1253 # leading and trailing angle brackets, the address
1254 # is invalid. ie:
1255 # "joe smith joe@smith.com" bad
1256 # "joe smith <joe@smith.com" bad
1257 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1258 $name = "";
1259 $address = "";
1260 $comment = "";
1261 }
1262 }
1263
1264 $name = trim($name);
1265 $name =~ s/^\"|\"$//g;
1266 $address = trim($address);
1267 $address =~ s/^\<|\>$//g;
1268
1269 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1270 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1271 $name = "\"$name\"";
1272 }
1273
1274 return ($name, $address, $comment);
1275}
1276
1277sub format_email {
1278 my ($name, $address) = @_;
1279
1280 my $formatted_email;
1281
1282 $name = trim($name);
1283 $name =~ s/^\"|\"$//g;
1284 $address = trim($address);
1285
1286 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1287 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1288 $name = "\"$name\"";
1289 }
1290
1291 if ("$name" eq "") {
1292 $formatted_email = "$address";
1293 } else {
1294 $formatted_email = "$name <$address>";
1295 }
1296
1297 return $formatted_email;
1298}
1299
1300sub which {
1301 my ($bin) = @_;
1302
1303 foreach my $path (split(/:/, $ENV{PATH})) {
1304 if (-e "$path/$bin") {
1305 return "$path/$bin";
1306 }
1307 }
1308
1309 return "";
1310}
1311
1312sub which_conf {
1313 my ($conf) = @_;
1314
1315 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1316 if (-e "$path/$conf") {
1317 return "$path/$conf";
1318 }
1319 }
1320
1321 return "";
1322}
1323
1324sub expand_tabs {
1325 my ($str) = @_;
1326
1327 my $res = '';
1328 my $n = 0;
1329 for my $c (split(//, $str)) {
1330 if ($c eq "\t") {
1331 $res .= ' ';
1332 $n++;
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01001333 for (; ($n % $tabsize) != 0; $n++) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001334 $res .= ' ';
1335 }
1336 next;
1337 }
1338 $res .= $c;
1339 $n++;
1340 }
1341
1342 return $res;
1343}
1344sub copy_spacing {
1345 (my $res = shift) =~ tr/\t/ /c;
1346 return $res;
1347}
1348
1349sub line_stats {
1350 my ($line) = @_;
1351
Elyes Haouas26e0b942022-05-22 11:11:11 +02001352 # Drop the diff line leader and expand tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001353 $line =~ s/^.//;
Julius Werner218906d2021-03-25 21:12:49 -07001354
1355 # Treat labels like whitespace when counting indentation
1356 $line =~ s/^( ?$Ident:)/" " x length($1)/e;
1357
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001358 $line = expand_tabs($line);
1359
1360 # Pick the indent from the front of the line.
1361 my ($white) = ($line =~ /^(\s*)/);
1362
1363 return (length($line), length($white));
1364}
1365
1366my $sanitise_quote = '';
1367
1368sub sanitise_line_reset {
1369 my ($in_comment) = @_;
1370
1371 if ($in_comment) {
1372 $sanitise_quote = '*/';
1373 } else {
1374 $sanitise_quote = '';
1375 }
1376}
1377sub sanitise_line {
1378 my ($line) = @_;
1379
1380 my $res = '';
1381 my $l = '';
1382
1383 my $qlen = 0;
1384 my $off = 0;
1385 my $c;
1386
1387 # Always copy over the diff marker.
1388 $res = substr($line, 0, 1);
1389
1390 for ($off = 1; $off < length($line); $off++) {
1391 $c = substr($line, $off, 1);
1392
Martin Roth60915b32018-08-10 21:04:05 -06001393 # Comments we are whacking completely including the begin
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001394 # and end, all to $;.
1395 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1396 $sanitise_quote = '*/';
1397
1398 substr($res, $off, 2, "$;$;");
1399 $off++;
1400 next;
1401 }
1402 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1403 $sanitise_quote = '';
1404 substr($res, $off, 2, "$;$;");
1405 $off++;
1406 next;
1407 }
1408 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1409 $sanitise_quote = '//';
1410
1411 substr($res, $off, 2, $sanitise_quote);
1412 $off++;
1413 next;
1414 }
1415
1416 # A \ in a string means ignore the next character.
1417 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1418 $c eq "\\") {
1419 substr($res, $off, 2, 'XX');
1420 $off++;
1421 next;
1422 }
1423 # Regular quotes.
1424 if ($c eq "'" || $c eq '"') {
1425 if ($sanitise_quote eq '') {
1426 $sanitise_quote = $c;
1427
1428 substr($res, $off, 1, $c);
1429 next;
1430 } elsif ($sanitise_quote eq $c) {
1431 $sanitise_quote = '';
1432 }
1433 }
1434
1435 #print "c<$c> SQ<$sanitise_quote>\n";
1436 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1437 substr($res, $off, 1, $;);
1438 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1439 substr($res, $off, 1, $;);
1440 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1441 substr($res, $off, 1, 'X');
1442 } else {
1443 substr($res, $off, 1, $c);
1444 }
1445 }
1446
1447 if ($sanitise_quote eq '//') {
1448 $sanitise_quote = '';
1449 }
1450
1451 # The pathname on a #include may be surrounded by '<' and '>'.
1452 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1453 my $clean = 'X' x length($1);
1454 $res =~ s@\<.*\>@<$clean>@;
1455
1456 # The whole of a #error is a string.
1457 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1458 my $clean = 'X' x length($1);
1459 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1460 }
1461
Martin Rothedd591d2017-03-14 10:16:29 -06001462 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1463 my $match = $1;
1464 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1465 }
1466
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001467 return $res;
1468}
1469
1470sub get_quoted_string {
1471 my ($line, $rawline) = @_;
1472
Martin Roth60915b32018-08-10 21:04:05 -06001473 return "" if (!defined($line) || !defined($rawline));
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001474 return "" if ($line !~ m/($String)/g);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001475 return substr($rawline, $-[0], $+[0] - $-[0]);
1476}
1477
1478sub ctx_statement_block {
1479 my ($linenr, $remain, $off) = @_;
1480 my $line = $linenr - 1;
1481 my $blk = '';
1482 my $soff = $off;
1483 my $coff = $off - 1;
1484 my $coff_set = 0;
1485
1486 my $loff = 0;
1487
1488 my $type = '';
1489 my $level = 0;
Julius Werner218906d2021-03-25 21:12:49 -07001490 my @stack = (['', $level]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001491 my $p;
1492 my $c;
1493 my $len = 0;
1494
1495 my $remainder;
1496 while (1) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001497 #warn "CSB: blk<$blk> remain<$remain>\n";
1498 # If we are about to drop off the end, pull in more
1499 # context.
1500 if ($off >= $len) {
1501 for (; $remain > 0; $line++) {
1502 last if (!defined $lines[$line]);
1503 next if ($lines[$line] =~ /^-/);
1504 $remain--;
1505 $loff = $len;
1506 $blk .= $lines[$line] . "\n";
1507 $len = length($blk);
1508 $line++;
1509 last;
1510 }
1511 # Bail if there is no further context.
1512 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1513 if ($off >= $len) {
1514 last;
1515 }
1516 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1517 $level++;
1518 $type = '#';
1519 }
1520 }
1521 $p = $c;
1522 $c = substr($blk, $off, 1);
1523 $remainder = substr($blk, $off);
1524
1525 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1526
1527 # Handle nested #if/#else.
1528 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1529 push(@stack, [ $type, $level ]);
Julius Werner218906d2021-03-25 21:12:49 -07001530 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/ && $#stack > 0) {
1531 ($type, $level) = @{$stack[$#stack]};
1532 } elsif ($remainder =~ /^#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001533 ($type, $level) = @{pop(@stack)};
1534 }
1535
1536 # Statement ends at the ';' or a close '}' at the
1537 # outermost level.
1538 if ($level == 0 && $c eq ';') {
1539 last;
1540 }
1541
1542 # An else is really a conditional as long as its not else if
1543 if ($level == 0 && $coff_set == 0 &&
1544 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1545 $remainder =~ /^(else)(?:\s|{)/ &&
1546 $remainder !~ /^else\s+if\b/) {
1547 $coff = $off + length($1) - 1;
1548 $coff_set = 1;
1549 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1550 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1551 }
1552
1553 if (($type eq '' || $type eq '(') && $c eq '(') {
1554 $level++;
1555 $type = '(';
1556 }
1557 if ($type eq '(' && $c eq ')') {
1558 $level--;
1559 $type = ($level != 0)? '(' : '';
1560
1561 if ($level == 0 && $coff < $soff) {
1562 $coff = $off;
1563 $coff_set = 1;
1564 #warn "CSB: mark coff<$coff>\n";
1565 }
1566 }
1567 if (($type eq '' || $type eq '{') && $c eq '{') {
1568 $level++;
1569 $type = '{';
1570 }
1571 if ($type eq '{' && $c eq '}') {
1572 $level--;
1573 $type = ($level != 0)? '{' : '';
1574
1575 if ($level == 0) {
1576 if (substr($blk, $off + 1, 1) eq ';') {
1577 $off++;
1578 }
1579 last;
1580 }
1581 }
1582 # Preprocessor commands end at the newline unless escaped.
1583 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1584 $level--;
1585 $type = '';
1586 $off++;
1587 last;
1588 }
1589 $off++;
1590 }
1591 # We are truly at the end, so shuffle to the next line.
1592 if ($off == $len) {
1593 $loff = $len + 1;
1594 $line++;
1595 $remain--;
1596 }
1597
1598 my $statement = substr($blk, $soff, $off - $soff + 1);
1599 my $condition = substr($blk, $soff, $coff - $soff + 1);
1600
1601 #warn "STATEMENT<$statement>\n";
1602 #warn "CONDITION<$condition>\n";
1603
1604 #print "coff<$coff> soff<$off> loff<$loff>\n";
1605
1606 return ($statement, $condition,
1607 $line, $remain + 1, $off - $loff + 1, $level);
1608}
1609
1610sub statement_lines {
1611 my ($stmt) = @_;
1612
1613 # Strip the diff line prefixes and rip blank lines at start and end.
1614 $stmt =~ s/(^|\n)./$1/g;
1615 $stmt =~ s/^\s*//;
1616 $stmt =~ s/\s*$//;
1617
1618 my @stmt_lines = ($stmt =~ /\n/g);
1619
1620 return $#stmt_lines + 2;
1621}
1622
1623sub statement_rawlines {
1624 my ($stmt) = @_;
1625
1626 my @stmt_lines = ($stmt =~ /\n/g);
1627
1628 return $#stmt_lines + 2;
1629}
1630
1631sub statement_block_size {
1632 my ($stmt) = @_;
1633
1634 $stmt =~ s/(^|\n)./$1/g;
1635 $stmt =~ s/^\s*{//;
1636 $stmt =~ s/}\s*$//;
1637 $stmt =~ s/^\s*//;
1638 $stmt =~ s/\s*$//;
1639
1640 my @stmt_lines = ($stmt =~ /\n/g);
1641 my @stmt_statements = ($stmt =~ /;/g);
1642
1643 my $stmt_lines = $#stmt_lines + 2;
1644 my $stmt_statements = $#stmt_statements + 1;
1645
1646 if ($stmt_lines > $stmt_statements) {
1647 return $stmt_lines;
1648 } else {
1649 return $stmt_statements;
1650 }
1651}
1652
1653sub ctx_statement_full {
1654 my ($linenr, $remain, $off) = @_;
1655 my ($statement, $condition, $level);
1656
1657 my (@chunks);
1658
1659 # Grab the first conditional/block pair.
1660 ($statement, $condition, $linenr, $remain, $off, $level) =
1661 ctx_statement_block($linenr, $remain, $off);
1662 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1663 push(@chunks, [ $condition, $statement ]);
1664 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1665 return ($level, $linenr, @chunks);
1666 }
1667
1668 # Pull in the following conditional/block pairs and see if they
1669 # could continue the statement.
1670 for (;;) {
1671 ($statement, $condition, $linenr, $remain, $off, $level) =
1672 ctx_statement_block($linenr, $remain, $off);
1673 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1674 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1675 #print "C: push\n";
1676 push(@chunks, [ $condition, $statement ]);
1677 }
1678
1679 return ($level, $linenr, @chunks);
1680}
1681
1682sub ctx_block_get {
1683 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1684 my $line;
1685 my $start = $linenr - 1;
1686 my $blk = '';
1687 my @o;
1688 my @c;
1689 my @res = ();
1690
1691 my $level = 0;
1692 my @stack = ($level);
1693 for ($line = $start; $remain > 0; $line++) {
1694 next if ($rawlines[$line] =~ /^-/);
1695 $remain--;
1696
1697 $blk .= $rawlines[$line];
1698
1699 # Handle nested #if/#else.
1700 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1701 push(@stack, $level);
Julius Werner218906d2021-03-25 21:12:49 -07001702 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/ && $#stack > 0) {
1703 $level = $stack[$#stack];
1704 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001705 $level = pop(@stack);
1706 }
1707
1708 foreach my $c (split(//, $lines[$line])) {
1709 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1710 if ($off > 0) {
1711 $off--;
1712 next;
1713 }
1714
1715 if ($c eq $close && $level > 0) {
1716 $level--;
1717 last if ($level == 0);
1718 } elsif ($c eq $open) {
1719 $level++;
1720 }
1721 }
1722
1723 if (!$outer || $level <= 1) {
1724 push(@res, $rawlines[$line]);
1725 }
1726
1727 last if ($level == 0);
1728 }
1729
1730 return ($level, @res);
1731}
1732sub ctx_block_outer {
1733 my ($linenr, $remain) = @_;
1734
1735 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1736 return @r;
1737}
1738sub ctx_block {
1739 my ($linenr, $remain) = @_;
1740
1741 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1742 return @r;
1743}
1744sub ctx_statement {
1745 my ($linenr, $remain, $off) = @_;
1746
1747 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1748 return @r;
1749}
1750sub ctx_block_level {
1751 my ($linenr, $remain) = @_;
1752
1753 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1754}
1755sub ctx_statement_level {
1756 my ($linenr, $remain, $off) = @_;
1757
1758 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1759}
1760
1761sub ctx_locate_comment {
1762 my ($first_line, $end_line) = @_;
1763
Elyes Haouas26e0b942022-05-22 11:11:11 +02001764 # If c99 comment on the current line, or the line before or after
1765 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1766 return $current_comment if (defined $current_comment);
1767 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1768 return $current_comment if (defined $current_comment);
1769 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1770 return $current_comment if (defined $current_comment);
1771
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001772 # Catch a comment on the end of the line itself.
Elyes Haouas26e0b942022-05-22 11:11:11 +02001773 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001774 return $current_comment if (defined $current_comment);
1775
1776 # Look through the context and try and figure out if there is a
1777 # comment.
1778 my $in_comment = 0;
1779 $current_comment = '';
1780 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1781 my $line = $rawlines[$linenr - 1];
1782 #warn " $line\n";
1783 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1784 $in_comment = 1;
1785 }
1786 if ($line =~ m@/\*@) {
1787 $in_comment = 1;
1788 }
1789 if (!$in_comment && $current_comment ne '') {
1790 $current_comment = '';
1791 }
1792 $current_comment .= $line . "\n" if ($in_comment);
1793 if ($line =~ m@\*/@) {
1794 $in_comment = 0;
1795 }
1796 }
1797
1798 chomp($current_comment);
1799 return($current_comment);
1800}
1801sub ctx_has_comment {
1802 my ($first_line, $end_line) = @_;
1803 my $cmt = ctx_locate_comment($first_line, $end_line);
1804
1805 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1806 ##print "CMMT: $cmt\n";
1807
1808 return ($cmt ne '');
1809}
1810
1811sub raw_line {
1812 my ($linenr, $cnt) = @_;
1813
1814 my $offset = $linenr - 1;
1815 $cnt++;
1816
1817 my $line;
1818 while ($cnt) {
1819 $line = $rawlines[$offset++];
1820 next if (defined($line) && $line =~ /^-/);
1821 $cnt--;
1822 }
1823
Martin Roth96a48f12016-08-29 15:30:23 -06001824 # coreboot: This probably shouldn't happen, but it does.
1825 # Return a defined value so we don't get an error.
1826 if (defined $line) {
1827 return $line;
1828 } else {
1829 return "";
1830 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001831}
1832
Martin Roth60915b32018-08-10 21:04:05 -06001833sub get_stat_real {
1834 my ($linenr, $lc) = @_;
1835
1836 my $stat_real = raw_line($linenr, 0);
1837 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1838 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1839 }
1840
1841 return $stat_real;
1842}
1843
1844sub get_stat_here {
1845 my ($linenr, $cnt, $here) = @_;
1846
1847 my $herectx = $here . "\n";
1848 for (my $n = 0; $n < $cnt; $n++) {
1849 $herectx .= raw_line($linenr, $n) . "\n";
1850 }
1851
1852 return $herectx;
1853}
1854
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001855sub cat_vet {
1856 my ($vet) = @_;
1857 my ($res, $coded);
1858
1859 $res = '';
1860 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1861 $res .= $1;
1862 if ($2 ne '') {
1863 $coded = sprintf("^%c", unpack('C', $2) + 64);
1864 $res .= $coded;
1865 }
1866 }
1867 $res =~ s/$/\$/;
1868
1869 return $res;
1870}
1871
1872my $av_preprocessor = 0;
1873my $av_pending;
1874my @av_paren_type;
1875my $av_pend_colon;
1876
1877sub annotate_reset {
1878 $av_preprocessor = 0;
1879 $av_pending = '_';
1880 @av_paren_type = ('E');
1881 $av_pend_colon = 'O';
1882}
1883
1884sub annotate_values {
1885 my ($stream, $type) = @_;
1886
1887 my $res;
1888 my $var = '_' x length($stream);
1889 my $cur = $stream;
1890
1891 print "$stream\n" if ($dbg_values > 1);
1892
1893 while (length($cur)) {
1894 @av_paren_type = ('E') if ($#av_paren_type < 0);
1895 print " <" . join('', @av_paren_type) .
1896 "> <$type> <$av_pending>" if ($dbg_values > 1);
1897 if ($cur =~ /^(\s+)/o) {
1898 print "WS($1)\n" if ($dbg_values > 1);
1899 if ($1 =~ /\n/ && $av_preprocessor) {
1900 $type = pop(@av_paren_type);
1901 $av_preprocessor = 0;
1902 }
1903
1904 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1905 print "CAST($1)\n" if ($dbg_values > 1);
1906 push(@av_paren_type, $type);
1907 $type = 'c';
1908
1909 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1910 print "DECLARE($1)\n" if ($dbg_values > 1);
1911 $type = 'T';
1912
1913 } elsif ($cur =~ /^($Modifier)\s*/) {
1914 print "MODIFIER($1)\n" if ($dbg_values > 1);
1915 $type = 'T';
1916
1917 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1918 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1919 $av_preprocessor = 1;
1920 push(@av_paren_type, $type);
1921 if ($2 ne '') {
1922 $av_pending = 'N';
1923 }
1924 $type = 'E';
1925
1926 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1927 print "UNDEF($1)\n" if ($dbg_values > 1);
1928 $av_preprocessor = 1;
1929 push(@av_paren_type, $type);
1930
1931 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1932 print "PRE_START($1)\n" if ($dbg_values > 1);
1933 $av_preprocessor = 1;
1934
1935 push(@av_paren_type, $type);
1936 push(@av_paren_type, $type);
1937 $type = 'E';
1938
1939 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1940 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1941 $av_preprocessor = 1;
1942
1943 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1944
1945 $type = 'E';
1946
1947 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1948 print "PRE_END($1)\n" if ($dbg_values > 1);
1949
1950 $av_preprocessor = 1;
1951
1952 # Assume all arms of the conditional end as this
1953 # one does, and continue as if the #endif was not here.
1954 pop(@av_paren_type);
1955 push(@av_paren_type, $type);
1956 $type = 'E';
1957
1958 } elsif ($cur =~ /^(\\\n)/o) {
1959 print "PRECONT($1)\n" if ($dbg_values > 1);
1960
1961 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1962 print "ATTR($1)\n" if ($dbg_values > 1);
1963 $av_pending = $type;
1964 $type = 'N';
1965
1966 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1967 print "SIZEOF($1)\n" if ($dbg_values > 1);
1968 if (defined $2) {
1969 $av_pending = 'V';
1970 }
1971 $type = 'N';
1972
1973 } elsif ($cur =~ /^(if|while|for)\b/o) {
1974 print "COND($1)\n" if ($dbg_values > 1);
1975 $av_pending = 'E';
1976 $type = 'N';
1977
1978 } elsif ($cur =~/^(case)/o) {
1979 print "CASE($1)\n" if ($dbg_values > 1);
1980 $av_pend_colon = 'C';
1981 $type = 'N';
1982
1983 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1984 print "KEYWORD($1)\n" if ($dbg_values > 1);
1985 $type = 'N';
1986
1987 } elsif ($cur =~ /^(\()/o) {
1988 print "PAREN('$1')\n" if ($dbg_values > 1);
1989 push(@av_paren_type, $av_pending);
1990 $av_pending = '_';
1991 $type = 'N';
1992
1993 } elsif ($cur =~ /^(\))/o) {
1994 my $new_type = pop(@av_paren_type);
1995 if ($new_type ne '_') {
1996 $type = $new_type;
1997 print "PAREN('$1') -> $type\n"
1998 if ($dbg_values > 1);
1999 } else {
2000 print "PAREN('$1')\n" if ($dbg_values > 1);
2001 }
2002
2003 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2004 print "FUNC($1)\n" if ($dbg_values > 1);
2005 $type = 'V';
2006 $av_pending = 'V';
2007
2008 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2009 if (defined $2 && $type eq 'C' || $type eq 'T') {
2010 $av_pend_colon = 'B';
2011 } elsif ($type eq 'E') {
2012 $av_pend_colon = 'L';
2013 }
2014 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2015 $type = 'V';
2016
2017 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2018 print "IDENT($1)\n" if ($dbg_values > 1);
2019 $type = 'V';
2020
2021 } elsif ($cur =~ /^($Assignment)/o) {
2022 print "ASSIGN($1)\n" if ($dbg_values > 1);
2023 $type = 'N';
2024
2025 } elsif ($cur =~/^(;|{|})/) {
2026 print "END($1)\n" if ($dbg_values > 1);
2027 $type = 'E';
2028 $av_pend_colon = 'O';
2029
2030 } elsif ($cur =~/^(,)/) {
2031 print "COMMA($1)\n" if ($dbg_values > 1);
2032 $type = 'C';
2033
2034 } elsif ($cur =~ /^(\?)/o) {
2035 print "QUESTION($1)\n" if ($dbg_values > 1);
2036 $type = 'N';
2037
2038 } elsif ($cur =~ /^(:)/o) {
2039 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2040
2041 substr($var, length($res), 1, $av_pend_colon);
2042 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2043 $type = 'E';
2044 } else {
2045 $type = 'N';
2046 }
2047 $av_pend_colon = 'O';
2048
2049 } elsif ($cur =~ /^(\[)/o) {
2050 print "CLOSE($1)\n" if ($dbg_values > 1);
2051 $type = 'N';
2052
2053 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2054 my $variant;
2055
2056 print "OPV($1)\n" if ($dbg_values > 1);
2057 if ($type eq 'V') {
2058 $variant = 'B';
2059 } else {
2060 $variant = 'U';
2061 }
2062
2063 substr($var, length($res), 1, $variant);
2064 $type = 'N';
2065
2066 } elsif ($cur =~ /^($Operators)/o) {
2067 print "OP($1)\n" if ($dbg_values > 1);
2068 if ($1 ne '++' && $1 ne '--') {
2069 $type = 'N';
2070 }
2071
2072 } elsif ($cur =~ /(^.)/o) {
2073 print "C($1)\n" if ($dbg_values > 1);
2074 }
2075 if (defined $1) {
2076 $cur = substr($cur, length($1));
2077 $res .= $type x length($1);
2078 }
2079 }
2080
2081 return ($res, $var);
2082}
2083
2084sub possible {
2085 my ($possible, $line) = @_;
2086 my $notPermitted = qr{(?:
2087 ^(?:
2088 $Modifier|
2089 $Storage|
2090 $Type|
2091 DEFINE_\S+
2092 )$|
2093 ^(?:
2094 goto|
2095 return|
2096 case|
2097 else|
2098 asm|__asm__|
2099 do|
2100 \#|
2101 \#\#|
2102 )(?:\s|$)|
2103 ^(?:typedef|struct|enum)\b
2104 )}x;
2105 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2106 if ($possible !~ $notPermitted) {
2107 # Check for modifiers.
2108 $possible =~ s/\s*$Storage\s*//g;
2109 $possible =~ s/\s*$Sparse\s*//g;
2110 if ($possible =~ /^\s*$/) {
2111
2112 } elsif ($possible =~ /\s/) {
2113 $possible =~ s/\s*$Type\s*//g;
2114 for my $modifier (split(' ', $possible)) {
2115 if ($modifier !~ $notPermitted) {
2116 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002117 push(@modifierListFile, $modifier);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002118 }
2119 }
2120
2121 } else {
2122 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002123 push(@typeListFile, $possible);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002124 }
2125 build_types();
2126 } else {
2127 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2128 }
2129}
2130
2131my $prefix = '';
2132
2133sub show_type {
2134 my ($type) = @_;
2135
Martin Rothedd591d2017-03-14 10:16:29 -06002136 $type =~ tr/[a-z]/[A-Z]/;
2137
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002138 return defined $use_type{$type} if (scalar keys %use_type > 0);
2139
2140 return !defined $ignore_type{$type};
2141}
2142
2143sub report {
2144 my ($level, $type, $msg) = @_;
2145
2146 if (!show_type($type) ||
2147 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2148 return 0;
2149 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002150 my $output = '';
Martin Roth387dec82017-09-17 19:20:46 -06002151 if ($color) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002152 if ($level eq 'ERROR') {
2153 $output .= RED;
2154 } elsif ($level eq 'WARNING') {
2155 $output .= YELLOW;
2156 } else {
2157 $output .= GREEN;
2158 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002159 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002160 $output .= $prefix . $level . ':';
2161 if ($show_types) {
Martin Roth387dec82017-09-17 19:20:46 -06002162 $output .= BLUE if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002163 $output .= "$type:";
2164 }
Martin Roth387dec82017-09-17 19:20:46 -06002165 $output .= RESET if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002166 $output .= ' ' . $msg . "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002167
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002168 if ($showfile) {
2169 my @lines = split("\n", $output, -1);
2170 splice(@lines, 1, 1);
2171 $output = join("\n", @lines);
2172 }
Elyes Haouas46b07e52022-04-07 10:07:34 +02002173
2174 if ($terse) {
2175 $output = (split('\n', $output))[0] . "\n";
2176 }
2177
2178 if ($verbose && exists($verbose_messages{$type}) &&
2179 !exists($verbose_emitted{$type})) {
2180 $output .= $verbose_messages{$type} . "\n\n";
2181 $verbose_emitted{$type} = 1;
2182 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002183
2184 push(our @report, $output);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002185
2186 return 1;
2187}
2188
2189sub report_dump {
2190 our @report;
2191}
2192
2193sub fixup_current_range {
2194 my ($lineRef, $offset, $length) = @_;
2195
2196 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2197 my $o = $1;
2198 my $l = $2;
2199 my $no = $o + $offset;
2200 my $nl = $l + $length;
2201 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2202 }
2203}
2204
2205sub fix_inserted_deleted_lines {
2206 my ($linesRef, $insertedRef, $deletedRef) = @_;
2207
2208 my $range_last_linenr = 0;
2209 my $delta_offset = 0;
2210
2211 my $old_linenr = 0;
2212 my $new_linenr = 0;
2213
2214 my $next_insert = 0;
2215 my $next_delete = 0;
2216
2217 my @lines = ();
2218
2219 my $inserted = @{$insertedRef}[$next_insert++];
2220 my $deleted = @{$deletedRef}[$next_delete++];
2221
2222 foreach my $old_line (@{$linesRef}) {
2223 my $save_line = 1;
2224 my $line = $old_line; #don't modify the array
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002225 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002226 $delta_offset = 0;
2227 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2228 $range_last_linenr = $new_linenr;
2229 fixup_current_range(\$line, $delta_offset, 0);
2230 }
2231
2232 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2233 $deleted = @{$deletedRef}[$next_delete++];
2234 $save_line = 0;
2235 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2236 }
2237
2238 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2239 push(@lines, ${$inserted}{'LINE'});
2240 $inserted = @{$insertedRef}[$next_insert++];
2241 $new_linenr++;
2242 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2243 }
2244
2245 if ($save_line) {
2246 push(@lines, $line);
2247 $new_linenr++;
2248 }
2249
2250 $old_linenr++;
2251 }
2252
2253 return @lines;
2254}
2255
2256sub fix_insert_line {
2257 my ($linenr, $line) = @_;
2258
2259 my $inserted = {
2260 LINENR => $linenr,
2261 LINE => $line,
2262 };
2263 push(@fixed_inserted, $inserted);
2264}
2265
2266sub fix_delete_line {
2267 my ($linenr, $line) = @_;
2268
2269 my $deleted = {
2270 LINENR => $linenr,
2271 LINE => $line,
2272 };
2273
2274 push(@fixed_deleted, $deleted);
2275}
2276
2277sub ERROR {
2278 my ($type, $msg) = @_;
2279
2280 if (report("ERROR", $type, $msg)) {
2281 our $clean = 0;
2282 our $cnt_error++;
2283 return 1;
2284 }
2285 return 0;
2286}
2287sub WARN {
2288 my ($type, $msg) = @_;
2289
2290 if (report("WARNING", $type, $msg)) {
2291 our $clean = 0;
2292 our $cnt_warn++;
2293 return 1;
2294 }
2295 return 0;
2296}
2297sub CHK {
2298 my ($type, $msg) = @_;
2299
2300 if ($check && report("CHECK", $type, $msg)) {
2301 our $clean = 0;
2302 our $cnt_chk++;
2303 return 1;
2304 }
2305 return 0;
2306}
2307
2308sub check_absolute_file {
2309 my ($absolute, $herecurr) = @_;
2310 my $file = $absolute;
2311
2312 ##print "absolute<$absolute>\n";
2313
2314 # See if any suffix of this path is a path within the tree.
2315 while ($file =~ s@^[^/]*/@@) {
2316 if (-f "$root/$file") {
2317 ##print "file<$file>\n";
2318 last;
2319 }
2320 }
2321 if (! -f _) {
2322 return 0;
2323 }
2324
2325 # It is, so see if the prefix is acceptable.
2326 my $prefix = $absolute;
2327 substr($prefix, -length($file)) = '';
2328
2329 ##print "prefix<$prefix>\n";
2330 if ($prefix ne ".../") {
2331 WARN("USE_RELATIVE_PATH",
2332 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2333 }
2334}
2335
2336sub trim {
2337 my ($string) = @_;
2338
2339 $string =~ s/^\s+|\s+$//g;
2340
2341 return $string;
2342}
2343
2344sub ltrim {
2345 my ($string) = @_;
2346
2347 $string =~ s/^\s+//;
2348
2349 return $string;
2350}
2351
2352sub rtrim {
2353 my ($string) = @_;
2354
2355 $string =~ s/\s+$//;
2356
2357 return $string;
2358}
2359
2360sub string_find_replace {
2361 my ($string, $find, $replace) = @_;
2362
2363 $string =~ s/$find/$replace/g;
2364
2365 return $string;
2366}
2367
2368sub tabify {
2369 my ($leading) = @_;
2370
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01002371 my $source_indent = $tabsize;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002372 my $max_spaces_before_tab = $source_indent - 1;
2373 my $spaces_to_tab = " " x $source_indent;
2374
2375 #convert leading spaces to tabs
2376 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2377 #Remove spaces before a tab
2378 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2379
2380 return "$leading";
2381}
2382
2383sub pos_last_openparen {
2384 my ($line) = @_;
2385
2386 my $pos = 0;
2387
2388 my $opens = $line =~ tr/\(/\(/;
2389 my $closes = $line =~ tr/\)/\)/;
2390
2391 my $last_openparen = 0;
2392
2393 if (($opens == 0) || ($closes >= $opens)) {
2394 return -1;
2395 }
2396
2397 my $len = length($line);
2398
2399 for ($pos = 0; $pos < $len; $pos++) {
2400 my $string = substr($line, $pos);
2401 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2402 $pos += length($1) - 1;
2403 } elsif (substr($line, $pos, 1) eq '(') {
2404 $last_openparen = $pos;
2405 } elsif (index($string, '(') == -1) {
2406 last;
2407 }
2408 }
2409
2410 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2411}
2412
Elyes Haouasf62a9892022-04-12 12:17:50 +02002413sub get_raw_comment {
2414 my ($line, $rawline) = @_;
2415 my $comment = '';
2416
2417 for my $i (0 .. (length($line) - 1)) {
2418 if (substr($line, $i, 1) eq "$;") {
2419 $comment .= substr($rawline, $i, 1);
2420 }
2421 }
2422
2423 return $comment;
2424}
2425
2426sub exclude_global_initialisers {
2427 my ($realfile) = @_;
2428
2429 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2430 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2431 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2432 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2433}
2434
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002435sub process {
2436 my $filename = shift;
2437
2438 my $linenr=0;
2439 my $prevline="";
2440 my $prevrawline="";
2441 my $stashline="";
2442 my $stashrawline="";
2443
2444 my $length;
2445 my $indent;
2446 my $previndent=0;
2447 my $stashindent=0;
2448
2449 our $clean = 1;
2450 my $signoff = 0;
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002451 my $author = '';
2452 my $authorsignoff = 0;
2453 my $author_sob = '';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002454 my $is_patch = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002455 my $in_header_lines = $file ? 0 : 1;
2456 my $in_commit_log = 0; #Scanning lines before patch
Elyes Haouascb346842022-07-13 17:05:19 +02002457 my $has_patch_separator = 0; #Found a --- line
Martin Rothedd591d2017-03-14 10:16:29 -06002458 my $has_commit_log = 0; #Encountered lines before patch
Elyes Haouase83e0902022-07-13 17:40:30 +02002459 my $commit_log_lines = 0; #Number of commit log lines
Martin Rothedd591d2017-03-14 10:16:29 -06002460 my $commit_log_possible_stack_dump = 0;
Elyes Haouas26e0b942022-05-22 11:11:11 +02002461 my $commit_log_long_line = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002462 my $commit_log_has_diff = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002463 my $reported_maintainer_file = 0;
2464 my $non_utf8_charset = 0;
2465
2466 my $last_blank_line = 0;
2467 my $last_coalesced_string_linenr = -1;
2468
2469 our @report = ();
2470 our $cnt_lines = 0;
2471 our $cnt_error = 0;
2472 our $cnt_warn = 0;
2473 our $cnt_chk = 0;
2474
2475 # Trace the real file/line as we go.
2476 my $realfile = '';
2477 my $realline = 0;
2478 my $realcnt = 0;
2479 my $here = '';
Martin Rothedd591d2017-03-14 10:16:29 -06002480 my $context_function; #undef'd unless there's a known function
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002481 my $in_comment = 0;
2482 my $comment_edge = 0;
2483 my $first_line = 0;
2484 my $p1_prefix = '';
2485
2486 my $prev_values = 'E';
2487
2488 # suppression flags
2489 my %suppress_ifbraces;
2490 my %suppress_whiletrailers;
2491 my %suppress_export;
2492 my $suppress_statement = 0;
2493
2494 my %signatures = ();
2495
2496 # Pre-scan the patch sanitizing the lines.
2497 # Pre-scan the patch looking for any __setup documentation.
2498 #
2499 my @setup_docs = ();
2500 my $setup_docs = 0;
2501
2502 my $camelcase_file_seeded = 0;
2503
Martin Roth60915b32018-08-10 21:04:05 -06002504 my $checklicenseline = 1;
2505
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002506 sanitise_line_reset();
2507 my $line;
2508 foreach my $rawline (@rawlines) {
2509 $linenr++;
2510 $line = $rawline;
2511
2512 push(@fixed, $rawline) if ($fix);
2513
2514 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2515 $setup_docs = 0;
Martin Rothedd591d2017-03-14 10:16:29 -06002516 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002517 $setup_docs = 1;
2518 }
2519 #next;
2520 }
Martin Roth387dec82017-09-17 19:20:46 -06002521 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002522 $realline=$1-1;
2523 if (defined $2) {
2524 $realcnt=$3+1;
2525 } else {
2526 $realcnt=1+1;
2527 }
2528 $in_comment = 0;
2529
2530 # Guestimate if this is a continuing comment. Run
2531 # the context looking for a comment "edge". If this
2532 # edge is a close comment then we must be in a comment
2533 # at context start.
2534 my $edge;
2535 my $cnt = $realcnt;
2536 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2537 next if (defined $rawlines[$ln - 1] &&
2538 $rawlines[$ln - 1] =~ /^-/);
2539 $cnt--;
2540 #print "RAW<$rawlines[$ln - 1]>\n";
2541 last if (!defined $rawlines[$ln - 1]);
2542 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2543 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2544 ($edge) = $1;
2545 last;
2546 }
2547 }
2548 if (defined $edge && $edge eq '*/') {
2549 $in_comment = 1;
2550 }
2551
2552 # Guestimate if this is a continuing comment. If this
2553 # is the start of a diff block and this line starts
2554 # ' *' then it is very likely a comment.
2555 if (!defined $edge &&
2556 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2557 {
2558 $in_comment = 1;
2559 }
2560
2561 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2562 sanitise_line_reset($in_comment);
2563
2564 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2565 # Standardise the strings and chars within the input to
2566 # simplify matching -- only bother with positive lines.
2567 $line = sanitise_line($rawline);
2568 }
2569 push(@lines, $line);
2570
2571 if ($realcnt > 1) {
2572 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2573 } else {
2574 $realcnt = 0;
2575 }
2576
2577 #print "==>$rawline\n";
2578 #print "-->$line\n";
2579
2580 if ($setup_docs && $line =~ /^\+/) {
2581 push(@setup_docs, $line);
2582 }
2583 }
2584
2585 $prefix = '';
2586
2587 $realcnt = 0;
2588 $linenr = 0;
2589 $fixlinenr = -1;
2590 foreach my $line (@lines) {
2591 $linenr++;
2592 $fixlinenr++;
2593 my $sline = $line; #copy of $line
2594 $sline =~ s/$;/ /g; #with comments as spaces
2595
2596 my $rawline = $rawlines[$linenr - 1];
Elyes Haouasf62a9892022-04-12 12:17:50 +02002597 my $raw_comment = get_raw_comment($line, $rawline);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002598
Martin Roth60915b32018-08-10 21:04:05 -06002599# check if it's a mode change, rename or start of a patch
2600 if (!$in_commit_log &&
2601 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2602 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2603 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2604 $is_patch = 1;
2605 }
2606
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002607#extract the line range in the file after the patch is applied
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002608 if (!$in_commit_log &&
Martin Roth387dec82017-09-17 19:20:46 -06002609 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2610 my $context = $4;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002611 $is_patch = 1;
2612 $first_line = $linenr + 1;
2613 $realline=$1-1;
2614 if (defined $2) {
2615 $realcnt=$3+1;
2616 } else {
2617 $realcnt=1+1;
2618 }
2619 annotate_reset();
2620 $prev_values = 'E';
2621
2622 %suppress_ifbraces = ();
2623 %suppress_whiletrailers = ();
2624 %suppress_export = ();
2625 $suppress_statement = 0;
Martin Roth387dec82017-09-17 19:20:46 -06002626 if ($context =~ /\b(\w+)\s*\(/) {
2627 $context_function = $1;
2628 } else {
2629 undef $context_function;
2630 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002631 next;
2632
2633# track the line number as we move through the hunk, note that
2634# new versions of GNU diff omit the leading space on completely
2635# blank context lines so we need to count that too.
2636 } elsif ($line =~ /^( |\+|$)/) {
2637 $realline++;
2638 $realcnt-- if ($realcnt != 0);
2639
2640 # Measure the line length and indent.
2641 ($length, $indent) = line_stats($rawline);
2642
2643 # Track the previous line.
2644 ($prevline, $stashline) = ($stashline, $line);
2645 ($previndent, $stashindent) = ($stashindent, $indent);
2646 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2647
2648 #warn "line<$line>\n";
2649
2650 } elsif ($realcnt == 1) {
2651 $realcnt--;
2652 }
2653
2654 my $hunk_line = ($realcnt != 0);
2655
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002656 $here = "#$linenr: " if (!$file);
2657 $here = "#$realline: " if ($file);
2658
2659 my $found_file = 0;
2660 # extract the filename as it passes
2661 if ($line =~ /^diff --git.*?(\S+)$/) {
2662 $realfile = $1;
2663 $realfile =~ s@^([^/]*)/@@ if (!$file);
2664 $in_commit_log = 0;
2665 $found_file = 1;
2666 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2667 $realfile = $1;
2668 $realfile =~ s@^([^/]*)/@@ if (!$file);
2669 $in_commit_log = 0;
2670
2671 $p1_prefix = $1;
2672 if (!$file && $tree && $p1_prefix ne '' &&
2673 -e "$root/$p1_prefix") {
2674 WARN("PATCH_PREFIX",
2675 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2676 }
2677
2678 if ($realfile =~ m@^include/asm/@) {
2679 ERROR("MODIFIED_INCLUDE_ASM",
2680 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2681 }
2682 $found_file = 1;
2683 }
2684
Martin Rothedd591d2017-03-14 10:16:29 -06002685 # coreboot
Martin Rotha3cac872017-03-04 18:17:35 -07002686 my $skipme = 0;
2687 foreach (@exclude) {
2688 if ($realfile =~ m@^(?:$_/)@) {
2689 $skipme = 1;
2690 }
2691 }
2692 if ($skipme) {
2693 next;
2694 }
2695
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002696#make up the handle for any error we report on this line
2697 if ($showfile) {
2698 $prefix = "$realfile:$realline: "
2699 } elsif ($emacs) {
2700 if ($file) {
2701 $prefix = "$filename:$realline: ";
2702 } else {
2703 $prefix = "$filename:$linenr: ";
2704 }
2705 }
2706
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002707 if ($found_file) {
Martin Rothedd591d2017-03-14 10:16:29 -06002708 if (is_maintained_obsolete($realfile)) {
2709 WARN("OBSOLETE",
2710 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2711 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002712 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002713 $check = 1;
2714 } else {
2715 $check = $check_orig;
2716 }
Martin Roth60915b32018-08-10 21:04:05 -06002717 $checklicenseline = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002718 next;
2719 }
2720
2721 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2722
2723 my $hereline = "$here\n$rawline\n";
2724 my $herecurr = "$here\n$rawline\n";
2725 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2726
2727 $cnt_lines++ if ($realcnt != 0);
2728
Elyes Haouase83e0902022-07-13 17:40:30 +02002729# Verify the existence of a commit log if appropriate
2730# 2 is used because a $signature is counted in $commit_log_lines
2731 if ($in_commit_log) {
2732 if ($line !~ /^\s*$/) {
2733 $commit_log_lines++; #could be a $signature
2734 }
2735 } elsif ($has_commit_log && $commit_log_lines < 2) {
2736 WARN("COMMIT_MESSAGE",
2737 "Missing commit description - Add an appropriate one\n");
2738 $commit_log_lines = 2; #warn only once
2739 }
2740
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002741# Check if the commit log has what seems like a diff which can confuse patch
2742 if ($in_commit_log && !$commit_log_has_diff &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02002743 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2744 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002745 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2746 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2747 ERROR("DIFF_IN_COMMIT_MSG",
2748 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2749 $commit_log_has_diff = 1;
2750 }
2751
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002752# Check for incorrect file permissions
2753 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2754 my $permhere = $here . "FILE: $realfile\n";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002755 if ($realfile !~ m@scripts/@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002756 $realfile !~ /\.(py|pl|awk|sh)$/) {
2757 ERROR("EXECUTE_PERMISSIONS",
2758 "do not set execute permissions for source files\n" . $permhere);
2759 }
2760 }
2761
2762# Check the patch for a signoff:
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002763 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002764 $signoff++;
2765 $in_commit_log = 0;
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002766 if ($author ne '' && $authorsignoff != 1) {
2767 if (same_email_addresses($1, $author)) {
2768 $authorsignoff = 1;
2769 } else {
2770 my $ctx = $1;
2771 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2772 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2773
2774 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2775 $author_sob = $ctx;
2776 $authorsignoff = 2;
2777 } elsif (lc $email_address eq lc $author_address) {
2778 $author_sob = $ctx;
2779 $authorsignoff = 3;
2780 } elsif ($email_name eq $author_name) {
2781 $author_sob = $ctx;
2782 $authorsignoff = 4;
2783
2784 my $address1 = $email_address;
2785 my $address2 = $author_address;
2786
2787 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2788 $address1 = "$1$2";
2789 }
2790 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2791 $address2 = "$1$2";
2792 }
2793 if ($address1 eq $address2) {
2794 $authorsignoff = 5;
2795 }
2796 }
2797 }
2798 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002799 }
2800
Elyes Haouascb346842022-07-13 17:05:19 +02002801# Check for patch separator
2802 if ($line =~ /^---$/) {
2803 $has_patch_separator = 1;
2804 $in_commit_log = 0;
2805 }
2806
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002807# Check if MAINTAINERS is being updated. If so, there's probably no need to
2808# emit the "does MAINTAINERS need updating?" message on file add/move/delete
2809 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2810 $reported_maintainer_file = 1;
2811 }
2812
2813# Check signature styles
2814 if (!$in_header_lines &&
2815 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2816 my $space_before = $1;
2817 my $sign_off = $2;
2818 my $space_after = $3;
2819 my $email = $4;
2820 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2821
2822 if ($sign_off !~ /$signature_tags/) {
2823 WARN("BAD_SIGN_OFF",
2824 "Non-standard signature: $sign_off\n" . $herecurr);
2825 }
2826 if (defined $space_before && $space_before ne "") {
2827 if (WARN("BAD_SIGN_OFF",
2828 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2829 $fix) {
2830 $fixed[$fixlinenr] =
2831 "$ucfirst_sign_off $email";
2832 }
2833 }
2834 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2835 if (WARN("BAD_SIGN_OFF",
2836 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2837 $fix) {
2838 $fixed[$fixlinenr] =
2839 "$ucfirst_sign_off $email";
2840 }
2841
2842 }
2843 if (!defined $space_after || $space_after ne " ") {
2844 if (WARN("BAD_SIGN_OFF",
2845 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2846 $fix) {
2847 $fixed[$fixlinenr] =
2848 "$ucfirst_sign_off $email";
2849 }
2850 }
2851
2852 my ($email_name, $email_address, $comment) = parse_email($email);
2853 my $suggested_email = format_email(($email_name, $email_address));
2854 if ($suggested_email eq "") {
2855 ERROR("BAD_SIGN_OFF",
2856 "Unrecognized email address: '$email'\n" . $herecurr);
2857 } else {
2858 my $dequoted = $suggested_email;
2859 $dequoted =~ s/^"//;
2860 $dequoted =~ s/" </ </;
2861 # Don't force email to have quotes
2862 # Allow just an angle bracketed address
2863 if ("$dequoted$comment" ne $email &&
2864 "<$email_address>$comment" ne $email &&
2865 "$suggested_email$comment" ne $email) {
2866 WARN("BAD_SIGN_OFF",
2867 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2868 }
2869 }
2870
2871# Check for duplicate signatures
2872 my $sig_nospace = $line;
2873 $sig_nospace =~ s/\s//g;
2874 $sig_nospace = lc($sig_nospace);
2875 if (defined $signatures{$sig_nospace}) {
2876 WARN("BAD_SIGN_OFF",
2877 "Duplicate signature\n" . $herecurr);
2878 } else {
2879 $signatures{$sig_nospace} = 1;
2880 }
2881 }
2882
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002883# Check email subject for common tools that don't need to be mentioned
2884 if ($in_header_lines &&
2885 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2886 WARN("EMAIL_SUBJECT",
2887 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2888 }
2889
Elyes Haouascb346842022-07-13 17:05:19 +02002890# Check for Gerrit Change-Ids not in any patch context
2891 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2892 if (ERROR("GERRIT_CHANGE_ID",
2893 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
2894 $fix) {
2895 fix_delete_line($fixlinenr, $rawline);
2896 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002897 }
2898
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002899# Check if the commit log is in a possible stack dump
2900 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2901 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2902 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2903 # timestamp
Elyes Haouas26e0b942022-05-22 11:11:11 +02002904 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2905 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2906 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2907 # stack dump address styles
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002908 $commit_log_possible_stack_dump = 1;
2909 }
2910
Martin Roth10d34b72022-03-22 16:24:44 -06002911# coreboot: The line length limit is 72
2912# Check for line lengths > 72 in commit log
2913 if ($in_commit_log && length($line) > 72 &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002914 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2915 # file delta changes
Elyes HAOUASac690492022-01-29 07:59:17 +01002916 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002917 # filename then :
Elyes HAOUASac690492022-01-29 07:59:17 +01002918 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
2919 # A Fixes: or Link: line or signature tag line
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002920 $commit_log_possible_stack_dump)) {
2921 WARN("COMMIT_LOG_LONG_LINE",
Paul Menzeldd1ee272021-12-09 12:49:35 +01002922 "Possible unwrapped commit description (prefer a maximum 72 chars per line)\n" . $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02002923 $commit_log_long_line = 1;
Martin Roth10d34b72022-03-22 16:24:44 -06002924 }
2925
2926# coreboot: The line subject limit is 65
2927# Check for line lengths > 65 in commit subject
Martin Roth97e7eea2022-03-22 18:06:15 -06002928# coreboot: Check for a period at the end of the subject line
Martin Roth10d34b72022-03-22 16:24:44 -06002929 if ($in_header_lines &&
2930 $line =~ /^Subject: /) {
2931 $line = $line.$rawlines[$linenr];
2932 $line =~ s/^Subject: \[PATCH\] //;
Martin Roth341a53d2022-05-24 18:46:45 -06002933 if (length($line) - length("Subject: [PATCH] ") > 65) {
2934 WARN("COMMIT_LOG_LONG_LINE",
2935 "Possible long commit subject (prefer a maximum 65 characters)\n" . $herecurr);
Martin Roth10d34b72022-03-22 16:24:44 -06002936 }
Martin Roth97e7eea2022-03-22 18:06:15 -06002937 if ($line =~ /\.$/) {
2938 WARN("SUBJECT_HAS_FULL_STOP",
2939 "Subject line should not end with a period.\n" . $herecurr);
2940 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002941 }
2942
2943# Reset possible stack dump if a blank line is found
2944 if ($in_commit_log && $commit_log_possible_stack_dump &&
2945 $line =~ /^\s*$/) {
2946 $commit_log_possible_stack_dump = 0;
2947 }
2948
2949# Check for git id commit length and improperly formed commit descriptions
2950 if ($in_commit_log && !$commit_log_possible_stack_dump &&
Martin Rothedd591d2017-03-14 10:16:29 -06002951 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
Martin Roth387dec82017-09-17 19:20:46 -06002952 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002953 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06002954 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002955 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2956 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2957 my $init_char = "c";
2958 my $orig_commit = "";
2959 my $short = 1;
2960 my $long = 0;
2961 my $case = 1;
2962 my $space = 1;
2963 my $hasdesc = 0;
2964 my $hasparens = 0;
2965 my $id = '0123456789ab';
2966 my $orig_desc = "commit description";
2967 my $description = "";
2968
2969 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2970 $init_char = $1;
2971 $orig_commit = lc($2);
2972 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2973 $orig_commit = lc($1);
2974 }
2975
2976 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2977 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2978 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2979 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2980 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2981 $orig_desc = $1;
2982 $hasparens = 1;
2983 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2984 defined $rawlines[$linenr] &&
2985 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2986 $orig_desc = $1;
2987 $hasparens = 1;
2988 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2989 defined $rawlines[$linenr] &&
2990 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2991 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2992 $orig_desc = $1;
2993 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2994 $orig_desc .= " " . $1;
2995 $hasparens = 1;
2996 }
2997
2998 ($id, $description) = git_commit_info($orig_commit,
2999 $id, $orig_desc);
3000
Martin Roth387dec82017-09-17 19:20:46 -06003001 if (defined($id) &&
3002 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003003 ERROR("GIT_COMMIT_ID",
3004 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
3005 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003006 }
3007
3008# Check for added, moved or deleted files
3009 if (!$reported_maintainer_file && !$in_commit_log &&
3010 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3011 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3012 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3013 (defined($1) || defined($2))))) {
Martin Rothedd591d2017-03-14 10:16:29 -06003014 $is_patch = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003015 $reported_maintainer_file = 1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003016 WARN("FILE_PATH_CHANGES",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003017 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3018 }
3019
3020# Check for wrappage within a valid hunk of the file
3021 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3022 ERROR("CORRUPTED_PATCH",
3023 "patch seems to be corrupt (line wrapped?)\n" .
3024 $herecurr) if (!$emitted_corrupt++);
3025 }
3026
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003027# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3028 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3029 $rawline !~ m/^$UTF8*$/) {
3030 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3031
3032 my $blank = copy_spacing($rawline);
3033 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3034 my $hereptr = "$hereline$ptr\n";
3035
3036 CHK("INVALID_UTF8",
3037 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3038 }
3039
3040# Check if it's the start of a commit log
3041# (not a header line and we haven't seen the patch filename)
3042 if ($in_header_lines && $realfile =~ /^$/ &&
Martin Roth387dec82017-09-17 19:20:46 -06003043 !($rawline =~ /^\s+(?:\S|$)/ ||
3044 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003045 $in_header_lines = 0;
3046 $in_commit_log = 1;
Martin Rothedd591d2017-03-14 10:16:29 -06003047 $has_commit_log = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003048 }
3049
3050# Check if there is UTF-8 in a commit log when a mail header has explicitly
3051# declined it, i.e defined some charset where it is missing.
3052 if ($in_header_lines &&
3053 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3054 $1 !~ /utf-8/i) {
3055 $non_utf8_charset = 1;
3056 }
3057
3058 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3059 $rawline =~ /$NON_ASCII_UTF8/) {
3060 WARN("UTF8_BEFORE_PATCH",
3061 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3062 }
3063
Martin Rothedd591d2017-03-14 10:16:29 -06003064# Check for absolute kernel paths in commit message
3065 if ($tree && $in_commit_log) {
3066 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3067 my $file = $1;
3068
3069 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3070 check_absolute_file($1, $herecurr)) {
3071 #
3072 } else {
3073 check_absolute_file($file, $herecurr);
3074 }
3075 }
3076 }
3077
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003078# Check for various typo / spelling mistakes
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003079 if (defined($misspellings) &&
3080 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02003081 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003082 my $typo = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003083 my $blank = copy_spacing($rawline);
3084 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3085 my $hereptr = "$hereline$ptr\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003086 my $typo_fix = $spelling_fix{lc($typo)};
3087 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3088 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
Martin Roth387dec82017-09-17 19:20:46 -06003089 my $msg_level = \&WARN;
3090 $msg_level = \&CHK if ($file);
3091 if (&{$msg_level}("TYPO_SPELLING",
Elyes Haouas26e0b942022-05-22 11:11:11 +02003092 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003093 $fix) {
3094 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3095 }
3096 }
3097 }
Elyes Haouas84083a22022-04-12 12:28:32 +02003098# check for repeated words separated by a single space
3099# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3100 if (($rawline =~ /^\+/ || $in_commit_log) &&
3101 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3102 pos($rawline) = 1 if (!$in_commit_log);
3103 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3104
3105 my $first = $1;
3106 my $second = $2;
3107 my $start_pos = $-[1];
3108 my $end_pos = $+[2];
3109 if ($first =~ /(?:struct|union|enum)/) {
3110 pos($rawline) += length($first) + length($second) + 1;
3111 next;
3112 }
3113
3114 next if (lc($first) ne lc($second));
3115 next if ($first eq 'long');
3116
3117 # check for character before and after the word matches
3118 my $start_char = '';
3119 my $end_char = '';
3120 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3121 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3122
3123 next if ($start_char =~ /^\S$/);
3124 next if (index(" \t.,;?!", $end_char) == -1);
3125
3126 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3127 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3128 next if (!exists($allow_repeated_words{lc($first)}));
3129 }
3130
3131 if (WARN("REPEATED_WORD",
3132 "Possible repeated word: '$first'\n" . $herecurr) &&
3133 $fix) {
3134 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3135 }
3136 }
3137
3138 # if it's a repeated word on consecutive lines in a comment block
3139 if ($prevline =~ /$;+\s*$/ &&
3140 $prevrawline =~ /($word_pattern)\s*$/) {
3141 my $last_word = $1;
3142 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3143 if (WARN("REPEATED_WORD",
3144 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3145 $fix) {
3146 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3147 }
3148 }
3149 }
3150 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003151
3152# ignore non-hunk lines and lines being removed
3153 next if (!$hunk_line || $line =~ /^-/);
3154
3155#trailing whitespace
3156 if ($line =~ /^\+.*\015/) {
3157 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3158 if (ERROR("DOS_LINE_ENDINGS",
3159 "DOS line endings\n" . $herevet) &&
3160 $fix) {
3161 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3162 }
3163 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3164 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3165 if (ERROR("TRAILING_WHITESPACE",
3166 "trailing whitespace\n" . $herevet) &&
3167 $fix) {
3168 $fixed[$fixlinenr] =~ s/\s+$//;
3169 }
3170
3171 $rpt_cleaners = 1;
3172 }
3173
3174# Check for FSF mailing addresses.
3175 if ($rawline =~ /\bwrite to the Free/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06003176 $rawline =~ /\b675\s+Mass\s+Ave/i ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003177 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3178 $rawline =~ /\b51\s+Franklin\s+St/i) {
3179 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
Martin Roth387dec82017-09-17 19:20:46 -06003180 my $msg_level = \&ERROR;
3181 $msg_level = \&CHK if ($file);
3182 &{$msg_level}("FSF_MAILING_ADDRESS",
3183 "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003184 }
3185
3186# check for Kconfig help text having a real description
3187# Only applies when adding the entry originally, after that we do not have
3188# sufficient context to determine whether it is indeed long enough.
3189 if ($realfile =~ /Kconfig/ &&
Martin Roth60915b32018-08-10 21:04:05 -06003190 # 'choice' is usually the last thing on the line (though
3191 # Kconfig supports named choices), so use a word boundary
3192 # (\b) rather than a whitespace character (\s)
3193 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
Elyes Haouasf62a9892022-04-12 12:17:50 +02003194 my $ln = $linenr;
3195 my $needs_help = 0;
3196 my $has_help = 0;
3197 my $help_length = 0;
3198 while (defined $lines[$ln]) {
3199 my $f = $lines[$ln++];
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003200
3201 next if ($f =~ /^-/);
Elyes Haouasf62a9892022-04-12 12:17:50 +02003202 last if ($f !~ /^[\+ ]/); # !patch context
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003203
Elyes Haouasf62a9892022-04-12 12:17:50 +02003204 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3205 $needs_help = 1;
3206 next;
3207 }
3208 if ($f =~ /^\+\s*help\s*$/) {
3209 $has_help = 1;
3210 next;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003211 }
3212
Elyes Haouasf62a9892022-04-12 12:17:50 +02003213 $f =~ s/^.//; # strip patch context [+ ]
3214 $f =~ s/#.*//; # strip # directives
3215 $f =~ s/^\s+//; # strip leading blanks
3216 next if ($f =~ /^$/); # skip blank lines
Martin Roth60915b32018-08-10 21:04:05 -06003217
Elyes Haouasf62a9892022-04-12 12:17:50 +02003218 # At the end of this Kconfig block:
Martin Roth60915b32018-08-10 21:04:05 -06003219 # This only checks context lines in the patch
3220 # and so hopefully shouldn't trigger false
3221 # positives, even though some of these are
3222 # common words in help texts
Elyes Haouasf62a9892022-04-12 12:17:50 +02003223 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3224 if|endif|menu|endmenu|source)\b/x) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003225 last;
3226 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003227 $help_length++ if ($has_help);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003228 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003229 if ($needs_help &&
3230 $help_length < $min_conf_desc_length) {
3231 my $stat_real = get_stat_real($linenr, $ln - 1);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003232 WARN("CONFIG_DESCRIPTION",
Elyes Haouasf62a9892022-04-12 12:17:50 +02003233 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003234 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003235 }
3236
Martin Roth387dec82017-09-17 19:20:46 -06003237# check for MAINTAINERS entries that don't have the right form
3238 if ($realfile =~ /^MAINTAINERS$/ &&
3239 $rawline =~ /^\+[A-Z]:/ &&
3240 $rawline !~ /^\+[A-Z]:\t\S/) {
3241 if (WARN("MAINTAINERS_STYLE",
3242 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3243 $fix) {
3244 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3245 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003246 }
3247
3248 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3249 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3250 my $flag = $1;
3251 my $replacement = {
3252 'EXTRA_AFLAGS' => 'asflags-y',
3253 'EXTRA_CFLAGS' => 'ccflags-y',
3254 'EXTRA_CPPFLAGS' => 'cppflags-y',
3255 'EXTRA_LDFLAGS' => 'ldflags-y',
3256 };
3257
3258 WARN("DEPRECATED_VARIABLE",
3259 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3260 }
3261
3262# check for DT compatible documentation
3263 if (defined $root &&
3264 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3265 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3266
3267 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3268
3269 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3270 my $vp_file = $dt_path . "vendor-prefixes.txt";
3271
3272 foreach my $compat (@compats) {
3273 my $compat2 = $compat;
3274 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3275 my $compat3 = $compat;
3276 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3277 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3278 if ( $? >> 8 ) {
3279 WARN("UNDOCUMENTED_DT_STRING",
3280 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3281 }
3282
3283 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3284 my $vendor = $1;
3285 `grep -Eq "^$vendor\\b" $vp_file`;
3286 if ( $? >> 8 ) {
3287 WARN("UNDOCUMENTED_DT_STRING",
3288 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3289 }
3290 }
3291 }
3292
Martin Roth60915b32018-08-10 21:04:05 -06003293# check for using SPDX license tag at beginning of files
3294 if ($realline == $checklicenseline) {
3295 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3296 $checklicenseline = 2;
3297 } elsif ($rawline =~ /^\+/) {
3298 my $comment = "";
3299 if ($realfile =~ /\.(h|s|S)$/) {
3300 $comment = '/*';
3301 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3302 $comment = '//';
3303 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3304 $comment = '#';
3305 } elsif ($realfile =~ /\.rst$/) {
3306 $comment = '..';
3307 }
3308
3309 if ($comment !~ /^$/ &&
3310 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3311 WARN("SPDX_LICENSE_TAG",
3312 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3313 }
3314 }
3315 }
3316
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003317# check we are in a valid source file if not then ignore this hunk
Martin Rothedd591d2017-03-14 10:16:29 -06003318 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003319
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003320# line length limit (with some exclusions)
3321#
3322# There are a few types of lines that may extend beyond $max_line_length:
3323# logging functions like pr_info that end in a string
3324# lines with a single string
3325# #defines that are a single string
Martin Roth60915b32018-08-10 21:04:05 -06003326# lines with an RFC3986 like URL
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003327#
3328# There are 3 different line length message types:
Martin Roth387dec82017-09-17 19:20:46 -06003329# LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003330# LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3331# LONG_LINE all other lines longer than $max_line_length
3332#
3333# if LONG_LINE is ignored, the other 2 types are also ignored
3334#
3335
Michael Niewöhner8eb7b352022-10-25 23:29:18 +02003336 $max_line_length += 1; # consider leading + in patches
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003337 if ($line =~ /^\+/ && $length > $max_line_length) {
3338 my $msg_type = "LONG_LINE";
3339
3340 # Check the allowed long line types first
3341
3342 # logging functions that end in a string that starts
3343 # before $max_line_length
3344 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3345 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3346 $msg_type = "";
3347
3348 # lines with only strings (w/ possible termination)
3349 # #defines with only strings
3350 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3351 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3352 $msg_type = "";
3353
Martin Roth60915b32018-08-10 21:04:05 -06003354 # More special cases
3355 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3356 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3357 $msg_type = "";
3358
3359 # URL ($rawline is used in case the URL is in a comment)
3360 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
Martin Rothedd591d2017-03-14 10:16:29 -06003361 $msg_type = "";
3362
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003363 # Otherwise set the alternate message types
3364
3365 # a comment starts before $max_line_length
3366 } elsif ($line =~ /($;[\s$;]*)$/ &&
3367 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3368 $msg_type = "LONG_LINE_COMMENT"
3369
3370 # a quoted string starts before $max_line_length
3371 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3372 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3373 $msg_type = "LONG_LINE_STRING"
3374 }
3375
3376 if ($msg_type ne "" &&
3377 (show_type("LONG_LINE") || show_type($msg_type))) {
Elyes Haouas0b1a03c2022-04-07 10:13:54 +02003378 my $msg_level = \&WARN;
3379 $msg_level = \&CHK if ($file);
3380 &{$msg_level}($msg_type,
3381 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003382 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003383 }
3384
3385# check for adding lines without a newline.
3386 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
Elyes Haouas86e4a3a2022-07-13 16:32:45 +02003387 if (WARN("MISSING_EOF_NEWLINE",
3388 "adding a line without newline at end of file\n" . $herecurr) &&
3389 $fix) {
3390 fix_delete_line($fixlinenr+1, "No newline at end of file");
3391 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003392 }
3393
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003394# check we are in a valid source file C or perl if not then ignore this hunk
3395 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3396
3397# at the beginning of a line any tabs must come first and anything
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003398# more than $tabsize must use tabs.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003399 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3400 $rawline =~ /^\+\s* \s*/) {
3401 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3402 $rpt_cleaners = 1;
3403 if (ERROR("CODE_INDENT",
3404 "code indent should use tabs where possible\n" . $herevet) &&
3405 $fix) {
3406 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3407 }
3408 }
3409
3410# check for space before tabs.
3411 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3412 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3413 if (WARN("SPACE_BEFORE_TAB",
3414 "please, no space before tabs\n" . $herevet) &&
3415 $fix) {
3416 while ($fixed[$fixlinenr] =~
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003417 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003418 while ($fixed[$fixlinenr] =~
3419 s/(^\+.*) +\t/$1\t/) {}
3420 }
3421 }
3422
Martin Roth60915b32018-08-10 21:04:05 -06003423# check for assignments on the start of a line
3424 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
Elyes Haouasc5ede532022-07-13 16:29:14 +02003425 my $operator = $1;
3426 if (CHK("ASSIGNMENT_CONTINUATIONS",
3427 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3428 $fix && $prevrawline =~ /^\+/) {
3429 # add assignment operator to the previous line, remove from current line
3430 $fixed[$fixlinenr - 1] .= " $operator";
3431 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3432 }
Martin Roth60915b32018-08-10 21:04:05 -06003433 }
3434
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003435# check for && or || at the start of a line
3436 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
Elyes Haouasd92fcf42022-07-13 16:34:29 +02003437 my $operator = $1;
3438 if (CHK("LOGICAL_CONTINUATIONS",
3439 "Logical continuations should be on the previous line\n" . $hereprev) &&
3440 $fix && $prevrawline =~ /^\+/) {
3441 # insert logical operator at last non-comment, non-whitepsace char on previous line
3442 $prevline =~ /[\s$;]*$/;
3443 my $line_end = substr($prevrawline, $-[0]);
3444 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3445 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3446 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003447 }
3448
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003449# check indentation starts on a tab stop
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003450 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06003451 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003452 my $indent = length($1);
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003453 if ($indent % $tabsize) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003454 if (WARN("TABSTOP",
3455 "Statements should start on a tabstop\n" . $herecurr) &&
3456 $fix) {
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003457 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003458 }
3459 }
3460 }
3461
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003462# check multi-line statement indentation matches previous line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003463 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06003464 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003465 $prevline =~ /^\+(\t*)(.*)$/;
3466 my $oldindent = $1;
3467 my $rest = $2;
3468
3469 my $pos = pos_last_openparen($rest);
3470 if ($pos >= 0) {
3471 $line =~ /^(\+| )([ \t]*)/;
3472 my $newindent = $2;
3473
3474 my $goodtabindent = $oldindent .
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003475 "\t" x ($pos / $tabsize) .
3476 " " x ($pos % $tabsize);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003477 my $goodspaceindent = $oldindent . " " x $pos;
3478
3479 if ($newindent ne $goodtabindent &&
3480 $newindent ne $goodspaceindent) {
3481
3482 if (CHK("PARENTHESIS_ALIGNMENT",
3483 "Alignment should match open parenthesis\n" . $hereprev) &&
3484 $fix && $line =~ /^\+/) {
3485 $fixed[$fixlinenr] =~
3486 s/^\+[ \t]*/\+$goodtabindent/;
3487 }
3488 }
3489 }
3490 }
3491
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003492# check for space after cast like "(int) foo" or "(struct foo) bar"
3493# avoid checking a few false positives:
3494# "sizeof(<type>)" or "__alignof__(<type>)"
3495# function pointer declarations like "(*foo)(int) = bar;"
3496# structure definitions like "(struct foo) { 0 };"
3497# multiline macros that define functions
3498# known attributes or the __attribute__ keyword
3499 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3500 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003501 if (CHK("SPACING",
3502 "No space is necessary after a cast\n" . $herecurr) &&
3503 $fix) {
3504 $fixed[$fixlinenr] =~
3505 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3506 }
3507 }
3508
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003509# Block comment styles
3510# Networking with an initial /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003511 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3512 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3513 $rawline =~ /^\+[ \t]*\*/ &&
3514 $realline > 2) {
3515 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3516 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3517 }
3518
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003519# Block comments use * on subsequent lines
3520 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3521 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003522 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3523 $rawline =~ /^\+/ && #line is new
3524 $rawline !~ /^\+[ \t]*\*/) { #no leading *
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003525 WARN("BLOCK_COMMENT_STYLE",
3526 "Block comments use * on subsequent lines\n" . $hereprev);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003527 }
3528
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003529# Block comments use */ on trailing lines
3530 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003531 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3532 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3533 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003534 WARN("BLOCK_COMMENT_STYLE",
3535 "Block comments use a trailing */ on a separate line\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003536 }
3537
Martin Rothedd591d2017-03-14 10:16:29 -06003538# Block comment * alignment
3539 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3540 $line =~ /^\+[ \t]*$;/ && #leading comment
3541 $rawline =~ /^\+[ \t]*\*/ && #leading *
3542 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3543 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3544 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3545 my $oldindent;
3546 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3547 if (defined($1)) {
3548 $oldindent = expand_tabs($1);
3549 } else {
3550 $prevrawline =~ m@^\+(.*/?)\*@;
3551 $oldindent = expand_tabs($1);
3552 }
3553 $rawline =~ m@^\+([ \t]*)\*@;
3554 my $newindent = $1;
3555 $newindent = expand_tabs($newindent);
3556 if (length($oldindent) ne length($newindent)) {
3557 WARN("BLOCK_COMMENT_STYLE",
3558 "Block comments should align the * on each line\n" . $hereprev);
3559 }
3560 }
3561
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003562# check for missing blank lines after struct/union declarations
3563# with exceptions for various attributes and macros
3564 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3565 $line =~ /^\+/ &&
3566 !($line =~ /^\+\s*$/ ||
3567 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3568 $line =~ /^\+\s*MODULE_/i ||
3569 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3570 $line =~ /^\+[a-z_]*init/ ||
3571 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3572 $line =~ /^\+\s*DECLARE/ ||
Martin Roth60915b32018-08-10 21:04:05 -06003573 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003574 $line =~ /^\+\s*__setup/)) {
3575 if (CHK("LINE_SPACING",
3576 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3577 $fix) {
3578 fix_insert_line($fixlinenr, "\+");
3579 }
3580 }
3581
3582# check for multiple consecutive blank lines
3583 if ($prevline =~ /^[\+ ]\s*$/ &&
3584 $line =~ /^\+\s*$/ &&
3585 $last_blank_line != ($linenr - 1)) {
3586 if (CHK("LINE_SPACING",
3587 "Please don't use multiple blank lines\n" . $hereprev) &&
3588 $fix) {
3589 fix_delete_line($fixlinenr, $rawline);
3590 }
3591
3592 $last_blank_line = $linenr;
3593 }
3594
3595# check for missing blank lines after declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003596# (declarations must have the same indentation and not be at the start of line)
3597 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3598 # use temporaries
3599 my $sl = $sline;
3600 my $pl = $prevline;
3601 # remove $Attribute/$Sparse uses to simplify comparisons
3602 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3603 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3604 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003605 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003606 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003607 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003608 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003609 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003610 $pl =~ /^\+\s+$declaration_macros/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003611 # for "else if" which can look like "$Ident $Ident"
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003612 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003613 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003614 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003615 # not starting a section or a macro "\" extended line
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003616 $pl =~ /(?:\{\s*|\\)$/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003617 # looks like a declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003618 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003619 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003620 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003621 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003622 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003623 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003624 $sl =~ /^\+\s+$declaration_macros/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003625 # start of struct or union or enum
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003626 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003627 # start or end of block or continuation of declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003628 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003629 # bitfield continuation
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003630 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003631 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003632 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3633 if (WARN("LINE_SPACING",
3634 "Missing a blank line after declarations\n" . $hereprev) &&
3635 $fix) {
3636 fix_insert_line($fixlinenr, "\+");
3637 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003638 }
3639 }
3640
3641# check for spaces at the beginning of a line.
3642# Exceptions:
3643# 1) within comments
3644# 2) indented preprocessor commands
3645# 3) hanging labels
3646 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3647 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3648 if (WARN("LEADING_SPACE",
3649 "please, no spaces at the start of a line\n" . $herevet) &&
3650 $fix) {
3651 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3652 }
3653 }
3654
3655# check we are in a valid C source file if not then ignore this hunk
3656 next if ($realfile !~ /\.(h|c)$/);
3657
Martin Roth60915b32018-08-10 21:04:05 -06003658# check for unusual line ending [ or (
3659 if ($line =~ /^\+.*([\[\(])\s*$/) {
3660 CHK("OPEN_ENDED_LINE",
3661 "Lines should not end with a '$1'\n" . $herecurr);
3662 }
3663
Martin Roth387dec82017-09-17 19:20:46 -06003664# check if this appears to be the start function declaration, save the name
3665 if ($sline =~ /^\+\{\s*$/ &&
3666 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3667 $context_function = $1;
3668 }
3669
3670# check if this appears to be the end of function declaration
3671 if ($sline =~ /^\+\}\s*$/) {
3672 undef $context_function;
3673 }
3674
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003675# check indentation of any line with a bare else
3676# (but not if it is a multiple line "if (foo) return bar; else return baz;")
3677# if the previous line is a break or return and is indented 1 tab more...
3678 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3679 my $tabs = length($1) + 1;
3680 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3681 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3682 defined $lines[$linenr] &&
3683 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3684 WARN("UNNECESSARY_ELSE",
3685 "else is not generally useful after a break or return\n" . $hereprev);
3686 }
3687 }
3688
3689# check indentation of a line with a break;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003690# if the previous line is a goto, return or break
3691# and is indented the same # of tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003692 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3693 my $tabs = $1;
Elyes Haouasa59a87c2022-07-13 16:36:25 +02003694 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3695 if (WARN("UNNECESSARY_BREAK",
3696 "break is not useful after a $1\n" . $hereprev) &&
3697 $fix) {
3698 fix_delete_line($fixlinenr, $rawline);
3699 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003700 }
3701 }
3702
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003703# check for RCS/CVS revision markers
3704 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3705 WARN("CVS_KEYWORD",
3706 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3707 }
3708
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003709# check for old HOTPLUG __dev<foo> section markings
3710 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3711 WARN("HOTPLUG_SECTION",
3712 "Using $1 is unnecessary\n" . $herecurr);
3713 }
3714
3715# Check for potential 'bare' types
3716 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3717 $realline_next);
3718#print "LINE<$line>\n";
Martin Roth387dec82017-09-17 19:20:46 -06003719 if ($linenr > $suppress_statement &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003720 $realcnt && $sline =~ /.\s*\S/) {
3721 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3722 ctx_statement_block($linenr, $realcnt, 0);
3723 $stat =~ s/\n./\n /g;
3724 $cond =~ s/\n./\n /g;
3725
3726#print "linenr<$linenr> <$stat>\n";
3727 # If this statement has no statement boundaries within
3728 # it there is no point in retrying a statement scan
3729 # until we hit end of it.
3730 my $frag = $stat; $frag =~ s/;+\s*$//;
3731 if ($frag !~ /(?:{|;)/) {
3732#print "skip<$line_nr_next>\n";
3733 $suppress_statement = $line_nr_next;
3734 }
3735
3736 # Find the real next line.
3737 $realline_next = $line_nr_next;
3738 if (defined $realline_next &&
3739 (!defined $lines[$realline_next - 1] ||
3740 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3741 $realline_next++;
3742 }
3743
3744 my $s = $stat;
3745 $s =~ s/{.*$//s;
3746
3747 # Ignore goto labels.
3748 if ($s =~ /$Ident:\*$/s) {
3749
3750 # Ignore functions being called
3751 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3752
3753 } elsif ($s =~ /^.\s*else\b/s) {
3754
3755 # declarations always start with types
3756 } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
3757 my $type = $1;
3758 $type =~ s/\s+/ /g;
3759 possible($type, "A:" . $s);
3760
3761 # definitions in global scope can only start with types
3762 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3763 possible($1, "B:" . $s);
3764 }
3765
3766 # any (foo ... *) is a pointer cast, and foo is a type
3767 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3768 possible($1, "C:" . $s);
3769 }
3770
3771 # Check for any sort of function declaration.
3772 # int foo(something bar, other baz);
3773 # void (*store_gdt)(x86_descr_ptr *);
3774 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3775 my ($name_len) = length($1);
3776
3777 my $ctx = $s;
3778 substr($ctx, 0, $name_len + 1, '');
3779 $ctx =~ s/\)[^\)]*$//;
3780
3781 for my $arg (split(/\s*,\s*/, $ctx)) {
3782 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3783
3784 possible($1, "D:" . $s);
3785 }
3786 }
3787 }
3788
3789 }
3790
3791#
3792# Checks which may be anchored in the context.
3793#
3794
3795# Check for switch () and associated case and default
3796# statements should be at the same indent.
3797 if ($line=~/\bswitch\s*\(.*\)/) {
3798 my $err = '';
3799 my $sep = '';
3800 my @ctx = ctx_block_outer($linenr, $realcnt);
3801 shift(@ctx);
3802 for my $ctx (@ctx) {
3803 my ($clen, $cindent) = line_stats($ctx);
3804 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3805 $indent != $cindent) {
3806 $err .= "$sep$ctx\n";
3807 $sep = '';
3808 } else {
3809 $sep = "[...]\n";
3810 }
3811 }
3812 if ($err ne '') {
3813 ERROR("SWITCH_CASE_INDENT_LEVEL",
3814 "switch and case should be at the same indent\n$hereline$err");
3815 }
3816 }
3817
3818# if/while/etc brace do not go on next line, unless defining a do while loop,
3819# or if that brace on the next line is for something else
3820 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3821 my $pre_ctx = "$1$2";
3822
3823 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3824
3825 if ($line =~ /^\+\t{6,}/) {
3826 WARN("DEEP_INDENTATION",
3827 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3828 }
3829
3830 my $ctx_cnt = $realcnt - $#ctx - 1;
3831 my $ctx = join("\n", @ctx);
3832
3833 my $ctx_ln = $linenr;
3834 my $ctx_skip = $realcnt;
3835
3836 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3837 defined $lines[$ctx_ln - 1] &&
3838 $lines[$ctx_ln - 1] =~ /^-/)) {
3839 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3840 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3841 $ctx_ln++;
3842 }
3843
3844 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3845 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3846
3847 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3848 ERROR("OPEN_BRACE",
3849 "that open brace { should be on the previous line\n" .
3850 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3851 }
3852 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3853 $ctx =~ /\)\s*\;\s*$/ &&
3854 defined $lines[$ctx_ln - 1])
3855 {
3856 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3857 if ($nindent > $indent) {
3858 WARN("TRAILING_SEMICOLON",
3859 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3860 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3861 }
3862 }
3863 }
3864
3865# Check relative indent for conditionals and blocks.
Martin Roth387dec82017-09-17 19:20:46 -06003866 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003867 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3868 ctx_statement_block($linenr, $realcnt, 0)
3869 if (!defined $stat);
3870 my ($s, $c) = ($stat, $cond);
3871
3872 substr($s, 0, length($c), '');
3873
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003874 # remove inline comments
3875 $s =~ s/$;/ /g;
3876 $c =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003877
3878 # Find out how long the conditional actually is.
3879 my @newlines = ($c =~ /\n/gs);
3880 my $cond_lines = 1 + $#newlines;
3881
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003882 # Make sure we remove the line prefixes as we have
3883 # none on the first line, and are going to readd them
3884 # where necessary.
3885 $s =~ s/\n./\n/gs;
3886 while ($s =~ /\n\s+\\\n/) {
3887 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3888 }
3889
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003890 # We want to check the first line inside the block
3891 # starting at the end of the conditional, so remove:
3892 # 1) any blank line termination
3893 # 2) any opening brace { on end of the line
3894 # 3) any do (...) {
3895 my $continuation = 0;
3896 my $check = 0;
3897 $s =~ s/^.*\bdo\b//;
3898 $s =~ s/^\s*{//;
3899 if ($s =~ s/^\s*\\//) {
3900 $continuation = 1;
3901 }
3902 if ($s =~ s/^\s*?\n//) {
3903 $check = 1;
3904 $cond_lines++;
3905 }
3906
3907 # Also ignore a loop construct at the end of a
3908 # preprocessor statement.
3909 if (($prevline =~ /^.\s*#\s*define\s/ ||
3910 $prevline =~ /\\\s*$/) && $continuation == 0) {
3911 $check = 0;
3912 }
3913
3914 my $cond_ptr = -1;
3915 $continuation = 0;
3916 while ($cond_ptr != $cond_lines) {
3917 $cond_ptr = $cond_lines;
3918
3919 # If we see an #else/#elif then the code
3920 # is not linear.
3921 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3922 $check = 0;
3923 }
3924
3925 # Ignore:
3926 # 1) blank lines, they should be at 0,
3927 # 2) preprocessor lines, and
3928 # 3) labels.
3929 if ($continuation ||
3930 $s =~ /^\s*?\n/ ||
3931 $s =~ /^\s*#\s*?/ ||
3932 $s =~ /^\s*$Ident\s*:/) {
3933 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3934 if ($s =~ s/^.*?\n//) {
3935 $cond_lines++;
3936 }
3937 }
3938 }
3939
3940 my (undef, $sindent) = line_stats("+" . $s);
3941 my $stat_real = raw_line($linenr, $cond_lines);
3942
3943 # Check if either of these lines are modified, else
3944 # this is not this patch's fault.
3945 if (!defined($stat_real) ||
3946 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3947 $check = 0;
3948 }
3949 if (defined($stat_real) && $cond_lines > 1) {
3950 $stat_real = "[...]\n$stat_real";
3951 }
3952
3953 #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
3954
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003955 if ($check && $s ne '' &&
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003956 (($sindent % $tabsize) != 0 ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003957 ($sindent < $indent) ||
Martin Roth387dec82017-09-17 19:20:46 -06003958 ($sindent == $indent &&
3959 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003960 ($sindent > $indent + $tabsize))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003961 WARN("SUSPECT_CODE_INDENT",
3962 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3963 }
Julius Werner218906d2021-03-25 21:12:49 -07003964
3965# Also check if the next statement after the previous condition has the same indent
3966 my ($stat_next, undef, $line_nr_next_next) =
3967 ctx_statement_block($line_nr_next, $remain_next, $off_next);
3968 my $s_next = $stat_next;
3969
3970 # Remove line prefixes
3971 $s_next =~ s/\n./\n/g;
3972
3973 # Remove any comments
3974 $s_next =~ s/$;//g;
3975
3976 # Remove any leading labels
3977 $s_next =~ s/\n( ?$Ident:)/"\n" . " " x length($1)/eg;
3978
3979 # Skip this check for in case next statement starts with 'else'
3980 if ($s_next !~ /\belse\b/) {
3981
3982 # Remove while that belongs to a do {} while
3983 if ($stat =~ /\bdo\b/) {
3984 $s_next =~ s/^.*\bwhile\b\s*($balanced_parens)\s*?//;
3985 }
3986
3987 # Remove blank lines
3988 $s_next =~ s/\s*\\?\n//g;
3989
3990 # Get the real next lines
3991 my $next_nof_lines = $line_nr_next_next - $line_nr_next;
3992 my $stat_next_real = raw_line($line_nr_next, $next_nof_lines);
3993 if (!defined($stat_next_real)) {
3994 $stat_next_real = "";
3995 } elsif ($next_nof_lines > 1) {
3996 $stat_next_real = "[...]\n$stat_next_real";
3997 }
3998 my (undef, $nindent) = line_stats('+' . $s_next);
3999
4000 #print "stat_next<$stat_next> stat<$stat> indent<$indent> nindent<$nindent> s_next<$s_next> stat_next_real<$stat_next_real>\n";
4001
4002 if ($nindent > $indent) {
4003 WARN("SUSPICIOUS_CODE_INDENT",
4004 "suspicious code indentation after conditional statements\n" .
4005 $herecurr . "$stat_real\n$stat_next_real\n");
4006 }
4007 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004008 }
4009
4010 # Track the 'values' across context and added lines.
4011 my $opline = $line; $opline =~ s/^./ /;
4012 my ($curr_values, $curr_vars) =
4013 annotate_values($opline . "\n", $prev_values);
4014 $curr_values = $prev_values . $curr_values;
4015 if ($dbg_values) {
4016 my $outline = $opline; $outline =~ s/\t/ /g;
4017 print "$linenr > .$outline\n";
4018 print "$linenr > $curr_values\n";
4019 print "$linenr > $curr_vars\n";
4020 }
4021 $prev_values = substr($curr_values, -1);
4022
4023#ignore lines not being added
4024 next if ($line =~ /^[^\+]/);
4025
Elyes Haouasf9a3554a2022-07-13 18:03:47 +02004026# check for self assignments used to avoid compiler warnings
4027# e.g.: int foo = foo, *bar = NULL;
4028# struct foo bar = *(&(bar));
4029 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4030 my $var = $1;
4031 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4032 WARN("SELF_ASSIGNMENT",
4033 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4034 }
4035 }
4036
Martin Rothedd591d2017-03-14 10:16:29 -06004037# check for dereferences that span multiple lines
4038 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4039 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4040 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4041 my $ref = $1;
4042 $line =~ /^.\s*($Lval)/;
4043 $ref .= $1;
4044 $ref =~ s/\s//g;
4045 WARN("MULTILINE_DEREFERENCE",
4046 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4047 }
4048
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004049# check for declarations of signed or unsigned without int
Martin Rothedd591d2017-03-14 10:16:29 -06004050 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004051 my $type = $1;
4052 my $var = $2;
4053 $var = "" if (!defined $var);
4054 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4055 my $sign = $1;
4056 my $pointer = $2;
4057
4058 $pointer = "" if (!defined $pointer);
4059
4060 if (WARN("UNSPECIFIED_INT",
4061 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4062 $fix) {
4063 my $decl = trim($sign) . " int ";
4064 my $comp_pointer = $pointer;
4065 $comp_pointer =~ s/\s//g;
4066 $decl .= $comp_pointer;
4067 $decl = rtrim($decl) if ($var eq "");
4068 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4069 }
4070 }
4071 }
4072
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004073# TEST: allow direct testing of the type matcher.
4074 if ($dbg_type) {
4075 if ($line =~ /^.\s*$Declare\s*$/) {
4076 ERROR("TEST_TYPE",
4077 "TEST: is type\n" . $herecurr);
4078 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4079 ERROR("TEST_NOT_TYPE",
4080 "TEST: is not type ($1 is)\n". $herecurr);
4081 }
4082 next;
4083 }
4084# TEST: allow direct testing of the attribute matcher.
4085 if ($dbg_attr) {
4086 if ($line =~ /^.\s*$Modifier\s*$/) {
4087 ERROR("TEST_ATTR",
4088 "TEST: is attr\n" . $herecurr);
4089 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4090 ERROR("TEST_NOT_ATTR",
4091 "TEST: is not attr ($1 is)\n". $herecurr);
4092 }
4093 next;
4094 }
4095
4096# check for initialisation to aggregates open brace on the next line
4097 if ($line =~ /^.\s*{/ &&
4098 $prevline =~ /(?:^|[^=])=\s*$/) {
4099 if (ERROR("OPEN_BRACE",
4100 "that open brace { should be on the previous line\n" . $hereprev) &&
4101 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4102 fix_delete_line($fixlinenr - 1, $prevrawline);
4103 fix_delete_line($fixlinenr, $rawline);
4104 my $fixedline = $prevrawline;
4105 $fixedline =~ s/\s*=\s*$/ = {/;
4106 fix_insert_line($fixlinenr, $fixedline);
4107 $fixedline = $line;
Martin Roth387dec82017-09-17 19:20:46 -06004108 $fixedline =~ s/^(.\s*)\{\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004109 fix_insert_line($fixlinenr, $fixedline);
4110 }
4111 }
4112
4113#
4114# Checks which are anchored on the added line.
4115#
4116
4117# check for malformed paths in #include statements (uses RAW line)
4118 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4119 my $path = $1;
4120 if ($path =~ m{//}) {
4121 ERROR("MALFORMED_INCLUDE",
4122 "malformed #include filename\n" . $herecurr);
4123 }
4124 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4125 ERROR("UAPI_INCLUDE",
4126 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4127 }
4128 }
4129
4130# no C99 // comments
4131 if ($line =~ m{//}) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004132 if (ERROR("C99_COMMENTS",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004133 "do not use C99 // comments\n" . $herecurr) &&
4134 $fix) {
4135 my $line = $fixed[$fixlinenr];
4136 if ($line =~ /\/\/(.*)$/) {
4137 my $comment = trim($1);
4138 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4139 }
4140 }
4141 }
4142 # Remove C99 comments.
4143 $line =~ s@//.*@@;
4144 $opline =~ s@//.*@@;
4145
4146# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4147# the whole statement.
4148#print "APW <$lines[$realline_next - 1]>\n";
4149 if (defined $realline_next &&
4150 exists $lines[$realline_next - 1] &&
4151 !defined $suppress_export{$realline_next} &&
4152 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4153 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4154 # Handle definitions which produce identifiers with
4155 # a prefix:
4156 # XXX(foo);
4157 # EXPORT_SYMBOL(something_foo);
4158 my $name = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004159 $name =~ s/^\s*($Ident).*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004160 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4161 $name =~ /^${Ident}_$2/) {
4162#print "FOO C name<$name>\n";
4163 $suppress_export{$realline_next} = 1;
4164
4165 } elsif ($stat !~ /(?:
4166 \n.}\s*$|
4167 ^.DEFINE_$Ident\(\Q$name\E\)|
4168 ^.DECLARE_$Ident\(\Q$name\E\)|
4169 ^.LIST_HEAD\(\Q$name\E\)|
4170 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4171 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4172 )/x) {
4173#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4174 $suppress_export{$realline_next} = 2;
4175 } else {
4176 $suppress_export{$realline_next} = 1;
4177 }
4178 }
4179 if (!defined $suppress_export{$linenr} &&
4180 $prevline =~ /^.\s*$/ &&
4181 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4182 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4183#print "FOO B <$lines[$linenr - 1]>\n";
4184 $suppress_export{$linenr} = 2;
4185 }
4186 if (defined $suppress_export{$linenr} &&
4187 $suppress_export{$linenr} == 2) {
4188 WARN("EXPORT_SYMBOL",
4189 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4190 }
4191
4192# check for global initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004193 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004194 if (ERROR("GLOBAL_INITIALISERS",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004195 "do not initialise globals to $1\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004196 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004197 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004198 }
4199 }
4200# check for static initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004201 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004202 if (ERROR("INITIALISED_STATIC",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004203 "do not initialise statics to $1\n" .
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004204 $herecurr) &&
4205 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004206 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004207 }
4208 }
4209
4210# check for misordered declarations of char/short/int/long with signed/unsigned
4211 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4212 my $tmp = trim($1);
4213 WARN("MISORDERED_TYPE",
4214 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4215 }
4216
4217# check for static const char * arrays.
4218 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4219 WARN("STATIC_CONST_CHAR_ARRAY",
4220 "static const char * array should probably be static const char * const\n" .
4221 $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02004222 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004223
4224# check for static char foo[] = "bar" declarations.
4225 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4226 WARN("STATIC_CONST_CHAR_ARRAY",
4227 "static char array declaration should probably be static const char\n" .
4228 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004229 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004230
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004231# check for const <foo> const where <foo> is not a pointer or array type
4232 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4233 my $found = $1;
4234 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4235 WARN("CONST_CONST",
4236 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4237 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4238 WARN("CONST_CONST",
4239 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4240 }
4241 }
4242
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004243# check for non-global char *foo[] = {"bar", ...} declarations.
4244 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4245 WARN("STATIC_CONST_CHAR_ARRAY",
4246 "char * array declaration might be better as static const\n" .
4247 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004248 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004249
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004250# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4251 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4252 my $array = $1;
4253 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4254 my $array_div = $1;
4255 if (WARN("ARRAY_SIZE",
4256 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4257 $fix) {
4258 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4259 }
4260 }
4261 }
4262
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004263# check for function declarations without arguments like "int foo()"
Elyes Haouas26e0b942022-05-22 11:11:11 +02004264 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004265 if (ERROR("FUNCTION_WITHOUT_ARGS",
4266 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4267 $fix) {
4268 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4269 }
4270 }
4271
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004272# check for new typedefs, only function parameters and sparse annotations
4273# make sense.
4274 if ($line =~ /\btypedef\s/ &&
4275 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4276 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4277 $line !~ /\b$typeTypedefs\b/ &&
Martin Rothedd591d2017-03-14 10:16:29 -06004278 $line !~ /\b__bitwise\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004279 WARN("NEW_TYPEDEFS",
4280 "do not add new typedefs\n" . $herecurr);
4281 }
4282
4283# * goes on variable not on type
4284 # (char*[ const])
4285 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4286 #print "AA<$1>\n";
4287 my ($ident, $from, $to) = ($1, $2, $2);
4288
4289 # Should start with a space.
4290 $to =~ s/^(\S)/ $1/;
4291 # Should not end with a space.
4292 $to =~ s/\s+$//;
4293 # '*'s should not have spaces between.
4294 while ($to =~ s/\*\s+\*/\*\*/) {
4295 }
4296
4297## print "1: from<$from> to<$to> ident<$ident>\n";
4298 if ($from ne $to) {
4299 if (ERROR("POINTER_LOCATION",
4300 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4301 $fix) {
4302 my $sub_from = $ident;
4303 my $sub_to = $ident;
4304 $sub_to =~ s/\Q$from\E/$to/;
4305 $fixed[$fixlinenr] =~
4306 s@\Q$sub_from\E@$sub_to@;
4307 }
4308 }
4309 }
4310 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4311 #print "BB<$1>\n";
4312 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4313
4314 # Should start with a space.
4315 $to =~ s/^(\S)/ $1/;
4316 # Should not end with a space.
4317 $to =~ s/\s+$//;
4318 # '*'s should not have spaces between.
4319 while ($to =~ s/\*\s+\*/\*\*/) {
4320 }
4321 # Modifiers should have spaces.
4322 $to =~ s/(\b$Modifier$)/$1 /;
4323
4324## print "2: from<$from> to<$to> ident<$ident>\n";
4325 if ($from ne $to && $ident !~ /^$Modifier$/) {
4326 if (ERROR("POINTER_LOCATION",
4327 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4328 $fix) {
4329
4330 my $sub_from = $match;
4331 my $sub_to = $match;
4332 $sub_to =~ s/\Q$from\E/$to/;
4333 $fixed[$fixlinenr] =~
4334 s@\Q$sub_from\E@$sub_to@;
4335 }
4336 }
4337 }
4338
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004339# avoid BUG() or BUG_ON()
4340 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
Martin Roth387dec82017-09-17 19:20:46 -06004341 my $msg_level = \&WARN;
4342 $msg_level = \&CHK if ($file);
4343 &{$msg_level}("AVOID_BUG",
4344 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004345 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004346
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004347# avoid LINUX_VERSION_CODE
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004348 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4349 WARN("LINUX_VERSION_CODE",
4350 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4351 }
4352
4353# check for uses of printk_ratelimit
4354 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4355 WARN("PRINTK_RATELIMITED",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004356 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004357 }
4358
Martin Roth60915b32018-08-10 21:04:05 -06004359# printk should use KERN_* levels
4360 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4361 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4362 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004363 }
4364
4365 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4366 my $orig = $1;
4367 my $level = lc($orig);
4368 $level = "warn" if ($level eq "warning");
4369 my $level2 = $level;
4370 $level2 = "dbg" if ($level eq "debug");
4371 WARN("PREFER_PR_LEVEL",
4372 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4373 }
4374
4375 if ($line =~ /\bpr_warning\s*\(/) {
4376 if (WARN("PREFER_PR_LEVEL",
4377 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4378 $fix) {
4379 $fixed[$fixlinenr] =~
4380 s/\bpr_warning\b/pr_warn/;
4381 }
4382 }
4383
4384 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4385 my $orig = $1;
4386 my $level = lc($orig);
4387 $level = "warn" if ($level eq "warning");
4388 $level = "dbg" if ($level eq "debug");
4389 WARN("PREFER_DEV_LEVEL",
4390 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4391 }
4392
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004393# ENOSYS means "bad syscall nr" and nothing else. This will have a small
4394# number of false positives, but assembly files are not checked, so at
4395# least the arch entry code will not trigger this warning.
4396 if ($line =~ /\bENOSYS\b/) {
4397 WARN("ENOSYS",
4398 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4399 }
4400
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004401# function brace can't be on same line, except for #defines of do while,
4402# or if closed on same line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004403 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06004404 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4405 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4406 $sline !~ /}/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004407 if (ERROR("OPEN_BRACE",
Martin Roth60915b32018-08-10 21:04:05 -06004408 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004409 $fix) {
4410 fix_delete_line($fixlinenr, $rawline);
4411 my $fixed_line = $rawline;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004412 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004413 my $line1 = $1;
4414 my $line2 = $2;
4415 fix_insert_line($fixlinenr, ltrim($line1));
4416 fix_insert_line($fixlinenr, "\+{");
4417 if ($line2 !~ /^\s*$/) {
4418 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4419 }
4420 }
4421 }
4422
4423# open braces for enum, union and struct go on the same line.
4424 if ($line =~ /^.\s*{/ &&
4425 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4426 if (ERROR("OPEN_BRACE",
4427 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4428 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4429 fix_delete_line($fixlinenr - 1, $prevrawline);
4430 fix_delete_line($fixlinenr, $rawline);
4431 my $fixedline = rtrim($prevrawline) . " {";
4432 fix_insert_line($fixlinenr, $fixedline);
4433 $fixedline = $rawline;
Martin Roth387dec82017-09-17 19:20:46 -06004434 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004435 if ($fixedline !~ /^\+\s*$/) {
4436 fix_insert_line($fixlinenr, $fixedline);
4437 }
4438 }
4439 }
4440
4441# missing space after union, struct or enum definition
4442 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4443 if (WARN("SPACING",
4444 "missing space after $1 definition\n" . $herecurr) &&
4445 $fix) {
4446 $fixed[$fixlinenr] =~
4447 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4448 }
4449 }
4450
4451# Function pointer declarations
4452# check spacing between type, funcptr, and args
4453# canonical declaration is "type (*funcptr)(args...)"
4454 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4455 my $declare = $1;
4456 my $pre_pointer_space = $2;
4457 my $post_pointer_space = $3;
4458 my $funcname = $4;
4459 my $post_funcname_space = $5;
4460 my $pre_args_space = $6;
4461
4462# the $Declare variable will capture all spaces after the type
4463# so check it for a missing trailing missing space but pointer return types
4464# don't need a space so don't warn for those.
4465 my $post_declare_space = "";
4466 if ($declare =~ /(\s+)$/) {
4467 $post_declare_space = $1;
4468 $declare = rtrim($declare);
4469 }
4470 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4471 WARN("SPACING",
4472 "missing space after return type\n" . $herecurr);
4473 $post_declare_space = " ";
4474 }
4475
4476# unnecessary space "type (*funcptr)(args...)"
4477# This test is not currently implemented because these declarations are
4478# equivalent to
4479# int foo(int bar, ...)
4480# and this is form shouldn't/doesn't generate a checkpatch warning.
4481#
4482# elsif ($declare =~ /\s{2,}$/) {
4483# WARN("SPACING",
4484# "Multiple spaces after return type\n" . $herecurr);
4485# }
4486
4487# unnecessary space "type ( *funcptr)(args...)"
4488 if (defined $pre_pointer_space &&
4489 $pre_pointer_space =~ /^\s/) {
4490 WARN("SPACING",
4491 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4492 }
4493
4494# unnecessary space "type (* funcptr)(args...)"
4495 if (defined $post_pointer_space &&
4496 $post_pointer_space =~ /^\s/) {
4497 WARN("SPACING",
4498 "Unnecessary space before function pointer name\n" . $herecurr);
4499 }
4500
4501# unnecessary space "type (*funcptr )(args...)"
4502 if (defined $post_funcname_space &&
4503 $post_funcname_space =~ /^\s/) {
4504 WARN("SPACING",
4505 "Unnecessary space after function pointer name\n" . $herecurr);
4506 }
4507
4508# unnecessary space "type (*funcptr) (args...)"
4509 if (defined $pre_args_space &&
4510 $pre_args_space =~ /^\s/) {
4511 WARN("SPACING",
4512 "Unnecessary space before function pointer arguments\n" . $herecurr);
4513 }
4514
4515 if (show_type("SPACING") && $fix) {
4516 $fixed[$fixlinenr] =~
4517 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4518 }
4519 }
4520
4521# check for spacing round square brackets; allowed:
4522# 1. with a type on the left -- int [] a;
4523# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4524# 3. inside a curly brace -- = { [0...10] = 5 }
Martin Rothedd591d2017-03-14 10:16:29 -06004525# 4. in an extended asm instruction -- : [r0]"r"(r0) (coreboot)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004526 while ($line =~ /(.*?\s)\[/g) {
4527 my ($where, $prefix) = ($-[1], $1);
4528 if ($prefix !~ /$Type\s+$/ &&
4529 ($where != 0 || $prefix !~ /^.\s+$/) &&
Martin Rothedd591d2017-03-14 10:16:29 -06004530 $prefix !~ /[{,:]\s+$/) { #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004531 if (ERROR("BRACKET_SPACE",
4532 "space prohibited before open square bracket '['\n" . $herecurr) &&
4533 $fix) {
4534 $fixed[$fixlinenr] =~
4535 s/^(\+.*?)\s+\[/$1\[/;
4536 }
4537 }
4538 }
4539
4540# check for spaces between functions and their parentheses.
4541 while ($line =~ /($Ident)\s+\(/g) {
4542 my $name = $1;
4543 my $ctx_before = substr($line, 0, $-[1]);
4544 my $ctx = "$ctx_before$name";
4545
4546 # Ignore those directives where spaces _are_ permitted.
4547 if ($name =~ /^(?:
4548 if|for|while|switch|return|case|
4549 volatile|__volatile__|
4550 __attribute__|format|__extension__|
4551 asm|__asm__)$/x)
4552 {
4553 # cpp #define statements have non-optional spaces, ie
4554 # if there is a space between the name and the open
4555 # parenthesis it is simply not a parameter group.
4556 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4557
4558 # cpp #elif statement condition may start with a (
4559 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4560
4561 # If this whole things ends with a type its most
4562 # likely a typedef for a function.
4563 } elsif ($ctx =~ /$Type$/) {
4564
4565 } else {
4566 if (WARN("SPACING",
4567 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4568 $fix) {
4569 $fixed[$fixlinenr] =~
4570 s/\b$name\s+\(/$name\(/;
4571 }
4572 }
4573 }
4574
4575# Check operator spacing.
4576 if (!($line=~/\#\s*include/)) {
4577 my $fixed_line = "";
4578 my $line_fixed = 0;
4579
4580 my $ops = qr{
4581 <<=|>>=|<=|>=|==|!=|
4582 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4583 =>|->|<<|>>|<|>|=|!|~|
4584 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4585 \?:|\?|:
4586 }x;
4587 my @elements = split(/($ops|;)/, $opline);
4588
4589## print("element count: <" . $#elements . ">\n");
4590## foreach my $el (@elements) {
4591## print("el: <$el>\n");
4592## }
4593
4594 my @fix_elements = ();
4595 my $off = 0;
4596
4597 foreach my $el (@elements) {
4598 push(@fix_elements, substr($rawline, $off, length($el)));
4599 $off += length($el);
4600 }
4601
4602 $off = 0;
4603
4604 my $blank = copy_spacing($opline);
4605 my $last_after = -1;
4606
4607 for (my $n = 0; $n < $#elements; $n += 2) {
4608
4609 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4610
4611## print("n: <$n> good: <$good>\n");
4612
4613 $off += length($elements[$n]);
4614
4615 # Pick up the preceding and succeeding characters.
4616 my $ca = substr($opline, 0, $off);
4617 my $cc = '';
4618 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4619 $cc = substr($opline, $off + length($elements[$n + 1]));
4620 }
4621 my $cb = "$ca$;$cc";
4622
4623 my $a = '';
4624 $a = 'V' if ($elements[$n] ne '');
4625 $a = 'W' if ($elements[$n] =~ /\s$/);
4626 $a = 'C' if ($elements[$n] =~ /$;$/);
4627 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4628 $a = 'O' if ($elements[$n] eq '');
4629 $a = 'E' if ($ca =~ /^\s*$/);
4630
4631 my $op = $elements[$n + 1];
4632
4633 my $c = '';
4634 if (defined $elements[$n + 2]) {
4635 $c = 'V' if ($elements[$n + 2] ne '');
4636 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4637 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4638 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4639 $c = 'O' if ($elements[$n + 2] eq '');
4640 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4641 } else {
4642 $c = 'E';
4643 }
4644
4645 my $ctx = "${a}x${c}";
4646
4647 my $at = "(ctx:$ctx)";
4648
4649 my $ptr = substr($blank, 0, $off) . "^";
4650 my $hereptr = "$hereline$ptr\n";
4651
4652 # Pull out the value of this operator.
4653 my $op_type = substr($curr_values, $off + 1, 1);
4654
4655 # Get the full operator variant.
4656 my $opv = $op . substr($curr_vars, $off, 1);
4657
4658 # Ignore operators passed as parameters.
4659 if ($op_type ne 'V' &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004660 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004661
4662# # Ignore comments
4663# } elsif ($op =~ /^$;+$/) {
4664
4665 # ; should have either the end of line or a space or \ after it
4666 } elsif ($op eq ';') {
4667 if ($ctx !~ /.x[WEBC]/ &&
4668 $cc !~ /^\\/ && $cc !~ /^;/) {
4669 if (ERROR("SPACING",
4670 "space required after that '$op' $at\n" . $hereptr)) {
4671 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4672 $line_fixed = 1;
4673 }
4674 }
4675
4676 # // is a comment
4677 } elsif ($op eq '//') {
4678
4679 # : when part of a bitfield
4680 } elsif ($opv eq ':B') {
4681 # skip the bitfield test for now
4682
4683 # No spaces for:
4684 # ->
4685 } elsif ($op eq '->') {
4686 if ($ctx =~ /Wx.|.xW/) {
4687 if (ERROR("SPACING",
4688 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4689 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4690 if (defined $fix_elements[$n + 2]) {
4691 $fix_elements[$n + 2] =~ s/^\s+//;
4692 }
4693 $line_fixed = 1;
4694 }
4695 }
4696
4697 # , must not have a space before and must have a space on the right.
4698 } elsif ($op eq ',') {
4699 my $rtrim_before = 0;
4700 my $space_after = 0;
4701 if ($ctx =~ /Wx./) {
4702 if (ERROR("SPACING",
4703 "space prohibited before that '$op' $at\n" . $hereptr)) {
4704 $line_fixed = 1;
4705 $rtrim_before = 1;
4706 }
4707 }
4708 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4709 if (ERROR("SPACING",
4710 "space required after that '$op' $at\n" . $hereptr)) {
4711 $line_fixed = 1;
4712 $last_after = $n;
4713 $space_after = 1;
4714 }
4715 }
4716 if ($rtrim_before || $space_after) {
4717 if ($rtrim_before) {
4718 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4719 } else {
4720 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4721 }
4722 if ($space_after) {
4723 $good .= " ";
4724 }
4725 }
4726
4727 # '*' as part of a type definition -- reported already.
4728 } elsif ($opv eq '*_') {
4729 #warn "'*' is part of type\n";
4730
4731 # unary operators should have a space before and
4732 # none after. May be left adjacent to another
4733 # unary operator, or a cast
4734 } elsif ($op eq '!' || $op eq '~' ||
4735 $opv eq '*U' || $opv eq '-U' ||
4736 $opv eq '&U' || $opv eq '&&U') {
4737 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4738 if (ERROR("SPACING",
4739 "space required before that '$op' $at\n" . $hereptr)) {
4740 if ($n != $last_after + 2) {
4741 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4742 $line_fixed = 1;
4743 }
4744 }
4745 }
4746 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4747 # A unary '*' may be const
4748
4749 } elsif ($ctx =~ /.xW/) {
4750 if (ERROR("SPACING",
4751 "space prohibited after that '$op' $at\n" . $hereptr)) {
4752 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4753 if (defined $fix_elements[$n + 2]) {
4754 $fix_elements[$n + 2] =~ s/^\s+//;
4755 }
4756 $line_fixed = 1;
4757 }
4758 }
4759
4760 # unary ++ and unary -- are allowed no space on one side.
4761 } elsif ($op eq '++' or $op eq '--') {
4762 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4763 if (ERROR("SPACING",
4764 "space required one side of that '$op' $at\n" . $hereptr)) {
4765 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4766 $line_fixed = 1;
4767 }
4768 }
4769 if ($ctx =~ /Wx[BE]/ ||
4770 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4771 if (ERROR("SPACING",
4772 "space prohibited before that '$op' $at\n" . $hereptr)) {
4773 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4774 $line_fixed = 1;
4775 }
4776 }
4777 if ($ctx =~ /ExW/) {
4778 if (ERROR("SPACING",
4779 "space prohibited after that '$op' $at\n" . $hereptr)) {
4780 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4781 if (defined $fix_elements[$n + 2]) {
4782 $fix_elements[$n + 2] =~ s/^\s+//;
4783 }
4784 $line_fixed = 1;
4785 }
4786 }
4787
4788 # << and >> may either have or not have spaces both sides
4789 } elsif ($op eq '<<' or $op eq '>>' or
4790 $op eq '&' or $op eq '^' or $op eq '|' or
4791 $op eq '+' or $op eq '-' or
4792 $op eq '*' or $op eq '/' or
4793 $op eq '%')
4794 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004795 if ($check) {
4796 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4797 if (CHK("SPACING",
4798 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4799 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4800 $fix_elements[$n + 2] =~ s/^\s+//;
4801 $line_fixed = 1;
4802 }
4803 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4804 if (CHK("SPACING",
4805 "space preferred before that '$op' $at\n" . $hereptr)) {
4806 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4807 $line_fixed = 1;
4808 }
4809 }
4810 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004811 if (ERROR("SPACING",
4812 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4813 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4814 if (defined $fix_elements[$n + 2]) {
4815 $fix_elements[$n + 2] =~ s/^\s+//;
4816 }
4817 $line_fixed = 1;
4818 }
4819 }
4820
4821 # A colon needs no spaces before when it is
4822 # terminating a case value or a label.
4823 } elsif ($opv eq ':C' || $opv eq ':L') {
4824 if ($ctx =~ /Wx./) {
4825 if (ERROR("SPACING",
4826 "space prohibited before that '$op' $at\n" . $hereptr)) {
4827 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4828 $line_fixed = 1;
4829 }
4830 }
4831
4832 # All the others need spaces both sides.
4833 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4834 my $ok = 0;
4835
4836 # Ignore email addresses <foo@bar>
4837 if (($op eq '<' &&
4838 $cc =~ /^\S+\@\S+>/) ||
4839 ($op eq '>' &&
4840 $ca =~ /<\S+\@\S+$/))
4841 {
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004842 $ok = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004843 }
4844
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004845 # for asm volatile statements
4846 # ignore a colon with another
4847 # colon immediately before or after
4848 if (($op eq ':') &&
4849 ($ca =~ /:$/ || $cc =~ /^:/)) {
4850 $ok = 1;
4851 }
4852
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004853 # messages are ERROR, but ?: are CHK
4854 if ($ok == 0) {
Martin Roth387dec82017-09-17 19:20:46 -06004855 my $msg_level = \&ERROR;
4856 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004857
Martin Roth387dec82017-09-17 19:20:46 -06004858 if (&{$msg_level}("SPACING",
4859 "spaces required around that '$op' $at\n" . $hereptr)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004860 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4861 if (defined $fix_elements[$n + 2]) {
4862 $fix_elements[$n + 2] =~ s/^\s+//;
4863 }
4864 $line_fixed = 1;
4865 }
4866 }
4867 }
4868 $off += length($elements[$n + 1]);
4869
4870## print("n: <$n> GOOD: <$good>\n");
4871
4872 $fixed_line = $fixed_line . $good;
4873 }
4874
4875 if (($#elements % 2) == 0) {
4876 $fixed_line = $fixed_line . $fix_elements[$#elements];
4877 }
4878
4879 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4880 $fixed[$fixlinenr] = $fixed_line;
4881 }
4882
4883
4884 }
4885
4886# check for whitespace before a non-naked semicolon
4887 if ($line =~ /^\+.*\S\s+;\s*$/) {
4888 if (WARN("SPACING",
4889 "space prohibited before semicolon\n" . $herecurr) &&
4890 $fix) {
4891 1 while $fixed[$fixlinenr] =~
4892 s/^(\+.*\S)\s+;/$1;/;
4893 }
4894 }
4895
4896# check for multiple assignments
4897 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4898 CHK("MULTIPLE_ASSIGNMENTS",
4899 "multiple assignments should be avoided\n" . $herecurr);
4900 }
4901
4902## # check for multiple declarations, allowing for a function declaration
4903## # continuation.
4904## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4905## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4906##
4907## # Remove any bracketed sections to ensure we do not
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004908## # falsely report the parameters of functions.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004909## my $ln = $line;
4910## while ($ln =~ s/\([^\(\)]*\)//g) {
4911## }
4912## if ($ln =~ /,/) {
4913## WARN("MULTIPLE_DECLARATION",
4914## "declaring multiple variables together should be avoided\n" . $herecurr);
4915## }
4916## }
4917
4918#need space before brace following if, while, etc
Alexander Couzensebef00f2016-04-11 00:52:01 +02004919 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
Elyes Haouas26e0b942022-05-22 11:11:11 +02004920 $line =~ /\b(?:else|do)\{/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004921 if (ERROR("SPACING",
4922 "space required before the open brace '{'\n" . $herecurr) &&
4923 $fix) {
Martin Roth387dec82017-09-17 19:20:46 -06004924 #coreboot - Open braces must be escaped in regex
Elyes Haouas26e0b942022-05-22 11:11:11 +02004925 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 \{/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004926 }
4927 }
4928
4929## # check for blank lines before declarations
4930## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4931## $prevrawline =~ /^.\s*$/) {
4932## WARN("SPACING",
4933## "No blank lines before declarations\n" . $hereprev);
4934## }
4935##
4936
4937# closing brace should have a space following it when it has anything
4938# on the line
Elyes Haouas26e0b942022-05-22 11:11:11 +02004939 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004940 if (ERROR("SPACING",
4941 "space required after that close brace '}'\n" . $herecurr) &&
4942 $fix) {
4943 $fixed[$fixlinenr] =~
4944 s/}((?!(?:,|;|\)))\S)/} $1/;
4945 }
4946 }
4947
4948# check spacing on square brackets
4949 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4950 if (ERROR("SPACING",
4951 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4952 $fix) {
4953 $fixed[$fixlinenr] =~
4954 s/\[\s+/\[/;
4955 }
4956 }
4957 if ($line =~ /\s\]/) {
4958 if (ERROR("SPACING",
4959 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4960 $fix) {
4961 $fixed[$fixlinenr] =~
4962 s/\s+\]/\]/;
4963 }
4964 }
4965
4966# check spacing on parentheses
4967 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4968 $line !~ /for\s*\(\s+;/) {
4969 if (ERROR("SPACING",
4970 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4971 $fix) {
4972 $fixed[$fixlinenr] =~
4973 s/\(\s+/\(/;
4974 }
4975 }
4976 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4977 $line !~ /for\s*\(.*;\s+\)/ &&
4978 $line !~ /:\s+\)/) {
4979 if (ERROR("SPACING",
4980 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4981 $fix) {
4982 $fixed[$fixlinenr] =~
4983 s/\s+\)/\)/;
4984 }
4985 }
4986
4987# check unnecessary parentheses around addressof/dereference single $Lvals
4988# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4989
4990 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4991 my $var = $1;
4992 if (CHK("UNNECESSARY_PARENTHESES",
4993 "Unnecessary parentheses around $var\n" . $herecurr) &&
4994 $fix) {
4995 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4996 }
4997 }
4998
4999# check for unnecessary parentheses around function pointer uses
5000# ie: (foo->bar)(); should be foo->bar();
5001# but not "if (foo->bar) (" to avoid some false positives
5002 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5003 my $var = $2;
5004 if (CHK("UNNECESSARY_PARENTHESES",
5005 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5006 $fix) {
5007 my $var2 = deparenthesize($var);
5008 $var2 =~ s/\s//g;
5009 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5010 }
5011 }
5012
Martin Roth387dec82017-09-17 19:20:46 -06005013# check for unnecessary parentheses around comparisons in if uses
Martin Roth60915b32018-08-10 21:04:05 -06005014# when !drivers/staging or command-line uses --strict
5015 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005016 $perl_version_ok && defined($stat) &&
Martin Roth387dec82017-09-17 19:20:46 -06005017 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5018 my $if_stat = $1;
5019 my $test = substr($2, 1, -1);
5020 my $herectx;
5021 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5022 my $match = $1;
5023 # avoid parentheses around potential macro args
5024 next if ($match =~ /^\s*\w+\s*$/);
5025 if (!defined($herectx)) {
5026 $herectx = $here . "\n";
5027 my $cnt = statement_rawlines($if_stat);
5028 for (my $n = 0; $n < $cnt; $n++) {
5029 my $rl = raw_line($linenr, $n);
5030 $herectx .= $rl . "\n";
5031 last if $rl =~ /^[ \+].*\{/;
5032 }
5033 }
5034 CHK("UNNECESSARY_PARENTHESES",
5035 "Unnecessary parentheses around '$match'\n" . $herectx);
5036 }
5037 }
5038
Elyes Haouas26e0b942022-05-22 11:11:11 +02005039# check that goto labels aren't indented (allow a single space indentation)
5040# and ignore bitfield definitions like foo:1
5041# Strictly, labels can have whitespace after the identifier and before the :
5042# but this is not allowed here as many ?: uses would appear to be labels
5043 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5044 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5045 $sline !~ /^.\s+default:/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005046 if (WARN("INDENTED_LABEL",
5047 "labels should not be indented\n" . $herecurr) &&
5048 $fix) {
5049 $fixed[$fixlinenr] =~
5050 s/^(.)\s+/$1/;
5051 }
5052 }
5053
Elyes Haouas50eef652022-07-13 18:07:58 +02005054# check if a statement with a comma should be two statements like:
5055# foo = bar(), /* comma should be semicolon */
5056# bar = baz();
5057 if (defined($stat) &&
5058 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5059 my $cnt = statement_rawlines($stat);
5060 my $herectx = get_stat_here($linenr, $cnt, $here);
5061 WARN("SUSPECT_COMMA_SEMICOLON",
5062 "Possible comma where semicolon could be used\n" . $herectx);
5063 }
5064
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005065# return is not a function
5066 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5067 my $spacing = $1;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005068 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005069 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5070 my $value = $1;
5071 $value = deparenthesize($value);
5072 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5073 ERROR("RETURN_PARENTHESES",
5074 "return is not a function, parentheses are not required\n" . $herecurr);
5075 }
5076 } elsif ($spacing !~ /\s+/) {
5077 ERROR("SPACING",
5078 "space required before the open parenthesis '('\n" . $herecurr);
5079 }
5080 }
5081
5082# unnecessary return in a void function
5083# at end-of-function, with the previous line a single leading tab, then return;
5084# and the line before that not a goto label target like "out:"
5085 if ($sline =~ /^[ \+]}\s*$/ &&
5086 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5087 $linenr >= 3 &&
5088 $lines[$linenr - 3] =~ /^[ +]/ &&
5089 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5090 WARN("RETURN_VOID",
5091 "void function return statements are not generally useful\n" . $hereprev);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005092 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005093
5094# if statements using unnecessary parentheses - ie: if ((foo == bar))
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005095 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005096 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5097 my $openparens = $1;
5098 my $count = $openparens =~ tr@\(@\(@;
5099 my $msg = "";
5100 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5101 my $comp = $4; #Not $1 because of $LvalOrFunc
5102 $msg = " - maybe == should be = ?" if ($comp eq "==");
5103 WARN("UNNECESSARY_PARENTHESES",
5104 "Unnecessary parentheses$msg\n" . $herecurr);
5105 }
5106 }
5107
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005108# comparisons with a constant or upper case identifier on the left
5109# avoid cases like "foo + BAR < baz"
5110# only fix matches surrounded by parentheses to avoid incorrect
5111# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005112 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005113 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5114 my $lead = $1;
5115 my $const = $2;
5116 my $comp = $3;
5117 my $to = $4;
5118 my $newcomp = $comp;
5119 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5120 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5121 WARN("CONSTANT_COMPARISON",
5122 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5123 $fix) {
5124 if ($comp eq "<") {
5125 $newcomp = ">";
5126 } elsif ($comp eq "<=") {
5127 $newcomp = ">=";
5128 } elsif ($comp eq ">") {
5129 $newcomp = "<";
5130 } elsif ($comp eq ">=") {
5131 $newcomp = "<=";
5132 }
5133 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5134 }
5135 }
5136
5137# Return of what appears to be an errno should normally be negative
5138 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005139 my $name = $1;
5140 if ($name ne 'EOF' && $name ne 'ERROR') {
5141 WARN("USE_NEGATIVE_ERRNO",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005142 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005143 }
5144 }
5145
5146# Need a space before open parenthesis after if, while etc
5147 if ($line =~ /\b(if|while|for|switch)\(/) {
5148 if (ERROR("SPACING",
5149 "space required before the open parenthesis '('\n" . $herecurr) &&
5150 $fix) {
5151 $fixed[$fixlinenr] =~
5152 s/\b(if|while|for|switch)\(/$1 \(/;
5153 }
5154 }
5155
5156# Check for illegal assignment in if conditional -- and check for trailing
5157# statements after the conditional.
5158 if ($line =~ /do\s*(?!{)/) {
5159 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5160 ctx_statement_block($linenr, $realcnt, 0)
5161 if (!defined $stat);
5162 my ($stat_next) = ctx_statement_block($line_nr_next,
5163 $remain_next, $off_next);
5164 $stat_next =~ s/\n./\n /g;
5165 ##print "stat<$stat> stat_next<$stat_next>\n";
5166
5167 if ($stat_next =~ /^\s*while\b/) {
5168 # If the statement carries leading newlines,
5169 # then count those as offsets.
5170 my ($whitespace) =
5171 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5172 my $offset =
5173 statement_rawlines($whitespace) - 1;
5174
5175 $suppress_whiletrailers{$line_nr_next +
5176 $offset} = 1;
5177 }
5178 }
5179 if (!defined $suppress_whiletrailers{$linenr} &&
5180 defined($stat) && defined($cond) &&
5181 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5182 my ($s, $c) = ($stat, $cond);
5183
5184 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5185 ERROR("ASSIGN_IN_IF",
5186 "do not use assignment in if condition\n" . $herecurr);
5187 }
5188
5189 # Find out what is on the end of the line after the
5190 # conditional.
5191 substr($s, 0, length($c), '');
5192 $s =~ s/\n.*//g;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005193 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005194 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5195 $c !~ /}\s*while\s*/)
5196 {
5197 # Find out how long the conditional actually is.
5198 my @newlines = ($c =~ /\n/gs);
5199 my $cond_lines = 1 + $#newlines;
5200 my $stat_real = '';
5201
5202 $stat_real = raw_line($linenr, $cond_lines)
5203 . "\n" if ($cond_lines);
5204 if (defined($stat_real) && $cond_lines > 1) {
5205 $stat_real = "[...]\n$stat_real";
5206 }
5207
5208 ERROR("TRAILING_STATEMENTS",
5209 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5210 }
5211 }
5212
5213# Check for bitwise tests written as boolean
5214 if ($line =~ /
5215 (?:
5216 (?:\[|\(|\&\&|\|\|)
5217 \s*0[xX][0-9]+\s*
5218 (?:\&\&|\|\|)
5219 |
5220 (?:\&\&|\|\|)
5221 \s*0[xX][0-9]+\s*
5222 (?:\&\&|\|\||\)|\])
5223 )/x)
5224 {
5225 WARN("HEXADECIMAL_BOOLEAN_TEST",
5226 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5227 }
5228
5229# if and else should not have general statements after it
5230 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5231 my $s = $1;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005232 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005233 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5234 ERROR("TRAILING_STATEMENTS",
5235 "trailing statements should be on next line\n" . $herecurr);
5236 }
5237 }
5238# if should not continue a brace
5239 if ($line =~ /}\s*if\b/) {
5240 ERROR("TRAILING_STATEMENTS",
5241 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5242 $herecurr);
5243 }
5244# case and default should not have general statements after them
5245 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5246 $line !~ /\G(?:
5247 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5248 \s*return\s+
5249 )/xg)
5250 {
5251 ERROR("TRAILING_STATEMENTS",
5252 "trailing statements should be on next line\n" . $herecurr);
5253 }
5254
5255 # Check for }<nl>else {, these must be at the same
5256 # indent level to be relevant to each other.
5257 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5258 $previndent == $indent) {
5259 if (ERROR("ELSE_AFTER_BRACE",
5260 "else should follow close brace '}'\n" . $hereprev) &&
5261 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5262 fix_delete_line($fixlinenr - 1, $prevrawline);
5263 fix_delete_line($fixlinenr, $rawline);
5264 my $fixedline = $prevrawline;
5265 $fixedline =~ s/}\s*$//;
5266 if ($fixedline !~ /^\+\s*$/) {
5267 fix_insert_line($fixlinenr, $fixedline);
5268 }
5269 $fixedline = $rawline;
5270 $fixedline =~ s/^(.\s*)else/$1} else/;
5271 fix_insert_line($fixlinenr, $fixedline);
5272 }
5273 }
5274
5275 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5276 $previndent == $indent) {
5277 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5278
5279 # Find out what is on the end of the line after the
5280 # conditional.
5281 substr($s, 0, length($c), '');
5282 $s =~ s/\n.*//g;
5283
5284 if ($s =~ /^\s*;/) {
5285 if (ERROR("WHILE_AFTER_BRACE",
5286 "while should follow close brace '}'\n" . $hereprev) &&
5287 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5288 fix_delete_line($fixlinenr - 1, $prevrawline);
5289 fix_delete_line($fixlinenr, $rawline);
5290 my $fixedline = $prevrawline;
5291 my $trailing = $rawline;
5292 $trailing =~ s/^\+//;
5293 $trailing = trim($trailing);
5294 $fixedline =~ s/}\s*$/} $trailing/;
5295 fix_insert_line($fixlinenr, $fixedline);
5296 }
5297 }
5298 }
5299
5300#Specific variable tests
5301 while ($line =~ m{($Constant|$Lval)}g) {
5302 my $var = $1;
5303
5304#gcc binary extension
5305 if ($var =~ /^$Binary$/) {
5306 if (WARN("GCC_BINARY_CONSTANT",
5307 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
5308 $fix) {
5309 my $hexval = sprintf("0x%x", oct($var));
5310 $fixed[$fixlinenr] =~
5311 s/\b$var\b/$hexval/;
5312 }
5313 }
5314
5315#CamelCase
5316 if ($var !~ /^$Constant$/ &&
5317 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5318#Ignore Page<foo> variants
5319 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02005320#Ignore SI style variants like nS, mV and dB
5321#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5322 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005323#Ignore some three character SI units explicitly, like MiB and KHz
5324 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
Elyes Haouas0d42db62022-09-05 11:24:00 +02005325 while ($var =~ m{\b($Ident)}g) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005326 my $word = $1;
5327 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5328 if ($check) {
5329 seed_camelcase_includes();
5330 if (!$file && !$camelcase_file_seeded) {
5331 seed_camelcase_file($realfile);
5332 $camelcase_file_seeded = 1;
5333 }
5334 }
5335 if (!defined $camelcase{$word}) {
5336 $camelcase{$word} = 1;
5337 CHK("CAMELCASE",
5338 "Avoid CamelCase: <$word>\n" . $herecurr);
5339 }
5340 }
5341 }
5342 }
5343
5344#no spaces allowed after \ in define
5345 if ($line =~ /\#\s*define.*\\\s+$/) {
5346 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5347 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5348 $fix) {
5349 $fixed[$fixlinenr] =~ s/\s+$//;
5350 }
5351 }
5352
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005353# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5354# itself <asm/foo.h> (uses RAW line)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005355 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5356 my $file = "$1.h";
5357 my $checkfile = "include/linux/$file";
5358 if (-f "$root/$checkfile" &&
5359 $realfile ne $checkfile &&
5360 $1 !~ /$allowed_asm_includes/)
5361 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005362 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5363 if ($asminclude > 0) {
5364 if ($realfile =~ m{^arch/}) {
5365 CHK("ARCH_INCLUDE_LINUX",
5366 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5367 } else {
5368 WARN("INCLUDE_LINUX",
5369 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5370 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005371 }
5372 }
5373 }
5374
5375# multi-statement macros should be enclosed in a do while loop, grab the
5376# first statement and ensure its the whole macro if its not enclosed
5377# in a known good container
5378 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5379 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5380 my $ln = $linenr;
5381 my $cnt = $realcnt;
5382 my ($off, $dstat, $dcond, $rest);
5383 my $ctx = '';
5384 my $has_flow_statement = 0;
5385 my $has_arg_concat = 0;
5386 ($dstat, $dcond, $ln, $cnt, $off) =
5387 ctx_statement_block($linenr, $realcnt, 0);
5388 $ctx = $dstat;
5389 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5390 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5391
5392 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005393 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005394
Martin Rothedd591d2017-03-14 10:16:29 -06005395 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5396 my $define_args = $1;
5397 my $define_stmt = $dstat;
5398 my @def_args = ();
5399
5400 if (defined $define_args && $define_args ne "") {
5401 $define_args = substr($define_args, 1, length($define_args) - 2);
5402 $define_args =~ s/\s*//g;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005403 $define_args =~ s/\\\+?//g;
Martin Rothedd591d2017-03-14 10:16:29 -06005404 @def_args = split(",", $define_args);
5405 }
5406
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005407 $dstat =~ s/$;//g;
5408 $dstat =~ s/\\\n.//g;
5409 $dstat =~ s/^\s*//s;
5410 $dstat =~ s/\s*$//s;
5411
5412 # Flatten any parentheses and braces
Elyes Haouas26e0b942022-05-22 11:11:11 +02005413 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5414 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5415 $dstat =~ s/.\[[^\[\]]*\]/1u/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005416 {
5417 }
5418
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005419 # Flatten any obvious string concatenation.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005420 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5421 $dstat =~ s/$Ident\s*($String)/$1/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005422 {
5423 }
5424
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005425 # Make asm volatile uses seem like a generic function
5426 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5427
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005428 my $exceptions = qr{
5429 $Declare|
5430 module_param_named|
5431 MODULE_PARM_DESC|
5432 DECLARE_PER_CPU|
5433 DEFINE_PER_CPU|
5434 __typeof__\(|
5435 union|
5436 struct|
5437 \.$Ident\s*=\s*|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005438 ^\"|\"$|
5439 ^\[
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005440 }x;
5441 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
Martin Rothedd591d2017-03-14 10:16:29 -06005442
5443 $ctx =~ s/\n*$//;
Martin Rothedd591d2017-03-14 10:16:29 -06005444 my $stmt_cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005445 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
Martin Rothedd591d2017-03-14 10:16:29 -06005446
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005447 if ($dstat ne '' &&
5448 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5449 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5450 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5451 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5452 $dstat !~ /$exceptions/ &&
5453 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5454 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5455 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
Elyes Haouas26e0b942022-05-22 11:11:11 +02005456 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005457 $dstat !~ /^for\s*$Constant$/ && # for (...)
5458 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
Martin Rothedd591d2017-03-14 10:16:29 -06005459 $dstat !~ /^do\s*{/ && # do {...
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005460 $dstat !~ /^\(\{/ && # ({...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005461 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5462 {
Martin Roth387dec82017-09-17 19:20:46 -06005463 if ($dstat =~ /^\s*if\b/) {
5464 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5465 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5466 } elsif ($dstat =~ /;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005467 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5468 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5469 } else {
5470 ERROR("COMPLEX_MACRO",
5471 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5472 }
Martin Rothedd591d2017-03-14 10:16:29 -06005473
5474 }
5475
5476 # Make $define_stmt single line, comment-free, etc
5477 my @stmt_array = split('\n', $define_stmt);
5478 my $first = 1;
5479 $define_stmt = "";
5480 foreach my $l (@stmt_array) {
5481 $l =~ s/\\$//;
5482 if ($first) {
5483 $define_stmt = $l;
5484 $first = 0;
5485 } elsif ($l =~ /^[\+ ]/) {
5486 $define_stmt .= substr($l, 1);
5487 }
5488 }
5489 $define_stmt =~ s/$;//g;
5490 $define_stmt =~ s/\s+/ /g;
5491 $define_stmt = trim($define_stmt);
5492
5493# check if any macro arguments are reused (ignore '...' and 'type')
5494 foreach my $arg (@def_args) {
5495 next if ($arg =~ /\.\.\./);
5496 next if ($arg =~ /^type$/i);
Martin Roth387dec82017-09-17 19:20:46 -06005497 my $tmp_stmt = $define_stmt;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005498 $tmp_stmt =~ s/\b(__must_be_array|offsetof|sizeof|sizeof_field|__stringify|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
Martin Roth387dec82017-09-17 19:20:46 -06005499 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5500 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
Martin Roth60915b32018-08-10 21:04:05 -06005501 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005502 if ($use_cnt > 1) {
5503 CHK("MACRO_ARG_REUSE",
5504 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5505 }
5506# check if any macro arguments may have other precedence issues
Martin Roth387dec82017-09-17 19:20:46 -06005507 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
Martin Rothedd591d2017-03-14 10:16:29 -06005508 ((defined($1) && $1 ne ',') ||
5509 (defined($2) && $2 ne ','))) {
5510 CHK("MACRO_ARG_PRECEDENCE",
5511 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5512 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005513 }
5514
5515# check for macros with flow control, but without ## concatenation
5516# ## concatenation is commonly a macro that defines a function so ignore those
5517 if ($has_flow_statement && !$has_arg_concat) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005518 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005519 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005520
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005521 WARN("MACRO_WITH_FLOW_CONTROL",
5522 "Macros with flow control statements should be avoided\n" . "$herectx");
5523 }
5524
5525# check for line continuations outside of #defines, preprocessor #, and asm
5526
5527 } else {
5528 if ($prevline !~ /^..*\\$/ &&
5529 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5530 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5531 $line =~ /^\+.*\\$/) {
5532 WARN("LINE_CONTINUATIONS",
5533 "Avoid unnecessary line continuations\n" . $herecurr);
5534 }
5535 }
5536
5537# do {} while (0) macro tests:
5538# single-statement macros do not need to be enclosed in do while (0) loop,
5539# macro should not end with a semicolon
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005540 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005541 $realfile !~ m@/vmlinux.lds.h$@ &&
5542 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5543 my $ln = $linenr;
5544 my $cnt = $realcnt;
5545 my ($off, $dstat, $dcond, $rest);
5546 my $ctx = '';
5547 ($dstat, $dcond, $ln, $cnt, $off) =
5548 ctx_statement_block($linenr, $realcnt, 0);
5549 $ctx = $dstat;
5550
5551 $dstat =~ s/\\\n.//g;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005552 $dstat =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005553
5554 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5555 my $stmts = $2;
5556 my $semis = $3;
5557
5558 $ctx =~ s/\n*$//;
5559 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005560 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005561
5562 if (($stmts =~ tr/;/;/) == 1 &&
5563 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5564 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5565 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5566 }
5567 if (defined $semis && $semis ne "") {
5568 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5569 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5570 }
5571 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5572 $ctx =~ s/\n*$//;
5573 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005574 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005575
5576 WARN("TRAILING_SEMICOLON",
5577 "macros should not use a trailing semicolon\n" . "$herectx");
5578 }
5579 }
5580
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005581# check for redundant bracing round if etc
5582 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5583 my ($level, $endln, @chunks) =
5584 ctx_statement_full($linenr, $realcnt, 1);
5585 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5586 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5587 if ($#chunks > 0 && $level == 0) {
5588 my @allowed = ();
5589 my $allow = 0;
5590 my $seen = 0;
5591 my $herectx = $here . "\n";
5592 my $ln = $linenr - 1;
5593 for my $chunk (@chunks) {
5594 my ($cond, $block) = @{$chunk};
5595
5596 # If the condition carries leading newlines, then count those as offsets.
5597 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5598 my $offset = statement_rawlines($whitespace) - 1;
5599
5600 $allowed[$allow] = 0;
5601 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5602
5603 # We have looked at and allowed this specific line.
5604 $suppress_ifbraces{$ln + $offset} = 1;
5605
5606 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5607 $ln += statement_rawlines($block) - 1;
5608
5609 substr($block, 0, length($cond), '');
5610
5611 $seen++ if ($block =~ /^\s*{/);
5612
5613 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5614 if (statement_lines($cond) > 1) {
5615 #print "APW: ALLOWED: cond<$cond>\n";
5616 $allowed[$allow] = 1;
5617 }
5618 if ($block =~/\b(?:if|for|while)\b/) {
5619 #print "APW: ALLOWED: block<$block>\n";
5620 $allowed[$allow] = 1;
5621 }
5622 if (statement_block_size($block) > 1) {
5623 #print "APW: ALLOWED: lines block<$block>\n";
5624 $allowed[$allow] = 1;
5625 }
5626 $allow++;
5627 }
5628 if ($seen) {
5629 my $sum_allowed = 0;
5630 foreach (@allowed) {
5631 $sum_allowed += $_;
5632 }
5633 if ($sum_allowed == 0) {
Martin Roth57f11622023-03-06 11:18:25 -07005634 # coreboot has decided to allow braces around single line statement blocks
5635 #WARN("BRACES",
5636 # "braces {} are not necessary for any arm of this statement\n" . $herectx);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005637 } elsif ($sum_allowed != $allow &&
5638 $seen != $allow) {
5639 CHK("BRACES",
5640 "braces {} should be used on all arms of this statement\n" . $herectx);
5641 }
5642 }
5643 }
5644 }
5645 if (!defined $suppress_ifbraces{$linenr - 1} &&
5646 $line =~ /\b(if|while|for|else)\b/) {
5647 my $allowed = 0;
5648
5649 # Check the pre-context.
5650 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5651 #print "APW: ALLOWED: pre<$1>\n";
5652 $allowed = 1;
5653 }
5654
5655 my ($level, $endln, @chunks) =
5656 ctx_statement_full($linenr, $realcnt, $-[0]);
5657
5658 # Check the condition.
5659 my ($cond, $block) = @{$chunks[0]};
5660 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5661 if (defined $cond) {
5662 substr($block, 0, length($cond), '');
5663 }
5664 if (statement_lines($cond) > 1) {
5665 #print "APW: ALLOWED: cond<$cond>\n";
5666 $allowed = 1;
5667 }
5668 if ($block =~/\b(?:if|for|while)\b/) {
5669 #print "APW: ALLOWED: block<$block>\n";
5670 $allowed = 1;
5671 }
5672 if (statement_block_size($block) > 1) {
5673 #print "APW: ALLOWED: lines block<$block>\n";
5674 $allowed = 1;
5675 }
5676 # Check the post-context.
5677 if (defined $chunks[1]) {
5678 my ($cond, $block) = @{$chunks[1]};
5679 if (defined $cond) {
5680 substr($block, 0, length($cond), '');
5681 }
5682 if ($block =~ /^\s*\{/) {
5683 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5684 $allowed = 1;
5685 }
5686 }
Martin Roth57f11622023-03-06 11:18:25 -07005687 # coreboot has decided to allow braces around single line statement blocks
5688 #if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5689 # my $cnt = statement_rawlines($block);
5690 # my $herectx = get_stat_here($linenr, $cnt, $here);
5691 #
5692 # WARN("BRACES",
5693 # "braces {} are not necessary for single statement blocks\n" . $herectx);
5694 #}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005695 }
5696
Martin Rothedd591d2017-03-14 10:16:29 -06005697# check for single line unbalanced braces
5698 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5699 $sline =~ /^.\s*else\s*\{\s*$/) {
5700 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5701 }
5702
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005703# check for unnecessary blank lines around braces
5704 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005705 if (CHK("BRACES",
5706 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5707 $fix && $prevrawline =~ /^\+/) {
5708 fix_delete_line($fixlinenr - 1, $prevrawline);
5709 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005710 }
5711 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005712 if (CHK("BRACES",
5713 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5714 $fix) {
5715 fix_delete_line($fixlinenr, $rawline);
5716 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005717 }
5718
5719# no volatiles please
5720 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5721 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5722 WARN("VOLATILE",
Martin Rothedd591d2017-03-14 10:16:29 -06005723 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005724 }
5725
5726# Check for user-visible strings broken across lines, which breaks the ability
5727# to grep for the string. Make exceptions when the previous string ends in a
5728# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5729# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005730 if ($line =~ /^\+\s*$String/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005731 $prevline =~ /"\s*$/ &&
5732 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5733 if (WARN("SPLIT_STRING",
5734 "quoted string split across lines\n" . $hereprev) &&
5735 $fix &&
5736 $prevrawline =~ /^\+.*"\s*$/ &&
5737 $last_coalesced_string_linenr != $linenr - 1) {
5738 my $extracted_string = get_quoted_string($line, $rawline);
5739 my $comma_close = "";
5740 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5741 $comma_close = $1;
5742 }
5743
5744 fix_delete_line($fixlinenr - 1, $prevrawline);
5745 fix_delete_line($fixlinenr, $rawline);
5746 my $fixedline = $prevrawline;
5747 $fixedline =~ s/"\s*$//;
5748 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5749 fix_insert_line($fixlinenr - 1, $fixedline);
5750 $fixedline = $rawline;
5751 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5752 if ($fixedline !~ /\+\s*$/) {
5753 fix_insert_line($fixlinenr, $fixedline);
5754 }
5755 $last_coalesced_string_linenr = $linenr;
5756 }
5757 }
5758
5759# check for missing a space in a string concatenation
5760 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5761 WARN('MISSING_SPACE',
5762 "break quoted strings at a space character\n" . $hereprev);
5763 }
5764
Martin Roth387dec82017-09-17 19:20:46 -06005765# check for an embedded function name in a string when the function is known
5766# This does not work very well for -f --file checking as it depends on patch
5767# context providing the function name or a single line form for in-file
5768# function declarations
Martin Rothedd591d2017-03-14 10:16:29 -06005769 if ($line =~ /^\+.*$String/ &&
5770 defined($context_function) &&
Martin Roth387dec82017-09-17 19:20:46 -06005771 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5772 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
Martin Rothedd591d2017-03-14 10:16:29 -06005773 WARN("EMBEDDED_FUNCTION_NAME",
Martin Roth387dec82017-09-17 19:20:46 -06005774 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
Martin Rothedd591d2017-03-14 10:16:29 -06005775 }
5776
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005777# check for spaces before a quoted newline
5778 if ($rawline =~ /^.*\".*\s\\n/) {
5779 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5780 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5781 $fix) {
5782 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5783 }
5784
5785 }
5786
5787# concatenated string without spaces between elements
Elyes Haouas71bfcf52022-07-13 16:51:20 +02005788 if ($line =~ /$String[A-Z_]/ ||
5789 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
5790 if (CHK("CONCATENATED_STRING",
5791 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5792 $fix) {
5793 while ($line =~ /($String)/g) {
5794 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5795 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5796 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5797 }
5798 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005799 }
5800
5801# uncoalesced string fragments
Elyes Haouase235a0d2022-07-13 16:52:48 +02005802 if ($line =~ /$String\s*[Lu]?"/) {
5803 if (WARN("STRING_FRAGMENTS",
5804 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5805 $fix) {
5806 while ($line =~ /($String)(?=\s*")/g) {
5807 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5808 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5809 }
5810 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005811 }
5812
Martin Rothedd591d2017-03-14 10:16:29 -06005813# check for non-standard and hex prefixed decimal printf formats
5814 my $show_L = 1; #don't show the same defect twice
5815 my $show_Z = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005816 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
Martin Rothedd591d2017-03-14 10:16:29 -06005817 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005818 $string =~ s/%%/__/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005819 # check for %L
5820 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005821 WARN("PRINTF_L",
Martin Rothedd591d2017-03-14 10:16:29 -06005822 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5823 $show_L = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005824 }
Martin Rothedd591d2017-03-14 10:16:29 -06005825 # check for %Z
5826 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5827 WARN("PRINTF_Z",
5828 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5829 $show_Z = 0;
5830 }
5831 # check for 0x<decimal>
5832 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5833 ERROR("PRINTF_0XDECIMAL",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005834 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5835 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005836 }
5837
5838# check for line continuations in quoted strings with odd counts of "
Martin Roth60915b32018-08-10 21:04:05 -06005839 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005840 WARN("LINE_CONTINUATIONS",
5841 "Avoid line continuations in quoted strings\n" . $herecurr);
5842 }
5843
5844# warn about #if 0
5845 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02005846 WARN("IF_0",
5847 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5848 }
5849
5850# warn about #if 1
5851 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5852 WARN("IF_1",
5853 "Consider removing the #if 1 and its #endif\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005854 }
5855
5856# check for needless "if (<foo>) fn(<foo>)" uses
5857 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005858 my $tested = quotemeta($1);
5859 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5860 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5861 my $func = $1;
5862 if (WARN('NEEDLESS_IF',
5863 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5864 $fix) {
5865 my $do_fix = 1;
5866 my $leading_tabs = "";
5867 my $new_leading_tabs = "";
5868 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5869 $leading_tabs = $1;
5870 } else {
5871 $do_fix = 0;
5872 }
5873 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5874 $new_leading_tabs = $1;
5875 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5876 $do_fix = 0;
5877 }
5878 } else {
5879 $do_fix = 0;
5880 }
5881 if ($do_fix) {
5882 fix_delete_line($fixlinenr - 1, $prevrawline);
5883 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5884 }
5885 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005886 }
5887 }
5888
5889# check for unnecessary "Out of Memory" messages
5890 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5891 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5892 (defined $1 || defined $3) &&
5893 $linenr > 3) {
5894 my $testval = $2;
5895 my $testline = $lines[$linenr - 3];
5896
5897 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5898# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5899
Elyes Haouasa7b0d382022-05-23 18:33:15 +02005900 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5901 $s !~ /\b__GFP_NOWARN\b/ ) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005902 WARN("OOM_MESSAGE",
5903 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5904 }
5905 }
5906
5907# check for logging functions with KERN_<LEVEL>
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005908 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005909 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5910 my $level = $1;
5911 if (WARN("UNNECESSARY_KERN_LEVEL",
5912 "Possible unnecessary $level\n" . $herecurr) &&
5913 $fix) {
5914 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5915 }
5916 }
5917
Martin Rothedd591d2017-03-14 10:16:29 -06005918# check for logging continuations
5919 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5920 WARN("LOGGING_CONTINUATION",
5921 "Avoid logging continuation uses where feasible\n" . $herecurr);
5922 }
5923
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005924# check for mask then right shift without a parentheses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005925 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005926 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5927 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5928 WARN("MASK_THEN_SHIFT",
5929 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5930 }
5931
5932# check for pointer comparisons to NULL
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005933 if ($perl_version_ok) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005934 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5935 my $val = $1;
5936 my $equal = "!";
5937 $equal = "" if ($4 eq "!=");
5938 if (CHK("COMPARISON_TO_NULL",
5939 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5940 $fix) {
5941 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5942 }
5943 }
5944 }
5945
5946# check for bad placement of section $InitAttribute (e.g.: __initdata)
5947 if ($line =~ /(\b$InitAttribute\b)/) {
5948 my $attr = $1;
5949 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5950 my $ptr = $1;
5951 my $var = $2;
5952 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5953 ERROR("MISPLACED_INIT",
5954 "$attr should be placed after $var\n" . $herecurr)) ||
5955 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5956 WARN("MISPLACED_INIT",
5957 "$attr should be placed after $var\n" . $herecurr))) &&
5958 $fix) {
5959 $fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
5960 }
5961 }
5962 }
5963
5964# check for $InitAttributeData (ie: __initdata) with const
5965 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5966 my $attr = $1;
5967 $attr =~ /($InitAttributePrefix)(.*)/;
5968 my $attr_prefix = $1;
5969 my $attr_type = $2;
5970 if (ERROR("INIT_ATTRIBUTE",
5971 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5972 $fix) {
5973 $fixed[$fixlinenr] =~
5974 s/$InitAttributeData/${attr_prefix}initconst/;
5975 }
5976 }
5977
5978# check for $InitAttributeConst (ie: __initconst) without const
5979 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5980 my $attr = $1;
5981 if (ERROR("INIT_ATTRIBUTE",
5982 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5983 $fix) {
5984 my $lead = $fixed[$fixlinenr] =~
5985 /(^\+\s*(?:static\s+))/;
5986 $lead = rtrim($1);
5987 $lead = "$lead " if ($lead !~ /^\+$/);
5988 $lead = "${lead}const ";
5989 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5990 }
5991 }
5992
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005993# check for __read_mostly with const non-pointer (should just be const)
5994 if ($line =~ /\b__read_mostly\b/ &&
5995 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5996 if (ERROR("CONST_READ_MOSTLY",
5997 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5998 $fix) {
5999 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6000 }
6001 }
6002
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006003# don't use __constant_<foo> functions outside of include/uapi/
6004 if ($realfile !~ m@^include/uapi/@ &&
6005 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6006 my $constant_func = $1;
6007 my $func = $constant_func;
6008 $func =~ s/^__constant_//;
6009 if (WARN("CONSTANT_CONVERSION",
6010 "$constant_func should be $func\n" . $herecurr) &&
6011 $fix) {
6012 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6013 }
6014 }
6015
6016# prefer usleep_range over udelay
6017 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6018 my $delay = $1;
6019 # ignore udelay's < 10, however
6020 if (! ($delay < 10) ) {
6021 CHK("USLEEP_RANGE",
6022 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
6023 }
6024 if ($delay > 2000) {
6025 WARN("LONG_UDELAY",
6026 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6027 }
6028 }
6029
6030# warn about unexpectedly long msleep's
6031 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6032 if ($1 < 20) {
6033 WARN("MSLEEP",
6034 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
6035 }
6036 }
6037
6038# check for comparisons of jiffies
6039 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6040 WARN("JIFFIES_COMPARISON",
6041 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6042 }
6043
6044# check for comparisons of get_jiffies_64()
6045 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6046 WARN("JIFFIES_COMPARISON",
6047 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6048 }
6049
6050# warn about #ifdefs in C files
6051# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6052# print "#ifdef in C files should be avoided\n";
6053# print "$herecurr";
6054# $clean = 0;
6055# }
6056
6057# warn about spacing in #ifdefs
6058 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6059 if (ERROR("SPACING",
6060 "exactly one space required after that #$1\n" . $herecurr) &&
6061 $fix) {
6062 $fixed[$fixlinenr] =~
6063 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6064 }
6065
6066 }
6067
6068# check for spinlock_t definitions without a comment.
6069 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6070 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6071 my $which = $1;
6072 if (!ctx_has_comment($first_line, $linenr)) {
6073 CHK("UNCOMMENTED_DEFINITION",
6074 "$1 definition without comment\n" . $herecurr);
6075 }
6076 }
6077# check for memory barriers without a comment.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006078
6079 my $barriers = qr{
6080 mb|
6081 rmb|
Elyes Haouas26e0b942022-05-22 11:11:11 +02006082 wmb
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006083 }x;
6084 my $barrier_stems = qr{
6085 mb__before_atomic|
6086 mb__after_atomic|
6087 store_release|
6088 load_acquire|
6089 store_mb|
6090 (?:$barriers)
6091 }x;
6092 my $all_barriers = qr{
6093 (?:$barriers)|
6094 smp_(?:$barrier_stems)|
6095 virt_(?:$barrier_stems)
6096 }x;
6097
6098 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006099 if (!ctx_has_comment($first_line, $linenr)) {
6100 WARN("MEMORY_BARRIER",
6101 "memory barrier without comment\n" . $herecurr);
6102 }
6103 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006104
6105 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6106
6107 if ($realfile !~ m@^include/asm-generic/@ &&
6108 $realfile !~ m@/barrier\.h$@ &&
6109 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6110 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6111 WARN("MEMORY_BARRIER",
6112 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6113 }
6114
6115# check for waitqueue_active without a comment.
6116 if ($line =~ /\bwaitqueue_active\s*\(/) {
6117 if (!ctx_has_comment($first_line, $linenr)) {
6118 WARN("WAITQUEUE_ACTIVE",
6119 "waitqueue_active without comment\n" . $herecurr);
6120 }
6121 }
6122
Elyes Haouas26e0b942022-05-22 11:11:11 +02006123# check for data_race without a comment.
6124 if ($line =~ /\bdata_race\s*\(/) {
6125 if (!ctx_has_comment($first_line, $linenr)) {
6126 WARN("DATA_RACE",
6127 "data_race without comment\n" . $herecurr);
6128 }
Martin Roth60915b32018-08-10 21:04:05 -06006129 }
6130
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006131# check of hardware specific defines
6132 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6133 CHK("ARCH_DEFINES",
6134 "architecture specific defines should be avoided\n" . $herecurr);
6135 }
6136
Martin Roth387dec82017-09-17 19:20:46 -06006137# check that the storage class is not after a type
6138 if ($line =~ /\b($Type)\s+($Storage)\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006139 WARN("STORAGE_CLASS",
Martin Roth387dec82017-09-17 19:20:46 -06006140 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6141 }
6142# Check that the storage class is at the beginning of a declaration
6143 if ($line =~ /\b$Storage\b/ &&
6144 $line !~ /^.\s*$Storage/ &&
6145 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6146 $1 !~ /[\,\)]\s*$/) {
6147 WARN("STORAGE_CLASS",
6148 "storage class should be at the beginning of the declaration\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006149 }
6150
6151# check the location of the inline attribute, that it is between
6152# storage class and type.
6153 if ($line =~ /\b$Type\s+$Inline\b/ ||
6154 $line =~ /\b$Inline\s+$Storage\b/) {
6155 ERROR("INLINE_LOCATION",
6156 "inline keyword should sit between storage class and type\n" . $herecurr);
6157 }
6158
6159# Check for __inline__ and __inline, prefer inline
6160 if ($realfile !~ m@\binclude/uapi/@ &&
6161 $line =~ /\b(__inline__|__inline)\b/) {
6162 if (WARN("INLINE",
6163 "plain inline is preferred over $1\n" . $herecurr) &&
6164 $fix) {
6165 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6166
6167 }
6168 }
6169
Elyes Haouas069dfe32022-05-23 18:38:19 +02006170# Check for compiler attributes
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006171 if ($realfile !~ m@\binclude/uapi/@ &&
Elyes Haouas069dfe32022-05-23 18:38:19 +02006172 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6173 my $attr = $1;
6174 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006175
Elyes Haouas069dfe32022-05-23 18:38:19 +02006176 my %attr_list = (
6177 "alias" => "__alias",
6178 "aligned" => "__aligned",
6179 "always_inline" => "__always_inline",
6180 "assume_aligned" => "__assume_aligned",
6181 "cold" => "__cold",
6182 "const" => "__attribute_const__",
6183 "copy" => "__copy",
6184 "designated_init" => "__designated_init",
6185 "externally_visible" => "__visible",
6186 "format" => "printf|scanf",
6187 "gnu_inline" => "__gnu_inline",
6188 "malloc" => "__malloc",
6189 "mode" => "__mode",
6190 "no_caller_saved_registers" => "__no_caller_saved_registers",
6191 "noclone" => "__noclone",
6192 "noinline" => "noinline",
6193 "nonstring" => "__nonstring",
6194 "noreturn" => "__noreturn",
6195 "packed" => "__packed",
6196 "pure" => "__pure",
6197 "section" => "__section",
6198 "used" => "__used",
6199 "weak" => "__weak"
6200 );
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006201
Elyes Haouas069dfe32022-05-23 18:38:19 +02006202 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6203 my $orig_attr = $1;
6204 my $params = '';
6205 $params = $2 if defined($2);
6206 my $curr_attr = $orig_attr;
6207 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6208 if (exists($attr_list{$curr_attr})) {
6209 my $new = $attr_list{$curr_attr};
6210 if ($curr_attr eq "format" && $params) {
6211 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6212 $new = "__$1\($2";
6213 } else {
6214 $new = "$new$params";
6215 }
6216 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6217 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6218 $fix) {
6219 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6220 $fixed[$fixlinenr] =~ s/$remove//;
6221 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6222 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6223 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6224 }
6225 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006226 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006227
Elyes Haouas069dfe32022-05-23 18:38:19 +02006228 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6229 if ($attr =~ /^_*unused/) {
6230 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6231 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006232 }
6233 }
6234
6235# Check for __attribute__ weak, or __weak declarations (may have link issues)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006236 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006237 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6238 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6239 $line =~ /\b__weak\b/)) {
6240 ERROR("WEAK_DECLARATION",
6241 "Using weak declarations can have unintended link defects\n" . $herecurr);
6242 }
6243
Martin Rothedd591d2017-03-14 10:16:29 -06006244# check for c99 types like uint8_t used outside of uapi/ and tools/
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006245 if ($realfile !~ m@\binclude/uapi/@ &&
Martin Rothedd591d2017-03-14 10:16:29 -06006246 $realfile !~ m@\btools/@ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006247 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6248 my $type = $1;
6249 if ($type =~ /\b($typeC99Typedefs)\b/) {
6250 $type = $1;
6251 my $kernel_type = 'u';
6252 $kernel_type = 's' if ($type =~ /^_*[si]/);
6253 $type =~ /(\d+)/;
6254 $kernel_type .= $1;
6255 if (CHK("PREFER_KERNEL_TYPES",
6256 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6257 $fix) {
6258 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6259 }
6260 }
6261 }
6262
6263# check for cast of C90 native int or longer types constants
6264 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6265 my $cast = $1;
6266 my $const = $2;
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006267 my $suffix = "";
6268 my $newconst = $const;
6269 $newconst =~ s/${Int_type}$//;
6270 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6271 if ($cast =~ /\blong\s+long\b/) {
6272 $suffix .= 'LL';
6273 } elsif ($cast =~ /\blong\b/) {
6274 $suffix .= 'L';
6275 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006276 if (WARN("TYPECAST_INT_CONSTANT",
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006277 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006278 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006279 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6280 }
6281 }
6282
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006283# check for sizeof(&)
6284 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6285 WARN("SIZEOF_ADDRESS",
6286 "sizeof(& should be avoided\n" . $herecurr);
6287 }
6288
6289# check for sizeof without parenthesis
6290 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6291 if (WARN("SIZEOF_PARENTHESIS",
6292 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6293 $fix) {
6294 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6295 }
6296 }
6297
6298# check for struct spinlock declarations
6299 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6300 WARN("USE_SPINLOCK_T",
6301 "struct spinlock should be spinlock_t\n" . $herecurr);
6302 }
6303
6304# check for seq_printf uses that could be seq_puts
6305 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6306 my $fmt = get_quoted_string($line, $rawline);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006307 $fmt =~ s/%%//g;
6308 if ($fmt !~ /%/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006309 if (WARN("PREFER_SEQ_PUTS",
6310 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6311 $fix) {
6312 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6313 }
6314 }
6315 }
6316
Martin Roth60915b32018-08-10 21:04:05 -06006317# check for vsprintf extension %p<foo> misuses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006318 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006319 defined $stat &&
6320 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6321 $1 !~ /^_*volatile_*$/) {
Martin Roth60915b32018-08-10 21:04:05 -06006322 my $stat_real;
6323
Martin Roth387dec82017-09-17 19:20:46 -06006324 my $lc = $stat =~ tr@\n@@;
6325 $lc = $lc + $linenr;
6326 for (my $count = $linenr; $count <= $lc; $count++) {
Martin Roth60915b32018-08-10 21:04:05 -06006327 my $specifier;
6328 my $extension;
6329 my $bad_specifier = "";
Martin Roth387dec82017-09-17 19:20:46 -06006330 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6331 $fmt =~ s/%%//g;
Martin Roth60915b32018-08-10 21:04:05 -06006332
6333 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
6334 $specifier = $1;
6335 $extension = $2;
6336 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
6337 $bad_specifier = $specifier;
6338 last;
6339 }
6340 if ($extension eq "x" && !defined($stat_real)) {
6341 if (!defined($stat_real)) {
6342 $stat_real = get_stat_real($linenr, $lc);
6343 }
6344 WARN("VSPRINTF_SPECIFIER_PX",
6345 "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n");
6346 }
Martin Roth387dec82017-09-17 19:20:46 -06006347 }
Martin Roth60915b32018-08-10 21:04:05 -06006348 if ($bad_specifier ne "") {
6349 my $stat_real = get_stat_real($linenr, $lc);
6350 my $ext_type = "Invalid";
6351 my $use = "";
6352 if ($bad_specifier =~ /p[Ff]/) {
6353 $ext_type = "Deprecated";
6354 $use = " - use %pS instead";
6355 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6356 }
6357
6358 WARN("VSPRINTF_POINTER_EXTENSION",
6359 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
Martin Roth387dec82017-09-17 19:20:46 -06006360 }
Martin Roth387dec82017-09-17 19:20:46 -06006361 }
6362 }
6363
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006364# Check for misused memsets
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006365 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006366 defined $stat &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006367 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006368
6369 my $ms_addr = $2;
6370 my $ms_val = $7;
6371 my $ms_size = $12;
6372
6373 if ($ms_size =~ /^(0x|)0$/i) {
6374 ERROR("MEMSET",
6375 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6376 } elsif ($ms_size =~ /^(0x|)1$/i) {
6377 WARN("MEMSET",
6378 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6379 }
6380 }
6381
6382# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006383# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006384# defined $stat &&
6385# $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6386# if (WARN("PREFER_ETHER_ADDR_COPY",
6387# "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6388# $fix) {
6389# $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6390# }
6391# }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006392
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006393# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006394# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006395# defined $stat &&
6396# $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6397# WARN("PREFER_ETHER_ADDR_EQUAL",
6398# "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6399# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006400
6401# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6402# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006403# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006404# defined $stat &&
6405# $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6406#
6407# my $ms_val = $7;
6408#
6409# if ($ms_val =~ /^(?:0x|)0+$/i) {
6410# if (WARN("PREFER_ETH_ZERO_ADDR",
6411# "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6412# $fix) {
6413# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6414# }
6415# } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6416# if (WARN("PREFER_ETH_BROADCAST_ADDR",
6417# "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6418# $fix) {
6419# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6420# }
6421# }
6422# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006423
Elyes Haouasf0e150c2022-04-12 13:12:19 +02006424# strlcpy uses that should likely be strscpy
6425 if ($line =~ /\bstrlcpy\s*\(/) {
6426 WARN("STRLCPY",
6427 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6428 }
6429
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006430# typecasts on min/max could be min_t/max_t
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006431 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006432 defined $stat &&
6433 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6434 if (defined $2 || defined $7) {
6435 my $call = $1;
6436 my $cast1 = deparenthesize($2);
6437 my $arg1 = $3;
6438 my $cast2 = deparenthesize($7);
6439 my $arg2 = $8;
6440 my $cast;
6441
6442 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6443 $cast = "$cast1 or $cast2";
6444 } elsif ($cast1 ne "") {
6445 $cast = $cast1;
6446 } else {
6447 $cast = $cast2;
6448 }
6449 WARN("MINMAX",
6450 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6451 }
6452 }
6453
6454# check usleep_range arguments
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006455 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006456 defined $stat &&
6457 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6458 my $min = $1;
6459 my $max = $7;
6460 if ($min eq $max) {
6461 WARN("USLEEP_RANGE",
6462 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6463 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6464 $min > $max) {
6465 WARN("USLEEP_RANGE",
6466 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6467 }
6468 }
6469
6470# check for naked sscanf
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006471 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006472 defined $stat &&
6473 $line =~ /\bsscanf\b/ &&
6474 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6475 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6476 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6477 my $lc = $stat =~ tr@\n@@;
6478 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006479 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006480 WARN("NAKED_SSCANF",
6481 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6482 }
6483
6484# check for simple sscanf that should be kstrto<foo>
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006485 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006486 defined $stat &&
6487 $line =~ /\bsscanf\b/) {
6488 my $lc = $stat =~ tr@\n@@;
6489 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006490 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006491 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6492 my $format = $6;
6493 my $count = $format =~ tr@%@%@;
6494 if ($count == 1 &&
6495 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6496 WARN("SSCANF_TO_KSTRTO",
6497 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6498 }
6499 }
6500 }
6501
6502# check for new externs in .h files.
6503 if ($realfile =~ /\.h$/ &&
6504 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6505 if (CHK("AVOID_EXTERNS",
6506 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6507 $fix) {
6508 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6509 }
6510 }
6511
6512# check for new externs in .c files.
6513 if ($realfile =~ /\.c$/ && defined $stat &&
6514 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6515 {
6516 my $function_name = $1;
6517 my $paren_space = $2;
6518
6519 my $s = $stat;
6520 if (defined $cond) {
6521 substr($s, 0, length($cond), '');
6522 }
Elyes Haouas26e0b942022-05-22 11:11:11 +02006523 if ($s =~ /^\s*;/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006524 {
6525 WARN("AVOID_EXTERNS",
6526 "externs should be avoided in .c files\n" . $herecurr);
6527 }
6528
6529 if ($paren_space =~ /\n/) {
6530 WARN("FUNCTION_ARGUMENTS",
6531 "arguments for function declarations should follow identifier\n" . $herecurr);
6532 }
6533
6534 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6535 $stat =~ /^.\s*extern\s+/)
6536 {
6537 WARN("AVOID_EXTERNS",
6538 "externs should be avoided in .c files\n" . $herecurr);
6539 }
6540
Martin Roth387dec82017-09-17 19:20:46 -06006541# check for function declarations that have arguments without identifier names
6542 if (defined $stat &&
Martin Roth60915b32018-08-10 21:04:05 -06006543 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
Martin Rothedd591d2017-03-14 10:16:29 -06006544 $1 ne "void") {
6545 my $args = trim($1);
6546 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6547 my $arg = trim($1);
6548 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6549 WARN("FUNCTION_ARGUMENTS",
6550 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6551 }
6552 }
6553 }
6554
Martin Roth387dec82017-09-17 19:20:46 -06006555# check for function definitions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006556 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006557 defined $stat &&
6558 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6559 $context_function = $1;
6560
6561# check for multiline function definition with misplaced open brace
6562 my $ok = 0;
6563 my $cnt = statement_rawlines($stat);
6564 my $herectx = $here . "\n";
6565 for (my $n = 0; $n < $cnt; $n++) {
6566 my $rl = raw_line($linenr, $n);
6567 $herectx .= $rl . "\n";
6568 $ok = 1 if ($rl =~ /^[ \+]\{/);
6569 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6570 last if $rl =~ /^[ \+].*\{/;
6571 }
6572 if (!$ok) {
6573 ERROR("OPEN_BRACE",
6574 "open brace '{' following function definitions go on the next line\n" . $herectx);
6575 }
6576 }
6577
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006578# checks for new __setup's
6579 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6580 my $name = $1;
6581
6582 if (!grep(/$name/, @setup_docs)) {
6583 CHK("UNDOCUMENTED_SETUP",
Martin Rothedd591d2017-03-14 10:16:29 -06006584 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006585 }
6586 }
6587
Elyes Haouasa7b0d382022-05-23 18:33:15 +02006588# check for pointless casting of alloc functions
6589 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006590 WARN("UNNECESSARY_CASTS",
6591 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6592 }
6593
6594# alloc style
6595# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006596 if ($perl_version_ok &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02006597 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006598 CHK("ALLOC_SIZEOF_STRUCT",
6599 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6600 }
6601
Elyes Haouas709fdb12022-05-28 10:03:10 +02006602# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006603 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006604 defined $stat &&
Elyes Haouas709fdb12022-05-28 10:03:10 +02006605 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006606 my $oldfunc = $3;
6607 my $a1 = $4;
6608 my $a2 = $10;
6609 my $newfunc = "kmalloc_array";
Elyes Haouas709fdb12022-05-28 10:03:10 +02006610 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
6611 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006612 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6613 my $r1 = $a1;
6614 my $r2 = $a2;
6615 if ($a1 =~ /^sizeof\s*\S/) {
6616 $r1 = $a2;
6617 $r2 = $a1;
6618 }
6619 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6620 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
Martin Roth387dec82017-09-17 19:20:46 -06006621 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006622 my $herectx = get_stat_here($linenr, $cnt, $here);
6623
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006624 if (WARN("ALLOC_WITH_MULTIPLY",
Martin Roth387dec82017-09-17 19:20:46 -06006625 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6626 $cnt == 1 &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006627 $fix) {
Elyes Haouas709fdb12022-05-28 10:03:10 +02006628 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006629 }
6630 }
6631 }
6632
6633# check for krealloc arg reuse
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006634 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006635 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
6636 WARN("KREALLOC_ARG_REUSE",
6637 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6638 }
6639
6640# check for alloc argument mismatch
6641 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6642 WARN("ALLOC_ARRAY_ARGS",
6643 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6644 }
6645
6646# check for multiple semicolons
6647 if ($line =~ /;\s*;\s*$/) {
6648 if (WARN("ONE_SEMICOLON",
6649 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6650 $fix) {
6651 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6652 }
6653 }
6654
Martin Rothedd591d2017-03-14 10:16:29 -06006655# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6656 if ($realfile !~ m@^include/uapi/@ &&
6657 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006658 my $ull = "";
6659 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6660 if (CHK("BIT_MACRO",
6661 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6662 $fix) {
6663 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6664 }
6665 }
6666
Elyes Haouasf62a9892022-04-12 12:17:50 +02006667# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6668 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6669 WARN("IS_ENABLED_CONFIG",
6670 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6671 }
6672
6673# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6674 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6675 my $config = $1;
6676 if (WARN("PREFER_IS_ENABLED",
6677 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6678 $fix) {
6679 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006680 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02006681 }
6682
6683# check for /* fallthrough */ like comment, prefer fallthrough;
6684 my @fallthroughs = (
6685 'fallthrough',
6686 '@fallthrough@',
6687 'lint -fallthrough[ \t]*',
6688 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6689 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6690 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6691 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6692 );
6693 if ($raw_comment ne '') {
6694 foreach my $ft (@fallthroughs) {
6695 if ($raw_comment =~ /$ft/) {
6696 my $msg_level = \&WARN;
6697 $msg_level = \&CHK if ($file);
6698 &{$msg_level}("PREFER_FALLTHROUGH",
6699 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6700 last;
6701 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006702 }
6703 }
6704
6705# check for switch/default statements without a break;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006706 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006707 defined $stat &&
6708 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006709 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006710 my $herectx = get_stat_here($linenr, $cnt, $here);
6711
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006712 WARN("DEFAULT_NO_BREAK",
6713 "switch default: should use break\n" . $herectx);
6714 }
6715
6716# check for gcc specific __FUNCTION__
6717 if ($line =~ /\b__FUNCTION__\b/) {
6718 if (WARN("USE_FUNC",
6719 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6720 $fix) {
6721 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6722 }
6723 }
6724
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006725# check for uses of __DATE__, __TIME__, __TIMESTAMP__
6726 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6727 ERROR("DATE_TIME",
6728 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6729 }
6730
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006731# check for use of yield()
6732 if ($line =~ /\byield\s*\(\s*\)/) {
6733 WARN("YIELD",
6734 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6735 }
6736
6737# check for comparisons against true and false
6738 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6739 my $lead = $1;
6740 my $arg = $2;
6741 my $test = $3;
6742 my $otype = $4;
6743 my $trail = $5;
6744 my $op = "!";
6745
6746 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6747
6748 my $type = lc($otype);
6749 if ($type =~ /^(?:true|false)$/) {
6750 if (("$test" eq "==" && "$type" eq "true") ||
6751 ("$test" eq "!=" && "$type" eq "false")) {
6752 $op = "";
6753 }
6754
6755 CHK("BOOL_COMPARISON",
6756 "Using comparison to $otype is error prone\n" . $herecurr);
6757
6758## maybe suggesting a correct construct would better
6759## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6760
6761 }
6762 }
6763
Martin Roth60915b32018-08-10 21:04:05 -06006764# check for bool bitfields
6765 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6766 WARN("BOOL_BITFIELD",
6767 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6768 }
6769
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006770# check for semaphores initialized locked
6771 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6772 WARN("CONSIDER_COMPLETION",
6773 "consider using a completion\n" . $herecurr);
6774 }
6775
6776# recommend kstrto* over simple_strto* and strict_strto*
6777 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6778 WARN("CONSIDER_KSTRTO",
6779 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6780 }
6781
6782# check for __initcall(), use device_initcall() explicitly or more appropriate function please
6783 if ($line =~ /^.\s*__initcall\s*\(/) {
6784 WARN("USE_DEVICE_INITCALL",
6785 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6786 }
6787
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006788# check for various structs that are normally const (ops, kgdb, device_tree)
Martin Roth387dec82017-09-17 19:20:46 -06006789# and avoid what seem like struct definitions 'struct foo {'
Elyes Haouas43529c82022-04-12 13:19:50 +02006790 if (defined($const_structs) &&
6791 $line !~ /\bconst\b/ &&
Martin Roth387dec82017-09-17 19:20:46 -06006792 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006793 WARN("CONST_STRUCT",
Martin Roth387dec82017-09-17 19:20:46 -06006794 "struct $1 should normally be const\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006795 }
6796
6797# use of NR_CPUS is usually wrong
6798# ignore definitions of NR_CPUS and usage to define arrays as likely right
6799 if ($line =~ /\bNR_CPUS\b/ &&
6800 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6801 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6802 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6803 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6804 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6805 {
6806 WARN("NR_CPUS",
6807 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6808 }
6809
6810# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6811 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6812 ERROR("DEFINE_ARCH_HAS",
6813 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6814 }
6815
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006816# likely/unlikely comparisons similar to "(likely(foo) > 0)"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006817 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006818 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6819 WARN("LIKELY_MISUSE",
6820 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6821 }
6822
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006823# whine mightly about in_atomic
6824 if ($line =~ /\bin_atomic\s*\(/) {
6825 if ($realfile =~ m@^drivers/@) {
6826 ERROR("IN_ATOMIC",
6827 "do not use in_atomic in drivers\n" . $herecurr);
6828 } elsif ($realfile !~ m@^kernel/@) {
6829 WARN("IN_ATOMIC",
6830 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6831 }
6832 }
6833
Martin Rothedd591d2017-03-14 10:16:29 -06006834# check for mutex_trylock_recursive usage
6835 if ($line =~ /mutex_trylock_recursive/) {
6836 ERROR("LOCKING",
6837 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6838 }
6839
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006840# check for lockdep_set_novalidate_class
6841 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6842 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6843 if ($realfile !~ m@^kernel/lockdep@ &&
6844 $realfile !~ m@^include/linux/lockdep@ &&
6845 $realfile !~ m@^drivers/base/core@) {
6846 ERROR("LOCKDEP",
6847 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6848 }
6849 }
6850
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006851 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6852 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006853 WARN("EXPORTED_WORLD_WRITABLE",
6854 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6855 }
6856
Martin Roth60915b32018-08-10 21:04:05 -06006857# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6858# and whether or not function naming is typical and if
6859# DEVICE_ATTR permissions uses are unusual too
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006860 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06006861 defined $stat &&
6862 $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) {
6863 my $var = $1;
6864 my $perms = $2;
6865 my $show = $3;
6866 my $store = $4;
6867 my $octal_perms = perms_to_octal($perms);
6868 if ($show =~ /^${var}_show$/ &&
6869 $store =~ /^${var}_store$/ &&
6870 $octal_perms eq "0644") {
6871 if (WARN("DEVICE_ATTR_RW",
6872 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6873 $fix) {
6874 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6875 }
6876 } elsif ($show =~ /^${var}_show$/ &&
6877 $store =~ /^NULL$/ &&
6878 $octal_perms eq "0444") {
6879 if (WARN("DEVICE_ATTR_RO",
6880 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6881 $fix) {
6882 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6883 }
6884 } elsif ($show =~ /^NULL$/ &&
6885 $store =~ /^${var}_store$/ &&
6886 $octal_perms eq "0200") {
6887 if (WARN("DEVICE_ATTR_WO",
6888 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6889 $fix) {
6890 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6891 }
6892 } elsif ($octal_perms eq "0644" ||
6893 $octal_perms eq "0444" ||
6894 $octal_perms eq "0200") {
6895 my $newshow = "$show";
6896 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6897 my $newstore = $store;
6898 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6899 my $rename = "";
6900 if ($show ne $newshow) {
6901 $rename .= " '$show' to '$newshow'";
6902 }
6903 if ($store ne $newstore) {
6904 $rename .= " '$store' to '$newstore'";
6905 }
6906 WARN("DEVICE_ATTR_FUNCTIONS",
6907 "Consider renaming function(s)$rename\n" . $herecurr);
6908 } else {
6909 WARN("DEVICE_ATTR_PERMS",
6910 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6911 }
6912 }
6913
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006914# Mode permission misuses where it seems decimal should be octal
6915# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
Martin Roth60915b32018-08-10 21:04:05 -06006916# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6917# specific definition of not visible in sysfs.
6918# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6919# use the default permissions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006920 if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006921 defined $stat &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006922 $line =~ /$mode_perms_search/) {
6923 foreach my $entry (@mode_permission_funcs) {
6924 my $func = $entry->[0];
6925 my $arg_pos = $entry->[1];
6926
Martin Rothedd591d2017-03-14 10:16:29 -06006927 my $lc = $stat =~ tr@\n@@;
6928 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006929 my $stat_real = get_stat_real($linenr, $lc);
Martin Rothedd591d2017-03-14 10:16:29 -06006930
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006931 my $skip_args = "";
6932 if ($arg_pos > 1) {
6933 $arg_pos--;
6934 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6935 }
Martin Rothedd591d2017-03-14 10:16:29 -06006936 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6937 if ($stat =~ /$test/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006938 my $val = $1;
6939 $val = $6 if ($skip_args ne "");
Martin Roth60915b32018-08-10 21:04:05 -06006940 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6941 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6942 ($val =~ /^$Octal$/ && length($val) ne 4))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006943 ERROR("NON_OCTAL_PERMISSIONS",
Martin Rothedd591d2017-03-14 10:16:29 -06006944 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6945 }
6946 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006947 ERROR("EXPORTED_WORLD_WRITABLE",
Martin Rothedd591d2017-03-14 10:16:29 -06006948 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006949 }
6950 }
6951 }
6952 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006953
Martin Rothedd591d2017-03-14 10:16:29 -06006954# check for uses of S_<PERMS> that could be octal for readability
Martin Roth60915b32018-08-10 21:04:05 -06006955 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6956 my $oval = $1;
6957 my $octal = perms_to_octal($oval);
Martin Rothedd591d2017-03-14 10:16:29 -06006958 if (WARN("SYMBOLIC_PERMS",
6959 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6960 $fix) {
Martin Roth60915b32018-08-10 21:04:05 -06006961 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
Martin Rothedd591d2017-03-14 10:16:29 -06006962 }
6963 }
6964
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006965# validate content of MODULE_LICENSE against list from include/linux/module.h
6966 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6967 my $extracted_string = get_quoted_string($line, $rawline);
6968 my $valid_licenses = qr{
6969 GPL|
6970 GPL\ v2|
6971 GPL\ and\ additional\ rights|
6972 Dual\ BSD/GPL|
6973 Dual\ MIT/GPL|
6974 Dual\ MPL/GPL|
6975 Proprietary
6976 }x;
6977 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6978 WARN("MODULE_LICENSE",
6979 "unknown module license " . $extracted_string . "\n" . $herecurr);
6980 }
6981 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006982 }
6983
6984 # If we have no input at all, then there is nothing to report on
6985 # so just keep quiet.
6986 if ($#rawlines == -1) {
6987 exit(0);
6988 }
6989
6990 # In mailback mode only produce a report in the negative, for
6991 # things that appear to be patches.
6992 if ($mailback && ($clean == 1 || !$is_patch)) {
6993 exit(0);
6994 }
6995
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01006996 # This is not a patch, and we are in 'no-patch' mode so
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006997 # just keep quiet.
6998 if (!$chk_patch && !$is_patch) {
6999 exit(0);
7000 }
7001
Martin Roth60915b32018-08-10 21:04:05 -06007002 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007003 ERROR("NOT_UNIFIED_DIFF",
7004 "Does not appear to be a unified-diff format patch\n");
7005 }
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02007006 if ($is_patch && $has_commit_log && $chk_signoff) {
7007 if ($signoff == 0) {
7008 ERROR("MISSING_SIGN_OFF",
7009 "Missing Signed-off-by: line(s)\n");
7010 } elsif ($authorsignoff != 1) {
7011 # authorsignoff values:
7012 # 0 -> missing sign off
7013 # 1 -> sign off identical
7014 # 2 -> names and addresses match, comments mismatch
7015 # 3 -> addresses match, names different
7016 # 4 -> names match, addresses different
7017 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7018
7019 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7020
7021 if ($authorsignoff == 0) {
7022 ERROR("NO_AUTHOR_SIGN_OFF",
7023 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7024 } elsif ($authorsignoff == 2) {
7025 CHK("FROM_SIGN_OFF_MISMATCH",
7026 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7027 } elsif ($authorsignoff == 3) {
7028 WARN("FROM_SIGN_OFF_MISMATCH",
7029 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7030 } elsif ($authorsignoff == 4) {
7031 WARN("FROM_SIGN_OFF_MISMATCH",
7032 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7033 } elsif ($authorsignoff == 5) {
7034 WARN("FROM_SIGN_OFF_MISMATCH",
7035 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7036 }
7037 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007038 }
7039
7040 print report_dump();
7041 if ($summary && !($clean == 1 && $quiet == 1)) {
7042 print "$filename " if ($summary_file);
7043 print "total: $cnt_error errors, $cnt_warn warnings, " .
7044 (($check)? "$cnt_chk checks, " : "") .
7045 "$cnt_lines lines checked\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007046 }
7047
7048 if ($quiet == 0) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007049 # If there were any defects found and not already fixing them
7050 if (!$clean and !$fix) {
7051 print << "EOM"
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007052
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007053NOTE: For some of the reported defects, checkpatch may be able to
7054 mechanically convert to the typical style using --fix or --fix-inplace.
7055EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007056 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007057 # If there were whitespace errors which cleanpatch can fix
7058 # then suggest that.
7059 if ($rpt_cleaners) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007060 $rpt_cleaners = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007061 print << "EOM"
7062
7063NOTE: Whitespace errors detected.
7064 You may wish to use scripts/cleanpatch or scripts/cleanfile
7065EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007066 }
7067 }
7068
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007069 if ($clean == 0 && $fix &&
7070 ("@rawlines" ne "@fixed" ||
7071 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7072 my $newfile = $filename;
7073 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7074 my $linecount = 0;
7075 my $f;
7076
7077 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7078
7079 open($f, '>', $newfile)
7080 or die "$P: Can't open $newfile for write\n";
7081 foreach my $fixed_line (@fixed) {
7082 $linecount++;
7083 if ($file) {
7084 if ($linecount > 3) {
7085 $fixed_line =~ s/^\+//;
7086 print $f $fixed_line . "\n";
7087 }
7088 } else {
7089 print $f $fixed_line . "\n";
7090 }
7091 }
7092 close($f);
7093
7094 if (!$quiet) {
7095 print << "EOM";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007096
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007097Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7098
7099Do _NOT_ trust the results written to this file.
7100Do _NOT_ submit these changes without inspecting them for correctness.
7101
7102This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7103No warranties, expressed or implied...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007104EOM
7105 }
7106 }
7107
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007108 if ($quiet == 0) {
7109 print "\n";
7110 if ($clean == 1) {
7111 print "$vname has no obvious style problems and is ready for submission.\n";
7112 } else {
7113 print "$vname has style problems, please review.\n";
7114 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007115 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007116 return $clean;
7117}