Whamcloud - gitweb
LU-6215 kernel: use f_path for inode dentry
[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         'LPROCFS',                      'CONFIG_PROC_FS',
442         'alloca',                       'malloc',
443         'mktemp',                       'mkstemp',
444         'sprintf',                      'snprintf',
445         'strcpy',                       'strncpy',
446         'strcat',                       'strncat',
447         'tempnam',                      'mkstemp',
448 );
449
450 my @rawlines = ();
451 my @lines = ();
452 my $vname;
453 for my $filename (@ARGV) {
454         my $FILE;
455         if ($file) {
456                 open($FILE, '-|', "diff -u /dev/null $filename") ||
457                         die "$P: $filename: diff failed - $!\n";
458         } elsif ($filename eq '-') {
459                 open($FILE, '<&STDIN');
460         } else {
461                 open($FILE, '<', "$filename") ||
462                         die "$P: $filename: open failed - $!\n";
463         }
464         if ($filename eq '-') {
465                 $vname = 'Your patch';
466         } else {
467                 $vname = $filename;
468         }
469         while (<$FILE>) {
470                 chomp;
471                 push(@rawlines, $_);
472         }
473         close($FILE);
474         if (!process($filename)) {
475                 $exit = 1;
476         }
477         @rawlines = ();
478         @lines = ();
479 }
480
481 exit($exit);
482
483 sub top_of_kernel_tree {
484         my ($root) = @_;
485
486         my @tree_check = (
487                 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
488                 "README", "Documentation", "arch", "include", "drivers",
489                 "fs", "init", "ipc", "kernel", "lib", "scripts",
490         );
491
492         foreach my $check (@tree_check) {
493                 if (! -e $root . '/' . $check) {
494                         return 0;
495                 }
496         }
497         return 1;
498     }
499
500 sub parse_email {
501         my ($formatted_email) = @_;
502
503         my $name = "";
504         my $address = "";
505         my $comment = "";
506
507         if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
508                 $name = $1;
509                 $address = $2;
510                 $comment = $3 if defined $3;
511         } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
512                 $address = $1;
513                 $comment = $2 if defined $2;
514         } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
515                 $address = $1;
516                 $comment = $2 if defined $2;
517                 $formatted_email =~ s/$address.*$//;
518                 $name = $formatted_email;
519                 $name =~ s/^\s+|\s+$//g;
520                 $name =~ s/^\"|\"$//g;
521                 # If there's a name left after stripping spaces and
522                 # leading quotes, and the address doesn't have both
523                 # leading and trailing angle brackets, the address
524                 # is invalid. ie:
525                 #   "joe smith joe@smith.com" bad
526                 #   "joe smith <joe@smith.com" bad
527                 if ($name ne "" && $address !~ /^<[^>]+>$/) {
528                         $name = "";
529                         $address = "";
530                         $comment = "";
531                 }
532         }
533
534         $name =~ s/^\s+|\s+$//g;
535         $name =~ s/^\"|\"$//g;
536         $address =~ s/^\s+|\s+$//g;
537         $address =~ s/^\<|\>$//g;
538
539         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
540                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
541                 $name = "\"$name\"";
542         }
543
544         return ($name, $address, $comment);
545 }
546
547 sub format_email {
548         my ($name, $address) = @_;
549
550         my $formatted_email;
551
552         $name =~ s/^\s+|\s+$//g;
553         $name =~ s/^\"|\"$//g;
554         $address =~ s/^\s+|\s+$//g;
555
556         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
557                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
558                 $name = "\"$name\"";
559         }
560
561         if ("$name" eq "") {
562                 $formatted_email = "$address";
563         } else {
564                 $formatted_email = "$name <$address>";
565         }
566
567         return $formatted_email;
568 }
569
570 sub which_conf {
571         my ($conf) = @_;
572
573         foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
574                 if (-e "$path/$conf") {
575                         return "$path/$conf";
576                 }
577         }
578
579         return "";
580 }
581
582 sub expand_tabs {
583         my ($str) = @_;
584
585         my $res = '';
586         my $n = 0;
587         for my $c (split(//, $str)) {
588                 if ($c eq "\t") {
589                         $res .= ' ';
590                         $n++;
591                         for (; ($n % 8) != 0; $n++) {
592                                 $res .= ' ';
593                         }
594                         next;
595                 }
596                 $res .= $c;
597                 $n++;
598         }
599
600         return $res;
601 }
602 sub copy_spacing {
603         (my $res = shift) =~ tr/\t/ /c;
604         return $res;
605 }
606
607 sub line_stats {
608         my ($line) = @_;
609
610         # Drop the diff line leader and expand tabs
611         $line =~ s/^.//;
612         $line = expand_tabs($line);
613
614         # Pick the indent from the front of the line.
615         my ($white) = ($line =~ /^(\s*)/);
616
617         return (length($line), length($white));
618 }
619
620 my $sanitise_quote = '';
621
622 sub sanitise_line_reset {
623         my ($in_comment) = @_;
624
625         if ($in_comment) {
626                 $sanitise_quote = '*/';
627         } else {
628                 $sanitise_quote = '';
629         }
630 }
631 sub sanitise_line {
632         my ($line) = @_;
633
634         my $res = '';
635         my $l = '';
636
637         my $qlen = 0;
638         my $off = 0;
639         my $c;
640
641         # Always copy over the diff marker.
642         $res = substr($line, 0, 1);
643
644         for ($off = 1; $off < length($line); $off++) {
645                 $c = substr($line, $off, 1);
646
647                 # Comments we are wacking completly including the begin
648                 # and end, all to $;.
649                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
650                         $sanitise_quote = '*/';
651
652                         substr($res, $off, 2, "$;$;");
653                         $off++;
654                         next;
655                 }
656                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
657                         $sanitise_quote = '';
658                         substr($res, $off, 2, "$;$;");
659                         $off++;
660                         next;
661                 }
662                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
663                         $sanitise_quote = '//';
664
665                         substr($res, $off, 2, $sanitise_quote);
666                         $off++;
667                         next;
668                 }
669
670                 # A \ in a string means ignore the next character.
671                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
672                     $c eq "\\") {
673                         substr($res, $off, 2, 'XX');
674                         $off++;
675                         next;
676                 }
677                 # Regular quotes.
678                 if ($c eq "'" || $c eq '"') {
679                         if ($sanitise_quote eq '') {
680                                 $sanitise_quote = $c;
681
682                                 substr($res, $off, 1, $c);
683                                 next;
684                         } elsif ($sanitise_quote eq $c) {
685                                 $sanitise_quote = '';
686                         }
687                 }
688
689                 #print "c<$c> SQ<$sanitise_quote>\n";
690                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
691                         substr($res, $off, 1, $;);
692                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
693                         substr($res, $off, 1, $;);
694                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
695                         substr($res, $off, 1, 'X');
696                 } else {
697                         substr($res, $off, 1, $c);
698                 }
699         }
700
701         if ($sanitise_quote eq '//') {
702                 $sanitise_quote = '';
703         }
704
705         # The pathname on a #include may be surrounded by '<' and '>'.
706         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
707                 my $clean = 'X' x length($1);
708                 $res =~ s@\<.*\>@<$clean>@;
709
710         # The whole of a #error is a string.
711         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
712                 my $clean = 'X' x length($1);
713                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
714         }
715
716         return $res;
717 }
718
719 sub ctx_statement_block {
720         my ($linenr, $remain, $off) = @_;
721         my $line = $linenr - 1;
722         my $blk = '';
723         my $soff = $off;
724         my $coff = $off - 1;
725         my $coff_set = 0;
726
727         my $loff = 0;
728
729         my $type = '';
730         my $level = 0;
731         my @stack = ();
732         my $p;
733         my $c;
734         my $len = 0;
735
736         my $remainder;
737         while (1) {
738                 @stack = (['', 0]) if ($#stack == -1);
739
740                 #warn "CSB: blk<$blk> remain<$remain>\n";
741                 # If we are about to drop off the end, pull in more
742                 # context.
743                 if ($off >= $len) {
744                         for (; $remain > 0; $line++) {
745                                 last if (!defined $lines[$line]);
746                                 next if ($lines[$line] =~ /^-/);
747                                 $remain--;
748                                 $loff = $len;
749                                 $blk .= $lines[$line] . "\n";
750                                 $len = length($blk);
751                                 $line++;
752                                 last;
753                         }
754                         # Bail if there is no further context.
755                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
756                         if ($off >= $len) {
757                                 last;
758                         }
759                         if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
760                                 $level++;
761                                 $type = '#';
762                         }
763                 }
764                 $p = $c;
765                 $c = substr($blk, $off, 1);
766                 $remainder = substr($blk, $off);
767
768                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
769
770                 # Handle nested #if/#else.
771                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
772                         push(@stack, [ $type, $level ]);
773                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
774                         ($type, $level) = @{$stack[$#stack - 1]};
775                 } elsif ($remainder =~ /^#\s*endif\b/) {
776                         ($type, $level) = @{pop(@stack)};
777                 }
778
779                 # Statement ends at the ';' or a close '}' at the
780                 # outermost level.
781                 if ($level == 0 && $c eq ';') {
782                         last;
783                 }
784
785                 # An else is really a conditional as long as its not else if
786                 if ($level == 0 && $coff_set == 0 &&
787                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
788                                 $remainder =~ /^(else)(?:\s|{)/ &&
789                                 $remainder !~ /^else\s+if\b/) {
790                         $coff = $off + length($1) - 1;
791                         $coff_set = 1;
792                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
793                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
794                 }
795
796                 if (($type eq '' || $type eq '(') && $c eq '(') {
797                         $level++;
798                         $type = '(';
799                 }
800                 if ($type eq '(' && $c eq ')') {
801                         $level--;
802                         $type = ($level != 0)? '(' : '';
803
804                         if ($level == 0 && $coff < $soff) {
805                                 $coff = $off;
806                                 $coff_set = 1;
807                                 #warn "CSB: mark coff<$coff>\n";
808                         }
809                 }
810                 if (($type eq '' || $type eq '{') && $c eq '{') {
811                         $level++;
812                         $type = '{';
813                 }
814                 if ($type eq '{' && $c eq '}') {
815                         $level--;
816                         $type = ($level != 0)? '{' : '';
817
818                         if ($level == 0) {
819                                 if (substr($blk, $off + 1, 1) eq ';') {
820                                         $off++;
821                                 }
822                                 last;
823                         }
824                 }
825                 # Preprocessor commands end at the newline unless escaped.
826                 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
827                         $level--;
828                         $type = '';
829                         $off++;
830                         last;
831                 }
832                 $off++;
833         }
834         # We are truly at the end, so shuffle to the next line.
835         if ($off == $len) {
836                 $loff = $len + 1;
837                 $line++;
838                 $remain--;
839         }
840
841         my $statement = substr($blk, $soff, $off - $soff + 1);
842         my $condition = substr($blk, $soff, $coff - $soff + 1);
843
844         #warn "STATEMENT<$statement>\n";
845         #warn "CONDITION<$condition>\n";
846
847         #print "coff<$coff> soff<$off> loff<$loff>\n";
848
849         return ($statement, $condition,
850                         $line, $remain + 1, $off - $loff + 1, $level);
851 }
852
853 sub statement_lines {
854         my ($stmt) = @_;
855
856         # Strip the diff line prefixes and rip blank lines at start and end.
857         $stmt =~ s/(^|\n)./$1/g;
858         $stmt =~ s/^\s*//;
859         $stmt =~ s/\s*$//;
860
861         my @stmt_lines = ($stmt =~ /\n/g);
862
863         return $#stmt_lines + 2;
864 }
865
866 sub statement_rawlines {
867         my ($stmt) = @_;
868
869         my @stmt_lines = ($stmt =~ /\n/g);
870
871         return $#stmt_lines + 2;
872 }
873
874 sub statement_block_size {
875         my ($stmt) = @_;
876
877         $stmt =~ s/(^|\n)./$1/g;
878         $stmt =~ s/^\s*{//;
879         $stmt =~ s/}\s*$//;
880         $stmt =~ s/^\s*//;
881         $stmt =~ s/\s*$//;
882
883         my @stmt_lines = ($stmt =~ /\n/g);
884         my @stmt_statements = ($stmt =~ /;/g);
885
886         my $stmt_lines = $#stmt_lines + 2;
887         my $stmt_statements = $#stmt_statements + 1;
888
889         if ($stmt_lines > $stmt_statements) {
890                 return $stmt_lines;
891         } else {
892                 return $stmt_statements;
893         }
894 }
895
896 sub ctx_statement_full {
897         my ($linenr, $remain, $off) = @_;
898         my ($statement, $condition, $level);
899
900         my (@chunks);
901
902         # Grab the first conditional/block pair.
903         ($statement, $condition, $linenr, $remain, $off, $level) =
904                                 ctx_statement_block($linenr, $remain, $off);
905         #print "F: c<$condition> s<$statement> remain<$remain>\n";
906         push(@chunks, [ $condition, $statement ]);
907         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
908                 return ($level, $linenr, @chunks);
909         }
910
911         # Pull in the following conditional/block pairs and see if they
912         # could continue the statement.
913         for (;;) {
914                 ($statement, $condition, $linenr, $remain, $off, $level) =
915                                 ctx_statement_block($linenr, $remain, $off);
916                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
917                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
918                 #print "C: push\n";
919                 push(@chunks, [ $condition, $statement ]);
920         }
921
922         return ($level, $linenr, @chunks);
923 }
924
925 sub ctx_block_get {
926         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
927         my $line;
928         my $start = $linenr - 1;
929         my $blk = '';
930         my @o;
931         my @c;
932         my @res = ();
933
934         my $level = 0;
935         my @stack = ($level);
936         for ($line = $start; $remain > 0; $line++) {
937                 next if ($rawlines[$line] =~ /^-/);
938                 $remain--;
939
940                 $blk .= $rawlines[$line];
941
942                 # Handle nested #if/#else.
943                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
944                         push(@stack, $level);
945                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
946                         $level = $stack[$#stack - 1];
947                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
948                         $level = pop(@stack);
949                 }
950
951                 foreach my $c (split(//, $lines[$line])) {
952                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
953                         if ($off > 0) {
954                                 $off--;
955                                 next;
956                         }
957
958                         if ($c eq $close && $level > 0) {
959                                 $level--;
960                                 last if ($level == 0);
961                         } elsif ($c eq $open) {
962                                 $level++;
963                         }
964                 }
965
966                 if (!$outer || $level <= 1) {
967                         push(@res, $rawlines[$line]);
968                 }
969
970                 last if ($level == 0);
971         }
972
973         return ($level, @res);
974 }
975 sub ctx_block_outer {
976         my ($linenr, $remain) = @_;
977
978         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
979         return @r;
980 }
981 sub ctx_block {
982         my ($linenr, $remain) = @_;
983
984         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
985         return @r;
986 }
987 sub ctx_statement {
988         my ($linenr, $remain, $off) = @_;
989
990         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
991         return @r;
992 }
993 sub ctx_block_level {
994         my ($linenr, $remain) = @_;
995
996         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
997 }
998 sub ctx_statement_level {
999         my ($linenr, $remain, $off) = @_;
1000
1001         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1002 }
1003
1004 sub ctx_locate_comment {
1005         my ($first_line, $end_line) = @_;
1006
1007         # Catch a comment on the end of the line itself.
1008         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1009         return $current_comment if (defined $current_comment);
1010
1011         # Look through the context and try and figure out if there is a
1012         # comment.
1013         my $in_comment = 0;
1014         $current_comment = '';
1015         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1016                 my $line = $rawlines[$linenr - 1];
1017                 #warn "           $line\n";
1018                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1019                         $in_comment = 1;
1020                 }
1021                 if ($line =~ m@/\*@) {
1022                         $in_comment = 1;
1023                 }
1024                 if (!$in_comment && $current_comment ne '') {
1025                         $current_comment = '';
1026                 }
1027                 $current_comment .= $line . "\n" if ($in_comment);
1028                 if ($line =~ m@\*/@) {
1029                         $in_comment = 0;
1030                 }
1031         }
1032
1033         chomp($current_comment);
1034         return($current_comment);
1035 }
1036 sub ctx_has_comment {
1037         my ($first_line, $end_line) = @_;
1038         my $cmt = ctx_locate_comment($first_line, $end_line);
1039
1040         ##print "LINE: $rawlines[$end_line - 1 ]\n";
1041         ##print "CMMT: $cmt\n";
1042
1043         return ($cmt ne '');
1044 }
1045
1046 sub raw_line {
1047         my ($linenr, $cnt) = @_;
1048
1049         my $offset = $linenr - 1;
1050         $cnt++;
1051
1052         my $line;
1053         while ($cnt) {
1054                 $line = $rawlines[$offset++];
1055                 next if (defined($line) && $line =~ /^-/);
1056                 $cnt--;
1057         }
1058
1059         return $line;
1060 }
1061
1062 sub cat_vet {
1063         my ($vet) = @_;
1064         my ($res, $coded);
1065
1066         $res = '';
1067         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1068                 $res .= $1;
1069                 if ($2 ne '') {
1070                         $coded = sprintf("^%c", unpack('C', $2) + 64);
1071                         $res .= $coded;
1072                 }
1073         }
1074         $res =~ s/$/\$/;
1075
1076         return $res;
1077 }
1078
1079 my $av_preprocessor = 0;
1080 my $av_pending;
1081 my @av_paren_type;
1082 my $av_pend_colon;
1083
1084 sub annotate_reset {
1085         $av_preprocessor = 0;
1086         $av_pending = '_';
1087         @av_paren_type = ('E');
1088         $av_pend_colon = 'O';
1089 }
1090
1091 sub annotate_values {
1092         my ($stream, $type) = @_;
1093
1094         my $res;
1095         my $var = '_' x length($stream);
1096         my $cur = $stream;
1097
1098         print "$stream\n" if ($dbg_values > 1);
1099
1100         while (length($cur)) {
1101                 @av_paren_type = ('E') if ($#av_paren_type < 0);
1102                 print " <" . join('', @av_paren_type) .
1103                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
1104                 if ($cur =~ /^(\s+)/o) {
1105                         print "WS($1)\n" if ($dbg_values > 1);
1106                         if ($1 =~ /\n/ && $av_preprocessor) {
1107                                 $type = pop(@av_paren_type);
1108                                 $av_preprocessor = 0;
1109                         }
1110
1111                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1112                         print "CAST($1)\n" if ($dbg_values > 1);
1113                         push(@av_paren_type, $type);
1114                         $type = 'c';
1115
1116                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1117                         print "DECLARE($1)\n" if ($dbg_values > 1);
1118                         $type = 'T';
1119
1120                 } elsif ($cur =~ /^($Modifier)\s*/) {
1121                         print "MODIFIER($1)\n" if ($dbg_values > 1);
1122                         $type = 'T';
1123
1124                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1125                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1126                         $av_preprocessor = 1;
1127                         push(@av_paren_type, $type);
1128                         if ($2 ne '') {
1129                                 $av_pending = 'N';
1130                         }
1131                         $type = 'E';
1132
1133                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1134                         print "UNDEF($1)\n" if ($dbg_values > 1);
1135                         $av_preprocessor = 1;
1136                         push(@av_paren_type, $type);
1137
1138                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1139                         print "PRE_START($1)\n" if ($dbg_values > 1);
1140                         $av_preprocessor = 1;
1141
1142                         push(@av_paren_type, $type);
1143                         push(@av_paren_type, $type);
1144                         $type = 'E';
1145
1146                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1147                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1148                         $av_preprocessor = 1;
1149
1150                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1151
1152                         $type = 'E';
1153
1154                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1155                         print "PRE_END($1)\n" if ($dbg_values > 1);
1156
1157                         $av_preprocessor = 1;
1158
1159                         # Assume all arms of the conditional end as this
1160                         # one does, and continue as if the #endif was not here.
1161                         pop(@av_paren_type);
1162                         push(@av_paren_type, $type);
1163                         $type = 'E';
1164
1165                 } elsif ($cur =~ /^(\\\n)/o) {
1166                         print "PRECONT($1)\n" if ($dbg_values > 1);
1167
1168                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1169                         print "ATTR($1)\n" if ($dbg_values > 1);
1170                         $av_pending = $type;
1171                         $type = 'N';
1172
1173                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1174                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1175                         if (defined $2) {
1176                                 $av_pending = 'V';
1177                         }
1178                         $type = 'N';
1179
1180                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1181                         print "COND($1)\n" if ($dbg_values > 1);
1182                         $av_pending = 'E';
1183                         $type = 'N';
1184
1185                 } elsif ($cur =~/^(case)/o) {
1186                         print "CASE($1)\n" if ($dbg_values > 1);
1187                         $av_pend_colon = 'C';
1188                         $type = 'N';
1189
1190                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1191                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1192                         $type = 'N';
1193
1194                 } elsif ($cur =~ /^(\()/o) {
1195                         print "PAREN('$1')\n" if ($dbg_values > 1);
1196                         push(@av_paren_type, $av_pending);
1197                         $av_pending = '_';
1198                         $type = 'N';
1199
1200                 } elsif ($cur =~ /^(\))/o) {
1201                         my $new_type = pop(@av_paren_type);
1202                         if ($new_type ne '_') {
1203                                 $type = $new_type;
1204                                 print "PAREN('$1') -> $type\n"
1205                                                         if ($dbg_values > 1);
1206                         } else {
1207                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1208                         }
1209
1210                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1211                         print "FUNC($1)\n" if ($dbg_values > 1);
1212                         $type = 'V';
1213                         $av_pending = 'V';
1214
1215                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1216                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1217                                 $av_pend_colon = 'B';
1218                         } elsif ($type eq 'E') {
1219                                 $av_pend_colon = 'L';
1220                         }
1221                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1222                         $type = 'V';
1223
1224                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1225                         print "IDENT($1)\n" if ($dbg_values > 1);
1226                         $type = 'V';
1227
1228                 } elsif ($cur =~ /^($Assignment)/o) {
1229                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1230                         $type = 'N';
1231
1232                 } elsif ($cur =~/^(;|{|})/) {
1233                         print "END($1)\n" if ($dbg_values > 1);
1234                         $type = 'E';
1235                         $av_pend_colon = 'O';
1236
1237                 } elsif ($cur =~/^(,)/) {
1238                         print "COMMA($1)\n" if ($dbg_values > 1);
1239                         $type = 'C';
1240
1241                 } elsif ($cur =~ /^(\?)/o) {
1242                         print "QUESTION($1)\n" if ($dbg_values > 1);
1243                         $type = 'N';
1244
1245                 } elsif ($cur =~ /^(:)/o) {
1246                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1247
1248                         substr($var, length($res), 1, $av_pend_colon);
1249                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1250                                 $type = 'E';
1251                         } else {
1252                                 $type = 'N';
1253                         }
1254                         $av_pend_colon = 'O';
1255
1256                 } elsif ($cur =~ /^(\[)/o) {
1257                         print "CLOSE($1)\n" if ($dbg_values > 1);
1258                         $type = 'N';
1259
1260                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1261                         my $variant;
1262
1263                         print "OPV($1)\n" if ($dbg_values > 1);
1264                         if ($type eq 'V') {
1265                                 $variant = 'B';
1266                         } else {
1267                                 $variant = 'U';
1268                         }
1269
1270                         substr($var, length($res), 1, $variant);
1271                         $type = 'N';
1272
1273                 } elsif ($cur =~ /^($Operators)/o) {
1274                         print "OP($1)\n" if ($dbg_values > 1);
1275                         if ($1 ne '++' && $1 ne '--') {
1276                                 $type = 'N';
1277                         }
1278
1279                 } elsif ($cur =~ /(^.)/o) {
1280                         print "C($1)\n" if ($dbg_values > 1);
1281                 }
1282                 if (defined $1) {
1283                         $cur = substr($cur, length($1));
1284                         $res .= $type x length($1);
1285                 }
1286         }
1287
1288         return ($res, $var);
1289 }
1290
1291 sub possible {
1292         my ($possible, $line) = @_;
1293         my $notPermitted = qr{(?:
1294                 ^(?:
1295                         $Modifier|
1296                         $Storage|
1297                         $Type|
1298                         DEFINE_\S+
1299                 )$|
1300                 ^(?:
1301                         goto|
1302                         return|
1303                         case|
1304                         else|
1305                         asm|__asm__|
1306                         do|
1307                         \#|
1308                         \#\#|
1309                 )(?:\s|$)|
1310                 ^(?:typedef|struct|enum)\b
1311             )}x;
1312         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1313         if ($possible !~ $notPermitted) {
1314                 # Check for modifiers.
1315                 $possible =~ s/\s*$Storage\s*//g;
1316                 $possible =~ s/\s*$Sparse\s*//g;
1317                 if ($possible =~ /^\s*$/) {
1318
1319                 } elsif ($possible =~ /\s/) {
1320                         $possible =~ s/\s*$Type\s*//g;
1321                         for my $modifier (split(' ', $possible)) {
1322                                 if ($modifier !~ $notPermitted) {
1323                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1324                                         push(@modifierList, $modifier);
1325                                 }
1326                         }
1327
1328                 } else {
1329                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1330                         push(@typeList, $possible);
1331                 }
1332                 build_types();
1333         } else {
1334                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1335         }
1336 }
1337
1338 my $prefix = '';
1339
1340 sub show_type {
1341        return !defined $ignore_type{$_[0]};
1342 }
1343
1344 sub report {
1345         if (!show_type($_[1]) ||
1346             (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1347                 return 0;
1348         }
1349         my $line;
1350         if ($show_types) {
1351                 $line = "$prefix$_[0]:$_[1]: $_[2]\n";
1352         } else {
1353                 $line = "$prefix$_[0]: $_[2]\n";
1354         }
1355         $line = (split('\n', $line))[0] . "\n" if ($terse);
1356
1357         push(our @report, $line);
1358
1359         return 1;
1360 }
1361 sub report_dump {
1362         our @report;
1363 }
1364
1365 sub ERROR {
1366         if (report("ERROR", $_[0], $_[1])) {
1367                 our $clean = 0;
1368                 our $cnt_error++;
1369         }
1370 }
1371 sub WARN {
1372         if (report("WARNING", $_[0], $_[1])) {
1373                 our $clean = 0;
1374                 our $cnt_warn++;
1375         }
1376 }
1377 sub CHK {
1378         if ($check && report("CHECK", $_[0], $_[1])) {
1379                 our $clean = 0;
1380                 our $cnt_chk++;
1381         }
1382 }
1383
1384 sub check_absolute_file {
1385         my ($absolute, $herecurr) = @_;
1386         my $file = $absolute;
1387
1388         ##print "absolute<$absolute>\n";
1389
1390         # See if any suffix of this path is a path within the tree.
1391         while ($file =~ s@^[^/]*/@@) {
1392                 if (-f "$root/$file") {
1393                         ##print "file<$file>\n";
1394                         last;
1395                 }
1396         }
1397         if (! -f _)  {
1398                 return 0;
1399         }
1400
1401         # It is, so see if the prefix is acceptable.
1402         my $prefix = $absolute;
1403         substr($prefix, -length($file)) = '';
1404
1405         ##print "prefix<$prefix>\n";
1406         if ($prefix ne ".../") {
1407                 WARN("USE_RELATIVE_PATH",
1408                      "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1409         }
1410 }
1411
1412 sub process {
1413         my $filename = shift;
1414
1415         my $linenr=0;
1416         my $prevline="";
1417         my $prevrawline="";
1418         my $stashline="";
1419         my $stashrawline="";
1420
1421         my $length;
1422         my $indent;
1423         my $previndent=0;
1424         my $stashindent=0;
1425
1426         our $clean = 1;
1427         my $signoff = 0;
1428         my $is_patch = 0;
1429
1430         my $in_header_lines = 1;
1431         my $in_commit_log = 0;          #Scanning lines before patch
1432
1433         our @report = ();
1434         our $cnt_lines = 0;
1435         our $cnt_error = 0;
1436         our $cnt_warn = 0;
1437         our $cnt_chk = 0;
1438
1439         # Trace the real file/line as we go.
1440         my $realfile = '';
1441         my $realline = 0;
1442         my $realcnt = 0;
1443         my $here = '';
1444         my $in_comment = 0;
1445         my $comment_edge = 0;
1446         my $first_line = 0;
1447         my $p1_prefix = '';
1448
1449         my $prev_values = 'E';
1450
1451         # suppression flags
1452         my %suppress_ifbraces;
1453         my %suppress_whiletrailers;
1454         my %suppress_export;
1455         my $suppress_statement = 0;
1456
1457         # Pre-scan the patch sanitizing the lines.
1458         # Pre-scan the patch looking for any __setup documentation.
1459         #
1460         my @setup_docs = ();
1461         my $setup_docs = 0;
1462
1463         sanitise_line_reset();
1464         my $line;
1465         foreach my $rawline (@rawlines) {
1466                 $linenr++;
1467                 $line = $rawline;
1468
1469                 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1470                         $setup_docs = 0;
1471                         if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1472                                 $setup_docs = 1;
1473                         }
1474                         #next;
1475                 }
1476                 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1477                         $realline=$1-1;
1478                         if (defined $2) {
1479                                 $realcnt=$3+1;
1480                         } else {
1481                                 $realcnt=1+1;
1482                         }
1483                         $in_comment = 0;
1484
1485                         # Guestimate if this is a continuing comment.  Run
1486                         # the context looking for a comment "edge".  If this
1487                         # edge is a close comment then we must be in a comment
1488                         # at context start.
1489                         my $edge;
1490                         my $cnt = $realcnt;
1491                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1492                                 next if (defined $rawlines[$ln - 1] &&
1493                                          $rawlines[$ln - 1] =~ /^-/);
1494                                 $cnt--;
1495                                 #print "RAW<$rawlines[$ln - 1]>\n";
1496                                 last if (!defined $rawlines[$ln - 1]);
1497                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1498                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1499                                         ($edge) = $1;
1500                                         last;
1501                                 }
1502                         }
1503                         if (defined $edge && $edge eq '*/') {
1504                                 $in_comment = 1;
1505                         }
1506
1507                         # Guestimate if this is a continuing comment.  If this
1508                         # is the start of a diff block and this line starts
1509                         # ' *' then it is very likely a comment.
1510                         if (!defined $edge &&
1511                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1512                         {
1513                                 $in_comment = 1;
1514                         }
1515
1516                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1517                         sanitise_line_reset($in_comment);
1518
1519                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1520                         # Standardise the strings and chars within the input to
1521                         # simplify matching -- only bother with positive lines.
1522                         $line = sanitise_line($rawline);
1523                 }
1524                 push(@lines, $line);
1525
1526                 if ($realcnt > 1) {
1527                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
1528                 } else {
1529                         $realcnt = 0;
1530                 }
1531
1532                 #print "==>$rawline\n";
1533                 #print "-->$line\n";
1534
1535                 if ($setup_docs && $line =~ /^\+/) {
1536                         push(@setup_docs, $line);
1537                 }
1538         }
1539
1540         $prefix = '';
1541
1542         $realcnt = 0;
1543         $linenr = 0;
1544         foreach my $line (@lines) {
1545                 $linenr++;
1546
1547                 my $rawline = $rawlines[$linenr - 1];
1548
1549 #extract the line range in the file after the patch is applied
1550                 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1551                         $is_patch = 1;
1552                         $first_line = $linenr + 1;
1553                         $realline=$1-1;
1554                         if (defined $2) {
1555                                 $realcnt=$3+1;
1556                         } else {
1557                                 $realcnt=1+1;
1558                         }
1559                         annotate_reset();
1560                         $prev_values = 'E';
1561
1562                         %suppress_ifbraces = ();
1563                         %suppress_whiletrailers = ();
1564                         %suppress_export = ();
1565                         $suppress_statement = 0;
1566                         next;
1567
1568 # track the line number as we move through the hunk, note that
1569 # new versions of GNU diff omit the leading space on completely
1570 # blank context lines so we need to count that too.
1571                 } elsif ($line =~ /^( |\+|$)/) {
1572                         $realline++;
1573                         $realcnt-- if ($realcnt != 0);
1574
1575                         # Measure the line length and indent.
1576                         ($length, $indent) = line_stats($rawline);
1577
1578                         # Track the previous line.
1579                         ($prevline, $stashline) = ($stashline, $line);
1580                         ($previndent, $stashindent) = ($stashindent, $indent);
1581                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1582
1583                         #warn "line<$line>\n";
1584
1585                 } elsif ($realcnt == 1) {
1586                         $realcnt--;
1587                 }
1588
1589                 my $hunk_line = ($realcnt != 0);
1590
1591 #make up the handle for any error we report on this line
1592                 $prefix = "$filename:$realline: " if ($emacs && $file);
1593                 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1594
1595                 $here = "#$linenr: " if (!$file);
1596                 $here = "#$realline: " if ($file);
1597
1598                 # extract the filename as it passes
1599                 if ($line =~ /^diff --git.*?(\S+)$/) {
1600                         $realfile = $1;
1601                         $realfile =~ s@^([^/]*)/@@;
1602                         $in_commit_log = 0;
1603                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1604                         $realfile = $1;
1605                         $realfile =~ s@^([^/]*)/@@;
1606                         $in_commit_log = 0;
1607
1608                         $p1_prefix = $1;
1609                         if (!$file && $tree && $p1_prefix ne '' &&
1610                             -e "$root/$p1_prefix") {
1611                                 WARN("PATCH_PREFIX",
1612                                      "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1613                         }
1614
1615                         if ($realfile =~ m@^include/asm/@) {
1616                                 ERROR("MODIFIED_INCLUDE_ASM",
1617                                       "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1618                         }
1619                         next;
1620                 }
1621
1622                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1623
1624                 my $hereline = "$here\n$rawline\n";
1625                 my $herecurr = "$here\n$rawline\n";
1626                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1627
1628                 $cnt_lines++ if ($realcnt != 0);
1629
1630 # Check for incorrect file permissions
1631                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1632                         my $permhere = $here . "FILE: $realfile\n";
1633                         if ($realfile =~ /(Makefile|Kconfig|\.c|\.h|\.S|\.tmpl)$/) {
1634                                 ERROR("EXECUTE_PERMISSIONS",
1635                                       "do not set execute permissions for source files\n" . $permhere);
1636                         }
1637                 }
1638
1639 # Check the patch for a signoff:
1640                 if ($line =~ /^\s*signed-off-by:/i) {
1641                         $signoff++;
1642                         $in_commit_log = 0;
1643                 }
1644
1645 # Check signature styles
1646                 if (!$in_header_lines &&
1647                     $line =~ /^(\s*)($signature_tags)(\s*)(.*)/) {
1648                         my $space_before = $1;
1649                         my $sign_off = $2;
1650                         my $space_after = $3;
1651                         my $email = $4;
1652                         my $ucfirst_sign_off = ucfirst(lc($sign_off));
1653
1654                         if (defined $space_before && $space_before ne "") {
1655                                 WARN("BAD_SIGN_OFF",
1656                                      "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr);
1657                         }
1658                         if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1659                                 WARN("BAD_SIGN_OFF",
1660                                      "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr);
1661                         }
1662                         if (!defined $space_after || $space_after ne " ") {
1663                                 WARN("BAD_SIGN_OFF",
1664                                      "Use a single space after $ucfirst_sign_off\n" . $herecurr);
1665                         }
1666
1667                         my ($email_name, $email_address, $comment) = parse_email($email);
1668                         my $suggested_email = format_email(($email_name, $email_address));
1669                         if ($suggested_email eq "") {
1670                                 ERROR("BAD_SIGN_OFF",
1671                                       "Unrecognized email address: '$email'\n" . $herecurr);
1672                         } else {
1673                                 my $dequoted = $suggested_email;
1674                                 $dequoted =~ s/^"//;
1675                                 $dequoted =~ s/" </ </;
1676                                 # Don't force email to have quotes
1677                                 # Allow just an angle bracketed address
1678                                 if ("$dequoted$comment" ne $email &&
1679                                     "<$email_address>$comment" ne $email &&
1680                                     "$suggested_email$comment" ne $email) {
1681                                         WARN("BAD_SIGN_OFF",
1682                                              "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1683                                 }
1684                         }
1685                 }
1686
1687 # Check for wrappage within a valid hunk of the file
1688                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1689                         ERROR("CORRUPTED_PATCH",
1690                               "patch seems to be corrupt (line wrapped?)\n" .
1691                                 $herecurr) if (!$emitted_corrupt++);
1692                 }
1693
1694 # Check for absolute kernel paths.
1695                 if ($tree) {
1696                         while ($line =~ m{(?:^|\s)(/\S*)}g) {
1697                                 my $file = $1;
1698
1699                                 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1700                                     check_absolute_file($1, $herecurr)) {
1701                                         #
1702                                 } else {
1703                                         check_absolute_file($file, $herecurr);
1704                                 }
1705                         }
1706                 }
1707
1708 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1709                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1710                     $rawline !~ m/^$UTF8*$/) {
1711                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1712
1713                         my $blank = copy_spacing($rawline);
1714                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1715                         my $hereptr = "$hereline$ptr\n";
1716
1717                         CHK("INVALID_UTF8",
1718                             "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1719                 }
1720
1721 # Check if it's the start of a commit log
1722 # (not a header line and we haven't seen the patch filename)
1723                 if ($in_header_lines && $realfile =~ /^$/ &&
1724                     $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1725                         $in_header_lines = 0;
1726                         $in_commit_log = 1;
1727                 }
1728
1729 # Still not yet in a patch, check for any UTF-8
1730                 if ($in_commit_log && $realfile =~ /^$/ &&
1731                     $rawline =~ /$NON_ASCII_UTF8/) {
1732                         CHK("UTF8_BEFORE_PATCH",
1733                             "8-bit UTF-8 used in possible commit log\n" . $herecurr);
1734                 }
1735
1736 # ignore non-hunk lines and lines being removed
1737                 next if (!$hunk_line || $line =~ /^-/);
1738
1739 #trailing whitespace
1740                 if ($line =~ /^\+.*\015/) {
1741                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1742                         ERROR("DOS_LINE_ENDINGS",
1743                               "DOS line endings\n" . $herevet);
1744
1745                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1746                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1747                         ERROR("TRAILING_WHITESPACE",
1748                               "trailing whitespace\n" . $herevet);
1749                         $rpt_cleaners = 1;
1750                 }
1751
1752 # check for Kconfig help text having a real description
1753 # Only applies when adding the entry originally, after that we do not have
1754 # sufficient context to determine whether it is indeed long enough.
1755                 if ($realfile =~ /Kconfig/ &&
1756                     $line =~ /.\s*config\s+/) {
1757                         my $length = 0;
1758                         my $cnt = $realcnt;
1759                         my $ln = $linenr + 1;
1760                         my $f;
1761                         my $is_start = 0;
1762                         my $is_end = 0;
1763                         for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
1764                                 $f = $lines[$ln - 1];
1765                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
1766                                 $is_end = $lines[$ln - 1] =~ /^\+/;
1767
1768                                 next if ($f =~ /^-/);
1769
1770                                 if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
1771                                         $is_start = 1;
1772                                 } elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
1773                                         $length = -1;
1774                                 }
1775
1776                                 $f =~ s/^.//;
1777                                 $f =~ s/#.*//;
1778                                 $f =~ s/^\s+//;
1779                                 next if ($f =~ /^$/);
1780                                 if ($f =~ /^\s*config\s/) {
1781                                         $is_end = 1;
1782                                         last;
1783                                 }
1784                                 $length++;
1785                         }
1786                         WARN("CONFIG_DESCRIPTION",
1787                              "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
1788                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
1789                 }
1790
1791                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
1792                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
1793                         my $flag = $1;
1794                         my $replacement = {
1795                                 'EXTRA_AFLAGS' =>   'asflags-y',
1796                                 'EXTRA_CFLAGS' =>   'ccflags-y',
1797                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
1798                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
1799                         };
1800
1801                         WARN("DEPRECATED_VARIABLE",
1802                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
1803                 }
1804
1805 # check we are in a valid source file if not then ignore this hunk
1806                 next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
1807
1808 #80 column limit
1809                 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
1810                     $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
1811                     !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
1812                     $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1813                     $length > 80)
1814                 {
1815                         WARN("LONG_LINE",
1816                              "line over 80 characters\n" . $herecurr);
1817                 }
1818
1819 # check for spaces before a quoted newline
1820                 if ($rawline =~ /^.*\".*\s\\n/) {
1821                         WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
1822                              "unnecessary whitespace before a quoted newline\n" . $herecurr);
1823                 }
1824
1825 # check for adding lines without a newline.
1826                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1827                         WARN("MISSING_EOF_NEWLINE",
1828                              "adding a line without newline at end of file\n" . $herecurr);
1829                 }
1830
1831 # Blackfin: use hi/lo macros
1832                 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
1833                         if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
1834                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
1835                                 ERROR("LO_MACRO",
1836                                       "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
1837                         }
1838                         if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
1839                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
1840                                 ERROR("HI_MACRO",
1841                                       "use the HI() macro, not (... >> 16)\n" . $herevet);
1842                         }
1843                 }
1844
1845 # check we are in a valid source file C, perl or bash script
1846 # if not then ignore this hunk
1847                 next if ($realfile !~ /\.(h|c|pl|sh)$/);
1848
1849 # at the beginning of a line any tabs must come first and anything
1850 # more than 8 must use tabs.
1851                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
1852                     $rawline =~ /^\+\s*        \s*/) {
1853                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1854                         ERROR("CODE_INDENT",
1855                               "code indent should use tabs where possible\n" . $herevet);
1856                         $rpt_cleaners = 1;
1857                 }
1858
1859 # check for space before tabs.
1860                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
1861                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1862                         WARN("SPACE_BEFORE_TAB",
1863                              "please, no space before tabs\n" . $herevet);
1864                 }
1865
1866 # check for spaces at the beginning of a line.
1867 # Exceptions:
1868 #  1) within comments
1869 #  2) indented preprocessor commands
1870 #  3) hanging labels
1871                 if ($rawline =~ /^\+ / && $line !~ /\+ *(?:$;|#|$Ident:)/)  {
1872                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1873                         WARN("LEADING_SPACE",
1874                              "please, no spaces at the start of a line\n" . $herevet);
1875                 }
1876
1877 # check we are in a valid C source file if not then ignore this hunk
1878                 next if ($realfile !~ /\.(h|c)$/);
1879
1880 # check for RCS/CVS revision markers
1881                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
1882                         WARN("CVS_KEYWORD",
1883                              "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1884                 }
1885
1886 # Blackfin: don't use __builtin_bfin_[cs]sync
1887                 if ($line =~ /__builtin_bfin_csync/) {
1888                         my $herevet = "$here\n" . cat_vet($line) . "\n";
1889                         ERROR("CSYNC",
1890                               "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
1891                 }
1892                 if ($line =~ /__builtin_bfin_ssync/) {
1893                         my $herevet = "$here\n" . cat_vet($line) . "\n";
1894                         ERROR("SSYNC",
1895                               "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
1896                 }
1897
1898 # Check for potential 'bare' types
1899                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1900                     $realline_next);
1901 #print "LINE<$line>\n";
1902                 if ($linenr >= $suppress_statement &&
1903                     $realcnt && $line =~ /.\s*\S/) {
1904                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1905                                 ctx_statement_block($linenr, $realcnt, 0);
1906                         $stat =~ s/\n./\n /g;
1907                         $cond =~ s/\n./\n /g;
1908
1909 #print "linenr<$linenr> <$stat>\n";
1910                         # If this statement has no statement boundaries within
1911                         # it there is no point in retrying a statement scan
1912                         # until we hit end of it.
1913                         my $frag = $stat; $frag =~ s/;+\s*$//;
1914                         if ($frag !~ /(?:{|;)/) {
1915 #print "skip<$line_nr_next>\n";
1916                                 $suppress_statement = $line_nr_next;
1917                         }
1918
1919                         # Find the real next line.
1920                         $realline_next = $line_nr_next;
1921                         if (defined $realline_next &&
1922                             (!defined $lines[$realline_next - 1] ||
1923                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1924                                 $realline_next++;
1925                         }
1926
1927                         my $s = $stat;
1928                         $s =~ s/{.*$//s;
1929
1930                         # Ignore goto labels.
1931                         if ($s =~ /$Ident:\*$/s) {
1932
1933                         # Ignore functions being called
1934                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1935
1936                         } elsif ($s =~ /^.\s*else\b/s) {
1937
1938                         # declarations always start with types
1939                         } 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) {
1940                                 my $type = $1;
1941                                 $type =~ s/\s+/ /g;
1942                                 possible($type, "A:" . $s);
1943
1944                         # definitions in global scope can only start with types
1945                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1946                                 possible($1, "B:" . $s);
1947                         }
1948
1949                         # any (foo ... *) is a pointer cast, and foo is a type
1950                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1951                                 possible($1, "C:" . $s);
1952                         }
1953
1954                         # Check for any sort of function declaration.
1955                         # int foo(something bar, other baz);
1956                         # void (*store_gdt)(x86_descr_ptr *);
1957                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1958                                 my ($name_len) = length($1);
1959
1960                                 my $ctx = $s;
1961                                 substr($ctx, 0, $name_len + 1, '');
1962                                 $ctx =~ s/\)[^\)]*$//;
1963
1964                                 for my $arg (split(/\s*,\s*/, $ctx)) {
1965                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1966
1967                                                 possible($1, "D:" . $s);
1968                                         }
1969                                 }
1970                         }
1971
1972                 }
1973
1974 #
1975 # Checks which may be anchored in the context.
1976 #
1977
1978 # Check for switch () and associated case and default
1979 # statements should be at the same indent.
1980                 if ($line=~/\bswitch\s*\(.*\)/) {
1981                         my $err = '';
1982                         my $sep = '';
1983                         my @ctx = ctx_block_outer($linenr, $realcnt);
1984                         shift(@ctx);
1985                         for my $ctx (@ctx) {
1986                                 my ($clen, $cindent) = line_stats($ctx);
1987                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1988                                                         $indent != $cindent) {
1989                                         $err .= "$sep$ctx\n";
1990                                         $sep = '';
1991                                 } else {
1992                                         $sep = "[...]\n";
1993                                 }
1994                         }
1995                         if ($err ne '') {
1996                                 ERROR("SWITCH_CASE_INDENT_LEVEL",
1997                                       "switch and case should be at the same indent\n$hereline$err");
1998                         }
1999                 }
2000
2001 # if/while/etc brace do not go on next line, unless defining a do while loop,
2002 # or if that brace on the next line is for something else
2003                 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2004                         my $pre_ctx = "$1$2";
2005
2006                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2007
2008                         if ($line =~ /^\+\t{6,}/) {
2009                                 WARN("DEEP_INDENTATION",
2010                                      "Too many leading tabs - consider code refactoring\n" . $herecurr);
2011                         }
2012
2013                         my $ctx_cnt = $realcnt - $#ctx - 1;
2014                         my $ctx = join("\n", @ctx);
2015
2016                         my $ctx_ln = $linenr;
2017                         my $ctx_skip = $realcnt;
2018
2019                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2020                                         defined $lines[$ctx_ln - 1] &&
2021                                         $lines[$ctx_ln - 1] =~ /^-/)) {
2022                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2023                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2024                                 $ctx_ln++;
2025                         }
2026
2027                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2028                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2029
2030                         if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2031                                 ERROR("OPEN_BRACE",
2032                                       "that open brace { should be on the previous line\n" .
2033                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2034                         }
2035                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2036                             $ctx =~ /\)\s*\;\s*$/ &&
2037                             defined $lines[$ctx_ln - 1])
2038                         {
2039                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2040                                 if ($nindent > $indent) {
2041                                         WARN("TRAILING_SEMICOLON",
2042                                              "trailing semicolon indicates no statements, indent implies otherwise\n" .
2043                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2044                                 }
2045                         }
2046                 }
2047
2048 # Check relative indent for conditionals and blocks.
2049                 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2050                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2051                                 ctx_statement_block($linenr, $realcnt, 0)
2052                                         if (!defined $stat);
2053                         my ($s, $c) = ($stat, $cond);
2054
2055                         substr($s, 0, length($c), '');
2056
2057                         # Make sure we remove the line prefixes as we have
2058                         # none on the first line, and are going to readd them
2059                         # where necessary.
2060                         $s =~ s/\n./\n/gs;
2061
2062                         # Find out how long the conditional actually is.
2063                         my @newlines = ($c =~ /\n/gs);
2064                         my $cond_lines = 1 + $#newlines;
2065
2066                         # We want to check the first line inside the block
2067                         # starting at the end of the conditional, so remove:
2068                         #  1) any blank line termination
2069                         #  2) any opening brace { on end of the line
2070                         #  3) any do (...) {
2071                         my $continuation = 0;
2072                         my $check = 0;
2073                         $s =~ s/^.*\bdo\b//;
2074                         $s =~ s/^\s*{//;
2075                         if ($s =~ s/^\s*\\//) {
2076                                 $continuation = 1;
2077                         }
2078                         if ($s =~ s/^\s*?\n//) {
2079                                 $check = 1;
2080                                 $cond_lines++;
2081                         }
2082
2083                         # Also ignore a loop construct at the end of a
2084                         # preprocessor statement.
2085                         if (($prevline =~ /^.\s*#\s*define\s/ ||
2086                             $prevline =~ /\\\s*$/) && $continuation == 0) {
2087                                 $check = 0;
2088                         }
2089
2090                         my $cond_ptr = -1;
2091                         $continuation = 0;
2092                         while ($cond_ptr != $cond_lines) {
2093                                 $cond_ptr = $cond_lines;
2094
2095                                 # If we see an #else/#elif then the code
2096                                 # is not linear.
2097                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2098                                         $check = 0;
2099                                 }
2100
2101                                 # Ignore:
2102                                 #  1) blank lines, they should be at 0,
2103                                 #  2) preprocessor lines, and
2104                                 #  3) labels.
2105                                 if ($continuation ||
2106                                     $s =~ /^\s*?\n/ ||
2107                                     $s =~ /^\s*#\s*?/ ||
2108                                     $s =~ /^\s*$Ident\s*:/) {
2109                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2110                                         if ($s =~ s/^.*?\n//) {
2111                                                 $cond_lines++;
2112                                         }
2113                                 }
2114                         }
2115
2116                         my (undef, $sindent) = line_stats("+" . $s);
2117                         my $stat_real = raw_line($linenr, $cond_lines);
2118
2119                         # Check if either of these lines are modified, else
2120                         # this is not this patch's fault.
2121                         if (!defined($stat_real) ||
2122                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2123                                 $check = 0;
2124                         }
2125                         if (defined($stat_real) && $cond_lines > 1) {
2126                                 $stat_real = "[...]\n$stat_real";
2127                         }
2128
2129                         #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";
2130
2131                         if ($check && (($sindent % 8) != 0 ||
2132                             ($sindent <= $indent && $s ne ''))) {
2133                                 WARN("SUSPECT_CODE_INDENT",
2134                                      "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2135                         }
2136                 }
2137
2138                 # Track the 'values' across context and added lines.
2139                 my $opline = $line; $opline =~ s/^./ /;
2140                 my ($curr_values, $curr_vars) =
2141                                 annotate_values($opline . "\n", $prev_values);
2142                 $curr_values = $prev_values . $curr_values;
2143                 if ($dbg_values) {
2144                         my $outline = $opline; $outline =~ s/\t/ /g;
2145                         print "$linenr > .$outline\n";
2146                         print "$linenr > $curr_values\n";
2147                         print "$linenr >  $curr_vars\n";
2148                 }
2149                 $prev_values = substr($curr_values, -1);
2150
2151 #ignore lines not being added
2152                 if ($line=~/^[^\+]/) {next;}
2153
2154 # TEST: allow direct testing of the type matcher.
2155                 if ($dbg_type) {
2156                         if ($line =~ /^.\s*$Declare\s*$/) {
2157                                 ERROR("TEST_TYPE",
2158                                       "TEST: is type\n" . $herecurr);
2159                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2160                                 ERROR("TEST_NOT_TYPE",
2161                                       "TEST: is not type ($1 is)\n". $herecurr);
2162                         }
2163                         next;
2164                 }
2165 # TEST: allow direct testing of the attribute matcher.
2166                 if ($dbg_attr) {
2167                         if ($line =~ /^.\s*$Modifier\s*$/) {
2168                                 ERROR("TEST_ATTR",
2169                                       "TEST: is attr\n" . $herecurr);
2170                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2171                                 ERROR("TEST_NOT_ATTR",
2172                                       "TEST: is not attr ($1 is)\n". $herecurr);
2173                         }
2174                         next;
2175                 }
2176
2177 # check for initialisation to aggregates open brace on the next line
2178                 if ($line =~ /^.\s*{/ &&
2179                     $prevline =~ /(?:^|[^=])=\s*$/) {
2180                         ERROR("OPEN_BRACE",
2181                               "that open brace { should be on the previous line\n" . $hereprev);
2182                 }
2183
2184 #
2185 # Checks which are anchored on the added line.
2186 #
2187
2188 # check for malformed paths in #include statements (uses RAW line)
2189                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2190                         my $path = $1;
2191                         if ($path =~ m{//}) {
2192                                 ERROR("MALFORMED_INCLUDE",
2193                                       "malformed #include filename\n" .
2194                                         $herecurr);
2195                         }
2196                 }
2197
2198 # no C99 // comments
2199                 if ($line =~ m{//}) {
2200                         ERROR("C99_COMMENTS",
2201                               "do not use C99 // comments\n" . $herecurr);
2202                 }
2203                 # Remove C99 comments.
2204                 $line =~ s@//.*@@;
2205                 $opline =~ s@//.*@@;
2206
2207 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2208 # the whole statement.
2209 #print "APW <$lines[$realline_next - 1]>\n";
2210                 if (defined $realline_next &&
2211                     exists $lines[$realline_next - 1] &&
2212                     !defined $suppress_export{$realline_next} &&
2213                     ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2214                      $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2215                         # Handle definitions which produce identifiers with
2216                         # a prefix:
2217                         #   XXX(foo);
2218                         #   EXPORT_SYMBOL(something_foo);
2219                         my $name = $1;
2220                         if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2221                             $name =~ /^${Ident}_$2/) {
2222 #print "FOO C name<$name>\n";
2223                                 $suppress_export{$realline_next} = 1;
2224
2225                         } elsif ($stat !~ /(?:
2226                                 \n.}\s*$|
2227                                 ^.DEFINE_$Ident\(\Q$name\E\)|
2228                                 ^.DECLARE_$Ident\(\Q$name\E\)|
2229                                 ^.LIST_HEAD\(\Q$name\E\)|
2230                                 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2231                                 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2232                             )/x) {
2233 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2234                                 $suppress_export{$realline_next} = 2;
2235                         } else {
2236                                 $suppress_export{$realline_next} = 1;
2237                         }
2238                 }
2239                 if (!defined $suppress_export{$linenr} &&
2240                     $prevline =~ /^.\s*$/ &&
2241                     ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2242                      $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2243 #print "FOO B <$lines[$linenr - 1]>\n";
2244                         $suppress_export{$linenr} = 2;
2245                 }
2246                 if (defined $suppress_export{$linenr} &&
2247                     $suppress_export{$linenr} == 2) {
2248                         WARN("EXPORT_SYMBOL",
2249                              "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2250                 }
2251
2252 # check for global initialisers.
2253                 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
2254                         ERROR("GLOBAL_INITIALISERS",
2255                               "do not initialise globals to 0 or NULL\n" .
2256                                 $herecurr);
2257                 }
2258 # check for static initialisers.
2259                 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2260                         ERROR("INITIALISED_STATIC",
2261                               "do not initialise statics to 0 or NULL\n" .
2262                                 $herecurr);
2263                 }
2264
2265 # check for static const char * arrays.
2266                 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2267                         WARN("STATIC_CONST_CHAR_ARRAY",
2268                              "static const char * array should probably be static const char * const\n" .
2269                                 $herecurr);
2270                }
2271
2272 # check for static char foo[] = "bar" declarations.
2273                 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2274                         WARN("STATIC_CONST_CHAR_ARRAY",
2275                              "static char array declaration should probably be static const char\n" .
2276                                 $herecurr);
2277                }
2278
2279 # check for declarations of struct pci_device_id
2280                 if ($line =~ /\bstruct\s+pci_device_id\s+\w+\s*\[\s*\]\s*\=\s*\{/) {
2281                         WARN("DEFINE_PCI_DEVICE_TABLE",
2282                              "Use DEFINE_PCI_DEVICE_TABLE for struct pci_device_id\n" . $herecurr);
2283                 }
2284
2285 # check for new typedefs, only function parameters and sparse annotations
2286 # make sense.
2287                 if ($line =~ /\btypedef\s/ &&
2288                     $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2289                     $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2290                     $line !~ /\b$typeTypedefs\b/ &&
2291                     $line !~ /\b__bitwise(?:__|)\b/) {
2292                         WARN("NEW_TYPEDEFS",
2293                              "do not add new typedefs\n" . $herecurr);
2294                 }
2295
2296 # * goes on variable not on type
2297                 # (char*[ const])
2298                 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2299                         #print "AA<$1>\n";
2300                         my ($from, $to) = ($2, $2);
2301
2302                         # Should start with a space.
2303                         $to =~ s/^(\S)/ $1/;
2304                         # Should not end with a space.
2305                         $to =~ s/\s+$//;
2306                         # '*'s should not have spaces between.
2307                         while ($to =~ s/\*\s+\*/\*\*/) {
2308                         }
2309
2310                         #print "from<$from> to<$to>\n";
2311                         if ($from ne $to) {
2312                                 ERROR("POINTER_LOCATION",
2313                                       "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr);
2314                         }
2315                 }
2316                 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2317                         #print "BB<$1>\n";
2318                         my ($from, $to, $ident) = ($2, $2, $3);
2319
2320                         # Should start with a space.
2321                         $to =~ s/^(\S)/ $1/;
2322                         # Should not end with a space.
2323                         $to =~ s/\s+$//;
2324                         # '*'s should not have spaces between.
2325                         while ($to =~ s/\*\s+\*/\*\*/) {
2326                         }
2327                         # Modifiers should have spaces.
2328                         $to =~ s/(\b$Modifier$)/$1 /;
2329
2330                         #print "from<$from> to<$to> ident<$ident>\n";
2331                         if ($from ne $to && $ident !~ /^$Modifier$/) {
2332                                 ERROR("POINTER_LOCATION",
2333                                       "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr);
2334                         }
2335                 }
2336
2337 # # no BUG() or BUG_ON()
2338 #               if ($line =~ /\b(BUG|BUG_ON)\b/) {
2339 #                       print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2340 #                       print "$herecurr";
2341 #                       $clean = 0;
2342 #               }
2343
2344                 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2345                         WARN("LINUX_VERSION_CODE",
2346                              "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2347                 }
2348
2349 # check for uses of printk_ratelimit
2350                 if ($line =~ /\bprintk_ratelimit\s*\(/) {
2351                         WARN("PRINTK_RATELIMITED",
2352 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2353                 }
2354
2355 # printk should use KERN_* levels.  Note that follow on printk's on the
2356 # same line do not need a level, so we use the current block context
2357 # to try and find and validate the current printk.  In summary the current
2358 # printk includes all preceding printk's which have no newline on the end.
2359 # we assume the first bad printk is the one to report.
2360                 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2361                         my $ok = 0;
2362                         for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2363                                 #print "CHECK<$lines[$ln - 1]\n";
2364                                 # we have a preceding printk if it ends
2365                                 # with "\n" ignore it, else it is to blame
2366                                 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2367                                         if ($rawlines[$ln - 1] !~ m{\\n"}) {
2368                                                 $ok = 1;
2369                                         }
2370                                         last;
2371                                 }
2372                         }
2373                         if ($ok == 0) {
2374                                 WARN("PRINTK_WITHOUT_KERN_LEVEL",
2375                                      "printk() should include KERN_ facility level\n" . $herecurr);
2376                         }
2377                 }
2378
2379 # function brace can't be on same line, except for #defines of do while,
2380 # or if closed on same line
2381                 if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
2382                     !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
2383                         ERROR("OPEN_BRACE",
2384                               "open brace '{' following function declarations go on the next line\n" . $herecurr);
2385                 }
2386
2387 # open braces for enum, union and struct go on the same line.
2388                 if ($line =~ /^.\s*{/ &&
2389                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2390                         ERROR("OPEN_BRACE",
2391                               "open brace '{' following $1 go on the same line\n" . $hereprev);
2392                 }
2393
2394 # missing space after union, struct or enum definition
2395                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
2396                     WARN("SPACING",
2397                          "missing space after $1 definition\n" . $herecurr);
2398                 }
2399
2400 # check for spacing round square brackets; allowed:
2401 #  1. with a type on the left -- int [] a;
2402 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2403 #  3. inside a curly brace -- = { [0...10] = 5 }
2404                 while ($line =~ /(.*?\s)\[/g) {
2405                         my ($where, $prefix) = ($-[1], $1);
2406                         if ($prefix !~ /$Type\s+$/ &&
2407                             ($where != 0 || $prefix !~ /^.\s+$/) &&
2408                             $prefix !~ /{\s+$/) {
2409                                 ERROR("BRACKET_SPACE",
2410                                       "space prohibited before open square bracket '['\n" . $herecurr);
2411                         }
2412                 }
2413
2414 # check for spaces between functions and their parentheses.
2415                 while ($line =~ /($Ident)\s+\(/g) {
2416                         my $name = $1;
2417                         my $ctx_before = substr($line, 0, $-[1]);
2418                         my $ctx = "$ctx_before$name";
2419
2420                         # Ignore those directives where spaces _are_ permitted.
2421                         if ($name =~ /^(?:
2422                                 if|for|while|switch|return|case|
2423                                 volatile|__volatile__|
2424                                 __attribute__|format|__extension__|
2425                                 asm|__asm__)$/x)
2426                         {
2427
2428                         # cpp #define statements have non-optional spaces, ie
2429                         # if there is a space between the name and the open
2430                         # parenthesis it is simply not a parameter group.
2431                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2432
2433                         # cpp #elif statement condition may start with a (
2434                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2435
2436                         # If this whole things ends with a type its most
2437                         # likely a typedef for a function.
2438                         } elsif ($ctx =~ /$Type$/) {
2439
2440                         } else {
2441                                 WARN("SPACING",
2442                                      "space prohibited between function name and open parenthesis '('\n" . $herecurr);
2443                         }
2444                 }
2445 # Check operator spacing.
2446                 if (!($line=~/\#\s*include/)) {
2447                         my $ops = qr{
2448                                 <<=|>>=|<=|>=|==|!=|
2449                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2450                                 =>|->|<<|>>|<|>|=|!|~|
2451                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2452                                 \?|:
2453                         }x;
2454                         my @elements = split(/($ops|;)/, $opline);
2455                         my $off = 0;
2456
2457                         my $blank = copy_spacing($opline);
2458
2459                         for (my $n = 0; $n < $#elements; $n += 2) {
2460                                 $off += length($elements[$n]);
2461
2462                                 # Pick up the preceding and succeeding characters.
2463                                 my $ca = substr($opline, 0, $off);
2464                                 my $cc = '';
2465                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2466                                         $cc = substr($opline, $off + length($elements[$n + 1]));
2467                                 }
2468                                 my $cb = "$ca$;$cc";
2469
2470                                 my $a = '';
2471                                 $a = 'V' if ($elements[$n] ne '');
2472                                 $a = 'W' if ($elements[$n] =~ /\s$/);
2473                                 $a = 'C' if ($elements[$n] =~ /$;$/);
2474                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2475                                 $a = 'O' if ($elements[$n] eq '');
2476                                 $a = 'E' if ($ca =~ /^\s*$/);
2477
2478                                 my $op = $elements[$n + 1];
2479
2480                                 my $c = '';
2481                                 if (defined $elements[$n + 2]) {
2482                                         $c = 'V' if ($elements[$n + 2] ne '');
2483                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2484                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2485                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2486                                         $c = 'O' if ($elements[$n + 2] eq '');
2487                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2488                                 } else {
2489                                         $c = 'E';
2490                                 }
2491
2492                                 my $ctx = "${a}x${c}";
2493
2494                                 my $at = "(ctx:$ctx)";
2495
2496                                 my $ptr = substr($blank, 0, $off) . "^";
2497                                 my $hereptr = "$hereline$ptr\n";
2498
2499                                 # Pull out the value of this operator.
2500                                 my $op_type = substr($curr_values, $off + 1, 1);
2501
2502                                 # Get the full operator variant.
2503                                 my $opv = $op . substr($curr_vars, $off, 1);
2504
2505                                 # Ignore operators passed as parameters.
2506                                 if ($op_type ne 'V' &&
2507                                     $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2508
2509 #                               # Ignore comments
2510 #                               } elsif ($op =~ /^$;+$/) {
2511
2512                                 # ; should have either the end of line or a space or \ after it
2513                                 } elsif ($op eq ';') {
2514                                         if ($ctx !~ /.x[WEBC]/ &&
2515                                             $cc !~ /^\\/ && $cc !~ /^;/) {
2516                                                 ERROR("SPACING",
2517                                                       "space required after that '$op' $at\n" . $hereptr);
2518                                         }
2519
2520                                 # // is a comment
2521                                 } elsif ($op eq '//') {
2522
2523                                 # No spaces for:
2524                                 #   ->
2525                                 #   :   when part of a bitfield
2526                                 } elsif ($op eq '->' || $opv eq ':B') {
2527                                         if ($ctx =~ /Wx.|.xW/) {
2528                                                 ERROR("SPACING",
2529                                                       "spaces prohibited around that '$op' $at\n" . $hereptr);
2530                                         }
2531
2532                                 # , must have a space on the right.
2533                                 } elsif ($op eq ',') {
2534                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
2535                                                 ERROR("SPACING",
2536                                                       "space required after that '$op' $at\n" . $hereptr);
2537                                         }
2538
2539                                 # '*' as part of a type definition -- reported already.
2540                                 } elsif ($opv eq '*_') {
2541                                         #warn "'*' is part of type\n";
2542
2543                                 # unary operators should have a space before and
2544                                 # none after.  May be left adjacent to another
2545                                 # unary operator, or a cast
2546                                 } elsif ($op eq '!' || $op eq '~' ||
2547                                          $opv eq '*U' || $opv eq '-U' ||
2548                                          $opv eq '&U' || $opv eq '&&U') {
2549                                         if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2550                                                 ERROR("SPACING",
2551                                                       "space required before that '$op' $at\n" . $hereptr);
2552                                         }
2553                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2554                                                 # A unary '*' may be const
2555
2556                                         } elsif ($ctx =~ /.xW/) {
2557                                                 ERROR("SPACING",
2558                                                       "space prohibited after that '$op' $at\n" . $hereptr);
2559                                         }
2560
2561                                 # unary ++ and unary -- are allowed no space on one side.
2562                                 } elsif ($op eq '++' or $op eq '--') {
2563                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2564                                                 ERROR("SPACING",
2565                                                       "space required one side of that '$op' $at\n" . $hereptr);
2566                                         }
2567                                         if ($ctx =~ /Wx[BE]/ ||
2568                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2569                                                 ERROR("SPACING",
2570                                                       "space prohibited before that '$op' $at\n" . $hereptr);
2571                                         }
2572                                         if ($ctx =~ /ExW/) {
2573                                                 ERROR("SPACING",
2574                                                       "space prohibited after that '$op' $at\n" . $hereptr);
2575                                         }
2576
2577
2578                                 # << and >> may either have or not have spaces both sides
2579                                 } elsif ($op eq '<<' or $op eq '>>' or
2580                                          $op eq '&' or $op eq '^' or $op eq '|' or
2581                                          $op eq '+' or $op eq '-' or
2582                                          $op eq '*' or $op eq '/' or
2583                                          $op eq '%')
2584                                 {
2585                                         if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
2586                                                 ERROR("SPACING",
2587                                                       "need consistent spacing around '$op' $at\n" .
2588                                                         $hereptr);
2589                                         }
2590
2591                                 # A colon needs no spaces before when it is
2592                                 # terminating a case value or a label.
2593                                 } elsif ($opv eq ':C' || $opv eq ':L') {
2594                                         if ($ctx =~ /Wx./) {
2595                                                 ERROR("SPACING",
2596                                                       "space prohibited before that '$op' $at\n" . $hereptr);
2597                                         }
2598
2599                                 # All the others need spaces both sides.
2600                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2601                                         my $ok = 0;
2602
2603                                         # Ignore email addresses <foo@bar>
2604                                         if (($op eq '<' &&
2605                                              $cc =~ /^\S+\@\S+>/) ||
2606                                             ($op eq '>' &&
2607                                              $ca =~ /<\S+\@\S+$/))
2608                                         {
2609                                                 $ok = 1;
2610                                         }
2611
2612                                         # Ignore ?:
2613                                         if (($opv eq ':O' && $ca =~ /\?$/) ||
2614                                             ($op eq '?' && $cc =~ /^:/)) {
2615                                                 $ok = 1;
2616                                         }
2617
2618                                         if ($ok == 0) {
2619                                                 ERROR("SPACING",
2620                                                       "spaces required around that '$op' $at\n" . $hereptr);
2621                                         }
2622                                 }
2623                                 $off += length($elements[$n + 1]);
2624                         }
2625                 }
2626
2627 # check for multiple assignments
2628                 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
2629                         CHK("MULTIPLE_ASSIGNMENTS",
2630                             "multiple assignments should be avoided\n" . $herecurr);
2631                 }
2632
2633 ## # check for multiple declarations, allowing for a function declaration
2634 ## # continuation.
2635 ##              if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
2636 ##                  $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
2637 ##
2638 ##                      # Remove any bracketed sections to ensure we do not
2639 ##                      # falsly report the parameters of functions.
2640 ##                      my $ln = $line;
2641 ##                      while ($ln =~ s/\([^\(\)]*\)//g) {
2642 ##                      }
2643 ##                      if ($ln =~ /,/) {
2644 ##                              WARN("MULTIPLE_DECLARATION",
2645 ##                                   "declaring multiple variables together should be avoided\n" . $herecurr);
2646 ##                      }
2647 ##              }
2648
2649 #need space before brace following if, while, etc
2650                 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
2651                     $line =~ /do{/) {
2652                         ERROR("SPACING",
2653                               "space required before the open brace '{'\n" . $herecurr);
2654                 }
2655
2656 # closing brace should have a space following it when it has anything
2657 # on the line
2658                 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2659                         ERROR("SPACING",
2660                               "space required after that close brace '}'\n" . $herecurr);
2661                 }
2662
2663 # check spacing on square brackets
2664                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2665                         ERROR("SPACING",
2666                               "space prohibited after that open square bracket '['\n" . $herecurr);
2667                 }
2668                 if ($line =~ /\s\]/) {
2669                         ERROR("SPACING",
2670                               "space prohibited before that close square bracket ']'\n" . $herecurr);
2671                 }
2672
2673 # check spacing on parentheses
2674                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2675                     $line !~ /for\s*\(\s+;/) {
2676                         ERROR("SPACING",
2677                               "space prohibited after that open parenthesis '('\n" . $herecurr);
2678                 }
2679                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2680                     $line !~ /for\s*\(.*;\s+\)/ &&
2681                     $line !~ /:\s+\)/) {
2682                         ERROR("SPACING",
2683                               "space prohibited before that close parenthesis ')'\n" . $herecurr);
2684                 }
2685
2686 #goto labels aren't indented, allow a single space however
2687                 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
2688                    !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
2689                         WARN("INDENTED_LABEL",
2690                              "labels should not be indented\n" . $herecurr);
2691                 }
2692
2693 # Return is not a function.
2694                 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2695                         my $spacing = $1;
2696                         my $value = $2;
2697
2698                         # Flatten any parentheses
2699                         $value =~ s/\(/ \(/g;
2700                         $value =~ s/\)/\) /g;
2701                         while ($value =~ s/\[[^\[\]]*\]/1/ ||
2702                                $value !~ /(?:$Ident|-?$Constant)\s*
2703                                              $Compare\s*
2704                                              (?:$Ident|-?$Constant)/x &&
2705                                $value =~ s/\([^\(\)]*\)/1/) {
2706                         }
2707 #print "value<$value>\n";
2708                         if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2709                                 ERROR("RETURN_PARENTHESES",
2710                                       "return is not a function, parentheses are not required\n" . $herecurr);
2711
2712                         } elsif ($spacing !~ /\s+/) {
2713                                 ERROR("SPACING",
2714                                       "space required before the open parenthesis '('\n" . $herecurr);
2715                         }
2716                 }
2717 # Return of what appears to be an errno should normally be -'ve
2718                 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2719                         my $name = $1;
2720                         if ($name ne 'EOF' && $name ne 'ERROR') {
2721                                 WARN("USE_NEGATIVE_ERRNO",
2722                                      "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2723                         }
2724                 }
2725
2726 # Need a space before open parenthesis after if, while etc
2727                 if ($line=~/\b(if|while|for|switch)\(/) {
2728                         ERROR("SPACING", "space required before the open parenthesis '('\n" . $herecurr);
2729                 }
2730
2731 # Check for illegal assignment in if conditional -- and check for trailing
2732 # statements after the conditional.
2733                 if ($line =~ /do\s*(?!{)/) {
2734                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2735                                 ctx_statement_block($linenr, $realcnt, 0)
2736                                         if (!defined $stat);
2737                         my ($stat_next) = ctx_statement_block($line_nr_next,
2738                                                 $remain_next, $off_next);
2739                         $stat_next =~ s/\n./\n /g;
2740                         ##print "stat<$stat> stat_next<$stat_next>\n";
2741
2742                         if ($stat_next =~ /^\s*while\b/) {
2743                                 # If the statement carries leading newlines,
2744                                 # then count those as offsets.
2745                                 my ($whitespace) =
2746                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2747                                 my $offset =
2748                                         statement_rawlines($whitespace) - 1;
2749
2750                                 $suppress_whiletrailers{$line_nr_next +
2751                                                                 $offset} = 1;
2752                         }
2753                 }
2754                 if (!defined $suppress_whiletrailers{$linenr} &&
2755                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2756                         my ($s, $c) = ($stat, $cond);
2757
2758                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2759                                 ERROR("ASSIGN_IN_IF",
2760                                       "do not use assignment in if condition\n" . $herecurr);
2761                         }
2762
2763                         # Find out what is on the end of the line after the
2764                         # conditional.
2765                         substr($s, 0, length($c), '');
2766                         $s =~ s/\n.*//g;
2767                         $s =~ s/$;//g;  # Remove any comments
2768                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2769                             $c !~ /}\s*while\s*/)
2770                         {
2771                                 # Find out how long the conditional actually is.
2772                                 my @newlines = ($c =~ /\n/gs);
2773                                 my $cond_lines = 1 + $#newlines;
2774                                 my $stat_real = '';
2775
2776                                 $stat_real = raw_line($linenr, $cond_lines)
2777                                                         . "\n" if ($cond_lines);
2778                                 if (defined($stat_real) && $cond_lines > 1) {
2779                                         $stat_real = "[...]\n$stat_real";
2780                                 }
2781
2782                                 ERROR("TRAILING_STATEMENTS",
2783                                       "trailing statements should be on next line\n" . $herecurr . $stat_real);
2784                         }
2785                 }
2786
2787 # Check for bitwise tests written as boolean
2788                 if ($line =~ /
2789                         (?:
2790                                 (?:\[|\(|\&\&|\|\|)
2791                                 \s*0[xX][0-9]+\s*
2792                                 (?:\&\&|\|\|)
2793                         |
2794                                 (?:\&\&|\|\|)
2795                                 \s*0[xX][0-9]+\s*
2796                                 (?:\&\&|\|\||\)|\])
2797                         )/x)
2798                 {
2799                         WARN("HEXADECIMAL_BOOLEAN_TEST",
2800                              "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2801                 }
2802
2803 # if and else should not have general statements after it
2804                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2805                         my $s = $1;
2806                         $s =~ s/$;//g;  # Remove any comments
2807                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2808                                 ERROR("TRAILING_STATEMENTS",
2809                                       "trailing statements should be on next line\n" . $herecurr);
2810                         }
2811                 }
2812 # if should not continue a brace
2813                 if ($line =~ /}\s*if\b/) {
2814                         ERROR("TRAILING_STATEMENTS",
2815                               "trailing statements should be on next line\n" .
2816                                 $herecurr);
2817                 }
2818 # case and default should not have general statements after them
2819                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2820                     $line !~ /\G(?:
2821                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2822                         \s*return\s+
2823                     )/xg)
2824                 {
2825                         ERROR("TRAILING_STATEMENTS",
2826                               "trailing statements should be on next line\n" . $herecurr);
2827                 }
2828
2829                 # Check for }<nl>else {, these must be at the same
2830                 # indent level to be relevant to each other.
2831                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2832                                                 $previndent == $indent) {
2833                         ERROR("ELSE_AFTER_BRACE",
2834                               "else should follow close brace '}'\n" . $hereprev);
2835                 }
2836
2837                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2838                                                 $previndent == $indent) {
2839                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2840
2841                         # Find out what is on the end of the line after the
2842                         # conditional.
2843                         substr($s, 0, length($c), '');
2844                         $s =~ s/\n.*//g;
2845
2846                         if ($s =~ /^\s*;/) {
2847                                 ERROR("WHILE_AFTER_BRACE",
2848                                       "while should follow close brace '}'\n" . $hereprev);
2849                         }
2850                 }
2851
2852 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2853 #               if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2854 #                   print "No studly caps, use _\n";
2855 #                   print "$herecurr";
2856 #                   $clean = 0;
2857 #               }
2858
2859 #no spaces allowed after \ in define
2860                 if ($line=~/\#\s*define.*\\\s$/) {
2861                         WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
2862                              "Whitepspace after \\ makes next lines useless\n" . $herecurr);
2863                 }
2864
2865 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
2866                 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
2867                         my $file = "$1.h";
2868                         my $checkfile = "include/linux/$file";
2869                         if (-f "$root/$checkfile" &&
2870                             $realfile ne $checkfile &&
2871                             $1 !~ /$allowed_asm_includes/)
2872                         {