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