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