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