checkpatch: improve space before tab --fix option
[linux-2.6-block.git] / scripts / checkpatch.pl
1 #!/usr/bin/perl -w
2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
7
8 use strict;
9 use POSIX;
10
11 my $P = $0;
12 $P =~ s@.*/@@g;
13
14 my $V = '0.32';
15
16 use Getopt::Long qw(:config no_auto_abbrev);
17
18 my $quiet = 0;
19 my $tree = 1;
20 my $chk_signoff = 1;
21 my $chk_patch = 1;
22 my $tst_only;
23 my $emacs = 0;
24 my $terse = 0;
25 my $file = 0;
26 my $check = 0;
27 my $summary = 1;
28 my $mailback = 0;
29 my $summary_file = 0;
30 my $show_types = 0;
31 my $fix = 0;
32 my $fix_inplace = 0;
33 my $root;
34 my %debug;
35 my %camelcase = ();
36 my %use_type = ();
37 my @use = ();
38 my %ignore_type = ();
39 my @ignore = ();
40 my $help = 0;
41 my $configuration_file = ".checkpatch.conf";
42 my $max_line_length = 80;
43 my $ignore_perl_version = 0;
44 my $minimum_perl_version = 5.10.0;
45
46 sub help {
47         my ($exitcode) = @_;
48
49         print << "EOM";
50 Usage: $P [OPTION]... [FILE]...
51 Version: $V
52
53 Options:
54   -q, --quiet                quiet
55   --no-tree                  run without a kernel tree
56   --no-signoff               do not check for 'Signed-off-by' line
57   --patch                    treat FILE as patchfile (default)
58   --emacs                    emacs compile window format
59   --terse                    one line per report
60   -f, --file                 treat FILE as regular source file
61   --subjective, --strict     enable more subjective tests
62   --types TYPE(,TYPE2...)    show only these comma separated message types
63   --ignore TYPE(,TYPE2...)   ignore various comma separated message types
64   --max-line-length=n        set the maximum line length, if exceeded, warn
65   --show-types               show the message "types" in the output
66   --root=PATH                PATH to the kernel tree root
67   --no-summary               suppress the per-file summary
68   --mailback                 only produce a report in case of warnings/errors
69   --summary-file             include the filename in summary
70   --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
71                              'values', 'possible', 'type', and 'attr' (default
72                              is all off)
73   --test-only=WORD           report only warnings/errors containing WORD
74                              literally
75   --fix                      EXPERIMENTAL - may create horrible results
76                              If correctable single-line errors exist, create
77                              "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
78                              with potential errors corrected to the preferred
79                              checkpatch style
80   --fix-inplace              EXPERIMENTAL - may create horrible results
81                              Is the same as --fix, but overwrites the input
82                              file.  It's your fault if there's no backup or git
83   --ignore-perl-version      override checking of perl version.  expect
84                              runtime errors.
85   -h, --help, --version      display this help and exit
86
87 When FILE is - read standard input.
88 EOM
89
90         exit($exitcode);
91 }
92
93 my $conf = which_conf($configuration_file);
94 if (-f $conf) {
95         my @conf_args;
96         open(my $conffile, '<', "$conf")
97             or warn "$P: Can't find a readable $configuration_file file $!\n";
98
99         while (<$conffile>) {
100                 my $line = $_;
101
102                 $line =~ s/\s*\n?$//g;
103                 $line =~ s/^\s*//g;
104                 $line =~ s/\s+/ /g;
105
106                 next if ($line =~ m/^\s*#/);
107                 next if ($line =~ m/^\s*$/);
108
109                 my @words = split(" ", $line);
110                 foreach my $word (@words) {
111                         last if ($word =~ m/^#/);
112                         push (@conf_args, $word);
113                 }
114         }
115         close($conffile);
116         unshift(@ARGV, @conf_args) if @conf_args;
117 }
118
119 GetOptions(
120         'q|quiet+'      => \$quiet,
121         'tree!'         => \$tree,
122         'signoff!'      => \$chk_signoff,
123         'patch!'        => \$chk_patch,
124         'emacs!'        => \$emacs,
125         'terse!'        => \$terse,
126         'f|file!'       => \$file,
127         'subjective!'   => \$check,
128         'strict!'       => \$check,
129         'ignore=s'      => \@ignore,
130         'types=s'       => \@use,
131         'show-types!'   => \$show_types,
132         'max-line-length=i' => \$max_line_length,
133         'root=s'        => \$root,
134         'summary!'      => \$summary,
135         'mailback!'     => \$mailback,
136         'summary-file!' => \$summary_file,
137         'fix!'          => \$fix,
138         'fix-inplace!'  => \$fix_inplace,
139         'ignore-perl-version!' => \$ignore_perl_version,
140         'debug=s'       => \%debug,
141         'test-only=s'   => \$tst_only,
142         'h|help'        => \$help,
143         'version'       => \$help
144 ) or help(1);
145
146 help(0) if ($help);
147
148 $fix = 1 if ($fix_inplace);
149
150 my $exit = 0;
151
152 if ($^V && $^V lt $minimum_perl_version) {
153         printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
154         if (!$ignore_perl_version) {
155                 exit(1);
156         }
157 }
158
159 if ($#ARGV < 0) {
160         print "$P: no input files\n";
161         exit(1);
162 }
163
164 sub hash_save_array_words {
165         my ($hashRef, $arrayRef) = @_;
166
167         my @array = split(/,/, join(',', @$arrayRef));
168         foreach my $word (@array) {
169                 $word =~ s/\s*\n?$//g;
170                 $word =~ s/^\s*//g;
171                 $word =~ s/\s+/ /g;
172                 $word =~ tr/[a-z]/[A-Z]/;
173
174                 next if ($word =~ m/^\s*#/);
175                 next if ($word =~ m/^\s*$/);
176
177                 $hashRef->{$word}++;
178         }
179 }
180
181 sub hash_show_words {
182         my ($hashRef, $prefix) = @_;
183
184         if ($quiet == 0 && keys %$hashRef) {
185                 print "NOTE: $prefix message types:";
186                 foreach my $word (sort keys %$hashRef) {
187                         print " $word";
188                 }
189                 print "\n\n";
190         }
191 }
192
193 hash_save_array_words(\%ignore_type, \@ignore);
194 hash_save_array_words(\%use_type, \@use);
195
196 my $dbg_values = 0;
197 my $dbg_possible = 0;
198 my $dbg_type = 0;
199 my $dbg_attr = 0;
200 for my $key (keys %debug) {
201         ## no critic
202         eval "\${dbg_$key} = '$debug{$key}';";
203         die "$@" if ($@);
204 }
205
206 my $rpt_cleaners = 0;
207
208 if ($terse) {
209         $emacs = 1;
210         $quiet++;
211 }
212
213 if ($tree) {
214         if (defined $root) {
215                 if (!top_of_kernel_tree($root)) {
216                         die "$P: $root: --root does not point at a valid tree\n";
217                 }
218         } else {
219                 if (top_of_kernel_tree('.')) {
220                         $root = '.';
221                 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
222                                                 top_of_kernel_tree($1)) {
223                         $root = $1;
224                 }
225         }
226
227         if (!defined $root) {
228                 print "Must be run from the top-level dir. of a kernel tree\n";
229                 exit(2);
230         }
231 }
232
233 my $emitted_corrupt = 0;
234
235 our $Ident      = qr{
236                         [A-Za-z_][A-Za-z\d_]*
237                         (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
238                 }x;
239 our $Storage    = qr{extern|static|asmlinkage};
240 our $Sparse     = qr{
241                         __user|
242                         __kernel|
243                         __force|
244                         __iomem|
245                         __must_check|
246                         __init_refok|
247                         __kprobes|
248                         __ref|
249                         __rcu
250                 }x;
251 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
252 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
253 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
254 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
255 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
256
257 # Notes to $Attribute:
258 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
259 our $Attribute  = qr{
260                         const|
261                         __percpu|
262                         __nocast|
263                         __safe|
264                         __bitwise__|
265                         __packed__|
266                         __packed2__|
267                         __naked|
268                         __maybe_unused|
269                         __always_unused|
270                         __noreturn|
271                         __used|
272                         __cold|
273                         __noclone|
274                         __deprecated|
275                         __read_mostly|
276                         __kprobes|
277                         $InitAttribute|
278                         ____cacheline_aligned|
279                         ____cacheline_aligned_in_smp|
280                         ____cacheline_internodealigned_in_smp|
281                         __weak
282                   }x;
283 our $Modifier;
284 our $Inline     = qr{inline|__always_inline|noinline};
285 our $Member     = qr{->$Ident|\.$Ident|\[[^]]*\]};
286 our $Lval       = qr{$Ident(?:$Member)*};
287
288 our $Int_type   = qr{(?i)llu|ull|ll|lu|ul|l|u};
289 our $Binary     = qr{(?i)0b[01]+$Int_type?};
290 our $Hex        = qr{(?i)0x[0-9a-f]+$Int_type?};
291 our $Int        = qr{[0-9]+$Int_type?};
292 our $Float_hex  = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
293 our $Float_dec  = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
294 our $Float_int  = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
295 our $Float      = qr{$Float_hex|$Float_dec|$Float_int};
296 our $Constant   = qr{$Float|$Binary|$Hex|$Int};
297 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
298 our $Compare    = qr{<=|>=|==|!=|<|>};
299 our $Arithmetic = qr{\+|-|\*|\/|%};
300 our $Operators  = qr{
301                         <=|>=|==|!=|
302                         =>|->|<<|>>|<|>|!|~|
303                         &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
304                   }x;
305
306 our $NonptrType;
307 our $NonptrTypeWithAttr;
308 our $Type;
309 our $Declare;
310
311 our $NON_ASCII_UTF8     = qr{
312         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
313         |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
314         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
315         |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
316         |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
317         | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
318         |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
319 }x;
320
321 our $UTF8       = qr{
322         [\x09\x0A\x0D\x20-\x7E]              # ASCII
323         | $NON_ASCII_UTF8
324 }x;
325
326 our $typeTypedefs = qr{(?x:
327         (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
328         atomic_t
329 )};
330
331 our $logFunctions = qr{(?x:
332         printk(?:_ratelimited|_once|)|
333         (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
334         WARN(?:_RATELIMIT|_ONCE|)|
335         panic|
336         MODULE_[A-Z_]+|
337         seq_vprintf|seq_printf|seq_puts
338 )};
339
340 our $signature_tags = qr{(?xi:
341         Signed-off-by:|
342         Acked-by:|
343         Tested-by:|
344         Reviewed-by:|
345         Reported-by:|
346         Suggested-by:|
347         To:|
348         Cc:
349 )};
350
351 our @typeList = (
352         qr{void},
353         qr{(?:unsigned\s+)?char},
354         qr{(?:unsigned\s+)?short},
355         qr{(?:unsigned\s+)?int},
356         qr{(?:unsigned\s+)?long},
357         qr{(?:unsigned\s+)?long\s+int},
358         qr{(?:unsigned\s+)?long\s+long},
359         qr{(?:unsigned\s+)?long\s+long\s+int},
360         qr{unsigned},
361         qr{float},
362         qr{double},
363         qr{bool},
364         qr{struct\s+$Ident},
365         qr{union\s+$Ident},
366         qr{enum\s+$Ident},
367         qr{${Ident}_t},
368         qr{${Ident}_handler},
369         qr{${Ident}_handler_fn},
370 );
371 our @typeListWithAttr = (
372         @typeList,
373         qr{struct\s+$InitAttribute\s+$Ident},
374         qr{union\s+$InitAttribute\s+$Ident},
375 );
376
377 our @modifierList = (
378         qr{fastcall},
379 );
380
381 our $allowed_asm_includes = qr{(?x:
382         irq|
383         memory
384 )};
385 # memory.h: ARM has a custom one
386
387 sub build_types {
388         my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
389         my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
390         my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
391         $Modifier       = qr{(?:$Attribute|$Sparse|$mods)};
392         $NonptrType     = qr{
393                         (?:$Modifier\s+|const\s+)*
394                         (?:
395                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
396                                 (?:$typeTypedefs\b)|
397                                 (?:${all}\b)
398                         )
399                         (?:\s+$Modifier|\s+const)*
400                   }x;
401         $NonptrTypeWithAttr     = qr{
402                         (?:$Modifier\s+|const\s+)*
403                         (?:
404                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
405                                 (?:$typeTypedefs\b)|
406                                 (?:${allWithAttr}\b)
407                         )
408                         (?:\s+$Modifier|\s+const)*
409                   }x;
410         $Type   = qr{
411                         $NonptrType
412                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*|\[\])+|(?:\s*\[\s*\])+)?
413                         (?:\s+$Inline|\s+$Modifier)*
414                   }x;
415         $Declare        = qr{(?:$Storage\s+)?$Type};
416 }
417 build_types();
418
419 our $Typecast   = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
420
421 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
422 # requires at least perl version v5.10.0
423 # Any use must be runtime checked with $^V
424
425 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
426 our $LvalOrFunc = qr{($Lval)\s*($balanced_parens{0,1})\s*};
427 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
428
429 sub deparenthesize {
430         my ($string) = @_;
431         return "" if (!defined($string));
432         $string =~ s@^\s*\(\s*@@g;
433         $string =~ s@\s*\)\s*$@@g;
434         $string =~ s@\s+@ @g;
435         return $string;
436 }
437
438 sub seed_camelcase_file {
439         my ($file) = @_;
440
441         return if (!(-f $file));
442
443         local $/;
444
445         open(my $include_file, '<', "$file")
446             or warn "$P: Can't read '$file' $!\n";
447         my $text = <$include_file>;
448         close($include_file);
449
450         my @lines = split('\n', $text);
451
452         foreach my $line (@lines) {
453                 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
454                 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
455                         $camelcase{$1} = 1;
456                 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
457                         $camelcase{$1} = 1;
458                 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
459                         $camelcase{$1} = 1;
460                 }
461         }
462 }
463
464 my $camelcase_seeded = 0;
465 sub seed_camelcase_includes {
466         return if ($camelcase_seeded);
467
468         my $files;
469         my $camelcase_cache = "";
470         my @include_files = ();
471
472         $camelcase_seeded = 1;
473
474         if (-d ".git") {
475                 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
476                 chomp $git_last_include_commit;
477                 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
478         } else {
479                 my $last_mod_date = 0;
480                 $files = `find $root/include -name "*.h"`;
481                 @include_files = split('\n', $files);
482                 foreach my $file (@include_files) {
483                         my $date = POSIX::strftime("%Y%m%d%H%M",
484                                                    localtime((stat $file)[9]));
485                         $last_mod_date = $date if ($last_mod_date < $date);
486                 }
487                 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
488         }
489
490         if ($camelcase_cache ne "" && -f $camelcase_cache) {
491                 open(my $camelcase_file, '<', "$camelcase_cache")
492                     or warn "$P: Can't read '$camelcase_cache' $!\n";
493                 while (<$camelcase_file>) {
494                         chomp;
495                         $camelcase{$_} = 1;
496                 }
497                 close($camelcase_file);
498
499                 return;
500         }
501
502         if (-d ".git") {
503                 $files = `git ls-files "include/*.h"`;
504                 @include_files = split('\n', $files);
505         }
506
507         foreach my $file (@include_files) {
508                 seed_camelcase_file($file);
509         }
510
511         if ($camelcase_cache ne "") {
512                 unlink glob ".checkpatch-camelcase.*";
513                 open(my $camelcase_file, '>', "$camelcase_cache")
514                     or warn "$P: Can't write '$camelcase_cache' $!\n";
515                 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
516                         print $camelcase_file ("$_\n");
517                 }
518                 close($camelcase_file);
519         }
520 }
521
522 $chk_signoff = 0 if ($file);
523
524 my @rawlines = ();
525 my @lines = ();
526 my @fixed = ();
527 my $vname;
528 for my $filename (@ARGV) {
529         my $FILE;
530         if ($file) {
531                 open($FILE, '-|', "diff -u /dev/null $filename") ||
532                         die "$P: $filename: diff failed - $!\n";
533         } elsif ($filename eq '-') {
534                 open($FILE, '<&STDIN');
535         } else {
536                 open($FILE, '<', "$filename") ||
537                         die "$P: $filename: open failed - $!\n";
538         }
539         if ($filename eq '-') {
540                 $vname = 'Your patch';
541         } else {
542                 $vname = $filename;
543         }
544         while (<$FILE>) {
545                 chomp;
546                 push(@rawlines, $_);
547         }
548         close($FILE);
549         if (!process($filename)) {
550                 $exit = 1;
551         }
552         @rawlines = ();
553         @lines = ();
554         @fixed = ();
555 }
556
557 exit($exit);
558
559 sub top_of_kernel_tree {
560         my ($root) = @_;
561
562         my @tree_check = (
563                 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
564                 "README", "Documentation", "arch", "include", "drivers",
565                 "fs", "init", "ipc", "kernel", "lib", "scripts",
566         );
567
568         foreach my $check (@tree_check) {
569                 if (! -e $root . '/' . $check) {
570                         return 0;
571                 }
572         }
573         return 1;
574 }
575
576 sub parse_email {
577         my ($formatted_email) = @_;
578
579         my $name = "";
580         my $address = "";
581         my $comment = "";
582
583         if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
584                 $name = $1;
585                 $address = $2;
586                 $comment = $3 if defined $3;
587         } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
588                 $address = $1;
589                 $comment = $2 if defined $2;
590         } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
591                 $address = $1;
592                 $comment = $2 if defined $2;
593                 $formatted_email =~ s/$address.*$//;
594                 $name = $formatted_email;
595                 $name = trim($name);
596                 $name =~ s/^\"|\"$//g;
597                 # If there's a name left after stripping spaces and
598                 # leading quotes, and the address doesn't have both
599                 # leading and trailing angle brackets, the address
600                 # is invalid. ie:
601                 #   "joe smith joe@smith.com" bad
602                 #   "joe smith <joe@smith.com" bad
603                 if ($name ne "" && $address !~ /^<[^>]+>$/) {
604                         $name = "";
605                         $address = "";
606                         $comment = "";
607                 }
608         }
609
610         $name = trim($name);
611         $name =~ s/^\"|\"$//g;
612         $address = trim($address);
613         $address =~ s/^\<|\>$//g;
614
615         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
616                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
617                 $name = "\"$name\"";
618         }
619
620         return ($name, $address, $comment);
621 }
622
623 sub format_email {
624         my ($name, $address) = @_;
625
626         my $formatted_email;
627
628         $name = trim($name);
629         $name =~ s/^\"|\"$//g;
630         $address = trim($address);
631
632         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
633                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
634                 $name = "\"$name\"";
635         }
636
637         if ("$name" eq "") {
638                 $formatted_email = "$address";
639         } else {
640                 $formatted_email = "$name <$address>";
641         }
642
643         return $formatted_email;
644 }
645
646 sub which_conf {
647         my ($conf) = @_;
648
649         foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
650                 if (-e "$path/$conf") {
651                         return "$path/$conf";
652                 }
653         }
654
655         return "";
656 }
657
658 sub expand_tabs {
659         my ($str) = @_;
660
661         my $res = '';
662         my $n = 0;
663         for my $c (split(//, $str)) {
664                 if ($c eq "\t") {
665                         $res .= ' ';
666                         $n++;
667                         for (; ($n % 8) != 0; $n++) {
668                                 $res .= ' ';
669                         }
670                         next;
671                 }
672                 $res .= $c;
673                 $n++;
674         }
675
676         return $res;
677 }
678 sub copy_spacing {
679         (my $res = shift) =~ tr/\t/ /c;
680         return $res;
681 }
682
683 sub line_stats {
684         my ($line) = @_;
685
686         # Drop the diff line leader and expand tabs
687         $line =~ s/^.//;
688         $line = expand_tabs($line);
689
690         # Pick the indent from the front of the line.
691         my ($white) = ($line =~ /^(\s*)/);
692
693         return (length($line), length($white));
694 }
695
696 my $sanitise_quote = '';
697
698 sub sanitise_line_reset {
699         my ($in_comment) = @_;
700
701         if ($in_comment) {
702                 $sanitise_quote = '*/';
703         } else {
704                 $sanitise_quote = '';
705         }
706 }
707 sub sanitise_line {
708         my ($line) = @_;
709
710         my $res = '';
711         my $l = '';
712
713         my $qlen = 0;
714         my $off = 0;
715         my $c;
716
717         # Always copy over the diff marker.
718         $res = substr($line, 0, 1);
719
720         for ($off = 1; $off < length($line); $off++) {
721                 $c = substr($line, $off, 1);
722
723                 # Comments we are wacking completly including the begin
724                 # and end, all to $;.
725                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
726                         $sanitise_quote = '*/';
727
728                         substr($res, $off, 2, "$;$;");
729                         $off++;
730                         next;
731                 }
732                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
733                         $sanitise_quote = '';
734                         substr($res, $off, 2, "$;$;");
735                         $off++;
736                         next;
737                 }
738                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
739                         $sanitise_quote = '//';
740
741                         substr($res, $off, 2, $sanitise_quote);
742                         $off++;
743                         next;
744                 }
745
746                 # A \ in a string means ignore the next character.
747                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
748                     $c eq "\\") {
749                         substr($res, $off, 2, 'XX');
750                         $off++;
751                         next;
752                 }
753                 # Regular quotes.
754                 if ($c eq "'" || $c eq '"') {
755                         if ($sanitise_quote eq '') {
756                                 $sanitise_quote = $c;
757
758                                 substr($res, $off, 1, $c);
759                                 next;
760                         } elsif ($sanitise_quote eq $c) {
761                                 $sanitise_quote = '';
762                         }
763                 }
764
765                 #print "c<$c> SQ<$sanitise_quote>\n";
766                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
767                         substr($res, $off, 1, $;);
768                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
769                         substr($res, $off, 1, $;);
770                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
771                         substr($res, $off, 1, 'X');
772                 } else {
773                         substr($res, $off, 1, $c);
774                 }
775         }
776
777         if ($sanitise_quote eq '//') {
778                 $sanitise_quote = '';
779         }
780
781         # The pathname on a #include may be surrounded by '<' and '>'.
782         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
783                 my $clean = 'X' x length($1);
784                 $res =~ s@\<.*\>@<$clean>@;
785
786         # The whole of a #error is a string.
787         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
788                 my $clean = 'X' x length($1);
789                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
790         }
791
792         return $res;
793 }
794
795 sub get_quoted_string {
796         my ($line, $rawline) = @_;
797
798         return "" if ($line !~ m/(\"[X]+\")/g);
799         return substr($rawline, $-[0], $+[0] - $-[0]);
800 }
801
802 sub ctx_statement_block {
803         my ($linenr, $remain, $off) = @_;
804         my $line = $linenr - 1;
805         my $blk = '';
806         my $soff = $off;
807         my $coff = $off - 1;
808         my $coff_set = 0;
809
810         my $loff = 0;
811
812         my $type = '';
813         my $level = 0;
814         my @stack = ();
815         my $p;
816         my $c;
817         my $len = 0;
818
819         my $remainder;
820         while (1) {
821                 @stack = (['', 0]) if ($#stack == -1);
822
823                 #warn "CSB: blk<$blk> remain<$remain>\n";
824                 # If we are about to drop off the end, pull in more
825                 # context.
826                 if ($off >= $len) {
827                         for (; $remain > 0; $line++) {
828                                 last if (!defined $lines[$line]);
829                                 next if ($lines[$line] =~ /^-/);
830                                 $remain--;
831                                 $loff = $len;
832                                 $blk .= $lines[$line] . "\n";
833                                 $len = length($blk);
834                                 $line++;
835                                 last;
836                         }
837                         # Bail if there is no further context.
838                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
839                         if ($off >= $len) {
840                                 last;
841                         }
842                         if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
843                                 $level++;
844                                 $type = '#';
845                         }
846                 }
847                 $p = $c;
848                 $c = substr($blk, $off, 1);
849                 $remainder = substr($blk, $off);
850
851                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
852
853                 # Handle nested #if/#else.
854                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
855                         push(@stack, [ $type, $level ]);
856                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
857                         ($type, $level) = @{$stack[$#stack - 1]};
858                 } elsif ($remainder =~ /^#\s*endif\b/) {
859                         ($type, $level) = @{pop(@stack)};
860                 }
861
862                 # Statement ends at the ';' or a close '}' at the
863                 # outermost level.
864                 if ($level == 0 && $c eq ';') {
865                         last;
866                 }
867
868                 # An else is really a conditional as long as its not else if
869                 if ($level == 0 && $coff_set == 0 &&
870                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
871                                 $remainder =~ /^(else)(?:\s|{)/ &&
872                                 $remainder !~ /^else\s+if\b/) {
873                         $coff = $off + length($1) - 1;
874                         $coff_set = 1;
875                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
876                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
877                 }
878
879                 if (($type eq '' || $type eq '(') && $c eq '(') {
880                         $level++;
881                         $type = '(';
882                 }
883                 if ($type eq '(' && $c eq ')') {
884                         $level--;
885                         $type = ($level != 0)? '(' : '';
886
887                         if ($level == 0 && $coff < $soff) {
888                                 $coff = $off;
889                                 $coff_set = 1;
890                                 #warn "CSB: mark coff<$coff>\n";
891                         }
892                 }
893                 if (($type eq '' || $type eq '{') && $c eq '{') {
894                         $level++;
895                         $type = '{';
896                 }
897                 if ($type eq '{' && $c eq '}') {
898                         $level--;
899                         $type = ($level != 0)? '{' : '';
900
901                         if ($level == 0) {
902                                 if (substr($blk, $off + 1, 1) eq ';') {
903                                         $off++;
904                                 }
905                                 last;
906                         }
907                 }
908                 # Preprocessor commands end at the newline unless escaped.
909                 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
910                         $level--;
911                         $type = '';
912                         $off++;
913                         last;
914                 }
915                 $off++;
916         }
917         # We are truly at the end, so shuffle to the next line.
918         if ($off == $len) {
919                 $loff = $len + 1;
920                 $line++;
921                 $remain--;
922         }
923
924         my $statement = substr($blk, $soff, $off - $soff + 1);
925         my $condition = substr($blk, $soff, $coff - $soff + 1);
926
927         #warn "STATEMENT<$statement>\n";
928         #warn "CONDITION<$condition>\n";
929
930         #print "coff<$coff> soff<$off> loff<$loff>\n";
931
932         return ($statement, $condition,
933                         $line, $remain + 1, $off - $loff + 1, $level);
934 }
935
936 sub statement_lines {
937         my ($stmt) = @_;
938
939         # Strip the diff line prefixes and rip blank lines at start and end.
940         $stmt =~ s/(^|\n)./$1/g;
941         $stmt =~ s/^\s*//;
942         $stmt =~ s/\s*$//;
943
944         my @stmt_lines = ($stmt =~ /\n/g);
945
946         return $#stmt_lines + 2;
947 }
948
949 sub statement_rawlines {
950         my ($stmt) = @_;
951
952         my @stmt_lines = ($stmt =~ /\n/g);
953
954         return $#stmt_lines + 2;
955 }
956
957 sub statement_block_size {
958         my ($stmt) = @_;
959
960         $stmt =~ s/(^|\n)./$1/g;
961         $stmt =~ s/^\s*{//;
962         $stmt =~ s/}\s*$//;
963         $stmt =~ s/^\s*//;
964         $stmt =~ s/\s*$//;
965
966         my @stmt_lines = ($stmt =~ /\n/g);
967         my @stmt_statements = ($stmt =~ /;/g);
968
969         my $stmt_lines = $#stmt_lines + 2;
970         my $stmt_statements = $#stmt_statements + 1;
971
972         if ($stmt_lines > $stmt_statements) {
973                 return $stmt_lines;
974         } else {
975                 return $stmt_statements;
976         }
977 }
978
979 sub ctx_statement_full {
980         my ($linenr, $remain, $off) = @_;
981         my ($statement, $condition, $level);
982
983         my (@chunks);
984
985         # Grab the first conditional/block pair.
986         ($statement, $condition, $linenr, $remain, $off, $level) =
987                                 ctx_statement_block($linenr, $remain, $off);
988         #print "F: c<$condition> s<$statement> remain<$remain>\n";
989         push(@chunks, [ $condition, $statement ]);
990         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
991                 return ($level, $linenr, @chunks);
992         }
993
994         # Pull in the following conditional/block pairs and see if they
995         # could continue the statement.
996         for (;;) {
997                 ($statement, $condition, $linenr, $remain, $off, $level) =
998                                 ctx_statement_block($linenr, $remain, $off);
999                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1000                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1001                 #print "C: push\n";
1002                 push(@chunks, [ $condition, $statement ]);
1003         }
1004
1005         return ($level, $linenr, @chunks);
1006 }
1007
1008 sub ctx_block_get {
1009         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1010         my $line;
1011         my $start = $linenr - 1;
1012         my $blk = '';
1013         my @o;
1014         my @c;
1015         my @res = ();
1016
1017         my $level = 0;
1018         my @stack = ($level);
1019         for ($line = $start; $remain > 0; $line++) {
1020                 next if ($rawlines[$line] =~ /^-/);
1021                 $remain--;
1022
1023                 $blk .= $rawlines[$line];
1024
1025                 # Handle nested #if/#else.
1026                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1027                         push(@stack, $level);
1028                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1029                         $level = $stack[$#stack - 1];
1030                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1031                         $level = pop(@stack);
1032                 }
1033
1034                 foreach my $c (split(//, $lines[$line])) {
1035                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
1036                         if ($off > 0) {
1037                                 $off--;
1038                                 next;
1039                         }
1040
1041                         if ($c eq $close && $level > 0) {
1042                                 $level--;
1043                                 last if ($level == 0);
1044                         } elsif ($c eq $open) {
1045                                 $level++;
1046                         }
1047                 }
1048
1049                 if (!$outer || $level <= 1) {
1050                         push(@res, $rawlines[$line]);
1051                 }
1052
1053                 last if ($level == 0);
1054         }
1055
1056         return ($level, @res);
1057 }
1058 sub ctx_block_outer {
1059         my ($linenr, $remain) = @_;
1060
1061         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1062         return @r;
1063 }
1064 sub ctx_block {
1065         my ($linenr, $remain) = @_;
1066
1067         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1068         return @r;
1069 }
1070 sub ctx_statement {
1071         my ($linenr, $remain, $off) = @_;
1072
1073         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1074         return @r;
1075 }
1076 sub ctx_block_level {
1077         my ($linenr, $remain) = @_;
1078
1079         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1080 }
1081 sub ctx_statement_level {
1082         my ($linenr, $remain, $off) = @_;
1083
1084         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1085 }
1086
1087 sub ctx_locate_comment {
1088         my ($first_line, $end_line) = @_;
1089
1090         # Catch a comment on the end of the line itself.
1091         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1092         return $current_comment if (defined $current_comment);
1093
1094         # Look through the context and try and figure out if there is a
1095         # comment.
1096         my $in_comment = 0;
1097         $current_comment = '';
1098         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1099                 my $line = $rawlines[$linenr - 1];
1100                 #warn "           $line\n";
1101                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1102                         $in_comment = 1;
1103                 }
1104                 if ($line =~ m@/\*@) {
1105                         $in_comment = 1;
1106                 }
1107                 if (!$in_comment && $current_comment ne '') {
1108                         $current_comment = '';
1109                 }
1110                 $current_comment .= $line . "\n" if ($in_comment);
1111                 if ($line =~ m@\*/@) {
1112                         $in_comment = 0;
1113                 }
1114         }
1115
1116         chomp($current_comment);
1117         return($current_comment);
1118 }
1119 sub ctx_has_comment {
1120         my ($first_line, $end_line) = @_;
1121         my $cmt = ctx_locate_comment($first_line, $end_line);
1122
1123         ##print "LINE: $rawlines[$end_line - 1 ]\n";
1124         ##print "CMMT: $cmt\n";
1125
1126         return ($cmt ne '');
1127 }
1128
1129 sub raw_line {
1130         my ($linenr, $cnt) = @_;
1131
1132         my $offset = $linenr - 1;
1133         $cnt++;
1134
1135         my $line;
1136         while ($cnt) {
1137                 $line = $rawlines[$offset++];
1138                 next if (defined($line) && $line =~ /^-/);
1139                 $cnt--;
1140         }
1141
1142         return $line;
1143 }
1144
1145 sub cat_vet {
1146         my ($vet) = @_;
1147         my ($res, $coded);
1148
1149         $res = '';
1150         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1151                 $res .= $1;
1152                 if ($2 ne '') {
1153                         $coded = sprintf("^%c", unpack('C', $2) + 64);
1154                         $res .= $coded;
1155                 }
1156         }
1157         $res =~ s/$/\$/;
1158
1159         return $res;
1160 }
1161
1162 my $av_preprocessor = 0;
1163 my $av_pending;
1164 my @av_paren_type;
1165 my $av_pend_colon;
1166
1167 sub annotate_reset {
1168         $av_preprocessor = 0;
1169         $av_pending = '_';
1170         @av_paren_type = ('E');
1171         $av_pend_colon = 'O';
1172 }
1173
1174 sub annotate_values {
1175         my ($stream, $type) = @_;
1176
1177         my $res;
1178         my $var = '_' x length($stream);
1179         my $cur = $stream;
1180
1181         print "$stream\n" if ($dbg_values > 1);
1182
1183         while (length($cur)) {
1184                 @av_paren_type = ('E') if ($#av_paren_type < 0);
1185                 print " <" . join('', @av_paren_type) .
1186                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
1187                 if ($cur =~ /^(\s+)/o) {
1188                         print "WS($1)\n" if ($dbg_values > 1);
1189                         if ($1 =~ /\n/ && $av_preprocessor) {
1190                                 $type = pop(@av_paren_type);
1191                                 $av_preprocessor = 0;
1192                         }
1193
1194                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1195                         print "CAST($1)\n" if ($dbg_values > 1);
1196                         push(@av_paren_type, $type);
1197                         $type = 'c';
1198
1199                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1200                         print "DECLARE($1)\n" if ($dbg_values > 1);
1201                         $type = 'T';
1202
1203                 } elsif ($cur =~ /^($Modifier)\s*/) {
1204                         print "MODIFIER($1)\n" if ($dbg_values > 1);
1205                         $type = 'T';
1206
1207                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1208                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1209                         $av_preprocessor = 1;
1210                         push(@av_paren_type, $type);
1211                         if ($2 ne '') {
1212                                 $av_pending = 'N';
1213                         }
1214                         $type = 'E';
1215
1216                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1217                         print "UNDEF($1)\n" if ($dbg_values > 1);
1218                         $av_preprocessor = 1;
1219                         push(@av_paren_type, $type);
1220
1221                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1222                         print "PRE_START($1)\n" if ($dbg_values > 1);
1223                         $av_preprocessor = 1;
1224
1225                         push(@av_paren_type, $type);
1226                         push(@av_paren_type, $type);
1227                         $type = 'E';
1228
1229                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1230                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1231                         $av_preprocessor = 1;
1232
1233                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1234
1235                         $type = 'E';
1236
1237                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1238                         print "PRE_END($1)\n" if ($dbg_values > 1);
1239
1240                         $av_preprocessor = 1;
1241
1242                         # Assume all arms of the conditional end as this
1243                         # one does, and continue as if the #endif was not here.
1244                         pop(@av_paren_type);
1245                         push(@av_paren_type, $type);
1246                         $type = 'E';
1247
1248                 } elsif ($cur =~ /^(\\\n)/o) {
1249                         print "PRECONT($1)\n" if ($dbg_values > 1);
1250
1251                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1252                         print "ATTR($1)\n" if ($dbg_values > 1);
1253                         $av_pending = $type;
1254                         $type = 'N';
1255
1256                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1257                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1258                         if (defined $2) {
1259                                 $av_pending = 'V';
1260                         }
1261                         $type = 'N';
1262
1263                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1264                         print "COND($1)\n" if ($dbg_values > 1);
1265                         $av_pending = 'E';
1266                         $type = 'N';
1267
1268                 } elsif ($cur =~/^(case)/o) {
1269                         print "CASE($1)\n" if ($dbg_values > 1);
1270                         $av_pend_colon = 'C';
1271                         $type = 'N';
1272
1273                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1274                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1275                         $type = 'N';
1276
1277                 } elsif ($cur =~ /^(\()/o) {
1278                         print "PAREN('$1')\n" if ($dbg_values > 1);
1279                         push(@av_paren_type, $av_pending);
1280                         $av_pending = '_';
1281                         $type = 'N';
1282
1283                 } elsif ($cur =~ /^(\))/o) {
1284                         my $new_type = pop(@av_paren_type);
1285                         if ($new_type ne '_') {
1286                                 $type = $new_type;
1287                                 print "PAREN('$1') -> $type\n"
1288                                                         if ($dbg_values > 1);
1289                         } else {
1290                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1291                         }
1292
1293                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1294                         print "FUNC($1)\n" if ($dbg_values > 1);
1295                         $type = 'V';
1296                         $av_pending = 'V';
1297
1298                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1299                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1300                                 $av_pend_colon = 'B';
1301                         } elsif ($type eq 'E') {
1302                                 $av_pend_colon = 'L';
1303                         }
1304                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1305                         $type = 'V';
1306
1307                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1308                         print "IDENT($1)\n" if ($dbg_values > 1);
1309                         $type = 'V';
1310
1311                 } elsif ($cur =~ /^($Assignment)/o) {
1312                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1313                         $type = 'N';
1314
1315                 } elsif ($cur =~/^(;|{|})/) {
1316                         print "END($1)\n" if ($dbg_values > 1);
1317                         $type = 'E';
1318                         $av_pend_colon = 'O';
1319
1320                 } elsif ($cur =~/^(,)/) {
1321                         print "COMMA($1)\n" if ($dbg_values > 1);
1322                         $type = 'C';
1323
1324                 } elsif ($cur =~ /^(\?)/o) {
1325                         print "QUESTION($1)\n" if ($dbg_values > 1);
1326                         $type = 'N';
1327
1328                 } elsif ($cur =~ /^(:)/o) {
1329                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1330
1331                         substr($var, length($res), 1, $av_pend_colon);
1332                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1333                                 $type = 'E';
1334                         } else {
1335                                 $type = 'N';
1336                         }
1337                         $av_pend_colon = 'O';
1338
1339                 } elsif ($cur =~ /^(\[)/o) {
1340                         print "CLOSE($1)\n" if ($dbg_values > 1);
1341                         $type = 'N';
1342
1343                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1344                         my $variant;
1345
1346                         print "OPV($1)\n" if ($dbg_values > 1);
1347                         if ($type eq 'V') {
1348                                 $variant = 'B';
1349                         } else {
1350                                 $variant = 'U';
1351                         }
1352
1353                         substr($var, length($res), 1, $variant);
1354                         $type = 'N';
1355
1356                 } elsif ($cur =~ /^($Operators)/o) {
1357                         print "OP($1)\n" if ($dbg_values > 1);
1358                         if ($1 ne '++' && $1 ne '--') {
1359                                 $type = 'N';
1360                         }
1361
1362                 } elsif ($cur =~ /(^.)/o) {
1363                         print "C($1)\n" if ($dbg_values > 1);
1364                 }
1365                 if (defined $1) {
1366                         $cur = substr($cur, length($1));
1367                         $res .= $type x length($1);
1368                 }
1369         }
1370
1371         return ($res, $var);
1372 }
1373
1374 sub possible {
1375         my ($possible, $line) = @_;
1376         my $notPermitted = qr{(?:
1377                 ^(?:
1378                         $Modifier|
1379                         $Storage|
1380                         $Type|
1381                         DEFINE_\S+
1382                 )$|
1383                 ^(?:
1384                         goto|
1385                         return|
1386                         case|
1387                         else|
1388                         asm|__asm__|
1389                         do|
1390                         \#|
1391                         \#\#|
1392                 )(?:\s|$)|
1393                 ^(?:typedef|struct|enum)\b
1394             )}x;
1395         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1396         if ($possible !~ $notPermitted) {
1397                 # Check for modifiers.
1398                 $possible =~ s/\s*$Storage\s*//g;
1399                 $possible =~ s/\s*$Sparse\s*//g;
1400                 if ($possible =~ /^\s*$/) {
1401
1402                 } elsif ($possible =~ /\s/) {
1403                         $possible =~ s/\s*$Type\s*//g;
1404                         for my $modifier (split(' ', $possible)) {
1405                                 if ($modifier !~ $notPermitted) {
1406                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1407                                         push(@modifierList, $modifier);
1408                                 }
1409                         }
1410
1411                 } else {
1412                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1413                         push(@typeList, $possible);
1414                 }
1415                 build_types();
1416         } else {
1417                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1418         }
1419 }
1420
1421 my $prefix = '';
1422
1423 sub show_type {
1424         return defined $use_type{$_[0]} if (scalar keys %use_type > 0);
1425
1426         return !defined $ignore_type{$_[0]};
1427 }
1428
1429 sub report {
1430         if (!show_type($_[1]) ||
1431             (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1432                 return 0;
1433         }
1434         my $line;
1435         if ($show_types) {
1436                 $line = "$prefix$_[0]:$_[1]: $_[2]\n";
1437         } else {
1438                 $line = "$prefix$_[0]: $_[2]\n";
1439         }
1440         $line = (split('\n', $line))[0] . "\n" if ($terse);
1441
1442         push(our @report, $line);
1443
1444         return 1;
1445 }
1446 sub report_dump {
1447         our @report;
1448 }
1449
1450 sub ERROR {
1451         if (report("ERROR", $_[0], $_[1])) {
1452                 our $clean = 0;
1453                 our $cnt_error++;
1454                 return 1;
1455         }
1456         return 0;
1457 }
1458 sub WARN {
1459         if (report("WARNING", $_[0], $_[1])) {
1460                 our $clean = 0;
1461                 our $cnt_warn++;
1462                 return 1;
1463         }
1464         return 0;
1465 }
1466 sub CHK {
1467         if ($check && report("CHECK", $_[0], $_[1])) {
1468                 our $clean = 0;
1469                 our $cnt_chk++;
1470                 return 1;
1471         }
1472         return 0;
1473 }
1474
1475 sub check_absolute_file {
1476         my ($absolute, $herecurr) = @_;
1477         my $file = $absolute;
1478
1479         ##print "absolute<$absolute>\n";
1480
1481         # See if any suffix of this path is a path within the tree.
1482         while ($file =~ s@^[^/]*/@@) {
1483                 if (-f "$root/$file") {
1484                         ##print "file<$file>\n";
1485                         last;
1486                 }
1487         }
1488         if (! -f _)  {
1489                 return 0;
1490         }
1491
1492         # It is, so see if the prefix is acceptable.
1493         my $prefix = $absolute;
1494         substr($prefix, -length($file)) = '';
1495
1496         ##print "prefix<$prefix>\n";
1497         if ($prefix ne ".../") {
1498                 WARN("USE_RELATIVE_PATH",
1499                      "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1500         }
1501 }
1502
1503 sub trim {
1504         my ($string) = @_;
1505
1506         $string =~ s/^\s+|\s+$//g;
1507
1508         return $string;
1509 }
1510
1511 sub ltrim {
1512         my ($string) = @_;
1513
1514         $string =~ s/^\s+//;
1515
1516         return $string;
1517 }
1518
1519 sub rtrim {
1520         my ($string) = @_;
1521
1522         $string =~ s/\s+$//;
1523
1524         return $string;
1525 }
1526
1527 sub string_find_replace {
1528         my ($string, $find, $replace) = @_;
1529
1530         $string =~ s/$find/$replace/g;
1531
1532         return $string;
1533 }
1534
1535 sub tabify {
1536         my ($leading) = @_;
1537
1538         my $source_indent = 8;
1539         my $max_spaces_before_tab = $source_indent - 1;
1540         my $spaces_to_tab = " " x $source_indent;
1541
1542         #convert leading spaces to tabs
1543         1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1544         #Remove spaces before a tab
1545         1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1546
1547         return "$leading";
1548 }
1549
1550 sub pos_last_openparen {
1551         my ($line) = @_;
1552
1553         my $pos = 0;
1554
1555         my $opens = $line =~ tr/\(/\(/;
1556         my $closes = $line =~ tr/\)/\)/;
1557
1558         my $last_openparen = 0;
1559
1560         if (($opens == 0) || ($closes >= $opens)) {
1561                 return -1;
1562         }
1563
1564         my $len = length($line);
1565
1566         for ($pos = 0; $pos < $len; $pos++) {
1567                 my $string = substr($line, $pos);
1568                 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1569                         $pos += length($1) - 1;
1570                 } elsif (substr($line, $pos, 1) eq '(') {
1571                         $last_openparen = $pos;
1572                 } elsif (index($string, '(') == -1) {
1573                         last;
1574                 }
1575         }
1576
1577         return $last_openparen + 1;
1578 }
1579
1580 sub process {
1581         my $filename = shift;
1582
1583         my $linenr=0;
1584         my $prevline="";
1585         my $prevrawline="";
1586         my $stashline="";
1587         my $stashrawline="";
1588
1589         my $length;
1590         my $indent;
1591         my $previndent=0;
1592         my $stashindent=0;
1593
1594         our $clean = 1;
1595         my $signoff = 0;
1596         my $is_patch = 0;
1597
1598         my $in_header_lines = 1;
1599         my $in_commit_log = 0;          #Scanning lines before patch
1600
1601         my $non_utf8_charset = 0;
1602
1603         our @report = ();
1604         our $cnt_lines = 0;
1605         our $cnt_error = 0;
1606         our $cnt_warn = 0;
1607         our $cnt_chk = 0;
1608
1609         # Trace the real file/line as we go.
1610         my $realfile = '';
1611         my $realline = 0;
1612         my $realcnt = 0;
1613         my $here = '';
1614         my $in_comment = 0;
1615         my $comment_edge = 0;
1616         my $first_line = 0;
1617         my $p1_prefix = '';
1618
1619         my $prev_values = 'E';
1620
1621         # suppression flags
1622         my %suppress_ifbraces;
1623         my %suppress_whiletrailers;
1624         my %suppress_export;
1625         my $suppress_statement = 0;
1626
1627         my %signatures = ();
1628
1629         # Pre-scan the patch sanitizing the lines.
1630         # Pre-scan the patch looking for any __setup documentation.
1631         #
1632         my @setup_docs = ();
1633         my $setup_docs = 0;
1634
1635         my $camelcase_file_seeded = 0;
1636
1637         sanitise_line_reset();
1638         my $line;
1639         foreach my $rawline (@rawlines) {
1640                 $linenr++;
1641                 $line = $rawline;
1642
1643                 push(@fixed, $rawline) if ($fix);
1644
1645                 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1646                         $setup_docs = 0;
1647                         if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1648                                 $setup_docs = 1;
1649                         }
1650                         #next;
1651                 }
1652                 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1653                         $realline=$1-1;
1654                         if (defined $2) {
1655                                 $realcnt=$3+1;
1656                         } else {
1657                                 $realcnt=1+1;
1658                         }
1659                         $in_comment = 0;
1660
1661                         # Guestimate if this is a continuing comment.  Run
1662                         # the context looking for a comment "edge".  If this
1663                         # edge is a close comment then we must be in a comment
1664                         # at context start.
1665                         my $edge;
1666                         my $cnt = $realcnt;
1667                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1668                                 next if (defined $rawlines[$ln - 1] &&
1669                                          $rawlines[$ln - 1] =~ /^-/);
1670                                 $cnt--;
1671                                 #print "RAW<$rawlines[$ln - 1]>\n";
1672                                 last if (!defined $rawlines[$ln - 1]);
1673                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1674                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1675                                         ($edge) = $1;
1676                                         last;
1677                                 }
1678                         }
1679                         if (defined $edge && $edge eq '*/') {
1680                                 $in_comment = 1;
1681                         }
1682
1683                         # Guestimate if this is a continuing comment.  If this
1684                         # is the start of a diff block and this line starts
1685                         # ' *' then it is very likely a comment.
1686                         if (!defined $edge &&
1687                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1688                         {
1689                                 $in_comment = 1;
1690                         }
1691
1692                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1693                         sanitise_line_reset($in_comment);
1694
1695                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1696                         # Standardise the strings and chars within the input to
1697                         # simplify matching -- only bother with positive lines.
1698                         $line = sanitise_line($rawline);
1699                 }
1700                 push(@lines, $line);
1701
1702                 if ($realcnt > 1) {
1703                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
1704                 } else {
1705                         $realcnt = 0;
1706                 }
1707
1708                 #print "==>$rawline\n";
1709                 #print "-->$line\n";
1710
1711                 if ($setup_docs && $line =~ /^\+/) {
1712                         push(@setup_docs, $line);
1713                 }
1714         }
1715
1716         $prefix = '';
1717
1718         $realcnt = 0;
1719         $linenr = 0;
1720         foreach my $line (@lines) {
1721                 $linenr++;
1722                 my $sline = $line;      #copy of $line
1723                 $sline =~ s/$;/ /g;     #with comments as spaces
1724
1725                 my $rawline = $rawlines[$linenr - 1];
1726
1727 #extract the line range in the file after the patch is applied
1728                 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1729                         $is_patch = 1;
1730                         $first_line = $linenr + 1;
1731                         $realline=$1-1;
1732                         if (defined $2) {
1733                                 $realcnt=$3+1;
1734                         } else {
1735                                 $realcnt=1+1;
1736                         }
1737                         annotate_reset();
1738                         $prev_values = 'E';
1739
1740                         %suppress_ifbraces = ();
1741                         %suppress_whiletrailers = ();
1742                         %suppress_export = ();
1743                         $suppress_statement = 0;
1744                         next;
1745
1746 # track the line number as we move through the hunk, note that
1747 # new versions of GNU diff omit the leading space on completely
1748 # blank context lines so we need to count that too.
1749                 } elsif ($line =~ /^( |\+|$)/) {
1750                         $realline++;
1751                         $realcnt-- if ($realcnt != 0);
1752
1753                         # Measure the line length and indent.
1754                         ($length, $indent) = line_stats($rawline);
1755
1756                         # Track the previous line.
1757                         ($prevline, $stashline) = ($stashline, $line);
1758                         ($previndent, $stashindent) = ($stashindent, $indent);
1759                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1760
1761                         #warn "line<$line>\n";
1762
1763                 } elsif ($realcnt == 1) {
1764                         $realcnt--;
1765                 }
1766
1767                 my $hunk_line = ($realcnt != 0);
1768
1769 #make up the handle for any error we report on this line
1770                 $prefix = "$filename:$realline: " if ($emacs && $file);
1771                 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1772
1773                 $here = "#$linenr: " if (!$file);
1774                 $here = "#$realline: " if ($file);
1775
1776                 # extract the filename as it passes
1777                 if ($line =~ /^diff --git.*?(\S+)$/) {
1778                         $realfile = $1;
1779                         $realfile =~ s@^([^/]*)/@@ if (!$file);
1780                         $in_commit_log = 0;
1781                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1782                         $realfile = $1;
1783                         $realfile =~ s@^([^/]*)/@@ if (!$file);
1784                         $in_commit_log = 0;
1785
1786                         $p1_prefix = $1;
1787                         if (!$file && $tree && $p1_prefix ne '' &&
1788                             -e "$root/$p1_prefix") {
1789                                 WARN("PATCH_PREFIX",
1790                                      "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1791                         }
1792
1793                         if ($realfile =~ m@^include/asm/@) {
1794                                 ERROR("MODIFIED_INCLUDE_ASM",
1795                                       "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1796                         }
1797                         next;
1798                 }
1799
1800                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1801
1802                 my $hereline = "$here\n$rawline\n";
1803                 my $herecurr = "$here\n$rawline\n";
1804                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1805
1806                 $cnt_lines++ if ($realcnt != 0);
1807
1808 # Check for incorrect file permissions
1809                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1810                         my $permhere = $here . "FILE: $realfile\n";
1811                         if ($realfile !~ m@scripts/@ &&
1812                             $realfile !~ /\.(py|pl|awk|sh)$/) {
1813                                 ERROR("EXECUTE_PERMISSIONS",
1814                                       "do not set execute permissions for source files\n" . $permhere);
1815                         }
1816                 }
1817
1818 # Check the patch for a signoff:
1819                 if ($line =~ /^\s*signed-off-by:/i) {
1820                         $signoff++;
1821                         $in_commit_log = 0;
1822                 }
1823
1824 # Check signature styles
1825                 if (!$in_header_lines &&
1826                     $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
1827                         my $space_before = $1;
1828                         my $sign_off = $2;
1829                         my $space_after = $3;
1830                         my $email = $4;
1831                         my $ucfirst_sign_off = ucfirst(lc($sign_off));
1832
1833                         if ($sign_off !~ /$signature_tags/) {
1834                                 WARN("BAD_SIGN_OFF",
1835                                      "Non-standard signature: $sign_off\n" . $herecurr);
1836                         }
1837                         if (defined $space_before && $space_before ne "") {
1838                                 if (WARN("BAD_SIGN_OFF",
1839                                          "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
1840                                     $fix) {
1841                                         $fixed[$linenr - 1] =
1842                                             "$ucfirst_sign_off $email";
1843                                 }
1844                         }
1845                         if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1846                                 if (WARN("BAD_SIGN_OFF",
1847                                          "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
1848                                     $fix) {
1849                                         $fixed[$linenr - 1] =
1850                                             "$ucfirst_sign_off $email";
1851                                 }
1852
1853                         }
1854                         if (!defined $space_after || $space_after ne " ") {
1855                                 if (WARN("BAD_SIGN_OFF",
1856                                          "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
1857                                     $fix) {
1858                                         $fixed[$linenr - 1] =
1859                                             "$ucfirst_sign_off $email";
1860                                 }
1861                         }
1862
1863                         my ($email_name, $email_address, $comment) = parse_email($email);
1864                         my $suggested_email = format_email(($email_name, $email_address));
1865                         if ($suggested_email eq "") {
1866                                 ERROR("BAD_SIGN_OFF",
1867                                       "Unrecognized email address: '$email'\n" . $herecurr);
1868                         } else {
1869                                 my $dequoted = $suggested_email;
1870                                 $dequoted =~ s/^"//;
1871                                 $dequoted =~ s/" </ </;
1872                                 # Don't force email to have quotes
1873                                 # Allow just an angle bracketed address
1874                                 if ("$dequoted$comment" ne $email &&
1875                                     "<$email_address>$comment" ne $email &&
1876                                     "$suggested_email$comment" ne $email) {
1877                                         WARN("BAD_SIGN_OFF",
1878                                              "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1879                                 }
1880                         }
1881
1882 # Check for duplicate signatures
1883                         my $sig_nospace = $line;
1884                         $sig_nospace =~ s/\s//g;
1885                         $sig_nospace = lc($sig_nospace);
1886                         if (defined $signatures{$sig_nospace}) {
1887                                 WARN("BAD_SIGN_OFF",
1888                                      "Duplicate signature\n" . $herecurr);
1889                         } else {
1890                                 $signatures{$sig_nospace} = 1;
1891                         }
1892                 }
1893
1894 # Check for wrappage within a valid hunk of the file
1895                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1896                         ERROR("CORRUPTED_PATCH",
1897                               "patch seems to be corrupt (line wrapped?)\n" .
1898                                 $herecurr) if (!$emitted_corrupt++);
1899                 }
1900
1901 # Check for absolute kernel paths.
1902                 if ($tree) {
1903                         while ($line =~ m{(?:^|\s)(/\S*)}g) {
1904                                 my $file = $1;
1905
1906                                 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1907                                     check_absolute_file($1, $herecurr)) {
1908                                         #
1909                                 } else {
1910                                         check_absolute_file($file, $herecurr);
1911                                 }
1912                         }
1913                 }
1914
1915 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1916                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1917                     $rawline !~ m/^$UTF8*$/) {
1918                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1919
1920                         my $blank = copy_spacing($rawline);
1921                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1922                         my $hereptr = "$hereline$ptr\n";
1923
1924                         CHK("INVALID_UTF8",
1925                             "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1926                 }
1927
1928 # Check if it's the start of a commit log
1929 # (not a header line and we haven't seen the patch filename)
1930                 if ($in_header_lines && $realfile =~ /^$/ &&
1931                     $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1932                         $in_header_lines = 0;
1933                         $in_commit_log = 1;
1934                 }
1935
1936 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1937 # declined it, i.e defined some charset where it is missing.
1938                 if ($in_header_lines &&
1939                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1940                     $1 !~ /utf-8/i) {
1941                         $non_utf8_charset = 1;
1942                 }
1943
1944                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1945                     $rawline =~ /$NON_ASCII_UTF8/) {
1946                         WARN("UTF8_BEFORE_PATCH",
1947                             "8-bit UTF-8 used in possible commit log\n" . $herecurr);
1948                 }
1949
1950 # ignore non-hunk lines and lines being removed
1951                 next if (!$hunk_line || $line =~ /^-/);
1952
1953 #trailing whitespace
1954                 if ($line =~ /^\+.*\015/) {
1955                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1956                         if (ERROR("DOS_LINE_ENDINGS",
1957                                   "DOS line endings\n" . $herevet) &&
1958                             $fix) {
1959                                 $fixed[$linenr - 1] =~ s/[\s\015]+$//;
1960                         }
1961                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1962                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1963                         if (ERROR("TRAILING_WHITESPACE",
1964                                   "trailing whitespace\n" . $herevet) &&
1965                             $fix) {
1966                                 $fixed[$linenr - 1] =~ s/\s+$//;
1967                         }
1968
1969                         $rpt_cleaners = 1;
1970                 }
1971
1972 # Check for FSF mailing addresses.
1973                 if ($rawline =~ /You should have received a copy/ ||
1974                     $rawline =~ /write to the Free Software/ ||
1975                     $rawline =~ /59 Temple Place/ ||
1976                     $rawline =~ /51 Franklin Street/) {
1977                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1978                         my $msg_type = \&ERROR;
1979                         $msg_type = \&CHK if ($file);
1980                         &{$msg_type}("FSF_MAILING_ADDRESS",
1981                                 "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)
1982                 }
1983
1984 # check for Kconfig help text having a real description
1985 # Only applies when adding the entry originally, after that we do not have
1986 # sufficient context to determine whether it is indeed long enough.
1987                 if ($realfile =~ /Kconfig/ &&
1988                     $line =~ /.\s*config\s+/) {
1989                         my $length = 0;
1990                         my $cnt = $realcnt;
1991                         my $ln = $linenr + 1;
1992                         my $f;
1993                         my $is_start = 0;
1994                         my $is_end = 0;
1995                         for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
1996                                 $f = $lines[$ln - 1];
1997                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
1998                                 $is_end = $lines[$ln - 1] =~ /^\+/;
1999
2000                                 next if ($f =~ /^-/);
2001
2002                                 if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
2003                                         $is_start = 1;
2004                                 } elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
2005                                         $length = -1;
2006                                 }
2007
2008                                 $f =~ s/^.//;
2009                                 $f =~ s/#.*//;
2010                                 $f =~ s/^\s+//;
2011                                 next if ($f =~ /^$/);
2012                                 if ($f =~ /^\s*config\s/) {
2013                                         $is_end = 1;
2014                                         last;
2015                                 }
2016                                 $length++;
2017                         }
2018                         WARN("CONFIG_DESCRIPTION",
2019                              "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
2020                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2021                 }
2022
2023 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2024                 if ($realfile =~ /Kconfig/ &&
2025                     $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2026                         WARN("CONFIG_EXPERIMENTAL",
2027                              "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2028                 }
2029
2030                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2031                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2032                         my $flag = $1;
2033                         my $replacement = {
2034                                 'EXTRA_AFLAGS' =>   'asflags-y',
2035                                 'EXTRA_CFLAGS' =>   'ccflags-y',
2036                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
2037                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
2038                         };
2039
2040                         WARN("DEPRECATED_VARIABLE",
2041                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2042                 }
2043
2044 # check we are in a valid source file if not then ignore this hunk
2045                 next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
2046
2047 #line length limit
2048                 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2049                     $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2050                     !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2051                     $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2052                     $length > $max_line_length)
2053                 {
2054                         WARN("LONG_LINE",
2055                              "line over $max_line_length characters\n" . $herecurr);
2056                 }
2057
2058 # Check for user-visible strings broken across lines, which breaks the ability
2059 # to grep for the string.  Make exceptions when the previous string ends in a
2060 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
2061 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
2062                 if ($line =~ /^\+\s*"/ &&
2063                     $prevline =~ /"\s*$/ &&
2064                     $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
2065                         WARN("SPLIT_STRING",
2066                              "quoted string split across lines\n" . $hereprev);
2067                 }
2068
2069 # check for spaces before a quoted newline
2070                 if ($rawline =~ /^.*\".*\s\\n/) {
2071                         if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2072                                  "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2073                             $fix) {
2074                                 $fixed[$linenr - 1] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2075                         }
2076
2077                 }
2078
2079 # check for adding lines without a newline.
2080                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2081                         WARN("MISSING_EOF_NEWLINE",
2082                              "adding a line without newline at end of file\n" . $herecurr);
2083                 }
2084
2085 # Blackfin: use hi/lo macros
2086                 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2087                         if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2088                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2089                                 ERROR("LO_MACRO",
2090                                       "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2091                         }
2092                         if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2093                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2094                                 ERROR("HI_MACRO",
2095                                       "use the HI() macro, not (... >> 16)\n" . $herevet);
2096                         }
2097                 }
2098
2099 # check we are in a valid source file C or perl if not then ignore this hunk
2100                 next if ($realfile !~ /\.(h|c|pl)$/);
2101
2102 # at the beginning of a line any tabs must come first and anything
2103 # more than 8 must use tabs.
2104                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2105                     $rawline =~ /^\+\s*        \s*/) {
2106                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2107                         $rpt_cleaners = 1;
2108                         if (ERROR("CODE_INDENT",
2109                                   "code indent should use tabs where possible\n" . $herevet) &&
2110                             $fix) {
2111                                 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2112                         }
2113                 }
2114
2115 # check for space before tabs.
2116                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2117                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2118                         if (WARN("SPACE_BEFORE_TAB",
2119                                 "please, no space before tabs\n" . $herevet) &&
2120                             $fix) {
2121                                 while ($fixed[$linenr - 1] =~
2122                                            s/(^\+.*) {8,8}+\t/$1\t\t/) {}
2123                                 while ($fixed[$linenr - 1] =~
2124                                            s/(^\+.*) +\t/$1\t/) {}
2125                         }
2126                 }
2127
2128 # check for && or || at the start of a line
2129                 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2130                         CHK("LOGICAL_CONTINUATIONS",
2131                             "Logical continuations should be on the previous line\n" . $hereprev);
2132                 }
2133
2134 # check multi-line statement indentation matches previous line
2135                 if ($^V && $^V ge 5.10.0 &&
2136                     $prevline =~ /^\+(\t*)(if \(|$Ident\().*(\&\&|\|\||,)\s*$/) {
2137                         $prevline =~ /^\+(\t*)(.*)$/;
2138                         my $oldindent = $1;
2139                         my $rest = $2;
2140
2141                         my $pos = pos_last_openparen($rest);
2142                         if ($pos >= 0) {
2143                                 $line =~ /^(\+| )([ \t]*)/;
2144                                 my $newindent = $2;
2145
2146                                 my $goodtabindent = $oldindent .
2147                                         "\t" x ($pos / 8) .
2148                                         " "  x ($pos % 8);
2149                                 my $goodspaceindent = $oldindent . " "  x $pos;
2150
2151                                 if ($newindent ne $goodtabindent &&
2152                                     $newindent ne $goodspaceindent) {
2153
2154                                         if (CHK("PARENTHESIS_ALIGNMENT",
2155                                                 "Alignment should match open parenthesis\n" . $hereprev) &&
2156                                             $fix && $line =~ /^\+/) {
2157                                                 $fixed[$linenr - 1] =~
2158                                                     s/^\+[ \t]*/\+$goodtabindent/;
2159                                         }
2160                                 }
2161                         }
2162                 }
2163
2164                 if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) {
2165                         if (CHK("SPACING",
2166                                 "No space is necessary after a cast\n" . $hereprev) &&
2167                             $fix) {
2168                                 $fixed[$linenr - 1] =~
2169                                     s/^(\+.*\*[ \t]*\))[ \t]+/$1/;
2170                         }
2171                 }
2172
2173                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2174                     $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2175                     $rawline =~ /^\+[ \t]*\*/) {
2176                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2177                              "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2178                 }
2179
2180                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2181                     $prevrawline =~ /^\+[ \t]*\/\*/ &&          #starting /*
2182                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
2183                     $rawline =~ /^\+/ &&                        #line is new
2184                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
2185                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2186                              "networking block comments start with * on subsequent lines\n" . $hereprev);
2187                 }
2188
2189                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2190                     $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
2191                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
2192                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
2193                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
2194                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2195                              "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2196                 }
2197
2198 # check for spaces at the beginning of a line.
2199 # Exceptions:
2200 #  1) within comments
2201 #  2) indented preprocessor commands
2202 #  3) hanging labels
2203                 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
2204                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2205                         if (WARN("LEADING_SPACE",
2206                                  "please, no spaces at the start of a line\n" . $herevet) &&
2207                             $fix) {
2208                                 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2209                         }
2210                 }
2211
2212 # check we are in a valid C source file if not then ignore this hunk
2213                 next if ($realfile !~ /\.(h|c)$/);
2214
2215 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2216                 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2217                         WARN("CONFIG_EXPERIMENTAL",
2218                              "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2219                 }
2220
2221 # check for RCS/CVS revision markers
2222                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2223                         WARN("CVS_KEYWORD",
2224                              "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2225                 }
2226
2227 # Blackfin: don't use __builtin_bfin_[cs]sync
2228                 if ($line =~ /__builtin_bfin_csync/) {
2229                         my $herevet = "$here\n" . cat_vet($line) . "\n";
2230                         ERROR("CSYNC",
2231                               "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2232                 }
2233                 if ($line =~ /__builtin_bfin_ssync/) {
2234                         my $herevet = "$here\n" . cat_vet($line) . "\n";
2235                         ERROR("SSYNC",
2236                               "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2237                 }
2238
2239 # check for old HOTPLUG __dev<foo> section markings
2240                 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2241                         WARN("HOTPLUG_SECTION",
2242                              "Using $1 is unnecessary\n" . $herecurr);
2243                 }
2244
2245 # Check for potential 'bare' types
2246                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2247                     $realline_next);
2248 #print "LINE<$line>\n";
2249                 if ($linenr >= $suppress_statement &&
2250                     $realcnt && $sline =~ /.\s*\S/) {
2251                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2252                                 ctx_statement_block($linenr, $realcnt, 0);
2253                         $stat =~ s/\n./\n /g;
2254                         $cond =~ s/\n./\n /g;
2255
2256 #print "linenr<$linenr> <$stat>\n";
2257                         # If this statement has no statement boundaries within
2258                         # it there is no point in retrying a statement scan
2259                         # until we hit end of it.
2260                         my $frag = $stat; $frag =~ s/;+\s*$//;
2261                         if ($frag !~ /(?:{|;)/) {
2262 #print "skip<$line_nr_next>\n";
2263                                 $suppress_statement = $line_nr_next;
2264                         }
2265
2266                         # Find the real next line.
2267                         $realline_next = $line_nr_next;
2268                         if (defined $realline_next &&
2269                             (!defined $lines[$realline_next - 1] ||
2270                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2271                                 $realline_next++;
2272                         }
2273
2274                         my $s = $stat;
2275                         $s =~ s/{.*$//s;
2276
2277                         # Ignore goto labels.
2278                         if ($s =~ /$Ident:\*$/s) {
2279
2280                         # Ignore functions being called
2281                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2282
2283                         } elsif ($s =~ /^.\s*else\b/s) {
2284
2285                         # declarations always start with types
2286                         } 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) {
2287                                 my $type = $1;
2288                                 $type =~ s/\s+/ /g;
2289                                 possible($type, "A:" . $s);
2290
2291                         # definitions in global scope can only start with types
2292                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2293                                 possible($1, "B:" . $s);
2294                         }
2295
2296                         # any (foo ... *) is a pointer cast, and foo is a type
2297                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2298                                 possible($1, "C:" . $s);
2299                         }
2300
2301                         # Check for any sort of function declaration.
2302                         # int foo(something bar, other baz);
2303                         # void (*store_gdt)(x86_descr_ptr *);
2304                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2305                                 my ($name_len) = length($1);
2306
2307                                 my $ctx = $s;
2308                                 substr($ctx, 0, $name_len + 1, '');
2309                                 $ctx =~ s/\)[^\)]*$//;
2310
2311                                 for my $arg (split(/\s*,\s*/, $ctx)) {
2312                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2313
2314                                                 possible($1, "D:" . $s);
2315                                         }
2316                                 }
2317                         }
2318
2319                 }
2320
2321 #
2322 # Checks which may be anchored in the context.
2323 #
2324
2325 # Check for switch () and associated case and default
2326 # statements should be at the same indent.
2327                 if ($line=~/\bswitch\s*\(.*\)/) {
2328                         my $err = '';
2329                         my $sep = '';
2330                         my @ctx = ctx_block_outer($linenr, $realcnt);
2331                         shift(@ctx);
2332                         for my $ctx (@ctx) {
2333                                 my ($clen, $cindent) = line_stats($ctx);
2334                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2335                                                         $indent != $cindent) {
2336                                         $err .= "$sep$ctx\n";
2337                                         $sep = '';
2338                                 } else {
2339                                         $sep = "[...]\n";
2340                                 }
2341                         }
2342                         if ($err ne '') {
2343                                 ERROR("SWITCH_CASE_INDENT_LEVEL",
2344                                       "switch and case should be at the same indent\n$hereline$err");
2345                         }
2346                 }
2347
2348 # if/while/etc brace do not go on next line, unless defining a do while loop,
2349 # or if that brace on the next line is for something else
2350                 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2351                         my $pre_ctx = "$1$2";
2352
2353                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2354
2355                         if ($line =~ /^\+\t{6,}/) {
2356                                 WARN("DEEP_INDENTATION",
2357                                      "Too many leading tabs - consider code refactoring\n" . $herecurr);
2358                         }
2359
2360                         my $ctx_cnt = $realcnt - $#ctx - 1;
2361                         my $ctx = join("\n", @ctx);
2362
2363                         my $ctx_ln = $linenr;
2364                         my $ctx_skip = $realcnt;
2365
2366                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2367                                         defined $lines[$ctx_ln - 1] &&
2368                                         $lines[$ctx_ln - 1] =~ /^-/)) {
2369                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2370                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2371                                 $ctx_ln++;
2372                         }
2373
2374                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2375                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2376
2377                         if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2378                                 ERROR("OPEN_BRACE",
2379                                       "that open brace { should be on the previous line\n" .
2380                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2381                         }
2382                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2383                             $ctx =~ /\)\s*\;\s*$/ &&
2384                             defined $lines[$ctx_ln - 1])
2385                         {
2386                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2387                                 if ($nindent > $indent) {
2388                                         WARN("TRAILING_SEMICOLON",
2389                                              "trailing semicolon indicates no statements, indent implies otherwise\n" .
2390                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2391                                 }
2392                         }
2393                 }
2394
2395 # Check relative indent for conditionals and blocks.
2396                 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2397                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2398                                 ctx_statement_block($linenr, $realcnt, 0)
2399                                         if (!defined $stat);
2400                         my ($s, $c) = ($stat, $cond);
2401
2402                         substr($s, 0, length($c), '');
2403
2404                         # Make sure we remove the line prefixes as we have
2405                         # none on the first line, and are going to readd them
2406                         # where necessary.
2407                         $s =~ s/\n./\n/gs;
2408
2409                         # Find out how long the conditional actually is.
2410                         my @newlines = ($c =~ /\n/gs);
2411                         my $cond_lines = 1 + $#newlines;
2412
2413                         # We want to check the first line inside the block
2414                         # starting at the end of the conditional, so remove:
2415                         #  1) any blank line termination
2416                         #  2) any opening brace { on end of the line
2417                         #  3) any do (...) {
2418                         my $continuation = 0;
2419                         my $check = 0;
2420                         $s =~ s/^.*\bdo\b//;
2421                         $s =~ s/^\s*{//;
2422                         if ($s =~ s/^\s*\\//) {
2423                                 $continuation = 1;
2424                         }
2425                         if ($s =~ s/^\s*?\n//) {
2426                                 $check = 1;
2427                                 $cond_lines++;
2428                         }
2429
2430                         # Also ignore a loop construct at the end of a
2431                         # preprocessor statement.
2432                         if (($prevline =~ /^.\s*#\s*define\s/ ||
2433                             $prevline =~ /\\\s*$/) && $continuation == 0) {
2434                                 $check = 0;
2435                         }
2436
2437                         my $cond_ptr = -1;
2438                         $continuation = 0;
2439                         while ($cond_ptr != $cond_lines) {
2440                                 $cond_ptr = $cond_lines;
2441
2442                                 # If we see an #else/#elif then the code
2443                                 # is not linear.
2444                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2445                                         $check = 0;
2446                                 }
2447
2448                                 # Ignore:
2449                                 #  1) blank lines, they should be at 0,
2450                                 #  2) preprocessor lines, and
2451                                 #  3) labels.
2452                                 if ($continuation ||
2453                                     $s =~ /^\s*?\n/ ||
2454                                     $s =~ /^\s*#\s*?/ ||
2455                                     $s =~ /^\s*$Ident\s*:/) {
2456                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2457                                         if ($s =~ s/^.*?\n//) {
2458                                                 $cond_lines++;
2459                                         }
2460                                 }
2461                         }
2462
2463                         my (undef, $sindent) = line_stats("+" . $s);
2464                         my $stat_real = raw_line($linenr, $cond_lines);
2465
2466                         # Check if either of these lines are modified, else
2467                         # this is not this patch's fault.
2468                         if (!defined($stat_real) ||
2469                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2470                                 $check = 0;
2471                         }
2472                         if (defined($stat_real) && $cond_lines > 1) {
2473                                 $stat_real = "[...]\n$stat_real";
2474                         }
2475
2476                         #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";
2477
2478                         if ($check && (($sindent % 8) != 0 ||
2479                             ($sindent <= $indent && $s ne ''))) {
2480                                 WARN("SUSPECT_CODE_INDENT",
2481                                      "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2482                         }
2483                 }
2484
2485                 # Track the 'values' across context and added lines.
2486                 my $opline = $line; $opline =~ s/^./ /;
2487                 my ($curr_values, $curr_vars) =
2488                                 annotate_values($opline . "\n", $prev_values);
2489                 $curr_values = $prev_values . $curr_values;
2490                 if ($dbg_values) {
2491                         my $outline = $opline; $outline =~ s/\t/ /g;
2492                         print "$linenr > .$outline\n";
2493                         print "$linenr > $curr_values\n";
2494                         print "$linenr >  $curr_vars\n";
2495                 }
2496                 $prev_values = substr($curr_values, -1);
2497
2498 #ignore lines not being added
2499                 next if ($line =~ /^[^\+]/);
2500
2501 # TEST: allow direct testing of the type matcher.
2502                 if ($dbg_type) {
2503                         if ($line =~ /^.\s*$Declare\s*$/) {
2504                                 ERROR("TEST_TYPE",
2505                                       "TEST: is type\n" . $herecurr);
2506                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2507                                 ERROR("TEST_NOT_TYPE",
2508                                       "TEST: is not type ($1 is)\n". $herecurr);
2509                         }
2510                         next;
2511                 }
2512 # TEST: allow direct testing of the attribute matcher.
2513                 if ($dbg_attr) {
2514                         if ($line =~ /^.\s*$Modifier\s*$/) {
2515                                 ERROR("TEST_ATTR",
2516                                       "TEST: is attr\n" . $herecurr);
2517                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2518                                 ERROR("TEST_NOT_ATTR",
2519                                       "TEST: is not attr ($1 is)\n". $herecurr);
2520                         }
2521                         next;
2522                 }
2523
2524 # check for initialisation to aggregates open brace on the next line
2525                 if ($line =~ /^.\s*{/ &&
2526                     $prevline =~ /(?:^|[^=])=\s*$/) {
2527                         ERROR("OPEN_BRACE",
2528                               "that open brace { should be on the previous line\n" . $hereprev);
2529                 }
2530
2531 #
2532 # Checks which are anchored on the added line.
2533 #
2534
2535 # check for malformed paths in #include statements (uses RAW line)
2536                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2537                         my $path = $1;
2538                         if ($path =~ m{//}) {
2539                                 ERROR("MALFORMED_INCLUDE",
2540                                       "malformed #include filename\n" . $herecurr);
2541                         }
2542                         if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2543                                 ERROR("UAPI_INCLUDE",
2544                                       "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2545                         }
2546                 }
2547
2548 # no C99 // comments
2549                 if ($line =~ m{//}) {
2550                         if (ERROR("C99_COMMENTS",
2551                                   "do not use C99 // comments\n" . $herecurr) &&
2552                             $fix) {
2553                                 my $line = $fixed[$linenr - 1];
2554                                 if ($line =~ /\/\/(.*)$/) {
2555                                         my $comment = trim($1);
2556                                         $fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@;
2557                                 }
2558                         }
2559                 }
2560                 # Remove C99 comments.
2561                 $line =~ s@//.*@@;
2562                 $opline =~ s@//.*@@;
2563
2564 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2565 # the whole statement.
2566 #print "APW <$lines[$realline_next - 1]>\n";
2567                 if (defined $realline_next &&
2568                     exists $lines[$realline_next - 1] &&
2569                     !defined $suppress_export{$realline_next} &&
2570                     ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2571                      $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2572                         # Handle definitions which produce identifiers with
2573                         # a prefix:
2574                         #   XXX(foo);
2575                         #   EXPORT_SYMBOL(something_foo);
2576                         my $name = $1;
2577                         if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2578                             $name =~ /^${Ident}_$2/) {
2579 #print "FOO C name<$name>\n";
2580                                 $suppress_export{$realline_next} = 1;
2581
2582                         } elsif ($stat !~ /(?:
2583                                 \n.}\s*$|
2584                                 ^.DEFINE_$Ident\(\Q$name\E\)|
2585                                 ^.DECLARE_$Ident\(\Q$name\E\)|
2586                                 ^.LIST_HEAD\(\Q$name\E\)|
2587                                 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2588                                 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2589                             )/x) {
2590 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2591                                 $suppress_export{$realline_next} = 2;
2592                         } else {
2593                                 $suppress_export{$realline_next} = 1;
2594                         }
2595                 }
2596                 if (!defined $suppress_export{$linenr} &&
2597                     $prevline =~ /^.\s*$/ &&
2598                     ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2599                      $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2600 #print "FOO B <$lines[$linenr - 1]>\n";
2601                         $suppress_export{$linenr} = 2;
2602                 }
2603                 if (defined $suppress_export{$linenr} &&
2604                     $suppress_export{$linenr} == 2) {
2605                         WARN("EXPORT_SYMBOL",
2606                              "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2607                 }
2608
2609 # check for global initialisers.
2610                 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
2611                         if (ERROR("GLOBAL_INITIALISERS",
2612                                   "do not initialise globals to 0 or NULL\n" .
2613                                       $herecurr) &&
2614                             $fix) {
2615                                 $fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
2616                         }
2617                 }
2618 # check for static initialisers.
2619                 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2620                         if (ERROR("INITIALISED_STATIC",
2621                                   "do not initialise statics to 0 or NULL\n" .
2622                                       $herecurr) &&
2623                             $fix) {
2624                                 $fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
2625                         }
2626                 }
2627
2628 # check for static const char * arrays.
2629                 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2630                         WARN("STATIC_CONST_CHAR_ARRAY",
2631                              "static const char * array should probably be static const char * const\n" .
2632                                 $herecurr);
2633                }
2634
2635 # check for static char foo[] = "bar" declarations.
2636                 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2637                         WARN("STATIC_CONST_CHAR_ARRAY",
2638                              "static char array declaration should probably be static const char\n" .
2639                                 $herecurr);
2640                }
2641
2642 # check for uses of DEFINE_PCI_DEVICE_TABLE
2643                 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
2644                         if (WARN("DEFINE_PCI_DEVICE_TABLE",
2645                                  "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
2646                             $fix) {
2647                                 $fixed[$linenr - 1] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
2648                         }
2649                 }
2650
2651 # check for new typedefs, only function parameters and sparse annotations
2652 # make sense.
2653                 if ($line =~ /\btypedef\s/ &&
2654                     $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2655                     $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2656                     $line !~ /\b$typeTypedefs\b/ &&
2657                     $line !~ /\b__bitwise(?:__|)\b/) {
2658                         WARN("NEW_TYPEDEFS",
2659                              "do not add new typedefs\n" . $herecurr);
2660                 }
2661
2662 # * goes on variable not on type
2663                 # (char*[ const])
2664                 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2665                         #print "AA<$1>\n";
2666                         my ($ident, $from, $to) = ($1, $2, $2);
2667
2668                         # Should start with a space.
2669                         $to =~ s/^(\S)/ $1/;
2670                         # Should not end with a space.
2671                         $to =~ s/\s+$//;
2672                         # '*'s should not have spaces between.
2673                         while ($to =~ s/\*\s+\*/\*\*/) {
2674                         }
2675
2676 ##                      print "1: from<$from> to<$to> ident<$ident>\n";
2677                         if ($from ne $to) {
2678                                 if (ERROR("POINTER_LOCATION",
2679                                           "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
2680                                     $fix) {
2681                                         my $sub_from = $ident;
2682                                         my $sub_to = $ident;
2683                                         $sub_to =~ s/\Q$from\E/$to/;
2684                                         $fixed[$linenr - 1] =~
2685                                             s@\Q$sub_from\E@$sub_to@;
2686                                 }
2687                         }
2688                 }
2689                 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2690                         #print "BB<$1>\n";
2691                         my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
2692
2693                         # Should start with a space.
2694                         $to =~ s/^(\S)/ $1/;
2695                         # Should not end with a space.
2696                         $to =~ s/\s+$//;
2697                         # '*'s should not have spaces between.
2698                         while ($to =~ s/\*\s+\*/\*\*/) {
2699                         }
2700                         # Modifiers should have spaces.
2701                         $to =~ s/(\b$Modifier$)/$1 /;
2702
2703 ##                      print "2: from<$from> to<$to> ident<$ident>\n";
2704                         if ($from ne $to && $ident !~ /^$Modifier$/) {
2705                                 if (ERROR("POINTER_LOCATION",
2706                                           "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
2707                                     $fix) {
2708
2709                                         my $sub_from = $match;
2710                                         my $sub_to = $match;
2711                                         $sub_to =~ s/\Q$from\E/$to/;
2712                                         $fixed[$linenr - 1] =~
2713                                             s@\Q$sub_from\E@$sub_to@;
2714                                 }
2715                         }
2716                 }
2717
2718 # # no BUG() or BUG_ON()
2719 #               if ($line =~ /\b(BUG|BUG_ON)\b/) {
2720 #                       print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2721 #                       print "$herecurr";
2722 #                       $clean = 0;
2723 #               }
2724
2725                 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2726                         WARN("LINUX_VERSION_CODE",
2727                              "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2728                 }
2729
2730 # check for uses of printk_ratelimit
2731                 if ($line =~ /\bprintk_ratelimit\s*\(/) {
2732                         WARN("PRINTK_RATELIMITED",
2733 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2734                 }
2735
2736 # printk should use KERN_* levels.  Note that follow on printk's on the
2737 # same line do not need a level, so we use the current block context
2738 # to try and find and validate the current printk.  In summary the current
2739 # printk includes all preceding printk's which have no newline on the end.
2740 # we assume the first bad printk is the one to report.
2741                 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2742                         my $ok = 0;
2743                         for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2744                                 #print "CHECK<$lines[$ln - 1]\n";
2745                                 # we have a preceding printk if it ends
2746                                 # with "\n" ignore it, else it is to blame
2747                                 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2748                                         if ($rawlines[$ln - 1] !~ m{\\n"}) {
2749                                                 $ok = 1;
2750                                         }
2751                                         last;
2752                                 }
2753                         }
2754                         if ($ok == 0) {
2755                                 WARN("PRINTK_WITHOUT_KERN_LEVEL",
2756                                      "printk() should include KERN_ facility level\n" . $herecurr);
2757                         }
2758                 }
2759
2760                 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
2761                         my $orig = $1;
2762                         my $level = lc($orig);
2763                         $level = "warn" if ($level eq "warning");
2764                         my $level2 = $level;
2765                         $level2 = "dbg" if ($level eq "debug");
2766                         WARN("PREFER_PR_LEVEL",
2767                              "Prefer netdev_$level2(netdev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
2768                 }
2769
2770                 if ($line =~ /\bpr_warning\s*\(/) {
2771                         if (WARN("PREFER_PR_LEVEL",
2772                                  "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
2773                             $fix) {
2774                                 $fixed[$linenr - 1] =~
2775                                     s/\bpr_warning\b/pr_warn/;
2776                         }
2777                 }
2778
2779                 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
2780                         my $orig = $1;
2781                         my $level = lc($orig);
2782                         $level = "warn" if ($level eq "warning");
2783                         $level = "dbg" if ($level eq "debug");
2784                         WARN("PREFER_DEV_LEVEL",
2785                              "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
2786                 }
2787
2788 # function brace can't be on same line, except for #defines of do while,
2789 # or if closed on same line
2790                 if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
2791                     !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
2792                         ERROR("OPEN_BRACE",
2793                               "open brace '{' following function declarations go on the next line\n" . $herecurr);
2794                 }
2795
2796 # open braces for enum, union and struct go on the same line.
2797                 if ($line =~ /^.\s*{/ &&
2798                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2799                         ERROR("OPEN_BRACE",
2800                               "open brace '{' following $1 go on the same line\n" . $hereprev);
2801                 }
2802
2803 # missing space after union, struct or enum definition
2804                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
2805                         if (WARN("SPACING",
2806                                  "missing space after $1 definition\n" . $herecurr) &&
2807                             $fix) {
2808                                 $fixed[$linenr - 1] =~
2809                                     s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
2810                         }
2811                 }
2812
2813 # check for spacing round square brackets; allowed:
2814 #  1. with a type on the left -- int [] a;
2815 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2816 #  3. inside a curly brace -- = { [0...10] = 5 }
2817                 while ($line =~ /(.*?\s)\[/g) {
2818                         my ($where, $prefix) = ($-[1], $1);
2819                         if ($prefix !~ /$Type\s+$/ &&
2820                             ($where != 0 || $prefix !~ /^.\s+$/) &&
2821                             $prefix !~ /[{,]\s+$/) {
2822                                 if (ERROR("BRACKET_SPACE",
2823                                           "space prohibited before open square bracket '['\n" . $herecurr) &&
2824                                     $fix) {
2825                                     $fixed[$linenr - 1] =~
2826                                         s/^(\+.*?)\s+\[/$1\[/;
2827                                 }
2828                         }
2829                 }
2830
2831 # check for spaces between functions and their parentheses.
2832                 while ($line =~ /($Ident)\s+\(/g) {
2833                         my $name = $1;
2834                         my $ctx_before = substr($line, 0, $-[1]);
2835                         my $ctx = "$ctx_before$name";
2836
2837                         # Ignore those directives where spaces _are_ permitted.
2838                         if ($name =~ /^(?:
2839                                 if|for|while|switch|return|case|
2840                                 volatile|__volatile__|
2841                                 __attribute__|format|__extension__|
2842                                 asm|__asm__)$/x)
2843                         {
2844                         # cpp #define statements have non-optional spaces, ie
2845                         # if there is a space between the name and the open
2846                         # parenthesis it is simply not a parameter group.
2847                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2848
2849                         # cpp #elif statement condition may start with a (
2850                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2851
2852                         # If this whole things ends with a type its most
2853                         # likely a typedef for a function.
2854                         } elsif ($ctx =~ /$Type$/) {
2855
2856                         } else {
2857                                 if (WARN("SPACING",
2858                                          "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
2859                                              $fix) {
2860                                         $fixed[$linenr - 1] =~
2861                                             s/\b$name\s+\(/$name\(/;
2862                                 }
2863                         }
2864                 }
2865
2866 # Check operator spacing.
2867                 if (!($line=~/\#\s*include/)) {
2868                         my $fixed_line = "";
2869                         my $line_fixed = 0;
2870
2871                         my $ops = qr{
2872                                 <<=|>>=|<=|>=|==|!=|
2873                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2874                                 =>|->|<<|>>|<|>|=|!|~|
2875                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2876                                 \?:|\?|:
2877                         }x;
2878                         my @elements = split(/($ops|;)/, $opline);
2879
2880 ##                      print("element count: <" . $#elements . ">\n");
2881 ##                      foreach my $el (@elements) {
2882 ##                              print("el: <$el>\n");
2883 ##                      }
2884
2885                         my @fix_elements = ();
2886                         my $off = 0;
2887
2888                         foreach my $el (@elements) {
2889                                 push(@fix_elements, substr($rawline, $off, length($el)));
2890                                 $off += length($el);
2891                         }
2892
2893                         $off = 0;
2894
2895                         my $blank = copy_spacing($opline);
2896                         my $last_after = -1;
2897
2898                         for (my $n = 0; $n < $#elements; $n += 2) {
2899
2900                                 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
2901
2902 ##                              print("n: <$n> good: <$good>\n");
2903
2904                                 $off += length($elements[$n]);
2905
2906                                 # Pick up the preceding and succeeding characters.
2907                                 my $ca = substr($opline, 0, $off);
2908                                 my $cc = '';
2909                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2910                                         $cc = substr($opline, $off + length($elements[$n + 1]));
2911                                 }
2912                                 my $cb = "$ca$;$cc";
2913
2914                                 my $a = '';
2915                                 $a = 'V' if ($elements[$n] ne '');
2916                                 $a = 'W' if ($elements[$n] =~ /\s$/);
2917                                 $a = 'C' if ($elements[$n] =~ /$;$/);
2918                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2919                                 $a = 'O' if ($elements[$n] eq '');
2920                                 $a = 'E' if ($ca =~ /^\s*$/);
2921
2922                                 my $op = $elements[$n + 1];
2923
2924                                 my $c = '';
2925                                 if (defined $elements[$n + 2]) {
2926                                         $c = 'V' if ($elements[$n + 2] ne '');
2927                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2928                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2929                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2930                                         $c = 'O' if ($elements[$n + 2] eq '');
2931                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2932                                 } else {
2933                                         $c = 'E';
2934                                 }
2935
2936                                 my $ctx = "${a}x${c}";
2937
2938                                 my $at = "(ctx:$ctx)";
2939
2940                                 my $ptr = substr($blank, 0, $off) . "^";
2941                                 my $hereptr = "$hereline$ptr\n";
2942
2943                                 # Pull out the value of this operator.
2944                                 my $op_type = substr($curr_values, $off + 1, 1);
2945
2946                                 # Get the full operator variant.
2947                                 my $opv = $op . substr($curr_vars, $off, 1);
2948
2949                                 # Ignore operators passed as parameters.
2950                                 if ($op_type ne 'V' &&
2951                                     $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2952
2953 #                               # Ignore comments
2954 #                               } elsif ($op =~ /^$;+$/) {
2955
2956                                 # ; should have either the end of line or a space or \ after it
2957                                 } elsif ($op eq ';') {
2958                                         if ($ctx !~ /.x[WEBC]/ &&
2959                                             $cc !~ /^\\/ && $cc !~ /^;/) {
2960                                                 if (ERROR("SPACING",
2961                                                           "space required after that '$op' $at\n" . $hereptr)) {
2962                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2963                                                         $line_fixed = 1;
2964                                                 }
2965                                         }
2966
2967                                 # // is a comment
2968                                 } elsif ($op eq '//') {
2969
2970                                 # No spaces for:
2971                                 #   ->
2972                                 #   :   when part of a bitfield
2973                                 } elsif ($op eq '->' || $opv eq ':B') {
2974                                         if ($ctx =~ /Wx.|.xW/) {
2975                                                 if (ERROR("SPACING",
2976                                                           "spaces prohibited around that '$op' $at\n" . $hereptr)) {
2977                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2978                                                         if (defined $fix_elements[$n + 2]) {
2979                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
2980                                                         }
2981                                                         $line_fixed = 1;
2982                                                 }
2983                                         }
2984
2985                                 # , must have a space on the right.
2986                                 } elsif ($op eq ',') {
2987                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
2988                                                 if (ERROR("SPACING",
2989                                                           "space required after that '$op' $at\n" . $hereptr)) {
2990                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2991                                                         $line_fixed = 1;
2992                                                         $last_after = $n;
2993                                                 }
2994                                         }
2995
2996                                 # '*' as part of a type definition -- reported already.
2997                                 } elsif ($opv eq '*_') {
2998                                         #warn "'*' is part of type\n";
2999
3000                                 # unary operators should have a space before and
3001                                 # none after.  May be left adjacent to another
3002                                 # unary operator, or a cast
3003                                 } elsif ($op eq '!' || $op eq '~' ||
3004                                          $opv eq '*U' || $opv eq '-U' ||
3005                                          $opv eq '&U' || $opv eq '&&U') {
3006                                         if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3007                                                 if (ERROR("SPACING",
3008                                                           "space required before that '$op' $at\n" . $hereptr)) {
3009                                                         if ($n != $last_after + 2) {
3010                                                                 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3011                                                                 $line_fixed = 1;
3012                                                         }
3013                                                 }
3014                                         }
3015                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3016                                                 # A unary '*' may be const
3017
3018                                         } elsif ($ctx =~ /.xW/) {
3019                                                 if (ERROR("SPACING",
3020                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
3021                                                         $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3022                                                         if (defined $fix_elements[$n + 2]) {
3023                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3024                                                         }
3025                                                         $line_fixed = 1;
3026                                                 }
3027                                         }
3028
3029                                 # unary ++ and unary -- are allowed no space on one side.
3030                                 } elsif ($op eq '++' or $op eq '--') {
3031                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3032                                                 if (ERROR("SPACING",
3033                                                           "space required one side of that '$op' $at\n" . $hereptr)) {
3034                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3035                                                         $line_fixed = 1;
3036                                                 }
3037                                         }
3038                                         if ($ctx =~ /Wx[BE]/ ||
3039                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3040                                                 if (ERROR("SPACING",
3041                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
3042                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3043                                                         $line_fixed = 1;
3044                                                 }
3045                                         }
3046                                         if ($ctx =~ /ExW/) {
3047                                                 if (ERROR("SPACING",
3048                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
3049                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3050                                                         if (defined $fix_elements[$n + 2]) {
3051                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3052                                                         }
3053                                                         $line_fixed = 1;
3054                                                 }
3055                                         }
3056
3057                                 # << and >> may either have or not have spaces both sides
3058                                 } elsif ($op eq '<<' or $op eq '>>' or
3059                                          $op eq '&' or $op eq '^' or $op eq '|' or
3060                                          $op eq '+' or $op eq '-' or
3061                                          $op eq '*' or $op eq '/' or
3062                                          $op eq '%')
3063                                 {
3064                                         if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3065                                                 if (ERROR("SPACING",
3066                                                           "need consistent spacing around '$op' $at\n" . $hereptr)) {
3067                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3068                                                         if (defined $fix_elements[$n + 2]) {
3069                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3070                                                         }
3071                                                         $line_fixed = 1;
3072                                                 }
3073                                         }
3074
3075                                 # A colon needs no spaces before when it is
3076                                 # terminating a case value or a label.
3077                                 } elsif ($opv eq ':C' || $opv eq ':L') {
3078                                         if ($ctx =~ /Wx./) {
3079                                                 if (ERROR("SPACING",
3080                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
3081                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3082                                                         $line_fixed = 1;
3083                                                 }
3084                                         }
3085
3086                                 # All the others need spaces both sides.
3087                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3088                                         my $ok = 0;
3089
3090                                         # Ignore email addresses <foo@bar>
3091                                         if (($op eq '<' &&
3092                                              $cc =~ /^\S+\@\S+>/) ||
3093                                             ($op eq '>' &&
3094                                              $ca =~ /<\S+\@\S+$/))
3095                                         {
3096                                                 $ok = 1;
3097                                         }
3098
3099                                         # messages are ERROR, but ?: are CHK
3100                                         if ($ok == 0) {
3101                                                 my $msg_type = \&ERROR;
3102                                                 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3103
3104                                                 if (&{$msg_type}("SPACING",
3105                                                                  "spaces required around that '$op' $at\n" . $hereptr)) {
3106                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3107                                                         if (defined $fix_elements[$n + 2]) {
3108                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3109                                                         }
3110                                                         $line_fixed = 1;
3111                                                 }
3112                                         }
3113                                 }
3114                                 $off += length($elements[$n + 1]);
3115
3116 ##                              print("n: <$n> GOOD: <$good>\n");
3117
3118                                 $fixed_line = $fixed_line . $good;
3119                         }
3120
3121                         if (($#elements % 2) == 0) {
3122                                 $fixed_line = $fixed_line . $fix_elements[$#elements];
3123                         }
3124
3125                         if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) {
3126                                 $fixed[$linenr - 1] = $fixed_line;
3127                         }
3128
3129
3130                 }
3131
3132 # check for whitespace before a non-naked semicolon
3133                 if ($line =~ /^\+.*\S\s+;\s*$/) {
3134                         if (WARN("SPACING",
3135                                  "space prohibited before semicolon\n" . $herecurr) &&
3136                             $fix) {
3137                                 1 while $fixed[$linenr - 1] =~
3138                                     s/^(\+.*\S)\s+;/$1;/;
3139                         }
3140                 }
3141
3142 # check for multiple assignments
3143                 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3144                         CHK("MULTIPLE_ASSIGNMENTS",
3145                             "multiple assignments should be avoided\n" . $herecurr);
3146                 }
3147
3148 ## # check for multiple declarations, allowing for a function declaration
3149 ## # continuation.
3150 ##              if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3151 ##                  $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3152 ##
3153 ##                      # Remove any bracketed sections to ensure we do not
3154 ##                      # falsly report the parameters of functions.
3155 ##                      my $ln = $line;
3156 ##                      while ($ln =~ s/\([^\(\)]*\)//g) {
3157 ##                      }
3158 ##                      if ($ln =~ /,/) {
3159 ##                              WARN("MULTIPLE_DECLARATION",
3160 ##                                   "declaring multiple variables together should be avoided\n" . $herecurr);
3161 ##                      }
3162 ##              }
3163
3164 #need space before brace following if, while, etc
3165                 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3166                     $line =~ /do{/) {
3167                         if (ERROR("SPACING",
3168                                   "space required before the open brace '{'\n" . $herecurr) &&
3169                             $fix) {
3170                                 $fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/;
3171                         }
3172                 }
3173
3174 ## # check for blank lines before declarations
3175 ##              if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3176 ##                  $prevrawline =~ /^.\s*$/) {
3177 ##                      WARN("SPACING",
3178 ##                           "No blank lines before declarations\n" . $hereprev);
3179 ##              }
3180 ##
3181
3182 # closing brace should have a space following it when it has anything
3183 # on the line
3184                 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3185                         if (ERROR("SPACING",
3186                                   "space required after that close brace '}'\n" . $herecurr) &&
3187                             $fix) {
3188                                 $fixed[$linenr - 1] =~
3189                                     s/}((?!(?:,|;|\)))\S)/} $1/;
3190                         }
3191                 }
3192
3193 # check spacing on square brackets
3194                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3195                         if (ERROR("SPACING",
3196                                   "space prohibited after that open square bracket '['\n" . $herecurr) &&
3197                             $fix) {
3198                                 $fixed[$linenr - 1] =~
3199                                     s/\[\s+/\[/;
3200                         }
3201                 }
3202                 if ($line =~ /\s\]/) {
3203                         if (ERROR("SPACING",
3204                                   "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3205                             $fix) {
3206                                 $fixed[$linenr - 1] =~
3207                                     s/\s+\]/\]/;
3208                         }
3209                 }
3210
3211 # check spacing on parentheses
3212                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3213                     $line !~ /for\s*\(\s+;/) {
3214                         if (ERROR("SPACING",
3215                                   "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3216                             $fix) {
3217                                 $fixed[$linenr - 1] =~
3218                                     s/\(\s+/\(/;
3219                         }
3220                 }
3221                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3222                     $line !~ /for\s*\(.*;\s+\)/ &&
3223                     $line !~ /:\s+\)/) {
3224                         if (ERROR("SPACING",
3225                                   "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3226                             $fix) {
3227                                 $fixed[$linenr - 1] =~
3228                                     s/\s+\)/\)/;
3229                         }
3230                 }
3231
3232 #goto labels aren't indented, allow a single space however
3233                 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3234                    !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3235                         if (WARN("INDENTED_LABEL",
3236                                  "labels should not be indented\n" . $herecurr) &&
3237                             $fix) {
3238                                 $fixed[$linenr - 1] =~
3239                                     s/^(.)\s+/$1/;
3240                         }
3241                 }
3242
3243 # Return is not a function.
3244                 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3245                         my $spacing = $1;
3246                         if ($^V && $^V ge 5.10.0 &&
3247                             $stat =~ /^.\s*return\s*$balanced_parens\s*;\s*$/) {
3248                                 ERROR("RETURN_PARENTHESES",
3249                                       "return is not a function, parentheses are not required\n" . $herecurr);
3250
3251                         } elsif ($spacing !~ /\s+/) {
3252                                 ERROR("SPACING",
3253                                       "space required before the open parenthesis '('\n" . $herecurr);
3254                         }
3255                 }
3256
3257 # Return of what appears to be an errno should normally be -'ve
3258                 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3259                         my $name = $1;
3260                         if ($name ne 'EOF' && $name ne 'ERROR') {
3261                                 WARN("USE_NEGATIVE_ERRNO",
3262                                      "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3263                         }
3264                 }
3265
3266 # Need a space before open parenthesis after if, while etc
3267                 if ($line =~ /\b(if|while|for|switch)\(/) {
3268                         if (ERROR("SPACING",
3269                                   "space required before the open parenthesis '('\n" . $herecurr) &&
3270                             $fix) {
3271                                 $fixed[$linenr - 1] =~
3272                                     s/\b(if|while|for|switch)\(/$1 \(/;
3273                         }
3274                 }
3275
3276 # Check for illegal assignment in if conditional -- and check for trailing
3277 # statements after the conditional.
3278                 if ($line =~ /do\s*(?!{)/) {
3279                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3280                                 ctx_statement_block($linenr, $realcnt, 0)
3281                                         if (!defined $stat);
3282                         my ($stat_next) = ctx_statement_block($line_nr_next,
3283                                                 $remain_next, $off_next);
3284                         $stat_next =~ s/\n./\n /g;
3285                         ##print "stat<$stat> stat_next<$stat_next>\n";
3286
3287                         if ($stat_next =~ /^\s*while\b/) {
3288                                 # If the statement carries leading newlines,
3289                                 # then count those as offsets.
3290                                 my ($whitespace) =
3291                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3292                                 my $offset =
3293                                         statement_rawlines($whitespace) - 1;
3294
3295                                 $suppress_whiletrailers{$line_nr_next +
3296                                                                 $offset} = 1;
3297                         }
3298                 }
3299                 if (!defined $suppress_whiletrailers{$linenr} &&
3300                     defined($stat) && defined($cond) &&
3301                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3302                         my ($s, $c) = ($stat, $cond);
3303
3304                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3305                                 ERROR("ASSIGN_IN_IF",
3306                                       "do not use assignment in if condition\n" . $herecurr);
3307                         }
3308
3309                         # Find out what is on the end of the line after the
3310                         # conditional.
3311                         substr($s, 0, length($c), '');
3312                         $s =~ s/\n.*//g;
3313                         $s =~ s/$;//g;  # Remove any comments
3314                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3315                             $c !~ /}\s*while\s*/)
3316                         {
3317                                 # Find out how long the conditional actually is.
3318                                 my @newlines = ($c =~ /\n/gs);
3319                                 my $cond_lines = 1 + $#newlines;
3320                                 my $stat_real = '';
3321
3322                                 $stat_real = raw_line($linenr, $cond_lines)
3323                                                         . "\n" if ($cond_lines);
3324                                 if (defined($stat_real) && $cond_lines > 1) {
3325                                         $stat_real = "[...]\n$stat_real";
3326                                 }
3327
3328                                 ERROR("TRAILING_STATEMENTS",
3329                                       "trailing statements should be on next line\n" . $herecurr . $stat_real);
3330                         }
3331                 }
3332
3333 # Check for bitwise tests written as boolean
3334                 if ($line =~ /
3335                         (?:
3336                                 (?:\[|\(|\&\&|\|\|)
3337                                 \s*0[xX][0-9]+\s*
3338                                 (?:\&\&|\|\|)
3339                         |
3340                                 (?:\&\&|\|\|)
3341                                 \s*0[xX][0-9]+\s*
3342                                 (?:\&\&|\|\||\)|\])
3343                         )/x)
3344                 {
3345                         WARN("HEXADECIMAL_BOOLEAN_TEST",
3346                              "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3347                 }
3348
3349 # if and else should not have general statements after it
3350                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3351                         my $s = $1;
3352                         $s =~ s/$;//g;  # Remove any comments
3353                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3354                                 ERROR("TRAILING_STATEMENTS",
3355                                       "trailing statements should be on next line\n" . $herecurr);
3356                         }
3357                 }
3358 # if should not continue a brace
3359                 if ($line =~ /}\s*if\b/) {
3360                         ERROR("TRAILING_STATEMENTS",
3361                               "trailing statements should be on next line\n" .
3362                                 $herecurr);
3363                 }
3364 # case and default should not have general statements after them
3365                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
3366                     $line !~ /\G(?:
3367                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
3368                         \s*return\s+
3369                     )/xg)
3370                 {
3371                         ERROR("TRAILING_STATEMENTS",
3372                               "trailing statements should be on next line\n" . $herecurr);
3373                 }
3374
3375                 # Check for }<nl>else {, these must be at the same
3376                 # indent level to be relevant to each other.
3377                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
3378                                                 $previndent == $indent) {
3379                         ERROR("ELSE_AFTER_BRACE",
3380                               "else should follow close brace '}'\n" . $hereprev);
3381                 }
3382
3383                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
3384                                                 $previndent == $indent) {
3385                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
3386
3387                         # Find out what is on the end of the line after the
3388                         # conditional.
3389                         substr($s, 0, length($c), '');
3390                         $s =~ s/\n.*//g;
3391
3392                         if ($s =~ /^\s*;/) {
3393                                 ERROR("WHILE_AFTER_BRACE",
3394                                       "while should follow close brace '}'\n" . $hereprev);
3395                         }
3396                 }
3397
3398 #Specific variable tests
3399                 while ($line =~ m{($Constant|$Lval)}g) {
3400                         my $var = $1;
3401
3402 #gcc binary extension
3403                         if ($var =~ /^$Binary$/) {
3404                                 if (WARN("GCC_BINARY_CONSTANT",
3405                                          "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
3406                                     $fix) {
3407                                         my $hexval = sprintf("0x%x", oct($var));
3408                                         $fixed[$linenr - 1] =~
3409                                             s/\b$var\b/$hexval/;
3410                                 }
3411                         }
3412
3413 #CamelCase
3414                         if ($var !~ /^$Constant$/ &&
3415                             $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
3416 #Ignore Page<foo> variants
3417                             $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
3418 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
3419                             $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) {
3420                                 while ($var =~ m{($Ident)}g) {
3421                                         my $word = $1;
3422                                         next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
3423                                         if ($check) {
3424                                                 seed_camelcase_includes();
3425                                                 if (!$file && !$camelcase_file_seeded) {
3426                                                         seed_camelcase_file($realfile);
3427                                                         $camelcase_file_seeded = 1;
3428                                                 }
3429                                         }
3430                                         if (!defined $camelcase{$word}) {
3431                                                 $camelcase{$word} = 1;
3432                                                 CHK("CAMELCASE",
3433                                                     "Avoid CamelCase: <$word>\n" . $herecurr);
3434                                         }
3435                                 }
3436                         }
3437                 }
3438
3439 #no spaces allowed after \ in define
3440                 if ($line =~ /\#\s*define.*\\\s+$/) {
3441                         if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
3442                                  "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
3443                             $fix) {
3444                                 $fixed[$linenr - 1] =~ s/\s+$//;
3445                         }
3446                 }
3447
3448 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
3449                 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
3450                         my $file = "$1.h";
3451                         my $checkfile = "include/linux/$file";
3452                         if (-f "$root/$checkfile" &&
3453                             $realfile ne $checkfile &&
3454                             $1 !~ /$allowed_asm_includes/)
3455                         {
3456                                 if ($realfile =~ m{^arch/}) {
3457                                         CHK("ARCH_INCLUDE_LINUX",
3458                                             "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3459                                 } else {
3460                                         WARN("INCLUDE_LINUX",
3461                                              "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3462                                 }
3463                         }
3464                 }
3465
3466 # multi-statement macros should be enclosed in a do while loop, grab the
3467 # first statement and ensure its the whole macro if its not enclosed
3468 # in a known good container
3469                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
3470                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
3471                         my $ln = $linenr;
3472                         my $cnt = $realcnt;
3473                         my ($off, $dstat, $dcond, $rest);
3474                         my $ctx = '';
3475                         ($dstat, $dcond, $ln, $cnt, $off) =
3476                                 ctx_statement_block($linenr, $realcnt, 0);
3477                         $ctx = $dstat;
3478                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
3479                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
3480
3481                         $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
3482                         $dstat =~ s/$;//g;
3483                         $dstat =~ s/\\\n.//g;
3484                         $dstat =~ s/^\s*//s;
3485                         $dstat =~ s/\s*$//s;
3486
3487                         # Flatten any parentheses and braces
3488                         while ($dstat =~ s/\([^\(\)]*\)/1/ ||
3489                                $dstat =~ s/\{[^\{\}]*\}/1/ ||
3490                                $dstat =~ s/\[[^\[\]]*\]/1/)
3491                         {
3492                         }
3493
3494                         # Flatten any obvious string concatentation.
3495                         while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
3496                                $dstat =~ s/$Ident\s*("X*")/$1/)
3497                         {
3498                         }
3499
3500                         my $exceptions = qr{
3501                                 $Declare|
3502                                 module_param_named|
3503                                 MODULE_PARM_DESC|
3504                                 DECLARE_PER_CPU|
3505                                 DEFINE_PER_CPU|
3506                                 __typeof__\(|
3507                                 union|
3508                                 struct|
3509                                 \.$Ident\s*=\s*|
3510                                 ^\"|\"$
3511                         }x;
3512                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
3513                         if ($dstat ne '' &&
3514                             $dstat !~ /^(?:$Ident|-?$Constant),$/ &&                    # 10, // foo(),
3515                             $dstat !~ /^(?:$Ident|-?$Constant);$/ &&                    # foo();
3516                             $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&          # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
3517                             $dstat !~ /^'X'$/ &&                                        # character constants
3518                             $dstat !~ /$exceptions/ &&
3519                             $dstat !~ /^\.$Ident\s*=/ &&                                # .foo =
3520                             $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&          # stringification #foo
3521                             $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&       # do {...} while (...); // do {...} while (...)
3522                             $dstat !~ /^for\s*$Constant$/ &&                            # for (...)
3523                             $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&   # for (...) bar()
3524                             $dstat !~ /^do\s*{/ &&                                      # do {...
3525                             $dstat !~ /^\({/ &&                                         # ({...
3526                             $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
3527                         {
3528                                 $ctx =~ s/\n*$//;
3529                                 my $herectx = $here . "\n";
3530                                 my $cnt = statement_rawlines($ctx);
3531
3532                                 for (my $n = 0; $n < $cnt; $n++) {
3533                                         $herectx .= raw_line($linenr, $n) . "\n";
3534                                 }
3535
3536                                 if ($dstat =~ /;/) {
3537                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
3538                                               "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
3539                                 } else {
3540                                         ERROR("COMPLEX_MACRO",
3541                                               "Macros with complex values should be enclosed in parenthesis\n" . "$herectx");
3542                                 }
3543                         }
3544
3545 # check for line continuations outside of #defines, preprocessor #, and asm
3546
3547                 } else {
3548                         if ($prevline !~ /^..*\\$/ &&
3549                             $line !~ /^\+\s*\#.*\\$/ &&         # preprocessor
3550                             $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&   # asm
3551                             $line =~ /^\+.*\\$/) {
3552                                 WARN("LINE_CONTINUATIONS",
3553                                      "Avoid unnecessary line continuations\n" . $herecurr);
3554                         }
3555                 }
3556
3557 # do {} while (0) macro tests:
3558 # single-statement macros do not need to be enclosed in do while (0) loop,
3559 # macro should not end with a semicolon
3560                 if ($^V && $^V ge 5.10.0 &&
3561                     $realfile !~ m@/vmlinux.lds.h$@ &&
3562                     $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
3563                         my $ln = $linenr;
3564                         my $cnt = $realcnt;
3565                         my ($off, $dstat, $dcond, $rest);
3566                         my $ctx = '';
3567                         ($dstat, $dcond, $ln, $cnt, $off) =
3568                                 ctx_statement_block($linenr, $realcnt, 0);
3569                         $ctx = $dstat;
3570
3571                         $dstat =~ s/\\\n.//g;
3572
3573                         if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
3574                                 my $stmts = $2;
3575                                 my $semis = $3;
3576
3577                                 $ctx =~ s/\n*$//;
3578                                 my $cnt = statement_rawlines($ctx);
3579                                 my $herectx = $here . "\n";
3580
3581                                 for (my $n = 0; $n < $cnt; $n++) {
3582                                         $herectx .= raw_line($linenr, $n) . "\n";
3583                                 }
3584
3585                                 if (($stmts =~ tr/;/;/) == 1 &&
3586                                     $stmts !~ /^\s*(if|while|for|switch)\b/) {
3587                                         WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
3588                                              "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
3589                                 }
3590                                 if (defined $semis && $semis ne "") {
3591                                         WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
3592                                              "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
3593                                 }
3594                         }
3595                 }
3596
3597 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
3598 # all assignments may have only one of the following with an assignment:
3599 #       .
3600 #       ALIGN(...)
3601 #       VMLINUX_SYMBOL(...)
3602                 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
3603                         WARN("MISSING_VMLINUX_SYMBOL",
3604                              "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
3605                 }
3606
3607 # check for redundant bracing round if etc
3608                 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
3609                         my ($level, $endln, @chunks) =
3610                                 ctx_statement_full($linenr, $realcnt, 1);
3611                         #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
3612                         #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
3613                         if ($#chunks > 0 && $level == 0) {
3614                                 my @allowed = ();
3615                                 my $allow = 0;
3616                                 my $seen = 0;
3617                                 my $herectx = $here . "\n";
3618                                 my $ln = $linenr - 1;
3619                                 for my $chunk (@chunks) {
3620                                         my ($cond, $block) = @{$chunk};
3621
3622                                         # If the condition carries leading newlines, then count those as offsets.
3623                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
3624                                         my $offset = statement_rawlines($whitespace) - 1;
3625
3626                                         $allowed[$allow] = 0;
3627                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
3628
3629                                         # We have looked at and allowed this specific line.
3630                                         $suppress_ifbraces{$ln + $offset} = 1;
3631
3632                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3633                                         $ln += statement_rawlines($block) - 1;
3634
3635                                         substr($block, 0, length($cond), '');
3636
3637                                         $seen++ if ($block =~ /^\s*{/);
3638
3639                                         #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
3640                                         if (statement_lines($cond) > 1) {
3641                                                 #print "APW: ALLOWED: cond<$cond>\n";
3642                                                 $allowed[$allow] = 1;
3643                                         }
3644                                         if ($block =~/\b(?:if|for|while)\b/) {
3645                                                 #print "APW: ALLOWED: block<$block>\n";
3646                                                 $allowed[$allow] = 1;
3647                                         }
3648                                         if (statement_block_size($block) > 1) {
3649                                                 #print "APW: ALLOWED: lines block<$block>\n";
3650                                                 $allowed[$allow] = 1;
3651                                         }
3652                                         $allow++;
3653                                 }
3654                                 if ($seen) {
3655                                         my $sum_allowed = 0;
3656                                         foreach (@allowed) {
3657                                                 $sum_allowed += $_;
3658                                         }
3659                                         if ($sum_allowed == 0) {
3660                                                 WARN("BRACES",
3661                                                      "braces {} are not necessary for any arm of this statement\n" . $herectx);
3662                                         } elsif ($sum_allowed != $allow &&
3663                                                  $seen != $allow) {
3664                                                 CHK("BRACES",
3665                                                     "braces {} should be used on all arms of this statement\n" . $herectx);
3666                                         }
3667                                 }
3668                         }
3669                 }
3670                 if (!defined $suppress_ifbraces{$linenr - 1} &&
3671                                         $line =~ /\b(if|while|for|else)\b/) {
3672                         my $allowed = 0;
3673
3674                         # Check the pre-context.
3675                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3676                                 #print "APW: ALLOWED: pre<$1>\n";
3677                                 $allowed = 1;
3678                         }
3679
3680                         my ($level, $endln, @chunks) =
3681                                 ctx_statement_full($linenr, $realcnt, $-[0]);
3682
3683                         # Check the condition.
3684                         my ($cond, $block) = @{$chunks[0]};
3685                         #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
3686                         if (defined $cond) {
3687                                 substr($block, 0, length($cond), '');
3688                         }
3689                         if (statement_lines($cond) > 1) {
3690                                 #print "APW: ALLOWED: cond<$cond>\n";
3691                                 $allowed = 1;
3692                         }
3693                         if ($block =~/\b(?:if|for|while)\b/) {
3694                                 #print "APW: ALLOWED: block<$block>\n";
3695                                 $allowed = 1;
3696                         }
3697                         if (statement_block_size($block) > 1) {
3698                                 #print "APW: ALLOWED: lines block<$block>\n";
3699                                 $allowed = 1;
3700                         }
3701                         # Check the post-context.
3702                         if (defined $chunks[1]) {
3703                                 my ($cond, $block) = @{$chunks[1]};
3704                                 if (defined $cond) {
3705                                         substr($block, 0, length($cond), '');
3706                                 }
3707                                 if ($block =~ /^\s*\{/) {
3708                                         #print "APW: ALLOWED: chunk-1 block<$block>\n";
3709                                         $allowed = 1;
3710                                 }
3711                         }
3712                         if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
3713                                 my $herectx = $here . "\n";
3714                                 my $cnt = statement_rawlines($block);
3715
3716                                 for (my $n = 0; $n < $cnt; $n++) {
3717                                         $herectx .= raw_line($linenr, $n) . "\n";
3718                                 }
3719
3720                                 WARN("BRACES",
3721                                      "braces {} are not necessary for single statement blocks\n" . $herectx);
3722                         }
3723                 }
3724
3725 # check for unnecessary blank lines around braces
3726                 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
3727                         CHK("BRACES",
3728                             "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
3729                 }
3730                 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
3731                         CHK("BRACES",
3732                             "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
3733                 }
3734
3735 # no volatiles please
3736                 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3737                 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
3738                         WARN("VOLATILE",
3739                              "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
3740                 }
3741
3742 # warn about #if 0
3743                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3744                         CHK("REDUNDANT_CODE",
3745                             "if this code is redundant consider removing it\n" .
3746                                 $herecurr);
3747                 }
3748
3749 # check for needless "if (<foo>) fn(<foo>)" uses
3750                 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
3751                         my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
3752                         if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
3753                                 WARN('NEEDLESS_IF',
3754                                      "$1(NULL) is safe this check is probably not required\n" . $hereprev);
3755                         }
3756                 }
3757
3758 # check for bad placement of section $InitAttribute (e.g.: __initdata)
3759                 if ($line =~ /(\b$InitAttribute\b)/) {
3760                         my $attr = $1;
3761                         if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
3762                                 my $ptr = $1;
3763                                 my $var = $2;
3764                                 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
3765                                       ERROR("MISPLACED_INIT",
3766                                             "$attr should be placed after $var\n" . $herecurr)) ||
3767                                      ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
3768                                       WARN("MISPLACED_INIT",
3769                                            "$attr should be placed after $var\n" . $herecurr))) &&
3770                                     $fix) {
3771                                         $fixed[$linenr - 1] =~ 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;
3772                                 }
3773                         }
3774                 }
3775
3776 # check for $InitAttributeData (ie: __initdata) with const
3777                 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
3778                         my $attr = $1;
3779                         $attr =~ /($InitAttributePrefix)(.*)/;
3780                         my $attr_prefix = $1;
3781                         my $attr_type = $2;
3782                         if (ERROR("INIT_ATTRIBUTE",
3783                                   "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
3784                             $fix) {
3785                                 $fixed[$linenr - 1] =~
3786                                     s/$InitAttributeData/${attr_prefix}initconst/;
3787                         }
3788                 }
3789
3790 # check for $InitAttributeConst (ie: __initconst) without const
3791                 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
3792                         my $attr = $1;
3793                         if (ERROR("INIT_ATTRIBUTE",
3794                                   "Use of $attr requires a separate use of const\n" . $herecurr) &&
3795                             $fix) {
3796                                 my $lead = $fixed[$linenr - 1] =~
3797                                     /(^\+\s*(?:static\s+))/;
3798                                 $lead = rtrim($1);
3799                                 $lead = "$lead " if ($lead !~ /^\+$/);
3800                                 $lead = "${lead}const ";
3801                                 $fixed[$linenr - 1] =~ s/(^\+\s*(?:static\s+))/$lead/;
3802                         }
3803                 }
3804
3805 # prefer usleep_range over udelay
3806                 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
3807                         # ignore udelay's < 10, however
3808                         if (! ($1 < 10) ) {
3809                                 CHK("USLEEP_RANGE",
3810                                     "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
3811                         }
3812                 }
3813
3814 # warn about unexpectedly long msleep's
3815                 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
3816                         if ($1 < 20) {
3817                                 WARN("MSLEEP",
3818                                      "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
3819                         }
3820                 }
3821
3822 # check for comparisons of jiffies
3823                 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
3824                         WARN("JIFFIES_COMPARISON",
3825                              "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
3826                 }
3827
3828 # check for comparisons of get_jiffies_64()
3829                 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
3830                         WARN("JIFFIES_COMPARISON",
3831                              "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
3832                 }
3833
3834 # warn about #ifdefs in C files
3835 #               if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3836 #                       print "#ifdef in C files should be avoided\n";
3837 #                       print "$herecurr";
3838 #                       $clean = 0;
3839 #               }
3840
3841 # warn about spacing in #ifdefs
3842                 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3843                         if (ERROR("SPACING",
3844                                   "exactly one space required after that #$1\n" . $herecurr) &&
3845                             $fix) {
3846                                 $fixed[$linenr - 1] =~
3847                                     s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
3848                         }
3849
3850                 }
3851
3852 # check for spinlock_t definitions without a comment.
3853                 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
3854                     $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
3855                         my $which = $1;
3856                         if (!ctx_has_comment($first_line, $linenr)) {
3857                                 CHK("UNCOMMENTED_DEFINITION",
3858                                     "$1 definition without comment\n" . $herecurr);
3859                         }
3860                 }
3861 # check for memory barriers without a comment.
3862                 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
3863                         if (!ctx_has_comment($first_line, $linenr)) {
3864                                 WARN("MEMORY_BARRIER",
3865                                      "memory barrier without comment\n" . $herecurr);
3866                         }
3867                 }
3868 # check of hardware specific defines
3869                 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
3870                         CHK("ARCH_DEFINES",
3871                             "architecture specific defines should be avoided\n" .  $herecurr);
3872                 }
3873
3874 # Check that the storage class is at the beginning of a declaration
3875                 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
3876                         WARN("STORAGE_CLASS",
3877                              "storage class should be at the beginning of the declaration\n" . $herecurr)
3878                 }
3879
3880 # check the location of the inline attribute, that it is between
3881 # storage class and type.
3882                 if ($line =~ /\b$Type\s+$Inline\b/ ||
3883                     $line =~ /\b$Inline\s+$Storage\b/) {
3884                         ERROR("INLINE_LOCATION",
3885                               "inline keyword should sit between storage class and type\n" . $herecurr);
3886                 }
3887
3888 # Check for __inline__ and __inline, prefer inline
3889                 if ($realfile !~ m@\binclude/uapi/@ &&
3890                     $line =~ /\b(__inline__|__inline)\b/) {
3891                         if (WARN("INLINE",
3892                                  "plain inline is preferred over $1\n" . $herecurr) &&
3893                             $fix) {
3894                                 $fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/;
3895
3896                         }
3897                 }
3898
3899 # Check for __attribute__ packed, prefer __packed
3900                 if ($realfile !~ m@\binclude/uapi/@ &&
3901                     $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
3902                         WARN("PREFER_PACKED",
3903                              "__packed is preferred over __attribute__((packed))\n" . $herecurr);
3904                 }
3905
3906 # Check for __attribute__ aligned, prefer __aligned
3907                 if ($realfile !~ m@\binclude/uapi/@ &&
3908                     $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
3909                         WARN("PREFER_ALIGNED",
3910                              "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
3911                 }
3912
3913 # Check for __attribute__ format(printf, prefer __printf
3914                 if ($realfile !~ m@\binclude/uapi/@ &&
3915                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
3916                         if (WARN("PREFER_PRINTF",
3917                                  "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
3918                             $fix) {
3919                                 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
3920
3921                         }
3922                 }
3923
3924 # Check for __attribute__ format(scanf, prefer __scanf
3925                 if ($realfile !~ m@\binclude/uapi/@ &&
3926                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
3927                         if (WARN("PREFER_SCANF",
3928                                  "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
3929                             $fix) {
3930                                 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
3931                         }
3932                 }
3933
3934 # check for sizeof(&)
3935                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
3936                         WARN("SIZEOF_ADDRESS",
3937                              "sizeof(& should be avoided\n" . $herecurr);
3938                 }
3939
3940 # check for sizeof without parenthesis
3941                 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
3942                         if (WARN("SIZEOF_PARENTHESIS",
3943                                  "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
3944                             $fix) {
3945                                 $fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
3946                         }
3947                 }
3948
3949 # check for line continuations in quoted strings with odd counts of "
3950                 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
3951                         WARN("LINE_CONTINUATIONS",
3952                              "Avoid line continuations in quoted strings\n" . $herecurr);
3953                 }
3954
3955 # check for struct spinlock declarations
3956                 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
3957                         WARN("USE_SPINLOCK_T",
3958                              "struct spinlock should be spinlock_t\n" . $herecurr);
3959                 }
3960
3961 # check for seq_printf uses that could be seq_puts
3962                 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
3963                         my $fmt = get_quoted_string($line, $rawline);
3964                         if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
3965                                 if (WARN("PREFER_SEQ_PUTS",
3966                                          "Prefer seq_puts to seq_printf\n" . $herecurr) &&
3967                                     $fix) {
3968                                         $fixed[$linenr - 1] =~ s/\bseq_printf\b/seq_puts/;
3969                                 }
3970                         }
3971                 }
3972
3973 # Check for misused memsets
3974                 if ($^V && $^V ge 5.10.0 &&
3975                     defined $stat &&
3976                     $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
3977
3978                         my $ms_addr = $2;
3979                         my $ms_val = $7;
3980                         my $ms_size = $12;
3981
3982                         if ($ms_size =~ /^(0x|)0$/i) {
3983                                 ERROR("MEMSET",
3984                                       "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
3985                         } elsif ($ms_size =~ /^(0x|)1$/i) {
3986                                 WARN("MEMSET",
3987                                      "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
3988                         }
3989                 }
3990
3991 # typecasts on min/max could be min_t/max_t
3992                 if ($^V && $^V ge 5.10.0 &&
3993                     defined $stat &&
3994                     $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
3995                         if (defined $2 || defined $7) {
3996                                 my $call = $1;
3997                                 my $cast1 = deparenthesize($2);
3998                                 my $arg1 = $3;
3999                                 my $cast2 = deparenthesize($7);
4000                                 my $arg2 = $8;
4001                                 my $cast;
4002
4003                                 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4004                                         $cast = "$cast1 or $cast2";
4005                                 } elsif ($cast1 ne "") {
4006                                         $cast = $cast1;
4007                                 } else {
4008                                         $cast = $cast2;
4009                                 }
4010                                 WARN("MINMAX",
4011                                      "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4012                         }
4013                 }
4014
4015 # check usleep_range arguments
4016                 if ($^V && $^V ge 5.10.0 &&
4017                     defined $stat &&
4018                     $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4019                         my $min = $1;
4020                         my $max = $7;
4021                         if ($min eq $max) {
4022                                 WARN("USLEEP_RANGE",
4023                                      "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4024                         } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4025                                  $min > $max) {
4026                                 WARN("USLEEP_RANGE",
4027                                      "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4028                         }
4029                 }
4030
4031 # check for naked sscanf
4032                 if ($^V && $^V ge 5.10.0 &&
4033                     defined $stat &&
4034                     $stat =~ /\bsscanf\b/ &&
4035                     ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4036                      $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4037                      $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4038                         my $lc = $stat =~ tr@\n@@;
4039                         $lc = $lc + $linenr;
4040                         my $stat_real = raw_line($linenr, 0);
4041                         for (my $count = $linenr + 1; $count <= $lc; $count++) {
4042                                 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4043                         }
4044                         WARN("NAKED_SSCANF",
4045                              "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4046                 }
4047
4048 # check for new externs in .h files.
4049                 if ($realfile =~ /\.h$/ &&
4050                     $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4051                         if (CHK("AVOID_EXTERNS",
4052                                 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4053                             $fix) {
4054                                 $fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4055                         }
4056                 }
4057
4058 # check for new externs in .c files.
4059                 if ($realfile =~ /\.c$/ && defined $stat &&
4060                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4061                 {
4062                         my $function_name = $1;
4063                         my $paren_space = $2;
4064
4065                         my $s = $stat;
4066                         if (defined $cond) {
4067                                 substr($s, 0, length($cond), '');
4068                         }
4069                         if ($s =~ /^\s*;/ &&
4070                             $function_name ne 'uninitialized_var')
4071                         {
4072                                 WARN("AVOID_EXTERNS",
4073                                      "externs should be avoided in .c files\n" .  $herecurr);
4074                         }
4075
4076                         if ($paren_space =~ /\n/) {
4077                                 WARN("FUNCTION_ARGUMENTS",
4078                                      "arguments for function declarations should follow identifier\n" . $herecurr);
4079                         }
4080
4081                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4082                     $stat =~ /^.\s*extern\s+/)
4083                 {
4084                         WARN("AVOID_EXTERNS",
4085                              "externs should be avoided in .c files\n" .  $herecurr);
4086                 }
4087
4088 # checks for new __setup's
4089                 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4090                         my $name = $1;
4091
4092                         if (!grep(/$name/, @setup_docs)) {
4093                                 CHK("UNDOCUMENTED_SETUP",
4094                                     "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4095                         }
4096                 }
4097
4098 # check for pointless casting of kmalloc return
4099                 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4100                         WARN("UNNECESSARY_CASTS",
4101                              "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4102                 }
4103
4104 # alloc style
4105 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4106                 if ($^V && $^V ge 5.10.0 &&
4107                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4108                         CHK("ALLOC_SIZEOF_STRUCT",
4109                             "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4110                 }
4111
4112 # check for krealloc arg reuse
4113                 if ($^V && $^V ge 5.10.0 &&
4114                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
4115                         WARN("KREALLOC_ARG_REUSE",
4116                              "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
4117                 }
4118
4119 # check for alloc argument mismatch
4120                 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
4121                         WARN("ALLOC_ARRAY_ARGS",
4122                              "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
4123                 }
4124
4125 # check for GFP_NOWAIT use
4126                 if ($line =~ /\b__GFP_NOFAIL\b/) {
4127                         WARN("__GFP_NOFAIL",
4128                              "Use of __GFP_NOFAIL is deprecated, no new users should be added\n" . $herecurr);
4129                 }
4130
4131 # check for multiple semicolons
4132                 if ($line =~ /;\s*;\s*$/) {
4133                         if (WARN("ONE_SEMICOLON",
4134                                  "Statements terminations use 1 semicolon\n" . $herecurr) &&
4135                             $fix) {
4136                                 $fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g;
4137                         }
4138                 }
4139
4140 # check for case / default statements not preceeded by break/fallthrough/switch
4141                 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
4142                         my $has_break = 0;
4143                         my $has_statement = 0;
4144                         my $count = 0;
4145                         my $prevline = $linenr;
4146                         while ($prevline > 1 && $count < 3 && !$has_break) {
4147                                 $prevline--;
4148                                 my $rline = $rawlines[$prevline - 1];
4149                                 my $fline = $lines[$prevline - 1];
4150                                 last if ($fline =~ /^\@\@/);
4151                                 next if ($fline =~ /^\-/);
4152                                 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
4153                                 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
4154                                 next if ($fline =~ /^.[\s$;]*$/);
4155                                 $has_statement = 1;
4156                                 $count++;
4157                                 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
4158                         }
4159                         if (!$has_break && $has_statement) {
4160                                 WARN("MISSING_BREAK",
4161                                      "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
4162                         }
4163                 }
4164
4165 # check for switch/default statements without a break;
4166                 if ($^V && $^V ge 5.10.0 &&
4167                     defined $stat &&
4168                     $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
4169                         my $ctx = '';
4170                         my $herectx = $here . "\n";
4171                         my $cnt = statement_rawlines($stat);
4172                         for (my $n = 0; $n < $cnt; $n++) {
4173                                 $herectx .= raw_line($linenr, $n) . "\n";
4174                         }
4175                         WARN("DEFAULT_NO_BREAK",
4176                              "switch default: should use break\n" . $herectx);
4177                 }
4178
4179 # check for gcc specific __FUNCTION__
4180                 if ($line =~ /\b__FUNCTION__\b/) {
4181                         if (WARN("USE_FUNC",
4182                                  "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
4183                             $fix) {
4184                                 $fixed[$linenr - 1] =~ s/\b__FUNCTION__\b/__func__/g;
4185                         }
4186                 }
4187
4188 # check for use of yield()
4189                 if ($line =~ /\byield\s*\(\s*\)/) {
4190                         WARN("YIELD",
4191                              "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
4192                 }
4193
4194 # check for comparisons against true and false
4195                 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
4196                         my $lead = $1;
4197                         my $arg = $2;
4198                         my $test = $3;
4199                         my $otype = $4;
4200                         my $trail = $5;
4201                         my $op = "!";
4202
4203                         ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
4204
4205                         my $type = lc($otype);
4206                         if ($type =~ /^(?:true|false)$/) {
4207                                 if (("$test" eq "==" && "$type" eq "true") ||
4208                                     ("$test" eq "!=" && "$type" eq "false")) {
4209                                         $op = "";
4210                                 }
4211
4212                                 CHK("BOOL_COMPARISON",
4213                                     "Using comparison to $otype is error prone\n" . $herecurr);
4214
4215 ## maybe suggesting a correct construct would better
4216 ##                                  "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
4217
4218                         }
4219                 }
4220
4221 # check for semaphores initialized locked
4222                 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
4223                         WARN("CONSIDER_COMPLETION",
4224                              "consider using a completion\n" . $herecurr);
4225                 }
4226
4227 # recommend kstrto* over simple_strto* and strict_strto*
4228                 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
4229                         WARN("CONSIDER_KSTRTO",
4230                              "$1 is obsolete, use k$3 instead\n" . $herecurr);
4231                 }
4232
4233 # check for __initcall(), use device_initcall() explicitly please
4234                 if ($line =~ /^.\s*__initcall\s*\(/) {
4235                         WARN("USE_DEVICE_INITCALL",
4236                              "please use device_initcall() instead of __initcall()\n" . $herecurr);
4237                 }
4238
4239 # check for various ops structs, ensure they are const.
4240                 my $struct_ops = qr{acpi_dock_ops|
4241                                 address_space_operations|
4242                                 backlight_ops|
4243                                 block_device_operations|
4244                                 dentry_operations|
4245                                 dev_pm_ops|
4246                                 dma_map_ops|
4247                                 extent_io_ops|
4248                                 file_lock_operations|
4249                                 file_operations|
4250                                 hv_ops|
4251                                 ide_dma_ops|
4252                                 intel_dvo_dev_ops|
4253                                 item_operations|
4254                                 iwl_ops|
4255                                 kgdb_arch|
4256                                 kgdb_io|
4257                                 kset_uevent_ops|
4258                                 lock_manager_operations|
4259                                 microcode_ops|
4260                                 mtrr_ops|
4261                                 neigh_ops|
4262                                 nlmsvc_binding|
4263                                 pci_raw_ops|
4264                                 pipe_buf_operations|
4265                                 platform_hibernation_ops|
4266                                 platform_suspend_ops|
4267                                 proto_ops|
4268                                 rpc_pipe_ops|
4269                                 seq_operations|
4270                                 snd_ac97_build_ops|
4271                                 soc_pcmcia_socket_ops|
4272                                 stacktrace_ops|
4273                                 sysfs_ops|
4274                                 tty_operations|
4275                                 usb_mon_operations|
4276                                 wd_ops}x;
4277                 if ($line !~ /\bconst\b/ &&
4278                     $line =~ /\bstruct\s+($struct_ops)\b/) {
4279                         WARN("CONST_STRUCT",
4280                              "struct $1 should normally be const\n" .
4281                                 $herecurr);
4282                 }
4283
4284 # use of NR_CPUS is usually wrong
4285 # ignore definitions of NR_CPUS and usage to define arrays as likely right
4286                 if ($line =~ /\bNR_CPUS\b/ &&
4287                     $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
4288                     $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
4289                     $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
4290                     $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
4291                     $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
4292                 {
4293                         WARN("NR_CPUS",
4294                              "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
4295                 }
4296
4297 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
4298                 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
4299                         ERROR("DEFINE_ARCH_HAS",
4300                               "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
4301                 }
4302
4303 # check for %L{u,d,i} in strings
4304                 my $string;
4305                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4306                         $string = substr($rawline, $-[1], $+[1] - $-[1]);
4307                         $string =~ s/%%/__/g;
4308                         if ($string =~ /(?<!%)%L[udi]/) {
4309                                 WARN("PRINTF_L",
4310                                      "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4311                                 last;
4312                         }
4313                 }
4314
4315 # whine mightly about in_atomic
4316                 if ($line =~ /\bin_atomic\s*\(/) {
4317                         if ($realfile =~ m@^drivers/@) {
4318                                 ERROR("IN_ATOMIC",
4319                                       "do not use in_atomic in drivers\n" . $herecurr);
4320                         } elsif ($realfile !~ m@^kernel/@) {
4321                                 WARN("IN_ATOMIC",
4322                                      "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
4323                         }
4324                 }
4325
4326 # check for lockdep_set_novalidate_class
4327                 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
4328                     $line =~ /__lockdep_no_validate__\s*\)/ ) {
4329                         if ($realfile !~ m@^kernel/lockdep@ &&
4330                             $realfile !~ m@^include/linux/lockdep@ &&
4331                             $realfile !~ m@^drivers/base/core@) {
4332                                 ERROR("LOCKDEP",
4333                                       "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
4334                         }
4335                 }
4336
4337                 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
4338                     $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
4339                         WARN("EXPORTED_WORLD_WRITABLE",
4340                              "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
4341                 }
4342         }
4343
4344         # If we have no input at all, then there is nothing to report on
4345         # so just keep quiet.
4346         if ($#rawlines == -1) {
4347                 exit(0);
4348         }
4349
4350         # In mailback mode only produce a report in the negative, for
4351         # things that appear to be patches.
4352         if ($mailback && ($clean == 1 || !$is_patch)) {
4353                 exit(0);
4354         }
4355
4356         # This is not a patch, and we are are in 'no-patch' mode so
4357         # just keep quiet.
4358         if (!$chk_patch && !$is_patch) {
4359                 exit(0);
4360         }
4361
4362         if (!$is_patch) {
4363                 ERROR("NOT_UNIFIED_DIFF",
4364                       "Does not appear to be a unified-diff format patch\n");
4365         }
4366         if ($is_patch && $chk_signoff && $signoff == 0) {
4367                 ERROR("MISSING_SIGN_OFF",
4368                       "Missing Signed-off-by: line(s)\n");
4369         }
4370
4371         print report_dump();
4372         if ($summary && !($clean == 1 && $quiet == 1)) {
4373                 print "$filename " if ($summary_file);
4374                 print "total: $cnt_error errors, $cnt_warn warnings, " .
4375                         (($check)? "$cnt_chk checks, " : "") .
4376                         "$cnt_lines lines checked\n";
4377                 print "\n" if ($quiet == 0);
4378         }
4379
4380         if ($quiet == 0) {
4381
4382                 if ($^V lt 5.10.0) {
4383                         print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
4384                         print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
4385                 }
4386
4387                 # If there were whitespace errors which cleanpatch can fix
4388                 # then suggest that.
4389                 if ($rpt_cleaners) {
4390                         print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
4391                         print "      scripts/cleanfile\n\n";
4392                         $rpt_cleaners = 0;
4393                 }
4394         }
4395
4396         hash_show_words(\%use_type, "Used");
4397         hash_show_words(\%ignore_type, "Ignored");
4398
4399         if ($clean == 0 && $fix && "@rawlines" ne "@fixed") {
4400                 my $newfile = $filename;
4401                 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
4402                 my $linecount = 0;
4403                 my $f;
4404
4405                 open($f, '>', $newfile)
4406                     or die "$P: Can't open $newfile for write\n";
4407                 foreach my $fixed_line (@fixed) {
4408                         $linecount++;
4409                         if ($file) {
4410                                 if ($linecount > 3) {
4411                                         $fixed_line =~ s/^\+//;
4412                                         print $f $fixed_line. "\n";
4413                                 }
4414                         } else {
4415                                 print $f $fixed_line . "\n";
4416                         }
4417                 }
4418                 close($f);
4419
4420                 if (!$quiet) {
4421                         print << "EOM";
4422 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
4423
4424 Do _NOT_ trust the results written to this file.
4425 Do _NOT_ submit these changes without inspecting them for correctness.
4426
4427 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
4428 No warranties, expressed or implied...
4429
4430 EOM
4431                 }
4432         }
4433
4434         if ($clean == 1 && $quiet == 0) {
4435                 print "$vname has no obvious style problems and is ready for submission.\n"
4436         }
4437         if ($clean == 0 && $quiet == 0) {
4438                 print << "EOM";
4439 $vname has style problems, please review.
4440
4441 If any of these errors are false positives, please report
4442 them to the maintainer, see CHECKPATCH in MAINTAINERS.
4443 EOM
4444         }
4445
4446         return $clean;
4447 }