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