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