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