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