block: make sure local irq is disabled when calling __blkcg_rstat_flush
[linux-block.git] / scripts / checkpatch.pl
CommitLineData
cb77f0d6 1#!/usr/bin/env perl
882ea1d6
JP
2# SPDX-License-Identifier: GPL-2.0
3#
dbf004d7 4# (c) 2001, Dave Jones. (the file handling bit)
00df344f 5# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
2a5a2c25 6# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
015830be 7# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
882ea1d6 8# (c) 2010-2018 Joe Perches <joe@perches.com>
0a920b5b
AW
9
10use strict;
cb77f0d6 11use warnings;
c707a81d 12use POSIX;
36061e38
JP
13use File::Basename;
14use Cwd 'abs_path';
57230297 15use Term::ANSIColor qw(:constants);
cd261496 16use Encode qw(decode encode);
0a920b5b
AW
17
18my $P = $0;
36061e38 19my $D = dirname(abs_path($P));
0a920b5b 20
000d1cc1 21my $V = '0.32';
0a920b5b
AW
22
23use Getopt::Long qw(:config no_auto_abbrev);
24
25my $quiet = 0;
52178ce0
DR
26my $verbose = 0;
27my %verbose_messages = ();
28my %verbose_emitted = ();
0a920b5b
AW
29my $tree = 1;
30my $chk_signoff = 1;
31my $chk_patch = 1;
773647a0 32my $tst_only;
6c72ffaa 33my $emacs = 0;
8905a67c 34my $terse = 0;
34d8815f 35my $showfile = 0;
6c72ffaa 36my $file = 0;
4a593c34 37my $git = 0;
0dea9f1e 38my %git_commits = ();
6c72ffaa 39my $check = 0;
2ac73b4f 40my $check_orig = 0;
8905a67c
AW
41my $summary = 1;
42my $mailback = 0;
13214adf 43my $summary_file = 0;
000d1cc1 44my $show_types = 0;
3beb42ec 45my $list_types = 0;
3705ce5b 46my $fix = 0;
9624b8d6 47my $fix_inplace = 0;
6c72ffaa 48my $root;
0f7f635b
JP
49my $gitroot = $ENV{'GIT_DIR'};
50$gitroot = ".git" if !defined($gitroot);
c2fdda0d 51my %debug;
3445686a 52my %camelcase = ();
91bfe484
JP
53my %use_type = ();
54my @use = ();
55my %ignore_type = ();
000d1cc1 56my @ignore = ();
77f5b10a 57my $help = 0;
000d1cc1 58my $configuration_file = ".checkpatch.conf";
bdc48fa1 59my $max_line_length = 100;
d62a201f
DH
60my $ignore_perl_version = 0;
61my $minimum_perl_version = 5.10.0;
56193274 62my $min_conf_desc_length = 4;
66b47b4a 63my $spelling_file = "$D/spelling.txt";
ebfd7d62 64my $codespell = 0;
f1a63678 65my $codespellfile = "/usr/share/codespell/dictionary.txt";
0ee3e7b8 66my $user_codespellfile = "";
bf1fa1da 67my $conststructsfile = "$D/const_structs.checkpatch";
52178ce0 68my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
ced69da1 69my $typedefsfile;
737c0767 70my $color = "auto";
98005e8c 71my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
dbbf869d
JP
72# git output parsing needs US English output, so first set backtick child process LANGUAGE
73my $git_command ='export LANGUAGE=en_US.UTF-8; git';
713a09de 74my $tabsize = 8;
3e89ad85 75my ${CONFIG_} = "CONFIG_";
77f5b10a
HE
76
77sub help {
78 my ($exitcode) = @_;
79
80 print << "EOM";
81Usage: $P [OPTION]... [FILE]...
82Version: $V
83
84Options:
85 -q, --quiet quiet
52178ce0 86 -v, --verbose verbose mode
77f5b10a
HE
87 --no-tree run without a kernel tree
88 --no-signoff do not check for 'Signed-off-by' line
89 --patch treat FILE as patchfile (default)
90 --emacs emacs compile window format
91 --terse one line per report
34d8815f 92 --showfile emit diffed file position, not input file position
4a593c34
DC
93 -g, --git treat FILE as a single commit or git revision range
94 single git commit with:
95 <rev>
96 <rev>^
97 <rev>~n
98 multiple git commits with:
99 <rev1>..<rev2>
100 <rev1>...<rev2>
101 <rev>-<count>
102 git merges are ignored
77f5b10a
HE
103 -f, --file treat FILE as regular source file
104 --subjective, --strict enable more subjective tests
3beb42ec 105 --list-types list the possible message types
91bfe484 106 --types TYPE(,TYPE2...) show only these comma separated message types
000d1cc1 107 --ignore TYPE(,TYPE2...) ignore various comma separated message types
3beb42ec 108 --show-types show the specific message type in the output
bdc48fa1
JP
109 --max-line-length=n set the maximum line length, (default $max_line_length)
110 if exceeded, warn on patches
111 requires --strict for use with --file
56193274 112 --min-conf-desc-length=n set the min description length, if shorter, warn
bdc48fa1 113 --tab-size=n set the number of spaces for tab (default $tabsize)
77f5b10a
HE
114 --root=PATH PATH to the kernel tree root
115 --no-summary suppress the per-file summary
116 --mailback only produce a report in case of warnings/errors
117 --summary-file include the filename in summary
118 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
119 'values', 'possible', 'type', and 'attr' (default
120 is all off)
121 --test-only=WORD report only warnings/errors containing WORD
122 literally
3705ce5b
JP
123 --fix EXPERIMENTAL - may create horrible results
124 If correctable single-line errors exist, create
125 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
126 with potential errors corrected to the preferred
127 checkpatch style
9624b8d6
JP
128 --fix-inplace EXPERIMENTAL - may create horrible results
129 Is the same as --fix, but overwrites the input
130 file. It's your fault if there's no backup or git
d62a201f
DH
131 --ignore-perl-version override checking of perl version. expect
132 runtime errors.
ebfd7d62 133 --codespell Use the codespell dictionary for spelling/typos
0ee3e7b8 134 (default:$codespellfile)
ebfd7d62 135 --codespellfile Use this codespell dictionary
75ad8c57 136 --typedefsfile Read additional types from this file
737c0767
JB
137 --color[=WHEN] Use colors 'always', 'never', or only when output
138 is a terminal ('auto'). Default is 'auto'.
3e89ad85
JF
139 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
140 ${CONFIG_})
77f5b10a
HE
141 -h, --help, --version display this help and exit
142
143When FILE is - read standard input.
144EOM
145
146 exit($exitcode);
147}
148
3beb42ec
JP
149sub uniq {
150 my %seen;
151 return grep { !$seen{$_}++ } @_;
152}
153
154sub list_types {
155 my ($exitcode) = @_;
156
157 my $count = 0;
158
159 local $/ = undef;
160
161 open(my $script, '<', abs_path($P)) or
162 die "$P: Can't read '$P' $!\n";
163
164 my $text = <$script>;
165 close($script);
166
52178ce0 167 my %types = ();
0547fa58 168 # Also catch when type or level is passed through a variable
52178ce0
DR
169 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
170 if (defined($1)) {
171 if (exists($types{$2})) {
172 $types{$2} .= ",$1" if ($types{$2} ne $1);
173 } else {
174 $types{$2} = $1;
175 }
176 } else {
177 $types{$2} = "UNDETERMINED";
178 }
3beb42ec 179 }
52178ce0 180
3beb42ec 181 print("#\tMessage type\n\n");
52178ce0
DR
182 if ($color) {
183 print(" ( Color coding: ");
184 print(RED . "ERROR" . RESET);
185 print(" | ");
186 print(YELLOW . "WARNING" . RESET);
187 print(" | ");
188 print(GREEN . "CHECK" . RESET);
189 print(" | ");
190 print("Multiple levels / Undetermined");
191 print(" )\n\n");
192 }
193
194 foreach my $type (sort keys %types) {
195 my $orig_type = $type;
196 if ($color) {
197 my $level = $types{$type};
198 if ($level eq "ERROR") {
199 $type = RED . $type . RESET;
200 } elsif ($level eq "WARN") {
201 $type = YELLOW . $type . RESET;
202 } elsif ($level eq "CHK") {
203 $type = GREEN . $type . RESET;
204 }
205 }
3beb42ec 206 print(++$count . "\t" . $type . "\n");
52178ce0
DR
207 if ($verbose && exists($verbose_messages{$orig_type})) {
208 my $message = $verbose_messages{$orig_type};
209 $message =~ s/\n/\n\t/g;
210 print("\t" . $message . "\n\n");
211 }
3beb42ec
JP
212 }
213
214 exit($exitcode);
215}
216
000d1cc1
JP
217my $conf = which_conf($configuration_file);
218if (-f $conf) {
219 my @conf_args;
220 open(my $conffile, '<', "$conf")
221 or warn "$P: Can't find a readable $configuration_file file $!\n";
222
223 while (<$conffile>) {
224 my $line = $_;
225
226 $line =~ s/\s*\n?$//g;
227 $line =~ s/^\s*//g;
228 $line =~ s/\s+/ /g;
229
230 next if ($line =~ m/^\s*#/);
231 next if ($line =~ m/^\s*$/);
232
233 my @words = split(" ", $line);
234 foreach my $word (@words) {
235 last if ($word =~ m/^#/);
236 push (@conf_args, $word);
237 }
238 }
239 close($conffile);
240 unshift(@ARGV, @conf_args) if @conf_args;
241}
242
52178ce0
DR
243sub load_docs {
244 open(my $docs, '<', "$docsfile")
245 or warn "$P: Can't read the documentation file $docsfile $!\n";
246
247 my $type = '';
248 my $desc = '';
249 my $in_desc = 0;
250
251 while (<$docs>) {
252 chomp;
253 my $line = $_;
254 $line =~ s/\s+$//;
255
256 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
257 if ($desc ne '') {
258 $verbose_messages{$type} = trim($desc);
259 }
260 $type = $1;
261 $desc = '';
262 $in_desc = 1;
263 } elsif ($in_desc) {
264 if ($line =~ /^(?:\s{4,}|$)/) {
265 $line =~ s/^\s{4}//;
266 $desc .= $line;
267 $desc .= "\n";
268 } else {
269 $verbose_messages{$type} = trim($desc);
270 $type = '';
271 $desc = '';
272 $in_desc = 0;
273 }
274 }
275 }
276
277 if ($desc ne '') {
278 $verbose_messages{$type} = trim($desc);
279 }
280 close($docs);
281}
282
737c0767
JB
283# Perl's Getopt::Long allows options to take optional arguments after a space.
284# Prevent --color by itself from consuming other arguments
285foreach (@ARGV) {
286 if ($_ eq "--color" || $_ eq "-color") {
287 $_ = "--color=$color";
288 }
289}
290
0a920b5b 291GetOptions(
6c72ffaa 292 'q|quiet+' => \$quiet,
52178ce0 293 'v|verbose!' => \$verbose,
0a920b5b
AW
294 'tree!' => \$tree,
295 'signoff!' => \$chk_signoff,
296 'patch!' => \$chk_patch,
6c72ffaa 297 'emacs!' => \$emacs,
8905a67c 298 'terse!' => \$terse,
34d8815f 299 'showfile!' => \$showfile,
77f5b10a 300 'f|file!' => \$file,
4a593c34 301 'g|git!' => \$git,
6c72ffaa
AW
302 'subjective!' => \$check,
303 'strict!' => \$check,
000d1cc1 304 'ignore=s' => \@ignore,
91bfe484 305 'types=s' => \@use,
000d1cc1 306 'show-types!' => \$show_types,
3beb42ec 307 'list-types!' => \$list_types,
6cd7f386 308 'max-line-length=i' => \$max_line_length,
56193274 309 'min-conf-desc-length=i' => \$min_conf_desc_length,
713a09de 310 'tab-size=i' => \$tabsize,
6c72ffaa 311 'root=s' => \$root,
8905a67c
AW
312 'summary!' => \$summary,
313 'mailback!' => \$mailback,
13214adf 314 'summary-file!' => \$summary_file,
3705ce5b 315 'fix!' => \$fix,
9624b8d6 316 'fix-inplace!' => \$fix_inplace,
d62a201f 317 'ignore-perl-version!' => \$ignore_perl_version,
c2fdda0d 318 'debug=s' => \%debug,
773647a0 319 'test-only=s' => \$tst_only,
ebfd7d62 320 'codespell!' => \$codespell,
0ee3e7b8 321 'codespellfile=s' => \$user_codespellfile,
75ad8c57 322 'typedefsfile=s' => \$typedefsfile,
737c0767
JB
323 'color=s' => \$color,
324 'no-color' => \$color, #keep old behaviors of -nocolor
325 'nocolor' => \$color, #keep old behaviors of -nocolor
3e89ad85 326 'kconfig-prefix=s' => \${CONFIG_},
77f5b10a
HE
327 'h|help' => \$help,
328 'version' => \$help
0ee3e7b8
PU
329) or $help = 2;
330
331if ($user_codespellfile) {
332 # Use the user provided codespell file unconditionally
333 $codespellfile = $user_codespellfile;
334} elsif (!(-f $codespellfile)) {
335 # If /usr/share/codespell/dictionary.txt is not present, try to find it
336 # under codespell's install directory: <codespell_root>/data/dictionary.txt
c882c6b1 337 if (($codespell || $help) && which("python3") ne "") {
0ee3e7b8
PU
338 my $python_codespell_dict = << "EOF";
339
340import os.path as op
341import codespell_lib
342codespell_dir = op.dirname(codespell_lib.__file__)
343codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
344print(codespell_file, end='')
345EOF
346
c882c6b1 347 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
0ee3e7b8
PU
348 $codespellfile = $codespell_dict if (-f $codespell_dict);
349 }
350}
77f5b10a 351
0ee3e7b8
PU
352# $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
353# $help is 2 if invalid option is passed - exitcode: 1
354help($help - 1) if ($help);
0a920b5b 355
52178ce0
DR
356die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
357die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
358
359if ($color =~ /^[01]$/) {
360 $color = !$color;
361} elsif ($color =~ /^always$/i) {
362 $color = 1;
363} elsif ($color =~ /^never$/i) {
364 $color = 0;
365} elsif ($color =~ /^auto$/i) {
366 $color = (-t STDOUT);
367} else {
368 die "$P: Invalid color mode: $color\n";
369}
370
371load_docs() if ($verbose);
3beb42ec
JP
372list_types(0) if ($list_types);
373
9624b8d6 374$fix = 1 if ($fix_inplace);
2ac73b4f 375$check_orig = $check;
9624b8d6 376
0a920b5b
AW
377my $exit = 0;
378
5b57980d 379my $perl_version_ok = 1;
d62a201f 380if ($^V && $^V lt $minimum_perl_version) {
5b57980d 381 $perl_version_ok = 0;
d62a201f 382 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
5b57980d 383 exit(1) if (!$ignore_perl_version);
d62a201f
DH
384}
385
45107ff6 386#if no filenames are given, push '-' to read patch from stdin
0a920b5b 387if ($#ARGV < 0) {
45107ff6 388 push(@ARGV, '-');
0a920b5b
AW
389}
390
713a09de 391# skip TAB size 1 to avoid additional checks on $tabsize - 1
32f30ca9 392die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
713a09de 393
91bfe484
JP
394sub hash_save_array_words {
395 my ($hashRef, $arrayRef) = @_;
396
397 my @array = split(/,/, join(',', @$arrayRef));
398 foreach my $word (@array) {
399 $word =~ s/\s*\n?$//g;
400 $word =~ s/^\s*//g;
401 $word =~ s/\s+/ /g;
402 $word =~ tr/[a-z]/[A-Z]/;
403
404 next if ($word =~ m/^\s*#/);
405 next if ($word =~ m/^\s*$/);
406
407 $hashRef->{$word}++;
408 }
409}
000d1cc1 410
91bfe484
JP
411sub hash_show_words {
412 my ($hashRef, $prefix) = @_;
000d1cc1 413
3c816e49 414 if (keys %$hashRef) {
d8469f16 415 print "\nNOTE: $prefix message types:";
58cb3cf6 416 foreach my $word (sort keys %$hashRef) {
91bfe484
JP
417 print " $word";
418 }
d8469f16 419 print "\n";
91bfe484 420 }
000d1cc1
JP
421}
422
91bfe484
JP
423hash_save_array_words(\%ignore_type, \@ignore);
424hash_save_array_words(\%use_type, \@use);
425
c2fdda0d
AW
426my $dbg_values = 0;
427my $dbg_possible = 0;
7429c690 428my $dbg_type = 0;
a1ef277e 429my $dbg_attr = 0;
c2fdda0d 430for my $key (keys %debug) {
21caa13c
AW
431 ## no critic
432 eval "\${dbg_$key} = '$debug{$key}';";
433 die "$@" if ($@);
c2fdda0d
AW
434}
435
d2c0a235
AW
436my $rpt_cleaners = 0;
437
8905a67c
AW
438if ($terse) {
439 $emacs = 1;
440 $quiet++;
441}
442
6c72ffaa
AW
443if ($tree) {
444 if (defined $root) {
445 if (!top_of_kernel_tree($root)) {
446 die "$P: $root: --root does not point at a valid tree\n";
447 }
448 } else {
449 if (top_of_kernel_tree('.')) {
450 $root = '.';
451 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
452 top_of_kernel_tree($1)) {
453 $root = $1;
454 }
455 }
456
457 if (!defined $root) {
458 print "Must be run from the top-level dir. of a kernel tree\n";
459 exit(2);
460 }
0a920b5b
AW
461}
462
6c72ffaa
AW
463my $emitted_corrupt = 0;
464
2ceb532b
AW
465our $Ident = qr{
466 [A-Za-z_][A-Za-z\d_]*
467 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
468 }x;
6c72ffaa
AW
469our $Storage = qr{extern|static|asmlinkage};
470our $Sparse = qr{
471 __user|
472 __kernel|
473 __force|
474 __iomem|
475 __must_check|
417495ed 476 __kprobes|
165e72a6 477 __ref|
33aa4597
GU
478 __refconst|
479 __refdata|
ad315455
BF
480 __rcu|
481 __private
6c72ffaa 482 }x;
e970b884
JP
483our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
484our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
485our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
486our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
487our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
8716de38 488
52131292
WS
489# Notes to $Attribute:
490# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
6c72ffaa
AW
491our $Attribute = qr{
492 const|
b5e8736a 493 volatile|
03f1df7d
JP
494 __percpu|
495 __nocast|
496 __safe|
46d832f5 497 __bitwise|
03f1df7d
JP
498 __packed__|
499 __packed2__|
500 __naked|
501 __maybe_unused|
502 __always_unused|
503 __noreturn|
504 __used|
505 __cold|
e23ef1f3 506 __pure|
03f1df7d
JP
507 __noclone|
508 __deprecated|
6c72ffaa 509 __read_mostly|
c5967e98 510 __ro_after_init|
6c72ffaa 511 __kprobes|
8716de38 512 $InitAttribute|
24e1d81a
AW
513 ____cacheline_aligned|
514 ____cacheline_aligned_in_smp|
5fe3af11 515 ____cacheline_internodealigned_in_smp|
86cffecd
KC
516 __weak|
517 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
6c72ffaa 518 }x;
c45dcabd 519our $Modifier;
91cb5195 520our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
6c72ffaa
AW
521our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
522our $Lval = qr{$Ident(?:$Member)*};
523
95e2c602
JP
524our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
525our $Binary = qr{(?i)0b[01]+$Int_type?};
526our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
527our $Int = qr{[0-9]+$Int_type?};
2435880f 528our $Octal = qr{0[0-7]+$Int_type?};
d2af5aa6 529our $String = qr{(?:\b[Lu])?"[X\t]*"};
326b1ffc
JP
530our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
531our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
532our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
74349bcc 533our $Float = qr{$Float_hex|$Float_dec|$Float_int};
2435880f 534our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
326b1ffc 535our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
447432f3 536our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
23f780c9 537our $Arithmetic = qr{\+|-|\*|\/|%};
6c72ffaa
AW
538our $Operators = qr{
539 <=|>=|==|!=|
540 =>|->|<<|>>|<|>|!|~|
23f780c9 541 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
6c72ffaa
AW
542 }x;
543
91cb5195
JP
544our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
545
ab7e23f3 546our $BasicType;
8905a67c 547our $NonptrType;
1813087d 548our $NonptrTypeMisordered;
8716de38 549our $NonptrTypeWithAttr;
8905a67c 550our $Type;
1813087d 551our $TypeMisordered;
8905a67c 552our $Declare;
1813087d 553our $DeclareMisordered;
8905a67c 554
15662b3e
JP
555our $NON_ASCII_UTF8 = qr{
556 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
171ae1a4
AW
557 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
558 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
559 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
560 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
561 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
562 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
563}x;
564
15662b3e
JP
565our $UTF8 = qr{
566 [\x09\x0A\x0D\x20-\x7E] # ASCII
567 | $NON_ASCII_UTF8
568}x;
569
e6176fa4 570our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
021158b4
JP
571our $typeOtherOSTypedefs = qr{(?x:
572 u_(?:char|short|int|long) | # bsd
573 u(?:nchar|short|int|long) # sysv
574)};
e6176fa4 575our $typeKernelTypedefs = qr{(?x:
fb9e9096 576 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
8ed22cad
AW
577 atomic_t
578)};
8ea0114e
MS
579our $typeStdioTypedefs = qr{(?x:
580 FILE
581)};
e6176fa4
JP
582our $typeTypedefs = qr{(?x:
583 $typeC99Typedefs\b|
584 $typeOtherOSTypedefs\b|
8ea0114e
MS
585 $typeKernelTypedefs\b|
586 $typeStdioTypedefs\b
e6176fa4 587)};
8ed22cad 588
6d32f7a3
JP
589our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
590
691e669b 591our $logFunctions = qr{(?x:
758d7aad 592 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
7d0b6594 593 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
87bd499a 594 TP_printk|
6e60c02e 595 WARN(?:_RATELIMIT|_ONCE|)|
b0531722 596 panic|
06668727
JP
597 MODULE_[A-Z_]+|
598 seq_vprintf|seq_printf|seq_puts
691e669b
JP
599)};
600
e29a70f1
JP
601our $allocFunctions = qr{(?x:
602 (?:(?:devm_)?
58f02267 603 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
e29a70f1
JP
604 kstrdup(?:_const)? |
605 kmemdup(?:_nul)?) |
461e1565 606 (?:\w+)?alloc_skb(?:_ip_align)? |
e29a70f1
JP
607 # dev_alloc_skb/netdev_alloc_skb, et al
608 dma_alloc_coherent
609)};
610
20112475
JP
611our $signature_tags = qr{(?xi:
612 Signed-off-by:|
d499480c 613 Co-developed-by:|
20112475
JP
614 Acked-by:|
615 Tested-by:|
616 Reviewed-by:|
617 Reported-by:|
8543ae12 618 Suggested-by:|
20112475
JP
619 To:|
620 Cc:
621)};
622
44c31888 623our @link_tags = qw(Link Closes);
f94e40ea
MB
624
625#Create a search and print patterns for all these strings to be used directly below
626our $link_tags_search = "";
627our $link_tags_print = "";
628foreach my $entry (@link_tags) {
629 if ($link_tags_search ne "") {
630 $link_tags_search .= '|';
631 $link_tags_print .= ' or ';
632 }
633 $entry .= ':';
634 $link_tags_search .= $entry;
635 $link_tags_print .= "'$entry'";
636}
637$link_tags_search = "(?:${link_tags_search})";
638
adb2da82
JP
639our $tracing_logging_tags = qr{(?xi:
640 [=-]*> |
641 <[=-]* |
642 \[ |
643 \] |
644 start |
645 called |
646 entered |
647 entry |
648 enter |
649 in |
650 inside |
651 here |
652 begin |
653 exit |
654 end |
655 done |
656 leave |
657 completed |
658 out |
659 return |
660 [\.\!:\s]*
661)};
662
831242ab
AS
663sub edit_distance_min {
664 my (@arr) = @_;
665 my $len = scalar @arr;
666 if ((scalar @arr) < 1) {
667 # if underflow, return
668 return;
669 }
670 my $min = $arr[0];
671 for my $i (0 .. ($len-1)) {
672 if ($arr[$i] < $min) {
673 $min = $arr[$i];
674 }
675 }
676 return $min;
677}
678
679sub get_edit_distance {
680 my ($str1, $str2) = @_;
681 $str1 = lc($str1);
682 $str2 = lc($str2);
683 $str1 =~ s/-//g;
684 $str2 =~ s/-//g;
685 my $len1 = length($str1);
686 my $len2 = length($str2);
687 # two dimensional array storing minimum edit distance
688 my @distance;
689 for my $i (0 .. $len1) {
690 for my $j (0 .. $len2) {
691 if ($i == 0) {
692 $distance[$i][$j] = $j;
693 } elsif ($j == 0) {
694 $distance[$i][$j] = $i;
695 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
696 $distance[$i][$j] = $distance[$i - 1][$j - 1];
697 } else {
698 my $dist1 = $distance[$i][$j - 1]; #insert distance
699 my $dist2 = $distance[$i - 1][$j]; # remove
700 my $dist3 = $distance[$i - 1][$j - 1]; #replace
701 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
702 }
703 }
704 }
705 return $distance[$len1][$len2];
706}
707
708sub find_standard_signature {
709 my ($sign_off) = @_;
710 my @standard_signature_tags = (
711 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
712 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
713 );
714 foreach my $signature (@standard_signature_tags) {
715 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
716 }
717
718 return "";
719}
720
9b71f79f
BH
721our $obsolete_archives = qr{(?xi:
722 \Qfreedesktop.org/archives/dri-devel\E |
723 \Qlists.infradead.org\E |
724 \Qlkml.org\E |
725 \Qmail-archive.com\E |
726 \Qmailman.alsa-project.org/pipermail\E |
727 \Qmarc.info\E |
728 \Qozlabs.org/pipermail\E |
729 \Qspinics.net\E
730)};
731
1813087d
JP
732our @typeListMisordered = (
733 qr{char\s+(?:un)?signed},
734 qr{int\s+(?:(?:un)?signed\s+)?short\s},
735 qr{int\s+short(?:\s+(?:un)?signed)},
736 qr{short\s+int(?:\s+(?:un)?signed)},
737 qr{(?:un)?signed\s+int\s+short},
738 qr{short\s+(?:un)?signed},
739 qr{long\s+int\s+(?:un)?signed},
740 qr{int\s+long\s+(?:un)?signed},
741 qr{long\s+(?:un)?signed\s+int},
742 qr{int\s+(?:un)?signed\s+long},
743 qr{int\s+(?:un)?signed},
744 qr{int\s+long\s+long\s+(?:un)?signed},
745 qr{long\s+long\s+int\s+(?:un)?signed},
746 qr{long\s+long\s+(?:un)?signed\s+int},
747 qr{long\s+long\s+(?:un)?signed},
748 qr{long\s+(?:un)?signed},
749);
750
8905a67c
AW
751our @typeList = (
752 qr{void},
0c773d9d
JP
753 qr{(?:(?:un)?signed\s+)?char},
754 qr{(?:(?:un)?signed\s+)?short\s+int},
755 qr{(?:(?:un)?signed\s+)?short},
756 qr{(?:(?:un)?signed\s+)?int},
757 qr{(?:(?:un)?signed\s+)?long\s+int},
758 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
759 qr{(?:(?:un)?signed\s+)?long\s+long},
760 qr{(?:(?:un)?signed\s+)?long},
761 qr{(?:un)?signed},
8905a67c
AW
762 qr{float},
763 qr{double},
764 qr{bool},
8905a67c
AW
765 qr{struct\s+$Ident},
766 qr{union\s+$Ident},
767 qr{enum\s+$Ident},
768 qr{${Ident}_t},
769 qr{${Ident}_handler},
770 qr{${Ident}_handler_fn},
1813087d 771 @typeListMisordered,
8905a67c 772);
938224b5
JP
773
774our $C90_int_types = qr{(?x:
775 long\s+long\s+int\s+(?:un)?signed|
776 long\s+long\s+(?:un)?signed\s+int|
777 long\s+long\s+(?:un)?signed|
778 (?:(?:un)?signed\s+)?long\s+long\s+int|
779 (?:(?:un)?signed\s+)?long\s+long|
780 int\s+long\s+long\s+(?:un)?signed|
781 int\s+(?:(?:un)?signed\s+)?long\s+long|
782
783 long\s+int\s+(?:un)?signed|
784 long\s+(?:un)?signed\s+int|
785 long\s+(?:un)?signed|
786 (?:(?:un)?signed\s+)?long\s+int|
787 (?:(?:un)?signed\s+)?long|
788 int\s+long\s+(?:un)?signed|
789 int\s+(?:(?:un)?signed\s+)?long|
790
791 int\s+(?:un)?signed|
792 (?:(?:un)?signed\s+)?int
793)};
794
485ff23e 795our @typeListFile = ();
8716de38
JP
796our @typeListWithAttr = (
797 @typeList,
798 qr{struct\s+$InitAttribute\s+$Ident},
799 qr{union\s+$InitAttribute\s+$Ident},
800);
801
c45dcabd
AW
802our @modifierList = (
803 qr{fastcall},
804);
485ff23e 805our @modifierListFile = ();
8905a67c 806
2435880f
JP
807our @mode_permission_funcs = (
808 ["module_param", 3],
809 ["module_param_(?:array|named|string)", 4],
810 ["module_param_array_named", 5],
811 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
812 ["proc_create(?:_data|)", 2],
459cf0ae
JP
813 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
814 ["IIO_DEV_ATTR_[A-Z_]+", 1],
815 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
816 ["SENSOR_TEMPLATE(?:_2|)", 3],
817 ["__ATTR", 2],
2435880f
JP
818);
819
1a3dcf2e
JP
820my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
821
515a235e
JP
822#Create a search pattern for all these functions to speed up a loop below
823our $mode_perms_search = "";
824foreach my $entry (@mode_permission_funcs) {
825 $mode_perms_search .= '|' if ($mode_perms_search ne "");
826 $mode_perms_search .= $entry->[0];
827}
00180468 828$mode_perms_search = "(?:${mode_perms_search})";
515a235e 829
9189c7e7
JP
830our %deprecated_apis = (
831 "synchronize_rcu_bh" => "synchronize_rcu",
832 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
833 "call_rcu_bh" => "call_rcu",
834 "rcu_barrier_bh" => "rcu_barrier",
835 "synchronize_sched" => "synchronize_rcu",
836 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
837 "call_rcu_sched" => "call_rcu",
838 "rcu_barrier_sched" => "rcu_barrier",
839 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
840 "cond_synchronize_sched" => "cond_synchronize_rcu",
defdaff1 841 "kmap" => "kmap_local_page",
a3ea42ff 842 "kunmap" => "kunmap_local",
defdaff1 843 "kmap_atomic" => "kmap_local_page",
a3ea42ff 844 "kunmap_atomic" => "kunmap_local",
9189c7e7
JP
845);
846
847#Create a search pattern for all these strings to speed up a loop below
848our $deprecated_apis_search = "";
849foreach my $entry (keys %deprecated_apis) {
850 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
851 $deprecated_apis_search .= $entry;
852}
853$deprecated_apis_search = "(?:${deprecated_apis_search})";
854
b392c64f
JP
855our $mode_perms_world_writable = qr{
856 S_IWUGO |
857 S_IWOTH |
858 S_IRWXUGO |
859 S_IALLUGO |
860 0[0-7][0-7][2367]
861}x;
862
f90774e1
JP
863our %mode_permission_string_types = (
864 "S_IRWXU" => 0700,
865 "S_IRUSR" => 0400,
866 "S_IWUSR" => 0200,
867 "S_IXUSR" => 0100,
868 "S_IRWXG" => 0070,
869 "S_IRGRP" => 0040,
870 "S_IWGRP" => 0020,
871 "S_IXGRP" => 0010,
872 "S_IRWXO" => 0007,
873 "S_IROTH" => 0004,
874 "S_IWOTH" => 0002,
875 "S_IXOTH" => 0001,
876 "S_IRWXUGO" => 0777,
877 "S_IRUGO" => 0444,
878 "S_IWUGO" => 0222,
879 "S_IXUGO" => 0111,
880);
881
882#Create a search pattern for all these strings to speed up a loop below
883our $mode_perms_string_search = "";
884foreach my $entry (keys %mode_permission_string_types) {
885 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
886 $mode_perms_string_search .= $entry;
887}
00180468
JP
888our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
889our $multi_mode_perms_string_search = qr{
890 ${single_mode_perms_string_search}
891 (?:\s*\|\s*${single_mode_perms_string_search})*
892}x;
893
894sub perms_to_octal {
895 my ($string) = @_;
896
897 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
898
899 my $val = "";
900 my $oval = "";
901 my $to = 0;
902 my $curpos = 0;
903 my $lastpos = 0;
904 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
905 $curpos = pos($string);
906 my $match = $2;
907 my $omatch = $1;
908 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
909 $lastpos = $curpos;
910 $to |= $mode_permission_string_types{$match};
911 $val .= '\s*\|\s*' if ($val ne "");
912 $val .= $match;
913 $oval .= $omatch;
914 }
915 $oval =~ s/^\s*\|\s*//;
916 $oval =~ s/\s*\|\s*$//;
917 return sprintf("%04o", $to);
918}
f90774e1 919
7840a94c
WS
920our $allowed_asm_includes = qr{(?x:
921 irq|
cdcee686
SR
922 memory|
923 time|
924 reboot
7840a94c
WS
925)};
926# memory.h: ARM has a custom one
927
66b47b4a
KC
928# Load common spelling mistakes and build regular expression list.
929my $misspellings;
66b47b4a 930my %spelling_fix;
66b47b4a 931
36061e38 932if (open(my $spelling, '<', $spelling_file)) {
36061e38
JP
933 while (<$spelling>) {
934 my $line = $_;
66b47b4a 935
36061e38
JP
936 $line =~ s/\s*\n?$//g;
937 $line =~ s/^\s*//g;
66b47b4a 938
36061e38
JP
939 next if ($line =~ m/^\s*#/);
940 next if ($line =~ m/^\s*$/);
941
942 my ($suspect, $fix) = split(/\|\|/, $line);
66b47b4a 943
36061e38
JP
944 $spelling_fix{$suspect} = $fix;
945 }
946 close($spelling);
36061e38
JP
947} else {
948 warn "No typos will be found - file '$spelling_file': $!\n";
66b47b4a 949}
66b47b4a 950
ebfd7d62
JP
951if ($codespell) {
952 if (open(my $spelling, '<', $codespellfile)) {
953 while (<$spelling>) {
954 my $line = $_;
955
956 $line =~ s/\s*\n?$//g;
957 $line =~ s/^\s*//g;
958
959 next if ($line =~ m/^\s*#/);
960 next if ($line =~ m/^\s*$/);
961 next if ($line =~ m/, disabled/i);
962
963 $line =~ s/,.*$//;
964
965 my ($suspect, $fix) = split(/->/, $line);
966
967 $spelling_fix{$suspect} = $fix;
968 }
969 close($spelling);
970 } else {
971 warn "No codespell typos will be found - file '$codespellfile': $!\n";
972 }
973}
974
975$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
976
75ad8c57
JF
977sub read_words {
978 my ($wordsRef, $file) = @_;
bf1fa1da 979
75ad8c57
JF
980 if (open(my $words, '<', $file)) {
981 while (<$words>) {
982 my $line = $_;
bf1fa1da 983
75ad8c57
JF
984 $line =~ s/\s*\n?$//g;
985 $line =~ s/^\s*//g;
bf1fa1da 986
75ad8c57
JF
987 next if ($line =~ m/^\s*#/);
988 next if ($line =~ m/^\s*$/);
989 if ($line =~ /\s/) {
990 print("$file: '$line' invalid - ignored\n");
991 next;
992 }
993
ced69da1 994 $$wordsRef .= '|' if (defined $$wordsRef);
75ad8c57
JF
995 $$wordsRef .= $line;
996 }
997 close($file);
998 return 1;
bf1fa1da 999 }
75ad8c57
JF
1000
1001 return 0;
1002}
1003
ced69da1
QM
1004my $const_structs;
1005if (show_type("CONST_STRUCT")) {
1006 read_words(\$const_structs, $conststructsfile)
1007 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1008}
75ad8c57 1009
ced69da1
QM
1010if (defined($typedefsfile)) {
1011 my $typeOtherTypedefs;
75ad8c57
JF
1012 read_words(\$typeOtherTypedefs, $typedefsfile)
1013 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
ced69da1 1014 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
bf1fa1da
JP
1015}
1016
8905a67c 1017sub build_types {
485ff23e
AD
1018 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1019 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1813087d 1020 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
8716de38 1021 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
c8cb2ca3 1022 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
ab7e23f3 1023 $BasicType = qr{
ab7e23f3
JP
1024 (?:$typeTypedefs\b)|
1025 (?:${all}\b)
1026 }x;
8905a67c 1027 $NonptrType = qr{
d2172eb5 1028 (?:$Modifier\s+|const\s+)*
cf655043 1029 (?:
6b48db24 1030 (?:typeof|__typeof__)\s*\([^\)]*\)|
8ed22cad 1031 (?:$typeTypedefs\b)|
c45dcabd 1032 (?:${all}\b)
cf655043 1033 )
c8cb2ca3 1034 (?:\s+$Modifier|\s+const)*
8905a67c 1035 }x;
1813087d
JP
1036 $NonptrTypeMisordered = qr{
1037 (?:$Modifier\s+|const\s+)*
1038 (?:
1039 (?:${Misordered}\b)
1040 )
1041 (?:\s+$Modifier|\s+const)*
1042 }x;
8716de38
JP
1043 $NonptrTypeWithAttr = qr{
1044 (?:$Modifier\s+|const\s+)*
1045 (?:
1046 (?:typeof|__typeof__)\s*\([^\)]*\)|
1047 (?:$typeTypedefs\b)|
1048 (?:${allWithAttr}\b)
1049 )
1050 (?:\s+$Modifier|\s+const)*
1051 }x;
8905a67c 1052 $Type = qr{
c45dcabd 1053 $NonptrType
7b18496c 1054 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
c8cb2ca3 1055 (?:\s+$Inline|\s+$Modifier)*
8905a67c 1056 }x;
1813087d
JP
1057 $TypeMisordered = qr{
1058 $NonptrTypeMisordered
7b18496c 1059 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1813087d
JP
1060 (?:\s+$Inline|\s+$Modifier)*
1061 }x;
91cb5195 1062 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1813087d 1063 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
8905a67c
AW
1064}
1065build_types();
6c72ffaa 1066
7d2367af 1067our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
d1fe9c09
JP
1068
1069# Using $balanced_parens, $LvalOrFunc, or $FuncArg
1070# requires at least perl version v5.10.0
1071# Any use must be runtime checked with $^V
1072
1073our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
2435880f 1074our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
c0a5c898 1075our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
7d2367af 1076
f8422308 1077our $declaration_macros = qr{(?x:
3e838b6c 1078 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
fe658f94 1079 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
dcea7964
JP
1080 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1081 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
f8422308
JP
1082)};
1083
8d0325cc
AS
1084our %allow_repeated_words = (
1085 add => '',
1086 added => '',
1087 bad => '',
1088 be => '',
1089);
1090
7d2367af
JP
1091sub deparenthesize {
1092 my ($string) = @_;
1093 return "" if (!defined($string));
5b9553ab
JP
1094
1095 while ($string =~ /^\s*\(.*\)\s*$/) {
1096 $string =~ s@^\s*\(\s*@@;
1097 $string =~ s@\s*\)\s*$@@;
1098 }
1099
7d2367af 1100 $string =~ s@\s+@ @g;
5b9553ab 1101
7d2367af
JP
1102 return $string;
1103}
1104
3445686a
JP
1105sub seed_camelcase_file {
1106 my ($file) = @_;
1107
1108 return if (!(-f $file));
1109
1110 local $/;
1111
1112 open(my $include_file, '<', "$file")
1113 or warn "$P: Can't read '$file' $!\n";
1114 my $text = <$include_file>;
1115 close($include_file);
1116
1117 my @lines = split('\n', $text);
1118
1119 foreach my $line (@lines) {
1120 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1121 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1122 $camelcase{$1} = 1;
11ea516a
JP
1123 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1124 $camelcase{$1} = 1;
1125 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
3445686a
JP
1126 $camelcase{$1} = 1;
1127 }
1128 }
1129}
1130
cd28b119
JP
1131our %maintained_status = ();
1132
85b0ee18
JP
1133sub is_maintained_obsolete {
1134 my ($filename) = @_;
1135
f2c19c2f 1136 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
85b0ee18 1137
cd28b119
JP
1138 if (!exists($maintained_status{$filename})) {
1139 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1140 }
85b0ee18 1141
cd28b119 1142 return $maintained_status{$filename} =~ /obsolete/i;
85b0ee18
JP
1143}
1144
3b6e8ac9
JP
1145sub is_SPDX_License_valid {
1146 my ($license) = @_;
1147
f9363b31 1148 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
3b6e8ac9 1149
56294112 1150 my $root_path = abs_path($root);
f9363b31 1151 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
3b6e8ac9
JP
1152 return 0 if ($status ne "");
1153 return 1;
1154}
1155
3445686a
JP
1156my $camelcase_seeded = 0;
1157sub seed_camelcase_includes {
1158 return if ($camelcase_seeded);
1159
1160 my $files;
c707a81d
JP
1161 my $camelcase_cache = "";
1162 my @include_files = ();
1163
1164 $camelcase_seeded = 1;
351b2a1f 1165
0f7f635b 1166 if (-e "$gitroot") {
dbbf869d 1167 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
351b2a1f 1168 chomp $git_last_include_commit;
c707a81d 1169 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
3445686a 1170 } else {
c707a81d 1171 my $last_mod_date = 0;
3445686a 1172 $files = `find $root/include -name "*.h"`;
c707a81d
JP
1173 @include_files = split('\n', $files);
1174 foreach my $file (@include_files) {
1175 my $date = POSIX::strftime("%Y%m%d%H%M",
1176 localtime((stat $file)[9]));
1177 $last_mod_date = $date if ($last_mod_date < $date);
1178 }
1179 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1180 }
1181
1182 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1183 open(my $camelcase_file, '<', "$camelcase_cache")
1184 or warn "$P: Can't read '$camelcase_cache' $!\n";
1185 while (<$camelcase_file>) {
1186 chomp;
1187 $camelcase{$_} = 1;
1188 }
1189 close($camelcase_file);
1190
1191 return;
3445686a 1192 }
c707a81d 1193
0f7f635b 1194 if (-e "$gitroot") {
dbbf869d 1195 $files = `${git_command} ls-files "include/*.h"`;
c707a81d
JP
1196 @include_files = split('\n', $files);
1197 }
1198
3445686a
JP
1199 foreach my $file (@include_files) {
1200 seed_camelcase_file($file);
1201 }
351b2a1f 1202
c707a81d 1203 if ($camelcase_cache ne "") {
351b2a1f 1204 unlink glob ".checkpatch-camelcase.*";
c707a81d
JP
1205 open(my $camelcase_file, '>', "$camelcase_cache")
1206 or warn "$P: Can't write '$camelcase_cache' $!\n";
351b2a1f
JP
1207 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1208 print $camelcase_file ("$_\n");
1209 }
1210 close($camelcase_file);
1211 }
3445686a
JP
1212}
1213
f5f61325
JP
1214sub git_is_single_file {
1215 my ($filename) = @_;
1216
1217 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1218
1219 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1220 my $count = $output =~ tr/\n//;
1221 return $count eq 1 && $output =~ m{^${filename}$};
1222}
1223
d311cd44
JP
1224sub git_commit_info {
1225 my ($commit, $id, $desc) = @_;
1226
0f7f635b 1227 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
d311cd44 1228
dbbf869d 1229 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
d311cd44
JP
1230 $output =~ s/^\s*//gm;
1231 my @lines = split("\n", $output);
1232
0d7835fc
JP
1233 return ($id, $desc) if ($#lines < 0);
1234
5a7f4455 1235 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
d311cd44
JP
1236# Maybe one day convert this block of bash into something that returns
1237# all matching commit ids, but it's very slow...
1238#
1239# echo "checking commits $1..."
1240# git rev-list --remotes | grep -i "^$1" |
1241# while read line ; do
1242# git log --format='%H %s' -1 $line |
1243# echo "commit $(cut -c 1-12,41-)"
1244# done
4ce9f970
JP
1245 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1246 $lines[0] =~ /^fatal: bad object $commit/) {
948b133a 1247 $id = undef;
d311cd44
JP
1248 } else {
1249 $id = substr($lines[0], 0, 12);
1250 $desc = substr($lines[0], 41);
1251 }
1252
1253 return ($id, $desc);
1254}
1255
6c72ffaa
AW
1256$chk_signoff = 0 if ($file);
1257
00df344f 1258my @rawlines = ();
c2fdda0d 1259my @lines = ();
3705ce5b 1260my @fixed = ();
d752fcc8
JP
1261my @fixed_inserted = ();
1262my @fixed_deleted = ();
194f66fc
JP
1263my $fixlinenr = -1;
1264
4a593c34
DC
1265# If input is git commits, extract all commits from the commit expressions.
1266# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
0f7f635b 1267die "$P: No git repository found\n" if ($git && !-e "$gitroot");
4a593c34
DC
1268
1269if ($git) {
1270 my @commits = ();
0dea9f1e 1271 foreach my $commit_expr (@ARGV) {
4a593c34 1272 my $git_range;
28898fd1
JP
1273 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1274 $git_range = "-$2 $1";
4a593c34
DC
1275 } elsif ($commit_expr =~ m/\.\./) {
1276 $git_range = "$commit_expr";
4a593c34 1277 } else {
0dea9f1e
JP
1278 $git_range = "-1 $commit_expr";
1279 }
dbbf869d 1280 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
0dea9f1e 1281 foreach my $line (split(/\n/, $lines)) {
28898fd1
JP
1282 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1283 next if (!defined($1) || !defined($2));
0dea9f1e
JP
1284 my $sha1 = $1;
1285 my $subject = $2;
1286 unshift(@commits, $sha1);
1287 $git_commits{$sha1} = $subject;
4a593c34
DC
1288 }
1289 }
1290 die "$P: no git commits after extraction!\n" if (@commits == 0);
1291 @ARGV = @commits;
1292}
1293
c2fdda0d 1294my $vname;
98005e8c 1295$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
6c72ffaa 1296for my $filename (@ARGV) {
21caa13c 1297 my $FILE;
f5f61325
JP
1298 my $is_git_file = git_is_single_file($filename);
1299 my $oldfile = $file;
1300 $file = 1 if ($is_git_file);
4a593c34
DC
1301 if ($git) {
1302 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1303 die "$P: $filename: git format-patch failed - $!\n";
1304 } elsif ($file) {
21caa13c 1305 open($FILE, '-|', "diff -u /dev/null $filename") ||
6c72ffaa 1306 die "$P: $filename: diff failed - $!\n";
21caa13c
AW
1307 } elsif ($filename eq '-') {
1308 open($FILE, '<&STDIN');
6c72ffaa 1309 } else {
21caa13c 1310 open($FILE, '<', "$filename") ||
6c72ffaa 1311 die "$P: $filename: open failed - $!\n";
0a920b5b 1312 }
c2fdda0d
AW
1313 if ($filename eq '-') {
1314 $vname = 'Your patch';
4a593c34 1315 } elsif ($git) {
0dea9f1e 1316 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
c2fdda0d
AW
1317 } else {
1318 $vname = $filename;
1319 }
21caa13c 1320 while (<$FILE>) {
6c72ffaa
AW
1321 chomp;
1322 push(@rawlines, $_);
c7f574d0 1323 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
6c72ffaa 1324 }
21caa13c 1325 close($FILE);
d8469f16
JP
1326
1327 if ($#ARGV > 0 && $quiet == 0) {
1328 print '-' x length($vname) . "\n";
1329 print "$vname\n";
1330 print '-' x length($vname) . "\n";
1331 }
1332
c2fdda0d 1333 if (!process($filename)) {
6c72ffaa
AW
1334 $exit = 1;
1335 }
1336 @rawlines = ();
13214adf 1337 @lines = ();
3705ce5b 1338 @fixed = ();
d752fcc8
JP
1339 @fixed_inserted = ();
1340 @fixed_deleted = ();
194f66fc 1341 $fixlinenr = -1;
485ff23e
AD
1342 @modifierListFile = ();
1343 @typeListFile = ();
1344 build_types();
f5f61325 1345 $file = $oldfile if ($is_git_file);
0a920b5b
AW
1346}
1347
d8469f16 1348if (!$quiet) {
3c816e49
JP
1349 hash_show_words(\%use_type, "Used");
1350 hash_show_words(\%ignore_type, "Ignored");
1351
5b57980d 1352 if (!$perl_version_ok) {
d8469f16
JP
1353 print << "EOM"
1354
1355NOTE: perl $^V is not modern enough to detect all possible issues.
5b57980d 1356 An upgrade to at least perl $minimum_perl_version is suggested.
d8469f16
JP
1357EOM
1358 }
1359 if ($exit) {
1360 print << "EOM"
1361
1362NOTE: If any of the errors are false positives, please report
1363 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1364EOM
1365 }
1366}
1367
0a920b5b
AW
1368exit($exit);
1369
1370sub top_of_kernel_tree {
6c72ffaa
AW
1371 my ($root) = @_;
1372
1373 my @tree_check = (
1374 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1375 "README", "Documentation", "arch", "include", "drivers",
1376 "fs", "init", "ipc", "kernel", "lib", "scripts",
1377 );
1378
1379 foreach my $check (@tree_check) {
1380 if (! -e $root . '/' . $check) {
1381 return 0;
1382 }
0a920b5b 1383 }
6c72ffaa 1384 return 1;
8f26b837 1385}
0a920b5b 1386
20112475
JP
1387sub parse_email {
1388 my ($formatted_email) = @_;
1389
1390 my $name = "";
fccaebf0 1391 my $quoted = "";
dfa05c28 1392 my $name_comment = "";
20112475
JP
1393 my $address = "";
1394 my $comment = "";
1395
1396 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1397 $name = $1;
1398 $address = $2;
1399 $comment = $3 if defined $3;
1400 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1401 $address = $1;
1402 $comment = $2 if defined $2;
1403 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1404 $address = $1;
1405 $comment = $2 if defined $2;
85e12066 1406 $formatted_email =~ s/\Q$address\E.*$//;
20112475 1407 $name = $formatted_email;
3705ce5b 1408 $name = trim($name);
20112475
JP
1409 $name =~ s/^\"|\"$//g;
1410 # If there's a name left after stripping spaces and
1411 # leading quotes, and the address doesn't have both
1412 # leading and trailing angle brackets, the address
1413 # is invalid. ie:
1414 # "joe smith joe@smith.com" bad
1415 # "joe smith <joe@smith.com" bad
1416 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1417 $name = "";
1418 $address = "";
1419 $comment = "";
1420 }
1421 }
1422
fccaebf0
DR
1423 # Extract comments from names excluding quoted parts
1424 # "John D. (Doe)" - Do not extract
1425 if ($name =~ s/\"(.+)\"//) {
1426 $quoted = $1;
1427 }
1428 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1429 $name_comment .= trim($1);
dfa05c28 1430 }
fccaebf0
DR
1431 $name =~ s/^[ \"]+|[ \"]+$//g;
1432 $name = trim("$quoted $name");
1433
3705ce5b 1434 $address = trim($address);
20112475 1435 $address =~ s/^\<|\>$//g;
fccaebf0 1436 $comment = trim($comment);
20112475
JP
1437
1438 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1439 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1440 $name = "\"$name\"";
1441 }
1442
dfa05c28 1443 return ($name, $name_comment, $address, $comment);
20112475
JP
1444}
1445
1446sub format_email {
48ca2d8a 1447 my ($name, $name_comment, $address, $comment) = @_;
20112475
JP
1448
1449 my $formatted_email;
1450
fccaebf0 1451 $name =~ s/^[ \"]+|[ \"]+$//g;
3705ce5b 1452 $address = trim($address);
fccaebf0 1453 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
20112475
JP
1454
1455 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1456 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1457 $name = "\"$name\"";
1458 }
1459
fccaebf0
DR
1460 $name_comment = trim($name_comment);
1461 $name_comment = " $name_comment" if ($name_comment ne "");
1462 $comment = trim($comment);
1463 $comment = " $comment" if ($comment ne "");
1464
20112475
JP
1465 if ("$name" eq "") {
1466 $formatted_email = "$address";
1467 } else {
48ca2d8a 1468 $formatted_email = "$name$name_comment <$address>";
20112475 1469 }
48ca2d8a 1470 $formatted_email .= "$comment";
20112475
JP
1471 return $formatted_email;
1472}
1473
dfa05c28
JP
1474sub reformat_email {
1475 my ($email) = @_;
1476
1477 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
48ca2d8a 1478 return format_email($email_name, $name_comment, $email_address, $comment);
dfa05c28
JP
1479}
1480
1481sub same_email_addresses {
fccaebf0 1482 my ($email1, $email2) = @_;
dfa05c28
JP
1483
1484 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1485 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1486
1487 return $email1_name eq $email2_name &&
48ca2d8a
DR
1488 $email1_address eq $email2_address &&
1489 $name1_comment eq $name2_comment &&
1490 $comment1 eq $comment2;
dfa05c28
JP
1491}
1492
d311cd44 1493sub which {
bd474ca0 1494 my ($bin) = @_;
d311cd44 1495
bd474ca0
JP
1496 foreach my $path (split(/:/, $ENV{PATH})) {
1497 if (-e "$path/$bin") {
1498 return "$path/$bin";
1499 }
d311cd44 1500 }
d311cd44 1501
bd474ca0 1502 return "";
d311cd44
JP
1503}
1504
000d1cc1
JP
1505sub which_conf {
1506 my ($conf) = @_;
1507
1508 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1509 if (-e "$path/$conf") {
1510 return "$path/$conf";
1511 }
1512 }
1513
1514 return "";
1515}
1516
0a920b5b
AW
1517sub expand_tabs {
1518 my ($str) = @_;
1519
1520 my $res = '';
1521 my $n = 0;
1522 for my $c (split(//, $str)) {
1523 if ($c eq "\t") {
1524 $res .= ' ';
1525 $n++;
713a09de 1526 for (; ($n % $tabsize) != 0; $n++) {
0a920b5b
AW
1527 $res .= ' ';
1528 }
1529 next;
1530 }
1531 $res .= $c;
1532 $n++;
1533 }
1534
1535 return $res;
1536}
6c72ffaa 1537sub copy_spacing {
773647a0 1538 (my $res = shift) =~ tr/\t/ /c;
6c72ffaa
AW
1539 return $res;
1540}
0a920b5b 1541
4a0df2ef
AW
1542sub line_stats {
1543 my ($line) = @_;
1544
1545 # Drop the diff line leader and expand tabs
1546 $line =~ s/^.//;
1547 $line = expand_tabs($line);
1548
1549 # Pick the indent from the front of the line.
1550 my ($white) = ($line =~ /^(\s*)/);
1551
1552 return (length($line), length($white));
1553}
1554
773647a0
AW
1555my $sanitise_quote = '';
1556
1557sub sanitise_line_reset {
1558 my ($in_comment) = @_;
1559
1560 if ($in_comment) {
1561 $sanitise_quote = '*/';
1562 } else {
1563 $sanitise_quote = '';
1564 }
1565}
00df344f
AW
1566sub sanitise_line {
1567 my ($line) = @_;
1568
1569 my $res = '';
1570 my $l = '';
1571
c2fdda0d 1572 my $qlen = 0;
773647a0
AW
1573 my $off = 0;
1574 my $c;
00df344f 1575
773647a0
AW
1576 # Always copy over the diff marker.
1577 $res = substr($line, 0, 1);
1578
1579 for ($off = 1; $off < length($line); $off++) {
1580 $c = substr($line, $off, 1);
1581
8d2e11b2 1582 # Comments we are whacking completely including the begin
773647a0
AW
1583 # and end, all to $;.
1584 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1585 $sanitise_quote = '*/';
1586
1587 substr($res, $off, 2, "$;$;");
1588 $off++;
1589 next;
00df344f 1590 }
81bc0e02 1591 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
773647a0
AW
1592 $sanitise_quote = '';
1593 substr($res, $off, 2, "$;$;");
1594 $off++;
1595 next;
c2fdda0d 1596 }
113f04a8
DW
1597 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1598 $sanitise_quote = '//';
1599
1600 substr($res, $off, 2, $sanitise_quote);
1601 $off++;
1602 next;
1603 }
773647a0
AW
1604
1605 # A \ in a string means ignore the next character.
1606 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1607 $c eq "\\") {
1608 substr($res, $off, 2, 'XX');
1609 $off++;
1610 next;
00df344f 1611 }
773647a0
AW
1612 # Regular quotes.
1613 if ($c eq "'" || $c eq '"') {
1614 if ($sanitise_quote eq '') {
1615 $sanitise_quote = $c;
00df344f 1616
773647a0
AW
1617 substr($res, $off, 1, $c);
1618 next;
1619 } elsif ($sanitise_quote eq $c) {
1620 $sanitise_quote = '';
1621 }
1622 }
00df344f 1623
fae17dae 1624 #print "c<$c> SQ<$sanitise_quote>\n";
773647a0
AW
1625 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1626 substr($res, $off, 1, $;);
113f04a8
DW
1627 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1628 substr($res, $off, 1, $;);
773647a0
AW
1629 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1630 substr($res, $off, 1, 'X');
1631 } else {
1632 substr($res, $off, 1, $c);
1633 }
c2fdda0d
AW
1634 }
1635
113f04a8
DW
1636 if ($sanitise_quote eq '//') {
1637 $sanitise_quote = '';
1638 }
1639
c2fdda0d 1640 # The pathname on a #include may be surrounded by '<' and '>'.
c45dcabd 1641 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
c2fdda0d
AW
1642 my $clean = 'X' x length($1);
1643 $res =~ s@\<.*\>@<$clean>@;
1644
1645 # The whole of a #error is a string.
c45dcabd 1646 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
c2fdda0d 1647 my $clean = 'X' x length($1);
c45dcabd 1648 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
c2fdda0d
AW
1649 }
1650
dadf680d
JP
1651 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1652 my $match = $1;
1653 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1654 }
1655
00df344f
AW
1656 return $res;
1657}
1658
a6962d72
JP
1659sub get_quoted_string {
1660 my ($line, $rawline) = @_;
1661
478b1799 1662 return "" if (!defined($line) || !defined($rawline));
33acb54a 1663 return "" if ($line !~ m/($String)/g);
a6962d72
JP
1664 return substr($rawline, $-[0], $+[0] - $-[0]);
1665}
1666
8905a67c
AW
1667sub ctx_statement_block {
1668 my ($linenr, $remain, $off) = @_;
1669 my $line = $linenr - 1;
1670 my $blk = '';
1671 my $soff = $off;
1672 my $coff = $off - 1;
773647a0 1673 my $coff_set = 0;
8905a67c 1674
13214adf
AW
1675 my $loff = 0;
1676
8905a67c
AW
1677 my $type = '';
1678 my $level = 0;
a2750645 1679 my @stack = ();
cf655043 1680 my $p;
8905a67c
AW
1681 my $c;
1682 my $len = 0;
13214adf
AW
1683
1684 my $remainder;
8905a67c 1685 while (1) {
a2750645
AW
1686 @stack = (['', 0]) if ($#stack == -1);
1687
773647a0 1688 #warn "CSB: blk<$blk> remain<$remain>\n";
8905a67c
AW
1689 # If we are about to drop off the end, pull in more
1690 # context.
1691 if ($off >= $len) {
1692 for (; $remain > 0; $line++) {
dea33496 1693 last if (!defined $lines[$line]);
c2fdda0d 1694 next if ($lines[$line] =~ /^-/);
8905a67c 1695 $remain--;
13214adf 1696 $loff = $len;
c2fdda0d 1697 $blk .= $lines[$line] . "\n";
8905a67c
AW
1698 $len = length($blk);
1699 $line++;
1700 last;
1701 }
1702 # Bail if there is no further context.
1703 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
13214adf 1704 if ($off >= $len) {
8905a67c
AW
1705 last;
1706 }
f74bd194
AW
1707 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1708 $level++;
1709 $type = '#';
1710 }
8905a67c 1711 }
cf655043 1712 $p = $c;
8905a67c 1713 $c = substr($blk, $off, 1);
13214adf 1714 $remainder = substr($blk, $off);
8905a67c 1715
773647a0 1716 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
4635f4fb
AW
1717
1718 # Handle nested #if/#else.
1719 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1720 push(@stack, [ $type, $level ]);
1721 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1722 ($type, $level) = @{$stack[$#stack - 1]};
1723 } elsif ($remainder =~ /^#\s*endif\b/) {
1724 ($type, $level) = @{pop(@stack)};
1725 }
1726
8905a67c
AW
1727 # Statement ends at the ';' or a close '}' at the
1728 # outermost level.
1729 if ($level == 0 && $c eq ';') {
1730 last;
1731 }
1732
13214adf 1733 # An else is really a conditional as long as its not else if
773647a0
AW
1734 if ($level == 0 && $coff_set == 0 &&
1735 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1736 $remainder =~ /^(else)(?:\s|{)/ &&
1737 $remainder !~ /^else\s+if\b/) {
1738 $coff = $off + length($1) - 1;
1739 $coff_set = 1;
1740 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1741 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
13214adf
AW
1742 }
1743
8905a67c
AW
1744 if (($type eq '' || $type eq '(') && $c eq '(') {
1745 $level++;
1746 $type = '(';
1747 }
1748 if ($type eq '(' && $c eq ')') {
1749 $level--;
1750 $type = ($level != 0)? '(' : '';
1751
1752 if ($level == 0 && $coff < $soff) {
1753 $coff = $off;
773647a0
AW
1754 $coff_set = 1;
1755 #warn "CSB: mark coff<$coff>\n";
8905a67c
AW
1756 }
1757 }
1758 if (($type eq '' || $type eq '{') && $c eq '{') {
1759 $level++;
1760 $type = '{';
1761 }
1762 if ($type eq '{' && $c eq '}') {
1763 $level--;
1764 $type = ($level != 0)? '{' : '';
1765
1766 if ($level == 0) {
b998e001
PP
1767 if (substr($blk, $off + 1, 1) eq ';') {
1768 $off++;
1769 }
8905a67c
AW
1770 last;
1771 }
1772 }
f74bd194
AW
1773 # Preprocessor commands end at the newline unless escaped.
1774 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1775 $level--;
1776 $type = '';
1777 $off++;
1778 last;
1779 }
8905a67c
AW
1780 $off++;
1781 }
a3bb97a7 1782 # We are truly at the end, so shuffle to the next line.
13214adf 1783 if ($off == $len) {
a3bb97a7 1784 $loff = $len + 1;
13214adf
AW
1785 $line++;
1786 $remain--;
1787 }
8905a67c
AW
1788
1789 my $statement = substr($blk, $soff, $off - $soff + 1);
1790 my $condition = substr($blk, $soff, $coff - $soff + 1);
1791
1792 #warn "STATEMENT<$statement>\n";
1793 #warn "CONDITION<$condition>\n";
1794
773647a0 1795 #print "coff<$coff> soff<$off> loff<$loff>\n";
13214adf
AW
1796
1797 return ($statement, $condition,
1798 $line, $remain + 1, $off - $loff + 1, $level);
1799}
1800
cf655043
AW
1801sub statement_lines {
1802 my ($stmt) = @_;
1803
1804 # Strip the diff line prefixes and rip blank lines at start and end.
1805 $stmt =~ s/(^|\n)./$1/g;
1806 $stmt =~ s/^\s*//;
1807 $stmt =~ s/\s*$//;
1808
1809 my @stmt_lines = ($stmt =~ /\n/g);
1810
1811 return $#stmt_lines + 2;
1812}
1813
1814sub statement_rawlines {
1815 my ($stmt) = @_;
1816
1817 my @stmt_lines = ($stmt =~ /\n/g);
1818
1819 return $#stmt_lines + 2;
1820}
1821
1822sub statement_block_size {
1823 my ($stmt) = @_;
1824
1825 $stmt =~ s/(^|\n)./$1/g;
1826 $stmt =~ s/^\s*{//;
1827 $stmt =~ s/}\s*$//;
1828 $stmt =~ s/^\s*//;
1829 $stmt =~ s/\s*$//;
1830
1831 my @stmt_lines = ($stmt =~ /\n/g);
1832 my @stmt_statements = ($stmt =~ /;/g);
1833
1834 my $stmt_lines = $#stmt_lines + 2;
1835 my $stmt_statements = $#stmt_statements + 1;
1836
1837 if ($stmt_lines > $stmt_statements) {
1838 return $stmt_lines;
1839 } else {
1840 return $stmt_statements;
1841 }
1842}
1843
13214adf
AW
1844sub ctx_statement_full {
1845 my ($linenr, $remain, $off) = @_;
1846 my ($statement, $condition, $level);
1847
1848 my (@chunks);
1849
cf655043 1850 # Grab the first conditional/block pair.
13214adf
AW
1851 ($statement, $condition, $linenr, $remain, $off, $level) =
1852 ctx_statement_block($linenr, $remain, $off);
773647a0 1853 #print "F: c<$condition> s<$statement> remain<$remain>\n";
cf655043
AW
1854 push(@chunks, [ $condition, $statement ]);
1855 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1856 return ($level, $linenr, @chunks);
1857 }
1858
1859 # Pull in the following conditional/block pairs and see if they
1860 # could continue the statement.
13214adf 1861 for (;;) {
13214adf
AW
1862 ($statement, $condition, $linenr, $remain, $off, $level) =
1863 ctx_statement_block($linenr, $remain, $off);
cf655043 1864 #print "C: c<$condition> s<$statement> remain<$remain>\n";
773647a0 1865 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
cf655043
AW
1866 #print "C: push\n";
1867 push(@chunks, [ $condition, $statement ]);
13214adf
AW
1868 }
1869
1870 return ($level, $linenr, @chunks);
8905a67c
AW
1871}
1872
4a0df2ef 1873sub ctx_block_get {
f0a594c1 1874 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
4a0df2ef
AW
1875 my $line;
1876 my $start = $linenr - 1;
4a0df2ef
AW
1877 my $blk = '';
1878 my @o;
1879 my @c;
1880 my @res = ();
1881
f0a594c1 1882 my $level = 0;
4635f4fb 1883 my @stack = ($level);
00df344f
AW
1884 for ($line = $start; $remain > 0; $line++) {
1885 next if ($rawlines[$line] =~ /^-/);
1886 $remain--;
1887
1888 $blk .= $rawlines[$line];
4635f4fb
AW
1889
1890 # Handle nested #if/#else.
01464f30 1891 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
4635f4fb 1892 push(@stack, $level);
01464f30 1893 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
4635f4fb 1894 $level = $stack[$#stack - 1];
01464f30 1895 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
4635f4fb
AW
1896 $level = pop(@stack);
1897 }
1898
01464f30 1899 foreach my $c (split(//, $lines[$line])) {
f0a594c1
AW
1900 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1901 if ($off > 0) {
1902 $off--;
1903 next;
1904 }
4a0df2ef 1905
f0a594c1
AW
1906 if ($c eq $close && $level > 0) {
1907 $level--;
1908 last if ($level == 0);
1909 } elsif ($c eq $open) {
1910 $level++;
1911 }
1912 }
4a0df2ef 1913
f0a594c1 1914 if (!$outer || $level <= 1) {
00df344f 1915 push(@res, $rawlines[$line]);
4a0df2ef
AW
1916 }
1917
f0a594c1 1918 last if ($level == 0);
4a0df2ef
AW
1919 }
1920
f0a594c1 1921 return ($level, @res);
4a0df2ef
AW
1922}
1923sub ctx_block_outer {
1924 my ($linenr, $remain) = @_;
1925
f0a594c1
AW
1926 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1927 return @r;
4a0df2ef
AW
1928}
1929sub ctx_block {
1930 my ($linenr, $remain) = @_;
1931
f0a594c1
AW
1932 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1933 return @r;
653d4876
AW
1934}
1935sub ctx_statement {
f0a594c1
AW
1936 my ($linenr, $remain, $off) = @_;
1937
1938 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1939 return @r;
1940}
1941sub ctx_block_level {
653d4876
AW
1942 my ($linenr, $remain) = @_;
1943
f0a594c1 1944 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
4a0df2ef 1945}
9c0ca6f9
AW
1946sub ctx_statement_level {
1947 my ($linenr, $remain, $off) = @_;
1948
1949 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1950}
4a0df2ef
AW
1951
1952sub ctx_locate_comment {
1953 my ($first_line, $end_line) = @_;
1954
a55ee0cc
JP
1955 # If c99 comment on the current line, or the line before or after
1956 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1957 return $current_comment if (defined $current_comment);
1958 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1959 return $current_comment if (defined $current_comment);
1960 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1961 return $current_comment if (defined $current_comment);
1962
4a0df2ef 1963 # Catch a comment on the end of the line itself.
a55ee0cc 1964 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
4a0df2ef
AW
1965 return $current_comment if (defined $current_comment);
1966
1967 # Look through the context and try and figure out if there is a
1968 # comment.
1969 my $in_comment = 0;
1970 $current_comment = '';
1971 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
00df344f
AW
1972 my $line = $rawlines[$linenr - 1];
1973 #warn " $line\n";
4a0df2ef
AW
1974 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1975 $in_comment = 1;
1976 }
1977 if ($line =~ m@/\*@) {
1978 $in_comment = 1;
1979 }
1980 if (!$in_comment && $current_comment ne '') {
1981 $current_comment = '';
1982 }
1983 $current_comment .= $line . "\n" if ($in_comment);
1984 if ($line =~ m@\*/@) {
1985 $in_comment = 0;
1986 }
1987 }
1988
1989 chomp($current_comment);
1990 return($current_comment);
1991}
1992sub ctx_has_comment {
1993 my ($first_line, $end_line) = @_;
1994 my $cmt = ctx_locate_comment($first_line, $end_line);
1995
00df344f 1996 ##print "LINE: $rawlines[$end_line - 1 ]\n";
4a0df2ef
AW
1997 ##print "CMMT: $cmt\n";
1998
1999 return ($cmt ne '');
2000}
2001
4d001e4d
AW
2002sub raw_line {
2003 my ($linenr, $cnt) = @_;
2004
2005 my $offset = $linenr - 1;
2006 $cnt++;
2007
2008 my $line;
2009 while ($cnt) {
2010 $line = $rawlines[$offset++];
2011 next if (defined($line) && $line =~ /^-/);
2012 $cnt--;
2013 }
2014
2015 return $line;
2016}
2017
2a9f9d85
TH
2018sub get_stat_real {
2019 my ($linenr, $lc) = @_;
2020
2021 my $stat_real = raw_line($linenr, 0);
2022 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2023 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2024 }
2025
2026 return $stat_real;
2027}
2028
e3d95a2a
TH
2029sub get_stat_here {
2030 my ($linenr, $cnt, $here) = @_;
2031
2032 my $herectx = $here . "\n";
2033 for (my $n = 0; $n < $cnt; $n++) {
2034 $herectx .= raw_line($linenr, $n) . "\n";
2035 }
2036
2037 return $herectx;
2038}
2039
6c72ffaa
AW
2040sub cat_vet {
2041 my ($vet) = @_;
2042 my ($res, $coded);
9c0ca6f9 2043
6c72ffaa
AW
2044 $res = '';
2045 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2046 $res .= $1;
2047 if ($2 ne '') {
2048 $coded = sprintf("^%c", unpack('C', $2) + 64);
2049 $res .= $coded;
9c0ca6f9
AW
2050 }
2051 }
6c72ffaa 2052 $res =~ s/$/\$/;
9c0ca6f9 2053
6c72ffaa 2054 return $res;
9c0ca6f9
AW
2055}
2056
c2fdda0d 2057my $av_preprocessor = 0;
cf655043 2058my $av_pending;
c2fdda0d 2059my @av_paren_type;
1f65f947 2060my $av_pend_colon;
c2fdda0d
AW
2061
2062sub annotate_reset {
2063 $av_preprocessor = 0;
cf655043
AW
2064 $av_pending = '_';
2065 @av_paren_type = ('E');
1f65f947 2066 $av_pend_colon = 'O';
c2fdda0d
AW
2067}
2068
6c72ffaa
AW
2069sub annotate_values {
2070 my ($stream, $type) = @_;
0a920b5b 2071
6c72ffaa 2072 my $res;
1f65f947 2073 my $var = '_' x length($stream);
6c72ffaa
AW
2074 my $cur = $stream;
2075
c2fdda0d 2076 print "$stream\n" if ($dbg_values > 1);
6c72ffaa 2077
6c72ffaa 2078 while (length($cur)) {
773647a0 2079 @av_paren_type = ('E') if ($#av_paren_type < 0);
cf655043 2080 print " <" . join('', @av_paren_type) .
171ae1a4 2081 "> <$type> <$av_pending>" if ($dbg_values > 1);
6c72ffaa 2082 if ($cur =~ /^(\s+)/o) {
c2fdda0d
AW
2083 print "WS($1)\n" if ($dbg_values > 1);
2084 if ($1 =~ /\n/ && $av_preprocessor) {
cf655043 2085 $type = pop(@av_paren_type);
c2fdda0d 2086 $av_preprocessor = 0;
6c72ffaa
AW
2087 }
2088
c023e473 2089 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
9446ef56
AW
2090 print "CAST($1)\n" if ($dbg_values > 1);
2091 push(@av_paren_type, $type);
addcdcea 2092 $type = 'c';
9446ef56 2093
e91b6e26 2094 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
c2fdda0d 2095 print "DECLARE($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2096 $type = 'T';
2097
389a2fe5
AW
2098 } elsif ($cur =~ /^($Modifier)\s*/) {
2099 print "MODIFIER($1)\n" if ($dbg_values > 1);
2100 $type = 'T';
2101
c45dcabd 2102 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
171ae1a4 2103 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
c2fdda0d 2104 $av_preprocessor = 1;
171ae1a4
AW
2105 push(@av_paren_type, $type);
2106 if ($2 ne '') {
2107 $av_pending = 'N';
2108 }
2109 $type = 'E';
2110
c45dcabd 2111 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
171ae1a4
AW
2112 print "UNDEF($1)\n" if ($dbg_values > 1);
2113 $av_preprocessor = 1;
2114 push(@av_paren_type, $type);
6c72ffaa 2115
c45dcabd 2116 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
cf655043 2117 print "PRE_START($1)\n" if ($dbg_values > 1);
c2fdda0d 2118 $av_preprocessor = 1;
cf655043
AW
2119
2120 push(@av_paren_type, $type);
2121 push(@av_paren_type, $type);
171ae1a4 2122 $type = 'E';
cf655043 2123
c45dcabd 2124 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
cf655043
AW
2125 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2126 $av_preprocessor = 1;
2127
2128 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2129
171ae1a4 2130 $type = 'E';
cf655043 2131
c45dcabd 2132 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
cf655043
AW
2133 print "PRE_END($1)\n" if ($dbg_values > 1);
2134
2135 $av_preprocessor = 1;
2136
2137 # Assume all arms of the conditional end as this
2138 # one does, and continue as if the #endif was not here.
2139 pop(@av_paren_type);
2140 push(@av_paren_type, $type);
171ae1a4 2141 $type = 'E';
6c72ffaa
AW
2142
2143 } elsif ($cur =~ /^(\\\n)/o) {
c2fdda0d 2144 print "PRECONT($1)\n" if ($dbg_values > 1);
6c72ffaa 2145
171ae1a4
AW
2146 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2147 print "ATTR($1)\n" if ($dbg_values > 1);
2148 $av_pending = $type;
2149 $type = 'N';
2150
6c72ffaa 2151 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
c2fdda0d 2152 print "SIZEOF($1)\n" if ($dbg_values > 1);
6c72ffaa 2153 if (defined $2) {
cf655043 2154 $av_pending = 'V';
6c72ffaa
AW
2155 }
2156 $type = 'N';
2157
14b111c1 2158 } elsif ($cur =~ /^(if|while|for)\b/o) {
c2fdda0d 2159 print "COND($1)\n" if ($dbg_values > 1);
14b111c1 2160 $av_pending = 'E';
6c72ffaa
AW
2161 $type = 'N';
2162
1f65f947
AW
2163 } elsif ($cur =~/^(case)/o) {
2164 print "CASE($1)\n" if ($dbg_values > 1);
2165 $av_pend_colon = 'C';
2166 $type = 'N';
2167
14b111c1 2168 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
c2fdda0d 2169 print "KEYWORD($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2170 $type = 'N';
2171
2172 } elsif ($cur =~ /^(\()/o) {
c2fdda0d 2173 print "PAREN('$1')\n" if ($dbg_values > 1);
cf655043
AW
2174 push(@av_paren_type, $av_pending);
2175 $av_pending = '_';
6c72ffaa
AW
2176 $type = 'N';
2177
2178 } elsif ($cur =~ /^(\))/o) {
cf655043
AW
2179 my $new_type = pop(@av_paren_type);
2180 if ($new_type ne '_') {
2181 $type = $new_type;
c2fdda0d
AW
2182 print "PAREN('$1') -> $type\n"
2183 if ($dbg_values > 1);
6c72ffaa 2184 } else {
c2fdda0d 2185 print "PAREN('$1')\n" if ($dbg_values > 1);
6c72ffaa
AW
2186 }
2187
c8cb2ca3 2188 } elsif ($cur =~ /^($Ident)\s*\(/o) {
c2fdda0d 2189 print "FUNC($1)\n" if ($dbg_values > 1);
c8cb2ca3 2190 $type = 'V';
cf655043 2191 $av_pending = 'V';
6c72ffaa 2192
8e761b04
AW
2193 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2194 if (defined $2 && $type eq 'C' || $type eq 'T') {
1f65f947 2195 $av_pend_colon = 'B';
8e761b04
AW
2196 } elsif ($type eq 'E') {
2197 $av_pend_colon = 'L';
1f65f947
AW
2198 }
2199 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2200 $type = 'V';
2201
6c72ffaa 2202 } elsif ($cur =~ /^($Ident|$Constant)/o) {
c2fdda0d 2203 print "IDENT($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2204 $type = 'V';
2205
2206 } elsif ($cur =~ /^($Assignment)/o) {
c2fdda0d 2207 print "ASSIGN($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2208 $type = 'N';
2209
cf655043 2210 } elsif ($cur =~/^(;|{|})/) {
c2fdda0d 2211 print "END($1)\n" if ($dbg_values > 1);
13214adf 2212 $type = 'E';
1f65f947
AW
2213 $av_pend_colon = 'O';
2214
8e761b04
AW
2215 } elsif ($cur =~/^(,)/) {
2216 print "COMMA($1)\n" if ($dbg_values > 1);
2217 $type = 'C';
2218
1f65f947
AW
2219 } elsif ($cur =~ /^(\?)/o) {
2220 print "QUESTION($1)\n" if ($dbg_values > 1);
2221 $type = 'N';
2222
2223 } elsif ($cur =~ /^(:)/o) {
2224 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2225
2226 substr($var, length($res), 1, $av_pend_colon);
2227 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2228 $type = 'E';
2229 } else {
2230 $type = 'N';
2231 }
2232 $av_pend_colon = 'O';
13214adf 2233
8e761b04 2234 } elsif ($cur =~ /^(\[)/o) {
13214adf 2235 print "CLOSE($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2236 $type = 'N';
2237
0d413866 2238 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
74048ed8
AW
2239 my $variant;
2240
2241 print "OPV($1)\n" if ($dbg_values > 1);
2242 if ($type eq 'V') {
2243 $variant = 'B';
2244 } else {
2245 $variant = 'U';
2246 }
2247
2248 substr($var, length($res), 1, $variant);
2249 $type = 'N';
2250
6c72ffaa 2251 } elsif ($cur =~ /^($Operators)/o) {
c2fdda0d 2252 print "OP($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2253 if ($1 ne '++' && $1 ne '--') {
2254 $type = 'N';
2255 }
2256
2257 } elsif ($cur =~ /(^.)/o) {
c2fdda0d 2258 print "C($1)\n" if ($dbg_values > 1);
6c72ffaa
AW
2259 }
2260 if (defined $1) {
2261 $cur = substr($cur, length($1));
2262 $res .= $type x length($1);
2263 }
9c0ca6f9 2264 }
0a920b5b 2265
1f65f947 2266 return ($res, $var);
0a920b5b
AW
2267}
2268
8905a67c 2269sub possible {
13214adf 2270 my ($possible, $line) = @_;
9a974fdb 2271 my $notPermitted = qr{(?:
0776e594
AW
2272 ^(?:
2273 $Modifier|
2274 $Storage|
2275 $Type|
9a974fdb
AW
2276 DEFINE_\S+
2277 )$|
2278 ^(?:
0776e594
AW
2279 goto|
2280 return|
2281 case|
2282 else|
2283 asm|__asm__|
89a88353
AW
2284 do|
2285 \#|
2286 \#\#|
9a974fdb 2287 )(?:\s|$)|
0776e594 2288 ^(?:typedef|struct|enum)\b
9a974fdb
AW
2289 )}x;
2290 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2291 if ($possible !~ $notPermitted) {
c45dcabd
AW
2292 # Check for modifiers.
2293 $possible =~ s/\s*$Storage\s*//g;
2294 $possible =~ s/\s*$Sparse\s*//g;
2295 if ($possible =~ /^\s*$/) {
2296
2297 } elsif ($possible =~ /\s/) {
2298 $possible =~ s/\s*$Type\s*//g;
d2506586 2299 for my $modifier (split(' ', $possible)) {
9a974fdb
AW
2300 if ($modifier !~ $notPermitted) {
2301 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
485ff23e 2302 push(@modifierListFile, $modifier);
9a974fdb 2303 }
d2506586 2304 }
c45dcabd
AW
2305
2306 } else {
2307 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
485ff23e 2308 push(@typeListFile, $possible);
c45dcabd 2309 }
8905a67c 2310 build_types();
0776e594
AW
2311 } else {
2312 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
8905a67c
AW
2313 }
2314}
2315
6c72ffaa
AW
2316my $prefix = '';
2317
000d1cc1 2318sub show_type {
cbec18af 2319 my ($type) = @_;
91bfe484 2320
522b837c
AD
2321 $type =~ tr/[a-z]/[A-Z]/;
2322
cbec18af
JP
2323 return defined $use_type{$type} if (scalar keys %use_type > 0);
2324
2325 return !defined $ignore_type{$type};
000d1cc1
JP
2326}
2327
f0a594c1 2328sub report {
cbec18af
JP
2329 my ($level, $type, $msg) = @_;
2330
2331 if (!show_type($type) ||
2332 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
773647a0
AW
2333 return 0;
2334 }
57230297 2335 my $output = '';
737c0767 2336 if ($color) {
57230297
JP
2337 if ($level eq 'ERROR') {
2338 $output .= RED;
2339 } elsif ($level eq 'WARNING') {
2340 $output .= YELLOW;
2341 } else {
2342 $output .= GREEN;
2343 }
2344 }
2345 $output .= $prefix . $level . ':';
000d1cc1 2346 if ($show_types) {
737c0767 2347 $output .= BLUE if ($color);
57230297 2348 $output .= "$type:";
000d1cc1 2349 }
737c0767 2350 $output .= RESET if ($color);
57230297 2351 $output .= ' ' . $msg . "\n";
34d8815f
JP
2352
2353 if ($showfile) {
2354 my @lines = split("\n", $output, -1);
2355 splice(@lines, 1, 1);
2356 $output = join("\n", @lines);
2357 }
52178ce0
DR
2358
2359 if ($terse) {
2360 $output = (split('\n', $output))[0] . "\n";
2361 }
2362
2363 if ($verbose && exists($verbose_messages{$type}) &&
2364 !exists($verbose_emitted{$type})) {
2365 $output .= $verbose_messages{$type} . "\n\n";
2366 $verbose_emitted{$type} = 1;
2367 }
8905a67c 2368
57230297 2369 push(our @report, $output);
773647a0
AW
2370
2371 return 1;
f0a594c1 2372}
cbec18af 2373
f0a594c1 2374sub report_dump {
13214adf 2375 our @report;
f0a594c1 2376}
000d1cc1 2377
d752fcc8
JP
2378sub fixup_current_range {
2379 my ($lineRef, $offset, $length) = @_;
2380
2381 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2382 my $o = $1;
2383 my $l = $2;
2384 my $no = $o + $offset;
2385 my $nl = $l + $length;
2386 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2387 }
2388}
2389
2390sub fix_inserted_deleted_lines {
2391 my ($linesRef, $insertedRef, $deletedRef) = @_;
2392
2393 my $range_last_linenr = 0;
2394 my $delta_offset = 0;
2395
2396 my $old_linenr = 0;
2397 my $new_linenr = 0;
2398
2399 my $next_insert = 0;
2400 my $next_delete = 0;
2401
2402 my @lines = ();
2403
2404 my $inserted = @{$insertedRef}[$next_insert++];
2405 my $deleted = @{$deletedRef}[$next_delete++];
2406
2407 foreach my $old_line (@{$linesRef}) {
2408 my $save_line = 1;
2409 my $line = $old_line; #don't modify the array
323b267f 2410 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
d752fcc8
JP
2411 $delta_offset = 0;
2412 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2413 $range_last_linenr = $new_linenr;
2414 fixup_current_range(\$line, $delta_offset, 0);
2415 }
2416
2417 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2418 $deleted = @{$deletedRef}[$next_delete++];
2419 $save_line = 0;
2420 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2421 }
2422
2423 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2424 push(@lines, ${$inserted}{'LINE'});
2425 $inserted = @{$insertedRef}[$next_insert++];
2426 $new_linenr++;
2427 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2428 }
2429
2430 if ($save_line) {
2431 push(@lines, $line);
2432 $new_linenr++;
2433 }
2434
2435 $old_linenr++;
2436 }
2437
2438 return @lines;
2439}
2440
f2d7e4d4
JP
2441sub fix_insert_line {
2442 my ($linenr, $line) = @_;
2443
2444 my $inserted = {
2445 LINENR => $linenr,
2446 LINE => $line,
2447 };
2448 push(@fixed_inserted, $inserted);
2449}
2450
2451sub fix_delete_line {
2452 my ($linenr, $line) = @_;
2453
2454 my $deleted = {
2455 LINENR => $linenr,
2456 LINE => $line,
2457 };
2458
2459 push(@fixed_deleted, $deleted);
2460}
2461
de7d4f0e 2462sub ERROR {
cbec18af
JP
2463 my ($type, $msg) = @_;
2464
2465 if (report("ERROR", $type, $msg)) {
773647a0
AW
2466 our $clean = 0;
2467 our $cnt_error++;
3705ce5b 2468 return 1;
773647a0 2469 }
3705ce5b 2470 return 0;
de7d4f0e
AW
2471}
2472sub WARN {
cbec18af
JP
2473 my ($type, $msg) = @_;
2474
2475 if (report("WARNING", $type, $msg)) {
773647a0
AW
2476 our $clean = 0;
2477 our $cnt_warn++;
3705ce5b 2478 return 1;
773647a0 2479 }
3705ce5b 2480 return 0;
de7d4f0e
AW
2481}
2482sub CHK {
cbec18af
JP
2483 my ($type, $msg) = @_;
2484
2485 if ($check && report("CHECK", $type, $msg)) {
6c72ffaa
AW
2486 our $clean = 0;
2487 our $cnt_chk++;
3705ce5b 2488 return 1;
6c72ffaa 2489 }
3705ce5b 2490 return 0;
de7d4f0e
AW
2491}
2492
6ecd9674
AW
2493sub check_absolute_file {
2494 my ($absolute, $herecurr) = @_;
2495 my $file = $absolute;
2496
2497 ##print "absolute<$absolute>\n";
2498
2499 # See if any suffix of this path is a path within the tree.
2500 while ($file =~ s@^[^/]*/@@) {
2501 if (-f "$root/$file") {
2502 ##print "file<$file>\n";
2503 last;
2504 }
2505 }
2506 if (! -f _) {
2507 return 0;
2508 }
2509
2510 # It is, so see if the prefix is acceptable.
2511 my $prefix = $absolute;
2512 substr($prefix, -length($file)) = '';
2513
2514 ##print "prefix<$prefix>\n";
2515 if ($prefix ne ".../") {
000d1cc1
JP
2516 WARN("USE_RELATIVE_PATH",
2517 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
6ecd9674
AW
2518 }
2519}
2520
3705ce5b
JP
2521sub trim {
2522 my ($string) = @_;
2523
b34c648b
JP
2524 $string =~ s/^\s+|\s+$//g;
2525
2526 return $string;
2527}
2528
2529sub ltrim {
2530 my ($string) = @_;
2531
2532 $string =~ s/^\s+//;
2533
2534 return $string;
2535}
2536
2537sub rtrim {
2538 my ($string) = @_;
2539
2540 $string =~ s/\s+$//;
3705ce5b
JP
2541
2542 return $string;
2543}
2544
52ea8506
JP
2545sub string_find_replace {
2546 my ($string, $find, $replace) = @_;
2547
2548 $string =~ s/$find/$replace/g;
2549
2550 return $string;
2551}
2552
3705ce5b
JP
2553sub tabify {
2554 my ($leading) = @_;
2555
713a09de 2556 my $source_indent = $tabsize;
3705ce5b
JP
2557 my $max_spaces_before_tab = $source_indent - 1;
2558 my $spaces_to_tab = " " x $source_indent;
2559
2560 #convert leading spaces to tabs
2561 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2562 #Remove spaces before a tab
2563 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2564
2565 return "$leading";
2566}
2567
d1fe9c09
JP
2568sub pos_last_openparen {
2569 my ($line) = @_;
2570
2571 my $pos = 0;
2572
2573 my $opens = $line =~ tr/\(/\(/;
2574 my $closes = $line =~ tr/\)/\)/;
2575
2576 my $last_openparen = 0;
2577
2578 if (($opens == 0) || ($closes >= $opens)) {
2579 return -1;
2580 }
2581
2582 my $len = length($line);
2583
2584 for ($pos = 0; $pos < $len; $pos++) {
2585 my $string = substr($line, $pos);
2586 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2587 $pos += length($1) - 1;
2588 } elsif (substr($line, $pos, 1) eq '(') {
2589 $last_openparen = $pos;
2590 } elsif (index($string, '(') == -1) {
2591 last;
2592 }
2593 }
2594
91cb5195 2595 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
d1fe9c09
JP
2596}
2597
f36d3eb8
JP
2598sub get_raw_comment {
2599 my ($line, $rawline) = @_;
2600 my $comment = '';
2601
2602 for my $i (0 .. (length($line) - 1)) {
2603 if (substr($line, $i, 1) eq "$;") {
2604 $comment .= substr($rawline, $i, 1);
2605 }
2606 }
2607
2608 return $comment;
2609}
2610
5b8f82e1
SL
2611sub exclude_global_initialisers {
2612 my ($realfile) = @_;
2613
2614 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2615 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2616 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2617 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2618}
2619
0a920b5b
AW
2620sub process {
2621 my $filename = shift;
0a920b5b
AW
2622
2623 my $linenr=0;
2624 my $prevline="";
c2fdda0d 2625 my $prevrawline="";
0a920b5b 2626 my $stashline="";
c2fdda0d 2627 my $stashrawline="";
0a920b5b 2628
4a0df2ef 2629 my $length;
0a920b5b
AW
2630 my $indent;
2631 my $previndent=0;
2632 my $stashindent=0;
2633
de7d4f0e 2634 our $clean = 1;
0a920b5b 2635 my $signoff = 0;
cd261496
GU
2636 my $author = '';
2637 my $authorsignoff = 0;
48ca2d8a 2638 my $author_sob = '';
0a920b5b 2639 my $is_patch = 0;
133712a2 2640 my $is_binding_patch = -1;
29ee1b0c 2641 my $in_header_lines = $file ? 0 : 1;
15662b3e 2642 my $in_commit_log = 0; #Scanning lines before patch
44d303eb 2643 my $has_patch_separator = 0; #Found a --- line
ed43c4e5 2644 my $has_commit_log = 0; #Encountered lines before patch
490b292c 2645 my $commit_log_lines = 0; #Number of commit log lines
77cb8546 2646 my $commit_log_possible_stack_dump = 0;
2a076f40 2647 my $commit_log_long_line = 0;
e518e9a5 2648 my $commit_log_has_diff = 0;
13f1937e 2649 my $reported_maintainer_file = 0;
fa64205d
PS
2650 my $non_utf8_charset = 0;
2651
4ce9f970
JP
2652 my $last_git_commit_id_linenr = -1;
2653
365dd4ea 2654 my $last_blank_line = 0;
5e4f6ba5 2655 my $last_coalesced_string_linenr = -1;
365dd4ea 2656
13214adf 2657 our @report = ();
6c72ffaa
AW
2658 our $cnt_lines = 0;
2659 our $cnt_error = 0;
2660 our $cnt_warn = 0;
2661 our $cnt_chk = 0;
2662
0a920b5b
AW
2663 # Trace the real file/line as we go.
2664 my $realfile = '';
2665 my $realline = 0;
2666 my $realcnt = 0;
2667 my $here = '';
77cb8546 2668 my $context_function; #undef'd unless there's a known function
0a920b5b 2669 my $in_comment = 0;
c2fdda0d 2670 my $comment_edge = 0;
0a920b5b 2671 my $first_line = 0;
1e855726 2672 my $p1_prefix = '';
0a920b5b 2673
13214adf
AW
2674 my $prev_values = 'E';
2675
2676 # suppression flags
773647a0 2677 my %suppress_ifbraces;
170d3a22 2678 my %suppress_whiletrailers;
2b474a1a 2679 my %suppress_export;
3e469cdc 2680 my $suppress_statement = 0;
653d4876 2681
7e51f197 2682 my %signatures = ();
323c1260 2683
c2fdda0d 2684 # Pre-scan the patch sanitizing the lines.
de7d4f0e 2685 # Pre-scan the patch looking for any __setup documentation.
c2fdda0d 2686 #
de7d4f0e
AW
2687 my @setup_docs = ();
2688 my $setup_docs = 0;
773647a0 2689
d8b07710
JP
2690 my $camelcase_file_seeded = 0;
2691
9f3a8992
RH
2692 my $checklicenseline = 1;
2693
773647a0 2694 sanitise_line_reset();
c2fdda0d
AW
2695 my $line;
2696 foreach my $rawline (@rawlines) {
773647a0
AW
2697 $linenr++;
2698 $line = $rawline;
c2fdda0d 2699
3705ce5b
JP
2700 push(@fixed, $rawline) if ($fix);
2701
773647a0 2702 if ($rawline=~/^\+\+\+\s+(\S+)/) {
de7d4f0e 2703 $setup_docs = 0;
2581ac7c 2704 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
de7d4f0e
AW
2705 $setup_docs = 1;
2706 }
773647a0
AW
2707 #next;
2708 }
74fd4f34 2709 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
773647a0
AW
2710 $realline=$1-1;
2711 if (defined $2) {
2712 $realcnt=$3+1;
2713 } else {
2714 $realcnt=1+1;
2715 }
c45dcabd 2716 $in_comment = 0;
773647a0
AW
2717
2718 # Guestimate if this is a continuing comment. Run
2719 # the context looking for a comment "edge". If this
2720 # edge is a close comment then we must be in a comment
2721 # at context start.
2722 my $edge;
01fa9147
AW
2723 my $cnt = $realcnt;
2724 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2725 next if (defined $rawlines[$ln - 1] &&
2726 $rawlines[$ln - 1] =~ /^-/);
2727 $cnt--;
2728 #print "RAW<$rawlines[$ln - 1]>\n";
721c1cb6 2729 last if (!defined $rawlines[$ln - 1]);
fae17dae
AW
2730 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2731 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2732 ($edge) = $1;
2733 last;
2734 }
773647a0
AW
2735 }
2736 if (defined $edge && $edge eq '*/') {
2737 $in_comment = 1;
2738 }
2739
2740 # Guestimate if this is a continuing comment. If this
2741 # is the start of a diff block and this line starts
2742 # ' *' then it is very likely a comment.
2743 if (!defined $edge &&
83242e0c 2744 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
773647a0
AW
2745 {
2746 $in_comment = 1;
2747 }
2748
2749 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2750 sanitise_line_reset($in_comment);
2751
171ae1a4 2752 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
773647a0 2753 # Standardise the strings and chars within the input to
171ae1a4 2754 # simplify matching -- only bother with positive lines.
773647a0 2755 $line = sanitise_line($rawline);
de7d4f0e 2756 }
773647a0
AW
2757 push(@lines, $line);
2758
2759 if ($realcnt > 1) {
2760 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2761 } else {
2762 $realcnt = 0;
2763 }
2764
2765 #print "==>$rawline\n";
2766 #print "-->$line\n";
de7d4f0e
AW
2767
2768 if ($setup_docs && $line =~ /^\+/) {
2769 push(@setup_docs, $line);
2770 }
2771 }
2772
6c72ffaa
AW
2773 $prefix = '';
2774
773647a0
AW
2775 $realcnt = 0;
2776 $linenr = 0;
194f66fc 2777 $fixlinenr = -1;
0a920b5b
AW
2778 foreach my $line (@lines) {
2779 $linenr++;
194f66fc 2780 $fixlinenr++;
1b5539b1
JP
2781 my $sline = $line; #copy of $line
2782 $sline =~ s/$;/ /g; #with comments as spaces
0a920b5b 2783
c2fdda0d 2784 my $rawline = $rawlines[$linenr - 1];
f36d3eb8 2785 my $raw_comment = get_raw_comment($line, $rawline);
6c72ffaa 2786
12c253ab
JP
2787# check if it's a mode change, rename or start of a patch
2788 if (!$in_commit_log &&
2789 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2790 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2791 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2792 $is_patch = 1;
2793 }
2794
0a920b5b 2795#extract the line range in the file after the patch is applied
e518e9a5 2796 if (!$in_commit_log &&
74fd4f34
JP
2797 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2798 my $context = $4;
0a920b5b 2799 $is_patch = 1;
4a0df2ef 2800 $first_line = $linenr + 1;
0a920b5b
AW
2801 $realline=$1-1;
2802 if (defined $2) {
2803 $realcnt=$3+1;
2804 } else {
2805 $realcnt=1+1;
2806 }
c2fdda0d 2807 annotate_reset();
13214adf
AW
2808 $prev_values = 'E';
2809
773647a0 2810 %suppress_ifbraces = ();
170d3a22 2811 %suppress_whiletrailers = ();
2b474a1a 2812 %suppress_export = ();
3e469cdc 2813 $suppress_statement = 0;
74fd4f34
JP
2814 if ($context =~ /\b(\w+)\s*\(/) {
2815 $context_function = $1;
2816 } else {
2817 undef $context_function;
2818 }
0a920b5b 2819 next;
0a920b5b 2820
4a0df2ef
AW
2821# track the line number as we move through the hunk, note that
2822# new versions of GNU diff omit the leading space on completely
2823# blank context lines so we need to count that too.
773647a0 2824 } elsif ($line =~ /^( |\+|$)/) {
0a920b5b 2825 $realline++;
d8aaf121 2826 $realcnt-- if ($realcnt != 0);
0a920b5b 2827
4a0df2ef 2828 # Measure the line length and indent.
c2fdda0d 2829 ($length, $indent) = line_stats($rawline);
0a920b5b
AW
2830
2831 # Track the previous line.
2832 ($prevline, $stashline) = ($stashline, $line);
2833 ($previndent, $stashindent) = ($stashindent, $indent);
c2fdda0d
AW
2834 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2835
773647a0 2836 #warn "line<$line>\n";
6c72ffaa 2837
d8aaf121
AW
2838 } elsif ($realcnt == 1) {
2839 $realcnt--;
0a920b5b
AW
2840 }
2841
cc77cdca
AW
2842 my $hunk_line = ($realcnt != 0);
2843
6c72ffaa
AW
2844 $here = "#$linenr: " if (!$file);
2845 $here = "#$realline: " if ($file);
773647a0 2846
2ac73b4f 2847 my $found_file = 0;
773647a0 2848 # extract the filename as it passes
3bf9a009
RV
2849 if ($line =~ /^diff --git.*?(\S+)$/) {
2850 $realfile = $1;
2b7ab453 2851 $realfile =~ s@^([^/]*)/@@ if (!$file);
270c49a0 2852 $in_commit_log = 0;
2ac73b4f 2853 $found_file = 1;
3bf9a009 2854 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
773647a0 2855 $realfile = $1;
2b7ab453 2856 $realfile =~ s@^([^/]*)/@@ if (!$file);
270c49a0 2857 $in_commit_log = 0;
1e855726
WS
2858
2859 $p1_prefix = $1;
e2f7aa4b
AW
2860 if (!$file && $tree && $p1_prefix ne '' &&
2861 -e "$root/$p1_prefix") {
000d1cc1
JP
2862 WARN("PATCH_PREFIX",
2863 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1e855726 2864 }
773647a0 2865
c1ab3326 2866 if ($realfile =~ m@^include/asm/@) {
000d1cc1
JP
2867 ERROR("MODIFIED_INCLUDE_ASM",
2868 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
773647a0 2869 }
2ac73b4f
JP
2870 $found_file = 1;
2871 }
2872
34d8815f
JP
2873#make up the handle for any error we report on this line
2874 if ($showfile) {
2875 $prefix = "$realfile:$realline: "
2876 } elsif ($emacs) {
7d3a9f67
JP
2877 if ($file) {
2878 $prefix = "$filename:$realline: ";
2879 } else {
2880 $prefix = "$filename:$linenr: ";
2881 }
34d8815f
JP
2882 }
2883
2ac73b4f 2884 if ($found_file) {
85b0ee18
JP
2885 if (is_maintained_obsolete($realfile)) {
2886 WARN("OBSOLETE",
2887 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2888 }
7bd7e483 2889 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2ac73b4f
JP
2890 $check = 1;
2891 } else {
2892 $check = $check_orig;
2893 }
9f3a8992 2894 $checklicenseline = 1;
133712a2
RH
2895
2896 if ($realfile !~ /^MAINTAINERS/) {
2897 my $last_binding_patch = $is_binding_patch;
2898
2899 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2900
2901 if (($last_binding_patch != -1) &&
2902 ($last_binding_patch ^ $is_binding_patch)) {
2903 WARN("DT_SPLIT_BINDING_PATCH",
858e6845 2904 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
133712a2
RH
2905 }
2906 }
2907
773647a0
AW
2908 next;
2909 }
2910
389834b6 2911 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
0a920b5b 2912
c2fdda0d
AW
2913 my $hereline = "$here\n$rawline\n";
2914 my $herecurr = "$here\n$rawline\n";
2915 my $hereprev = "$here\n$prevrawline\n$rawline\n";
0a920b5b 2916
6c72ffaa
AW
2917 $cnt_lines++ if ($realcnt != 0);
2918
490b292c
JP
2919# Verify the existence of a commit log if appropriate
2920# 2 is used because a $signature is counted in $commit_log_lines
2921 if ($in_commit_log) {
2922 if ($line !~ /^\s*$/) {
2923 $commit_log_lines++; #could be a $signature
2924 }
2925 } elsif ($has_commit_log && $commit_log_lines < 2) {
2926 WARN("COMMIT_MESSAGE",
2927 "Missing commit description - Add an appropriate one\n");
2928 $commit_log_lines = 2; #warn only once
2929 }
2930
e518e9a5
JP
2931# Check if the commit log has what seems like a diff which can confuse patch
2932 if ($in_commit_log && !$commit_log_has_diff &&
13e45417
MP
2933 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2934 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
e518e9a5
JP
2935 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2936 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2937 ERROR("DIFF_IN_COMMIT_MSG",
2938 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2939 $commit_log_has_diff = 1;
2940 }
2941
3bf9a009
RV
2942# Check for incorrect file permissions
2943 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2944 my $permhere = $here . "FILE: $realfile\n";
04db4d25
JP
2945 if ($realfile !~ m@scripts/@ &&
2946 $realfile !~ /\.(py|pl|awk|sh)$/) {
000d1cc1
JP
2947 ERROR("EXECUTE_PERMISSIONS",
2948 "do not set execute permissions for source files\n" . $permhere);
3bf9a009
RV
2949 }
2950 }
2951
cd261496
GU
2952# Check the patch for a From:
2953 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2954 $author = $1;
e7f929f3
DR
2955 my $curline = $linenr;
2956 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2957 $author .= $1;
2958 }
cd261496
GU
2959 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2960 $author =~ s/"//g;
dfa05c28 2961 $author = reformat_email($author);
cd261496
GU
2962 }
2963
20112475 2964# Check the patch for a signoff:
dfa05c28 2965 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
4a0df2ef 2966 $signoff++;
15662b3e 2967 $in_commit_log = 0;
48ca2d8a 2968 if ($author ne '' && $authorsignoff != 1) {
fccaebf0 2969 if (same_email_addresses($1, $author)) {
dfa05c28 2970 $authorsignoff = 1;
48ca2d8a
DR
2971 } else {
2972 my $ctx = $1;
2973 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2974 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2975
046fc741 2976 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
48ca2d8a
DR
2977 $author_sob = $ctx;
2978 $authorsignoff = 2;
046fc741 2979 } elsif (lc $email_address eq lc $author_address) {
48ca2d8a
DR
2980 $author_sob = $ctx;
2981 $authorsignoff = 3;
2982 } elsif ($email_name eq $author_name) {
2983 $author_sob = $ctx;
2984 $authorsignoff = 4;
2985
2986 my $address1 = $email_address;
2987 my $address2 = $author_address;
2988
2989 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2990 $address1 = "$1$2";
2991 }
2992 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2993 $address2 = "$1$2";
2994 }
2995 if ($address1 eq $address2) {
2996 $authorsignoff = 5;
2997 }
2998 }
cd261496
GU
2999 }
3000 }
20112475
JP
3001 }
3002
44d303eb
JP
3003# Check for patch separator
3004 if ($line =~ /^---$/) {
3005 $has_patch_separator = 1;
3006 $in_commit_log = 0;
3007 }
3008
e0d975b1
JP
3009# Check if MAINTAINERS is being updated. If so, there's probably no need to
3010# emit the "does MAINTAINERS need updating?" message on file add/move/delete
3011 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3012 $reported_maintainer_file = 1;
3013 }
3014
20112475 3015# Check signature styles
270c49a0 3016 if (!$in_header_lines &&
ce0338df 3017 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
20112475
JP
3018 my $space_before = $1;
3019 my $sign_off = $2;
3020 my $space_after = $3;
3021 my $email = $4;
3022 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3023
ce0338df 3024 if ($sign_off !~ /$signature_tags/) {
831242ab
AS
3025 my $suggested_signature = find_standard_signature($sign_off);
3026 if ($suggested_signature eq "") {
3027 WARN("BAD_SIGN_OFF",
3028 "Non-standard signature: $sign_off\n" . $herecurr);
3029 } else {
3030 if (WARN("BAD_SIGN_OFF",
3031 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3032 $fix) {
3033 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3034 }
3035 }
ce0338df 3036 }
20112475 3037 if (defined $space_before && $space_before ne "") {
3705ce5b
JP
3038 if (WARN("BAD_SIGN_OFF",
3039 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3040 $fix) {
194f66fc 3041 $fixed[$fixlinenr] =
3705ce5b
JP
3042 "$ucfirst_sign_off $email";
3043 }
20112475
JP
3044 }
3045 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3705ce5b
JP
3046 if (WARN("BAD_SIGN_OFF",
3047 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3048 $fix) {
194f66fc 3049 $fixed[$fixlinenr] =
3705ce5b
JP
3050 "$ucfirst_sign_off $email";
3051 }
3052
20112475
JP
3053 }
3054 if (!defined $space_after || $space_after ne " ") {
3705ce5b
JP
3055 if (WARN("BAD_SIGN_OFF",
3056 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3057 $fix) {
194f66fc 3058 $fixed[$fixlinenr] =
3705ce5b
JP
3059 "$ucfirst_sign_off $email";
3060 }
0a920b5b 3061 }
20112475 3062
dfa05c28 3063 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
48ca2d8a 3064 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
20112475 3065 if ($suggested_email eq "") {
000d1cc1
JP
3066 ERROR("BAD_SIGN_OFF",
3067 "Unrecognized email address: '$email'\n" . $herecurr);
20112475
JP
3068 } else {
3069 my $dequoted = $suggested_email;
3070 $dequoted =~ s/^"//;
3071 $dequoted =~ s/" </ </;
3072 # Don't force email to have quotes
3073 # Allow just an angle bracketed address
fccaebf0
DR
3074 if (!same_email_addresses($email, $suggested_email)) {
3075 if (WARN("BAD_SIGN_OFF",
3076 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3077 $fix) {
3078 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3079 }
3080 }
3081
3082 # Address part shouldn't have comments
3083 my $stripped_address = $email_address;
3084 $stripped_address =~ s/\([^\(\)]*\)//g;
3085 if ($email_address ne $stripped_address) {
3086 if (WARN("BAD_SIGN_OFF",
3087 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3088 $fix) {
3089 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3090 }
3091 }
3092
3093 # Only one name comment should be allowed
3094 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3095 if ($comment_count > 1) {
000d1cc1 3096 WARN("BAD_SIGN_OFF",
fccaebf0
DR
3097 "Use a single name comment in email: '$email'\n" . $herecurr);
3098 }
3099
3100
3101 # stable@vger.kernel.org or stable@kernel.org shouldn't
e73d2715 3102 # have an email name. In addition comments should strictly
fccaebf0
DR
3103 # begin with a #
3104 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3105 if (($comment ne "" && $comment !~ /^#.+/) ||
3106 ($email_name ne "")) {
3107 my $cur_name = $email_name;
3108 my $new_comment = $comment;
3109 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3110
3111 # Remove brackets enclosing comment text
3112 # and # from start of comments to get comment text
3113 $new_comment =~ s/^\((.*)\)$/$1/;
3114 $new_comment =~ s/^\[(.*)\]$/$1/;
3115 $new_comment =~ s/^[\s\#]+|\s+$//g;
3116
3117 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3118 $new_comment = " # $new_comment" if ($new_comment ne "");
3119 my $new_email = "$email_address$new_comment";
3120
3121 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3122 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3123 $fix) {
3124 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3125 }
3126 }
3127 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3128 my $new_comment = $comment;
3129
3130 # Extract comment text from within brackets or
3131 # c89 style /*...*/ comments
3132 $new_comment =~ s/^\[(.*)\]$/$1/;
3133 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3134
3135 $new_comment = trim($new_comment);
3136 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3137 $new_comment = "($new_comment)" if ($new_comment ne "");
3138 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3139
3140 if (WARN("BAD_SIGN_OFF",
3141 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3142 $fix) {
3143 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3144 }
20112475 3145 }
0a920b5b 3146 }
7e51f197
JP
3147
3148# Check for duplicate signatures
3149 my $sig_nospace = $line;
3150 $sig_nospace =~ s/\s//g;
3151 $sig_nospace = lc($sig_nospace);
3152 if (defined $signatures{$sig_nospace}) {
3153 WARN("BAD_SIGN_OFF",
3154 "Duplicate signature\n" . $herecurr);
3155 } else {
3156 $signatures{$sig_nospace} = 1;
3157 }
6c5d24ee
SC
3158
3159# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3160 if ($sign_off =~ /^co-developed-by:$/i) {
3161 if ($email eq $author) {
3162 WARN("BAD_SIGN_OFF",
1916f777 3163 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
6c5d24ee
SC
3164 }
3165 if (!defined $lines[$linenr]) {
3166 WARN("BAD_SIGN_OFF",
1916f777
TL
3167 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3168 } elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
6c5d24ee 3169 WARN("BAD_SIGN_OFF",
1916f777 3170 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
6c5d24ee
SC
3171 } elsif ($1 ne $email) {
3172 WARN("BAD_SIGN_OFF",
1916f777 3173 "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
6c5d24ee
SC
3174 }
3175 }
d7f1d71e 3176
44c31888 3177# check if Reported-by: is followed by a Closes: tag
d7f1d71e
KW
3178 if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3179 if (!defined $lines[$linenr]) {
3180 WARN("BAD_REPORTED_BY_LINK",
44c31888 3181 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
d6ccdd67 3182 } elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
d7f1d71e 3183 WARN("BAD_REPORTED_BY_LINK",
44c31888 3184 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
d7f1d71e
KW
3185 }
3186 }
0a920b5b
AW
3187 }
3188
d7f1d71e 3189
bd17e036
NS
3190# Check Fixes: styles is correct
3191 if (!$in_header_lines &&
3192 $line =~ /^\s*fixes:?\s*(?:commit\s*)?[0-9a-f]{5,}\b/i) {
3193 my $orig_commit = "";
3194 my $id = "0123456789ab";
3195 my $title = "commit title";
3196 my $tag_case = 1;
3197 my $tag_space = 1;
3198 my $id_length = 1;
3199 my $id_case = 1;
3200 my $title_has_quotes = 0;
3201
3202 if ($line =~ /(\s*fixes:?)\s+([0-9a-f]{5,})\s+($balanced_parens)/i) {
3203 my $tag = $1;
3204 $orig_commit = $2;
3205 $title = $3;
3206
3207 $tag_case = 0 if $tag eq "Fixes:";
3208 $tag_space = 0 if ($line =~ /^fixes:? [0-9a-f]{5,} ($balanced_parens)/i);
3209
3210 $id_length = 0 if ($orig_commit =~ /^[0-9a-f]{12}$/i);
3211 $id_case = 0 if ($orig_commit !~ /[A-F]/);
3212
3213 # Always strip leading/trailing parens then double quotes if existing
3214 $title = substr($title, 1, -1);
3215 if ($title =~ /^".*"$/) {
3216 $title = substr($title, 1, -1);
3217 $title_has_quotes = 1;
3218 }
3219 }
3220
3221 my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3222 $title);
3223
3224 if ($ctitle ne $title || $tag_case || $tag_space ||
3225 $id_length || $id_case || !$title_has_quotes) {
3226 if (WARN("BAD_FIXES_TAG",
3227 "Please use correct Fixes: style 'Fixes: <12 chars of sha1> (\"<title line>\")' - ie: 'Fixes: $cid (\"$ctitle\")'\n" . $herecurr) &&
3228 $fix) {
3229 $fixed[$fixlinenr] = "Fixes: $cid (\"$ctitle\")";
3230 }
3231 }
3232 }
3233
a2fe16b9
JP
3234# Check email subject for common tools that don't need to be mentioned
3235 if ($in_header_lines &&
3236 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3237 WARN("EMAIL_SUBJECT",
3238 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3239 }
3240
44d303eb
JP
3241# Check for Gerrit Change-Ids not in any patch context
3242 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
7580c5b9
AS
3243 if (ERROR("GERRIT_CHANGE_ID",
3244 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3245 $fix) {
ea7dbab3
DR
3246 fix_delete_line($fixlinenr, $rawline);
3247 }
7ebd05ef
CC
3248 }
3249
369c8dd3
JP
3250# Check if the commit log is in a possible stack dump
3251 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3252 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3253 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3254 # timestamp
634cffcc
JP
3255 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3256 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3257 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3258 # stack dump address styles
369c8dd3
JP
3259 $commit_log_possible_stack_dump = 1;
3260 }
3261
2a076f40
JP
3262# Check for line lengths > 75 in commit log, warn once
3263 if ($in_commit_log && !$commit_log_long_line &&
369c8dd3
JP
3264 length($line) > 75 &&
3265 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3266 # file delta changes
36f8b348 3267 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
369c8dd3 3268 # filename then :
f94e40ea
MB
3269 $line =~ /^\s*(?:Fixes:|$link_tags_search|$signature_tags)/i ||
3270 # A Fixes:, link or signature tag line
369c8dd3 3271 $commit_log_possible_stack_dump)) {
2a076f40
JP
3272 WARN("COMMIT_LOG_LONG_LINE",
3273 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3274 $commit_log_long_line = 1;
3275 }
3276
bf4daf12 3277# Reset possible stack dump if a blank line is found
369c8dd3
JP
3278 if ($in_commit_log && $commit_log_possible_stack_dump &&
3279 $line =~ /^\s*$/) {
3280 $commit_log_possible_stack_dump = 0;
3281 }
bf4daf12 3282
76f381bb
KW
3283# Check for odd tags before a URI/URL
3284 if ($in_commit_log &&
f94e40ea 3285 $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
76f381bb
KW
3286 if ($1 =~ /^v(?:ersion)?\d+/i) {
3287 WARN("COMMIT_LOG_VERSIONING",
3288 "Patch version information should be after the --- line\n" . $herecurr);
3289 } else {
3290 WARN("COMMIT_LOG_USE_LINK",
f94e40ea 3291 "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
76f381bb
KW
3292 }
3293 }
3294
d6ccdd67
MB
3295# Check for misuse of the link tags
3296 if ($in_commit_log &&
3297 $line =~ /^\s*(\w+:)\s*(\S+)/) {
3298 my $tag = $1;
3299 my $value = $2;
3300 if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3301 WARN("COMMIT_LOG_WRONG_LINK",
3302 "'$tag' should be followed by a public http(s) link\n" . $herecurr);
76f381bb
KW
3303 }
3304 }
3305
084a617a
DR
3306# Check for lines starting with a #
3307 if ($in_commit_log && $line =~ /^#/) {
3308 if (WARN("COMMIT_COMMENT_SYMBOL",
3309 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3310 $fix) {
3311 $fixed[$fixlinenr] =~ s/^/ /;
3312 }
3313 }
3314
0d7835fc 3315# Check for git id commit length and improperly formed commit descriptions
4ce9f970
JP
3316# A correctly formed commit description is:
3317# commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3318# with the commit subject '("' prefix and '")' suffix
3319# This is a fairly compilicated block as it tests for what appears to be
3320# bare SHA-1 hash with minimum length of 5. It also avoids several types of
3321# possible SHA-1 matches.
3322# A commit match can span multiple lines so this block attempts to find a
3323# complete typical commit on a maximum of 3 lines
3324 if ($perl_version_ok &&
3325 $in_commit_log && !$commit_log_possible_stack_dump &&
a8972573 3326 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
e882dbfc 3327 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
4ce9f970
JP
3328 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3329 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
aab38f51 3330 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
369c8dd3
JP
3331 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3332 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
fe043ea1
JP
3333 my $init_char = "c";
3334 my $orig_commit = "";
0d7835fc
JP
3335 my $short = 1;
3336 my $long = 0;
3337 my $case = 1;
3338 my $space = 1;
0d7835fc
JP
3339 my $id = '0123456789ab';
3340 my $orig_desc = "commit description";
3341 my $description = "";
4ce9f970
JP
3342 my $herectx = $herecurr;
3343 my $has_parens = 0;
3344 my $has_quotes = 0;
3345
3346 my $input = $line;
3347 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3348 for (my $n = 0; $n < 2; $n++) {
3349 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3350 $orig_desc = $1;
3351 $has_parens = 1;
3352 # Always strip leading/trailing parens then double quotes if existing
3353 $orig_desc = substr($orig_desc, 1, -1);
3354 if ($orig_desc =~ /^".*"$/) {
3355 $orig_desc = substr($orig_desc, 1, -1);
3356 $has_quotes = 1;
3357 }
3358 last;
3359 }
3360 last if ($#lines < $linenr + $n);
3361 $input .= " " . trim($rawlines[$linenr + $n]);
3362 $herectx .= "$rawlines[$linenr + $n]\n";
3363 }
3364 $herectx = $herecurr if (!$has_parens);
3365 }
0d7835fc 3366
4ce9f970 3367 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
fe043ea1
JP
3368 $init_char = $1;
3369 $orig_commit = lc($2);
4ce9f970
JP
3370 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3371 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3372 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3373 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3374 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
fe043ea1
JP
3375 $orig_commit = lc($1);
3376 }
3377
0d7835fc
JP
3378 ($id, $description) = git_commit_info($orig_commit,
3379 $id, $orig_desc);
3380
948b133a 3381 if (defined($id) &&
4ce9f970
JP
3382 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3383 $last_git_commit_id_linenr != $linenr - 1) {
0d7835fc 3384 ERROR("GIT_COMMIT_ID",
4ce9f970 3385 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
0d7835fc 3386 }
4ce9f970
JP
3387 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3388 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
d311cd44
JP
3389 }
3390
9b71f79f
BH
3391# Check for mailing list archives other than lore.kernel.org
3392 if ($rawline =~ m{http.*\b$obsolete_archives}) {
3393 WARN("PREFER_LORE_ARCHIVE",
3394 "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3395 }
3396
13f1937e
JP
3397# Check for added, moved or deleted files
3398 if (!$reported_maintainer_file && !$in_commit_log &&
3399 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3400 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3401 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3402 (defined($1) || defined($2))))) {
a82603a8 3403 $is_patch = 1;
13f1937e
JP
3404 $reported_maintainer_file = 1;
3405 WARN("FILE_PATH_CHANGES",
3406 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3407 }
3408
e400edb1
RH
3409# Check for adding new DT bindings not in schema format
3410 if (!$in_commit_log &&
3411 ($line =~ /^new file mode\s*\d+\s*$/) &&
3412 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3413 WARN("DT_SCHEMA_BINDING_PATCH",
56ddc4cd 3414 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
e400edb1
RH
3415 }
3416
00df344f 3417# Check for wrappage within a valid hunk of the file
8905a67c 3418 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
000d1cc1
JP
3419 ERROR("CORRUPTED_PATCH",
3420 "patch seems to be corrupt (line wrapped?)\n" .
6c72ffaa 3421 $herecurr) if (!$emitted_corrupt++);
de7d4f0e
AW
3422 }
3423
3424# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3425 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
171ae1a4
AW
3426 $rawline !~ m/^$UTF8*$/) {
3427 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3428
3429 my $blank = copy_spacing($rawline);
3430 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3431 my $hereptr = "$hereline$ptr\n";
3432
34d99219
JP
3433 CHK("INVALID_UTF8",
3434 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
00df344f
AW
3435 }
3436
15662b3e
JP
3437# Check if it's the start of a commit log
3438# (not a header line and we haven't seen the patch filename)
3439 if ($in_header_lines && $realfile =~ /^$/ &&
eb3a58de
JP
3440 !($rawline =~ /^\s+(?:\S|$)/ ||
3441 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
15662b3e
JP
3442 $in_header_lines = 0;
3443 $in_commit_log = 1;
ed43c4e5 3444 $has_commit_log = 1;
15662b3e
JP
3445 }
3446
fa64205d
PS
3447# Check if there is UTF-8 in a commit log when a mail header has explicitly
3448# declined it, i.e defined some charset where it is missing.
3449 if ($in_header_lines &&
3450 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3451 $1 !~ /utf-8/i) {
3452 $non_utf8_charset = 1;
3453 }
3454
3455 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
15662b3e 3456 $rawline =~ /$NON_ASCII_UTF8/) {
fa64205d 3457 WARN("UTF8_BEFORE_PATCH",
15662b3e
JP
3458 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3459 }
3460
d6430f71
JP
3461# Check for absolute kernel paths in commit message
3462 if ($tree && $in_commit_log) {
3463 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3464 my $file = $1;
3465
3466 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3467 check_absolute_file($1, $herecurr)) {
3468 #
3469 } else {
3470 check_absolute_file($file, $herecurr);
3471 }
3472 }
3473 }
3474
66b47b4a 3475# Check for various typo / spelling mistakes
66d7a382
JP
3476 if (defined($misspellings) &&
3477 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
7da07c31 3478 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
66b47b4a 3479 my $typo = $1;
7da07c31
DR
3480 my $blank = copy_spacing($rawline);
3481 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3482 my $hereptr = "$hereline$ptr\n";
66b47b4a
KC
3483 my $typo_fix = $spelling_fix{lc($typo)};
3484 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3485 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
0675a8fb
JD
3486 my $msg_level = \&WARN;
3487 $msg_level = \&CHK if ($file);
3488 if (&{$msg_level}("TYPO_SPELLING",
7da07c31 3489 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
66b47b4a
KC
3490 $fix) {
3491 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3492 }
3493 }
3494 }
3495
a8dd86bf
MC
3496# check for invalid commit id
3497 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3498 my $id;
3499 my $description;
3500 ($id, $description) = git_commit_info($2, undef, undef);
3501 if (!defined($id)) {
3502 WARN("UNKNOWN_COMMIT_ID",
3503 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3504 }
3505 }
3506
310cd06b 3507# check for repeated words separated by a single space
8d0325cc
AS
3508# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3509 if (($rawline =~ /^\+/ || $in_commit_log) &&
3510 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
1db81a68 3511 pos($rawline) = 1 if (!$in_commit_log);
310cd06b
JP
3512 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3513
3514 my $first = $1;
3515 my $second = $2;
1db81a68
DR
3516 my $start_pos = $-[1];
3517 my $end_pos = $+[2];
310cd06b
JP
3518 if ($first =~ /(?:struct|union|enum)/) {
3519 pos($rawline) += length($first) + length($second) + 1;
3520 next;
3521 }
3522
1db81a68 3523 next if (lc($first) ne lc($second));
310cd06b
JP
3524 next if ($first eq 'long');
3525
1db81a68
DR
3526 # check for character before and after the word matches
3527 my $start_char = '';
3528 my $end_char = '';
3529 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3530 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3531
3532 next if ($start_char =~ /^\S$/);
3533 next if (index(" \t.,;?!", $end_char) == -1);
3534
ea7dbab3
DR
3535 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3536 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3537 next if (!exists($allow_repeated_words{lc($first)}));
3538 }
8d0325cc 3539
310cd06b
JP
3540 if (WARN("REPEATED_WORD",
3541 "Possible repeated word: '$first'\n" . $herecurr) &&
3542 $fix) {
3543 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3544 }
3545 }
3546
3547 # if it's a repeated word on consecutive lines in a comment block
3548 if ($prevline =~ /$;+\s*$/ &&
3549 $prevrawline =~ /($word_pattern)\s*$/) {
3550 my $last_word = $1;
3551 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3552 if (WARN("REPEATED_WORD",
3553 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3554 $fix) {
3555 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3556 }
3557 }
3558 }
3559 }
3560
30670854
AW
3561# ignore non-hunk lines and lines being removed
3562 next if (!$hunk_line || $line =~ /^-/);
0a920b5b 3563
0a920b5b 3564#trailing whitespace
9c0ca6f9 3565 if ($line =~ /^\+.*\015/) {
c2fdda0d 3566 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
d5e616fc
JP
3567 if (ERROR("DOS_LINE_ENDINGS",
3568 "DOS line endings\n" . $herevet) &&
3569 $fix) {
194f66fc 3570 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
d5e616fc 3571 }
c2fdda0d
AW
3572 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3573 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3705ce5b
JP
3574 if (ERROR("TRAILING_WHITESPACE",
3575 "trailing whitespace\n" . $herevet) &&
3576 $fix) {
194f66fc 3577 $fixed[$fixlinenr] =~ s/\s+$//;
3705ce5b
JP
3578 }
3579
d2c0a235 3580 $rpt_cleaners = 1;
0a920b5b 3581 }
5368df20 3582
4783f894 3583# Check for FSF mailing addresses.
109d8cb2 3584 if ($rawline =~ /\bwrite to the Free/i ||
1bde561e 3585 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3e2232f2
JP
3586 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3587 $rawline =~ /\b51\s+Franklin\s+St/i) {
4783f894 3588 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
0675a8fb
JD
3589 my $msg_level = \&ERROR;
3590 $msg_level = \&CHK if ($file);
3591 &{$msg_level}("FSF_MAILING_ADDRESS",
3592 "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)
4783f894
JT
3593 }
3594
3354957a 3595# check for Kconfig help text having a real description
9fe287d7
AW
3596# Only applies when adding the entry originally, after that we do not have
3597# sufficient context to determine whether it is indeed long enough.
3354957a 3598 if ($realfile =~ /Kconfig/ &&
678ae162
UM
3599 # 'choice' is usually the last thing on the line (though
3600 # Kconfig supports named choices), so use a word boundary
3601 # (\b) rather than a whitespace character (\s)
3602 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
b8709bce
JP
3603 my $ln = $linenr;
3604 my $needs_help = 0;
3605 my $has_help = 0;
3606 my $help_length = 0;
3607 while (defined $lines[$ln]) {
3608 my $f = $lines[$ln++];
9fe287d7
AW
3609
3610 next if ($f =~ /^-/);
b8709bce 3611 last if ($f !~ /^[\+ ]/); # !patch context
a1385803 3612
b8709bce
JP
3613 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3614 $needs_help = 1;
3615 next;
3616 }
3617 if ($f =~ /^\+\s*help\s*$/) {
3618 $has_help = 1;
3619 next;
a1385803
AW
3620 }
3621
b8709bce
JP
3622 $f =~ s/^.//; # strip patch context [+ ]
3623 $f =~ s/#.*//; # strip # directives
3624 $f =~ s/^\s+//; # strip leading blanks
3625 next if ($f =~ /^$/); # skip blank lines
678ae162 3626
b8709bce 3627 # At the end of this Kconfig block:
678ae162
UM
3628 # This only checks context lines in the patch
3629 # and so hopefully shouldn't trigger false
3630 # positives, even though some of these are
3631 # common words in help texts
b8709bce
JP
3632 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3633 if|endif|menu|endmenu|source)\b/x) {
9fe287d7
AW
3634 last;
3635 }
b8709bce 3636 $help_length++ if ($has_help);
3354957a 3637 }
b8709bce
JP
3638 if ($needs_help &&
3639 $help_length < $min_conf_desc_length) {
3640 my $stat_real = get_stat_real($linenr, $ln - 1);
56193274 3641 WARN("CONFIG_DESCRIPTION",
b8709bce 3642 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
56193274 3643 }
3354957a
AK
3644 }
3645
7ccf41a8
JP
3646# check MAINTAINERS entries
3647 if ($realfile =~ /^MAINTAINERS$/) {
3648# check MAINTAINERS entries for the right form
3649 if ($rawline =~ /^\+[A-Z]:/ &&
3650 $rawline !~ /^\+[A-Z]:\t\S/) {
3651 if (WARN("MAINTAINERS_STYLE",
3652 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3653 $fix) {
3654 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3655 }
3656 }
3657# check MAINTAINERS entries for the right ordering too
3658 my $preferred_order = 'MRLSWQBCPTFXNK';
3659 if ($rawline =~ /^\+[A-Z]:/ &&
3660 $prevrawline =~ /^[\+ ][A-Z]:/) {
3661 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3662 my $cur = $1;
3663 my $curval = $2;
3664 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3665 my $prev = $1;
3666 my $prevval = $2;
3667 my $curindex = index($preferred_order, $cur);
3668 my $previndex = index($preferred_order, $prev);
3669 if ($curindex < 0) {
3670 WARN("MAINTAINERS_STYLE",
3671 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3672 } else {
3673 if ($previndex >= 0 && $curindex < $previndex) {
3674 WARN("MAINTAINERS_STYLE",
3675 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3676 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3677 ($prev eq 'X' && $cur eq 'X')) &&
3678 ($prevval cmp $curval) > 0) {
3679 WARN("MAINTAINERS_STYLE",
3680 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3681 }
3682 }
628f91a2
JP
3683 }
3684 }
3685
c68e5878
AL
3686 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3687 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3688 my $flag = $1;
3689 my $replacement = {
3690 'EXTRA_AFLAGS' => 'asflags-y',
3691 'EXTRA_CFLAGS' => 'ccflags-y',
3692 'EXTRA_CPPFLAGS' => 'cppflags-y',
3693 'EXTRA_LDFLAGS' => 'ldflags-y',
3694 };
3695
3696 WARN("DEPRECATED_VARIABLE",
3697 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3698 }
3699
bff5da43 3700# check for DT compatible documentation
7dd05b38
FV
3701 if (defined $root &&
3702 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3703 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3704
bff5da43
RH
3705 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3706
cc93319b 3707 my $dt_path = $root . "/Documentation/devicetree/bindings/";
852d095d 3708 my $vp_file = $dt_path . "vendor-prefixes.yaml";
cc93319b 3709
bff5da43
RH
3710 foreach my $compat (@compats) {
3711 my $compat2 = $compat;
185d566b
RH
3712 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3713 my $compat3 = $compat;
3714 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3715 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
bff5da43
RH
3716 if ( $? >> 8 ) {
3717 WARN("UNDOCUMENTED_DT_STRING",
3718 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3719 }
3720
4fbf32a6
FV
3721 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3722 my $vendor = $1;
852d095d 3723 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
bff5da43
RH
3724 if ( $? >> 8 ) {
3725 WARN("UNDOCUMENTED_DT_STRING",
cc93319b 3726 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
bff5da43
RH
3727 }
3728 }
3729 }
3730
9f3a8992
RH
3731# check for using SPDX license tag at beginning of files
3732 if ($realline == $checklicenseline) {
3733 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3734 $checklicenseline = 2;
3735 } elsif ($rawline =~ /^\+/) {
3736 my $comment = "";
3737 if ($realfile =~ /\.(h|s|S)$/) {
3738 $comment = '/*';
d1d84b5f 3739 } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
9f3a8992 3740 $comment = '//';
c8df0ab6 3741 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
9f3a8992
RH
3742 $comment = '#';
3743 } elsif ($realfile =~ /\.rst$/) {
3744 $comment = '..';
3745 }
3746
fdf13693
JP
3747# check SPDX comment style for .[chsS] files
3748 if ($realfile =~ /\.[chsS]$/ &&
3749 $rawline =~ /SPDX-License-Identifier:/ &&
ffbce897 3750 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
fdf13693
JP
3751 WARN("SPDX_LICENSE_TAG",
3752 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3753 }
3754
9f3a8992 3755 if ($comment !~ /^$/ &&
ffbce897
JP
3756 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3757 WARN("SPDX_LICENSE_TAG",
3758 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3b6e8ac9 3759 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
ffbce897
JP
3760 my $spdx_license = $1;
3761 if (!is_SPDX_License_valid($spdx_license)) {
3762 WARN("SPDX_LICENSE_TAG",
3763 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3764 }
50c92900 3765 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
a04bb4c2 3766 $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
50c92900
LR
3767 my $msg_level = \&WARN;
3768 $msg_level = \&CHK if ($file);
3769 if (&{$msg_level}("SPDX_LICENSE_TAG",
3770
3771 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3772 $fix) {
3773 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3774 }
3775 }
a04bb4c2
DR
3776 if ($realfile =~ m@^include/dt-bindings/@ &&
3777 $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3778 WARN("SPDX_LICENSE_TAG",
3779 "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3780 }
9f3a8992
RH
3781 }
3782 }
3783 }
3784
a0154cdb 3785# check for embedded filenames
36217357 3786 if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
a0154cdb
JP
3787 WARN("EMBEDDED_FILENAME",
3788 "It's generally not useful to have the filename in the file\n" . $herecurr);
3789 }
3790
5368df20 3791# check we are in a valid source file if not then ignore this hunk
d1d84b5f 3792 next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
5368df20 3793
a8da38a9
JP
3794# check for using SPDX-License-Identifier on the wrong line number
3795 if ($realline != $checklicenseline &&
3796 $rawline =~ /\bSPDX-License-Identifier:/ &&
3797 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3798 WARN("SPDX_LICENSE_TAG",
3799 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3800 }
3801
47e0c88b
JP
3802# line length limit (with some exclusions)
3803#
3804# There are a few types of lines that may extend beyond $max_line_length:
3805# logging functions like pr_info that end in a string
3806# lines with a single string
3807# #defines that are a single string
2e4bbbc5 3808# lines with an RFC3986 like URL
47e0c88b
JP
3809#
3810# There are 3 different line length message types:
ab1ecabf 3811# LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
47e0c88b
JP
3812# LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3813# LONG_LINE all other lines longer than $max_line_length
3814#
3815# if LONG_LINE is ignored, the other 2 types are also ignored
3816#
3817
b4749e96 3818 if ($line =~ /^\+/ && $length > $max_line_length) {
47e0c88b
JP
3819 my $msg_type = "LONG_LINE";
3820
3821 # Check the allowed long line types first
3822
3823 # logging functions that end in a string that starts
3824 # before $max_line_length
3825 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3826 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3827 $msg_type = "";
3828
3829 # lines with only strings (w/ possible termination)
3830 # #defines with only strings
3831 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3832 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3833 $msg_type = "";
3834
cc147506
JP
3835 # More special cases
3836 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3837 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
d560a5f8
JP
3838 $msg_type = "";
3839
2e4bbbc5
AB
3840 # URL ($rawline is used in case the URL is in a comment)
3841 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3842 $msg_type = "";
3843
47e0c88b
JP
3844 # Otherwise set the alternate message types
3845
3846 # a comment starts before $max_line_length
3847 } elsif ($line =~ /($;[\s$;]*)$/ &&
3848 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3849 $msg_type = "LONG_LINE_COMMENT"
3850
3851 # a quoted string starts before $max_line_length
3852 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3853 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3854 $msg_type = "LONG_LINE_STRING"
3855 }
3856
3857 if ($msg_type ne "" &&
3858 (show_type("LONG_LINE") || show_type($msg_type))) {
bdc48fa1
JP
3859 my $msg_level = \&WARN;
3860 $msg_level = \&CHK if ($file);
3861 &{$msg_level}($msg_type,
3862 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
47e0c88b 3863 }
0a920b5b
AW
3864 }
3865
8905a67c
AW
3866# check for adding lines without a newline.
3867 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
47ca69b8
TR
3868 if (WARN("MISSING_EOF_NEWLINE",
3869 "adding a line without newline at end of file\n" . $herecurr) &&
3870 $fix) {
3871 fix_delete_line($fixlinenr+1, "No newline at end of file");
3872 }
8905a67c
AW
3873 }
3874
de93245c
AS
3875# check for .L prefix local symbols in .S files
3876 if ($realfile =~ /\.S$/ &&
3877 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3878 WARN("AVOID_L_PREFIX",
f4bf1cd4 3879 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr);
de93245c
AS
3880 }
3881
b9ea10d6 3882# check we are in a valid source file C or perl if not then ignore this hunk
de4c924c 3883 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
0a920b5b
AW
3884
3885# at the beginning of a line any tabs must come first and anything
713a09de 3886# more than $tabsize must use tabs.
c2fdda0d
AW
3887 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3888 $rawline =~ /^\+\s* \s*/) {
3889 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
d2c0a235 3890 $rpt_cleaners = 1;
3705ce5b
JP
3891 if (ERROR("CODE_INDENT",
3892 "code indent should use tabs where possible\n" . $herevet) &&
3893 $fix) {
194f66fc 3894 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3705ce5b 3895 }
0a920b5b
AW
3896 }
3897
08e44365
AP
3898# check for space before tabs.
3899 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3900 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3705ce5b
JP
3901 if (WARN("SPACE_BEFORE_TAB",
3902 "please, no space before tabs\n" . $herevet) &&
3903 $fix) {
194f66fc 3904 while ($fixed[$fixlinenr] =~
713a09de 3905 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
194f66fc 3906 while ($fixed[$fixlinenr] =~
c76f4cb3 3907 s/(^\+.*) +\t/$1\t/) {}
3705ce5b 3908 }
08e44365 3909 }
6a487211
JP
3910
3911# check for assignments on the start of a line
3912 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
da7355ab
AS
3913 my $operator = $1;
3914 if (CHK("ASSIGNMENT_CONTINUATIONS",
3915 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3916 $fix && $prevrawline =~ /^\+/) {
3917 # add assignment operator to the previous line, remove from current line
3918 $fixed[$fixlinenr - 1] .= " $operator";
3919 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3920 }
6a487211 3921 }
08e44365 3922
d1fe9c09
JP
3923# check for && or || at the start of a line
3924 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
8e08f076
AS
3925 my $operator = $1;
3926 if (CHK("LOGICAL_CONTINUATIONS",
3927 "Logical continuations should be on the previous line\n" . $hereprev) &&
3928 $fix && $prevrawline =~ /^\+/) {
3929 # insert logical operator at last non-comment, non-whitepsace char on previous line
3930 $prevline =~ /[\s$;]*$/;
3931 my $line_end = substr($prevrawline, $-[0]);
3932 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3933 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3934 }
d1fe9c09
JP
3935 }
3936
a91e8994 3937# check indentation starts on a tab stop
5b57980d 3938 if ($perl_version_ok &&
bd49111f 3939 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
a91e8994 3940 my $indent = length($1);
713a09de 3941 if ($indent % $tabsize) {
a91e8994
JP
3942 if (WARN("TABSTOP",
3943 "Statements should start on a tabstop\n" . $herecurr) &&
3944 $fix) {
713a09de 3945 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
a91e8994
JP
3946 }
3947 }
3948 }
3949
d1fe9c09 3950# check multi-line statement indentation matches previous line
5b57980d 3951 if ($perl_version_ok &&
fd71f632 3952 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
d1fe9c09
JP
3953 $prevline =~ /^\+(\t*)(.*)$/;
3954 my $oldindent = $1;
3955 my $rest = $2;
3956
3957 my $pos = pos_last_openparen($rest);
3958 if ($pos >= 0) {
b34a26f3
JP
3959 $line =~ /^(\+| )([ \t]*)/;
3960 my $newindent = $2;
d1fe9c09
JP
3961
3962 my $goodtabindent = $oldindent .
713a09de
AB
3963 "\t" x ($pos / $tabsize) .
3964 " " x ($pos % $tabsize);
d1fe9c09
JP
3965 my $goodspaceindent = $oldindent . " " x $pos;
3966
3967 if ($newindent ne $goodtabindent &&
3968 $newindent ne $goodspaceindent) {
3705ce5b
JP
3969
3970 if (CHK("PARENTHESIS_ALIGNMENT",
3971 "Alignment should match open parenthesis\n" . $hereprev) &&
3972 $fix && $line =~ /^\+/) {
194f66fc 3973 $fixed[$fixlinenr] =~
3705ce5b
JP
3974 s/^\+[ \t]*/\+$goodtabindent/;
3975 }
d1fe9c09
JP
3976 }
3977 }
3978 }
3979
6ab3a970
JP
3980# check for space after cast like "(int) foo" or "(struct foo) bar"
3981# avoid checking a few false positives:
3982# "sizeof(<type>)" or "__alignof__(<type>)"
3983# function pointer declarations like "(*foo)(int) = bar;"
3984# structure definitions like "(struct foo) { 0 };"
3985# multiline macros that define functions
3986# known attributes or the __attribute__ keyword
3987 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3988 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3705ce5b 3989 if (CHK("SPACING",
f27c95db 3990 "No space is necessary after a cast\n" . $herecurr) &&
3705ce5b 3991 $fix) {
194f66fc 3992 $fixed[$fixlinenr] =~
f27c95db 3993 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3705ce5b 3994 }
aad4f614
JP
3995 }
3996
86406b1c
JP
3997# Block comment styles
3998# Networking with an initial /*
05880600 3999 if ($realfile =~ m@^(drivers/net/|net/)@ &&
fdb4bcd6 4000 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
85ad978c 4001 $rawline =~ /^\+[ \t]*\*/ &&
c70735c2 4002 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
05880600
JP
4003 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
4004 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
4005 }
4006
86406b1c
JP
4007# Block comments use * on subsequent lines
4008 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4009 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
a605e32e 4010 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
61135e96 4011 $rawline =~ /^\+/ && #line is new
a605e32e 4012 $rawline !~ /^\+[ \t]*\*/) { #no leading *
86406b1c
JP
4013 WARN("BLOCK_COMMENT_STYLE",
4014 "Block comments use * on subsequent lines\n" . $hereprev);
a605e32e
JP
4015 }
4016
86406b1c
JP
4017# Block comments use */ on trailing lines
4018 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
c24f9f19
JP
4019 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
4020 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
4021 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
86406b1c
JP
4022 WARN("BLOCK_COMMENT_STYLE",
4023 "Block comments use a trailing */ on a separate line\n" . $herecurr);
05880600
JP
4024 }
4025
08eb9b80
JP
4026# Block comment * alignment
4027 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
af207524
JP
4028 $line =~ /^\+[ \t]*$;/ && #leading comment
4029 $rawline =~ /^\+[ \t]*\*/ && #leading *
4030 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
08eb9b80 4031 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
af207524
JP
4032 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4033 my $oldindent;
08eb9b80 4034 $prevrawline =~ m@^\+([ \t]*/?)\*@;
af207524
JP
4035 if (defined($1)) {
4036 $oldindent = expand_tabs($1);
4037 } else {
4038 $prevrawline =~ m@^\+(.*/?)\*@;
4039 $oldindent = expand_tabs($1);
4040 }
08eb9b80
JP
4041 $rawline =~ m@^\+([ \t]*)\*@;
4042 my $newindent = $1;
08eb9b80 4043 $newindent = expand_tabs($newindent);
af207524 4044 if (length($oldindent) ne length($newindent)) {
08eb9b80
JP
4045 WARN("BLOCK_COMMENT_STYLE",
4046 "Block comments should align the * on each line\n" . $hereprev);
4047 }
4048 }
4049
7f619191
JP
4050# check for missing blank lines after struct/union declarations
4051# with exceptions for various attributes and macros
4052 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4053 $line =~ /^\+/ &&
4054 !($line =~ /^\+\s*$/ ||
05dc40e6 4055 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
7f619191
JP
4056 $line =~ /^\+\s*MODULE_/i ||
4057 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4058 $line =~ /^\+[a-z_]*init/ ||
4059 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4060 $line =~ /^\+\s*DECLARE/ ||
0bc989ff 4061 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
7f619191 4062 $line =~ /^\+\s*__setup/)) {
d752fcc8
JP
4063 if (CHK("LINE_SPACING",
4064 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4065 $fix) {
f2d7e4d4 4066 fix_insert_line($fixlinenr, "\+");
d752fcc8 4067 }
7f619191
JP
4068 }
4069
365dd4ea
JP
4070# check for multiple consecutive blank lines
4071 if ($prevline =~ /^[\+ ]\s*$/ &&
4072 $line =~ /^\+\s*$/ &&
4073 $last_blank_line != ($linenr - 1)) {
d752fcc8
JP
4074 if (CHK("LINE_SPACING",
4075 "Please don't use multiple blank lines\n" . $hereprev) &&
4076 $fix) {
f2d7e4d4 4077 fix_delete_line($fixlinenr, $rawline);
d752fcc8
JP
4078 }
4079
365dd4ea
JP
4080 $last_blank_line = $linenr;
4081 }
4082
3b617e3b 4083# check for missing blank lines after declarations
b5e8736a
JP
4084# (declarations must have the same indentation and not be at the start of line)
4085 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4086 # use temporaries
4087 my $sl = $sline;
4088 my $pl = $prevline;
4089 # remove $Attribute/$Sparse uses to simplify comparisons
4090 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4091 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4092 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
5a4e1fd3 4093 # function pointer declarations
b5e8736a 4094 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3f7bac03 4095 # foo bar; where foo is some local typedef or #define
b5e8736a 4096 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3f7bac03 4097 # known declaration macros
b5e8736a 4098 $pl =~ /^\+\s+$declaration_macros/) &&
3f7bac03 4099 # for "else if" which can look like "$Ident $Ident"
b5e8736a 4100 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3f7bac03 4101 # other possible extensions of declaration lines
b5e8736a 4102 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3f7bac03 4103 # not starting a section or a macro "\" extended line
b5e8736a 4104 $pl =~ /(?:\{\s*|\\)$/) &&
3f7bac03 4105 # looks like a declaration
b5e8736a 4106 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
5a4e1fd3 4107 # function pointer declarations
b5e8736a 4108 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3f7bac03 4109 # foo bar; where foo is some local typedef or #define
b5e8736a 4110 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3f7bac03 4111 # known declaration macros
b5e8736a 4112 $sl =~ /^\+\s+$declaration_macros/ ||
3f7bac03 4113 # start of struct or union or enum
b5e8736a 4114 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3f7bac03 4115 # start or end of block or continuation of declaration
b5e8736a 4116 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3f7bac03 4117 # bitfield continuation
b5e8736a 4118 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3f7bac03 4119 # other possible extensions of declaration lines
b5e8736a
JP
4120 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4121 if (WARN("LINE_SPACING",
4122 "Missing a blank line after declarations\n" . $hereprev) &&
4123 $fix) {
4124 fix_insert_line($fixlinenr, "\+");
4125 }
d752fcc8 4126 }
3b617e3b
JP
4127 }
4128
5f7ddae6 4129# check for spaces at the beginning of a line.
6b4c5beb
AW
4130# Exceptions:
4131# 1) within comments
4132# 2) indented preprocessor commands
4133# 3) hanging labels
3705ce5b 4134 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
5f7ddae6 4135 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3705ce5b
JP
4136 if (WARN("LEADING_SPACE",
4137 "please, no spaces at the start of a line\n" . $herevet) &&
4138 $fix) {
194f66fc 4139 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3705ce5b 4140 }
5f7ddae6
RR
4141 }
4142
b9ea10d6
AW
4143# check we are in a valid C source file if not then ignore this hunk
4144 next if ($realfile !~ /\.(h|c)$/);
4145
5751a24e
JP
4146# check for unusual line ending [ or (
4147 if ($line =~ /^\+.*([\[\(])\s*$/) {
4148 CHK("OPEN_ENDED_LINE",
4149 "Lines should not end with a '$1'\n" . $herecurr);
4150 }
4151
4dbed76f
JP
4152# check if this appears to be the start function declaration, save the name
4153 if ($sline =~ /^\+\{\s*$/ &&
4154 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4155 $context_function = $1;
4156 }
4157
4158# check if this appears to be the end of function declaration
4159 if ($sline =~ /^\+\}\s*$/) {
4160 undef $context_function;
4161 }
4162
032a4c0f 4163# check indentation of any line with a bare else
840080a0 4164# (but not if it is a multiple line "if (foo) return bar; else return baz;")
032a4c0f
JP
4165# if the previous line is a break or return and is indented 1 tab more...
4166 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4167 my $tabs = length($1) + 1;
840080a0
JP
4168 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4169 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4170 defined $lines[$linenr] &&
4171 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
032a4c0f
JP
4172 WARN("UNNECESSARY_ELSE",
4173 "else is not generally useful after a break or return\n" . $hereprev);
4174 }
4175 }
4176
c00df19a 4177# check indentation of a line with a break;
dc58bc55
JP
4178# if the previous line is a goto, return or break
4179# and is indented the same # of tabs
c00df19a
JP
4180 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4181 my $tabs = $1;
dc58bc55
JP
4182 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4183 if (WARN("UNNECESSARY_BREAK",
4184 "break is not useful after a $1\n" . $hereprev) &&
4185 $fix) {
4186 fix_delete_line($fixlinenr, $rawline);
4187 }
c00df19a
JP
4188 }
4189 }
4190
c2fdda0d 4191# check for RCS/CVS revision markers
cf655043 4192 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
000d1cc1
JP
4193 WARN("CVS_KEYWORD",
4194 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
c2fdda0d 4195 }
22f2a2ef 4196
56e77d70
JP
4197# check for old HOTPLUG __dev<foo> section markings
4198 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4199 WARN("HOTPLUG_SECTION",
4200 "Using $1 is unnecessary\n" . $herecurr);
4201 }
4202
9c0ca6f9 4203# Check for potential 'bare' types
2b474a1a
AW
4204 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4205 $realline_next);
3e469cdc 4206#print "LINE<$line>\n";
ca819864 4207 if ($linenr > $suppress_statement &&
1b5539b1 4208 $realcnt && $sline =~ /.\s*\S/) {
170d3a22 4209 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
f5fe35dd 4210 ctx_statement_block($linenr, $realcnt, 0);
171ae1a4
AW
4211 $stat =~ s/\n./\n /g;
4212 $cond =~ s/\n./\n /g;
4213
3e469cdc
AW
4214#print "linenr<$linenr> <$stat>\n";
4215 # If this statement has no statement boundaries within
4216 # it there is no point in retrying a statement scan
4217 # until we hit end of it.
4218 my $frag = $stat; $frag =~ s/;+\s*$//;
4219 if ($frag !~ /(?:{|;)/) {
4220#print "skip<$line_nr_next>\n";
4221 $suppress_statement = $line_nr_next;
4222 }
f74bd194 4223
2b474a1a
AW
4224 # Find the real next line.
4225 $realline_next = $line_nr_next;
4226 if (defined $realline_next &&
4227 (!defined $lines[$realline_next - 1] ||
4228 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4229 $realline_next++;
4230 }
4231
171ae1a4
AW
4232 my $s = $stat;
4233 $s =~ s/{.*$//s;
cf655043 4234
c2fdda0d 4235 # Ignore goto labels.
171ae1a4 4236 if ($s =~ /$Ident:\*$/s) {
c2fdda0d
AW
4237
4238 # Ignore functions being called
171ae1a4 4239 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
c2fdda0d 4240
463f2864
AW
4241 } elsif ($s =~ /^.\s*else\b/s) {
4242
c45dcabd 4243 # declarations always start with types
d2506586 4244 } 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) {
c45dcabd
AW
4245 my $type = $1;
4246 $type =~ s/\s+/ /g;
4247 possible($type, "A:" . $s);
4248
8905a67c 4249 # definitions in global scope can only start with types
a6a84062 4250 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
c45dcabd 4251 possible($1, "B:" . $s);
c2fdda0d 4252 }
8905a67c
AW
4253
4254 # any (foo ... *) is a pointer cast, and foo is a type
65863862 4255 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
c45dcabd 4256 possible($1, "C:" . $s);
8905a67c
AW
4257 }
4258
4259 # Check for any sort of function declaration.
4260 # int foo(something bar, other baz);
4261 # void (*store_gdt)(x86_descr_ptr *);
171ae1a4 4262 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
8905a67c 4263 my ($name_len) = length($1);
8905a67c 4264
cf655043 4265 my $ctx = $s;
773647a0 4266 substr($ctx, 0, $name_len + 1, '');
8905a67c 4267 $ctx =~ s/\)[^\)]*$//;
cf655043 4268
8905a67c 4269 for my $arg (split(/\s*,\s*/, $ctx)) {
c45dcabd 4270 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
8905a67c 4271
c45dcabd 4272 possible($1, "D:" . $s);
8905a67c
AW
4273 }
4274 }
9c0ca6f9 4275 }
8905a67c 4276
9c0ca6f9
AW
4277 }
4278
653d4876
AW
4279#
4280# Checks which may be anchored in the context.
4281#
00df344f 4282
653d4876
AW
4283# Check for switch () and associated case and default
4284# statements should be at the same indent.
00df344f
AW
4285 if ($line=~/\bswitch\s*\(.*\)/) {
4286 my $err = '';
4287 my $sep = '';
4288 my @ctx = ctx_block_outer($linenr, $realcnt);
4289 shift(@ctx);
4290 for my $ctx (@ctx) {
4291 my ($clen, $cindent) = line_stats($ctx);
4292 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4293 $indent != $cindent) {
4294 $err .= "$sep$ctx\n";
4295 $sep = '';
4296 } else {
4297 $sep = "[...]\n";
4298 }
4299 }
4300 if ($err ne '') {
000d1cc1
JP
4301 ERROR("SWITCH_CASE_INDENT_LEVEL",
4302 "switch and case should be at the same indent\n$hereline$err");
de7d4f0e
AW
4303 }
4304 }
4305
4306# if/while/etc brace do not go on next line, unless defining a do while loop,
4307# or if that brace on the next line is for something else
0fe3dc2b 4308 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
773647a0
AW
4309 my $pre_ctx = "$1$2";
4310
9c0ca6f9 4311 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
8eef05dd
JP
4312
4313 if ($line =~ /^\+\t{6,}/) {
4314 WARN("DEEP_INDENTATION",
4315 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4316 }
4317
de7d4f0e
AW
4318 my $ctx_cnt = $realcnt - $#ctx - 1;
4319 my $ctx = join("\n", @ctx);
4320
548596d5
AW
4321 my $ctx_ln = $linenr;
4322 my $ctx_skip = $realcnt;
773647a0 4323
548596d5
AW
4324 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4325 defined $lines[$ctx_ln - 1] &&
4326 $lines[$ctx_ln - 1] =~ /^-/)) {
4327 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4328 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
de7d4f0e 4329 $ctx_ln++;
de7d4f0e 4330 }
548596d5 4331
53210168
AW
4332 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4333 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
de7d4f0e 4334
d752fcc8 4335 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
000d1cc1
JP
4336 ERROR("OPEN_BRACE",
4337 "that open brace { should be on the previous line\n" .
01464f30 4338 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
00df344f 4339 }
773647a0
AW
4340 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4341 $ctx =~ /\)\s*\;\s*$/ &&
4342 defined $lines[$ctx_ln - 1])
4343 {
9c0ca6f9
AW
4344 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4345 if ($nindent > $indent) {
000d1cc1
JP
4346 WARN("TRAILING_SEMICOLON",
4347 "trailing semicolon indicates no statements, indent implies otherwise\n" .
01464f30 4348 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
9c0ca6f9
AW
4349 }
4350 }
00df344f
AW
4351 }
4352
4d001e4d 4353# Check relative indent for conditionals and blocks.
f6950a73 4354 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3e469cdc
AW
4355 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4356 ctx_statement_block($linenr, $realcnt, 0)
4357 if (!defined $stat);
4d001e4d
AW
4358 my ($s, $c) = ($stat, $cond);
4359
4360 substr($s, 0, length($c), '');
4361
9f5af480
JP
4362 # remove inline comments
4363 $s =~ s/$;/ /g;
4364 $c =~ s/$;/ /g;
4d001e4d
AW
4365
4366 # Find out how long the conditional actually is.
6f779c18
AW
4367 my @newlines = ($c =~ /\n/gs);
4368 my $cond_lines = 1 + $#newlines;
4d001e4d 4369
9f5af480
JP
4370 # Make sure we remove the line prefixes as we have
4371 # none on the first line, and are going to readd them
4372 # where necessary.
4373 $s =~ s/\n./\n/gs;
4374 while ($s =~ /\n\s+\\\n/) {
4375 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4376 }
4377
4d001e4d
AW
4378 # We want to check the first line inside the block
4379 # starting at the end of the conditional, so remove:
4380 # 1) any blank line termination
4381 # 2) any opening brace { on end of the line
4382 # 3) any do (...) {
4383 my $continuation = 0;
4384 my $check = 0;
4385 $s =~ s/^.*\bdo\b//;
4386 $s =~ s/^\s*{//;
4387 if ($s =~ s/^\s*\\//) {
4388 $continuation = 1;
4389 }
9bd49efe 4390 if ($s =~ s/^\s*?\n//) {
4d001e4d
AW
4391 $check = 1;
4392 $cond_lines++;
4393 }
4394
4395 # Also ignore a loop construct at the end of a
4396 # preprocessor statement.
4397 if (($prevline =~ /^.\s*#\s*define\s/ ||
4398 $prevline =~ /\\\s*$/) && $continuation == 0) {
4399 $check = 0;
4400 }
4401
9bd49efe 4402 my $cond_ptr = -1;
740504c6 4403 $continuation = 0;
9bd49efe
AW
4404 while ($cond_ptr != $cond_lines) {
4405 $cond_ptr = $cond_lines;
4406
f16fa28f
AW
4407 # If we see an #else/#elif then the code
4408 # is not linear.
4409 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4410 $check = 0;
4411 }
4412
9bd49efe
AW
4413 # Ignore:
4414 # 1) blank lines, they should be at 0,
4415 # 2) preprocessor lines, and
4416 # 3) labels.
740504c6
AW
4417 if ($continuation ||
4418 $s =~ /^\s*?\n/ ||
9bd49efe
AW
4419 $s =~ /^\s*#\s*?/ ||
4420 $s =~ /^\s*$Ident\s*:/) {
740504c6 4421 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
30dad6eb
AW
4422 if ($s =~ s/^.*?\n//) {
4423 $cond_lines++;
4424 }
9bd49efe 4425 }
4d001e4d
AW
4426 }
4427
4428 my (undef, $sindent) = line_stats("+" . $s);
4429 my $stat_real = raw_line($linenr, $cond_lines);
4430
4431 # Check if either of these lines are modified, else
4432 # this is not this patch's fault.
4433 if (!defined($stat_real) ||
4434 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4435 $check = 0;
4436 }
4437 if (defined($stat_real) && $cond_lines > 1) {
4438 $stat_real = "[...]\n$stat_real";
4439 }
4440
9bd49efe 4441 #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";
4d001e4d 4442
9f5af480 4443 if ($check && $s ne '' &&
713a09de 4444 (($sindent % $tabsize) != 0 ||
9f5af480 4445 ($sindent < $indent) ||
f6950a73
JP
4446 ($sindent == $indent &&
4447 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
713a09de 4448 ($sindent > $indent + $tabsize))) {
000d1cc1
JP
4449 WARN("SUSPECT_CODE_INDENT",
4450 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4d001e4d
AW
4451 }
4452 }
4453
6c72ffaa
AW
4454 # Track the 'values' across context and added lines.
4455 my $opline = $line; $opline =~ s/^./ /;
1f65f947
AW
4456 my ($curr_values, $curr_vars) =
4457 annotate_values($opline . "\n", $prev_values);
6c72ffaa 4458 $curr_values = $prev_values . $curr_values;
c2fdda0d
AW
4459 if ($dbg_values) {
4460 my $outline = $opline; $outline =~ s/\t/ /g;
cf655043
AW
4461 print "$linenr > .$outline\n";
4462 print "$linenr > $curr_values\n";
1f65f947 4463 print "$linenr > $curr_vars\n";
c2fdda0d 4464 }
6c72ffaa
AW
4465 $prev_values = substr($curr_values, -1);
4466
00df344f 4467#ignore lines not being added
3705ce5b 4468 next if ($line =~ /^[^\+]/);
00df344f 4469
99ca38c2
JP
4470# check for self assignments used to avoid compiler warnings
4471# e.g.: int foo = foo, *bar = NULL;
4472# struct foo bar = *(&(bar));
4473 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4474 my $var = $1;
4475 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4476 WARN("SELF_ASSIGNMENT",
4477 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4478 }
4479 }
4480
11ca40a0
JP
4481# check for dereferences that span multiple lines
4482 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4483 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4484 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4485 my $ref = $1;
4486 $line =~ /^.\s*($Lval)/;
4487 $ref .= $1;
4488 $ref =~ s/\s//g;
4489 WARN("MULTILINE_DEREFERENCE",
4490 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4491 }
4492
a1ce18e4 4493# check for declarations of signed or unsigned without int
c8447115 4494 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
a1ce18e4
JP
4495 my $type = $1;
4496 my $var = $2;
207a8e84
JP
4497 $var = "" if (!defined $var);
4498 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
a1ce18e4
JP
4499 my $sign = $1;
4500 my $pointer = $2;
4501
4502 $pointer = "" if (!defined $pointer);
4503
4504 if (WARN("UNSPECIFIED_INT",
4505 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4506 $fix) {
4507 my $decl = trim($sign) . " int ";
207a8e84
JP
4508 my $comp_pointer = $pointer;
4509 $comp_pointer =~ s/\s//g;
4510 $decl .= $comp_pointer;
4511 $decl = rtrim($decl) if ($var eq "");
4512 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
a1ce18e4
JP
4513 }
4514 }
4515 }
4516
653d4876 4517# TEST: allow direct testing of the type matcher.
7429c690
AW
4518 if ($dbg_type) {
4519 if ($line =~ /^.\s*$Declare\s*$/) {
000d1cc1
JP
4520 ERROR("TEST_TYPE",
4521 "TEST: is type\n" . $herecurr);
7429c690 4522 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
000d1cc1
JP
4523 ERROR("TEST_NOT_TYPE",
4524 "TEST: is not type ($1 is)\n". $herecurr);
7429c690 4525 }
653d4876
AW
4526 next;
4527 }
a1ef277e
AW
4528# TEST: allow direct testing of the attribute matcher.
4529 if ($dbg_attr) {
9360b0e5 4530 if ($line =~ /^.\s*$Modifier\s*$/) {
000d1cc1
JP
4531 ERROR("TEST_ATTR",
4532 "TEST: is attr\n" . $herecurr);
9360b0e5 4533 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
000d1cc1
JP
4534 ERROR("TEST_NOT_ATTR",
4535 "TEST: is not attr ($1 is)\n". $herecurr);
a1ef277e
AW
4536 }
4537 next;
4538 }
653d4876 4539
f0a594c1 4540# check for initialisation to aggregates open brace on the next line
99423c20
AW
4541 if ($line =~ /^.\s*{/ &&
4542 $prevline =~ /(?:^|[^=])=\s*$/) {
d752fcc8
JP
4543 if (ERROR("OPEN_BRACE",
4544 "that open brace { should be on the previous line\n" . $hereprev) &&
f2d7e4d4
JP
4545 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4546 fix_delete_line($fixlinenr - 1, $prevrawline);
4547 fix_delete_line($fixlinenr, $rawline);
d752fcc8
JP
4548 my $fixedline = $prevrawline;
4549 $fixedline =~ s/\s*=\s*$/ = {/;
f2d7e4d4 4550 fix_insert_line($fixlinenr, $fixedline);
d752fcc8 4551 $fixedline = $line;
8d81ae05 4552 $fixedline =~ s/^(.\s*)\{\s*/$1/;
f2d7e4d4 4553 fix_insert_line($fixlinenr, $fixedline);
d752fcc8 4554 }
f0a594c1
AW
4555 }
4556
653d4876
AW
4557#
4558# Checks which are anchored on the added line.
4559#
4560
4561# check for malformed paths in #include statements (uses RAW line)
c45dcabd 4562 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
653d4876
AW
4563 my $path = $1;
4564 if ($path =~ m{//}) {
000d1cc1 4565 ERROR("MALFORMED_INCLUDE",
495e9d84
JP
4566 "malformed #include filename\n" . $herecurr);
4567 }
4568 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4569 ERROR("UAPI_INCLUDE",
4570 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
653d4876 4571 }
653d4876 4572 }
00df344f 4573
0a920b5b 4574# no C99 // comments
00df344f 4575 if ($line =~ m{//}) {
3705ce5b
JP
4576 if (ERROR("C99_COMMENTS",
4577 "do not use C99 // comments\n" . $herecurr) &&
4578 $fix) {
194f66fc 4579 my $line = $fixed[$fixlinenr];
3705ce5b
JP
4580 if ($line =~ /\/\/(.*)$/) {
4581 my $comment = trim($1);
194f66fc 4582 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3705ce5b
JP
4583 }
4584 }
0a920b5b 4585 }
00df344f 4586 # Remove C99 comments.
0a920b5b 4587 $line =~ s@//.*@@;
6c72ffaa 4588 $opline =~ s@//.*@@;
0a920b5b 4589
2b474a1a
AW
4590# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4591# the whole statement.
4592#print "APW <$lines[$realline_next - 1]>\n";
4593 if (defined $realline_next &&
4594 exists $lines[$realline_next - 1] &&
4595 !defined $suppress_export{$realline_next} &&
36794822 4596 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
3cbf62df
AW
4597 # Handle definitions which produce identifiers with
4598 # a prefix:
4599 # XXX(foo);
4600 # EXPORT_SYMBOL(something_foo);
653d4876 4601 my $name = $1;
70a11659 4602 $name =~ s/^\s*($Ident).*/$1/;
87a53877 4603 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3cbf62df
AW
4604 $name =~ /^${Ident}_$2/) {
4605#print "FOO C name<$name>\n";
4606 $suppress_export{$realline_next} = 1;
4607
4608 } elsif ($stat !~ /(?:
2b474a1a 4609 \n.}\s*$|
48012058
AW
4610 ^.DEFINE_$Ident\(\Q$name\E\)|
4611 ^.DECLARE_$Ident\(\Q$name\E\)|
4612 ^.LIST_HEAD\(\Q$name\E\)|
2b474a1a
AW
4613 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4614 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
48012058 4615 )/x) {
2b474a1a
AW
4616#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4617 $suppress_export{$realline_next} = 2;
4618 } else {
4619 $suppress_export{$realline_next} = 1;
0a920b5b
AW
4620 }
4621 }
2b474a1a
AW
4622 if (!defined $suppress_export{$linenr} &&
4623 $prevline =~ /^.\s*$/ &&
36794822 4624 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
2b474a1a
AW
4625#print "FOO B <$lines[$linenr - 1]>\n";
4626 $suppress_export{$linenr} = 2;
4627 }
4628 if (defined $suppress_export{$linenr} &&
4629 $suppress_export{$linenr} == 2) {
000d1cc1
JP
4630 WARN("EXPORT_SYMBOL",
4631 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2b474a1a 4632 }
0a920b5b 4633
5150bda4 4634# check for global initialisers.
5b8f82e1
SL
4635 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4636 !exclude_global_initialisers($realfile)) {
d5e616fc 4637 if (ERROR("GLOBAL_INITIALISERS",
6d32f7a3 4638 "do not initialise globals to $1\n" . $herecurr) &&
d5e616fc 4639 $fix) {
6d32f7a3 4640 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
d5e616fc 4641 }
f0a594c1 4642 }
653d4876 4643# check for static initialisers.
6d32f7a3 4644 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
d5e616fc 4645 if (ERROR("INITIALISED_STATIC",
6d32f7a3 4646 "do not initialise statics to $1\n" .
d5e616fc
JP
4647 $herecurr) &&
4648 $fix) {
6d32f7a3 4649 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
d5e616fc 4650 }
0a920b5b
AW
4651 }
4652
1813087d
JP
4653# check for misordered declarations of char/short/int/long with signed/unsigned
4654 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4655 my $tmp = trim($1);
4656 WARN("MISORDERED_TYPE",
4657 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4658 }
4659
809e082e
JP
4660# check for unnecessary <signed> int declarations of short/long/long long
4661 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4662 my $type = trim($1);
4663 next if ($type !~ /\bint\b/);
4664 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4665 my $new_type = $type;
4666 $new_type =~ s/\b\s*int\s*\b/ /;
4667 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4668 $new_type =~ s/^const\s+//;
4669 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4670 $new_type = "const $new_type" if ($type =~ /^const\b/);
4671 $new_type =~ s/\s+/ /g;
4672 $new_type = trim($new_type);
4673 if (WARN("UNNECESSARY_INT",
4674 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4675 $fix) {
4676 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4677 }
4678 }
4679
cb710eca
JP
4680# check for static const char * arrays.
4681 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
000d1cc1
JP
4682 WARN("STATIC_CONST_CHAR_ARRAY",
4683 "static const char * array should probably be static const char * const\n" .
cb710eca 4684 $herecurr);
77b8c0a8
JP
4685 }
4686
4687# check for initialized const char arrays that should be static const
4688 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4689 if (WARN("STATIC_CONST_CHAR_ARRAY",
4690 "const array should probably be static const\n" . $herecurr) &&
4691 $fix) {
4692 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4693 }
4694 }
cb710eca
JP
4695
4696# check for static char foo[] = "bar" declarations.
4697 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
000d1cc1
JP
4698 WARN("STATIC_CONST_CHAR_ARRAY",
4699 "static char array declaration should probably be static const char\n" .
cb710eca 4700 $herecurr);
77b8c0a8 4701 }
cb710eca 4702
ab7e23f3
JP
4703# check for const <foo> const where <foo> is not a pointer or array type
4704 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4705 my $found = $1;
4706 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4707 WARN("CONST_CONST",
4708 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4709 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4710 WARN("CONST_CONST",
4711 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4712 }
4713 }
4714
73169765
JP
4715# check for const static or static <non ptr type> const declarations
4716# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4717 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4718 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4719 if (WARN("STATIC_CONST",
4720 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4721 $fix) {
4722 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4723 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4724 }
4725 }
4726
9b0fa60d
JP
4727# check for non-global char *foo[] = {"bar", ...} declarations.
4728 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4729 WARN("STATIC_CONST_CHAR_ARRAY",
4730 "char * array declaration might be better as static const\n" .
4731 $herecurr);
ea7dbab3 4732 }
9b0fa60d 4733
b598b670
JP
4734# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4735 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4736 my $array = $1;
4737 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4738 my $array_div = $1;
4739 if (WARN("ARRAY_SIZE",
4740 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4741 $fix) {
4742 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4743 }
4744 }
4745 }
4746
b36190c5 4747# check for function declarations without arguments like "int foo()"
16b7f3c8 4748 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
b36190c5
JP
4749 if (ERROR("FUNCTION_WITHOUT_ARGS",
4750 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4751 $fix) {
194f66fc 4752 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
b36190c5
JP
4753 }
4754 }
4755
653d4876
AW
4756# check for new typedefs, only function parameters and sparse annotations
4757# make sense.
4758 if ($line =~ /\btypedef\s/ &&
8054576d 4759 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
c45dcabd 4760 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
8ed22cad 4761 $line !~ /\b$typeTypedefs\b/ &&
46d832f5 4762 $line !~ /\b__bitwise\b/) {
000d1cc1
JP
4763 WARN("NEW_TYPEDEFS",
4764 "do not add new typedefs\n" . $herecurr);
0a920b5b
AW
4765 }
4766
4767# * goes on variable not on type
65863862 4768 # (char*[ const])
bfcb2cc7
AW
4769 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4770 #print "AA<$1>\n";
3705ce5b 4771 my ($ident, $from, $to) = ($1, $2, $2);
65863862
AW
4772
4773 # Should start with a space.
4774 $to =~ s/^(\S)/ $1/;
4775 # Should not end with a space.
4776 $to =~ s/\s+$//;
4777 # '*'s should not have spaces between.
f9a0b3d1 4778 while ($to =~ s/\*\s+\*/\*\*/) {
65863862 4779 }
d8aaf121 4780
3705ce5b 4781## print "1: from<$from> to<$to> ident<$ident>\n";
65863862 4782 if ($from ne $to) {
3705ce5b
JP
4783 if (ERROR("POINTER_LOCATION",
4784 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4785 $fix) {
4786 my $sub_from = $ident;
4787 my $sub_to = $ident;
4788 $sub_to =~ s/\Q$from\E/$to/;
194f66fc 4789 $fixed[$fixlinenr] =~
3705ce5b
JP
4790 s@\Q$sub_from\E@$sub_to@;
4791 }
65863862 4792 }
bfcb2cc7
AW
4793 }
4794 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4795 #print "BB<$1>\n";
3705ce5b 4796 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
65863862
AW
4797
4798 # Should start with a space.
4799 $to =~ s/^(\S)/ $1/;
4800 # Should not end with a space.
4801 $to =~ s/\s+$//;
4802 # '*'s should not have spaces between.
f9a0b3d1 4803 while ($to =~ s/\*\s+\*/\*\*/) {
65863862
AW
4804 }
4805 # Modifiers should have spaces.
4806 $to =~ s/(\b$Modifier$)/$1 /;
d8aaf121 4807
3705ce5b 4808## print "2: from<$from> to<$to> ident<$ident>\n";
667026e7 4809 if ($from ne $to && $ident !~ /^$Modifier$/) {
3705ce5b
JP
4810 if (ERROR("POINTER_LOCATION",
4811 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4812 $fix) {
4813
4814 my $sub_from = $match;
4815 my $sub_to = $match;
4816 $sub_to =~ s/\Q$from\E/$to/;
194f66fc 4817 $fixed[$fixlinenr] =~
3705ce5b
JP
4818 s@\Q$sub_from\E@$sub_to@;
4819 }
65863862 4820 }
0a920b5b
AW
4821 }
4822
69d517e6
DH
4823# do not use BUG() or variants
4824 if ($line =~ /\b(?!AA_|BUILD_|DCCP_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
0675a8fb
JD
4825 my $msg_level = \&WARN;
4826 $msg_level = \&CHK if ($file);
4827 &{$msg_level}("AVOID_BUG",
69d517e6 4828 "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr);
9d3e3c70 4829 }
0a920b5b 4830
9d3e3c70 4831# avoid LINUX_VERSION_CODE
8905a67c 4832 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
000d1cc1
JP
4833 WARN("LINUX_VERSION_CODE",
4834 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
8905a67c
AW
4835 }
4836
17441227
JP
4837# check for uses of printk_ratelimit
4838 if ($line =~ /\bprintk_ratelimit\s*\(/) {
000d1cc1 4839 WARN("PRINTK_RATELIMITED",
101ee680 4840 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
17441227
JP
4841 }
4842
eeef5733
JP
4843# printk should use KERN_* levels
4844 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4845 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4846 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
0a920b5b
AW
4847 }
4848
f5eea3b0
JP
4849# prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4850 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4851 my $printk = $1;
4852 my $modifier = $2;
4853 my $orig = $3;
4854 $modifier = "" if (!defined($modifier));
243f3803
JP
4855 my $level = lc($orig);
4856 $level = "warn" if ($level eq "warning");
8f26b837
JP
4857 my $level2 = $level;
4858 $level2 = "dbg" if ($level eq "debug");
f5eea3b0
JP
4859 $level .= $modifier;
4860 $level2 .= $modifier;
243f3803 4861 WARN("PREFER_PR_LEVEL",
f5eea3b0 4862 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
243f3803
JP
4863 }
4864
f5eea3b0 4865# prefer dev_<level> to dev_printk(KERN_<LEVEL>
dc139313
JP
4866 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4867 my $orig = $1;
4868 my $level = lc($orig);
4869 $level = "warn" if ($level eq "warning");
4870 $level = "dbg" if ($level eq "debug");
4871 WARN("PREFER_DEV_LEVEL",
4872 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4873 }
4874
8020b253
NB
4875# trace_printk should not be used in production code.
4876 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4877 WARN("TRACE_PRINTK",
4878 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4879 }
4880
91c9afaf
AL
4881# ENOSYS means "bad syscall nr" and nothing else. This will have a small
4882# number of false positives, but assembly files are not checked, so at
4883# least the arch entry code will not trigger this warning.
4884 if ($line =~ /\bENOSYS\b/) {
4885 WARN("ENOSYS",
4886 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4887 }
4888
6b9ea5ff
JK
4889# ENOTSUPP is not a standard error code and should be avoided in new patches.
4890# Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4891# Similarly to ENOSYS warning a small number of false positives is expected.
4892 if (!$file && $line =~ /\bENOTSUPP\b/) {
4893 if (WARN("ENOTSUPP",
4894 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4895 $fix) {
4896 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4897 }
4898 }
4899
653d4876
AW
4900# function brace can't be on same line, except for #defines of do while,
4901# or if closed on same line
5b57980d 4902 if ($perl_version_ok &&
2d453e3b
JP
4903 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4904 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4905 $sline !~ /}/) {
8d182478 4906 if (ERROR("OPEN_BRACE",
2d453e3b 4907 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
8d182478
JP
4908 $fix) {
4909 fix_delete_line($fixlinenr, $rawline);
4910 my $fixed_line = $rawline;
03f49351 4911 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
8d182478
JP
4912 my $line1 = $1;
4913 my $line2 = $2;
4914 fix_insert_line($fixlinenr, ltrim($line1));
4915 fix_insert_line($fixlinenr, "\+{");
4916 if ($line2 !~ /^\s*$/) {
4917 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4918 }
4919 }
0a920b5b 4920 }
653d4876 4921
8905a67c
AW
4922# open braces for enum, union and struct go on the same line.
4923 if ($line =~ /^.\s*{/ &&
4924 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
8d182478
JP
4925 if (ERROR("OPEN_BRACE",
4926 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4927 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4928 fix_delete_line($fixlinenr - 1, $prevrawline);
4929 fix_delete_line($fixlinenr, $rawline);
4930 my $fixedline = rtrim($prevrawline) . " {";
4931 fix_insert_line($fixlinenr, $fixedline);
4932 $fixedline = $rawline;
8d81ae05 4933 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
8d182478
JP
4934 if ($fixedline !~ /^\+\s*$/) {
4935 fix_insert_line($fixlinenr, $fixedline);
4936 }
4937 }
8905a67c
AW
4938 }
4939
0c73b4eb 4940# missing space after union, struct or enum definition
3705ce5b
JP
4941 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4942 if (WARN("SPACING",
4943 "missing space after $1 definition\n" . $herecurr) &&
4944 $fix) {
194f66fc 4945 $fixed[$fixlinenr] =~
3705ce5b
JP
4946 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4947 }
0c73b4eb
AW
4948 }
4949
31070b5d
JP
4950# Function pointer declarations
4951# check spacing between type, funcptr, and args
4952# canonical declaration is "type (*funcptr)(args...)"
91f72e9c 4953 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
31070b5d
JP
4954 my $declare = $1;
4955 my $pre_pointer_space = $2;
4956 my $post_pointer_space = $3;
4957 my $funcname = $4;
4958 my $post_funcname_space = $5;
4959 my $pre_args_space = $6;
4960
91f72e9c
JP
4961# the $Declare variable will capture all spaces after the type
4962# so check it for a missing trailing missing space but pointer return types
4963# don't need a space so don't warn for those.
4964 my $post_declare_space = "";
4965 if ($declare =~ /(\s+)$/) {
4966 $post_declare_space = $1;
4967 $declare = rtrim($declare);
4968 }
4969 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
31070b5d
JP
4970 WARN("SPACING",
4971 "missing space after return type\n" . $herecurr);
91f72e9c 4972 $post_declare_space = " ";
31070b5d
JP
4973 }
4974
4975# unnecessary space "type (*funcptr)(args...)"
91f72e9c
JP
4976# This test is not currently implemented because these declarations are
4977# equivalent to
4978# int foo(int bar, ...)
4979# and this is form shouldn't/doesn't generate a checkpatch warning.
4980#
4981# elsif ($declare =~ /\s{2,}$/) {
4982# WARN("SPACING",
4983# "Multiple spaces after return type\n" . $herecurr);
4984# }
31070b5d
JP
4985
4986# unnecessary space "type ( *funcptr)(args...)"
4987 if (defined $pre_pointer_space &&
4988 $pre_pointer_space =~ /^\s/) {
4989 WARN("SPACING",
4990 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4991 }
4992
4993# unnecessary space "type (* funcptr)(args...)"
4994 if (defined $post_pointer_space &&
4995 $post_pointer_space =~ /^\s/) {
4996 WARN("SPACING",
4997 "Unnecessary space before function pointer name\n" . $herecurr);
4998 }
4999
5000# unnecessary space "type (*funcptr )(args...)"
5001 if (defined $post_funcname_space &&
5002 $post_funcname_space =~ /^\s/) {
5003 WARN("SPACING",
5004 "Unnecessary space after function pointer name\n" . $herecurr);
5005 }
5006
5007# unnecessary space "type (*funcptr) (args...)"
5008 if (defined $pre_args_space &&
5009 $pre_args_space =~ /^\s/) {
5010 WARN("SPACING",
5011 "Unnecessary space before function pointer arguments\n" . $herecurr);
5012 }
5013
5014 if (show_type("SPACING") && $fix) {
194f66fc 5015 $fixed[$fixlinenr] =~
91f72e9c 5016 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
31070b5d
JP
5017 }
5018 }
5019
8d31cfce
AW
5020# check for spacing round square brackets; allowed:
5021# 1. with a type on the left -- int [] a;
fe2a7dbc
AW
5022# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5023# 3. inside a curly brace -- = { [0...10] = 5 }
8d31cfce
AW
5024 while ($line =~ /(.*?\s)\[/g) {
5025 my ($where, $prefix) = ($-[1], $1);
5026 if ($prefix !~ /$Type\s+$/ &&
fe2a7dbc 5027 ($where != 0 || $prefix !~ /^.\s+$/) &&
38dca988 5028 $prefix !~ /[{,:]\s+$/) {
3705ce5b
JP
5029 if (ERROR("BRACKET_SPACE",
5030 "space prohibited before open square bracket '['\n" . $herecurr) &&
5031 $fix) {
194f66fc 5032 $fixed[$fixlinenr] =~
3705ce5b
JP
5033 s/^(\+.*?)\s+\[/$1\[/;
5034 }
8d31cfce
AW
5035 }
5036 }
5037
f0a594c1 5038# check for spaces between functions and their parentheses.
6c72ffaa 5039 while ($line =~ /($Ident)\s+\(/g) {
c2fdda0d 5040 my $name = $1;
773647a0
AW
5041 my $ctx_before = substr($line, 0, $-[1]);
5042 my $ctx = "$ctx_before$name";
c2fdda0d
AW
5043
5044 # Ignore those directives where spaces _are_ permitted.
773647a0
AW
5045 if ($name =~ /^(?:
5046 if|for|while|switch|return|case|
5047 volatile|__volatile__|
5048 __attribute__|format|__extension__|
5049 asm|__asm__)$/x)
5050 {
c2fdda0d
AW
5051 # cpp #define statements have non-optional spaces, ie
5052 # if there is a space between the name and the open
5053 # parenthesis it is simply not a parameter group.
c45dcabd 5054 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
773647a0
AW
5055
5056 # cpp #elif statement condition may start with a (
c45dcabd 5057 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
c2fdda0d
AW
5058
5059 # If this whole things ends with a type its most
5060 # likely a typedef for a function.
773647a0 5061 } elsif ($ctx =~ /$Type$/) {
c2fdda0d
AW
5062
5063 } else {
3705ce5b
JP
5064 if (WARN("SPACING",
5065 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5066 $fix) {
194f66fc 5067 $fixed[$fixlinenr] =~
3705ce5b
JP
5068 s/\b$name\s+\(/$name\(/;
5069 }
6c72ffaa 5070 }
f0a594c1 5071 }
9a4cad4e 5072
653d4876 5073# Check operator spacing.
0a920b5b 5074 if (!($line=~/\#\s*include/)) {
3705ce5b
JP
5075 my $fixed_line = "";
5076 my $line_fixed = 0;
5077
9c0ca6f9
AW
5078 my $ops = qr{
5079 <<=|>>=|<=|>=|==|!=|
5080 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5081 =>|->|<<|>>|<|>|=|!|~|
1f65f947 5082 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
84731623 5083 \?:|\?|:
9c0ca6f9 5084 }x;
cf655043 5085 my @elements = split(/($ops|;)/, $opline);
3705ce5b
JP
5086
5087## print("element count: <" . $#elements . ">\n");
5088## foreach my $el (@elements) {
5089## print("el: <$el>\n");
5090## }
5091
5092 my @fix_elements = ();
00df344f 5093 my $off = 0;
6c72ffaa 5094
3705ce5b
JP
5095 foreach my $el (@elements) {
5096 push(@fix_elements, substr($rawline, $off, length($el)));
5097 $off += length($el);
5098 }
5099
5100 $off = 0;
5101
6c72ffaa 5102 my $blank = copy_spacing($opline);
b34c648b 5103 my $last_after = -1;
6c72ffaa 5104
0a920b5b 5105 for (my $n = 0; $n < $#elements; $n += 2) {
3705ce5b
JP
5106
5107 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5108
5109## print("n: <$n> good: <$good>\n");
5110
4a0df2ef
AW
5111 $off += length($elements[$n]);
5112
25985edc 5113 # Pick up the preceding and succeeding characters.
773647a0
AW
5114 my $ca = substr($opline, 0, $off);
5115 my $cc = '';
5116 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5117 $cc = substr($opline, $off + length($elements[$n + 1]));
5118 }
5119 my $cb = "$ca$;$cc";
5120
4a0df2ef
AW
5121 my $a = '';
5122 $a = 'V' if ($elements[$n] ne '');
5123 $a = 'W' if ($elements[$n] =~ /\s$/);
cf655043 5124 $a = 'C' if ($elements[$n] =~ /$;$/);
4a0df2ef
AW
5125 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5126 $a = 'O' if ($elements[$n] eq '');
773647a0 5127 $a = 'E' if ($ca =~ /^\s*$/);
4a0df2ef 5128
0a920b5b 5129 my $op = $elements[$n + 1];
4a0df2ef
AW
5130
5131 my $c = '';
0a920b5b 5132 if (defined $elements[$n + 2]) {
4a0df2ef
AW
5133 $c = 'V' if ($elements[$n + 2] ne '');
5134 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
cf655043 5135 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4a0df2ef
AW
5136 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5137 $c = 'O' if ($elements[$n + 2] eq '');
8b1b3378 5138 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4a0df2ef
AW
5139 } else {
5140 $c = 'E';
0a920b5b
AW
5141 }
5142
4a0df2ef
AW
5143 my $ctx = "${a}x${c}";
5144
5145 my $at = "(ctx:$ctx)";
5146
6c72ffaa 5147 my $ptr = substr($blank, 0, $off) . "^";
de7d4f0e 5148 my $hereptr = "$hereline$ptr\n";
0a920b5b 5149
74048ed8 5150 # Pull out the value of this operator.
6c72ffaa 5151 my $op_type = substr($curr_values, $off + 1, 1);
0a920b5b 5152
1f65f947
AW
5153 # Get the full operator variant.
5154 my $opv = $op . substr($curr_vars, $off, 1);
5155
13214adf
AW
5156 # Ignore operators passed as parameters.
5157 if ($op_type ne 'V' &&
d7fe8065 5158 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
13214adf 5159
cf655043
AW
5160# # Ignore comments
5161# } elsif ($op =~ /^$;+$/) {
13214adf 5162
d8aaf121 5163 # ; should have either the end of line or a space or \ after it
13214adf 5164 } elsif ($op eq ';') {
cf655043
AW
5165 if ($ctx !~ /.x[WEBC]/ &&
5166 $cc !~ /^\\/ && $cc !~ /^;/) {
3705ce5b
JP
5167 if (ERROR("SPACING",
5168 "space required after that '$op' $at\n" . $hereptr)) {
b34c648b 5169 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3705ce5b
JP
5170 $line_fixed = 1;
5171 }
d8aaf121
AW
5172 }
5173
5174 # // is a comment
5175 } elsif ($op eq '//') {
0a920b5b 5176
b00e4814
JP
5177 # : when part of a bitfield
5178 } elsif ($opv eq ':B') {
5179 # skip the bitfield test for now
5180
1f65f947
AW
5181 # No spaces for:
5182 # ->
b00e4814 5183 } elsif ($op eq '->') {
4a0df2ef 5184 if ($ctx =~ /Wx.|.xW/) {
3705ce5b
JP
5185 if (ERROR("SPACING",
5186 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
b34c648b 5187 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3705ce5b
JP
5188 if (defined $fix_elements[$n + 2]) {
5189 $fix_elements[$n + 2] =~ s/^\s+//;
5190 }
b34c648b 5191 $line_fixed = 1;
3705ce5b 5192 }
0a920b5b
AW
5193 }
5194
2381097b 5195 # , must not have a space before and must have a space on the right.
0a920b5b 5196 } elsif ($op eq ',') {
2381097b
JP
5197 my $rtrim_before = 0;
5198 my $space_after = 0;
5199 if ($ctx =~ /Wx./) {
5200 if (ERROR("SPACING",
5201 "space prohibited before that '$op' $at\n" . $hereptr)) {
5202 $line_fixed = 1;
5203 $rtrim_before = 1;
5204 }
5205 }
cf655043 5206 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3705ce5b
JP
5207 if (ERROR("SPACING",
5208 "space required after that '$op' $at\n" . $hereptr)) {
3705ce5b 5209 $line_fixed = 1;
b34c648b 5210 $last_after = $n;
2381097b
JP
5211 $space_after = 1;
5212 }
5213 }
5214 if ($rtrim_before || $space_after) {
5215 if ($rtrim_before) {
5216 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5217 } else {
5218 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5219 }
5220 if ($space_after) {
5221 $good .= " ";
3705ce5b 5222 }
0a920b5b
AW
5223 }
5224
9c0ca6f9 5225 # '*' as part of a type definition -- reported already.
74048ed8 5226 } elsif ($opv eq '*_') {
9c0ca6f9
AW
5227 #warn "'*' is part of type\n";
5228
5229 # unary operators should have a space before and
5230 # none after. May be left adjacent to another
5231 # unary operator, or a cast
5232 } elsif ($op eq '!' || $op eq '~' ||
74048ed8 5233 $opv eq '*U' || $opv eq '-U' ||
0d413866 5234 $opv eq '&U' || $opv eq '&&U') {
cf655043 5235 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3705ce5b
JP
5236 if (ERROR("SPACING",
5237 "space required before that '$op' $at\n" . $hereptr)) {
b34c648b
JP
5238 if ($n != $last_after + 2) {
5239 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5240 $line_fixed = 1;
5241 }
3705ce5b 5242 }
0a920b5b 5243 }
a3340b35 5244 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
171ae1a4
AW
5245 # A unary '*' may be const
5246
5247 } elsif ($ctx =~ /.xW/) {
3705ce5b
JP
5248 if (ERROR("SPACING",
5249 "space prohibited after that '$op' $at\n" . $hereptr)) {
b34c648b 5250 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3705ce5b
JP
5251 if (defined $fix_elements[$n + 2]) {
5252 $fix_elements[$n + 2] =~ s/^\s+//;
5253 }
b34c648b 5254 $line_fixed = 1;
3705ce5b 5255 }
0a920b5b
AW
5256 }
5257
5258 # unary ++ and unary -- are allowed no space on one side.
5259 } elsif ($op eq '++' or $op eq '--') {
773647a0 5260 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3705ce5b
JP
5261 if (ERROR("SPACING",
5262 "space required one side of that '$op' $at\n" . $hereptr)) {
b34c648b 5263 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3705ce5b
JP
5264 $line_fixed = 1;
5265 }
773647a0
AW
5266 }
5267 if ($ctx =~ /Wx[BE]/ ||
5268 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3705ce5b
JP
5269 if (ERROR("SPACING",
5270 "space prohibited before that '$op' $at\n" . $hereptr)) {
b34c648b 5271 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3705ce5b
JP
5272 $line_fixed = 1;
5273 }
0a920b5b 5274 }
773647a0 5275 if ($ctx =~ /ExW/) {
3705ce5b
JP
5276 if (ERROR("SPACING",
5277 "space prohibited after that '$op' $at\n" . $hereptr)) {
b34c648b 5278 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3705ce5b
JP
5279 if (defined $fix_elements[$n + 2]) {
5280 $fix_elements[$n + 2] =~ s/^\s+//;
5281 }
b34c648b 5282 $line_fixed = 1;
3705ce5b 5283 }
653d4876 5284 }
0a920b5b 5285
0a920b5b 5286 # << and >> may either have or not have spaces both sides
9c0ca6f9
AW
5287 } elsif ($op eq '<<' or $op eq '>>' or
5288 $op eq '&' or $op eq '^' or $op eq '|' or
5289 $op eq '+' or $op eq '-' or
c2fdda0d
AW
5290 $op eq '*' or $op eq '/' or
5291 $op eq '%')
0a920b5b 5292 {
d2e025f3
JP
5293 if ($check) {
5294 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5295 if (CHK("SPACING",
5296 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5297 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5298 $fix_elements[$n + 2] =~ s/^\s+//;
5299 $line_fixed = 1;
5300 }
5301 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5302 if (CHK("SPACING",
5303 "space preferred before that '$op' $at\n" . $hereptr)) {
5304 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5305 $line_fixed = 1;
5306 }
5307 }
5308 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3705ce5b
JP
5309 if (ERROR("SPACING",
5310 "need consistent spacing around '$op' $at\n" . $hereptr)) {
b34c648b
JP
5311 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5312 if (defined $fix_elements[$n + 2]) {
5313 $fix_elements[$n + 2] =~ s/^\s+//;
5314 }
3705ce5b
JP
5315 $line_fixed = 1;
5316 }
0a920b5b
AW
5317 }
5318
1f65f947
AW
5319 # A colon needs no spaces before when it is
5320 # terminating a case value or a label.
5321 } elsif ($opv eq ':C' || $opv eq ':L') {
263afd39 5322 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
3705ce5b
JP
5323 if (ERROR("SPACING",
5324 "space prohibited before that '$op' $at\n" . $hereptr)) {
b34c648b 5325 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3705ce5b
JP
5326 $line_fixed = 1;
5327 }
1f65f947
AW
5328 }
5329
0a920b5b 5330 # All the others need spaces both sides.
cf655043 5331 } elsif ($ctx !~ /[EWC]x[CWE]/) {
1f65f947
AW
5332 my $ok = 0;
5333
22f2a2ef 5334 # Ignore email addresses <foo@bar>
1f65f947
AW
5335 if (($op eq '<' &&
5336 $cc =~ /^\S+\@\S+>/) ||
5337 ($op eq '>' &&
5338 $ca =~ /<\S+\@\S+$/))
5339 {
342d3d2f 5340 $ok = 1;
1f65f947
AW
5341 }
5342
e0df7e1f
JP
5343 # for asm volatile statements
5344 # ignore a colon with another
5345 # colon immediately before or after
5346 if (($op eq ':') &&
5347 ($ca =~ /:$/ || $cc =~ /^:/)) {
5348 $ok = 1;
5349 }
5350
84731623 5351 # messages are ERROR, but ?: are CHK
1f65f947 5352 if ($ok == 0) {
0675a8fb
JD
5353 my $msg_level = \&ERROR;
5354 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
84731623 5355
0675a8fb
JD
5356 if (&{$msg_level}("SPACING",
5357 "spaces required around that '$op' $at\n" . $hereptr)) {
b34c648b
JP
5358 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5359 if (defined $fix_elements[$n + 2]) {
5360 $fix_elements[$n + 2] =~ s/^\s+//;
5361 }
3705ce5b
JP
5362 $line_fixed = 1;
5363 }
22f2a2ef 5364 }
0a920b5b 5365 }
4a0df2ef 5366 $off += length($elements[$n + 1]);
3705ce5b
JP
5367
5368## print("n: <$n> GOOD: <$good>\n");
5369
5370 $fixed_line = $fixed_line . $good;
5371 }
5372
5373 if (($#elements % 2) == 0) {
5374 $fixed_line = $fixed_line . $fix_elements[$#elements];
0a920b5b 5375 }
3705ce5b 5376
194f66fc
JP
5377 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5378 $fixed[$fixlinenr] = $fixed_line;
3705ce5b
JP
5379 }
5380
5381
0a920b5b
AW
5382 }
5383
786b6326 5384# check for whitespace before a non-naked semicolon
d2e248e7 5385 if ($line =~ /^\+.*\S\s+;\s*$/) {
786b6326
JP
5386 if (WARN("SPACING",
5387 "space prohibited before semicolon\n" . $herecurr) &&
5388 $fix) {
194f66fc 5389 1 while $fixed[$fixlinenr] =~
786b6326
JP
5390 s/^(\+.*\S)\s+;/$1;/;
5391 }
5392 }
5393
f0a594c1
AW
5394# check for multiple assignments
5395 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
000d1cc1
JP
5396 CHK("MULTIPLE_ASSIGNMENTS",
5397 "multiple assignments should be avoided\n" . $herecurr);
f0a594c1
AW
5398 }
5399
22f2a2ef
AW
5400## # check for multiple declarations, allowing for a function declaration
5401## # continuation.
5402## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5403## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5404##
5405## # Remove any bracketed sections to ensure we do not
e73d2715 5406## # falsely report the parameters of functions.
22f2a2ef
AW
5407## my $ln = $line;
5408## while ($ln =~ s/\([^\(\)]*\)//g) {
5409## }
5410## if ($ln =~ /,/) {
000d1cc1
JP
5411## WARN("MULTIPLE_DECLARATION",
5412## "declaring multiple variables together should be avoided\n" . $herecurr);
22f2a2ef
AW
5413## }
5414## }
f0a594c1 5415
0a920b5b 5416#need space before brace following if, while, etc
6b8c69e4 5417 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
6ad724e2 5418 $line =~ /\b(?:else|do)\{/) {
3705ce5b
JP
5419 if (ERROR("SPACING",
5420 "space required before the open brace '{'\n" . $herecurr) &&
5421 $fix) {
6ad724e2 5422 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
3705ce5b 5423 }
de7d4f0e
AW
5424 }
5425
c4a62ef9
JP
5426## # check for blank lines before declarations
5427## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5428## $prevrawline =~ /^.\s*$/) {
5429## WARN("SPACING",
5430## "No blank lines before declarations\n" . $hereprev);
5431## }
5432##
5433
de7d4f0e
AW
5434# closing brace should have a space following it when it has anything
5435# on the line
94fb9845 5436 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
d5e616fc
JP
5437 if (ERROR("SPACING",
5438 "space required after that close brace '}'\n" . $herecurr) &&
5439 $fix) {
194f66fc 5440 $fixed[$fixlinenr] =~
d5e616fc
JP
5441 s/}((?!(?:,|;|\)))\S)/} $1/;
5442 }
0a920b5b
AW
5443 }
5444
22f2a2ef
AW
5445# check spacing on square brackets
5446 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3705ce5b
JP
5447 if (ERROR("SPACING",
5448 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5449 $fix) {
194f66fc 5450 $fixed[$fixlinenr] =~
3705ce5b
JP
5451 s/\[\s+/\[/;
5452 }
22f2a2ef
AW
5453 }
5454 if ($line =~ /\s\]/) {
3705ce5b
JP
5455 if (ERROR("SPACING",
5456 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5457 $fix) {
194f66fc 5458 $fixed[$fixlinenr] =~
3705ce5b
JP
5459 s/\s+\]/\]/;
5460 }
22f2a2ef
AW
5461 }
5462
c45dcabd 5463# check spacing on parentheses
9c0ca6f9
AW
5464 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5465 $line !~ /for\s*\(\s+;/) {
3705ce5b
JP
5466 if (ERROR("SPACING",
5467 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5468 $fix) {
194f66fc 5469 $fixed[$fixlinenr] =~
3705ce5b
JP
5470 s/\(\s+/\(/;
5471 }
22f2a2ef 5472 }
13214adf 5473 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
c45dcabd
AW
5474 $line !~ /for\s*\(.*;\s+\)/ &&
5475 $line !~ /:\s+\)/) {
3705ce5b
JP
5476 if (ERROR("SPACING",
5477 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5478 $fix) {
194f66fc 5479 $fixed[$fixlinenr] =~
3705ce5b
JP
5480 s/\s+\)/\)/;
5481 }
22f2a2ef
AW
5482 }
5483
e2826fd0
JP
5484# check unnecessary parentheses around addressof/dereference single $Lvals
5485# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5486
5487 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
ea4acbb1
JP
5488 my $var = $1;
5489 if (CHK("UNNECESSARY_PARENTHESES",
5490 "Unnecessary parentheses around $var\n" . $herecurr) &&
5491 $fix) {
5492 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5493 }
5494 }
5495
5496# check for unnecessary parentheses around function pointer uses
5497# ie: (foo->bar)(); should be foo->bar();
5498# but not "if (foo->bar) (" to avoid some false positives
5499 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5500 my $var = $2;
5501 if (CHK("UNNECESSARY_PARENTHESES",
5502 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5503 $fix) {
5504 my $var2 = deparenthesize($var);
5505 $var2 =~ s/\s//g;
5506 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5507 }
5508 }
e2826fd0 5509
63b7c73e 5510# check for unnecessary parentheses around comparisons in if uses
a032aa4c
JP
5511# when !drivers/staging or command-line uses --strict
5512 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5b57980d 5513 $perl_version_ok && defined($stat) &&
63b7c73e
JP
5514 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5515 my $if_stat = $1;
5516 my $test = substr($2, 1, -1);
5517 my $herectx;
5518 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5519 my $match = $1;
5520 # avoid parentheses around potential macro args
5521 next if ($match =~ /^\s*\w+\s*$/);
5522 if (!defined($herectx)) {
5523 $herectx = $here . "\n";
5524 my $cnt = statement_rawlines($if_stat);
5525 for (my $n = 0; $n < $cnt; $n++) {
5526 my $rl = raw_line($linenr, $n);
5527 $herectx .= $rl . "\n";
5528 last if $rl =~ /^[ \+].*\{/;
5529 }
5530 }
5531 CHK("UNNECESSARY_PARENTHESES",
5532 "Unnecessary parentheses around '$match'\n" . $herectx);
5533 }
5534 }
5535
69078651
JP
5536# check that goto labels aren't indented (allow a single space indentation)
5537# and ignore bitfield definitions like foo:1
5538# Strictly, labels can have whitespace after the identifier and before the :
5539# but this is not allowed here as many ?: uses would appear to be labels
5540 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5541 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5542 $sline !~ /^.\s+default:/) {
3705ce5b
JP
5543 if (WARN("INDENTED_LABEL",
5544 "labels should not be indented\n" . $herecurr) &&
5545 $fix) {
194f66fc 5546 $fixed[$fixlinenr] =~
3705ce5b
JP
5547 s/^(.)\s+/$1/;
5548 }
0a920b5b
AW
5549 }
5550
40873aba
JP
5551# check if a statement with a comma should be two statements like:
5552# foo = bar(), /* comma should be semicolon */
5553# bar = baz();
5554 if (defined($stat) &&
5555 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5556 my $cnt = statement_rawlines($stat);
5557 my $herectx = get_stat_here($linenr, $cnt, $here);
5558 WARN("SUSPECT_COMMA_SEMICOLON",
5559 "Possible comma where semicolon could be used\n" . $herectx);
5560 }
5561
5b9553ab 5562# return is not a function
507e5141 5563 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
c45dcabd 5564 my $spacing = $1;
5b57980d 5565 if ($perl_version_ok &&
5b9553ab
JP
5566 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5567 my $value = $1;
5568 $value = deparenthesize($value);
5569 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5570 ERROR("RETURN_PARENTHESES",
5571 "return is not a function, parentheses are not required\n" . $herecurr);
5572 }
c45dcabd 5573 } elsif ($spacing !~ /\s+/) {
000d1cc1
JP
5574 ERROR("SPACING",
5575 "space required before the open parenthesis '('\n" . $herecurr);
c45dcabd
AW
5576 }
5577 }
507e5141 5578
b43ae21b
JP
5579# unnecessary return in a void function
5580# at end-of-function, with the previous line a single leading tab, then return;
5581# and the line before that not a goto label target like "out:"
5582 if ($sline =~ /^[ \+]}\s*$/ &&
5583 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5584 $linenr >= 3 &&
5585 $lines[$linenr - 3] =~ /^[ +]/ &&
5586 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
9819cf25 5587 WARN("RETURN_VOID",
b43ae21b 5588 "void function return statements are not generally useful\n" . $hereprev);
ea7dbab3 5589 }
9819cf25 5590
189248d8 5591# if statements using unnecessary parentheses - ie: if ((foo == bar))
5b57980d 5592 if ($perl_version_ok &&
189248d8
JP
5593 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5594 my $openparens = $1;
5595 my $count = $openparens =~ tr@\(@\(@;
5596 my $msg = "";
5597 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5598 my $comp = $4; #Not $1 because of $LvalOrFunc
5599 $msg = " - maybe == should be = ?" if ($comp eq "==");
5600 WARN("UNNECESSARY_PARENTHESES",
5601 "Unnecessary parentheses$msg\n" . $herecurr);
5602 }
5603 }
5604
c5595fa2
JP
5605# comparisons with a constant or upper case identifier on the left
5606# avoid cases like "foo + BAR < baz"
5607# only fix matches surrounded by parentheses to avoid incorrect
5608# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5b57980d 5609 if ($perl_version_ok &&
c5595fa2
JP
5610 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5611 my $lead = $1;
5612 my $const = $2;
5613 my $comp = $3;
5614 my $to = $4;
5615 my $newcomp = $comp;
f39e1769 5616 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
c5595fa2
JP
5617 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5618 WARN("CONSTANT_COMPARISON",
5619 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5620 $fix) {
5621 if ($comp eq "<") {
5622 $newcomp = ">";
5623 } elsif ($comp eq "<=") {
5624 $newcomp = ">=";
5625 } elsif ($comp eq ">") {
5626 $newcomp = "<";
5627 } elsif ($comp eq ">=") {
5628 $newcomp = "<=";
5629 }
5630 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5631 }
5632 }
5633
f34e4a4f
JP
5634# Return of what appears to be an errno should normally be negative
5635 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
53a3c448 5636 my $name = $1;
46b85bf9 5637 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
000d1cc1 5638 WARN("USE_NEGATIVE_ERRNO",
f34e4a4f 5639 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
53a3c448
AW
5640 }
5641 }
c45dcabd 5642
0a920b5b 5643# Need a space before open parenthesis after if, while etc
3705ce5b
JP
5644 if ($line =~ /\b(if|while|for|switch)\(/) {
5645 if (ERROR("SPACING",
5646 "space required before the open parenthesis '('\n" . $herecurr) &&
5647 $fix) {
194f66fc 5648 $fixed[$fixlinenr] =~
3705ce5b
JP
5649 s/\b(if|while|for|switch)\(/$1 \(/;
5650 }
0a920b5b
AW
5651 }
5652
f5fe35dd
AW
5653# Check for illegal assignment in if conditional -- and check for trailing
5654# statements after the conditional.
170d3a22 5655 if ($line =~ /do\s*(?!{)/) {
3e469cdc
AW
5656 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5657 ctx_statement_block($linenr, $realcnt, 0)
5658 if (!defined $stat);
170d3a22
AW
5659 my ($stat_next) = ctx_statement_block($line_nr_next,
5660 $remain_next, $off_next);
5661 $stat_next =~ s/\n./\n /g;
5662 ##print "stat<$stat> stat_next<$stat_next>\n";
5663
5664 if ($stat_next =~ /^\s*while\b/) {
5665 # If the statement carries leading newlines,
5666 # then count those as offsets.
5667 my ($whitespace) =
5668 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5669 my $offset =
5670 statement_rawlines($whitespace) - 1;
5671
5672 $suppress_whiletrailers{$line_nr_next +
5673 $offset} = 1;
5674 }
5675 }
5676 if (!defined $suppress_whiletrailers{$linenr} &&
c11230f4 5677 defined($stat) && defined($cond) &&
170d3a22 5678 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
171ae1a4 5679 my ($s, $c) = ($stat, $cond);
481efd7b 5680 my $fixed_assign_in_if = 0;
8905a67c 5681
b53c8e10 5682 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
65b64b3b
JP
5683 if (ERROR("ASSIGN_IN_IF",
5684 "do not use assignment in if condition\n" . $herecurr) &&
5685 $fix && $perl_version_ok) {
5686 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5687 my $space = $1;
5688 my $not = $2;
5689 my $statement = $3;
5690 my $assigned = $4;
5691 my $test = $8;
5692 my $against = $9;
5693 my $brace = $15;
5694 fix_delete_line($fixlinenr, $rawline);
5695 fix_insert_line($fixlinenr, "$space$statement;");
5696 my $newline = "${space}if (";
5697 $newline .= '!' if defined($not);
5698 $newline .= '(' if (defined $not && defined($test) && defined($against));
5699 $newline .= "$assigned";
5700 $newline .= " $test $against" if (defined($test) && defined($against));
5701 $newline .= ')' if (defined $not && defined($test) && defined($against));
5702 $newline .= ')';
5703 $newline .= " {" if (defined($brace));
5704 fix_insert_line($fixlinenr + 1, $newline);
481efd7b 5705 $fixed_assign_in_if = 1;
65b64b3b
JP
5706 }
5707 }
8905a67c
AW
5708 }
5709
5710 # Find out what is on the end of the line after the
5711 # conditional.
773647a0 5712 substr($s, 0, length($c), '');
8905a67c 5713 $s =~ s/\n.*//g;
342d3d2f 5714 $s =~ s/$;//g; # Remove any comments
53210168
AW
5715 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5716 $c !~ /}\s*while\s*/)
773647a0 5717 {
bb44ad39
AW
5718 # Find out how long the conditional actually is.
5719 my @newlines = ($c =~ /\n/gs);
5720 my $cond_lines = 1 + $#newlines;
42bdf74c 5721 my $stat_real = '';
bb44ad39 5722
42bdf74c
HS
5723 $stat_real = raw_line($linenr, $cond_lines)
5724 . "\n" if ($cond_lines);
bb44ad39
AW
5725 if (defined($stat_real) && $cond_lines > 1) {
5726 $stat_real = "[...]\n$stat_real";
5727 }
5728
481efd7b
JP
5729 if (ERROR("TRAILING_STATEMENTS",
5730 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5731 !$fixed_assign_in_if &&
5732 $cond_lines == 0 &&
5733 $fix && $perl_version_ok &&
5734 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5735 my $indent = $1;
5736 my $test = $2;
5737 my $rest = rtrim($4);
5738 if ($rest =~ /;$/) {
5739 $fixed[$fixlinenr] = "\+$indent$test";
5740 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5741 }
5742 }
8905a67c
AW
5743 }
5744 }
5745
13214adf
AW
5746# Check for bitwise tests written as boolean
5747 if ($line =~ /
5748 (?:
5749 (?:\[|\(|\&\&|\|\|)
5750 \s*0[xX][0-9]+\s*
5751 (?:\&\&|\|\|)
5752 |
5753 (?:\&\&|\|\|)
5754 \s*0[xX][0-9]+\s*
5755 (?:\&\&|\|\||\)|\])
5756 )/x)
5757 {
000d1cc1
JP
5758 WARN("HEXADECIMAL_BOOLEAN_TEST",
5759 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
13214adf
AW
5760 }
5761
8905a67c 5762# if and else should not have general statements after it
13214adf
AW
5763 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5764 my $s = $1;
342d3d2f 5765 $s =~ s/$;//g; # Remove any comments
13214adf 5766 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
000d1cc1
JP
5767 ERROR("TRAILING_STATEMENTS",
5768 "trailing statements should be on next line\n" . $herecurr);
13214adf 5769 }
0a920b5b 5770 }
39667782
AW
5771# if should not continue a brace
5772 if ($line =~ /}\s*if\b/) {
000d1cc1 5773 ERROR("TRAILING_STATEMENTS",
048b123f 5774 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
39667782
AW
5775 $herecurr);
5776 }
a1080bf8
AW
5777# case and default should not have general statements after them
5778 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5779 $line !~ /\G(?:
3fef12d6 5780 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
a1080bf8
AW
5781 \s*return\s+
5782 )/xg)
5783 {
000d1cc1
JP
5784 ERROR("TRAILING_STATEMENTS",
5785 "trailing statements should be on next line\n" . $herecurr);
a1080bf8 5786 }
0a920b5b
AW
5787
5788 # Check for }<nl>else {, these must be at the same
5789 # indent level to be relevant to each other.
8b8856f4
JP
5790 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5791 $previndent == $indent) {
5792 if (ERROR("ELSE_AFTER_BRACE",
5793 "else should follow close brace '}'\n" . $hereprev) &&
5794 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5795 fix_delete_line($fixlinenr - 1, $prevrawline);
5796 fix_delete_line($fixlinenr, $rawline);
5797 my $fixedline = $prevrawline;
5798 $fixedline =~ s/}\s*$//;
5799 if ($fixedline !~ /^\+\s*$/) {
5800 fix_insert_line($fixlinenr, $fixedline);
5801 }
5802 $fixedline = $rawline;
5803 $fixedline =~ s/^(.\s*)else/$1} else/;
5804 fix_insert_line($fixlinenr, $fixedline);
5805 }
0a920b5b
AW
5806 }
5807
8b8856f4
JP
5808 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5809 $previndent == $indent) {
c2fdda0d
AW
5810 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5811
5812 # Find out what is on the end of the line after the
5813 # conditional.
773647a0 5814 substr($s, 0, length($c), '');
c2fdda0d
AW
5815 $s =~ s/\n.*//g;
5816
5817 if ($s =~ /^\s*;/) {
8b8856f4
JP
5818 if (ERROR("WHILE_AFTER_BRACE",
5819 "while should follow close brace '}'\n" . $hereprev) &&
5820 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5821 fix_delete_line($fixlinenr - 1, $prevrawline);
5822 fix_delete_line($fixlinenr, $rawline);
5823 my $fixedline = $prevrawline;
5824 my $trailing = $rawline;
5825 $trailing =~ s/^\+//;
5826 $trailing = trim($trailing);
5827 $fixedline =~ s/}\s*$/} $trailing/;
5828 fix_insert_line($fixlinenr, $fixedline);
5829 }
c2fdda0d
AW
5830 }
5831 }
5832
95e2c602 5833#Specific variable tests
323c1260
JP
5834 while ($line =~ m{($Constant|$Lval)}g) {
5835 my $var = $1;
95e2c602 5836
95e2c602 5837#CamelCase
807bd26c 5838 if ($var !~ /^$Constant$/ &&
be79794b 5839 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4104a206
ŁS
5840#Ignore some autogenerated defines and enum values
5841 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
22735ce8 5842#Ignore Page<foo> variants
807bd26c 5843 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
d99a4158
GE
5844#Ignore ETHTOOL_LINK_MODE_<foo> variants
5845 $var !~ /^ETHTOOL_LINK_MODE_/ &&
d439e6a5
JP
5846#Ignore SI style variants like nS, mV and dB
5847#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5848 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
f5123576
JW
5849#Ignore some three character SI units explicitly, like MiB and KHz
5850 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
f858e23a 5851 while ($var =~ m{\b($Ident)}g) {
7e781f67
JP
5852 my $word = $1;
5853 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
d8b07710
JP
5854 if ($check) {
5855 seed_camelcase_includes();
5856 if (!$file && !$camelcase_file_seeded) {
5857 seed_camelcase_file($realfile);
5858 $camelcase_file_seeded = 1;
5859 }
5860 }
7e781f67
JP
5861 if (!defined $camelcase{$word}) {
5862 $camelcase{$word} = 1;
5863 CHK("CAMELCASE",
5864 "Avoid CamelCase: <$word>\n" . $herecurr);
5865 }
3445686a 5866 }
323c1260
JP
5867 }
5868 }
0a920b5b
AW
5869
5870#no spaces allowed after \ in define
d5e616fc
JP
5871 if ($line =~ /\#\s*define.*\\\s+$/) {
5872 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5873 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5874 $fix) {
194f66fc 5875 $fixed[$fixlinenr] =~ s/\s+$//;
d5e616fc 5876 }
0a920b5b
AW
5877 }
5878
0e212e0a
FF
5879# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5880# itself <asm/foo.h> (uses RAW line)
c45dcabd 5881 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
e09dec48
AW
5882 my $file = "$1.h";
5883 my $checkfile = "include/linux/$file";
5884 if (-f "$root/$checkfile" &&
5885 $realfile ne $checkfile &&
7840a94c 5886 $1 !~ /$allowed_asm_includes/)
c45dcabd 5887 {
0e212e0a
FF
5888 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5889 if ($asminclude > 0) {
5890 if ($realfile =~ m{^arch/}) {
5891 CHK("ARCH_INCLUDE_LINUX",
5892 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5893 } else {
5894 WARN("INCLUDE_LINUX",
5895 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5896 }
e09dec48 5897 }
0a920b5b
AW
5898 }
5899 }
5900
653d4876
AW
5901# multi-statement macros should be enclosed in a do while loop, grab the
5902# first statement and ensure its the whole macro if its not enclosed
cf655043 5903# in a known good container
b8f96a31
AW
5904 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5905 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
d8aaf121
AW
5906 my $ln = $linenr;
5907 my $cnt = $realcnt;
c45dcabd
AW
5908 my ($off, $dstat, $dcond, $rest);
5909 my $ctx = '';
08a2843e
JP
5910 my $has_flow_statement = 0;
5911 my $has_arg_concat = 0;
c45dcabd 5912 ($dstat, $dcond, $ln, $cnt, $off) =
f74bd194
AW
5913 ctx_statement_block($linenr, $realcnt, 0);
5914 $ctx = $dstat;
c45dcabd 5915 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
a3bb97a7 5916 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
c45dcabd 5917
08a2843e 5918 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
62e15a6d 5919 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
08a2843e 5920
f59b64bf
JP
5921 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5922 my $define_args = $1;
5923 my $define_stmt = $dstat;
5924 my @def_args = ();
5925
5926 if (defined $define_args && $define_args ne "") {
5927 $define_args = substr($define_args, 1, length($define_args) - 2);
5928 $define_args =~ s/\s*//g;
8c8c45cf 5929 $define_args =~ s/\\\+?//g;
f59b64bf
JP
5930 @def_args = split(",", $define_args);
5931 }
5932
292f1a9b 5933 $dstat =~ s/$;//g;
c45dcabd
AW
5934 $dstat =~ s/\\\n.//g;
5935 $dstat =~ s/^\s*//s;
5936 $dstat =~ s/\s*$//s;
de7d4f0e 5937
c45dcabd 5938 # Flatten any parentheses and braces
2e44e803
DR
5939 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5940 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5941 $dstat =~ s/.\[[^\[\]]*\]/1u/)
bf30d6ed 5942 {
de7d4f0e 5943 }
d8aaf121 5944
342d3d2f 5945 # Flatten any obvious string concatenation.
33acb54a
JP
5946 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5947 $dstat =~ s/$Ident\s*($String)/$1/)
e45bab8e
AW
5948 {
5949 }
5950
42e15293
JP
5951 # Make asm volatile uses seem like a generic function
5952 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5953
c45dcabd
AW
5954 my $exceptions = qr{
5955 $Declare|
5956 module_param_named|
a0a0a7a9 5957 MODULE_PARM_DESC|
c45dcabd
AW
5958 DECLARE_PER_CPU|
5959 DEFINE_PER_CPU|
383099fd 5960 __typeof__\(|
22fd2d3e
SS
5961 union|
5962 struct|
ea71a0a0 5963 \.$Ident\s*=\s*|
6b10df42
VZ
5964 ^\"|\"$|
5965 ^\[
c45dcabd 5966 }x;
5eaa20b9 5967 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
f59b64bf
JP
5968
5969 $ctx =~ s/\n*$//;
f59b64bf 5970 my $stmt_cnt = statement_rawlines($ctx);
e3d95a2a 5971 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
f59b64bf 5972
f74bd194
AW
5973 if ($dstat ne '' &&
5974 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5975 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
3cc4b1c3 5976 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
356fd398 5977 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
f74bd194
AW
5978 $dstat !~ /$exceptions/ &&
5979 $dstat !~ /^\.$Ident\s*=/ && # .foo =
e942e2c3 5980 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
dc3f4dee 5981 $dstat !~ /^case\b/ && # case ...
72f115f9 5982 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
2e44e803 5983 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
f74bd194
AW
5984 $dstat !~ /^for\s*$Constant$/ && # for (...)
5985 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5986 $dstat !~ /^do\s*{/ && # do {...
4e5d56bd 5987 $dstat !~ /^\(\{/ && # ({...
f95a7e6a 5988 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
f74bd194 5989 {
e795556a
JP
5990 if ($dstat =~ /^\s*if\b/) {
5991 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5992 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5993 } elsif ($dstat =~ /;/) {
f74bd194
AW
5994 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5995 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5996 } else {
000d1cc1 5997 ERROR("COMPLEX_MACRO",
388982b5 5998 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
d8aaf121 5999 }
f59b64bf
JP
6000
6001 }
5207649b
JP
6002
6003 # Make $define_stmt single line, comment-free, etc
6004 my @stmt_array = split('\n', $define_stmt);
6005 my $first = 1;
6006 $define_stmt = "";
6007 foreach my $l (@stmt_array) {
6008 $l =~ s/\\$//;
6009 if ($first) {
6010 $define_stmt = $l;
6011 $first = 0;
6012 } elsif ($l =~ /^[\+ ]/) {
6013 $define_stmt .= substr($l, 1);
6014 }
6015 }
6016 $define_stmt =~ s/$;//g;
6017 $define_stmt =~ s/\s+/ /g;
6018 $define_stmt = trim($define_stmt);
6019
f59b64bf
JP
6020# check if any macro arguments are reused (ignore '...' and 'type')
6021 foreach my $arg (@def_args) {
6022 next if ($arg =~ /\.\.\./);
9192d41a 6023 next if ($arg =~ /^type$/i);
7fe528a2 6024 my $tmp_stmt = $define_stmt;
7b844345 6025 $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;
7fe528a2
JP
6026 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6027 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
d41362ed 6028 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
f59b64bf
JP
6029 if ($use_cnt > 1) {
6030 CHK("MACRO_ARG_REUSE",
6031 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
9192d41a
JP
6032 }
6033# check if any macro arguments may have other precedence issues
7fe528a2 6034 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
9192d41a
JP
6035 ((defined($1) && $1 ne ',') ||
6036 (defined($2) && $2 ne ','))) {
6037 CHK("MACRO_ARG_PRECEDENCE",
6038 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
f59b64bf 6039 }
653d4876 6040 }
5023d347 6041
08a2843e
JP
6042# check for macros with flow control, but without ## concatenation
6043# ## concatenation is commonly a macro that defines a function so ignore those
6044 if ($has_flow_statement && !$has_arg_concat) {
08a2843e 6045 my $cnt = statement_rawlines($ctx);
e3d95a2a 6046 my $herectx = get_stat_here($linenr, $cnt, $here);
08a2843e 6047
08a2843e
JP
6048 WARN("MACRO_WITH_FLOW_CONTROL",
6049 "Macros with flow control statements should be avoided\n" . "$herectx");
6050 }
6051
481eb486 6052# check for line continuations outside of #defines, preprocessor #, and asm
5023d347
JP
6053
6054 } else {
6055 if ($prevline !~ /^..*\\$/ &&
481eb486
JP
6056 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6057 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5023d347
JP
6058 $line =~ /^\+.*\\$/) {
6059 WARN("LINE_CONTINUATIONS",
6060 "Avoid unnecessary line continuations\n" . $herecurr);
6061 }
0a920b5b
AW
6062 }
6063
b13edf7f
JP
6064# do {} while (0) macro tests:
6065# single-statement macros do not need to be enclosed in do while (0) loop,
6066# macro should not end with a semicolon
5b57980d 6067 if ($perl_version_ok &&
b13edf7f
JP
6068 $realfile !~ m@/vmlinux.lds.h$@ &&
6069 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6070 my $ln = $linenr;
6071 my $cnt = $realcnt;
6072 my ($off, $dstat, $dcond, $rest);
6073 my $ctx = '';
6074 ($dstat, $dcond, $ln, $cnt, $off) =
6075 ctx_statement_block($linenr, $realcnt, 0);
6076 $ctx = $dstat;
6077
6078 $dstat =~ s/\\\n.//g;
1b36b201 6079 $dstat =~ s/$;/ /g;
b13edf7f
JP
6080
6081 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6082 my $stmts = $2;
6083 my $semis = $3;
6084
6085 $ctx =~ s/\n*$//;
6086 my $cnt = statement_rawlines($ctx);
e3d95a2a 6087 my $herectx = get_stat_here($linenr, $cnt, $here);
b13edf7f 6088
ac8e97f8
JP
6089 if (($stmts =~ tr/;/;/) == 1 &&
6090 $stmts !~ /^\s*(if|while|for|switch)\b/) {
b13edf7f
JP
6091 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6092 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6093 }
6094 if (defined $semis && $semis ne "") {
6095 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6096 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6097 }
f5ef95b1
JP
6098 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6099 $ctx =~ s/\n*$//;
6100 my $cnt = statement_rawlines($ctx);
e3d95a2a 6101 my $herectx = get_stat_here($linenr, $cnt, $here);
f5ef95b1
JP
6102
6103 WARN("TRAILING_SEMICOLON",
6104 "macros should not use a trailing semicolon\n" . "$herectx");
b13edf7f
JP
6105 }
6106 }
6107
f0a594c1 6108# check for redundant bracing round if etc
13214adf
AW
6109 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6110 my ($level, $endln, @chunks) =
cf655043 6111 ctx_statement_full($linenr, $realcnt, 1);
13214adf 6112 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
cf655043
AW
6113 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6114 if ($#chunks > 0 && $level == 0) {
aad4f614
JP
6115 my @allowed = ();
6116 my $allow = 0;
13214adf 6117 my $seen = 0;
773647a0 6118 my $herectx = $here . "\n";
cf655043 6119 my $ln = $linenr - 1;
13214adf
AW
6120 for my $chunk (@chunks) {
6121 my ($cond, $block) = @{$chunk};
6122
773647a0
AW
6123 # If the condition carries leading newlines, then count those as offsets.
6124 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6125 my $offset = statement_rawlines($whitespace) - 1;
6126
aad4f614 6127 $allowed[$allow] = 0;
773647a0
AW
6128 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6129
6130 # We have looked at and allowed this specific line.
6131 $suppress_ifbraces{$ln + $offset} = 1;
6132
6133 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
cf655043
AW
6134 $ln += statement_rawlines($block) - 1;
6135
773647a0 6136 substr($block, 0, length($cond), '');
13214adf
AW
6137
6138 $seen++ if ($block =~ /^\s*{/);
6139
aad4f614 6140 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
cf655043
AW
6141 if (statement_lines($cond) > 1) {
6142 #print "APW: ALLOWED: cond<$cond>\n";
aad4f614 6143 $allowed[$allow] = 1;
13214adf
AW
6144 }
6145 if ($block =~/\b(?:if|for|while)\b/) {
cf655043 6146 #print "APW: ALLOWED: block<$block>\n";
aad4f614 6147 $allowed[$allow] = 1;
13214adf 6148 }
cf655043
AW
6149 if (statement_block_size($block) > 1) {
6150 #print "APW: ALLOWED: lines block<$block>\n";
aad4f614 6151 $allowed[$allow] = 1;
13214adf 6152 }
aad4f614 6153 $allow++;
13214adf 6154 }
aad4f614
JP
6155 if ($seen) {
6156 my $sum_allowed = 0;
6157 foreach (@allowed) {
6158 $sum_allowed += $_;
6159 }
6160 if ($sum_allowed == 0) {
6161 WARN("BRACES",
6162 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6163 } elsif ($sum_allowed != $allow &&
6164 $seen != $allow) {
6165 CHK("BRACES",
6166 "braces {} should be used on all arms of this statement\n" . $herectx);
6167 }
13214adf
AW
6168 }
6169 }
6170 }
773647a0 6171 if (!defined $suppress_ifbraces{$linenr - 1} &&
13214adf 6172 $line =~ /\b(if|while|for|else)\b/) {
cf655043
AW
6173 my $allowed = 0;
6174
6175 # Check the pre-context.
6176 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6177 #print "APW: ALLOWED: pre<$1>\n";
6178 $allowed = 1;
6179 }
773647a0
AW
6180
6181 my ($level, $endln, @chunks) =
6182 ctx_statement_full($linenr, $realcnt, $-[0]);
6183
cf655043
AW
6184 # Check the condition.
6185 my ($cond, $block) = @{$chunks[0]};
773647a0 6186 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
cf655043 6187 if (defined $cond) {
773647a0 6188 substr($block, 0, length($cond), '');
cf655043
AW
6189 }
6190 if (statement_lines($cond) > 1) {
6191 #print "APW: ALLOWED: cond<$cond>\n";
6192 $allowed = 1;
6193 }
6194 if ($block =~/\b(?:if|for|while)\b/) {
6195 #print "APW: ALLOWED: block<$block>\n";
6196 $allowed = 1;
6197 }
6198 if (statement_block_size($block) > 1) {
6199 #print "APW: ALLOWED: lines block<$block>\n";
6200 $allowed = 1;
6201 }
6202 # Check the post-context.
6203 if (defined $chunks[1]) {
6204 my ($cond, $block) = @{$chunks[1]};
6205 if (defined $cond) {
773647a0 6206 substr($block, 0, length($cond), '');
cf655043
AW
6207 }
6208 if ($block =~ /^\s*\{/) {
6209 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6210 $allowed = 1;
6211 }
6212 }
6213 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
f055663c 6214 my $cnt = statement_rawlines($block);
e3d95a2a 6215 my $herectx = get_stat_here($linenr, $cnt, $here);
cf655043 6216
000d1cc1
JP
6217 WARN("BRACES",
6218 "braces {} are not necessary for single statement blocks\n" . $herectx);
f0a594c1
AW
6219 }
6220 }
6221
e4c5babd 6222# check for single line unbalanced braces
95330473
SE
6223 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6224 $sline =~ /^.\s*else\s*\{\s*$/) {
e4c5babd
JP
6225 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6226 }
6227
0979ae66 6228# check for unnecessary blank lines around braces
77b9a53a 6229 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
f8e58219
JP
6230 if (CHK("BRACES",
6231 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6232 $fix && $prevrawline =~ /^\+/) {
6233 fix_delete_line($fixlinenr - 1, $prevrawline);
6234 }
0979ae66 6235 }
77b9a53a 6236 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
f8e58219
JP
6237 if (CHK("BRACES",
6238 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6239 $fix) {
6240 fix_delete_line($fixlinenr, $rawline);
6241 }
0979ae66
JP
6242 }
6243
4a0df2ef 6244# no volatiles please
6c72ffaa
AW
6245 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6246 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
000d1cc1 6247 WARN("VOLATILE",
8c27ceff 6248 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
4a0df2ef
AW
6249 }
6250
5e4f6ba5
JP
6251# Check for user-visible strings broken across lines, which breaks the ability
6252# to grep for the string. Make exceptions when the previous string ends in a
6253# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6254# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
33acb54a 6255 if ($line =~ /^\+\s*$String/ &&
5e4f6ba5
JP
6256 $prevline =~ /"\s*$/ &&
6257 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6258 if (WARN("SPLIT_STRING",
6259 "quoted string split across lines\n" . $hereprev) &&
6260 $fix &&
6261 $prevrawline =~ /^\+.*"\s*$/ &&
6262 $last_coalesced_string_linenr != $linenr - 1) {
6263 my $extracted_string = get_quoted_string($line, $rawline);
6264 my $comma_close = "";
6265 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6266 $comma_close = $1;
6267 }
6268
6269 fix_delete_line($fixlinenr - 1, $prevrawline);
6270 fix_delete_line($fixlinenr, $rawline);
6271 my $fixedline = $prevrawline;
6272 $fixedline =~ s/"\s*$//;
6273 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6274 fix_insert_line($fixlinenr - 1, $fixedline);
6275 $fixedline = $rawline;
6276 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6277 if ($fixedline !~ /\+\s*$/) {
6278 fix_insert_line($fixlinenr, $fixedline);
6279 }
6280 $last_coalesced_string_linenr = $linenr;
6281 }
6282 }
6283
6284# check for missing a space in a string concatenation
6285 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6286 WARN('MISSING_SPACE',
6287 "break quoted strings at a space character\n" . $hereprev);
6288 }
6289
e4b7d309
JP
6290# check for an embedded function name in a string when the function is known
6291# This does not work very well for -f --file checking as it depends on patch
6292# context providing the function name or a single line form for in-file
6293# function declarations
77cb8546
JP
6294 if ($line =~ /^\+.*$String/ &&
6295 defined($context_function) &&
e4b7d309
JP
6296 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6297 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
77cb8546 6298 WARN("EMBEDDED_FUNCTION_NAME",
e4b7d309 6299 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
77cb8546
JP
6300 }
6301
adb2da82
JP
6302# check for unnecessary function tracing like uses
6303# This does not use $logFunctions because there are many instances like
6304# 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6305 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6306 if (WARN("TRACING_LOGGING",
6307 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6308 $fix) {
6309 fix_delete_line($fixlinenr, $rawline);
6310 }
6311 }
6312
5e4f6ba5
JP
6313# check for spaces before a quoted newline
6314 if ($rawline =~ /^.*\".*\s\\n/) {
6315 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6316 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6317 $fix) {
6318 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6319 }
6320
6321 }
6322
f17dba4f 6323# concatenated string without spaces between elements
d2af5aa6
JP
6324 if ($line =~ /$String[A-Z_]/ ||
6325 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
79682c0c
JP
6326 if (CHK("CONCATENATED_STRING",
6327 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6328 $fix) {
6329 while ($line =~ /($String)/g) {
6330 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6331 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6332 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6333 }
6334 }
f17dba4f
JP
6335 }
6336
90ad30e5 6337# uncoalesced string fragments
d2af5aa6 6338 if ($line =~ /$String\s*[Lu]?"/) {
79682c0c
JP
6339 if (WARN("STRING_FRAGMENTS",
6340 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6341 $fix) {
6342 while ($line =~ /($String)(?=\s*")/g) {
6343 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6344 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6345 }
6346 }
90ad30e5
JP
6347 }
6348
522b837c
AD
6349# check for non-standard and hex prefixed decimal printf formats
6350 my $show_L = 1; #don't show the same defect twice
6351 my $show_Z = 1;
5e4f6ba5 6352 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
522b837c 6353 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5e4f6ba5 6354 $string =~ s/%%/__/g;
522b837c
AD
6355 # check for %L
6356 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5e4f6ba5 6357 WARN("PRINTF_L",
522b837c
AD
6358 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6359 $show_L = 0;
6360 }
6361 # check for %Z
6362 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6363 WARN("PRINTF_Z",
6364 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6365 $show_Z = 0;
6366 }
6367 # check for 0x<decimal>
6368 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6369 ERROR("PRINTF_0XDECIMAL",
6e300757
JP
6370 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6371 }
5e4f6ba5
JP
6372 }
6373
6374# check for line continuations in quoted strings with odd counts of "
3f7f335d 6375 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5e4f6ba5
JP
6376 WARN("LINE_CONTINUATIONS",
6377 "Avoid line continuations in quoted strings\n" . $herecurr);
6378 }
6379
00df344f 6380# warn about #if 0
c45dcabd 6381 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
60f89010
PDH
6382 WARN("IF_0",
6383 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6384 }
6385
6386# warn about #if 1
6387 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6388 WARN("IF_1",
6389 "Consider removing the #if 1 and its #endif\n" . $herecurr);
4a0df2ef
AW
6390 }
6391
03df4b51
AW
6392# check for needless "if (<foo>) fn(<foo>)" uses
6393 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
100425de
JP
6394 my $tested = quotemeta($1);
6395 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6396 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6397 my $func = $1;
6398 if (WARN('NEEDLESS_IF',
6399 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6400 $fix) {
6401 my $do_fix = 1;
6402 my $leading_tabs = "";
6403 my $new_leading_tabs = "";
6404 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6405 $leading_tabs = $1;
6406 } else {
6407 $do_fix = 0;
6408 }
6409 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6410 $new_leading_tabs = $1;
6411 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6412 $do_fix = 0;
6413 }
6414 } else {
6415 $do_fix = 0;
6416 }
6417 if ($do_fix) {
6418 fix_delete_line($fixlinenr - 1, $prevrawline);
6419 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6420 }
6421 }
4c432a8f
GKH
6422 }
6423 }
f0a594c1 6424
1eacac32
JFG
6425# check for soon-to-be-deprecated single-argument k[v]free_rcu() API
6426 if ($line =~ /\bk[v]?free_rcu\s*\([^(]+\)/) {
6427 if ($line =~ /\bk[v]?free_rcu\s*\([^,]+\)/) {
6428 ERROR("DEPRECATED_API",
6429 "Single-argument k[v]free_rcu() API is deprecated, please pass rcu_head object or call k[v]free_rcu_mightsleep()." . $herecurr);
6430 }
6431 }
6432
6433
ebfdc409
JP
6434# check for unnecessary "Out of Memory" messages
6435 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6436 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6437 (defined $1 || defined $3) &&
6438 $linenr > 3) {
6439 my $testval = $2;
6440 my $testline = $lines[$linenr - 3];
6441
6442 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6443# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6444
e29a70f1
JP
6445 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6446 $s !~ /\b__GFP_NOWARN\b/ ) {
ebfdc409
JP
6447 WARN("OOM_MESSAGE",
6448 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6449 }
6450 }
6451
f78d98f6 6452# check for logging functions with KERN_<LEVEL>
dcaf1123 6453 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
f78d98f6
JP
6454 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6455 my $level = $1;
6456 if (WARN("UNNECESSARY_KERN_LEVEL",
6457 "Possible unnecessary $level\n" . $herecurr) &&
6458 $fix) {
6459 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6460 }
6461 }
6462
45c55e92
JP
6463# check for logging continuations
6464 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6465 WARN("LOGGING_CONTINUATION",
6466 "Avoid logging continuation uses where feasible\n" . $herecurr);
6467 }
6468
70eb2275
DR
6469# check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6470 if (defined $stat &&
6471 $line =~ /\b$logFunctions\s*\(/ &&
6472 index($stat, '"') >= 0) {
6473 my $lc = $stat =~ tr@\n@@;
6474 $lc = $lc + $linenr;
6475 my $stat_real = get_stat_real($linenr, $lc);
6476 pos($stat_real) = index($stat_real, '"');
6477 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6478 my $pspec = $1;
6479 my $h = $2;
6480 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6481 if (WARN("UNNECESSARY_MODIFIER",
6482 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6483 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6484 my $nspec = $pspec;
6485 $nspec =~ s/h//g;
6486 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6487 }
6488 }
6489 }
6490
abb08a53 6491# check for mask then right shift without a parentheses
5b57980d 6492 if ($perl_version_ok &&
abb08a53
JP
6493 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6494 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6495 WARN("MASK_THEN_SHIFT",
6496 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6497 }
6498
b75ac618 6499# check for pointer comparisons to NULL
5b57980d 6500 if ($perl_version_ok) {
b75ac618
JP
6501 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6502 my $val = $1;
6503 my $equal = "!";
6504 $equal = "" if ($4 eq "!=");
6505 if (CHK("COMPARISON_TO_NULL",
6506 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6507 $fix) {
6508 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6509 }
6510 }
6511 }
6512
8716de38
JP
6513# check for bad placement of section $InitAttribute (e.g.: __initdata)
6514 if ($line =~ /(\b$InitAttribute\b)/) {
6515 my $attr = $1;
6516 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6517 my $ptr = $1;
6518 my $var = $2;
6519 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6520 ERROR("MISPLACED_INIT",
6521 "$attr should be placed after $var\n" . $herecurr)) ||
6522 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6523 WARN("MISPLACED_INIT",
6524 "$attr should be placed after $var\n" . $herecurr))) &&
6525 $fix) {
194f66fc 6526 $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;
8716de38
JP
6527 }
6528 }
6529 }
6530
e970b884
JP
6531# check for $InitAttributeData (ie: __initdata) with const
6532 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6533 my $attr = $1;
6534 $attr =~ /($InitAttributePrefix)(.*)/;
6535 my $attr_prefix = $1;
6536 my $attr_type = $2;
6537 if (ERROR("INIT_ATTRIBUTE",
6538 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6539 $fix) {
194f66fc 6540 $fixed[$fixlinenr] =~
e970b884
JP
6541 s/$InitAttributeData/${attr_prefix}initconst/;
6542 }
6543 }
6544
6545# check for $InitAttributeConst (ie: __initconst) without const
6546 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6547 my $attr = $1;
6548 if (ERROR("INIT_ATTRIBUTE",
6549 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6550 $fix) {
194f66fc 6551 my $lead = $fixed[$fixlinenr] =~
e970b884
JP
6552 /(^\+\s*(?:static\s+))/;
6553 $lead = rtrim($1);
6554 $lead = "$lead " if ($lead !~ /^\+$/);
6555 $lead = "${lead}const ";
194f66fc 6556 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
e970b884
JP
6557 }
6558 }
6559
c17893c7
JP
6560# check for __read_mostly with const non-pointer (should just be const)
6561 if ($line =~ /\b__read_mostly\b/ &&
6562 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6563 if (ERROR("CONST_READ_MOSTLY",
6564 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6565 $fix) {
6566 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6567 }
6568 }
6569
fbdb8138
JP
6570# don't use __constant_<foo> functions outside of include/uapi/
6571 if ($realfile !~ m@^include/uapi/@ &&
6572 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6573 my $constant_func = $1;
6574 my $func = $constant_func;
6575 $func =~ s/^__constant_//;
6576 if (WARN("CONSTANT_CONVERSION",
6577 "$constant_func should be $func\n" . $herecurr) &&
6578 $fix) {
194f66fc 6579 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
fbdb8138
JP
6580 }
6581 }
6582
1a15a250 6583# prefer usleep_range over udelay
37581c28 6584 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
43c1d77c 6585 my $delay = $1;
1a15a250 6586 # ignore udelay's < 10, however
43c1d77c 6587 if (! ($delay < 10) ) {
000d1cc1 6588 CHK("USLEEP_RANGE",
458f69ef 6589 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
43c1d77c
JP
6590 }
6591 if ($delay > 2000) {
6592 WARN("LONG_UDELAY",
6593 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
1a15a250
PP
6594 }
6595 }
6596
09ef8725
PP
6597# warn about unexpectedly long msleep's
6598 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6599 if ($1 < 20) {
000d1cc1 6600 WARN("MSLEEP",
458f69ef 6601 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
09ef8725
PP
6602 }
6603 }
6604
36ec1939
JP
6605# check for comparisons of jiffies
6606 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6607 WARN("JIFFIES_COMPARISON",
6608 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6609 }
6610
9d7a34a5
JP
6611# check for comparisons of get_jiffies_64()
6612 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6613 WARN("JIFFIES_COMPARISON",
6614 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6615 }
6616
00df344f 6617# warn about #ifdefs in C files
c45dcabd 6618# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
00df344f
AW
6619# print "#ifdef in C files should be avoided\n";
6620# print "$herecurr";
6621# $clean = 0;
6622# }
6623
22f2a2ef 6624# warn about spacing in #ifdefs
c45dcabd 6625 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3705ce5b
JP
6626 if (ERROR("SPACING",
6627 "exactly one space required after that #$1\n" . $herecurr) &&
6628 $fix) {
194f66fc 6629 $fixed[$fixlinenr] =~
3705ce5b
JP
6630 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6631 }
6632
22f2a2ef
AW
6633 }
6634
4a0df2ef 6635# check for spinlock_t definitions without a comment.
171ae1a4
AW
6636 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6637 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4a0df2ef
AW
6638 my $which = $1;
6639 if (!ctx_has_comment($first_line, $linenr)) {
000d1cc1
JP
6640 CHK("UNCOMMENTED_DEFINITION",
6641 "$1 definition without comment\n" . $herecurr);
4a0df2ef
AW
6642 }
6643 }
6644# check for memory barriers without a comment.
402c2553
MT
6645
6646 my $barriers = qr{
6647 mb|
6648 rmb|
ad83ec6c 6649 wmb
402c2553
MT
6650 }x;
6651 my $barrier_stems = qr{
6652 mb__before_atomic|
6653 mb__after_atomic|
6654 store_release|
6655 load_acquire|
6656 store_mb|
6657 (?:$barriers)
6658 }x;
6659 my $all_barriers = qr{
6660 (?:$barriers)|
43e361f2
MT
6661 smp_(?:$barrier_stems)|
6662 virt_(?:$barrier_stems)
402c2553
MT
6663 }x;
6664
6665 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
4a0df2ef 6666 if (!ctx_has_comment($first_line, $linenr)) {
c1fd7bb9
JP
6667 WARN("MEMORY_BARRIER",
6668 "memory barrier without comment\n" . $herecurr);
4a0df2ef
AW
6669 }
6670 }
3ad81779 6671
f4073b0f
MT
6672 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6673
6674 if ($realfile !~ m@^include/asm-generic/@ &&
6675 $realfile !~ m@/barrier\.h$@ &&
6676 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6677 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6678 WARN("MEMORY_BARRIER",
6679 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6680 }
6681
cb426e99
JP
6682# check for waitqueue_active without a comment.
6683 if ($line =~ /\bwaitqueue_active\s*\(/) {
6684 if (!ctx_has_comment($first_line, $linenr)) {
6685 WARN("WAITQUEUE_ACTIVE",
6686 "waitqueue_active without comment\n" . $herecurr);
6687 }
6688 }
3ad81779 6689
5099a722
ME
6690# check for data_race without a comment.
6691 if ($line =~ /\bdata_race\s*\(/) {
6692 if (!ctx_has_comment($first_line, $linenr)) {
6693 WARN("DATA_RACE",
6694 "data_race without comment\n" . $herecurr);
6695 }
6696 }
6697
4a0df2ef 6698# check of hardware specific defines
c45dcabd 6699 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
000d1cc1
JP
6700 CHK("ARCH_DEFINES",
6701 "architecture specific defines should be avoided\n" . $herecurr);
0a920b5b 6702 }
653d4876 6703
596ed45b
JP
6704# check that the storage class is not after a type
6705 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6706 WARN("STORAGE_CLASS",
6707 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6708 }
d4977c78 6709# Check that the storage class is at the beginning of a declaration
596ed45b
JP
6710 if ($line =~ /\b$Storage\b/ &&
6711 $line !~ /^.\s*$Storage/ &&
6712 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6713 $1 !~ /[\,\)]\s*$/) {
000d1cc1 6714 WARN("STORAGE_CLASS",
596ed45b 6715 "storage class should be at the beginning of the declaration\n" . $herecurr);
d4977c78
TK
6716 }
6717
de7d4f0e
AW
6718# check the location of the inline attribute, that it is between
6719# storage class and type.
9c0ca6f9
AW
6720 if ($line =~ /\b$Type\s+$Inline\b/ ||
6721 $line =~ /\b$Inline\s+$Storage\b/) {
000d1cc1
JP
6722 ERROR("INLINE_LOCATION",
6723 "inline keyword should sit between storage class and type\n" . $herecurr);
de7d4f0e
AW
6724 }
6725
8905a67c 6726# Check for __inline__ and __inline, prefer inline
2b7ab453
JP
6727 if ($realfile !~ m@\binclude/uapi/@ &&
6728 $line =~ /\b(__inline__|__inline)\b/) {
d5e616fc
JP
6729 if (WARN("INLINE",
6730 "plain inline is preferred over $1\n" . $herecurr) &&
6731 $fix) {
194f66fc 6732 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
d5e616fc
JP
6733
6734 }
8905a67c
AW
6735 }
6736
7ebe1d17 6737# Check for compiler attributes
2b7ab453 6738 if ($realfile !~ m@\binclude/uapi/@ &&
7ebe1d17
DR
6739 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6740 my $attr = $1;
6741 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6742
6743 my %attr_list = (
0830aab0 6744 "alias" => "__alias",
7ebe1d17
DR
6745 "aligned" => "__aligned",
6746 "always_inline" => "__always_inline",
6747 "assume_aligned" => "__assume_aligned",
6748 "cold" => "__cold",
6749 "const" => "__attribute_const__",
6750 "copy" => "__copy",
6751 "designated_init" => "__designated_init",
6752 "externally_visible" => "__visible",
6753 "format" => "printf|scanf",
6754 "gnu_inline" => "__gnu_inline",
6755 "malloc" => "__malloc",
6756 "mode" => "__mode",
6757 "no_caller_saved_registers" => "__no_caller_saved_registers",
6758 "noclone" => "__noclone",
6759 "noinline" => "noinline",
6760 "nonstring" => "__nonstring",
6761 "noreturn" => "__noreturn",
6762 "packed" => "__packed",
6763 "pure" => "__pure",
339f29d9 6764 "section" => "__section",
0830aab0
JP
6765 "used" => "__used",
6766 "weak" => "__weak"
7ebe1d17
DR
6767 );
6768
7ebe1d17 6769 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
339f29d9 6770 my $orig_attr = $1;
7ebe1d17
DR
6771 my $params = '';
6772 $params = $2 if defined($2);
339f29d9 6773 my $curr_attr = $orig_attr;
7ebe1d17 6774 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
7ebe1d17 6775 if (exists($attr_list{$curr_attr})) {
339f29d9 6776 my $new = $attr_list{$curr_attr};
7ebe1d17
DR
6777 if ($curr_attr eq "format" && $params) {
6778 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
339f29d9 6779 $new = "__$1\($2";
7ebe1d17 6780 } else {
339f29d9
JP
6781 $new = "$new$params";
6782 }
6783 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6784 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6785 $fix) {
6786 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6787 $fixed[$fixlinenr] =~ s/$remove//;
6788 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6789 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6790 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
7ebe1d17 6791 }
7ebe1d17 6792 }
d5e616fc 6793 }
5f14d3bd 6794
7ebe1d17
DR
6795 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6796 if ($attr =~ /^_*unused/) {
6797 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6798 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
d5e616fc 6799 }
6061d949
JP
6800 }
6801
619a908a 6802# Check for __attribute__ weak, or __weak declarations (may have link issues)
5b57980d 6803 if ($perl_version_ok &&
619a908a
JP
6804 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6805 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6806 $line =~ /\b__weak\b/)) {
6807 ERROR("WEAK_DECLARATION",
6808 "Using weak declarations can have unintended link defects\n" . $herecurr);
6809 }
6810
fd39f904 6811# check for c99 types like uint8_t used outside of uapi/ and tools/
e6176fa4 6812 if ($realfile !~ m@\binclude/uapi/@ &&
fd39f904 6813 $realfile !~ m@\btools/@ &&
e6176fa4
JP
6814 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6815 my $type = $1;
6816 if ($type =~ /\b($typeC99Typedefs)\b/) {
6817 $type = $1;
6818 my $kernel_type = 'u';
6819 $kernel_type = 's' if ($type =~ /^_*[si]/);
6820 $type =~ /(\d+)/;
6821 $kernel_type .= $1;
6822 if (CHK("PREFER_KERNEL_TYPES",
6823 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6824 $fix) {
6825 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6826 }
6827 }
6828 }
6829
938224b5
JP
6830# check for cast of C90 native int or longer types constants
6831 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6832 my $cast = $1;
6833 my $const = $2;
0972b8bf
JP
6834 my $suffix = "";
6835 my $newconst = $const;
6836 $newconst =~ s/${Int_type}$//;
6837 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6838 if ($cast =~ /\blong\s+long\b/) {
6839 $suffix .= 'LL';
6840 } elsif ($cast =~ /\blong\b/) {
6841 $suffix .= 'L';
6842 }
938224b5 6843 if (WARN("TYPECAST_INT_CONSTANT",
0972b8bf 6844 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
938224b5 6845 $fix) {
938224b5
JP
6846 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6847 }
6848 }
6849
8f53a9b8
JP
6850# check for sizeof(&)
6851 if ($line =~ /\bsizeof\s*\(\s*\&/) {
000d1cc1
JP
6852 WARN("SIZEOF_ADDRESS",
6853 "sizeof(& should be avoided\n" . $herecurr);
8f53a9b8
JP
6854 }
6855
66c80b60
JP
6856# check for sizeof without parenthesis
6857 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
d5e616fc
JP
6858 if (WARN("SIZEOF_PARENTHESIS",
6859 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6860 $fix) {
194f66fc 6861 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
d5e616fc 6862 }
66c80b60
JP
6863 }
6864
88982fea
JP
6865# check for struct spinlock declarations
6866 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6867 WARN("USE_SPINLOCK_T",
6868 "struct spinlock should be spinlock_t\n" . $herecurr);
6869 }
6870
a6962d72 6871# check for seq_printf uses that could be seq_puts
06668727 6872 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
a6962d72 6873 my $fmt = get_quoted_string($line, $rawline);
caac1d5f
HA
6874 $fmt =~ s/%%//g;
6875 if ($fmt !~ /%/) {
d5e616fc
JP
6876 if (WARN("PREFER_SEQ_PUTS",
6877 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6878 $fix) {
194f66fc 6879 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
d5e616fc 6880 }
a6962d72
JP
6881 }
6882 }
6883
478b1799 6884# check for vsprintf extension %p<foo> misuses
5b57980d 6885 if ($perl_version_ok &&
0b523769
JP
6886 defined $stat &&
6887 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6888 $1 !~ /^_*volatile_*$/) {
e3c6bc95
TH
6889 my $stat_real;
6890
0b523769
JP
6891 my $lc = $stat =~ tr@\n@@;
6892 $lc = $lc + $linenr;
6893 for (my $count = $linenr; $count <= $lc; $count++) {
ffe07513
JP
6894 my $specifier;
6895 my $extension;
3bd32d6a 6896 my $qualifier;
ffe07513 6897 my $bad_specifier = "";
0b523769
JP
6898 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6899 $fmt =~ s/%%//g;
e3c6bc95 6900
3bd32d6a 6901 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
e3c6bc95
TH
6902 $specifier = $1;
6903 $extension = $2;
3bd32d6a 6904 $qualifier = $3;
af612e43 6905 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
3bd32d6a 6906 ($extension eq "f" &&
af612e43
SA
6907 defined $qualifier && $qualifier !~ /^w/) ||
6908 ($extension eq "4" &&
6909 defined $qualifier && $qualifier !~ /^cc/)) {
e3c6bc95
TH
6910 $bad_specifier = $specifier;
6911 last;
6912 }
6913 if ($extension eq "x" && !defined($stat_real)) {
6914 if (!defined($stat_real)) {
6915 $stat_real = get_stat_real($linenr, $lc);
6916 }
6917 WARN("VSPRINTF_SPECIFIER_PX",
6918 "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");
6919 }
1df7338a 6920 }
e3c6bc95
TH
6921 if ($bad_specifier ne "") {
6922 my $stat_real = get_stat_real($linenr, $lc);
de48fa1a 6923 my $msg_level = \&WARN;
e3c6bc95
TH
6924 my $ext_type = "Invalid";
6925 my $use = "";
6926 if ($bad_specifier =~ /p[Ff]/) {
e3c6bc95
TH
6927 $use = " - use %pS instead";
6928 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
de48fa1a
MO
6929 } elsif ($bad_specifier =~ /pA/) {
6930 $use = " - '%pA' is only intended to be used from Rust code";
6931 $msg_level = \&ERROR;
e3c6bc95 6932 }
2a9f9d85 6933
de48fa1a
MO
6934 &{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6935 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
e3c6bc95 6936 }
0b523769
JP
6937 }
6938 }
6939
554e165c 6940# Check for misused memsets
5b57980d 6941 if ($perl_version_ok &&
d1fe9c09 6942 defined $stat &&
9e20a853 6943 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
d7c76ba7
JP
6944
6945 my $ms_addr = $2;
d1fe9c09
JP
6946 my $ms_val = $7;
6947 my $ms_size = $12;
554e165c 6948
554e165c
AW
6949 if ($ms_size =~ /^(0x|)0$/i) {
6950 ERROR("MEMSET",
d7c76ba7 6951 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
554e165c
AW
6952 } elsif ($ms_size =~ /^(0x|)1$/i) {
6953 WARN("MEMSET",
d7c76ba7
JP
6954 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6955 }
6956 }
6957
98a9bba5 6958# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5b57980d 6959# if ($perl_version_ok &&
f333195d
JP
6960# defined $stat &&
6961# $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6962# if (WARN("PREFER_ETHER_ADDR_COPY",
6963# "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6964# $fix) {
6965# $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6966# }
6967# }
98a9bba5 6968
b6117d17 6969# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5b57980d 6970# if ($perl_version_ok &&
f333195d
JP
6971# defined $stat &&
6972# $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6973# WARN("PREFER_ETHER_ADDR_EQUAL",
6974# "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6975# }
b6117d17 6976
8617cd09
MK
6977# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6978# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5b57980d 6979# if ($perl_version_ok &&
f333195d
JP
6980# defined $stat &&
6981# $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6982#
6983# my $ms_val = $7;
6984#
6985# if ($ms_val =~ /^(?:0x|)0+$/i) {
6986# if (WARN("PREFER_ETH_ZERO_ADDR",
6987# "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6988# $fix) {
6989# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6990# }
6991# } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6992# if (WARN("PREFER_ETH_BROADCAST_ADDR",
6993# "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6994# $fix) {
6995# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6996# }
6997# }
6998# }
8617cd09 6999
5dbdb2d8
JP
7000# strlcpy uses that should likely be strscpy
7001 if ($line =~ /\bstrlcpy\s*\(/) {
7002 WARN("STRLCPY",
7003 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
7004 }
7005
d7c76ba7 7006# typecasts on min/max could be min_t/max_t
5b57980d 7007 if ($perl_version_ok &&
d1fe9c09 7008 defined $stat &&
d7c76ba7 7009 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
d1fe9c09 7010 if (defined $2 || defined $7) {
d7c76ba7
JP
7011 my $call = $1;
7012 my $cast1 = deparenthesize($2);
7013 my $arg1 = $3;
d1fe9c09
JP
7014 my $cast2 = deparenthesize($7);
7015 my $arg2 = $8;
d7c76ba7
JP
7016 my $cast;
7017
d1fe9c09 7018 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
d7c76ba7
JP
7019 $cast = "$cast1 or $cast2";
7020 } elsif ($cast1 ne "") {
7021 $cast = $cast1;
7022 } else {
7023 $cast = $cast2;
7024 }
7025 WARN("MINMAX",
7026 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
554e165c
AW
7027 }
7028 }
7029
4a273195 7030# check usleep_range arguments
5b57980d 7031 if ($perl_version_ok &&
4a273195
JP
7032 defined $stat &&
7033 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7034 my $min = $1;
7035 my $max = $7;
7036 if ($min eq $max) {
7037 WARN("USLEEP_RANGE",
458f69ef 7038 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
4a273195
JP
7039 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7040 $min > $max) {
7041 WARN("USLEEP_RANGE",
458f69ef 7042 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
4a273195
JP
7043 }
7044 }
7045
823b794c 7046# check for naked sscanf
5b57980d 7047 if ($perl_version_ok &&
823b794c 7048 defined $stat &&
6c8bd707 7049 $line =~ /\bsscanf\b/ &&
823b794c
JP
7050 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7051 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7052 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7053 my $lc = $stat =~ tr@\n@@;
7054 $lc = $lc + $linenr;
2a9f9d85 7055 my $stat_real = get_stat_real($linenr, $lc);
823b794c
JP
7056 WARN("NAKED_SSCANF",
7057 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7058 }
7059
afc819ab 7060# check for simple sscanf that should be kstrto<foo>
5b57980d 7061 if ($perl_version_ok &&
afc819ab
JP
7062 defined $stat &&
7063 $line =~ /\bsscanf\b/) {
7064 my $lc = $stat =~ tr@\n@@;
7065 $lc = $lc + $linenr;
2a9f9d85 7066 my $stat_real = get_stat_real($linenr, $lc);
afc819ab
JP
7067 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7068 my $format = $6;
7069 my $count = $format =~ tr@%@%@;
7070 if ($count == 1 &&
7071 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7072 WARN("SSCANF_TO_KSTRTO",
7073 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7074 }
7075 }
7076 }
7077
70dc8a48
JP
7078# check for new externs in .h files.
7079 if ($realfile =~ /\.h$/ &&
7080 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
d1d85780
JP
7081 if (CHK("AVOID_EXTERNS",
7082 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
70dc8a48 7083 $fix) {
194f66fc 7084 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
70dc8a48
JP
7085 }
7086 }
7087
de7d4f0e 7088# check for new externs in .c files.
171ae1a4 7089 if ($realfile =~ /\.c$/ && defined $stat &&
c45dcabd 7090 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
171ae1a4 7091 {
c45dcabd
AW
7092 my $function_name = $1;
7093 my $paren_space = $2;
171ae1a4
AW
7094
7095 my $s = $stat;
7096 if (defined $cond) {
7097 substr($s, 0, length($cond), '');
7098 }
d8b44b58 7099 if ($s =~ /^\s*;/)
c45dcabd 7100 {
000d1cc1
JP
7101 WARN("AVOID_EXTERNS",
7102 "externs should be avoided in .c files\n" . $herecurr);
171ae1a4
AW
7103 }
7104
7105 if ($paren_space =~ /\n/) {
000d1cc1
JP
7106 WARN("FUNCTION_ARGUMENTS",
7107 "arguments for function declarations should follow identifier\n" . $herecurr);
171ae1a4 7108 }
9c9ba34e
AW
7109
7110 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7111 $stat =~ /^.\s*extern\s+/)
7112 {
000d1cc1
JP
7113 WARN("AVOID_EXTERNS",
7114 "externs should be avoided in .c files\n" . $herecurr);
de7d4f0e
AW
7115 }
7116
a0ad7596
JP
7117# check for function declarations that have arguments without identifier names
7118 if (defined $stat &&
d8b44b58
KC
7119 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7120 $1 ne "void") {
7121 my $args = trim($1);
ca0d8929
JP
7122 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7123 my $arg = trim($1);
d8b44b58 7124 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
ca0d8929
JP
7125 WARN("FUNCTION_ARGUMENTS",
7126 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7127 }
7128 }
7129 }
7130
a0ad7596 7131# check for function definitions
5b57980d 7132 if ($perl_version_ok &&
a0ad7596
JP
7133 defined $stat &&
7134 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7135 $context_function = $1;
7136
7137# check for multiline function definition with misplaced open brace
7138 my $ok = 0;
7139 my $cnt = statement_rawlines($stat);
7140 my $herectx = $here . "\n";
7141 for (my $n = 0; $n < $cnt; $n++) {
7142 my $rl = raw_line($linenr, $n);
7143 $herectx .= $rl . "\n";
7144 $ok = 1 if ($rl =~ /^[ \+]\{/);
7145 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7146 last if $rl =~ /^[ \+].*\{/;
7147 }
7148 if (!$ok) {
7149 ERROR("OPEN_BRACE",
7150 "open brace '{' following function definitions go on the next line\n" . $herectx);
7151 }
7152 }
7153
de7d4f0e
AW
7154# checks for new __setup's
7155 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7156 my $name = $1;
7157
7158 if (!grep(/$name/, @setup_docs)) {
000d1cc1 7159 CHK("UNDOCUMENTED_SETUP",
2581ac7c 7160 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
de7d4f0e 7161 }
653d4876 7162 }
9c0ca6f9 7163
e29a70f1
JP
7164# check for pointless casting of alloc functions
7165 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
000d1cc1
JP
7166 WARN("UNNECESSARY_CASTS",
7167 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
9c0ca6f9 7168 }
13214adf 7169
a640d25c
JP
7170# alloc style
7171# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5b57980d 7172 if ($perl_version_ok &&
e29a70f1 7173 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
a640d25c
JP
7174 CHK("ALLOC_SIZEOF_STRUCT",
7175 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7176 }
7177
73f1d07e 7178# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
5b57980d 7179 if ($perl_version_ok &&
1b4a2ed4 7180 defined $stat &&
73f1d07e 7181 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
60a55369
JP
7182 my $oldfunc = $3;
7183 my $a1 = $4;
7184 my $a2 = $10;
7185 my $newfunc = "kmalloc_array";
73f1d07e
GS
7186 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7187 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
60a55369 7188 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
e367455a
JP
7189 my $r1 = $a1;
7190 my $r2 = $a2;
7191 if ($a1 =~ /^sizeof\s*\S/) {
7192 $r1 = $a2;
7193 $r2 = $a1;
7194 }
7195 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7196 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
1b4a2ed4 7197 my $cnt = statement_rawlines($stat);
e3d95a2a
TH
7198 my $herectx = get_stat_here($linenr, $cnt, $here);
7199
60a55369 7200 if (WARN("ALLOC_WITH_MULTIPLY",
1b4a2ed4
JP
7201 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7202 $cnt == 1 &&
60a55369 7203 $fix) {
73f1d07e 7204 $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;
60a55369
JP
7205 }
7206 }
7207 }
7208
972fdea2 7209# check for krealloc arg reuse
5b57980d 7210 if ($perl_version_ok &&
4cab63ce
JP
7211 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7212 $1 eq $3) {
972fdea2
JP
7213 WARN("KREALLOC_ARG_REUSE",
7214 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7215 }
7216
5ce59ae0 7217# check for alloc argument mismatch
3965292a 7218 if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
5ce59ae0
JP
7219 WARN("ALLOC_ARRAY_ARGS",
7220 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7221 }
7222
caf2a54f
JP
7223# check for multiple semicolons
7224 if ($line =~ /;\s*;\s*$/) {
d5e616fc
JP
7225 if (WARN("ONE_SEMICOLON",
7226 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7227 $fix) {
194f66fc 7228 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
d5e616fc 7229 }
d1e2ad07
JP
7230 }
7231
cec3aaa5
TW
7232# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7233 if ($realfile !~ m@^include/uapi/@ &&
7234 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
0ab90191
JP
7235 my $ull = "";
7236 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7237 if (CHK("BIT_MACRO",
7238 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7239 $fix) {
7240 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7241 }
7242 }
7243
50161266 7244# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
3e89ad85 7245 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
50161266 7246 WARN("IS_ENABLED_CONFIG",
3e89ad85 7247 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
50161266
JP
7248 }
7249
2d632745 7250# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
3e89ad85 7251 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
2d632745
JP
7252 my $config = $1;
7253 if (WARN("PREFER_IS_ENABLED",
3e89ad85 7254 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
2d632745
JP
7255 $fix) {
7256 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7257 }
7258 }
7259
f36d3eb8
JP
7260# check for /* fallthrough */ like comment, prefer fallthrough;
7261 my @fallthroughs = (
7262 'fallthrough',
7263 '@fallthrough@',
7264 'lint -fallthrough[ \t]*',
7265 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7266 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7267 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7268 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7269 );
7270 if ($raw_comment ne '') {
7271 foreach my $ft (@fallthroughs) {
7272 if ($raw_comment =~ /$ft/) {
7273 my $msg_level = \&WARN;
7274 $msg_level = \&CHK if ($file);
7275 &{$msg_level}("PREFER_FALLTHROUGH",
7276 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7277 last;
7278 }
7279 }
7280 }
7281
d1e2ad07 7282# check for switch/default statements without a break;
5b57980d 7283 if ($perl_version_ok &&
d1e2ad07
JP
7284 defined $stat &&
7285 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
d1e2ad07 7286 my $cnt = statement_rawlines($stat);
e3d95a2a
TH
7287 my $herectx = get_stat_here($linenr, $cnt, $here);
7288
d1e2ad07
JP
7289 WARN("DEFAULT_NO_BREAK",
7290 "switch default: should use break\n" . $herectx);
caf2a54f
JP
7291 }
7292
13214adf 7293# check for gcc specific __FUNCTION__
d5e616fc
JP
7294 if ($line =~ /\b__FUNCTION__\b/) {
7295 if (WARN("USE_FUNC",
7296 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7297 $fix) {
194f66fc 7298 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
d5e616fc 7299 }
13214adf 7300 }
773647a0 7301
62ec818f
JP
7302# check for uses of __DATE__, __TIME__, __TIMESTAMP__
7303 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7304 ERROR("DATE_TIME",
7305 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7306 }
7307
2c92488a
JP
7308# check for use of yield()
7309 if ($line =~ /\byield\s*\(\s*\)/) {
7310 WARN("YIELD",
7311 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7312 }
7313
179f8f40
JP
7314# check for comparisons against true and false
7315 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7316 my $lead = $1;
7317 my $arg = $2;
7318 my $test = $3;
7319 my $otype = $4;
7320 my $trail = $5;
7321 my $op = "!";
7322
7323 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7324
7325 my $type = lc($otype);
7326 if ($type =~ /^(?:true|false)$/) {
7327 if (("$test" eq "==" && "$type" eq "true") ||
7328 ("$test" eq "!=" && "$type" eq "false")) {
7329 $op = "";
7330 }
7331
7332 CHK("BOOL_COMPARISON",
7333 "Using comparison to $otype is error prone\n" . $herecurr);
7334
7335## maybe suggesting a correct construct would better
7336## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7337
7338 }
7339 }
7340
4882720b
TG
7341# check for semaphores initialized locked
7342 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
000d1cc1
JP
7343 WARN("CONSIDER_COMPLETION",
7344 "consider using a completion\n" . $herecurr);
773647a0 7345 }
6712d858 7346
67d0a075
JP
7347# recommend kstrto* over simple_strto* and strict_strto*
7348 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
000d1cc1 7349 WARN("CONSIDER_KSTRTO",
67d0a075 7350 "$1 is obsolete, use k$3 instead\n" . $herecurr);
773647a0 7351 }
6712d858 7352
ae3ccc46 7353# check for __initcall(), use device_initcall() explicitly or more appropriate function please
f3db6639 7354 if ($line =~ /^.\s*__initcall\s*\(/) {
000d1cc1 7355 WARN("USE_DEVICE_INITCALL",
ae3ccc46 7356 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
f3db6639 7357 }
6712d858 7358
3d709ab5
PM
7359# check for spin_is_locked(), suggest lockdep instead
7360 if ($line =~ /\bspin_is_locked\(/) {
7361 WARN("USE_LOCKDEP",
7362 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7363 }
7364
9189c7e7
JP
7365# check for deprecated apis
7366 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7367 my $deprecated_api = $1;
7368 my $new_api = $deprecated_apis{$deprecated_api};
7369 WARN("DEPRECATED_API",
7370 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7371 }
7372
0f3c5aab 7373# check for various structs that are normally const (ops, kgdb, device_tree)
d9190e4e 7374# and avoid what seem like struct definitions 'struct foo {'
ced69da1
QM
7375 if (defined($const_structs) &&
7376 $line !~ /\bconst\b/ &&
d9190e4e 7377 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
000d1cc1 7378 WARN("CONST_STRUCT",
d9190e4e 7379 "struct $1 should normally be const\n" . $herecurr);
2b6db5cb 7380 }
773647a0
AW
7381
7382# use of NR_CPUS is usually wrong
7383# ignore definitions of NR_CPUS and usage to define arrays as likely right
35cdcbfc 7384# ignore designated initializers using NR_CPUS
773647a0 7385 if ($line =~ /\bNR_CPUS\b/ &&
c45dcabd
AW
7386 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7387 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
171ae1a4
AW
7388 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7389 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
35cdcbfc
PW
7390 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7391 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
773647a0 7392 {
000d1cc1
JP
7393 WARN("NR_CPUS",
7394 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
773647a0 7395 }
9c9ba34e 7396
52ea8506
JP
7397# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7398 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7399 ERROR("DEFINE_ARCH_HAS",
7400 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7401 }
7402
acd9362c 7403# likely/unlikely comparisons similar to "(likely(foo) > 0)"
5b57980d 7404 if ($perl_version_ok &&
acd9362c
JP
7405 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7406 WARN("LIKELY_MISUSE",
7407 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7408 }
7409
fbe74541
JP
7410# return sysfs_emit(foo, fmt, ...) fmt without newline
7411 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7412 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7413 my $offset = $+[6] - 1;
7414 if (WARN("SYSFS_EMIT",
7415 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7416 $fix) {
7417 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7418 }
7419 }
7420
de3f186f
DE
7421# nested likely/unlikely calls
7422 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7423 WARN("LIKELY_MISUSE",
7424 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7425 }
7426
691d77b6
AW
7427# whine mightly about in_atomic
7428 if ($line =~ /\bin_atomic\s*\(/) {
7429 if ($realfile =~ m@^drivers/@) {
000d1cc1
JP
7430 ERROR("IN_ATOMIC",
7431 "do not use in_atomic in drivers\n" . $herecurr);
f4a87736 7432 } elsif ($realfile !~ m@^kernel/@) {
000d1cc1
JP
7433 WARN("IN_ATOMIC",
7434 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
691d77b6
AW
7435 }
7436 }
1704f47b
PZ
7437
7438# check for lockdep_set_novalidate_class
7439 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7440 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7441 if ($realfile !~ m@^kernel/lockdep@ &&
7442 $realfile !~ m@^include/linux/lockdep@ &&
7443 $realfile !~ m@^drivers/base/core@) {
000d1cc1
JP
7444 ERROR("LOCKDEP",
7445 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
1704f47b
PZ
7446 }
7447 }
88f8831c 7448
b392c64f
JP
7449 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7450 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
000d1cc1
JP
7451 WARN("EXPORTED_WORLD_WRITABLE",
7452 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
88f8831c 7453 }
2435880f 7454
00180468
JP
7455# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7456# and whether or not function naming is typical and if
7457# DEVICE_ATTR permissions uses are unusual too
5b57980d 7458 if ($perl_version_ok &&
00180468
JP
7459 defined $stat &&
7460 $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*\)/) {
7461 my $var = $1;
7462 my $perms = $2;
7463 my $show = $3;
7464 my $store = $4;
7465 my $octal_perms = perms_to_octal($perms);
7466 if ($show =~ /^${var}_show$/ &&
7467 $store =~ /^${var}_store$/ &&
7468 $octal_perms eq "0644") {
7469 if (WARN("DEVICE_ATTR_RW",
7470 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7471 $fix) {
7472 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7473 }
7474 } elsif ($show =~ /^${var}_show$/ &&
7475 $store =~ /^NULL$/ &&
7476 $octal_perms eq "0444") {
7477 if (WARN("DEVICE_ATTR_RO",
7478 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7479 $fix) {
7480 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7481 }
7482 } elsif ($show =~ /^NULL$/ &&
7483 $store =~ /^${var}_store$/ &&
7484 $octal_perms eq "0200") {
7485 if (WARN("DEVICE_ATTR_WO",
7486 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7487 $fix) {
7488 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7489 }
7490 } elsif ($octal_perms eq "0644" ||
7491 $octal_perms eq "0444" ||
7492 $octal_perms eq "0200") {
7493 my $newshow = "$show";
7494 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7495 my $newstore = $store;
7496 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7497 my $rename = "";
7498 if ($show ne $newshow) {
7499 $rename .= " '$show' to '$newshow'";
7500 }
7501 if ($store ne $newstore) {
7502 $rename .= " '$store' to '$newstore'";
7503 }
7504 WARN("DEVICE_ATTR_FUNCTIONS",
7505 "Consider renaming function(s)$rename\n" . $herecurr);
7506 } else {
7507 WARN("DEVICE_ATTR_PERMS",
7508 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7509 }
7510 }
7511
515a235e
JP
7512# Mode permission misuses where it seems decimal should be octal
7513# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
73121534
JP
7514# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7515# specific definition of not visible in sysfs.
7516# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7517# use the default permissions
5b57980d 7518 if ($perl_version_ok &&
459cf0ae 7519 defined $stat &&
515a235e
JP
7520 $line =~ /$mode_perms_search/) {
7521 foreach my $entry (@mode_permission_funcs) {
7522 my $func = $entry->[0];
7523 my $arg_pos = $entry->[1];
7524
459cf0ae
JP
7525 my $lc = $stat =~ tr@\n@@;
7526 $lc = $lc + $linenr;
2a9f9d85 7527 my $stat_real = get_stat_real($linenr, $lc);
459cf0ae 7528
515a235e
JP
7529 my $skip_args = "";
7530 if ($arg_pos > 1) {
7531 $arg_pos--;
7532 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7533 }
f90774e1 7534 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
459cf0ae 7535 if ($stat =~ /$test/) {
515a235e
JP
7536 my $val = $1;
7537 $val = $6 if ($skip_args ne "");
73121534
JP
7538 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7539 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7540 ($val =~ /^$Octal$/ && length($val) ne 4))) {
515a235e 7541 ERROR("NON_OCTAL_PERMISSIONS",
459cf0ae 7542 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
f90774e1
JP
7543 }
7544 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
c0a5c898 7545 ERROR("EXPORTED_WORLD_WRITABLE",
459cf0ae 7546 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
f90774e1 7547 }
2435880f
JP
7548 }
7549 }
7550 }
5a6d20ce 7551
459cf0ae 7552# check for uses of S_<PERMS> that could be octal for readability
bc22d9a7 7553 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
00180468
JP
7554 my $oval = $1;
7555 my $octal = perms_to_octal($oval);
459cf0ae
JP
7556 if (WARN("SYMBOLIC_PERMS",
7557 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7558 $fix) {
00180468 7559 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
459cf0ae
JP
7560 }
7561 }
7562
5a6d20ce
BA
7563# validate content of MODULE_LICENSE against list from include/linux/module.h
7564 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7565 my $extracted_string = get_quoted_string($line, $rawline);
7566 my $valid_licenses = qr{
7567 GPL|
7568 GPL\ v2|
7569 GPL\ and\ additional\ rights|
7570 Dual\ BSD/GPL|
7571 Dual\ MIT/GPL|
7572 Dual\ MPL/GPL|
7573 Proprietary
7574 }x;
7575 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7576 WARN("MODULE_LICENSE",
7577 "unknown module license " . $extracted_string . "\n" . $herecurr);
7578 }
6e8f42dc
JP
7579 if (!$file && $extracted_string eq '"GPL v2"') {
7580 if (WARN("MODULE_LICENSE",
7581 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7582 $fix) {
7583 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7584 }
7585 }
5a6d20ce 7586 }
6a8d76cb
MC
7587
7588# check for sysctl duplicate constants
7589 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7590 WARN("DUPLICATED_SYSCTL_CONST",
7591 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7592 }
13214adf
AW
7593 }
7594
7595 # If we have no input at all, then there is nothing to report on
7596 # so just keep quiet.
7597 if ($#rawlines == -1) {
7598 exit(0);
0a920b5b
AW
7599 }
7600
8905a67c
AW
7601 # In mailback mode only produce a report in the negative, for
7602 # things that appear to be patches.
7603 if ($mailback && ($clean == 1 || !$is_patch)) {
7604 exit(0);
7605 }
7606
e73d2715 7607 # This is not a patch, and we are in 'no-patch' mode so
8905a67c
AW
7608 # just keep quiet.
7609 if (!$chk_patch && !$is_patch) {
7610 exit(0);
7611 }
7612
a08ffbef 7613 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
000d1cc1
JP
7614 ERROR("NOT_UNIFIED_DIFF",
7615 "Does not appear to be a unified-diff format patch\n");
0a920b5b 7616 }
cd261496
GU
7617 if ($is_patch && $has_commit_log && $chk_signoff) {
7618 if ($signoff == 0) {
7619 ERROR("MISSING_SIGN_OFF",
7620 "Missing Signed-off-by: line(s)\n");
48ca2d8a
DR
7621 } elsif ($authorsignoff != 1) {
7622 # authorsignoff values:
7623 # 0 -> missing sign off
7624 # 1 -> sign off identical
7625 # 2 -> names and addresses match, comments mismatch
7626 # 3 -> addresses match, names different
7627 # 4 -> names match, addresses different
7628 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7629
7630 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7631
7632 if ($authorsignoff == 0) {
7633 ERROR("NO_AUTHOR_SIGN_OFF",
7634 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7635 } elsif ($authorsignoff == 2) {
7636 CHK("FROM_SIGN_OFF_MISMATCH",
7637 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7638 } elsif ($authorsignoff == 3) {
7639 WARN("FROM_SIGN_OFF_MISMATCH",
7640 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7641 } elsif ($authorsignoff == 4) {
7642 WARN("FROM_SIGN_OFF_MISMATCH",
7643 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7644 } elsif ($authorsignoff == 5) {
7645 WARN("FROM_SIGN_OFF_MISMATCH",
7646 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7647 }
cd261496 7648 }
0a920b5b
AW
7649 }
7650
8905a67c 7651 print report_dump();
13214adf
AW
7652 if ($summary && !($clean == 1 && $quiet == 1)) {
7653 print "$filename " if ($summary_file);
8905a67c
AW
7654 print "total: $cnt_error errors, $cnt_warn warnings, " .
7655 (($check)? "$cnt_chk checks, " : "") .
7656 "$cnt_lines lines checked\n";
f0a594c1 7657 }
8905a67c 7658
d2c0a235 7659 if ($quiet == 0) {
ef212196
JP
7660 # If there were any defects found and not already fixing them
7661 if (!$clean and !$fix) {
7662 print << "EOM"
7663
7664NOTE: For some of the reported defects, checkpatch may be able to
7665 mechanically convert to the typical style using --fix or --fix-inplace.
7666EOM
7667 }
d2c0a235
AW
7668 # If there were whitespace errors which cleanpatch can fix
7669 # then suggest that.
7670 if ($rpt_cleaners) {
b0781216 7671 $rpt_cleaners = 0;
d8469f16
JP
7672 print << "EOM"
7673
7674NOTE: Whitespace errors detected.
7675 You may wish to use scripts/cleanpatch or scripts/cleanfile
7676EOM
d2c0a235
AW
7677 }
7678 }
7679
d752fcc8
JP
7680 if ($clean == 0 && $fix &&
7681 ("@rawlines" ne "@fixed" ||
7682 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
9624b8d6
JP
7683 my $newfile = $filename;
7684 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
3705ce5b
JP
7685 my $linecount = 0;
7686 my $f;
7687
d752fcc8
JP
7688 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7689
3705ce5b
JP
7690 open($f, '>', $newfile)
7691 or die "$P: Can't open $newfile for write\n";
7692 foreach my $fixed_line (@fixed) {
7693 $linecount++;
7694 if ($file) {
7695 if ($linecount > 3) {
7696 $fixed_line =~ s/^\+//;
d752fcc8 7697 print $f $fixed_line . "\n";
3705ce5b
JP
7698 }
7699 } else {
7700 print $f $fixed_line . "\n";
7701 }
7702 }
7703 close($f);
7704
7705 if (!$quiet) {
7706 print << "EOM";
d8469f16 7707
3705ce5b
JP
7708Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7709
7710Do _NOT_ trust the results written to this file.
7711Do _NOT_ submit these changes without inspecting them for correctness.
7712
7713This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7714No warranties, expressed or implied...
3705ce5b
JP
7715EOM
7716 }
7717 }
7718
d8469f16
JP
7719 if ($quiet == 0) {
7720 print "\n";
7721 if ($clean == 1) {
7722 print "$vname has no obvious style problems and is ready for submission.\n";
7723 } else {
7724 print "$vname has style problems, please review.\n";
7725 }
0a920b5b
AW
7726 }
7727 return $clean;
7728}