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