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