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