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