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