]> git.karo-electronics.de Git - karo-tx-linux.git/blob - scripts/checkpatch.pl
checkpatch: make sure a commit reference description uses parentheses
[karo-tx-linux.git] / 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 use strict;
9 use POSIX;
10 use File::Basename;
11 use Cwd 'abs_path';
12
13 my $P = $0;
14 my $D = dirname(abs_path($P));
15
16 my $V = '0.32';
17
18 use Getopt::Long qw(:config no_auto_abbrev);
19
20 my $quiet = 0;
21 my $tree = 1;
22 my $chk_signoff = 1;
23 my $chk_patch = 1;
24 my $tst_only;
25 my $emacs = 0;
26 my $terse = 0;
27 my $file = 0;
28 my $check = 0;
29 my $check_orig = 0;
30 my $summary = 1;
31 my $mailback = 0;
32 my $summary_file = 0;
33 my $show_types = 0;
34 my $fix = 0;
35 my $fix_inplace = 0;
36 my $root;
37 my %debug;
38 my %camelcase = ();
39 my %use_type = ();
40 my @use = ();
41 my %ignore_type = ();
42 my @ignore = ();
43 my $help = 0;
44 my $configuration_file = ".checkpatch.conf";
45 my $max_line_length = 80;
46 my $ignore_perl_version = 0;
47 my $minimum_perl_version = 5.10.0;
48 my $min_conf_desc_length = 4;
49 my $spelling_file = "$D/spelling.txt";
50
51 sub help {
52         my ($exitcode) = @_;
53
54         print << "EOM";
55 Usage: $P [OPTION]... [FILE]...
56 Version: $V
57
58 Options:
59   -q, --quiet                quiet
60   --no-tree                  run without a kernel tree
61   --no-signoff               do not check for 'Signed-off-by' line
62   --patch                    treat FILE as patchfile (default)
63   --emacs                    emacs compile window format
64   --terse                    one line per report
65   -f, --file                 treat FILE as regular source file
66   --subjective, --strict     enable more subjective tests
67   --types TYPE(,TYPE2...)    show only these comma separated message types
68   --ignore TYPE(,TYPE2...)   ignore various comma separated message types
69   --max-line-length=n        set the maximum line length, if exceeded, warn
70   --min-conf-desc-length=n   set the min description length, if shorter, warn
71   --show-types               show the message "types" in the output
72   --root=PATH                PATH to the kernel tree root
73   --no-summary               suppress the per-file summary
74   --mailback                 only produce a report in case of warnings/errors
75   --summary-file             include the filename in summary
76   --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
77                              'values', 'possible', 'type', and 'attr' (default
78                              is all off)
79   --test-only=WORD           report only warnings/errors containing WORD
80                              literally
81   --fix                      EXPERIMENTAL - may create horrible results
82                              If correctable single-line errors exist, create
83                              "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84                              with potential errors corrected to the preferred
85                              checkpatch style
86   --fix-inplace              EXPERIMENTAL - may create horrible results
87                              Is the same as --fix, but overwrites the input
88                              file.  It's your fault if there's no backup or git
89   --ignore-perl-version      override checking of perl version.  expect
90                              runtime errors.
91   -h, --help, --version      display this help and exit
92
93 When FILE is - read standard input.
94 EOM
95
96         exit($exitcode);
97 }
98
99 my $conf = which_conf($configuration_file);
100 if (-f $conf) {
101         my @conf_args;
102         open(my $conffile, '<', "$conf")
103             or warn "$P: Can't find a readable $configuration_file file $!\n";
104
105         while (<$conffile>) {
106                 my $line = $_;
107
108                 $line =~ s/\s*\n?$//g;
109                 $line =~ s/^\s*//g;
110                 $line =~ s/\s+/ /g;
111
112                 next if ($line =~ m/^\s*#/);
113                 next if ($line =~ m/^\s*$/);
114
115                 my @words = split(" ", $line);
116                 foreach my $word (@words) {
117                         last if ($word =~ m/^#/);
118                         push (@conf_args, $word);
119                 }
120         }
121         close($conffile);
122         unshift(@ARGV, @conf_args) if @conf_args;
123 }
124
125 GetOptions(
126         'q|quiet+'      => \$quiet,
127         'tree!'         => \$tree,
128         'signoff!'      => \$chk_signoff,
129         'patch!'        => \$chk_patch,
130         'emacs!'        => \$emacs,
131         'terse!'        => \$terse,
132         'f|file!'       => \$file,
133         'subjective!'   => \$check,
134         'strict!'       => \$check,
135         'ignore=s'      => \@ignore,
136         'types=s'       => \@use,
137         'show-types!'   => \$show_types,
138         'max-line-length=i' => \$max_line_length,
139         'min-conf-desc-length=i' => \$min_conf_desc_length,
140         'root=s'        => \$root,
141         'summary!'      => \$summary,
142         'mailback!'     => \$mailback,
143         'summary-file!' => \$summary_file,
144         'fix!'          => \$fix,
145         'fix-inplace!'  => \$fix_inplace,
146         'ignore-perl-version!' => \$ignore_perl_version,
147         'debug=s'       => \%debug,
148         'test-only=s'   => \$tst_only,
149         'h|help'        => \$help,
150         'version'       => \$help
151 ) or help(1);
152
153 help(0) if ($help);
154
155 $fix = 1 if ($fix_inplace);
156 $check_orig = $check;
157
158 my $exit = 0;
159
160 if ($^V && $^V lt $minimum_perl_version) {
161         printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
162         if (!$ignore_perl_version) {
163                 exit(1);
164         }
165 }
166
167 if ($#ARGV < 0) {
168         print "$P: no input files\n";
169         exit(1);
170 }
171
172 sub hash_save_array_words {
173         my ($hashRef, $arrayRef) = @_;
174
175         my @array = split(/,/, join(',', @$arrayRef));
176         foreach my $word (@array) {
177                 $word =~ s/\s*\n?$//g;
178                 $word =~ s/^\s*//g;
179                 $word =~ s/\s+/ /g;
180                 $word =~ tr/[a-z]/[A-Z]/;
181
182                 next if ($word =~ m/^\s*#/);
183                 next if ($word =~ m/^\s*$/);
184
185                 $hashRef->{$word}++;
186         }
187 }
188
189 sub hash_show_words {
190         my ($hashRef, $prefix) = @_;
191
192         if ($quiet == 0 && keys %$hashRef) {
193                 print "NOTE: $prefix message types:";
194                 foreach my $word (sort keys %$hashRef) {
195                         print " $word";
196                 }
197                 print "\n\n";
198         }
199 }
200
201 hash_save_array_words(\%ignore_type, \@ignore);
202 hash_save_array_words(\%use_type, \@use);
203
204 my $dbg_values = 0;
205 my $dbg_possible = 0;
206 my $dbg_type = 0;
207 my $dbg_attr = 0;
208 for my $key (keys %debug) {
209         ## no critic
210         eval "\${dbg_$key} = '$debug{$key}';";
211         die "$@" if ($@);
212 }
213
214 my $rpt_cleaners = 0;
215
216 if ($terse) {
217         $emacs = 1;
218         $quiet++;
219 }
220
221 if ($tree) {
222         if (defined $root) {
223                 if (!top_of_kernel_tree($root)) {
224                         die "$P: $root: --root does not point at a valid tree\n";
225                 }
226         } else {
227                 if (top_of_kernel_tree('.')) {
228                         $root = '.';
229                 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
230                                                 top_of_kernel_tree($1)) {
231                         $root = $1;
232                 }
233         }
234
235         if (!defined $root) {
236                 print "Must be run from the top-level dir. of a kernel tree\n";
237                 exit(2);
238         }
239 }
240
241 my $emitted_corrupt = 0;
242
243 our $Ident      = qr{
244                         [A-Za-z_][A-Za-z\d_]*
245                         (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
246                 }x;
247 our $Storage    = qr{extern|static|asmlinkage};
248 our $Sparse     = qr{
249                         __user|
250                         __kernel|
251                         __force|
252                         __iomem|
253                         __must_check|
254                         __init_refok|
255                         __kprobes|
256                         __ref|
257                         __rcu
258                 }x;
259 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
260 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
261 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
262 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
263 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
264
265 # Notes to $Attribute:
266 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
267 our $Attribute  = qr{
268                         const|
269                         __percpu|
270                         __nocast|
271                         __safe|
272                         __bitwise__|
273                         __packed__|
274                         __packed2__|
275                         __naked|
276                         __maybe_unused|
277                         __always_unused|
278                         __noreturn|
279                         __used|
280                         __cold|
281                         __pure|
282                         __noclone|
283                         __deprecated|
284                         __read_mostly|
285                         __kprobes|
286                         $InitAttribute|
287                         ____cacheline_aligned|
288                         ____cacheline_aligned_in_smp|
289                         ____cacheline_internodealigned_in_smp|
290                         __weak
291                   }x;
292 our $Modifier;
293 our $Inline     = qr{inline|__always_inline|noinline|__inline|__inline__};
294 our $Member     = qr{->$Ident|\.$Ident|\[[^]]*\]};
295 our $Lval       = qr{$Ident(?:$Member)*};
296
297 our $Int_type   = qr{(?i)llu|ull|ll|lu|ul|l|u};
298 our $Binary     = qr{(?i)0b[01]+$Int_type?};
299 our $Hex        = qr{(?i)0x[0-9a-f]+$Int_type?};
300 our $Int        = qr{[0-9]+$Int_type?};
301 our $Octal      = qr{0[0-7]+$Int_type?};
302 our $String     = qr{"[X\t]*"};
303 our $Float_hex  = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
304 our $Float_dec  = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
305 our $Float_int  = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
306 our $Float      = qr{$Float_hex|$Float_dec|$Float_int};
307 our $Constant   = qr{$Float|$Binary|$Octal|$Hex|$Int};
308 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
309 our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
310 our $Arithmetic = qr{\+|-|\*|\/|%};
311 our $Operators  = qr{
312                         <=|>=|==|!=|
313                         =>|->|<<|>>|<|>|!|~|
314                         &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
315                   }x;
316
317 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
318
319 our $NonptrType;
320 our $NonptrTypeMisordered;
321 our $NonptrTypeWithAttr;
322 our $Type;
323 our $TypeMisordered;
324 our $Declare;
325 our $DeclareMisordered;
326
327 our $NON_ASCII_UTF8     = qr{
328         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
329         |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
330         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
331         |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
332         |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
333         | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
334         |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
335 }x;
336
337 our $UTF8       = qr{
338         [\x09\x0A\x0D\x20-\x7E]              # ASCII
339         | $NON_ASCII_UTF8
340 }x;
341
342 our $typeOtherOSTypedefs = qr{(?x:
343         u_(?:char|short|int|long) |          # bsd
344         u(?:nchar|short|int|long)            # sysv
345 )};
346
347 our $typeTypedefs = qr{(?x:
348         (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
349         atomic_t
350 )};
351
352 our $logFunctions = qr{(?x:
353         printk(?:_ratelimited|_once|)|
354         (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
355         WARN(?:_RATELIMIT|_ONCE|)|
356         panic|
357         MODULE_[A-Z_]+|
358         seq_vprintf|seq_printf|seq_puts
359 )};
360
361 our $signature_tags = qr{(?xi:
362         Signed-off-by:|
363         Acked-by:|
364         Tested-by:|
365         Reviewed-by:|
366         Reported-by:|
367         Suggested-by:|
368         To:|
369         Cc:
370 )};
371
372 our @typeListMisordered = (
373         qr{char\s+(?:un)?signed},
374         qr{int\s+(?:(?:un)?signed\s+)?short\s},
375         qr{int\s+short(?:\s+(?:un)?signed)},
376         qr{short\s+int(?:\s+(?:un)?signed)},
377         qr{(?:un)?signed\s+int\s+short},
378         qr{short\s+(?:un)?signed},
379         qr{long\s+int\s+(?:un)?signed},
380         qr{int\s+long\s+(?:un)?signed},
381         qr{long\s+(?:un)?signed\s+int},
382         qr{int\s+(?:un)?signed\s+long},
383         qr{int\s+(?:un)?signed},
384         qr{int\s+long\s+long\s+(?:un)?signed},
385         qr{long\s+long\s+int\s+(?:un)?signed},
386         qr{long\s+long\s+(?:un)?signed\s+int},
387         qr{long\s+long\s+(?:un)?signed},
388         qr{long\s+(?:un)?signed},
389 );
390
391 our @typeList = (
392         qr{void},
393         qr{(?:(?:un)?signed\s+)?char},
394         qr{(?:(?:un)?signed\s+)?short\s+int},
395         qr{(?:(?:un)?signed\s+)?short},
396         qr{(?:(?:un)?signed\s+)?int},
397         qr{(?:(?:un)?signed\s+)?long\s+int},
398         qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
399         qr{(?:(?:un)?signed\s+)?long\s+long},
400         qr{(?:(?:un)?signed\s+)?long},
401         qr{(?:un)?signed},
402         qr{float},
403         qr{double},
404         qr{bool},
405         qr{struct\s+$Ident},
406         qr{union\s+$Ident},
407         qr{enum\s+$Ident},
408         qr{${Ident}_t},
409         qr{${Ident}_handler},
410         qr{${Ident}_handler_fn},
411         @typeListMisordered,
412 );
413 our @typeListWithAttr = (
414         @typeList,
415         qr{struct\s+$InitAttribute\s+$Ident},
416         qr{union\s+$InitAttribute\s+$Ident},
417 );
418
419 our @modifierList = (
420         qr{fastcall},
421 );
422
423 our @mode_permission_funcs = (
424         ["module_param", 3],
425         ["module_param_(?:array|named|string)", 4],
426         ["module_param_array_named", 5],
427         ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
428         ["proc_create(?:_data|)", 2],
429         ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
430 );
431
432 #Create a search pattern for all these functions to speed up a loop below
433 our $mode_perms_search = "";
434 foreach my $entry (@mode_permission_funcs) {
435         $mode_perms_search .= '|' if ($mode_perms_search ne "");
436         $mode_perms_search .= $entry->[0];
437 }
438
439 our $allowed_asm_includes = qr{(?x:
440         irq|
441         memory|
442         time|
443         reboot
444 )};
445 # memory.h: ARM has a custom one
446
447 # Load common spelling mistakes and build regular expression list.
448 my $misspellings;
449 my %spelling_fix;
450
451 if (open(my $spelling, '<', $spelling_file)) {
452         my @spelling_list;
453         while (<$spelling>) {
454                 my $line = $_;
455
456                 $line =~ s/\s*\n?$//g;
457                 $line =~ s/^\s*//g;
458
459                 next if ($line =~ m/^\s*#/);
460                 next if ($line =~ m/^\s*$/);
461
462                 my ($suspect, $fix) = split(/\|\|/, $line);
463
464                 push(@spelling_list, $suspect);
465                 $spelling_fix{$suspect} = $fix;
466         }
467         close($spelling);
468         $misspellings = join("|", @spelling_list);
469 } else {
470         warn "No typos will be found - file '$spelling_file': $!\n";
471 }
472
473 sub build_types {
474         my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
475         my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
476         my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
477         my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
478         $Modifier       = qr{(?:$Attribute|$Sparse|$mods)};
479         $NonptrType     = qr{
480                         (?:$Modifier\s+|const\s+)*
481                         (?:
482                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
483                                 (?:$typeOtherOSTypedefs\b)|
484                                 (?:$typeTypedefs\b)|
485                                 (?:${all}\b)
486                         )
487                         (?:\s+$Modifier|\s+const)*
488                   }x;
489         $NonptrTypeMisordered   = qr{
490                         (?:$Modifier\s+|const\s+)*
491                         (?:
492                                 (?:${Misordered}\b)
493                         )
494                         (?:\s+$Modifier|\s+const)*
495                   }x;
496         $NonptrTypeWithAttr     = qr{
497                         (?:$Modifier\s+|const\s+)*
498                         (?:
499                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
500                                 (?:$typeTypedefs\b)|
501                                 (?:$typeOtherOSTypedefs\b)|
502                                 (?:${allWithAttr}\b)
503                         )
504                         (?:\s+$Modifier|\s+const)*
505                   }x;
506         $Type   = qr{
507                         $NonptrType
508                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
509                         (?:\s+$Inline|\s+$Modifier)*
510                   }x;
511         $TypeMisordered = qr{
512                         $NonptrTypeMisordered
513                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
514                         (?:\s+$Inline|\s+$Modifier)*
515                   }x;
516         $Declare        = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
517         $DeclareMisordered      = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
518 }
519 build_types();
520
521 our $Typecast   = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
522
523 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
524 # requires at least perl version v5.10.0
525 # Any use must be runtime checked with $^V
526
527 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
528 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
529 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
530
531 our $declaration_macros = qr{(?x:
532         (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
533         (?:$Storage\s+)?LIST_HEAD\s*\(|
534         (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
535 )};
536
537 sub deparenthesize {
538         my ($string) = @_;
539         return "" if (!defined($string));
540
541         while ($string =~ /^\s*\(.*\)\s*$/) {
542                 $string =~ s@^\s*\(\s*@@;
543                 $string =~ s@\s*\)\s*$@@;
544         }
545
546         $string =~ s@\s+@ @g;
547
548         return $string;
549 }
550
551 sub seed_camelcase_file {
552         my ($file) = @_;
553
554         return if (!(-f $file));
555
556         local $/;
557
558         open(my $include_file, '<', "$file")
559             or warn "$P: Can't read '$file' $!\n";
560         my $text = <$include_file>;
561         close($include_file);
562
563         my @lines = split('\n', $text);
564
565         foreach my $line (@lines) {
566                 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
567                 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
568                         $camelcase{$1} = 1;
569                 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
570                         $camelcase{$1} = 1;
571                 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
572                         $camelcase{$1} = 1;
573                 }
574         }
575 }
576
577 my $camelcase_seeded = 0;
578 sub seed_camelcase_includes {
579         return if ($camelcase_seeded);
580
581         my $files;
582         my $camelcase_cache = "";
583         my @include_files = ();
584
585         $camelcase_seeded = 1;
586
587         if (-e ".git") {
588                 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
589                 chomp $git_last_include_commit;
590                 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
591         } else {
592                 my $last_mod_date = 0;
593                 $files = `find $root/include -name "*.h"`;
594                 @include_files = split('\n', $files);
595                 foreach my $file (@include_files) {
596                         my $date = POSIX::strftime("%Y%m%d%H%M",
597                                                    localtime((stat $file)[9]));
598                         $last_mod_date = $date if ($last_mod_date < $date);
599                 }
600                 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
601         }
602
603         if ($camelcase_cache ne "" && -f $camelcase_cache) {
604                 open(my $camelcase_file, '<', "$camelcase_cache")
605                     or warn "$P: Can't read '$camelcase_cache' $!\n";
606                 while (<$camelcase_file>) {
607                         chomp;
608                         $camelcase{$_} = 1;
609                 }
610                 close($camelcase_file);
611
612                 return;
613         }
614
615         if (-e ".git") {
616                 $files = `git ls-files "include/*.h"`;
617                 @include_files = split('\n', $files);
618         }
619
620         foreach my $file (@include_files) {
621                 seed_camelcase_file($file);
622         }
623
624         if ($camelcase_cache ne "") {
625                 unlink glob ".checkpatch-camelcase.*";
626                 open(my $camelcase_file, '>', "$camelcase_cache")
627                     or warn "$P: Can't write '$camelcase_cache' $!\n";
628                 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
629                         print $camelcase_file ("$_\n");
630                 }
631                 close($camelcase_file);
632         }
633 }
634
635 sub git_commit_info {
636         my ($commit, $id, $desc) = @_;
637
638         return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
639
640         my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
641         $output =~ s/^\s*//gm;
642         my @lines = split("\n", $output);
643
644         return ($id, $desc) if ($#lines < 0);
645
646         if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
647 # Maybe one day convert this block of bash into something that returns
648 # all matching commit ids, but it's very slow...
649 #
650 #               echo "checking commits $1..."
651 #               git rev-list --remotes | grep -i "^$1" |
652 #               while read line ; do
653 #                   git log --format='%H %s' -1 $line |
654 #                   echo "commit $(cut -c 1-12,41-)"
655 #               done
656         } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
657         } else {
658                 $id = substr($lines[0], 0, 12);
659                 $desc = substr($lines[0], 41);
660         }
661
662         return ($id, $desc);
663 }
664
665 $chk_signoff = 0 if ($file);
666
667 my @rawlines = ();
668 my @lines = ();
669 my @fixed = ();
670 my @fixed_inserted = ();
671 my @fixed_deleted = ();
672 my $fixlinenr = -1;
673
674 my $vname;
675 for my $filename (@ARGV) {
676         my $FILE;
677         if ($file) {
678                 open($FILE, '-|', "diff -u /dev/null $filename") ||
679                         die "$P: $filename: diff failed - $!\n";
680         } elsif ($filename eq '-') {
681                 open($FILE, '<&STDIN');
682         } else {
683                 open($FILE, '<', "$filename") ||
684                         die "$P: $filename: open failed - $!\n";
685         }
686         if ($filename eq '-') {
687                 $vname = 'Your patch';
688         } else {
689                 $vname = $filename;
690         }
691         while (<$FILE>) {
692                 chomp;
693                 push(@rawlines, $_);
694         }
695         close($FILE);
696         if (!process($filename)) {
697                 $exit = 1;
698         }
699         @rawlines = ();
700         @lines = ();
701         @fixed = ();
702         @fixed_inserted = ();
703         @fixed_deleted = ();
704         $fixlinenr = -1;
705 }
706
707 exit($exit);
708
709 sub top_of_kernel_tree {
710         my ($root) = @_;
711
712         my @tree_check = (
713                 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
714                 "README", "Documentation", "arch", "include", "drivers",
715                 "fs", "init", "ipc", "kernel", "lib", "scripts",
716         );
717
718         foreach my $check (@tree_check) {
719                 if (! -e $root . '/' . $check) {
720                         return 0;
721                 }
722         }
723         return 1;
724 }
725
726 sub parse_email {
727         my ($formatted_email) = @_;
728
729         my $name = "";
730         my $address = "";
731         my $comment = "";
732
733         if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
734                 $name = $1;
735                 $address = $2;
736                 $comment = $3 if defined $3;
737         } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
738                 $address = $1;
739                 $comment = $2 if defined $2;
740         } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
741                 $address = $1;
742                 $comment = $2 if defined $2;
743                 $formatted_email =~ s/$address.*$//;
744                 $name = $formatted_email;
745                 $name = trim($name);
746                 $name =~ s/^\"|\"$//g;
747                 # If there's a name left after stripping spaces and
748                 # leading quotes, and the address doesn't have both
749                 # leading and trailing angle brackets, the address
750                 # is invalid. ie:
751                 #   "joe smith joe@smith.com" bad
752                 #   "joe smith <joe@smith.com" bad
753                 if ($name ne "" && $address !~ /^<[^>]+>$/) {
754                         $name = "";
755                         $address = "";
756                         $comment = "";
757                 }
758         }
759
760         $name = trim($name);
761         $name =~ s/^\"|\"$//g;
762         $address = trim($address);
763         $address =~ s/^\<|\>$//g;
764
765         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
766                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
767                 $name = "\"$name\"";
768         }
769
770         return ($name, $address, $comment);
771 }
772
773 sub format_email {
774         my ($name, $address) = @_;
775
776         my $formatted_email;
777
778         $name = trim($name);
779         $name =~ s/^\"|\"$//g;
780         $address = trim($address);
781
782         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
783                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
784                 $name = "\"$name\"";
785         }
786
787         if ("$name" eq "") {
788                 $formatted_email = "$address";
789         } else {
790                 $formatted_email = "$name <$address>";
791         }
792
793         return $formatted_email;
794 }
795
796 sub which {
797         my ($bin) = @_;
798
799         foreach my $path (split(/:/, $ENV{PATH})) {
800                 if (-e "$path/$bin") {
801                         return "$path/$bin";
802                 }
803         }
804
805         return "";
806 }
807
808 sub which_conf {
809         my ($conf) = @_;
810
811         foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
812                 if (-e "$path/$conf") {
813                         return "$path/$conf";
814                 }
815         }
816
817         return "";
818 }
819
820 sub expand_tabs {
821         my ($str) = @_;
822
823         my $res = '';
824         my $n = 0;
825         for my $c (split(//, $str)) {
826                 if ($c eq "\t") {
827                         $res .= ' ';
828                         $n++;
829                         for (; ($n % 8) != 0; $n++) {
830                                 $res .= ' ';
831                         }
832                         next;
833                 }
834                 $res .= $c;
835                 $n++;
836         }
837
838         return $res;
839 }
840 sub copy_spacing {
841         (my $res = shift) =~ tr/\t/ /c;
842         return $res;
843 }
844
845 sub line_stats {
846         my ($line) = @_;
847
848         # Drop the diff line leader and expand tabs
849         $line =~ s/^.//;
850         $line = expand_tabs($line);
851
852         # Pick the indent from the front of the line.
853         my ($white) = ($line =~ /^(\s*)/);
854
855         return (length($line), length($white));
856 }
857
858 my $sanitise_quote = '';
859
860 sub sanitise_line_reset {
861         my ($in_comment) = @_;
862
863         if ($in_comment) {
864                 $sanitise_quote = '*/';
865         } else {
866                 $sanitise_quote = '';
867         }
868 }
869 sub sanitise_line {
870         my ($line) = @_;
871
872         my $res = '';
873         my $l = '';
874
875         my $qlen = 0;
876         my $off = 0;
877         my $c;
878
879         # Always copy over the diff marker.
880         $res = substr($line, 0, 1);
881
882         for ($off = 1; $off < length($line); $off++) {
883                 $c = substr($line, $off, 1);
884
885                 # Comments we are wacking completly including the begin
886                 # and end, all to $;.
887                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
888                         $sanitise_quote = '*/';
889
890                         substr($res, $off, 2, "$;$;");
891                         $off++;
892                         next;
893                 }
894                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
895                         $sanitise_quote = '';
896                         substr($res, $off, 2, "$;$;");
897                         $off++;
898                         next;
899                 }
900                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
901                         $sanitise_quote = '//';
902
903                         substr($res, $off, 2, $sanitise_quote);
904                         $off++;
905                         next;
906                 }
907
908                 # A \ in a string means ignore the next character.
909                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
910                     $c eq "\\") {
911                         substr($res, $off, 2, 'XX');
912                         $off++;
913                         next;
914                 }
915                 # Regular quotes.
916                 if ($c eq "'" || $c eq '"') {
917                         if ($sanitise_quote eq '') {
918                                 $sanitise_quote = $c;
919
920                                 substr($res, $off, 1, $c);
921                                 next;
922                         } elsif ($sanitise_quote eq $c) {
923                                 $sanitise_quote = '';
924                         }
925                 }
926
927                 #print "c<$c> SQ<$sanitise_quote>\n";
928                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
929                         substr($res, $off, 1, $;);
930                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
931                         substr($res, $off, 1, $;);
932                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
933                         substr($res, $off, 1, 'X');
934                 } else {
935                         substr($res, $off, 1, $c);
936                 }
937         }
938
939         if ($sanitise_quote eq '//') {
940                 $sanitise_quote = '';
941         }
942
943         # The pathname on a #include may be surrounded by '<' and '>'.
944         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
945                 my $clean = 'X' x length($1);
946                 $res =~ s@\<.*\>@<$clean>@;
947
948         # The whole of a #error is a string.
949         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
950                 my $clean = 'X' x length($1);
951                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
952         }
953
954         return $res;
955 }
956
957 sub get_quoted_string {
958         my ($line, $rawline) = @_;
959
960         return "" if ($line !~ m/(\"[X\t]+\")/g);
961         return substr($rawline, $-[0], $+[0] - $-[0]);
962 }
963
964 sub ctx_statement_block {
965         my ($linenr, $remain, $off) = @_;
966         my $line = $linenr - 1;
967         my $blk = '';
968         my $soff = $off;
969         my $coff = $off - 1;
970         my $coff_set = 0;
971
972         my $loff = 0;
973
974         my $type = '';
975         my $level = 0;
976         my @stack = ();
977         my $p;
978         my $c;
979         my $len = 0;
980
981         my $remainder;
982         while (1) {
983                 @stack = (['', 0]) if ($#stack == -1);
984
985                 #warn "CSB: blk<$blk> remain<$remain>\n";
986                 # If we are about to drop off the end, pull in more
987                 # context.
988                 if ($off >= $len) {
989                         for (; $remain > 0; $line++) {
990                                 last if (!defined $lines[$line]);
991                                 next if ($lines[$line] =~ /^-/);
992                                 $remain--;
993                                 $loff = $len;
994                                 $blk .= $lines[$line] . "\n";
995                                 $len = length($blk);
996                                 $line++;
997                                 last;
998                         }
999                         # Bail if there is no further context.
1000                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1001                         if ($off >= $len) {
1002                                 last;
1003                         }
1004                         if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1005                                 $level++;
1006                                 $type = '#';
1007                         }
1008                 }
1009                 $p = $c;
1010                 $c = substr($blk, $off, 1);
1011                 $remainder = substr($blk, $off);
1012
1013                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1014
1015                 # Handle nested #if/#else.
1016                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1017                         push(@stack, [ $type, $level ]);
1018                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1019                         ($type, $level) = @{$stack[$#stack - 1]};
1020                 } elsif ($remainder =~ /^#\s*endif\b/) {
1021                         ($type, $level) = @{pop(@stack)};
1022                 }
1023
1024                 # Statement ends at the ';' or a close '}' at the
1025                 # outermost level.
1026                 if ($level == 0 && $c eq ';') {
1027                         last;
1028                 }
1029
1030                 # An else is really a conditional as long as its not else if
1031                 if ($level == 0 && $coff_set == 0 &&
1032                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1033                                 $remainder =~ /^(else)(?:\s|{)/ &&
1034                                 $remainder !~ /^else\s+if\b/) {
1035                         $coff = $off + length($1) - 1;
1036                         $coff_set = 1;
1037                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1038                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1039                 }
1040
1041                 if (($type eq '' || $type eq '(') && $c eq '(') {
1042                         $level++;
1043                         $type = '(';
1044                 }
1045                 if ($type eq '(' && $c eq ')') {
1046                         $level--;
1047                         $type = ($level != 0)? '(' : '';
1048
1049                         if ($level == 0 && $coff < $soff) {
1050                                 $coff = $off;
1051                                 $coff_set = 1;
1052                                 #warn "CSB: mark coff<$coff>\n";
1053                         }
1054                 }
1055                 if (($type eq '' || $type eq '{') && $c eq '{') {
1056                         $level++;
1057                         $type = '{';
1058                 }
1059                 if ($type eq '{' && $c eq '}') {
1060                         $level--;
1061                         $type = ($level != 0)? '{' : '';
1062
1063                         if ($level == 0) {
1064                                 if (substr($blk, $off + 1, 1) eq ';') {
1065                                         $off++;
1066                                 }
1067                                 last;
1068                         }
1069                 }
1070                 # Preprocessor commands end at the newline unless escaped.
1071                 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1072                         $level--;
1073                         $type = '';
1074                         $off++;
1075                         last;
1076                 }
1077                 $off++;
1078         }
1079         # We are truly at the end, so shuffle to the next line.
1080         if ($off == $len) {
1081                 $loff = $len + 1;
1082                 $line++;
1083                 $remain--;
1084         }
1085
1086         my $statement = substr($blk, $soff, $off - $soff + 1);
1087         my $condition = substr($blk, $soff, $coff - $soff + 1);
1088
1089         #warn "STATEMENT<$statement>\n";
1090         #warn "CONDITION<$condition>\n";
1091
1092         #print "coff<$coff> soff<$off> loff<$loff>\n";
1093
1094         return ($statement, $condition,
1095                         $line, $remain + 1, $off - $loff + 1, $level);
1096 }
1097
1098 sub statement_lines {
1099         my ($stmt) = @_;
1100
1101         # Strip the diff line prefixes and rip blank lines at start and end.
1102         $stmt =~ s/(^|\n)./$1/g;
1103         $stmt =~ s/^\s*//;
1104         $stmt =~ s/\s*$//;
1105
1106         my @stmt_lines = ($stmt =~ /\n/g);
1107
1108         return $#stmt_lines + 2;
1109 }
1110
1111 sub statement_rawlines {
1112         my ($stmt) = @_;
1113
1114         my @stmt_lines = ($stmt =~ /\n/g);
1115
1116         return $#stmt_lines + 2;
1117 }
1118
1119 sub statement_block_size {
1120         my ($stmt) = @_;
1121
1122         $stmt =~ s/(^|\n)./$1/g;
1123         $stmt =~ s/^\s*{//;
1124         $stmt =~ s/}\s*$//;
1125         $stmt =~ s/^\s*//;
1126         $stmt =~ s/\s*$//;
1127
1128         my @stmt_lines = ($stmt =~ /\n/g);
1129         my @stmt_statements = ($stmt =~ /;/g);
1130
1131         my $stmt_lines = $#stmt_lines + 2;
1132         my $stmt_statements = $#stmt_statements + 1;
1133
1134         if ($stmt_lines > $stmt_statements) {
1135                 return $stmt_lines;
1136         } else {
1137                 return $stmt_statements;
1138         }
1139 }
1140
1141 sub ctx_statement_full {
1142         my ($linenr, $remain, $off) = @_;
1143         my ($statement, $condition, $level);
1144
1145         my (@chunks);
1146
1147         # Grab the first conditional/block pair.
1148         ($statement, $condition, $linenr, $remain, $off, $level) =
1149                                 ctx_statement_block($linenr, $remain, $off);
1150         #print "F: c<$condition> s<$statement> remain<$remain>\n";
1151         push(@chunks, [ $condition, $statement ]);
1152         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1153                 return ($level, $linenr, @chunks);
1154         }
1155
1156         # Pull in the following conditional/block pairs and see if they
1157         # could continue the statement.
1158         for (;;) {
1159                 ($statement, $condition, $linenr, $remain, $off, $level) =
1160                                 ctx_statement_block($linenr, $remain, $off);
1161                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1162                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1163                 #print "C: push\n";
1164                 push(@chunks, [ $condition, $statement ]);
1165         }
1166
1167         return ($level, $linenr, @chunks);
1168 }
1169
1170 sub ctx_block_get {
1171         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1172         my $line;
1173         my $start = $linenr - 1;
1174         my $blk = '';
1175         my @o;
1176         my @c;
1177         my @res = ();
1178
1179         my $level = 0;
1180         my @stack = ($level);
1181         for ($line = $start; $remain > 0; $line++) {
1182                 next if ($rawlines[$line] =~ /^-/);
1183                 $remain--;
1184
1185                 $blk .= $rawlines[$line];
1186
1187                 # Handle nested #if/#else.
1188                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1189                         push(@stack, $level);
1190                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1191                         $level = $stack[$#stack - 1];
1192                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1193                         $level = pop(@stack);
1194                 }
1195
1196                 foreach my $c (split(//, $lines[$line])) {
1197                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
1198                         if ($off > 0) {
1199                                 $off--;
1200                                 next;
1201                         }
1202
1203                         if ($c eq $close && $level > 0) {
1204                                 $level--;
1205                                 last if ($level == 0);
1206                         } elsif ($c eq $open) {
1207                                 $level++;
1208                         }
1209                 }
1210
1211                 if (!$outer || $level <= 1) {
1212                         push(@res, $rawlines[$line]);
1213                 }
1214
1215                 last if ($level == 0);
1216         }
1217
1218         return ($level, @res);
1219 }
1220 sub ctx_block_outer {
1221         my ($linenr, $remain) = @_;
1222
1223         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1224         return @r;
1225 }
1226 sub ctx_block {
1227         my ($linenr, $remain) = @_;
1228
1229         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1230         return @r;
1231 }
1232 sub ctx_statement {
1233         my ($linenr, $remain, $off) = @_;
1234
1235         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1236         return @r;
1237 }
1238 sub ctx_block_level {
1239         my ($linenr, $remain) = @_;
1240
1241         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1242 }
1243 sub ctx_statement_level {
1244         my ($linenr, $remain, $off) = @_;
1245
1246         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1247 }
1248
1249 sub ctx_locate_comment {
1250         my ($first_line, $end_line) = @_;
1251
1252         # Catch a comment on the end of the line itself.
1253         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1254         return $current_comment if (defined $current_comment);
1255
1256         # Look through the context and try and figure out if there is a
1257         # comment.
1258         my $in_comment = 0;
1259         $current_comment = '';
1260         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1261                 my $line = $rawlines[$linenr - 1];
1262                 #warn "           $line\n";
1263                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1264                         $in_comment = 1;
1265                 }
1266                 if ($line =~ m@/\*@) {
1267                         $in_comment = 1;
1268                 }
1269                 if (!$in_comment && $current_comment ne '') {
1270                         $current_comment = '';
1271                 }
1272                 $current_comment .= $line . "\n" if ($in_comment);
1273                 if ($line =~ m@\*/@) {
1274                         $in_comment = 0;
1275                 }
1276         }
1277
1278         chomp($current_comment);
1279         return($current_comment);
1280 }
1281 sub ctx_has_comment {
1282         my ($first_line, $end_line) = @_;
1283         my $cmt = ctx_locate_comment($first_line, $end_line);
1284
1285         ##print "LINE: $rawlines[$end_line - 1 ]\n";
1286         ##print "CMMT: $cmt\n";
1287
1288         return ($cmt ne '');
1289 }
1290
1291 sub raw_line {
1292         my ($linenr, $cnt) = @_;
1293
1294         my $offset = $linenr - 1;
1295         $cnt++;
1296
1297         my $line;
1298         while ($cnt) {
1299                 $line = $rawlines[$offset++];
1300                 next if (defined($line) && $line =~ /^-/);
1301                 $cnt--;
1302         }
1303
1304         return $line;
1305 }
1306
1307 sub cat_vet {
1308         my ($vet) = @_;
1309         my ($res, $coded);
1310
1311         $res = '';
1312         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1313                 $res .= $1;
1314                 if ($2 ne '') {
1315                         $coded = sprintf("^%c", unpack('C', $2) + 64);
1316                         $res .= $coded;
1317                 }
1318         }
1319         $res =~ s/$/\$/;
1320
1321         return $res;
1322 }
1323
1324 my $av_preprocessor = 0;
1325 my $av_pending;
1326 my @av_paren_type;
1327 my $av_pend_colon;
1328
1329 sub annotate_reset {
1330         $av_preprocessor = 0;
1331         $av_pending = '_';
1332         @av_paren_type = ('E');
1333         $av_pend_colon = 'O';
1334 }
1335
1336 sub annotate_values {
1337         my ($stream, $type) = @_;
1338
1339         my $res;
1340         my $var = '_' x length($stream);
1341         my $cur = $stream;
1342
1343         print "$stream\n" if ($dbg_values > 1);
1344
1345         while (length($cur)) {
1346                 @av_paren_type = ('E') if ($#av_paren_type < 0);
1347                 print " <" . join('', @av_paren_type) .
1348                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
1349                 if ($cur =~ /^(\s+)/o) {
1350                         print "WS($1)\n" if ($dbg_values > 1);
1351                         if ($1 =~ /\n/ && $av_preprocessor) {
1352                                 $type = pop(@av_paren_type);
1353                                 $av_preprocessor = 0;
1354                         }
1355
1356                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1357                         print "CAST($1)\n" if ($dbg_values > 1);
1358                         push(@av_paren_type, $type);
1359                         $type = 'c';
1360
1361                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1362                         print "DECLARE($1)\n" if ($dbg_values > 1);
1363                         $type = 'T';
1364
1365                 } elsif ($cur =~ /^($Modifier)\s*/) {
1366                         print "MODIFIER($1)\n" if ($dbg_values > 1);
1367                         $type = 'T';
1368
1369                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1370                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1371                         $av_preprocessor = 1;
1372                         push(@av_paren_type, $type);
1373                         if ($2 ne '') {
1374                                 $av_pending = 'N';
1375                         }
1376                         $type = 'E';
1377
1378                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1379                         print "UNDEF($1)\n" if ($dbg_values > 1);
1380                         $av_preprocessor = 1;
1381                         push(@av_paren_type, $type);
1382
1383                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1384                         print "PRE_START($1)\n" if ($dbg_values > 1);
1385                         $av_preprocessor = 1;
1386
1387                         push(@av_paren_type, $type);
1388                         push(@av_paren_type, $type);
1389                         $type = 'E';
1390
1391                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1392                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1393                         $av_preprocessor = 1;
1394
1395                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1396
1397                         $type = 'E';
1398
1399                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1400                         print "PRE_END($1)\n" if ($dbg_values > 1);
1401
1402                         $av_preprocessor = 1;
1403
1404                         # Assume all arms of the conditional end as this
1405                         # one does, and continue as if the #endif was not here.
1406                         pop(@av_paren_type);
1407                         push(@av_paren_type, $type);
1408                         $type = 'E';
1409
1410                 } elsif ($cur =~ /^(\\\n)/o) {
1411                         print "PRECONT($1)\n" if ($dbg_values > 1);
1412
1413                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1414                         print "ATTR($1)\n" if ($dbg_values > 1);
1415                         $av_pending = $type;
1416                         $type = 'N';
1417
1418                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1419                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1420                         if (defined $2) {
1421                                 $av_pending = 'V';
1422                         }
1423                         $type = 'N';
1424
1425                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1426                         print "COND($1)\n" if ($dbg_values > 1);
1427                         $av_pending = 'E';
1428                         $type = 'N';
1429
1430                 } elsif ($cur =~/^(case)/o) {
1431                         print "CASE($1)\n" if ($dbg_values > 1);
1432                         $av_pend_colon = 'C';
1433                         $type = 'N';
1434
1435                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1436                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1437                         $type = 'N';
1438
1439                 } elsif ($cur =~ /^(\()/o) {
1440                         print "PAREN('$1')\n" if ($dbg_values > 1);
1441                         push(@av_paren_type, $av_pending);
1442                         $av_pending = '_';
1443                         $type = 'N';
1444
1445                 } elsif ($cur =~ /^(\))/o) {
1446                         my $new_type = pop(@av_paren_type);
1447                         if ($new_type ne '_') {
1448                                 $type = $new_type;
1449                                 print "PAREN('$1') -> $type\n"
1450                                                         if ($dbg_values > 1);
1451                         } else {
1452                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1453                         }
1454
1455                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1456                         print "FUNC($1)\n" if ($dbg_values > 1);
1457                         $type = 'V';
1458                         $av_pending = 'V';
1459
1460                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1461                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1462                                 $av_pend_colon = 'B';
1463                         } elsif ($type eq 'E') {
1464                                 $av_pend_colon = 'L';
1465                         }
1466                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1467                         $type = 'V';
1468
1469                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1470                         print "IDENT($1)\n" if ($dbg_values > 1);
1471                         $type = 'V';
1472
1473                 } elsif ($cur =~ /^($Assignment)/o) {
1474                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1475                         $type = 'N';
1476
1477                 } elsif ($cur =~/^(;|{|})/) {
1478                         print "END($1)\n" if ($dbg_values > 1);
1479                         $type = 'E';
1480                         $av_pend_colon = 'O';
1481
1482                 } elsif ($cur =~/^(,)/) {
1483                         print "COMMA($1)\n" if ($dbg_values > 1);
1484                         $type = 'C';
1485
1486                 } elsif ($cur =~ /^(\?)/o) {
1487                         print "QUESTION($1)\n" if ($dbg_values > 1);
1488                         $type = 'N';
1489
1490                 } elsif ($cur =~ /^(:)/o) {
1491                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1492
1493                         substr($var, length($res), 1, $av_pend_colon);
1494                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1495                                 $type = 'E';
1496                         } else {
1497                                 $type = 'N';
1498                         }
1499                         $av_pend_colon = 'O';
1500
1501                 } elsif ($cur =~ /^(\[)/o) {
1502                         print "CLOSE($1)\n" if ($dbg_values > 1);
1503                         $type = 'N';
1504
1505                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1506                         my $variant;
1507
1508                         print "OPV($1)\n" if ($dbg_values > 1);
1509                         if ($type eq 'V') {
1510                                 $variant = 'B';
1511                         } else {
1512                                 $variant = 'U';
1513                         }
1514
1515                         substr($var, length($res), 1, $variant);
1516                         $type = 'N';
1517
1518                 } elsif ($cur =~ /^($Operators)/o) {
1519                         print "OP($1)\n" if ($dbg_values > 1);
1520                         if ($1 ne '++' && $1 ne '--') {
1521                                 $type = 'N';
1522                         }
1523
1524                 } elsif ($cur =~ /(^.)/o) {
1525                         print "C($1)\n" if ($dbg_values > 1);
1526                 }
1527                 if (defined $1) {
1528                         $cur = substr($cur, length($1));
1529                         $res .= $type x length($1);
1530                 }
1531         }
1532
1533         return ($res, $var);
1534 }
1535
1536 sub possible {
1537         my ($possible, $line) = @_;
1538         my $notPermitted = qr{(?:
1539                 ^(?:
1540                         $Modifier|
1541                         $Storage|
1542                         $Type|
1543                         DEFINE_\S+
1544                 )$|
1545                 ^(?:
1546                         goto|
1547                         return|
1548                         case|
1549                         else|
1550                         asm|__asm__|
1551                         do|
1552                         \#|
1553                         \#\#|
1554                 )(?:\s|$)|
1555                 ^(?:typedef|struct|enum)\b
1556             )}x;
1557         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1558         if ($possible !~ $notPermitted) {
1559                 # Check for modifiers.
1560                 $possible =~ s/\s*$Storage\s*//g;
1561                 $possible =~ s/\s*$Sparse\s*//g;
1562                 if ($possible =~ /^\s*$/) {
1563
1564                 } elsif ($possible =~ /\s/) {
1565                         $possible =~ s/\s*$Type\s*//g;
1566                         for my $modifier (split(' ', $possible)) {
1567                                 if ($modifier !~ $notPermitted) {
1568                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1569                                         push(@modifierList, $modifier);
1570                                 }
1571                         }
1572
1573                 } else {
1574                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1575                         push(@typeList, $possible);
1576                 }
1577                 build_types();
1578         } else {
1579                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1580         }
1581 }
1582
1583 my $prefix = '';
1584
1585 sub show_type {
1586         my ($type) = @_;
1587
1588         return defined $use_type{$type} if (scalar keys %use_type > 0);
1589
1590         return !defined $ignore_type{$type};
1591 }
1592
1593 sub report {
1594         my ($level, $type, $msg) = @_;
1595
1596         if (!show_type($type) ||
1597             (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1598                 return 0;
1599         }
1600         my $line;
1601         if ($show_types) {
1602                 $line = "$prefix$level:$type: $msg\n";
1603         } else {
1604                 $line = "$prefix$level: $msg\n";
1605         }
1606         $line = (split('\n', $line))[0] . "\n" if ($terse);
1607
1608         push(our @report, $line);
1609
1610         return 1;
1611 }
1612
1613 sub report_dump {
1614         our @report;
1615 }
1616
1617 sub fixup_current_range {
1618         my ($lineRef, $offset, $length) = @_;
1619
1620         if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1621                 my $o = $1;
1622                 my $l = $2;
1623                 my $no = $o + $offset;
1624                 my $nl = $l + $length;
1625                 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1626         }
1627 }
1628
1629 sub fix_inserted_deleted_lines {
1630         my ($linesRef, $insertedRef, $deletedRef) = @_;
1631
1632         my $range_last_linenr = 0;
1633         my $delta_offset = 0;
1634
1635         my $old_linenr = 0;
1636         my $new_linenr = 0;
1637
1638         my $next_insert = 0;
1639         my $next_delete = 0;
1640
1641         my @lines = ();
1642
1643         my $inserted = @{$insertedRef}[$next_insert++];
1644         my $deleted = @{$deletedRef}[$next_delete++];
1645
1646         foreach my $old_line (@{$linesRef}) {
1647                 my $save_line = 1;
1648                 my $line = $old_line;   #don't modify the array
1649                 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) {     #new filename
1650                         $delta_offset = 0;
1651                 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) {    #new hunk
1652                         $range_last_linenr = $new_linenr;
1653                         fixup_current_range(\$line, $delta_offset, 0);
1654                 }
1655
1656                 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1657                         $deleted = @{$deletedRef}[$next_delete++];
1658                         $save_line = 0;
1659                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1660                 }
1661
1662                 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1663                         push(@lines, ${$inserted}{'LINE'});
1664                         $inserted = @{$insertedRef}[$next_insert++];
1665                         $new_linenr++;
1666                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1667                 }
1668
1669                 if ($save_line) {
1670                         push(@lines, $line);
1671                         $new_linenr++;
1672                 }
1673
1674                 $old_linenr++;
1675         }
1676
1677         return @lines;
1678 }
1679
1680 sub fix_insert_line {
1681         my ($linenr, $line) = @_;
1682
1683         my $inserted = {
1684                 LINENR => $linenr,
1685                 LINE => $line,
1686         };
1687         push(@fixed_inserted, $inserted);
1688 }
1689
1690 sub fix_delete_line {
1691         my ($linenr, $line) = @_;
1692
1693         my $deleted = {
1694                 LINENR => $linenr,
1695                 LINE => $line,
1696         };
1697
1698         push(@fixed_deleted, $deleted);
1699 }
1700
1701 sub ERROR {
1702         my ($type, $msg) = @_;
1703
1704         if (report("ERROR", $type, $msg)) {
1705                 our $clean = 0;
1706                 our $cnt_error++;
1707                 return 1;
1708         }
1709         return 0;
1710 }
1711 sub WARN {
1712         my ($type, $msg) = @_;
1713
1714         if (report("WARNING", $type, $msg)) {
1715                 our $clean = 0;
1716                 our $cnt_warn++;
1717                 return 1;
1718         }
1719         return 0;
1720 }
1721 sub CHK {
1722         my ($type, $msg) = @_;
1723
1724         if ($check && report("CHECK", $type, $msg)) {
1725                 our $clean = 0;
1726                 our $cnt_chk++;
1727                 return 1;
1728         }
1729         return 0;
1730 }
1731
1732 sub check_absolute_file {
1733         my ($absolute, $herecurr) = @_;
1734         my $file = $absolute;
1735
1736         ##print "absolute<$absolute>\n";
1737
1738         # See if any suffix of this path is a path within the tree.
1739         while ($file =~ s@^[^/]*/@@) {
1740                 if (-f "$root/$file") {
1741                         ##print "file<$file>\n";
1742                         last;
1743                 }
1744         }
1745         if (! -f _)  {
1746                 return 0;
1747         }
1748
1749         # It is, so see if the prefix is acceptable.
1750         my $prefix = $absolute;
1751         substr($prefix, -length($file)) = '';
1752
1753         ##print "prefix<$prefix>\n";
1754         if ($prefix ne ".../") {
1755                 WARN("USE_RELATIVE_PATH",
1756                      "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1757         }
1758 }
1759
1760 sub trim {
1761         my ($string) = @_;
1762
1763         $string =~ s/^\s+|\s+$//g;
1764
1765         return $string;
1766 }
1767
1768 sub ltrim {
1769         my ($string) = @_;
1770
1771         $string =~ s/^\s+//;
1772
1773         return $string;
1774 }
1775
1776 sub rtrim {
1777         my ($string) = @_;
1778
1779         $string =~ s/\s+$//;
1780
1781         return $string;
1782 }
1783
1784 sub string_find_replace {
1785         my ($string, $find, $replace) = @_;
1786
1787         $string =~ s/$find/$replace/g;
1788
1789         return $string;
1790 }
1791
1792 sub tabify {
1793         my ($leading) = @_;
1794
1795         my $source_indent = 8;
1796         my $max_spaces_before_tab = $source_indent - 1;
1797         my $spaces_to_tab = " " x $source_indent;
1798
1799         #convert leading spaces to tabs
1800         1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1801         #Remove spaces before a tab
1802         1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1803
1804         return "$leading";
1805 }
1806
1807 sub pos_last_openparen {
1808         my ($line) = @_;
1809
1810         my $pos = 0;
1811
1812         my $opens = $line =~ tr/\(/\(/;
1813         my $closes = $line =~ tr/\)/\)/;
1814
1815         my $last_openparen = 0;
1816
1817         if (($opens == 0) || ($closes >= $opens)) {
1818                 return -1;
1819         }
1820
1821         my $len = length($line);
1822
1823         for ($pos = 0; $pos < $len; $pos++) {
1824                 my $string = substr($line, $pos);
1825                 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1826                         $pos += length($1) - 1;
1827                 } elsif (substr($line, $pos, 1) eq '(') {
1828                         $last_openparen = $pos;
1829                 } elsif (index($string, '(') == -1) {
1830                         last;
1831                 }
1832         }
1833
1834         return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1835 }
1836
1837 sub process {
1838         my $filename = shift;
1839
1840         my $linenr=0;
1841         my $prevline="";
1842         my $prevrawline="";
1843         my $stashline="";
1844         my $stashrawline="";
1845
1846         my $length;
1847         my $indent;
1848         my $previndent=0;
1849         my $stashindent=0;
1850
1851         our $clean = 1;
1852         my $signoff = 0;
1853         my $is_patch = 0;
1854
1855         my $in_header_lines = $file ? 0 : 1;
1856         my $in_commit_log = 0;          #Scanning lines before patch
1857         my $reported_maintainer_file = 0;
1858         my $non_utf8_charset = 0;
1859
1860         my $last_blank_line = 0;
1861         my $last_coalesced_string_linenr = -1;
1862
1863         our @report = ();
1864         our $cnt_lines = 0;
1865         our $cnt_error = 0;
1866         our $cnt_warn = 0;
1867         our $cnt_chk = 0;
1868
1869         # Trace the real file/line as we go.
1870         my $realfile = '';
1871         my $realline = 0;
1872         my $realcnt = 0;
1873         my $here = '';
1874         my $in_comment = 0;
1875         my $comment_edge = 0;
1876         my $first_line = 0;
1877         my $p1_prefix = '';
1878
1879         my $prev_values = 'E';
1880
1881         # suppression flags
1882         my %suppress_ifbraces;
1883         my %suppress_whiletrailers;
1884         my %suppress_export;
1885         my $suppress_statement = 0;
1886
1887         my %signatures = ();
1888
1889         # Pre-scan the patch sanitizing the lines.
1890         # Pre-scan the patch looking for any __setup documentation.
1891         #
1892         my @setup_docs = ();
1893         my $setup_docs = 0;
1894
1895         my $camelcase_file_seeded = 0;
1896
1897         sanitise_line_reset();
1898         my $line;
1899         foreach my $rawline (@rawlines) {
1900                 $linenr++;
1901                 $line = $rawline;
1902
1903                 push(@fixed, $rawline) if ($fix);
1904
1905                 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1906                         $setup_docs = 0;
1907                         if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1908                                 $setup_docs = 1;
1909                         }
1910                         #next;
1911                 }
1912                 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1913                         $realline=$1-1;
1914                         if (defined $2) {
1915                                 $realcnt=$3+1;
1916                         } else {
1917                                 $realcnt=1+1;
1918                         }
1919                         $in_comment = 0;
1920
1921                         # Guestimate if this is a continuing comment.  Run
1922                         # the context looking for a comment "edge".  If this
1923                         # edge is a close comment then we must be in a comment
1924                         # at context start.
1925                         my $edge;
1926                         my $cnt = $realcnt;
1927                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1928                                 next if (defined $rawlines[$ln - 1] &&
1929                                          $rawlines[$ln - 1] =~ /^-/);
1930                                 $cnt--;
1931                                 #print "RAW<$rawlines[$ln - 1]>\n";
1932                                 last if (!defined $rawlines[$ln - 1]);
1933                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1934                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1935                                         ($edge) = $1;
1936                                         last;
1937                                 }
1938                         }
1939                         if (defined $edge && $edge eq '*/') {
1940                                 $in_comment = 1;
1941                         }
1942
1943                         # Guestimate if this is a continuing comment.  If this
1944                         # is the start of a diff block and this line starts
1945                         # ' *' then it is very likely a comment.
1946                         if (!defined $edge &&
1947                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1948                         {
1949                                 $in_comment = 1;
1950                         }
1951
1952                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1953                         sanitise_line_reset($in_comment);
1954
1955                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1956                         # Standardise the strings and chars within the input to
1957                         # simplify matching -- only bother with positive lines.
1958                         $line = sanitise_line($rawline);
1959                 }
1960                 push(@lines, $line);
1961
1962                 if ($realcnt > 1) {
1963                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
1964                 } else {
1965                         $realcnt = 0;
1966                 }
1967
1968                 #print "==>$rawline\n";
1969                 #print "-->$line\n";
1970
1971                 if ($setup_docs && $line =~ /^\+/) {
1972                         push(@setup_docs, $line);
1973                 }
1974         }
1975
1976         $prefix = '';
1977
1978         $realcnt = 0;
1979         $linenr = 0;
1980         $fixlinenr = -1;
1981         foreach my $line (@lines) {
1982                 $linenr++;
1983                 $fixlinenr++;
1984                 my $sline = $line;      #copy of $line
1985                 $sline =~ s/$;/ /g;     #with comments as spaces
1986
1987                 my $rawline = $rawlines[$linenr - 1];
1988
1989 #extract the line range in the file after the patch is applied
1990                 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1991                         $is_patch = 1;
1992                         $first_line = $linenr + 1;
1993                         $realline=$1-1;
1994                         if (defined $2) {
1995                                 $realcnt=$3+1;
1996                         } else {
1997                                 $realcnt=1+1;
1998                         }
1999                         annotate_reset();
2000                         $prev_values = 'E';
2001
2002                         %suppress_ifbraces = ();
2003                         %suppress_whiletrailers = ();
2004                         %suppress_export = ();
2005                         $suppress_statement = 0;
2006                         next;
2007
2008 # track the line number as we move through the hunk, note that
2009 # new versions of GNU diff omit the leading space on completely
2010 # blank context lines so we need to count that too.
2011                 } elsif ($line =~ /^( |\+|$)/) {
2012                         $realline++;
2013                         $realcnt-- if ($realcnt != 0);
2014
2015                         # Measure the line length and indent.
2016                         ($length, $indent) = line_stats($rawline);
2017
2018                         # Track the previous line.
2019                         ($prevline, $stashline) = ($stashline, $line);
2020                         ($previndent, $stashindent) = ($stashindent, $indent);
2021                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2022
2023                         #warn "line<$line>\n";
2024
2025                 } elsif ($realcnt == 1) {
2026                         $realcnt--;
2027                 }
2028
2029                 my $hunk_line = ($realcnt != 0);
2030
2031 #make up the handle for any error we report on this line
2032                 $prefix = "$filename:$realline: " if ($emacs && $file);
2033                 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2034
2035                 $here = "#$linenr: " if (!$file);
2036                 $here = "#$realline: " if ($file);
2037
2038                 my $found_file = 0;
2039                 # extract the filename as it passes
2040                 if ($line =~ /^diff --git.*?(\S+)$/) {
2041                         $realfile = $1;
2042                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2043                         $in_commit_log = 0;
2044                         $found_file = 1;
2045                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2046                         $realfile = $1;
2047                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2048                         $in_commit_log = 0;
2049
2050                         $p1_prefix = $1;
2051                         if (!$file && $tree && $p1_prefix ne '' &&
2052                             -e "$root/$p1_prefix") {
2053                                 WARN("PATCH_PREFIX",
2054                                      "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2055                         }
2056
2057                         if ($realfile =~ m@^include/asm/@) {
2058                                 ERROR("MODIFIED_INCLUDE_ASM",
2059                                       "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2060                         }
2061                         $found_file = 1;
2062                 }
2063
2064                 if ($found_file) {
2065                         if ($realfile =~ m@^(drivers/net/|net/)@) {
2066                                 $check = 1;
2067                         } else {
2068                                 $check = $check_orig;
2069                         }
2070                         next;
2071                 }
2072
2073                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2074
2075                 my $hereline = "$here\n$rawline\n";
2076                 my $herecurr = "$here\n$rawline\n";
2077                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2078
2079                 $cnt_lines++ if ($realcnt != 0);
2080
2081 # Check for incorrect file permissions
2082                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2083                         my $permhere = $here . "FILE: $realfile\n";
2084                         if ($realfile !~ m@scripts/@ &&
2085                             $realfile !~ /\.(py|pl|awk|sh)$/) {
2086                                 ERROR("EXECUTE_PERMISSIONS",
2087                                       "do not set execute permissions for source files\n" . $permhere);
2088                         }
2089                 }
2090
2091 # Check the patch for a signoff:
2092                 if ($line =~ /^\s*signed-off-by:/i) {
2093                         $signoff++;
2094                         $in_commit_log = 0;
2095                 }
2096
2097 # Check if MAINTAINERS is being updated.  If so, there's probably no need to
2098 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2099                 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2100                         $reported_maintainer_file = 1;
2101                 }
2102
2103 # Check signature styles
2104                 if (!$in_header_lines &&
2105                     $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2106                         my $space_before = $1;
2107                         my $sign_off = $2;
2108                         my $space_after = $3;
2109                         my $email = $4;
2110                         my $ucfirst_sign_off = ucfirst(lc($sign_off));
2111
2112                         if ($sign_off !~ /$signature_tags/) {
2113                                 WARN("BAD_SIGN_OFF",
2114                                      "Non-standard signature: $sign_off\n" . $herecurr);
2115                         }
2116                         if (defined $space_before && $space_before ne "") {
2117                                 if (WARN("BAD_SIGN_OFF",
2118                                          "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2119                                     $fix) {
2120                                         $fixed[$fixlinenr] =
2121                                             "$ucfirst_sign_off $email";
2122                                 }
2123                         }
2124                         if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2125                                 if (WARN("BAD_SIGN_OFF",
2126                                          "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2127                                     $fix) {
2128                                         $fixed[$fixlinenr] =
2129                                             "$ucfirst_sign_off $email";
2130                                 }
2131
2132                         }
2133                         if (!defined $space_after || $space_after ne " ") {
2134                                 if (WARN("BAD_SIGN_OFF",
2135                                          "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2136                                     $fix) {
2137                                         $fixed[$fixlinenr] =
2138                                             "$ucfirst_sign_off $email";
2139                                 }
2140                         }
2141
2142                         my ($email_name, $email_address, $comment) = parse_email($email);
2143                         my $suggested_email = format_email(($email_name, $email_address));
2144                         if ($suggested_email eq "") {
2145                                 ERROR("BAD_SIGN_OFF",
2146                                       "Unrecognized email address: '$email'\n" . $herecurr);
2147                         } else {
2148                                 my $dequoted = $suggested_email;
2149                                 $dequoted =~ s/^"//;
2150                                 $dequoted =~ s/" </ </;
2151                                 # Don't force email to have quotes
2152                                 # Allow just an angle bracketed address
2153                                 if ("$dequoted$comment" ne $email &&
2154                                     "<$email_address>$comment" ne $email &&
2155                                     "$suggested_email$comment" ne $email) {
2156                                         WARN("BAD_SIGN_OFF",
2157                                              "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2158                                 }
2159                         }
2160
2161 # Check for duplicate signatures
2162                         my $sig_nospace = $line;
2163                         $sig_nospace =~ s/\s//g;
2164                         $sig_nospace = lc($sig_nospace);
2165                         if (defined $signatures{$sig_nospace}) {
2166                                 WARN("BAD_SIGN_OFF",
2167                                      "Duplicate signature\n" . $herecurr);
2168                         } else {
2169                                 $signatures{$sig_nospace} = 1;
2170                         }
2171                 }
2172
2173 # Check for old stable address
2174                 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2175                         ERROR("STABLE_ADDRESS",
2176                               "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2177                 }
2178
2179 # Check for unwanted Gerrit info
2180                 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2181                         ERROR("GERRIT_CHANGE_ID",
2182                               "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2183                 }
2184
2185 # Check for git id commit length and improperly formed commit descriptions
2186                 if ($in_commit_log && $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i) {
2187                         my $init_char = $1;
2188                         my $orig_commit = lc($2);
2189                         my $short = 1;
2190                         my $long = 0;
2191                         my $case = 1;
2192                         my $space = 1;
2193                         my $hasdesc = 0;
2194                         my $hasparens = 0;
2195                         my $id = '0123456789ab';
2196                         my $orig_desc = "commit description";
2197                         my $description = "";
2198
2199                         $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2200                         $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2201                         $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2202                         $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2203                         if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2204                                 $orig_desc = $1;
2205                                 $hasparens = 1;
2206                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2207                                  defined $rawlines[$linenr] &&
2208                                  $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2209                                 $orig_desc = $1;
2210                                 $hasparens = 1;
2211                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2212                                  defined $rawlines[$linenr] &&
2213                                  $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2214                                 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2215                                 $orig_desc = $1;
2216                                 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2217                                 $orig_desc .= " " . $1;
2218                                 $hasparens = 1;
2219                         }
2220
2221                         ($id, $description) = git_commit_info($orig_commit,
2222                                                               $id, $orig_desc);
2223
2224                         if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2225                                 ERROR("GIT_COMMIT_ID",
2226                                       "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2227                         }
2228                 }
2229
2230 # Check for added, moved or deleted files
2231                 if (!$reported_maintainer_file && !$in_commit_log &&
2232                     ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2233                      $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2234                      ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2235                       (defined($1) || defined($2))))) {
2236                         $reported_maintainer_file = 1;
2237                         WARN("FILE_PATH_CHANGES",
2238                              "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2239                 }
2240
2241 # Check for wrappage within a valid hunk of the file
2242                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2243                         ERROR("CORRUPTED_PATCH",
2244                               "patch seems to be corrupt (line wrapped?)\n" .
2245                                 $herecurr) if (!$emitted_corrupt++);
2246                 }
2247
2248 # Check for absolute kernel paths.
2249                 if ($tree) {
2250                         while ($line =~ m{(?:^|\s)(/\S*)}g) {
2251                                 my $file = $1;
2252
2253                                 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2254                                     check_absolute_file($1, $herecurr)) {
2255                                         #
2256                                 } else {
2257                                         check_absolute_file($file, $herecurr);
2258                                 }
2259                         }
2260                 }
2261
2262 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2263                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2264                     $rawline !~ m/^$UTF8*$/) {
2265                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2266
2267                         my $blank = copy_spacing($rawline);
2268                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2269                         my $hereptr = "$hereline$ptr\n";
2270
2271                         CHK("INVALID_UTF8",
2272                             "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2273                 }
2274
2275 # Check if it's the start of a commit log
2276 # (not a header line and we haven't seen the patch filename)
2277                 if ($in_header_lines && $realfile =~ /^$/ &&
2278                     !($rawline =~ /^\s+\S/ ||
2279                       $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2280                         $in_header_lines = 0;
2281                         $in_commit_log = 1;
2282                 }
2283
2284 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2285 # declined it, i.e defined some charset where it is missing.
2286                 if ($in_header_lines &&
2287                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2288                     $1 !~ /utf-8/i) {
2289                         $non_utf8_charset = 1;
2290                 }
2291
2292                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2293                     $rawline =~ /$NON_ASCII_UTF8/) {
2294                         WARN("UTF8_BEFORE_PATCH",
2295                             "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2296                 }
2297
2298 # Check for various typo / spelling mistakes
2299                 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2300                         while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2301                                 my $typo = $1;
2302                                 my $typo_fix = $spelling_fix{lc($typo)};
2303                                 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2304                                 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2305                                 my $msg_type = \&WARN;
2306                                 $msg_type = \&CHK if ($file);
2307                                 if (&{$msg_type}("TYPO_SPELLING",
2308                                                  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2309                                     $fix) {
2310                                         $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2311                                 }
2312                         }
2313                 }
2314
2315 # ignore non-hunk lines and lines being removed
2316                 next if (!$hunk_line || $line =~ /^-/);
2317
2318 #trailing whitespace
2319                 if ($line =~ /^\+.*\015/) {
2320                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2321                         if (ERROR("DOS_LINE_ENDINGS",
2322                                   "DOS line endings\n" . $herevet) &&
2323                             $fix) {
2324                                 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2325                         }
2326                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2327                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2328                         if (ERROR("TRAILING_WHITESPACE",
2329                                   "trailing whitespace\n" . $herevet) &&
2330                             $fix) {
2331                                 $fixed[$fixlinenr] =~ s/\s+$//;
2332                         }
2333
2334                         $rpt_cleaners = 1;
2335                 }
2336
2337 # Check for FSF mailing addresses.
2338                 if ($rawline =~ /\bwrite to the Free/i ||
2339                     $rawline =~ /\b59\s+Temple\s+Pl/i ||
2340                     $rawline =~ /\b51\s+Franklin\s+St/i) {
2341                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2342                         my $msg_type = \&ERROR;
2343                         $msg_type = \&CHK if ($file);
2344                         &{$msg_type}("FSF_MAILING_ADDRESS",
2345                                      "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
2346                 }
2347
2348 # check for Kconfig help text having a real description
2349 # Only applies when adding the entry originally, after that we do not have
2350 # sufficient context to determine whether it is indeed long enough.
2351                 if ($realfile =~ /Kconfig/ &&
2352                     $line =~ /^\+\s*config\s+/) {
2353                         my $length = 0;
2354                         my $cnt = $realcnt;
2355                         my $ln = $linenr + 1;
2356                         my $f;
2357                         my $is_start = 0;
2358                         my $is_end = 0;
2359                         for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2360                                 $f = $lines[$ln - 1];
2361                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2362                                 $is_end = $lines[$ln - 1] =~ /^\+/;
2363
2364                                 next if ($f =~ /^-/);
2365                                 last if (!$file && $f =~ /^\@\@/);
2366
2367                                 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2368                                         $is_start = 1;
2369                                 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2370                                         $length = -1;
2371                                 }
2372
2373                                 $f =~ s/^.//;
2374                                 $f =~ s/#.*//;
2375                                 $f =~ s/^\s+//;
2376                                 next if ($f =~ /^$/);
2377                                 if ($f =~ /^\s*config\s/) {
2378                                         $is_end = 1;
2379                                         last;
2380                                 }
2381                                 $length++;
2382                         }
2383                         if ($is_start && $is_end && $length < $min_conf_desc_length) {
2384                                 WARN("CONFIG_DESCRIPTION",
2385                                      "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2386                         }
2387                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2388                 }
2389
2390 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2391                 if ($realfile =~ /Kconfig/ &&
2392                     $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2393                         WARN("CONFIG_EXPERIMENTAL",
2394                              "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2395                 }
2396
2397 # discourage the use of boolean for type definition attributes of Kconfig options
2398                 if ($realfile =~ /Kconfig/ &&
2399                     $line =~ /^\+\s*\bboolean\b/) {
2400                         WARN("CONFIG_TYPE_BOOLEAN",
2401                              "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2402                 }
2403
2404                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2405                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2406                         my $flag = $1;
2407                         my $replacement = {
2408                                 'EXTRA_AFLAGS' =>   'asflags-y',
2409                                 'EXTRA_CFLAGS' =>   'ccflags-y',
2410                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
2411                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
2412                         };
2413
2414                         WARN("DEPRECATED_VARIABLE",
2415                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2416                 }
2417
2418 # check for DT compatible documentation
2419                 if (defined $root &&
2420                         (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2421                          ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2422
2423                         my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2424
2425                         my $dt_path = $root . "/Documentation/devicetree/bindings/";
2426                         my $vp_file = $dt_path . "vendor-prefixes.txt";
2427
2428                         foreach my $compat (@compats) {
2429                                 my $compat2 = $compat;
2430                                 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2431                                 my $compat3 = $compat;
2432                                 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2433                                 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2434                                 if ( $? >> 8 ) {
2435                                         WARN("UNDOCUMENTED_DT_STRING",
2436                                              "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2437                                 }
2438
2439                                 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2440                                 my $vendor = $1;
2441                                 `grep -Eq "^$vendor\\b" $vp_file`;
2442                                 if ( $? >> 8 ) {
2443                                         WARN("UNDOCUMENTED_DT_STRING",
2444                                              "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2445                                 }
2446                         }
2447                 }
2448
2449 # check we are in a valid source file if not then ignore this hunk
2450                 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2451
2452 #line length limit
2453                 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2454                     $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2455                     !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2456                     $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2457                     $length > $max_line_length)
2458                 {
2459                         WARN("LONG_LINE",
2460                              "line over $max_line_length characters\n" . $herecurr);
2461                 }
2462
2463 # check for adding lines without a newline.
2464                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2465                         WARN("MISSING_EOF_NEWLINE",
2466                              "adding a line without newline at end of file\n" . $herecurr);
2467                 }
2468
2469 # Blackfin: use hi/lo macros
2470                 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2471                         if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2472                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2473                                 ERROR("LO_MACRO",
2474                                       "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2475                         }
2476                         if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2477                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2478                                 ERROR("HI_MACRO",
2479                                       "use the HI() macro, not (... >> 16)\n" . $herevet);
2480                         }
2481                 }
2482
2483 # check we are in a valid source file C or perl if not then ignore this hunk
2484                 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2485
2486 # at the beginning of a line any tabs must come first and anything
2487 # more than 8 must use tabs.
2488                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2489                     $rawline =~ /^\+\s*        \s*/) {
2490                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2491                         $rpt_cleaners = 1;
2492                         if (ERROR("CODE_INDENT",
2493                                   "code indent should use tabs where possible\n" . $herevet) &&
2494                             $fix) {
2495                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2496                         }
2497                 }
2498
2499 # check for space before tabs.
2500                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2501                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2502                         if (WARN("SPACE_BEFORE_TAB",
2503                                 "please, no space before tabs\n" . $herevet) &&
2504                             $fix) {
2505                                 while ($fixed[$fixlinenr] =~
2506                                            s/(^\+.*) {8,8}\t/$1\t\t/) {}
2507                                 while ($fixed[$fixlinenr] =~
2508                                            s/(^\+.*) +\t/$1\t/) {}
2509                         }
2510                 }
2511
2512 # check for && or || at the start of a line
2513                 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2514                         CHK("LOGICAL_CONTINUATIONS",
2515                             "Logical continuations should be on the previous line\n" . $hereprev);
2516                 }
2517
2518 # check multi-line statement indentation matches previous line
2519                 if ($^V && $^V ge 5.10.0 &&
2520                     $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2521                         $prevline =~ /^\+(\t*)(.*)$/;
2522                         my $oldindent = $1;
2523                         my $rest = $2;
2524
2525                         my $pos = pos_last_openparen($rest);
2526                         if ($pos >= 0) {
2527                                 $line =~ /^(\+| )([ \t]*)/;
2528                                 my $newindent = $2;
2529
2530                                 my $goodtabindent = $oldindent .
2531                                         "\t" x ($pos / 8) .
2532                                         " "  x ($pos % 8);
2533                                 my $goodspaceindent = $oldindent . " "  x $pos;
2534
2535                                 if ($newindent ne $goodtabindent &&
2536                                     $newindent ne $goodspaceindent) {
2537
2538                                         if (CHK("PARENTHESIS_ALIGNMENT",
2539                                                 "Alignment should match open parenthesis\n" . $hereprev) &&
2540                                             $fix && $line =~ /^\+/) {
2541                                                 $fixed[$fixlinenr] =~
2542                                                     s/^\+[ \t]*/\+$goodtabindent/;
2543                                         }
2544                                 }
2545                         }
2546                 }
2547
2548                 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;:\?\(\{\}\[\<\>]|&&|\|\||\\$)/ &&
2549                     (!defined($1) || $1 !~ /sizeof\s*/)) {
2550                         if (CHK("SPACING",
2551                                 "No space is necessary after a cast\n" . $herecurr) &&
2552                             $fix) {
2553                                 $fixed[$fixlinenr] =~
2554                                     s/(\(\s*$Type\s*\))[ \t]+/$1/;
2555                         }
2556                 }
2557
2558                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2559                     $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2560                     $rawline =~ /^\+[ \t]*\*/ &&
2561                     $realline > 2) {
2562                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2563                              "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2564                 }
2565
2566                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2567                     $prevrawline =~ /^\+[ \t]*\/\*/ &&          #starting /*
2568                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
2569                     $rawline =~ /^\+/ &&                        #line is new
2570                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
2571                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2572                              "networking block comments start with * on subsequent lines\n" . $hereprev);
2573                 }
2574
2575                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2576                     $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
2577                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
2578                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
2579                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
2580                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2581                              "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2582                 }
2583
2584 # check for missing blank lines after struct/union declarations
2585 # with exceptions for various attributes and macros
2586                 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2587                     $line =~ /^\+/ &&
2588                     !($line =~ /^\+\s*$/ ||
2589                       $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2590                       $line =~ /^\+\s*MODULE_/i ||
2591                       $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2592                       $line =~ /^\+[a-z_]*init/ ||
2593                       $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2594                       $line =~ /^\+\s*DECLARE/ ||
2595                       $line =~ /^\+\s*__setup/)) {
2596                         if (CHK("LINE_SPACING",
2597                                 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2598                             $fix) {
2599                                 fix_insert_line($fixlinenr, "\+");
2600                         }
2601                 }
2602
2603 # check for multiple consecutive blank lines
2604                 if ($prevline =~ /^[\+ ]\s*$/ &&
2605                     $line =~ /^\+\s*$/ &&
2606                     $last_blank_line != ($linenr - 1)) {
2607                         if (CHK("LINE_SPACING",
2608                                 "Please don't use multiple blank lines\n" . $hereprev) &&
2609                             $fix) {
2610                                 fix_delete_line($fixlinenr, $rawline);
2611                         }
2612
2613                         $last_blank_line = $linenr;
2614                 }
2615
2616 # check for missing blank lines after declarations
2617                 if ($sline =~ /^\+\s+\S/ &&                     #Not at char 1
2618                         # actual declarations
2619                     ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2620                         # function pointer declarations
2621                      $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2622                         # foo bar; where foo is some local typedef or #define
2623                      $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2624                         # known declaration macros
2625                      $prevline =~ /^\+\s+$declaration_macros/) &&
2626                         # for "else if" which can look like "$Ident $Ident"
2627                     !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2628                         # other possible extensions of declaration lines
2629                       $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2630                         # not starting a section or a macro "\" extended line
2631                       $prevline =~ /(?:\{\s*|\\)$/) &&
2632                         # looks like a declaration
2633                     !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2634                         # function pointer declarations
2635                       $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2636                         # foo bar; where foo is some local typedef or #define
2637                       $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2638                         # known declaration macros
2639                       $sline =~ /^\+\s+$declaration_macros/ ||
2640                         # start of struct or union or enum
2641                       $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2642                         # start or end of block or continuation of declaration
2643                       $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2644                         # bitfield continuation
2645                       $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2646                         # other possible extensions of declaration lines
2647                       $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2648                         # indentation of previous and current line are the same
2649                     (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2650                         if (WARN("LINE_SPACING",
2651                                  "Missing a blank line after declarations\n" . $hereprev) &&
2652                             $fix) {
2653                                 fix_insert_line($fixlinenr, "\+");
2654                         }
2655                 }
2656
2657 # check for spaces at the beginning of a line.
2658 # Exceptions:
2659 #  1) within comments
2660 #  2) indented preprocessor commands
2661 #  3) hanging labels
2662                 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
2663                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2664                         if (WARN("LEADING_SPACE",
2665                                  "please, no spaces at the start of a line\n" . $herevet) &&
2666                             $fix) {
2667                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2668                         }
2669                 }
2670
2671 # check we are in a valid C source file if not then ignore this hunk
2672                 next if ($realfile !~ /\.(h|c)$/);
2673
2674 # check indentation of any line with a bare else
2675 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2676 # if the previous line is a break or return and is indented 1 tab more...
2677                 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2678                         my $tabs = length($1) + 1;
2679                         if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2680                             ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2681                              defined $lines[$linenr] &&
2682                              $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2683                                 WARN("UNNECESSARY_ELSE",
2684                                      "else is not generally useful after a break or return\n" . $hereprev);
2685                         }
2686                 }
2687
2688 # check indentation of a line with a break;
2689 # if the previous line is a goto or return and is indented the same # of tabs
2690                 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2691                         my $tabs = $1;
2692                         if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2693                                 WARN("UNNECESSARY_BREAK",
2694                                      "break is not useful after a goto or return\n" . $hereprev);
2695                         }
2696                 }
2697
2698 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2699                 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2700                         WARN("CONFIG_EXPERIMENTAL",
2701                              "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2702                 }
2703
2704 # check for RCS/CVS revision markers
2705                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2706                         WARN("CVS_KEYWORD",
2707                              "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2708                 }
2709
2710 # Blackfin: don't use __builtin_bfin_[cs]sync
2711                 if ($line =~ /__builtin_bfin_csync/) {
2712                         my $herevet = "$here\n" . cat_vet($line) . "\n";
2713                         ERROR("CSYNC",
2714                               "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2715                 }
2716                 if ($line =~ /__builtin_bfin_ssync/) {
2717                         my $herevet = "$here\n" . cat_vet($line) . "\n";
2718                         ERROR("SSYNC",
2719                               "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2720                 }
2721
2722 # check for old HOTPLUG __dev<foo> section markings
2723                 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2724                         WARN("HOTPLUG_SECTION",
2725                              "Using $1 is unnecessary\n" . $herecurr);
2726                 }
2727
2728 # Check for potential 'bare' types
2729                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2730                     $realline_next);
2731 #print "LINE<$line>\n";
2732                 if ($linenr >= $suppress_statement &&
2733                     $realcnt && $sline =~ /.\s*\S/) {
2734                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2735                                 ctx_statement_block($linenr, $realcnt, 0);
2736                         $stat =~ s/\n./\n /g;
2737                         $cond =~ s/\n./\n /g;
2738
2739 #print "linenr<$linenr> <$stat>\n";
2740                         # If this statement has no statement boundaries within
2741                         # it there is no point in retrying a statement scan
2742                         # until we hit end of it.
2743                         my $frag = $stat; $frag =~ s/;+\s*$//;
2744                         if ($frag !~ /(?:{|;)/) {
2745 #print "skip<$line_nr_next>\n";
2746                                 $suppress_statement = $line_nr_next;
2747                         }
2748
2749                         # Find the real next line.
2750                         $realline_next = $line_nr_next;
2751                         if (defined $realline_next &&
2752                             (!defined $lines[$realline_next - 1] ||
2753                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2754                                 $realline_next++;
2755                         }
2756
2757                         my $s = $stat;
2758                         $s =~ s/{.*$//s;
2759
2760                         # Ignore goto labels.
2761                         if ($s =~ /$Ident:\*$/s) {
2762
2763                         # Ignore functions being called
2764                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2765
2766                         } elsif ($s =~ /^.\s*else\b/s) {
2767
2768                         # declarations always start with types
2769                         } 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) {
2770                                 my $type = $1;
2771                                 $type =~ s/\s+/ /g;
2772                                 possible($type, "A:" . $s);
2773
2774                         # definitions in global scope can only start with types
2775                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2776                                 possible($1, "B:" . $s);
2777                         }
2778
2779                         # any (foo ... *) is a pointer cast, and foo is a type
2780                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2781                                 possible($1, "C:" . $s);
2782                         }
2783
2784                         # Check for any sort of function declaration.
2785                         # int foo(something bar, other baz);
2786                         # void (*store_gdt)(x86_descr_ptr *);
2787                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2788                                 my ($name_len) = length($1);
2789
2790                                 my $ctx = $s;
2791                                 substr($ctx, 0, $name_len + 1, '');
2792                                 $ctx =~ s/\)[^\)]*$//;
2793
2794                                 for my $arg (split(/\s*,\s*/, $ctx)) {
2795                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2796
2797                                                 possible($1, "D:" . $s);
2798                                         }
2799                                 }
2800                         }
2801
2802                 }
2803
2804 #
2805 # Checks which may be anchored in the context.
2806 #
2807
2808 # Check for switch () and associated case and default
2809 # statements should be at the same indent.
2810                 if ($line=~/\bswitch\s*\(.*\)/) {
2811                         my $err = '';
2812                         my $sep = '';
2813                         my @ctx = ctx_block_outer($linenr, $realcnt);
2814                         shift(@ctx);
2815                         for my $ctx (@ctx) {
2816                                 my ($clen, $cindent) = line_stats($ctx);
2817                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2818                                                         $indent != $cindent) {
2819                                         $err .= "$sep$ctx\n";
2820                                         $sep = '';
2821                                 } else {
2822                                         $sep = "[...]\n";
2823                                 }
2824                         }
2825                         if ($err ne '') {
2826                                 ERROR("SWITCH_CASE_INDENT_LEVEL",
2827                                       "switch and case should be at the same indent\n$hereline$err");
2828                         }
2829                 }
2830
2831 # if/while/etc brace do not go on next line, unless defining a do while loop,
2832 # or if that brace on the next line is for something else
2833                 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2834                         my $pre_ctx = "$1$2";
2835
2836                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2837
2838                         if ($line =~ /^\+\t{6,}/) {
2839                                 WARN("DEEP_INDENTATION",
2840                                      "Too many leading tabs - consider code refactoring\n" . $herecurr);
2841                         }
2842
2843                         my $ctx_cnt = $realcnt - $#ctx - 1;
2844                         my $ctx = join("\n", @ctx);
2845
2846                         my $ctx_ln = $linenr;
2847                         my $ctx_skip = $realcnt;
2848
2849                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2850                                         defined $lines[$ctx_ln - 1] &&
2851                                         $lines[$ctx_ln - 1] =~ /^-/)) {
2852                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2853                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2854                                 $ctx_ln++;
2855                         }
2856
2857                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2858                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2859
2860                         if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2861                                 ERROR("OPEN_BRACE",
2862                                       "that open brace { should be on the previous line\n" .
2863                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2864                         }
2865                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2866                             $ctx =~ /\)\s*\;\s*$/ &&
2867                             defined $lines[$ctx_ln - 1])
2868                         {
2869                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2870                                 if ($nindent > $indent) {
2871                                         WARN("TRAILING_SEMICOLON",
2872                                              "trailing semicolon indicates no statements, indent implies otherwise\n" .
2873                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2874                                 }
2875                         }
2876                 }
2877
2878 # Check relative indent for conditionals and blocks.
2879                 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2880                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2881                                 ctx_statement_block($linenr, $realcnt, 0)
2882                                         if (!defined $stat);
2883                         my ($s, $c) = ($stat, $cond);
2884
2885                         substr($s, 0, length($c), '');
2886
2887                         # Make sure we remove the line prefixes as we have
2888                         # none on the first line, and are going to readd them
2889                         # where necessary.
2890                         $s =~ s/\n./\n/gs;
2891
2892                         # Find out how long the conditional actually is.
2893                         my @newlines = ($c =~ /\n/gs);
2894                         my $cond_lines = 1 + $#newlines;
2895
2896                         # We want to check the first line inside the block
2897                         # starting at the end of the conditional, so remove:
2898                         #  1) any blank line termination
2899                         #  2) any opening brace { on end of the line
2900                         #  3) any do (...) {
2901                         my $continuation = 0;
2902                         my $check = 0;
2903                         $s =~ s/^.*\bdo\b//;
2904                         $s =~ s/^\s*{//;
2905                         if ($s =~ s/^\s*\\//) {
2906                                 $continuation = 1;
2907                         }
2908                         if ($s =~ s/^\s*?\n//) {
2909                                 $check = 1;
2910                                 $cond_lines++;
2911                         }
2912
2913                         # Also ignore a loop construct at the end of a
2914                         # preprocessor statement.
2915                         if (($prevline =~ /^.\s*#\s*define\s/ ||
2916                             $prevline =~ /\\\s*$/) && $continuation == 0) {
2917                                 $check = 0;
2918                         }
2919
2920                         my $cond_ptr = -1;
2921                         $continuation = 0;
2922                         while ($cond_ptr != $cond_lines) {
2923                                 $cond_ptr = $cond_lines;
2924
2925                                 # If we see an #else/#elif then the code
2926                                 # is not linear.
2927                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2928                                         $check = 0;
2929                                 }
2930
2931                                 # Ignore:
2932                                 #  1) blank lines, they should be at 0,
2933                                 #  2) preprocessor lines, and
2934                                 #  3) labels.
2935                                 if ($continuation ||
2936                                     $s =~ /^\s*?\n/ ||
2937                                     $s =~ /^\s*#\s*?/ ||
2938                                     $s =~ /^\s*$Ident\s*:/) {
2939                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2940                                         if ($s =~ s/^.*?\n//) {
2941                                                 $cond_lines++;
2942                                         }
2943                                 }
2944                         }
2945
2946                         my (undef, $sindent) = line_stats("+" . $s);
2947                         my $stat_real = raw_line($linenr, $cond_lines);
2948
2949                         # Check if either of these lines are modified, else
2950                         # this is not this patch's fault.
2951                         if (!defined($stat_real) ||
2952                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2953                                 $check = 0;
2954                         }
2955                         if (defined($stat_real) && $cond_lines > 1) {
2956                                 $stat_real = "[...]\n$stat_real";
2957                         }
2958
2959                         #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";
2960
2961                         if ($check && (($sindent % 8) != 0 ||
2962                             ($sindent <= $indent && $s ne ''))) {
2963                                 WARN("SUSPECT_CODE_INDENT",
2964                                      "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2965                         }
2966                 }
2967
2968                 # Track the 'values' across context and added lines.
2969                 my $opline = $line; $opline =~ s/^./ /;
2970                 my ($curr_values, $curr_vars) =
2971                                 annotate_values($opline . "\n", $prev_values);
2972                 $curr_values = $prev_values . $curr_values;
2973                 if ($dbg_values) {
2974                         my $outline = $opline; $outline =~ s/\t/ /g;
2975                         print "$linenr > .$outline\n";
2976                         print "$linenr > $curr_values\n";
2977                         print "$linenr >  $curr_vars\n";
2978                 }
2979                 $prev_values = substr($curr_values, -1);
2980
2981 #ignore lines not being added
2982                 next if ($line =~ /^[^\+]/);
2983
2984 # TEST: allow direct testing of the type matcher.
2985                 if ($dbg_type) {
2986                         if ($line =~ /^.\s*$Declare\s*$/) {
2987                                 ERROR("TEST_TYPE",
2988                                       "TEST: is type\n" . $herecurr);
2989                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2990                                 ERROR("TEST_NOT_TYPE",
2991                                       "TEST: is not type ($1 is)\n". $herecurr);
2992                         }
2993                         next;
2994                 }
2995 # TEST: allow direct testing of the attribute matcher.
2996                 if ($dbg_attr) {
2997                         if ($line =~ /^.\s*$Modifier\s*$/) {
2998                                 ERROR("TEST_ATTR",
2999                                       "TEST: is attr\n" . $herecurr);
3000                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3001                                 ERROR("TEST_NOT_ATTR",
3002                                       "TEST: is not attr ($1 is)\n". $herecurr);
3003                         }
3004                         next;
3005                 }
3006
3007 # check for initialisation to aggregates open brace on the next line
3008                 if ($line =~ /^.\s*{/ &&
3009                     $prevline =~ /(?:^|[^=])=\s*$/) {
3010                         if (ERROR("OPEN_BRACE",
3011                                   "that open brace { should be on the previous line\n" . $hereprev) &&
3012                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3013                                 fix_delete_line($fixlinenr - 1, $prevrawline);
3014                                 fix_delete_line($fixlinenr, $rawline);
3015                                 my $fixedline = $prevrawline;
3016                                 $fixedline =~ s/\s*=\s*$/ = {/;
3017                                 fix_insert_line($fixlinenr, $fixedline);
3018                                 $fixedline = $line;
3019                                 $fixedline =~ s/^(.\s*){\s*/$1/;
3020                                 fix_insert_line($fixlinenr, $fixedline);
3021                         }
3022                 }
3023
3024 #
3025 # Checks which are anchored on the added line.
3026 #
3027
3028 # check for malformed paths in #include statements (uses RAW line)
3029                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3030                         my $path = $1;
3031                         if ($path =~ m{//}) {
3032                                 ERROR("MALFORMED_INCLUDE",
3033                                       "malformed #include filename\n" . $herecurr);
3034                         }
3035                         if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3036                                 ERROR("UAPI_INCLUDE",
3037                                       "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3038                         }
3039                 }
3040
3041 # no C99 // comments
3042                 if ($line =~ m{//}) {
3043                         if (ERROR("C99_COMMENTS",
3044                                   "do not use C99 // comments\n" . $herecurr) &&
3045                             $fix) {
3046                                 my $line = $fixed[$fixlinenr];
3047                                 if ($line =~ /\/\/(.*)$/) {
3048                                         my $comment = trim($1);
3049                                         $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3050                                 }
3051                         }
3052                 }
3053                 # Remove C99 comments.
3054                 $line =~ s@//.*@@;
3055                 $opline =~ s@//.*@@;
3056
3057 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3058 # the whole statement.
3059 #print "APW <$lines[$realline_next - 1]>\n";
3060                 if (defined $realline_next &&
3061                     exists $lines[$realline_next - 1] &&
3062                     !defined $suppress_export{$realline_next} &&
3063                     ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3064                      $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3065                         # Handle definitions which produce identifiers with
3066                         # a prefix:
3067                         #   XXX(foo);
3068                         #   EXPORT_SYMBOL(something_foo);
3069                         my $name = $1;
3070                         if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3071                             $name =~ /^${Ident}_$2/) {
3072 #print "FOO C name<$name>\n";
3073                                 $suppress_export{$realline_next} = 1;
3074
3075                         } elsif ($stat !~ /(?:
3076                                 \n.}\s*$|
3077                                 ^.DEFINE_$Ident\(\Q$name\E\)|
3078                                 ^.DECLARE_$Ident\(\Q$name\E\)|
3079                                 ^.LIST_HEAD\(\Q$name\E\)|
3080                                 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3081                                 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3082                             )/x) {
3083 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3084                                 $suppress_export{$realline_next} = 2;
3085                         } else {
3086                                 $suppress_export{$realline_next} = 1;
3087                         }
3088                 }
3089                 if (!defined $suppress_export{$linenr} &&
3090                     $prevline =~ /^.\s*$/ &&
3091                     ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3092                      $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3093 #print "FOO B <$lines[$linenr - 1]>\n";
3094                         $suppress_export{$linenr} = 2;
3095                 }
3096                 if (defined $suppress_export{$linenr} &&
3097                     $suppress_export{$linenr} == 2) {
3098                         WARN("EXPORT_SYMBOL",
3099                              "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3100                 }
3101
3102 # check for global initialisers.
3103                 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3104                         if (ERROR("GLOBAL_INITIALISERS",
3105                                   "do not initialise globals to 0 or NULL\n" .
3106                                       $herecurr) &&
3107                             $fix) {
3108                                 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3109                         }
3110                 }
3111 # check for static initialisers.
3112                 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3113                         if (ERROR("INITIALISED_STATIC",
3114                                   "do not initialise statics to 0 or NULL\n" .
3115                                       $herecurr) &&
3116                             $fix) {
3117                                 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3118                         }
3119                 }
3120
3121 # check for misordered declarations of char/short/int/long with signed/unsigned
3122                 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3123                         my $tmp = trim($1);
3124                         WARN("MISORDERED_TYPE",
3125                              "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3126                 }
3127
3128 # check for static const char * arrays.
3129                 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3130                         WARN("STATIC_CONST_CHAR_ARRAY",
3131                              "static const char * array should probably be static const char * const\n" .
3132                                 $herecurr);
3133                }
3134
3135 # check for static char foo[] = "bar" declarations.
3136                 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3137                         WARN("STATIC_CONST_CHAR_ARRAY",
3138                              "static char array declaration should probably be static const char\n" .
3139                                 $herecurr);
3140                }
3141
3142 # check for non-global char *foo[] = {"bar", ...} declarations.
3143                 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3144                         WARN("STATIC_CONST_CHAR_ARRAY",
3145                              "char * array declaration might be better as static const\n" .
3146                                 $herecurr);
3147                }
3148
3149 # check for function declarations without arguments like "int foo()"
3150                 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3151                         if (ERROR("FUNCTION_WITHOUT_ARGS",
3152                                   "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3153                             $fix) {
3154                                 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3155                         }
3156                 }
3157
3158 # check for uses of DEFINE_PCI_DEVICE_TABLE
3159                 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3160                         if (WARN("DEFINE_PCI_DEVICE_TABLE",
3161                                  "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3162                             $fix) {
3163                                 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3164                         }
3165                 }
3166
3167 # check for new typedefs, only function parameters and sparse annotations
3168 # make sense.
3169                 if ($line =~ /\btypedef\s/ &&
3170                     $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3171                     $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3172                     $line !~ /\b$typeTypedefs\b/ &&
3173                     $line !~ /\b$typeOtherOSTypedefs\b/ &&
3174                     $line !~ /\b__bitwise(?:__|)\b/) {
3175                         WARN("NEW_TYPEDEFS",
3176                              "do not add new typedefs\n" . $herecurr);
3177                 }
3178
3179 # * goes on variable not on type
3180                 # (char*[ const])
3181                 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3182                         #print "AA<$1>\n";
3183                         my ($ident, $from, $to) = ($1, $2, $2);
3184
3185                         # Should start with a space.
3186                         $to =~ s/^(\S)/ $1/;
3187                         # Should not end with a space.
3188                         $to =~ s/\s+$//;
3189                         # '*'s should not have spaces between.
3190                         while ($to =~ s/\*\s+\*/\*\*/) {
3191                         }
3192
3193 ##                      print "1: from<$from> to<$to> ident<$ident>\n";
3194                         if ($from ne $to) {
3195                                 if (ERROR("POINTER_LOCATION",
3196                                           "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
3197                                     $fix) {
3198                                         my $sub_from = $ident;
3199                                         my $sub_to = $ident;
3200                                         $sub_to =~ s/\Q$from\E/$to/;
3201                                         $fixed[$fixlinenr] =~
3202                                             s@\Q$sub_from\E@$sub_to@;
3203                                 }
3204                         }
3205                 }
3206                 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3207                         #print "BB<$1>\n";
3208                         my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3209
3210                         # Should start with a space.
3211                         $to =~ s/^(\S)/ $1/;
3212                         # Should not end with a space.
3213                         $to =~ s/\s+$//;
3214                         # '*'s should not have spaces between.
3215                         while ($to =~ s/\*\s+\*/\*\*/) {
3216                         }
3217                         # Modifiers should have spaces.
3218                         $to =~ s/(\b$Modifier$)/$1 /;
3219
3220 ##                      print "2: from<$from> to<$to> ident<$ident>\n";
3221                         if ($from ne $to && $ident !~ /^$Modifier$/) {
3222                                 if (ERROR("POINTER_LOCATION",
3223                                           "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
3224                                     $fix) {
3225
3226                                         my $sub_from = $match;
3227                                         my $sub_to = $match;
3228                                         $sub_to =~ s/\Q$from\E/$to/;
3229                                         $fixed[$fixlinenr] =~
3230                                             s@\Q$sub_from\E@$sub_to@;
3231                                 }
3232                         }
3233                 }
3234
3235 # # no BUG() or BUG_ON()
3236 #               if ($line =~ /\b(BUG|BUG_ON)\b/) {
3237 #                       print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3238 #                       print "$herecurr";
3239 #                       $clean = 0;
3240 #               }
3241
3242                 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3243                         WARN("LINUX_VERSION_CODE",
3244                              "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3245                 }
3246
3247 # check for uses of printk_ratelimit
3248                 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3249                         WARN("PRINTK_RATELIMITED",
3250                              "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3251                 }
3252
3253 # printk should use KERN_* levels.  Note that follow on printk's on the
3254 # same line do not need a level, so we use the current block context
3255 # to try and find and validate the current printk.  In summary the current
3256 # printk includes all preceding printk's which have no newline on the end.
3257 # we assume the first bad printk is the one to report.
3258                 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3259                         my $ok = 0;
3260                         for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3261                                 #print "CHECK<$lines[$ln - 1]\n";
3262                                 # we have a preceding printk if it ends
3263                                 # with "\n" ignore it, else it is to blame
3264                                 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3265                                         if ($rawlines[$ln - 1] !~ m{\\n"}) {
3266                                                 $ok = 1;
3267                                         }
3268                                         last;
3269                                 }
3270                         }
3271                         if ($ok == 0) {
3272                                 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3273                                      "printk() should include KERN_ facility level\n" . $herecurr);
3274                         }
3275                 }
3276
3277                 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3278                         my $orig = $1;
3279                         my $level = lc($orig);
3280                         $level = "warn" if ($level eq "warning");
3281                         my $level2 = $level;
3282                         $level2 = "dbg" if ($level eq "debug");
3283                         WARN("PREFER_PR_LEVEL",
3284                              "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
3285                 }
3286
3287                 if ($line =~ /\bpr_warning\s*\(/) {
3288                         if (WARN("PREFER_PR_LEVEL",
3289                                  "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3290                             $fix) {
3291                                 $fixed[$fixlinenr] =~
3292                                     s/\bpr_warning\b/pr_warn/;
3293                         }
3294                 }
3295
3296                 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3297                         my $orig = $1;
3298                         my $level = lc($orig);
3299                         $level = "warn" if ($level eq "warning");
3300                         $level = "dbg" if ($level eq "debug");
3301                         WARN("PREFER_DEV_LEVEL",
3302                              "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3303                 }
3304
3305 # function brace can't be on same line, except for #defines of do while,
3306 # or if closed on same line
3307                 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3308                     !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3309                         if (ERROR("OPEN_BRACE",
3310                                   "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3311                             $fix) {
3312                                 fix_delete_line($fixlinenr, $rawline);
3313                                 my $fixed_line = $rawline;
3314                                 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3315                                 my $line1 = $1;
3316                                 my $line2 = $2;
3317                                 fix_insert_line($fixlinenr, ltrim($line1));
3318                                 fix_insert_line($fixlinenr, "\+{");
3319                                 if ($line2 !~ /^\s*$/) {
3320                                         fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3321                                 }
3322                         }
3323                 }
3324
3325 # open braces for enum, union and struct go on the same line.
3326                 if ($line =~ /^.\s*{/ &&
3327                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3328                         if (ERROR("OPEN_BRACE",
3329                                   "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3330                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3331                                 fix_delete_line($fixlinenr - 1, $prevrawline);
3332                                 fix_delete_line($fixlinenr, $rawline);
3333                                 my $fixedline = rtrim($prevrawline) . " {";
3334                                 fix_insert_line($fixlinenr, $fixedline);
3335                                 $fixedline = $rawline;
3336                                 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3337                                 if ($fixedline !~ /^\+\s*$/) {
3338                                         fix_insert_line($fixlinenr, $fixedline);
3339                                 }
3340                         }
3341                 }
3342
3343 # missing space after union, struct or enum definition
3344                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3345                         if (WARN("SPACING",
3346                                  "missing space after $1 definition\n" . $herecurr) &&
3347                             $fix) {
3348                                 $fixed[$fixlinenr] =~
3349                                     s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3350                         }
3351                 }
3352
3353 # Function pointer declarations
3354 # check spacing between type, funcptr, and args
3355 # canonical declaration is "type (*funcptr)(args...)"
3356                 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3357                         my $declare = $1;
3358                         my $pre_pointer_space = $2;
3359                         my $post_pointer_space = $3;
3360                         my $funcname = $4;
3361                         my $post_funcname_space = $5;
3362                         my $pre_args_space = $6;
3363
3364 # the $Declare variable will capture all spaces after the type
3365 # so check it for a missing trailing missing space but pointer return types
3366 # don't need a space so don't warn for those.
3367                         my $post_declare_space = "";
3368                         if ($declare =~ /(\s+)$/) {
3369                                 $post_declare_space = $1;
3370                                 $declare = rtrim($declare);
3371                         }
3372                         if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3373                                 WARN("SPACING",
3374                                      "missing space after return type\n" . $herecurr);
3375                                 $post_declare_space = " ";
3376                         }
3377
3378 # unnecessary space "type  (*funcptr)(args...)"
3379 # This test is not currently implemented because these declarations are
3380 # equivalent to
3381 #       int  foo(int bar, ...)
3382 # and this is form shouldn't/doesn't generate a checkpatch warning.
3383 #
3384 #                       elsif ($declare =~ /\s{2,}$/) {
3385 #                               WARN("SPACING",
3386 #                                    "Multiple spaces after return type\n" . $herecurr);
3387 #                       }
3388
3389 # unnecessary space "type ( *funcptr)(args...)"
3390                         if (defined $pre_pointer_space &&
3391                             $pre_pointer_space =~ /^\s/) {
3392                                 WARN("SPACING",
3393                                      "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3394                         }
3395
3396 # unnecessary space "type (* funcptr)(args...)"
3397                         if (defined $post_pointer_space &&
3398                             $post_pointer_space =~ /^\s/) {
3399                                 WARN("SPACING",
3400                                      "Unnecessary space before function pointer name\n" . $herecurr);
3401                         }
3402
3403 # unnecessary space "type (*funcptr )(args...)"
3404                         if (defined $post_funcname_space &&
3405                             $post_funcname_space =~ /^\s/) {
3406                                 WARN("SPACING",
3407                                      "Unnecessary space after function pointer name\n" . $herecurr);
3408                         }
3409
3410 # unnecessary space "type (*funcptr) (args...)"
3411                         if (defined $pre_args_space &&
3412                             $pre_args_space =~ /^\s/) {
3413                                 WARN("SPACING",
3414                                      "Unnecessary space before function pointer arguments\n" . $herecurr);
3415                         }
3416
3417                         if (show_type("SPACING") && $fix) {
3418                                 $fixed[$fixlinenr] =~
3419                                     s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3420                         }
3421                 }
3422
3423 # check for spacing round square brackets; allowed:
3424 #  1. with a type on the left -- int [] a;
3425 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3426 #  3. inside a curly brace -- = { [0...10] = 5 }
3427                 while ($line =~ /(.*?\s)\[/g) {
3428                         my ($where, $prefix) = ($-[1], $1);
3429                         if ($prefix !~ /$Type\s+$/ &&
3430                             ($where != 0 || $prefix !~ /^.\s+$/) &&
3431                             $prefix !~ /[{,]\s+$/) {
3432                                 if (ERROR("BRACKET_SPACE",
3433                                           "space prohibited before open square bracket '['\n" . $herecurr) &&
3434                                     $fix) {
3435                                     $fixed[$fixlinenr] =~
3436                                         s/^(\+.*?)\s+\[/$1\[/;
3437                                 }
3438                         }
3439                 }
3440
3441 # check for spaces between functions and their parentheses.
3442                 while ($line =~ /($Ident)\s+\(/g) {
3443                         my $name = $1;
3444                         my $ctx_before = substr($line, 0, $-[1]);
3445                         my $ctx = "$ctx_before$name";
3446
3447                         # Ignore those directives where spaces _are_ permitted.
3448                         if ($name =~ /^(?:
3449                                 if|for|while|switch|return|case|
3450                                 volatile|__volatile__|
3451                                 __attribute__|format|__extension__|
3452                                 asm|__asm__)$/x)
3453                         {
3454                         # cpp #define statements have non-optional spaces, ie
3455                         # if there is a space between the name and the open
3456                         # parenthesis it is simply not a parameter group.
3457                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3458
3459                         # cpp #elif statement condition may start with a (
3460                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3461
3462                         # If this whole things ends with a type its most
3463                         # likely a typedef for a function.
3464                         } elsif ($ctx =~ /$Type$/) {
3465
3466                         } else {
3467                                 if (WARN("SPACING",
3468                                          "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3469                                              $fix) {
3470                                         $fixed[$fixlinenr] =~
3471                                             s/\b$name\s+\(/$name\(/;
3472                                 }
3473                         }
3474                 }
3475
3476 # Check operator spacing.
3477                 if (!($line=~/\#\s*include/)) {
3478                         my $fixed_line = "";
3479                         my $line_fixed = 0;
3480
3481                         my $ops = qr{
3482                                 <<=|>>=|<=|>=|==|!=|
3483                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3484                                 =>|->|<<|>>|<|>|=|!|~|
3485                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3486                                 \?:|\?|:
3487                         }x;
3488                         my @elements = split(/($ops|;)/, $opline);
3489
3490 ##                      print("element count: <" . $#elements . ">\n");
3491 ##                      foreach my $el (@elements) {
3492 ##                              print("el: <$el>\n");
3493 ##                      }
3494
3495                         my @fix_elements = ();
3496                         my $off = 0;
3497
3498                         foreach my $el (@elements) {
3499                                 push(@fix_elements, substr($rawline, $off, length($el)));
3500                                 $off += length($el);
3501                         }
3502
3503                         $off = 0;
3504
3505                         my $blank = copy_spacing($opline);
3506                         my $last_after = -1;
3507
3508                         for (my $n = 0; $n < $#elements; $n += 2) {
3509
3510                                 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3511
3512 ##                              print("n: <$n> good: <$good>\n");
3513
3514                                 $off += length($elements[$n]);
3515
3516                                 # Pick up the preceding and succeeding characters.
3517                                 my $ca = substr($opline, 0, $off);
3518                                 my $cc = '';
3519                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3520                                         $cc = substr($opline, $off + length($elements[$n + 1]));
3521                                 }
3522                                 my $cb = "$ca$;$cc";
3523
3524                                 my $a = '';
3525                                 $a = 'V' if ($elements[$n] ne '');
3526                                 $a = 'W' if ($elements[$n] =~ /\s$/);
3527                                 $a = 'C' if ($elements[$n] =~ /$;$/);
3528                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3529                                 $a = 'O' if ($elements[$n] eq '');
3530                                 $a = 'E' if ($ca =~ /^\s*$/);
3531
3532                                 my $op = $elements[$n + 1];
3533
3534                                 my $c = '';
3535                                 if (defined $elements[$n + 2]) {
3536                                         $c = 'V' if ($elements[$n + 2] ne '');
3537                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3538                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3539                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3540                                         $c = 'O' if ($elements[$n + 2] eq '');
3541                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3542                                 } else {
3543                                         $c = 'E';
3544                                 }
3545
3546                                 my $ctx = "${a}x${c}";
3547
3548                                 my $at = "(ctx:$ctx)";
3549
3550                                 my $ptr = substr($blank, 0, $off) . "^";
3551                                 my $hereptr = "$hereline$ptr\n";
3552
3553                                 # Pull out the value of this operator.
3554                                 my $op_type = substr($curr_values, $off + 1, 1);
3555
3556                                 # Get the full operator variant.
3557                                 my $opv = $op . substr($curr_vars, $off, 1);
3558
3559                                 # Ignore operators passed as parameters.
3560                                 if ($op_type ne 'V' &&
3561                                     $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3562
3563 #                               # Ignore comments
3564 #                               } elsif ($op =~ /^$;+$/) {
3565
3566                                 # ; should have either the end of line or a space or \ after it
3567                                 } elsif ($op eq ';') {
3568                                         if ($ctx !~ /.x[WEBC]/ &&
3569                                             $cc !~ /^\\/ && $cc !~ /^;/) {
3570                                                 if (ERROR("SPACING",
3571                                                           "space required after that '$op' $at\n" . $hereptr)) {
3572                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3573                                                         $line_fixed = 1;
3574                                                 }
3575                                         }
3576
3577                                 # // is a comment
3578                                 } elsif ($op eq '//') {
3579
3580                                 #   :   when part of a bitfield
3581                                 } elsif ($opv eq ':B') {
3582                                         # skip the bitfield test for now
3583
3584                                 # No spaces for:
3585                                 #   ->
3586                                 } elsif ($op eq '->') {
3587                                         if ($ctx =~ /Wx.|.xW/) {
3588                                                 if (ERROR("SPACING",
3589                                                           "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3590                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3591                                                         if (defined $fix_elements[$n + 2]) {
3592                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3593                                                         }
3594                                                         $line_fixed = 1;
3595                                                 }
3596                                         }
3597
3598                                 # , must not have a space before and must have a space on the right.
3599                                 } elsif ($op eq ',') {
3600                                         my $rtrim_before = 0;
3601                                         my $space_after = 0;
3602                                         if ($ctx =~ /Wx./) {
3603                                                 if (ERROR("SPACING",
3604                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
3605                                                         $line_fixed = 1;
3606                                                         $rtrim_before = 1;
3607                                                 }
3608                                         }
3609                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3610                                                 if (ERROR("SPACING",
3611                                                           "space required after that '$op' $at\n" . $hereptr)) {
3612                                                         $line_fixed = 1;
3613                                                         $last_after = $n;
3614                                                         $space_after = 1;
3615                                                 }
3616                                         }
3617                                         if ($rtrim_before || $space_after) {
3618                                                 if ($rtrim_before) {
3619                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3620                                                 } else {
3621                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3622                                                 }
3623                                                 if ($space_after) {
3624                                                         $good .= " ";
3625                                                 }
3626                                         }
3627
3628                                 # '*' as part of a type definition -- reported already.
3629                                 } elsif ($opv eq '*_') {
3630                                         #warn "'*' is part of type\n";
3631
3632                                 # unary operators should have a space before and
3633                                 # none after.  May be left adjacent to another
3634                                 # unary operator, or a cast
3635                                 } elsif ($op eq '!' || $op eq '~' ||
3636                                          $opv eq '*U' || $opv eq '-U' ||
3637                                          $opv eq '&U' || $opv eq '&&U') {
3638                                         if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3639                                                 if (ERROR("SPACING",
3640                                                           "space required before that '$op' $at\n" . $hereptr)) {
3641                                                         if ($n != $last_after + 2) {
3642                                                                 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3643                                                                 $line_fixed = 1;
3644                                                         }
3645                                                 }
3646                                         }
3647                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3648                                                 # A unary '*' may be const
3649
3650                                         } elsif ($ctx =~ /.xW/) {
3651                                                 if (ERROR("SPACING",
3652                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
3653                                                         $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3654                                                         if (defined $fix_elements[$n + 2]) {
3655                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3656                                                         }
3657                                                         $line_fixed = 1;
3658                                                 }
3659                                         }
3660
3661                                 # unary ++ and unary -- are allowed no space on one side.
3662                                 } elsif ($op eq '++' or $op eq '--') {
3663                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3664                                                 if (ERROR("SPACING",
3665                                                           "space required one side of that '$op' $at\n" . $hereptr)) {
3666                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3667                                                         $line_fixed = 1;
3668                                                 }
3669                                         }
3670                                         if ($ctx =~ /Wx[BE]/ ||
3671                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3672                                                 if (ERROR("SPACING",
3673                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
3674                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3675                                                         $line_fixed = 1;
3676                                                 }
3677                                         }
3678                                         if ($ctx =~ /ExW/) {
3679                                                 if (ERROR("SPACING",
3680                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
3681                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3682                                                         if (defined $fix_elements[$n + 2]) {
3683                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3684                                                         }
3685                                                         $line_fixed = 1;
3686                                                 }
3687                                         }
3688
3689                                 # << and >> may either have or not have spaces both sides
3690                                 } elsif ($op eq '<<' or $op eq '>>' or
3691                                          $op eq '&' or $op eq '^' or $op eq '|' or
3692                                          $op eq '+' or $op eq '-' or
3693                                          $op eq '*' or $op eq '/' or
3694                                          $op eq '%')
3695                                 {
3696                                         if ($check) {
3697                                                 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
3698                                                         if (CHK("SPACING",
3699                                                                 "spaces preferred around that '$op' $at\n" . $hereptr)) {
3700                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3701                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3702                                                                 $line_fixed = 1;
3703                                                         }
3704                                                 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
3705                                                         if (CHK("SPACING",
3706                                                                 "space preferred before that '$op' $at\n" . $hereptr)) {
3707                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
3708                                                                 $line_fixed = 1;
3709                                                         }
3710                                                 }
3711                                         } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3712                                                 if (ERROR("SPACING",
3713                                                           "need consistent spacing around '$op' $at\n" . $hereptr)) {
3714                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3715                                                         if (defined $fix_elements[$n + 2]) {
3716                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3717                                                         }
3718                                                         $line_fixed = 1;
3719                                                 }
3720                                         }
3721
3722                                 # A colon needs no spaces before when it is
3723                                 # terminating a case value or a label.
3724                                 } elsif ($opv eq ':C' || $opv eq ':L') {
3725                                         if ($ctx =~ /Wx./) {
3726                                                 if (ERROR("SPACING",
3727                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
3728                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3729                                                         $line_fixed = 1;
3730                                                 }
3731                                         }
3732
3733                                 # All the others need spaces both sides.
3734                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3735                                         my $ok = 0;
3736
3737                                         # Ignore email addresses <foo@bar>
3738                                         if (($op eq '<' &&
3739                                              $cc =~ /^\S+\@\S+>/) ||
3740                                             ($op eq '>' &&
3741                                              $ca =~ /<\S+\@\S+$/))
3742                                         {
3743                                                 $ok = 1;
3744                                         }
3745
3746                                         # messages are ERROR, but ?: are CHK
3747                                         if ($ok == 0) {
3748                                                 my $msg_type = \&ERROR;
3749                                                 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3750
3751                                                 if (&{$msg_type}("SPACING",
3752                                                                  "spaces required around that '$op' $at\n" . $hereptr)) {
3753                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3754                                                         if (defined $fix_elements[$n + 2]) {
3755                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
3756                                                         }
3757                                                         $line_fixed = 1;
3758                                                 }
3759                                         }
3760                                 }
3761                                 $off += length($elements[$n + 1]);
3762
3763 ##                              print("n: <$n> GOOD: <$good>\n");
3764
3765                                 $fixed_line = $fixed_line . $good;
3766                         }
3767
3768                         if (($#elements % 2) == 0) {
3769                                 $fixed_line = $fixed_line . $fix_elements[$#elements];
3770                         }
3771
3772                         if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3773                                 $fixed[$fixlinenr] = $fixed_line;
3774                         }
3775
3776
3777                 }
3778
3779 # check for whitespace before a non-naked semicolon
3780                 if ($line =~ /^\+.*\S\s+;\s*$/) {
3781                         if (WARN("SPACING",
3782                                  "space prohibited before semicolon\n" . $herecurr) &&
3783                             $fix) {
3784                                 1 while $fixed[$fixlinenr] =~
3785                                     s/^(\+.*\S)\s+;/$1;/;
3786                         }
3787                 }
3788
3789 # check for multiple assignments
3790                 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3791                         CHK("MULTIPLE_ASSIGNMENTS",
3792                             "multiple assignments should be avoided\n" . $herecurr);
3793                 }
3794
3795 ## # check for multiple declarations, allowing for a function declaration
3796 ## # continuation.
3797 ##              if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3798 ##                  $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3799 ##
3800 ##                      # Remove any bracketed sections to ensure we do not
3801 ##                      # falsly report the parameters of functions.
3802 ##                      my $ln = $line;
3803 ##                      while ($ln =~ s/\([^\(\)]*\)//g) {
3804 ##                      }
3805 ##                      if ($ln =~ /,/) {
3806 ##                              WARN("MULTIPLE_DECLARATION",
3807 ##                                   "declaring multiple variables together should be avoided\n" . $herecurr);
3808 ##                      }
3809 ##              }
3810
3811 #need space before brace following if, while, etc
3812                 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3813                     $line =~ /do{/) {
3814                         if (ERROR("SPACING",
3815                                   "space required before the open brace '{'\n" . $herecurr) &&
3816                             $fix) {
3817                                 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3818                         }
3819                 }
3820
3821 ## # check for blank lines before declarations
3822 ##              if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3823 ##                  $prevrawline =~ /^.\s*$/) {
3824 ##                      WARN("SPACING",
3825 ##                           "No blank lines before declarations\n" . $hereprev);
3826 ##              }
3827 ##
3828
3829 # closing brace should have a space following it when it has anything
3830 # on the line
3831                 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3832                         if (ERROR("SPACING",
3833                                   "space required after that close brace '}'\n" . $herecurr) &&
3834                             $fix) {
3835                                 $fixed[$fixlinenr] =~
3836                                     s/}((?!(?:,|;|\)))\S)/} $1/;
3837                         }
3838                 }
3839
3840 # check spacing on square brackets
3841                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3842                         if (ERROR("SPACING",
3843                                   "space prohibited after that open square bracket '['\n" . $herecurr) &&
3844                             $fix) {
3845                                 $fixed[$fixlinenr] =~
3846                                     s/\[\s+/\[/;
3847                         }
3848                 }
3849                 if ($line =~ /\s\]/) {
3850                         if (ERROR("SPACING",
3851                                   "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3852                             $fix) {
3853                                 $fixed[$fixlinenr] =~
3854                                     s/\s+\]/\]/;
3855                         }
3856                 }
3857
3858 # check spacing on parentheses
3859                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3860                     $line !~ /for\s*\(\s+;/) {
3861                         if (ERROR("SPACING",
3862                                   "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3863                             $fix) {
3864                                 $fixed[$fixlinenr] =~
3865                                     s/\(\s+/\(/;
3866                         }
3867                 }
3868                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3869                     $line !~ /for\s*\(.*;\s+\)/ &&
3870                     $line !~ /:\s+\)/) {
3871                         if (ERROR("SPACING",
3872                                   "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3873                             $fix) {
3874                                 $fixed[$fixlinenr] =~
3875                                     s/\s+\)/\)/;
3876                         }
3877                 }
3878
3879 # check unnecessary parentheses around addressof/dereference single $Lvals
3880 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3881
3882                 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3883                         my $var = $1;
3884                         if (CHK("UNNECESSARY_PARENTHESES",
3885                                 "Unnecessary parentheses around $var\n" . $herecurr) &&
3886                             $fix) {
3887                                 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3888                         }
3889                 }
3890
3891 # check for unnecessary parentheses around function pointer uses
3892 # ie: (foo->bar)(); should be foo->bar();
3893 # but not "if (foo->bar) (" to avoid some false positives
3894                 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3895                         my $var = $2;
3896                         if (CHK("UNNECESSARY_PARENTHESES",
3897                                 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3898                             $fix) {
3899                                 my $var2 = deparenthesize($var);
3900                                 $var2 =~ s/\s//g;
3901                                 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3902                         }
3903                 }
3904
3905 #goto labels aren't indented, allow a single space however
3906                 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3907                    !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3908                         if (WARN("INDENTED_LABEL",
3909                                  "labels should not be indented\n" . $herecurr) &&
3910                             $fix) {
3911                                 $fixed[$fixlinenr] =~
3912                                     s/^(.)\s+/$1/;
3913                         }
3914                 }
3915
3916 # return is not a function
3917                 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3918                         my $spacing = $1;
3919                         if ($^V && $^V ge 5.10.0 &&
3920                             $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3921                                 my $value = $1;
3922                                 $value = deparenthesize($value);
3923                                 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3924                                         ERROR("RETURN_PARENTHESES",
3925                                               "return is not a function, parentheses are not required\n" . $herecurr);
3926                                 }
3927                         } elsif ($spacing !~ /\s+/) {
3928                                 ERROR("SPACING",
3929                                       "space required before the open parenthesis '('\n" . $herecurr);
3930                         }
3931                 }
3932
3933 # unnecessary return in a void function
3934 # at end-of-function, with the previous line a single leading tab, then return;
3935 # and the line before that not a goto label target like "out:"
3936                 if ($sline =~ /^[ \+]}\s*$/ &&
3937                     $prevline =~ /^\+\treturn\s*;\s*$/ &&
3938                     $linenr >= 3 &&
3939                     $lines[$linenr - 3] =~ /^[ +]/ &&
3940                     $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3941                         WARN("RETURN_VOID",
3942                              "void function return statements are not generally useful\n" . $hereprev);
3943                }
3944
3945 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3946                 if ($^V && $^V ge 5.10.0 &&
3947                     $line =~ /\bif\s*((?:\(\s*){2,})/) {
3948                         my $openparens = $1;
3949                         my $count = $openparens =~ tr@\(@\(@;
3950                         my $msg = "";
3951                         if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3952                                 my $comp = $4;  #Not $1 because of $LvalOrFunc
3953                                 $msg = " - maybe == should be = ?" if ($comp eq "==");
3954                                 WARN("UNNECESSARY_PARENTHESES",
3955                                      "Unnecessary parentheses$msg\n" . $herecurr);
3956                         }
3957                 }
3958
3959 # Return of what appears to be an errno should normally be -'ve
3960                 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3961                         my $name = $1;
3962                         if ($name ne 'EOF' && $name ne 'ERROR') {
3963                                 WARN("USE_NEGATIVE_ERRNO",
3964                                      "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3965                         }
3966                 }
3967
3968 # Need a space before open parenthesis after if, while etc
3969                 if ($line =~ /\b(if|while|for|switch)\(/) {
3970                         if (ERROR("SPACING",
3971                                   "space required before the open parenthesis '('\n" . $herecurr) &&
3972                             $fix) {
3973                                 $fixed[$fixlinenr] =~
3974                                     s/\b(if|while|for|switch)\(/$1 \(/;
3975                         }
3976                 }
3977
3978 # Check for illegal assignment in if conditional -- and check for trailing
3979 # statements after the conditional.
3980                 if ($line =~ /do\s*(?!{)/) {
3981                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3982                                 ctx_statement_block($linenr, $realcnt, 0)
3983                                         if (!defined $stat);
3984                         my ($stat_next) = ctx_statement_block($line_nr_next,
3985                                                 $remain_next, $off_next);
3986                         $stat_next =~ s/\n./\n /g;
3987                         ##print "stat<$stat> stat_next<$stat_next>\n";
3988
3989                         if ($stat_next =~ /^\s*while\b/) {
3990                                 # If the statement carries leading newlines,
3991                                 # then count those as offsets.
3992                                 my ($whitespace) =
3993                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3994                                 my $offset =
3995                                         statement_rawlines($whitespace) - 1;
3996
3997                                 $suppress_whiletrailers{$line_nr_next +
3998                                                                 $offset} = 1;
3999                         }
4000                 }
4001                 if (!defined $suppress_whiletrailers{$linenr} &&
4002                     defined($stat) && defined($cond) &&
4003                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4004                         my ($s, $c) = ($stat, $cond);
4005
4006                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4007                                 ERROR("ASSIGN_IN_IF",
4008                                       "do not use assignment in if condition\n" . $herecurr);
4009                         }
4010
4011                         # Find out what is on the end of the line after the
4012                         # conditional.
4013                         substr($s, 0, length($c), '');
4014                         $s =~ s/\n.*//g;
4015                         $s =~ s/$;//g;  # Remove any comments
4016                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4017                             $c !~ /}\s*while\s*/)
4018                         {
4019                                 # Find out how long the conditional actually is.
4020                                 my @newlines = ($c =~ /\n/gs);
4021                                 my $cond_lines = 1 + $#newlines;
4022                                 my $stat_real = '';
4023
4024                                 $stat_real = raw_line($linenr, $cond_lines)
4025                                                         . "\n" if ($cond_lines);
4026                                 if (defined($stat_real) && $cond_lines > 1) {
4027                                         $stat_real = "[...]\n$stat_real";
4028                                 }
4029
4030                                 ERROR("TRAILING_STATEMENTS",
4031                                       "trailing statements should be on next line\n" . $herecurr . $stat_real);
4032                         }
4033                 }
4034
4035 # Check for bitwise tests written as boolean
4036                 if ($line =~ /
4037                         (?:
4038                                 (?:\[|\(|\&\&|\|\|)
4039                                 \s*0[xX][0-9]+\s*
4040                                 (?:\&\&|\|\|)
4041                         |
4042                                 (?:\&\&|\|\|)
4043                                 \s*0[xX][0-9]+\s*
4044                                 (?:\&\&|\|\||\)|\])
4045                         )/x)
4046                 {
4047                         WARN("HEXADECIMAL_BOOLEAN_TEST",
4048                              "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4049                 }
4050
4051 # if and else should not have general statements after it
4052                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4053                         my $s = $1;
4054                         $s =~ s/$;//g;  # Remove any comments
4055                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4056                                 ERROR("TRAILING_STATEMENTS",
4057                                       "trailing statements should be on next line\n" . $herecurr);
4058                         }
4059                 }
4060 # if should not continue a brace
4061                 if ($line =~ /}\s*if\b/) {
4062                         ERROR("TRAILING_STATEMENTS",
4063                               "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4064                                 $herecurr);
4065                 }
4066 # case and default should not have general statements after them
4067                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4068                     $line !~ /\G(?:
4069                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4070                         \s*return\s+
4071                     )/xg)
4072                 {
4073                         ERROR("TRAILING_STATEMENTS",
4074                               "trailing statements should be on next line\n" . $herecurr);
4075                 }
4076
4077                 # Check for }<nl>else {, these must be at the same
4078                 # indent level to be relevant to each other.
4079                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4080                     $previndent == $indent) {
4081                         if (ERROR("ELSE_AFTER_BRACE",
4082                                   "else should follow close brace '}'\n" . $hereprev) &&
4083                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4084                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4085                                 fix_delete_line($fixlinenr, $rawline);
4086                                 my $fixedline = $prevrawline;
4087                                 $fixedline =~ s/}\s*$//;
4088                                 if ($fixedline !~ /^\+\s*$/) {
4089                                         fix_insert_line($fixlinenr, $fixedline);
4090                                 }
4091                                 $fixedline = $rawline;
4092                                 $fixedline =~ s/^(.\s*)else/$1} else/;
4093                                 fix_insert_line($fixlinenr, $fixedline);
4094                         }
4095                 }
4096
4097                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4098                     $previndent == $indent) {
4099                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4100
4101                         # Find out what is on the end of the line after the
4102                         # conditional.
4103                         substr($s, 0, length($c), '');
4104                         $s =~ s/\n.*//g;
4105
4106                         if ($s =~ /^\s*;/) {
4107                                 if (ERROR("WHILE_AFTER_BRACE",
4108                                           "while should follow close brace '}'\n" . $hereprev) &&
4109                                     $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4110                                         fix_delete_line($fixlinenr - 1, $prevrawline);
4111                                         fix_delete_line($fixlinenr, $rawline);
4112                                         my $fixedline = $prevrawline;
4113                                         my $trailing = $rawline;
4114                                         $trailing =~ s/^\+//;
4115                                         $trailing = trim($trailing);
4116                                         $fixedline =~ s/}\s*$/} $trailing/;
4117                                         fix_insert_line($fixlinenr, $fixedline);
4118                                 }
4119                         }
4120                 }
4121
4122 #Specific variable tests
4123                 while ($line =~ m{($Constant|$Lval)}g) {
4124                         my $var = $1;
4125
4126 #gcc binary extension
4127                         if ($var =~ /^$Binary$/) {
4128                                 if (WARN("GCC_BINARY_CONSTANT",
4129                                          "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4130                                     $fix) {
4131                                         my $hexval = sprintf("0x%x", oct($var));
4132                                         $fixed[$fixlinenr] =~
4133                                             s/\b$var\b/$hexval/;
4134                                 }
4135                         }
4136
4137 #CamelCase
4138                         if ($var !~ /^$Constant$/ &&
4139                             $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4140 #Ignore Page<foo> variants
4141                             $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4142 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4143                             $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4144 #Ignore some three character SI units explicitly, like MiB and KHz
4145                             $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4146                                 while ($var =~ m{($Ident)}g) {
4147                                         my $word = $1;
4148                                         next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4149                                         if ($check) {
4150                                                 seed_camelcase_includes();
4151                                                 if (!$file && !$camelcase_file_seeded) {
4152                                                         seed_camelcase_file($realfile);
4153                                                         $camelcase_file_seeded = 1;
4154                                                 }
4155                                         }
4156                                         if (!defined $camelcase{$word}) {
4157                                                 $camelcase{$word} = 1;
4158                                                 CHK("CAMELCASE",
4159                                                     "Avoid CamelCase: <$word>\n" . $herecurr);
4160                                         }
4161                                 }
4162                         }
4163                 }
4164
4165 #no spaces allowed after \ in define
4166                 if ($line =~ /\#\s*define.*\\\s+$/) {
4167                         if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4168                                  "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4169                             $fix) {
4170                                 $fixed[$fixlinenr] =~ s/\s+$//;
4171                         }
4172                 }
4173
4174 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4175                 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4176                         my $file = "$1.h";
4177                         my $checkfile = "include/linux/$file";
4178                         if (-f "$root/$checkfile" &&
4179                             $realfile ne $checkfile &&
4180                             $1 !~ /$allowed_asm_includes/)
4181                         {
4182                                 if ($realfile =~ m{^arch/}) {
4183                                         CHK("ARCH_INCLUDE_LINUX",
4184                                             "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4185                                 } else {
4186                                         WARN("INCLUDE_LINUX",
4187                                              "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4188                                 }
4189                         }
4190                 }
4191
4192 # multi-statement macros should be enclosed in a do while loop, grab the
4193 # first statement and ensure its the whole macro if its not enclosed
4194 # in a known good container
4195                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4196                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4197                         my $ln = $linenr;
4198                         my $cnt = $realcnt;
4199                         my ($off, $dstat, $dcond, $rest);
4200                         my $ctx = '';
4201                         my $has_flow_statement = 0;
4202                         my $has_arg_concat = 0;
4203                         ($dstat, $dcond, $ln, $cnt, $off) =
4204                                 ctx_statement_block($linenr, $realcnt, 0);
4205                         $ctx = $dstat;
4206                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4207                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4208
4209                         $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4210                         $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4211
4212                         $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4213                         $dstat =~ s/$;//g;
4214                         $dstat =~ s/\\\n.//g;
4215                         $dstat =~ s/^\s*//s;
4216                         $dstat =~ s/\s*$//s;
4217
4218                         # Flatten any parentheses and braces
4219                         while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4220                                $dstat =~ s/\{[^\{\}]*\}/1/ ||
4221                                $dstat =~ s/\[[^\[\]]*\]/1/)
4222                         {
4223                         }
4224
4225                         # Flatten any obvious string concatentation.
4226                         while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4227                                $dstat =~ s/$Ident\s*("X*")/$1/)
4228                         {
4229                         }
4230
4231                         my $exceptions = qr{
4232                                 $Declare|
4233                                 module_param_named|
4234                                 MODULE_PARM_DESC|
4235                                 DECLARE_PER_CPU|
4236                                 DEFINE_PER_CPU|
4237                                 __typeof__\(|
4238                                 union|
4239                                 struct|
4240                                 \.$Ident\s*=\s*|
4241                                 ^\"|\"$
4242                         }x;
4243                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4244                         if ($dstat ne '' &&
4245                             $dstat !~ /^(?:$Ident|-?$Constant),$/ &&                    # 10, // foo(),
4246                             $dstat !~ /^(?:$Ident|-?$Constant);$/ &&                    # foo();
4247                             $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&          # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4248                             $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&                  # character constants
4249                             $dstat !~ /$exceptions/ &&
4250                             $dstat !~ /^\.$Ident\s*=/ &&                                # .foo =
4251                             $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&          # stringification #foo
4252                             $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&       # do {...} while (...); // do {...} while (...)
4253                             $dstat !~ /^for\s*$Constant$/ &&                            # for (...)
4254                             $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&   # for (...) bar()
4255                             $dstat !~ /^do\s*{/ &&                                      # do {...
4256                             $dstat !~ /^\({/ &&                                         # ({...
4257                             $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4258                         {
4259                                 $ctx =~ s/\n*$//;
4260                                 my $herectx = $here . "\n";
4261                                 my $cnt = statement_rawlines($ctx);
4262
4263                                 for (my $n = 0; $n < $cnt; $n++) {
4264                                         $herectx .= raw_line($linenr, $n) . "\n";
4265                                 }
4266
4267                                 if ($dstat =~ /;/) {
4268                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4269                                               "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4270                                 } else {
4271                                         ERROR("COMPLEX_MACRO",
4272                                               "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4273                                 }
4274                         }
4275
4276 # check for macros with flow control, but without ## concatenation
4277 # ## concatenation is commonly a macro that defines a function so ignore those
4278                         if ($has_flow_statement && !$has_arg_concat) {
4279                                 my $herectx = $here . "\n";
4280                                 my $cnt = statement_rawlines($ctx);
4281
4282                                 for (my $n = 0; $n < $cnt; $n++) {
4283                                         $herectx .= raw_line($linenr, $n) . "\n";
4284                                 }
4285                                 WARN("MACRO_WITH_FLOW_CONTROL",
4286                                      "Macros with flow control statements should be avoided\n" . "$herectx");
4287                         }
4288
4289 # check for line continuations outside of #defines, preprocessor #, and asm
4290
4291                 } else {
4292                         if ($prevline !~ /^..*\\$/ &&
4293                             $line !~ /^\+\s*\#.*\\$/ &&         # preprocessor
4294                             $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&   # asm
4295                             $line =~ /^\+.*\\$/) {
4296                                 WARN("LINE_CONTINUATIONS",
4297                                      "Avoid unnecessary line continuations\n" . $herecurr);
4298                         }
4299                 }
4300
4301 # do {} while (0) macro tests:
4302 # single-statement macros do not need to be enclosed in do while (0) loop,
4303 # macro should not end with a semicolon
4304                 if ($^V && $^V ge 5.10.0 &&
4305                     $realfile !~ m@/vmlinux.lds.h$@ &&
4306                     $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4307                         my $ln = $linenr;
4308                         my $cnt = $realcnt;
4309                         my ($off, $dstat, $dcond, $rest);
4310                         my $ctx = '';
4311                         ($dstat, $dcond, $ln, $cnt, $off) =
4312                                 ctx_statement_block($linenr, $realcnt, 0);
4313                         $ctx = $dstat;
4314
4315                         $dstat =~ s/\\\n.//g;
4316                         $dstat =~ s/$;/ /g;
4317
4318                         if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4319                                 my $stmts = $2;
4320                                 my $semis = $3;
4321
4322                                 $ctx =~ s/\n*$//;
4323                                 my $cnt = statement_rawlines($ctx);
4324                                 my $herectx = $here . "\n";
4325
4326                                 for (my $n = 0; $n < $cnt; $n++) {
4327                                         $herectx .= raw_line($linenr, $n) . "\n";
4328                                 }
4329
4330                                 if (($stmts =~ tr/;/;/) == 1 &&
4331                                     $stmts !~ /^\s*(if|while|for|switch)\b/) {
4332                                         WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4333                                              "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4334                                 }
4335                                 if (defined $semis && $semis ne "") {
4336                                         WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4337                                              "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4338                                 }
4339                         } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4340                                 $ctx =~ s/\n*$//;
4341                                 my $cnt = statement_rawlines($ctx);
4342                                 my $herectx = $here . "\n";
4343
4344                                 for (my $n = 0; $n < $cnt; $n++) {
4345                                         $herectx .= raw_line($linenr, $n) . "\n";
4346                                 }
4347
4348                                 WARN("TRAILING_SEMICOLON",
4349                                      "macros should not use a trailing semicolon\n" . "$herectx");
4350                         }
4351                 }
4352
4353 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4354 # all assignments may have only one of the following with an assignment:
4355 #       .
4356 #       ALIGN(...)
4357 #       VMLINUX_SYMBOL(...)
4358                 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4359                         WARN("MISSING_VMLINUX_SYMBOL",
4360                              "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4361                 }
4362
4363 # check for redundant bracing round if etc
4364                 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4365                         my ($level, $endln, @chunks) =
4366                                 ctx_statement_full($linenr, $realcnt, 1);
4367                         #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4368                         #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4369                         if ($#chunks > 0 && $level == 0) {
4370                                 my @allowed = ();
4371                                 my $allow = 0;
4372                                 my $seen = 0;
4373                                 my $herectx = $here . "\n";
4374                                 my $ln = $linenr - 1;
4375                                 for my $chunk (@chunks) {
4376                                         my ($cond, $block) = @{$chunk};
4377
4378                                         # If the condition carries leading newlines, then count those as offsets.
4379                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4380                                         my $offset = statement_rawlines($whitespace) - 1;
4381
4382                                         $allowed[$allow] = 0;
4383                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4384
4385                                         # We have looked at and allowed this specific line.
4386                                         $suppress_ifbraces{$ln + $offset} = 1;
4387
4388                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4389                                         $ln += statement_rawlines($block) - 1;
4390
4391                                         substr($block, 0, length($cond), '');
4392
4393                                         $seen++ if ($block =~ /^\s*{/);
4394
4395                                         #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4396                                         if (statement_lines($cond) > 1) {
4397                                                 #print "APW: ALLOWED: cond<$cond>\n";
4398                                                 $allowed[$allow] = 1;
4399                                         }
4400                                         if ($block =~/\b(?:if|for|while)\b/) {
4401                                                 #print "APW: ALLOWED: block<$block>\n";
4402                                                 $allowed[$allow] = 1;
4403                                         }
4404                                         if (statement_block_size($block) > 1) {
4405                                                 #print "APW: ALLOWED: lines block<$block>\n";
4406                                                 $allowed[$allow] = 1;
4407                                         }
4408                                         $allow++;
4409                                 }
4410                                 if ($seen) {
4411                                         my $sum_allowed = 0;
4412                                         foreach (@allowed) {
4413                                                 $sum_allowed += $_;
4414                                         }
4415                                         if ($sum_allowed == 0) {
4416                                                 WARN("BRACES",
4417                                                      "braces {} are not necessary for any arm of this statement\n" . $herectx);
4418                                         } elsif ($sum_allowed != $allow &&
4419                                                  $seen != $allow) {
4420                                                 CHK("BRACES",
4421                                                     "braces {} should be used on all arms of this statement\n" . $herectx);
4422                                         }
4423                                 }
4424                         }
4425                 }
4426                 if (!defined $suppress_ifbraces{$linenr - 1} &&
4427                                         $line =~ /\b(if|while|for|else)\b/) {
4428                         my $allowed = 0;
4429
4430                         # Check the pre-context.
4431                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4432                                 #print "APW: ALLOWED: pre<$1>\n";
4433                                 $allowed = 1;
4434                         }
4435
4436                         my ($level, $endln, @chunks) =
4437                                 ctx_statement_full($linenr, $realcnt, $-[0]);
4438
4439                         # Check the condition.
4440                         my ($cond, $block) = @{$chunks[0]};
4441                         #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4442                         if (defined $cond) {
4443                                 substr($block, 0, length($cond), '');
4444                         }
4445                         if (statement_lines($cond) > 1) {
4446                                 #print "APW: ALLOWED: cond<$cond>\n";
4447                                 $allowed = 1;
4448                         }
4449                         if ($block =~/\b(?:if|for|while)\b/) {
4450                                 #print "APW: ALLOWED: block<$block>\n";
4451                                 $allowed = 1;
4452                         }
4453                         if (statement_block_size($block) > 1) {
4454                                 #print "APW: ALLOWED: lines block<$block>\n";
4455                                 $allowed = 1;
4456                         }
4457                         # Check the post-context.
4458                         if (defined $chunks[1]) {
4459                                 my ($cond, $block) = @{$chunks[1]};
4460                                 if (defined $cond) {
4461                                         substr($block, 0, length($cond), '');
4462                                 }
4463                                 if ($block =~ /^\s*\{/) {
4464                                         #print "APW: ALLOWED: chunk-1 block<$block>\n";
4465                                         $allowed = 1;
4466                                 }
4467                         }
4468                         if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4469                                 my $herectx = $here . "\n";
4470                                 my $cnt = statement_rawlines($block);
4471
4472                                 for (my $n = 0; $n < $cnt; $n++) {
4473                                         $herectx .= raw_line($linenr, $n) . "\n";
4474                                 }
4475
4476                                 WARN("BRACES",
4477                                      "braces {} are not necessary for single statement blocks\n" . $herectx);
4478                         }
4479                 }
4480
4481 # check for unnecessary blank lines around braces
4482                 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4483                         if (CHK("BRACES",
4484                                 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4485                             $fix && $prevrawline =~ /^\+/) {
4486                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4487                         }
4488                 }
4489                 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4490                         if (CHK("BRACES",
4491                                 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4492                             $fix) {
4493                                 fix_delete_line($fixlinenr, $rawline);
4494                         }
4495                 }
4496
4497 # no volatiles please
4498                 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4499                 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4500                         WARN("VOLATILE",
4501                              "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4502                 }
4503
4504 # Check for user-visible strings broken across lines, which breaks the ability
4505 # to grep for the string.  Make exceptions when the previous string ends in a
4506 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4507 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4508                 if ($line =~ /^\+\s*"[X\t]*"/ &&
4509                     $prevline =~ /"\s*$/ &&
4510                     $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4511                         if (WARN("SPLIT_STRING",
4512                                  "quoted string split across lines\n" . $hereprev) &&
4513                                      $fix &&
4514                                      $prevrawline =~ /^\+.*"\s*$/ &&
4515                                      $last_coalesced_string_linenr != $linenr - 1) {
4516                                 my $extracted_string = get_quoted_string($line, $rawline);
4517                                 my $comma_close = "";
4518                                 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4519                                         $comma_close = $1;
4520                                 }
4521
4522                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4523                                 fix_delete_line($fixlinenr, $rawline);
4524                                 my $fixedline = $prevrawline;
4525                                 $fixedline =~ s/"\s*$//;
4526                                 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4527                                 fix_insert_line($fixlinenr - 1, $fixedline);
4528                                 $fixedline = $rawline;
4529                                 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4530                                 if ($fixedline !~ /\+\s*$/) {
4531                                         fix_insert_line($fixlinenr, $fixedline);
4532                                 }
4533                                 $last_coalesced_string_linenr = $linenr;
4534                         }
4535                 }
4536
4537 # check for missing a space in a string concatenation
4538                 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4539                         WARN('MISSING_SPACE',
4540                              "break quoted strings at a space character\n" . $hereprev);
4541                 }
4542
4543 # check for spaces before a quoted newline
4544                 if ($rawline =~ /^.*\".*\s\\n/) {
4545                         if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4546                                  "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4547                             $fix) {
4548                                 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4549                         }
4550
4551                 }
4552
4553 # concatenated string without spaces between elements
4554                 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4555                         CHK("CONCATENATED_STRING",
4556                             "Concatenated strings should use spaces between elements\n" . $herecurr);
4557                 }
4558
4559 # uncoalesced string fragments
4560                 if ($line =~ /"X*"\s*"/) {
4561                         WARN("STRING_FRAGMENTS",
4562                              "Consecutive strings are generally better as a single string\n" . $herecurr);
4563                 }
4564
4565 # check for %L{u,d,i} in strings
4566                 my $string;
4567                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4568                         $string = substr($rawline, $-[1], $+[1] - $-[1]);
4569                         $string =~ s/%%/__/g;
4570                         if ($string =~ /(?<!%)%L[udi]/) {
4571                                 WARN("PRINTF_L",
4572                                      "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4573                                 last;
4574                         }
4575                 }
4576
4577 # check for line continuations in quoted strings with odd counts of "
4578                 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4579                         WARN("LINE_CONTINUATIONS",
4580                              "Avoid line continuations in quoted strings\n" . $herecurr);
4581                 }
4582
4583 # warn about #if 0
4584                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4585                         CHK("REDUNDANT_CODE",
4586                             "if this code is redundant consider removing it\n" .
4587                                 $herecurr);
4588                 }
4589
4590 # check for needless "if (<foo>) fn(<foo>)" uses
4591                 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4592                         my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4593                         if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4594                                 WARN('NEEDLESS_IF',
4595                                      "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4596                         }
4597                 }
4598
4599 # check for unnecessary "Out of Memory" messages
4600                 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4601                     $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4602                     (defined $1 || defined $3) &&
4603                     $linenr > 3) {
4604                         my $testval = $2;
4605                         my $testline = $lines[$linenr - 3];
4606
4607                         my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4608 #                       print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4609
4610                         if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4611                                 WARN("OOM_MESSAGE",
4612                                      "Possible unnecessary 'out of memory' message\n" . $hereprev);
4613                         }
4614                 }
4615
4616 # check for logging functions with KERN_<LEVEL>
4617                 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4618                     $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4619                         my $level = $1;
4620                         if (WARN("UNNECESSARY_KERN_LEVEL",
4621                                  "Possible unnecessary $level\n" . $herecurr) &&
4622                             $fix) {
4623                                 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4624                         }
4625                 }
4626
4627 # check for mask then right shift without a parentheses
4628                 if ($^V && $^V ge 5.10.0 &&
4629                     $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4630                     $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4631                         WARN("MASK_THEN_SHIFT",
4632                              "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4633                 }
4634
4635 # check for pointer comparisons to NULL
4636                 if ($^V && $^V ge 5.10.0) {
4637                         while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4638                                 my $val = $1;
4639                                 my $equal = "!";
4640                                 $equal = "" if ($4 eq "!=");
4641                                 if (CHK("COMPARISON_TO_NULL",
4642                                         "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4643                                             $fix) {
4644                                         $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4645                                 }
4646                         }
4647                 }
4648
4649 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4650                 if ($line =~ /(\b$InitAttribute\b)/) {
4651                         my $attr = $1;
4652                         if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4653                                 my $ptr = $1;
4654                                 my $var = $2;
4655                                 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4656                                       ERROR("MISPLACED_INIT",
4657                                             "$attr should be placed after $var\n" . $herecurr)) ||
4658                                      ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4659                                       WARN("MISPLACED_INIT",
4660                                            "$attr should be placed after $var\n" . $herecurr))) &&
4661                                     $fix) {
4662                                         $fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
4663                                 }
4664                         }
4665                 }
4666
4667 # check for $InitAttributeData (ie: __initdata) with const
4668                 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4669                         my $attr = $1;
4670                         $attr =~ /($InitAttributePrefix)(.*)/;
4671                         my $attr_prefix = $1;
4672                         my $attr_type = $2;
4673                         if (ERROR("INIT_ATTRIBUTE",
4674                                   "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4675                             $fix) {
4676                                 $fixed[$fixlinenr] =~
4677                                     s/$InitAttributeData/${attr_prefix}initconst/;
4678                         }
4679                 }
4680
4681 # check for $InitAttributeConst (ie: __initconst) without const
4682                 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4683                         my $attr = $1;
4684                         if (ERROR("INIT_ATTRIBUTE",
4685                                   "Use of $attr requires a separate use of const\n" . $herecurr) &&
4686                             $fix) {
4687                                 my $lead = $fixed[$fixlinenr] =~
4688                                     /(^\+\s*(?:static\s+))/;
4689                                 $lead = rtrim($1);
4690                                 $lead = "$lead " if ($lead !~ /^\+$/);
4691                                 $lead = "${lead}const ";
4692                                 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4693                         }
4694                 }
4695
4696 # don't use __constant_<foo> functions outside of include/uapi/
4697                 if ($realfile !~ m@^include/uapi/@ &&
4698                     $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4699                         my $constant_func = $1;
4700                         my $func = $constant_func;
4701                         $func =~ s/^__constant_//;
4702                         if (WARN("CONSTANT_CONVERSION",
4703                                  "$constant_func should be $func\n" . $herecurr) &&
4704                             $fix) {
4705                                 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4706                         }
4707                 }
4708
4709 # prefer usleep_range over udelay
4710                 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4711                         my $delay = $1;
4712                         # ignore udelay's < 10, however
4713                         if (! ($delay < 10) ) {
4714                                 CHK("USLEEP_RANGE",
4715                                     "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4716                         }
4717                         if ($delay > 2000) {
4718                                 WARN("LONG_UDELAY",
4719                                      "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4720                         }
4721                 }
4722
4723 # warn about unexpectedly long msleep's
4724                 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4725                         if ($1 < 20) {
4726                                 WARN("MSLEEP",
4727                                      "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4728                         }
4729                 }
4730
4731 # check for comparisons of jiffies
4732                 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4733                         WARN("JIFFIES_COMPARISON",
4734                              "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4735                 }
4736
4737 # check for comparisons of get_jiffies_64()
4738                 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4739                         WARN("JIFFIES_COMPARISON",
4740                              "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4741                 }
4742
4743 # warn about #ifdefs in C files
4744 #               if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4745 #                       print "#ifdef in C files should be avoided\n";
4746 #                       print "$herecurr";
4747 #                       $clean = 0;
4748 #               }
4749
4750 # warn about spacing in #ifdefs
4751                 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4752                         if (ERROR("SPACING",
4753                                   "exactly one space required after that #$1\n" . $herecurr) &&
4754                             $fix) {
4755                                 $fixed[$fixlinenr] =~
4756                                     s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4757                         }
4758
4759                 }
4760
4761 # check for spinlock_t definitions without a comment.
4762                 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4763                     $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4764                         my $which = $1;
4765                         if (!ctx_has_comment($first_line, $linenr)) {
4766                                 CHK("UNCOMMENTED_DEFINITION",
4767                                     "$1 definition without comment\n" . $herecurr);
4768                         }
4769                 }
4770 # check for memory barriers without a comment.
4771                 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4772                         if (!ctx_has_comment($first_line, $linenr)) {
4773                                 WARN("MEMORY_BARRIER",
4774                                      "memory barrier without comment\n" . $herecurr);
4775                         }
4776                 }
4777 # check of hardware specific defines
4778                 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4779                         CHK("ARCH_DEFINES",
4780                             "architecture specific defines should be avoided\n" .  $herecurr);
4781                 }
4782
4783 # Check that the storage class is at the beginning of a declaration
4784                 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4785                         WARN("STORAGE_CLASS",
4786                              "storage class should be at the beginning of the declaration\n" . $herecurr)
4787                 }
4788
4789 # check the location of the inline attribute, that it is between
4790 # storage class and type.
4791                 if ($line =~ /\b$Type\s+$Inline\b/ ||
4792                     $line =~ /\b$Inline\s+$Storage\b/) {
4793                         ERROR("INLINE_LOCATION",
4794                               "inline keyword should sit between storage class and type\n" . $herecurr);
4795                 }
4796
4797 # Check for __inline__ and __inline, prefer inline
4798                 if ($realfile !~ m@\binclude/uapi/@ &&
4799                     $line =~ /\b(__inline__|__inline)\b/) {
4800                         if (WARN("INLINE",
4801                                  "plain inline is preferred over $1\n" . $herecurr) &&
4802                             $fix) {
4803                                 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4804
4805                         }
4806                 }
4807
4808 # Check for __attribute__ packed, prefer __packed
4809                 if ($realfile !~ m@\binclude/uapi/@ &&
4810                     $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4811                         WARN("PREFER_PACKED",
4812                              "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4813                 }
4814
4815 # Check for __attribute__ aligned, prefer __aligned
4816                 if ($realfile !~ m@\binclude/uapi/@ &&
4817                     $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4818                         WARN("PREFER_ALIGNED",
4819                              "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4820                 }
4821
4822 # Check for __attribute__ format(printf, prefer __printf
4823                 if ($realfile !~ m@\binclude/uapi/@ &&
4824                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4825                         if (WARN("PREFER_PRINTF",
4826                                  "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4827                             $fix) {
4828                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4829
4830                         }
4831                 }
4832
4833 # Check for __attribute__ format(scanf, prefer __scanf
4834                 if ($realfile !~ m@\binclude/uapi/@ &&
4835                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4836                         if (WARN("PREFER_SCANF",
4837                                  "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4838                             $fix) {
4839                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4840                         }
4841                 }
4842
4843 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4844                 if ($^V && $^V ge 5.10.0 &&
4845                     $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4846                     ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4847                      $line =~ /\b__weak\b/)) {
4848                         ERROR("WEAK_DECLARATION",
4849                               "Using weak declarations can have unintended link defects\n" . $herecurr);
4850                 }
4851
4852 # check for sizeof(&)
4853                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4854                         WARN("SIZEOF_ADDRESS",
4855                              "sizeof(& should be avoided\n" . $herecurr);
4856                 }
4857
4858 # check for sizeof without parenthesis
4859                 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4860                         if (WARN("SIZEOF_PARENTHESIS",
4861                                  "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4862                             $fix) {
4863                                 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4864                         }
4865                 }
4866
4867 # check for struct spinlock declarations
4868                 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4869                         WARN("USE_SPINLOCK_T",
4870                              "struct spinlock should be spinlock_t\n" . $herecurr);
4871                 }
4872
4873 # check for seq_printf uses that could be seq_puts
4874                 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4875                         my $fmt = get_quoted_string($line, $rawline);
4876                         $fmt =~ s/%%//g;
4877                         if ($fmt !~ /%/) {
4878                                 if (WARN("PREFER_SEQ_PUTS",
4879                                          "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4880                                     $fix) {
4881                                         $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4882                                 }
4883                         }
4884                 }
4885
4886 # Check for misused memsets
4887                 if ($^V && $^V ge 5.10.0 &&
4888                     defined $stat &&
4889                     $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4890
4891                         my $ms_addr = $2;
4892                         my $ms_val = $7;
4893                         my $ms_size = $12;
4894
4895                         if ($ms_size =~ /^(0x|)0$/i) {
4896                                 ERROR("MEMSET",
4897                                       "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4898                         } elsif ($ms_size =~ /^(0x|)1$/i) {
4899                                 WARN("MEMSET",
4900                                      "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4901                         }
4902                 }
4903
4904 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4905                 if ($^V && $^V ge 5.10.0 &&
4906                     $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4907                         if (WARN("PREFER_ETHER_ADDR_COPY",
4908                                  "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4909                             $fix) {
4910                                 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4911                         }
4912                 }
4913
4914 # typecasts on min/max could be min_t/max_t
4915                 if ($^V && $^V ge 5.10.0 &&
4916                     defined $stat &&
4917                     $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4918                         if (defined $2 || defined $7) {
4919                                 my $call = $1;
4920                                 my $cast1 = deparenthesize($2);
4921                                 my $arg1 = $3;
4922                                 my $cast2 = deparenthesize($7);
4923                                 my $arg2 = $8;
4924                                 my $cast;
4925
4926                                 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4927                                         $cast = "$cast1 or $cast2";
4928                                 } elsif ($cast1 ne "") {
4929                                         $cast = $cast1;
4930                                 } else {
4931                                         $cast = $cast2;
4932                                 }
4933                                 WARN("MINMAX",
4934                                      "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4935                         }
4936                 }
4937
4938 # check usleep_range arguments
4939                 if ($^V && $^V ge 5.10.0 &&
4940                     defined $stat &&
4941                     $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4942                         my $min = $1;
4943                         my $max = $7;
4944                         if ($min eq $max) {
4945                                 WARN("USLEEP_RANGE",
4946                                      "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4947                         } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4948                                  $min > $max) {
4949                                 WARN("USLEEP_RANGE",
4950                                      "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4951                         }
4952                 }
4953
4954 # check for naked sscanf
4955                 if ($^V && $^V ge 5.10.0 &&
4956                     defined $stat &&
4957                     $line =~ /\bsscanf\b/ &&
4958                     ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4959                      $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4960                      $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4961                         my $lc = $stat =~ tr@\n@@;
4962                         $lc = $lc + $linenr;
4963                         my $stat_real = raw_line($linenr, 0);
4964                         for (my $count = $linenr + 1; $count <= $lc; $count++) {
4965                                 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4966                         }
4967                         WARN("NAKED_SSCANF",
4968                              "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4969                 }
4970
4971 # check for simple sscanf that should be kstrto<foo>
4972                 if ($^V && $^V ge 5.10.0 &&
4973                     defined $stat &&
4974                     $line =~ /\bsscanf\b/) {
4975                         my $lc = $stat =~ tr@\n@@;
4976                         $lc = $lc + $linenr;
4977                         my $stat_real = raw_line($linenr, 0);
4978                         for (my $count = $linenr + 1; $count <= $lc; $count++) {
4979                                 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4980                         }
4981                         if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4982                                 my $format = $6;
4983                                 my $count = $format =~ tr@%@%@;
4984                                 if ($count == 1 &&
4985                                     $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4986                                         WARN("SSCANF_TO_KSTRTO",
4987                                              "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4988                                 }
4989                         }
4990                 }
4991
4992 # check for new externs in .h files.
4993                 if ($realfile =~ /\.h$/ &&
4994                     $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4995                         if (CHK("AVOID_EXTERNS",
4996                                 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4997                             $fix) {
4998                                 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4999                         }
5000                 }
5001
5002 # check for new externs in .c files.
5003                 if ($realfile =~ /\.c$/ && defined $stat &&
5004                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5005                 {
5006                         my $function_name = $1;
5007                         my $paren_space = $2;
5008
5009                         my $s = $stat;
5010                         if (defined $cond) {
5011                                 substr($s, 0, length($cond), '');
5012                         }
5013                         if ($s =~ /^\s*;/ &&
5014                             $function_name ne 'uninitialized_var')
5015                         {
5016                                 WARN("AVOID_EXTERNS",
5017                                      "externs should be avoided in .c files\n" .  $herecurr);
5018                         }
5019
5020                         if ($paren_space =~ /\n/) {
5021                                 WARN("FUNCTION_ARGUMENTS",
5022                                      "arguments for function declarations should follow identifier\n" . $herecurr);
5023                         }
5024
5025                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5026                     $stat =~ /^.\s*extern\s+/)
5027                 {
5028                         WARN("AVOID_EXTERNS",
5029                              "externs should be avoided in .c files\n" .  $herecurr);
5030                 }
5031
5032 # checks for new __setup's
5033                 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5034                         my $name = $1;
5035
5036                         if (!grep(/$name/, @setup_docs)) {
5037                                 CHK("UNDOCUMENTED_SETUP",
5038                                     "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5039                         }
5040                 }
5041
5042 # check for pointless casting of kmalloc return
5043                 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5044                         WARN("UNNECESSARY_CASTS",
5045                              "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5046                 }
5047
5048 # alloc style
5049 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5050                 if ($^V && $^V ge 5.10.0 &&
5051                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5052                         CHK("ALLOC_SIZEOF_STRUCT",
5053                             "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5054                 }
5055
5056 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5057                 if ($^V && $^V ge 5.10.0 &&
5058                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5059                         my $oldfunc = $3;
5060                         my $a1 = $4;
5061                         my $a2 = $10;
5062                         my $newfunc = "kmalloc_array";
5063                         $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5064                         my $r1 = $a1;
5065                         my $r2 = $a2;
5066                         if ($a1 =~ /^sizeof\s*\S/) {
5067                                 $r1 = $a2;
5068                                 $r2 = $a1;
5069                         }
5070                         if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5071                             !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5072                                 if (WARN("ALLOC_WITH_MULTIPLY",
5073                                          "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5074                                     $fix) {
5075                                         $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
5076
5077                                 }
5078                         }
5079                 }
5080
5081 # check for krealloc arg reuse
5082                 if ($^V && $^V ge 5.10.0 &&
5083                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5084                         WARN("KREALLOC_ARG_REUSE",
5085                              "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5086                 }
5087
5088 # check for alloc argument mismatch
5089                 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5090                         WARN("ALLOC_ARRAY_ARGS",
5091                              "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5092                 }
5093
5094 # check for multiple semicolons
5095                 if ($line =~ /;\s*;\s*$/) {
5096                         if (WARN("ONE_SEMICOLON",
5097                                  "Statements terminations use 1 semicolon\n" . $herecurr) &&
5098                             $fix) {
5099                                 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5100                         }
5101                 }
5102
5103 # check for #defines like: 1 << <digit> that could be BIT(digit)
5104                 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5105                         my $ull = "";
5106                         $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5107                         if (CHK("BIT_MACRO",
5108                                 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5109                             $fix) {
5110                                 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5111                         }
5112                 }
5113
5114 # check for case / default statements not preceded by break/fallthrough/switch
5115                 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5116                         my $has_break = 0;
5117                         my $has_statement = 0;
5118                         my $count = 0;
5119                         my $prevline = $linenr;
5120                         while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5121                                 $prevline--;
5122                                 my $rline = $rawlines[$prevline - 1];
5123                                 my $fline = $lines[$prevline - 1];
5124                                 last if ($fline =~ /^\@\@/);
5125                                 next if ($fline =~ /^\-/);
5126                                 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5127                                 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5128                                 next if ($fline =~ /^.[\s$;]*$/);
5129                                 $has_statement = 1;
5130                                 $count++;
5131                                 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5132                         }
5133                         if (!$has_break && $has_statement) {
5134                                 WARN("MISSING_BREAK",
5135                                      "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5136                         }
5137                 }
5138
5139 # check for switch/default statements without a break;
5140                 if ($^V && $^V ge 5.10.0 &&
5141                     defined $stat &&
5142                     $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5143                         my $ctx = '';
5144                         my $herectx = $here . "\n";
5145                         my $cnt = statement_rawlines($stat);
5146                         for (my $n = 0; $n < $cnt; $n++) {
5147                                 $herectx .= raw_line($linenr, $n) . "\n";
5148                         }
5149                         WARN("DEFAULT_NO_BREAK",
5150                              "switch default: should use break\n" . $herectx);
5151                 }
5152
5153 # check for gcc specific __FUNCTION__
5154                 if ($line =~ /\b__FUNCTION__\b/) {
5155                         if (WARN("USE_FUNC",
5156                                  "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
5157                             $fix) {
5158                                 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5159                         }
5160                 }
5161
5162 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5163                 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5164                         ERROR("DATE_TIME",
5165                               "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5166                 }
5167
5168 # check for use of yield()
5169                 if ($line =~ /\byield\s*\(\s*\)/) {
5170                         WARN("YIELD",
5171                              "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
5172                 }
5173
5174 # check for comparisons against true and false
5175                 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5176                         my $lead = $1;
5177                         my $arg = $2;
5178                         my $test = $3;
5179                         my $otype = $4;
5180                         my $trail = $5;
5181                         my $op = "!";
5182
5183                         ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5184
5185                         my $type = lc($otype);
5186                         if ($type =~ /^(?:true|false)$/) {
5187                                 if (("$test" eq "==" && "$type" eq "true") ||
5188                                     ("$test" eq "!=" && "$type" eq "false")) {
5189                                         $op = "";
5190                                 }
5191
5192                                 CHK("BOOL_COMPARISON",
5193                                     "Using comparison to $otype is error prone\n" . $herecurr);
5194
5195 ## maybe suggesting a correct construct would better
5196 ##                                  "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5197
5198                         }
5199                 }
5200
5201 # check for semaphores initialized locked
5202                 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5203                         WARN("CONSIDER_COMPLETION",
5204                              "consider using a completion\n" . $herecurr);
5205                 }
5206
5207 # recommend kstrto* over simple_strto* and strict_strto*
5208                 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5209                         WARN("CONSIDER_KSTRTO",
5210                              "$1 is obsolete, use k$3 instead\n" . $herecurr);
5211                 }
5212
5213 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5214                 if ($line =~ /^.\s*__initcall\s*\(/) {
5215                         WARN("USE_DEVICE_INITCALL",
5216                              "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5217                 }
5218
5219 # check for various ops structs, ensure they are const.
5220                 my $struct_ops = qr{acpi_dock_ops|
5221                                 address_space_operations|
5222                                 backlight_ops|
5223                                 block_device_operations|
5224                                 dentry_operations|
5225                                 dev_pm_ops|
5226                                 dma_map_ops|
5227                                 extent_io_ops|
5228                                 file_lock_operations|
5229                                 file_operations|
5230                                 hv_ops|
5231                                 ide_dma_ops|
5232                                 intel_dvo_dev_ops|
5233                                 item_operations|
5234                                 iwl_ops|
5235                                 kgdb_arch|
5236                                 kgdb_io|
5237                                 kset_uevent_ops|
5238                                 lock_manager_operations|
5239                                 microcode_ops|
5240                                 mtrr_ops|
5241                                 neigh_ops|
5242                                 nlmsvc_binding|
5243                                 pci_raw_ops|
5244                                 pipe_buf_operations|
5245                                 platform_hibernation_ops|
5246                                 platform_suspend_ops|
5247                                 proto_ops|
5248                                 rpc_pipe_ops|
5249                                 seq_operations|
5250                                 snd_ac97_build_ops|
5251                                 soc_pcmcia_socket_ops|
5252                                 stacktrace_ops|
5253                                 sysfs_ops|
5254                                 tty_operations|
5255                                 usb_mon_operations|
5256                                 wd_ops}x;
5257                 if ($line !~ /\bconst\b/ &&
5258                     $line =~ /\bstruct\s+($struct_ops)\b/) {
5259                         WARN("CONST_STRUCT",
5260                              "struct $1 should normally be const\n" .
5261                                 $herecurr);
5262                 }
5263
5264 # use of NR_CPUS is usually wrong
5265 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5266                 if ($line =~ /\bNR_CPUS\b/ &&
5267                     $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5268                     $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5269                     $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5270                     $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5271                     $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5272                 {
5273                         WARN("NR_CPUS",
5274                              "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5275                 }
5276
5277 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5278                 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5279                         ERROR("DEFINE_ARCH_HAS",
5280                               "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5281                 }
5282
5283 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5284                 if ($^V && $^V ge 5.10.0 &&
5285                     $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5286                         WARN("LIKELY_MISUSE",
5287                              "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5288                 }
5289
5290 # whine mightly about in_atomic
5291                 if ($line =~ /\bin_atomic\s*\(/) {
5292                         if ($realfile =~ m@^drivers/@) {
5293                                 ERROR("IN_ATOMIC",
5294                                       "do not use in_atomic in drivers\n" . $herecurr);
5295                         } elsif ($realfile !~ m@^kernel/@) {
5296                                 WARN("IN_ATOMIC",
5297                                      "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5298                         }
5299                 }
5300
5301 # check for lockdep_set_novalidate_class
5302                 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5303                     $line =~ /__lockdep_no_validate__\s*\)/ ) {
5304                         if ($realfile !~ m@^kernel/lockdep@ &&
5305                             $realfile !~ m@^include/linux/lockdep@ &&
5306                             $realfile !~ m@^drivers/base/core@) {
5307                                 ERROR("LOCKDEP",
5308                                       "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5309                         }
5310                 }
5311
5312                 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5313                     $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5314                         WARN("EXPORTED_WORLD_WRITABLE",
5315                              "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5316                 }
5317
5318 # Mode permission misuses where it seems decimal should be octal
5319 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5320                 if ($^V && $^V ge 5.10.0 &&
5321                     $line =~ /$mode_perms_search/) {
5322                         foreach my $entry (@mode_permission_funcs) {
5323                                 my $func = $entry->[0];
5324                                 my $arg_pos = $entry->[1];
5325
5326                                 my $skip_args = "";
5327                                 if ($arg_pos > 1) {
5328                                         $arg_pos--;
5329                                         $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5330                                 }
5331                                 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5332                                 if ($line =~ /$test/) {
5333                                         my $val = $1;
5334                                         $val = $6 if ($skip_args ne "");
5335
5336                                         if ($val !~ /^0$/ &&
5337                                             (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5338                                              length($val) ne 4)) {
5339                                                 ERROR("NON_OCTAL_PERMISSIONS",
5340                                                       "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5341                                         } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5342                                                 ERROR("EXPORTED_WORLD_WRITABLE",
5343                                                       "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5344                                         }
5345                                 }
5346                         }
5347                 }
5348         }
5349
5350         # If we have no input at all, then there is nothing to report on
5351         # so just keep quiet.
5352         if ($#rawlines == -1) {
5353                 exit(0);
5354         }
5355
5356         # In mailback mode only produce a report in the negative, for
5357         # things that appear to be patches.
5358         if ($mailback && ($clean == 1 || !$is_patch)) {
5359                 exit(0);
5360         }
5361
5362         # This is not a patch, and we are are in 'no-patch' mode so
5363         # just keep quiet.
5364         if (!$chk_patch && !$is_patch) {
5365                 exit(0);
5366         }
5367
5368         if (!$is_patch) {
5369                 ERROR("NOT_UNIFIED_DIFF",
5370                       "Does not appear to be a unified-diff format patch\n");
5371         }
5372         if ($is_patch && $chk_signoff && $signoff == 0) {
5373                 ERROR("MISSING_SIGN_OFF",
5374                       "Missing Signed-off-by: line(s)\n");
5375         }
5376
5377         print report_dump();
5378         if ($summary && !($clean == 1 && $quiet == 1)) {
5379                 print "$filename " if ($summary_file);
5380                 print "total: $cnt_error errors, $cnt_warn warnings, " .
5381                         (($check)? "$cnt_chk checks, " : "") .
5382                         "$cnt_lines lines checked\n";
5383                 print "\n" if ($quiet == 0);
5384         }
5385
5386         if ($quiet == 0) {
5387
5388                 if ($^V lt 5.10.0) {
5389                         print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5390                         print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5391                 }
5392
5393                 # If there were whitespace errors which cleanpatch can fix
5394                 # then suggest that.
5395                 if ($rpt_cleaners) {
5396                         print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5397                         print "      scripts/cleanfile\n\n";
5398                         $rpt_cleaners = 0;
5399                 }
5400         }
5401
5402         hash_show_words(\%use_type, "Used");
5403         hash_show_words(\%ignore_type, "Ignored");
5404
5405         if ($clean == 0 && $fix &&
5406             ("@rawlines" ne "@fixed" ||
5407              $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5408                 my $newfile = $filename;
5409                 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5410                 my $linecount = 0;
5411                 my $f;
5412
5413                 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5414
5415                 open($f, '>', $newfile)
5416                     or die "$P: Can't open $newfile for write\n";
5417                 foreach my $fixed_line (@fixed) {
5418                         $linecount++;
5419                         if ($file) {
5420                                 if ($linecount > 3) {
5421                                         $fixed_line =~ s/^\+//;
5422                                         print $f $fixed_line . "\n";
5423                                 }
5424                         } else {
5425                                 print $f $fixed_line . "\n";
5426                         }
5427                 }
5428                 close($f);
5429
5430                 if (!$quiet) {
5431                         print << "EOM";
5432 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5433
5434 Do _NOT_ trust the results written to this file.
5435 Do _NOT_ submit these changes without inspecting them for correctness.
5436
5437 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5438 No warranties, expressed or implied...
5439
5440 EOM
5441                 }
5442         }
5443
5444         if ($clean == 1 && $quiet == 0) {
5445                 print "$vname has no obvious style problems and is ready for submission.\n"
5446         }
5447         if ($clean == 0 && $quiet == 0) {
5448                 print << "EOM";
5449 $vname has style problems, please review.
5450
5451 If any of these errors are false positives, please report
5452 them to the maintainer, see CHECKPATCH in MAINTAINERS.
5453 EOM
5454         }
5455
5456         return $clean;
5457 }