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