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