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