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