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