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