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