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