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