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