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