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