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