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