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