vc: introduce struct vc_draw_region
[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|---help---)\s*$/) {
3046                                         if ($lines[$ln - 1] =~ "---help---") {
3047                                                 WARN("CONFIG_DESCRIPTION",
3048                                                      "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
3049                                         }
3050                                         $length = -1;
3051                                 }
3052
3053                                 $f =~ s/^.//;
3054                                 $f =~ s/#.*//;
3055                                 $f =~ s/^\s+//;
3056                                 next if ($f =~ /^$/);
3057
3058                                 # This only checks context lines in the patch
3059                                 # and so hopefully shouldn't trigger false
3060                                 # positives, even though some of these are
3061                                 # common words in help texts
3062                                 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3063                                                   if|endif|menu|endmenu|source)\b/x) {
3064                                         $is_end = 1;
3065                                         last;
3066                                 }
3067                                 $length++;
3068                         }
3069                         if ($is_start && $is_end && $length < $min_conf_desc_length) {
3070                                 WARN("CONFIG_DESCRIPTION",
3071                                      "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3072                         }
3073                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3074                 }
3075
3076 # check MAINTAINERS entries
3077                 if ($realfile =~ /^MAINTAINERS$/) {
3078 # check MAINTAINERS entries for the right form
3079                         if ($rawline =~ /^\+[A-Z]:/ &&
3080                             $rawline !~ /^\+[A-Z]:\t\S/) {
3081                                 if (WARN("MAINTAINERS_STYLE",
3082                                          "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3083                                     $fix) {
3084                                         $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3085                                 }
3086                         }
3087 # check MAINTAINERS entries for the right ordering too
3088                         my $preferred_order = 'MRLSWQBCPTFXNK';
3089                         if ($rawline =~ /^\+[A-Z]:/ &&
3090                             $prevrawline =~ /^[\+ ][A-Z]:/) {
3091                                 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3092                                 my $cur = $1;
3093                                 my $curval = $2;
3094                                 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3095                                 my $prev = $1;
3096                                 my $prevval = $2;
3097                                 my $curindex = index($preferred_order, $cur);
3098                                 my $previndex = index($preferred_order, $prev);
3099                                 if ($curindex < 0) {
3100                                         WARN("MAINTAINERS_STYLE",
3101                                              "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3102                                 } else {
3103                                         if ($previndex >= 0 && $curindex < $previndex) {
3104                                                 WARN("MAINTAINERS_STYLE",
3105                                                      "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3106                                         } elsif ((($prev eq 'F' && $cur eq 'F') ||
3107                                                   ($prev eq 'X' && $cur eq 'X')) &&
3108                                                  ($prevval cmp $curval) > 0) {
3109                                                 WARN("MAINTAINERS_STYLE",
3110                                                      "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3111                                         }
3112                                 }
3113                         }
3114                 }
3115
3116 # discourage the use of boolean for type definition attributes of Kconfig options
3117                 if ($realfile =~ /Kconfig/ &&
3118                     $line =~ /^\+\s*\bboolean\b/) {
3119                         WARN("CONFIG_TYPE_BOOLEAN",
3120                              "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3121                 }
3122
3123                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3124                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3125                         my $flag = $1;
3126                         my $replacement = {
3127                                 'EXTRA_AFLAGS' =>   'asflags-y',
3128                                 'EXTRA_CFLAGS' =>   'ccflags-y',
3129                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
3130                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
3131                         };
3132
3133                         WARN("DEPRECATED_VARIABLE",
3134                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3135                 }
3136
3137 # check for DT compatible documentation
3138                 if (defined $root &&
3139                         (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3140                          ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3141
3142                         my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3143
3144                         my $dt_path = $root . "/Documentation/devicetree/bindings/";
3145                         my $vp_file = $dt_path . "vendor-prefixes.yaml";
3146
3147                         foreach my $compat (@compats) {
3148                                 my $compat2 = $compat;
3149                                 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3150                                 my $compat3 = $compat;
3151                                 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3152                                 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3153                                 if ( $? >> 8 ) {
3154                                         WARN("UNDOCUMENTED_DT_STRING",
3155                                              "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3156                                 }
3157
3158                                 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3159                                 my $vendor = $1;
3160                                 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3161                                 if ( $? >> 8 ) {
3162                                         WARN("UNDOCUMENTED_DT_STRING",
3163                                              "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3164                                 }
3165                         }
3166                 }
3167
3168 # check for using SPDX license tag at beginning of files
3169                 if ($realline == $checklicenseline) {
3170                         if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3171                                 $checklicenseline = 2;
3172                         } elsif ($rawline =~ /^\+/) {
3173                                 my $comment = "";
3174                                 if ($realfile =~ /\.(h|s|S)$/) {
3175                                         $comment = '/*';
3176                                 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3177                                         $comment = '//';
3178                                 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3179                                         $comment = '#';
3180                                 } elsif ($realfile =~ /\.rst$/) {
3181                                         $comment = '..';
3182                                 }
3183
3184 # check SPDX comment style for .[chsS] files
3185                                 if ($realfile =~ /\.[chsS]$/ &&
3186                                     $rawline =~ /SPDX-License-Identifier:/ &&
3187                                     $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3188                                         WARN("SPDX_LICENSE_TAG",
3189                                              "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3190                                 }
3191
3192                                 if ($comment !~ /^$/ &&
3193                                     $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3194                                         WARN("SPDX_LICENSE_TAG",
3195                                              "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3196                                 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3197                                         my $spdx_license = $1;
3198                                         if (!is_SPDX_License_valid($spdx_license)) {
3199                                                 WARN("SPDX_LICENSE_TAG",
3200                                                      "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3201                                         }
3202                                         if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3203                                             not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3204                                                 my $msg_level = \&WARN;
3205                                                 $msg_level = \&CHK if ($file);
3206                                                 if (&{$msg_level}("SPDX_LICENSE_TAG",
3207
3208                                                                   "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3209                                                     $fix) {
3210                                                         $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3211                                                 }
3212                                         }
3213                                 }
3214                         }
3215                 }
3216
3217 # check we are in a valid source file if not then ignore this hunk
3218                 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3219
3220 # check for using SPDX-License-Identifier on the wrong line number
3221                 if ($realline != $checklicenseline &&
3222                     $rawline =~ /\bSPDX-License-Identifier:/ &&
3223                     substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3224                         WARN("SPDX_LICENSE_TAG",
3225                              "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3226                 }
3227
3228 # line length limit (with some exclusions)
3229 #
3230 # There are a few types of lines that may extend beyond $max_line_length:
3231 #       logging functions like pr_info that end in a string
3232 #       lines with a single string
3233 #       #defines that are a single string
3234 #       lines with an RFC3986 like URL
3235 #
3236 # There are 3 different line length message types:
3237 # LONG_LINE_COMMENT     a comment starts before but extends beyond $max_line_length
3238 # LONG_LINE_STRING      a string starts before but extends beyond $max_line_length
3239 # LONG_LINE             all other lines longer than $max_line_length
3240 #
3241 # if LONG_LINE is ignored, the other 2 types are also ignored
3242 #
3243
3244                 if ($line =~ /^\+/ && $length > $max_line_length) {
3245                         my $msg_type = "LONG_LINE";
3246
3247                         # Check the allowed long line types first
3248
3249                         # logging functions that end in a string that starts
3250                         # before $max_line_length
3251                         if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3252                             length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3253                                 $msg_type = "";
3254
3255                         # lines with only strings (w/ possible termination)
3256                         # #defines with only strings
3257                         } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3258                                  $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3259                                 $msg_type = "";
3260
3261                         # More special cases
3262                         } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3263                                  $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3264                                 $msg_type = "";
3265
3266                         # URL ($rawline is used in case the URL is in a comment)
3267                         } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3268                                 $msg_type = "";
3269
3270                         # Otherwise set the alternate message types
3271
3272                         # a comment starts before $max_line_length
3273                         } elsif ($line =~ /($;[\s$;]*)$/ &&
3274                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3275                                 $msg_type = "LONG_LINE_COMMENT"
3276
3277                         # a quoted string starts before $max_line_length
3278                         } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3279                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3280                                 $msg_type = "LONG_LINE_STRING"
3281                         }
3282
3283                         if ($msg_type ne "" &&
3284                             (show_type("LONG_LINE") || show_type($msg_type))) {
3285                                 my $msg_level = \&WARN;
3286                                 $msg_level = \&CHK if ($file);
3287                                 &{$msg_level}($msg_type,
3288                                               "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3289                         }
3290                 }
3291
3292 # check for adding lines without a newline.
3293                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3294                         WARN("MISSING_EOF_NEWLINE",
3295                              "adding a line without newline at end of file\n" . $herecurr);
3296                 }
3297
3298 # check we are in a valid source file C or perl if not then ignore this hunk
3299                 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3300
3301 # at the beginning of a line any tabs must come first and anything
3302 # more than $tabsize must use tabs.
3303                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3304                     $rawline =~ /^\+\s*        \s*/) {
3305                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3306                         $rpt_cleaners = 1;
3307                         if (ERROR("CODE_INDENT",
3308                                   "code indent should use tabs where possible\n" . $herevet) &&
3309                             $fix) {
3310                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3311                         }
3312                 }
3313
3314 # check for space before tabs.
3315                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3316                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3317                         if (WARN("SPACE_BEFORE_TAB",
3318                                 "please, no space before tabs\n" . $herevet) &&
3319                             $fix) {
3320                                 while ($fixed[$fixlinenr] =~
3321                                            s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3322                                 while ($fixed[$fixlinenr] =~
3323                                            s/(^\+.*) +\t/$1\t/) {}
3324                         }
3325                 }
3326
3327 # check for assignments on the start of a line
3328                 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3329                         CHK("ASSIGNMENT_CONTINUATIONS",
3330                             "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3331                 }
3332
3333 # check for && or || at the start of a line
3334                 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3335                         CHK("LOGICAL_CONTINUATIONS",
3336                             "Logical continuations should be on the previous line\n" . $hereprev);
3337                 }
3338
3339 # check indentation starts on a tab stop
3340                 if ($perl_version_ok &&
3341                     $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3342                         my $indent = length($1);
3343                         if ($indent % $tabsize) {
3344                                 if (WARN("TABSTOP",
3345                                          "Statements should start on a tabstop\n" . $herecurr) &&
3346                                     $fix) {
3347                                         $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3348                                 }
3349                         }
3350                 }
3351
3352 # check multi-line statement indentation matches previous line
3353                 if ($perl_version_ok &&
3354                     $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3355                         $prevline =~ /^\+(\t*)(.*)$/;
3356                         my $oldindent = $1;
3357                         my $rest = $2;
3358
3359                         my $pos = pos_last_openparen($rest);
3360                         if ($pos >= 0) {
3361                                 $line =~ /^(\+| )([ \t]*)/;
3362                                 my $newindent = $2;
3363
3364                                 my $goodtabindent = $oldindent .
3365                                         "\t" x ($pos / $tabsize) .
3366                                         " "  x ($pos % $tabsize);
3367                                 my $goodspaceindent = $oldindent . " "  x $pos;
3368
3369                                 if ($newindent ne $goodtabindent &&
3370                                     $newindent ne $goodspaceindent) {
3371
3372                                         if (CHK("PARENTHESIS_ALIGNMENT",
3373                                                 "Alignment should match open parenthesis\n" . $hereprev) &&
3374                                             $fix && $line =~ /^\+/) {
3375                                                 $fixed[$fixlinenr] =~
3376                                                     s/^\+[ \t]*/\+$goodtabindent/;
3377                                         }
3378                                 }
3379                         }
3380                 }
3381
3382 # check for space after cast like "(int) foo" or "(struct foo) bar"
3383 # avoid checking a few false positives:
3384 #   "sizeof(<type>)" or "__alignof__(<type>)"
3385 #   function pointer declarations like "(*foo)(int) = bar;"
3386 #   structure definitions like "(struct foo) { 0 };"
3387 #   multiline macros that define functions
3388 #   known attributes or the __attribute__ keyword
3389                 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3390                     (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3391                         if (CHK("SPACING",
3392                                 "No space is necessary after a cast\n" . $herecurr) &&
3393                             $fix) {
3394                                 $fixed[$fixlinenr] =~
3395                                     s/(\(\s*$Type\s*\))[ \t]+/$1/;
3396                         }
3397                 }
3398
3399 # Block comment styles
3400 # Networking with an initial /*
3401                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3402                     $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3403                     $rawline =~ /^\+[ \t]*\*/ &&
3404                     $realline > 2) {
3405                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3406                              "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3407                 }
3408
3409 # Block comments use * on subsequent lines
3410                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3411                     $prevrawline =~ /^\+.*?\/\*/ &&             #starting /*
3412                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
3413                     $rawline =~ /^\+/ &&                        #line is new
3414                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
3415                         WARN("BLOCK_COMMENT_STYLE",
3416                              "Block comments use * on subsequent lines\n" . $hereprev);
3417                 }
3418
3419 # Block comments use */ on trailing lines
3420                 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
3421                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
3422                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
3423                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
3424                         WARN("BLOCK_COMMENT_STYLE",
3425                              "Block comments use a trailing */ on a separate line\n" . $herecurr);
3426                 }
3427
3428 # Block comment * alignment
3429                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3430                     $line =~ /^\+[ \t]*$;/ &&                   #leading comment
3431                     $rawline =~ /^\+[ \t]*\*/ &&                #leading *
3432                     (($prevrawline =~ /^\+.*?\/\*/ &&           #leading /*
3433                       $prevrawline !~ /\*\/[ \t]*$/) ||         #no trailing */
3434                      $prevrawline =~ /^\+[ \t]*\*/)) {          #leading *
3435                         my $oldindent;
3436                         $prevrawline =~ m@^\+([ \t]*/?)\*@;
3437                         if (defined($1)) {
3438                                 $oldindent = expand_tabs($1);
3439                         } else {
3440                                 $prevrawline =~ m@^\+(.*/?)\*@;
3441                                 $oldindent = expand_tabs($1);
3442                         }
3443                         $rawline =~ m@^\+([ \t]*)\*@;
3444                         my $newindent = $1;
3445                         $newindent = expand_tabs($newindent);
3446                         if (length($oldindent) ne length($newindent)) {
3447                                 WARN("BLOCK_COMMENT_STYLE",
3448                                      "Block comments should align the * on each line\n" . $hereprev);
3449                         }
3450                 }
3451
3452 # check for missing blank lines after struct/union declarations
3453 # with exceptions for various attributes and macros
3454                 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3455                     $line =~ /^\+/ &&
3456                     !($line =~ /^\+\s*$/ ||
3457                       $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3458                       $line =~ /^\+\s*MODULE_/i ||
3459                       $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3460                       $line =~ /^\+[a-z_]*init/ ||
3461                       $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3462                       $line =~ /^\+\s*DECLARE/ ||
3463                       $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3464                       $line =~ /^\+\s*__setup/)) {
3465                         if (CHK("LINE_SPACING",
3466                                 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3467                             $fix) {
3468                                 fix_insert_line($fixlinenr, "\+");
3469                         }
3470                 }
3471
3472 # check for multiple consecutive blank lines
3473                 if ($prevline =~ /^[\+ ]\s*$/ &&
3474                     $line =~ /^\+\s*$/ &&
3475                     $last_blank_line != ($linenr - 1)) {
3476                         if (CHK("LINE_SPACING",
3477                                 "Please don't use multiple blank lines\n" . $hereprev) &&
3478                             $fix) {
3479                                 fix_delete_line($fixlinenr, $rawline);
3480                         }
3481
3482                         $last_blank_line = $linenr;
3483                 }
3484
3485 # check for missing blank lines after declarations
3486                 if ($sline =~ /^\+\s+\S/ &&                     #Not at char 1
3487                         # actual declarations
3488                     ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3489                         # function pointer declarations
3490                      $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3491                         # foo bar; where foo is some local typedef or #define
3492                      $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3493                         # known declaration macros
3494                      $prevline =~ /^\+\s+$declaration_macros/) &&
3495                         # for "else if" which can look like "$Ident $Ident"
3496                     !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3497                         # other possible extensions of declaration lines
3498                       $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3499                         # not starting a section or a macro "\" extended line
3500                       $prevline =~ /(?:\{\s*|\\)$/) &&
3501                         # looks like a declaration
3502                     !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3503                         # function pointer declarations
3504                       $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3505                         # foo bar; where foo is some local typedef or #define
3506                       $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3507                         # known declaration macros
3508                       $sline =~ /^\+\s+$declaration_macros/ ||
3509                         # start of struct or union or enum
3510                       $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3511                         # start or end of block or continuation of declaration
3512                       $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3513                         # bitfield continuation
3514                       $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3515                         # other possible extensions of declaration lines
3516                       $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3517                         # indentation of previous and current line are the same
3518                     (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3519                         if (WARN("LINE_SPACING",
3520                                  "Missing a blank line after declarations\n" . $hereprev) &&
3521                             $fix) {
3522                                 fix_insert_line($fixlinenr, "\+");
3523                         }
3524                 }
3525
3526 # check for spaces at the beginning of a line.
3527 # Exceptions:
3528 #  1) within comments
3529 #  2) indented preprocessor commands
3530 #  3) hanging labels
3531                 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
3532                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3533                         if (WARN("LEADING_SPACE",
3534                                  "please, no spaces at the start of a line\n" . $herevet) &&
3535                             $fix) {
3536                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3537                         }
3538                 }
3539
3540 # check we are in a valid C source file if not then ignore this hunk
3541                 next if ($realfile !~ /\.(h|c)$/);
3542
3543 # check for unusual line ending [ or (
3544                 if ($line =~ /^\+.*([\[\(])\s*$/) {
3545                         CHK("OPEN_ENDED_LINE",
3546                             "Lines should not end with a '$1'\n" . $herecurr);
3547                 }
3548
3549 # check if this appears to be the start function declaration, save the name
3550                 if ($sline =~ /^\+\{\s*$/ &&
3551                     $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3552                         $context_function = $1;
3553                 }
3554
3555 # check if this appears to be the end of function declaration
3556                 if ($sline =~ /^\+\}\s*$/) {
3557                         undef $context_function;
3558                 }
3559
3560 # check indentation of any line with a bare else
3561 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3562 # if the previous line is a break or return and is indented 1 tab more...
3563                 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3564                         my $tabs = length($1) + 1;
3565                         if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3566                             ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3567                              defined $lines[$linenr] &&
3568                              $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3569                                 WARN("UNNECESSARY_ELSE",
3570                                      "else is not generally useful after a break or return\n" . $hereprev);
3571                         }
3572                 }
3573
3574 # check indentation of a line with a break;
3575 # if the previous line is a goto or return and is indented the same # of tabs
3576                 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3577                         my $tabs = $1;
3578                         if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3579                                 WARN("UNNECESSARY_BREAK",
3580                                      "break is not useful after a goto or return\n" . $hereprev);
3581                         }
3582                 }
3583
3584 # check for RCS/CVS revision markers
3585                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3586                         WARN("CVS_KEYWORD",
3587                              "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3588                 }
3589
3590 # check for old HOTPLUG __dev<foo> section markings
3591                 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3592                         WARN("HOTPLUG_SECTION",
3593                              "Using $1 is unnecessary\n" . $herecurr);
3594                 }
3595
3596 # Check for potential 'bare' types
3597                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3598                     $realline_next);
3599 #print "LINE<$line>\n";
3600                 if ($linenr > $suppress_statement &&
3601                     $realcnt && $sline =~ /.\s*\S/) {
3602                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3603                                 ctx_statement_block($linenr, $realcnt, 0);
3604                         $stat =~ s/\n./\n /g;
3605                         $cond =~ s/\n./\n /g;
3606
3607 #print "linenr<$linenr> <$stat>\n";
3608                         # If this statement has no statement boundaries within
3609                         # it there is no point in retrying a statement scan
3610                         # until we hit end of it.
3611                         my $frag = $stat; $frag =~ s/;+\s*$//;
3612                         if ($frag !~ /(?:{|;)/) {
3613 #print "skip<$line_nr_next>\n";
3614                                 $suppress_statement = $line_nr_next;
3615                         }
3616
3617                         # Find the real next line.
3618                         $realline_next = $line_nr_next;
3619                         if (defined $realline_next &&
3620                             (!defined $lines[$realline_next - 1] ||
3621                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3622                                 $realline_next++;
3623                         }
3624
3625                         my $s = $stat;
3626                         $s =~ s/{.*$//s;
3627
3628                         # Ignore goto labels.
3629                         if ($s =~ /$Ident:\*$/s) {
3630
3631                         # Ignore functions being called
3632                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3633
3634                         } elsif ($s =~ /^.\s*else\b/s) {
3635
3636                         # declarations always start with types
3637                         } 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) {
3638                                 my $type = $1;
3639                                 $type =~ s/\s+/ /g;
3640                                 possible($type, "A:" . $s);
3641
3642                         # definitions in global scope can only start with types
3643                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3644                                 possible($1, "B:" . $s);
3645                         }
3646
3647                         # any (foo ... *) is a pointer cast, and foo is a type
3648                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3649                                 possible($1, "C:" . $s);
3650                         }
3651
3652                         # Check for any sort of function declaration.
3653                         # int foo(something bar, other baz);
3654                         # void (*store_gdt)(x86_descr_ptr *);
3655                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3656                                 my ($name_len) = length($1);
3657
3658                                 my $ctx = $s;
3659                                 substr($ctx, 0, $name_len + 1, '');
3660                                 $ctx =~ s/\)[^\)]*$//;
3661
3662                                 for my $arg (split(/\s*,\s*/, $ctx)) {
3663                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3664
3665                                                 possible($1, "D:" . $s);
3666                                         }
3667                                 }
3668                         }
3669
3670                 }
3671
3672 #
3673 # Checks which may be anchored in the context.
3674 #
3675
3676 # Check for switch () and associated case and default
3677 # statements should be at the same indent.
3678                 if ($line=~/\bswitch\s*\(.*\)/) {
3679                         my $err = '';
3680                         my $sep = '';
3681                         my @ctx = ctx_block_outer($linenr, $realcnt);
3682                         shift(@ctx);
3683                         for my $ctx (@ctx) {
3684                                 my ($clen, $cindent) = line_stats($ctx);
3685                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3686                                                         $indent != $cindent) {
3687                                         $err .= "$sep$ctx\n";
3688                                         $sep = '';
3689                                 } else {
3690                                         $sep = "[...]\n";
3691                                 }
3692                         }
3693                         if ($err ne '') {
3694                                 ERROR("SWITCH_CASE_INDENT_LEVEL",
3695                                       "switch and case should be at the same indent\n$hereline$err");
3696                         }
3697                 }
3698
3699 # if/while/etc brace do not go on next line, unless defining a do while loop,
3700 # or if that brace on the next line is for something else
3701                 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3702                         my $pre_ctx = "$1$2";
3703
3704                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3705
3706                         if ($line =~ /^\+\t{6,}/) {
3707                                 WARN("DEEP_INDENTATION",
3708                                      "Too many leading tabs - consider code refactoring\n" . $herecurr);
3709                         }
3710
3711                         my $ctx_cnt = $realcnt - $#ctx - 1;
3712                         my $ctx = join("\n", @ctx);
3713
3714                         my $ctx_ln = $linenr;
3715                         my $ctx_skip = $realcnt;
3716
3717                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3718                                         defined $lines[$ctx_ln - 1] &&
3719                                         $lines[$ctx_ln - 1] =~ /^-/)) {
3720                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3721                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3722                                 $ctx_ln++;
3723                         }
3724
3725                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3726                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3727
3728                         if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3729                                 ERROR("OPEN_BRACE",
3730                                       "that open brace { should be on the previous line\n" .
3731                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3732                         }
3733                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3734                             $ctx =~ /\)\s*\;\s*$/ &&
3735                             defined $lines[$ctx_ln - 1])
3736                         {
3737                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3738                                 if ($nindent > $indent) {
3739                                         WARN("TRAILING_SEMICOLON",
3740                                              "trailing semicolon indicates no statements, indent implies otherwise\n" .
3741                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3742                                 }
3743                         }
3744                 }
3745
3746 # Check relative indent for conditionals and blocks.
3747                 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3748                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3749                                 ctx_statement_block($linenr, $realcnt, 0)
3750                                         if (!defined $stat);
3751                         my ($s, $c) = ($stat, $cond);
3752
3753                         substr($s, 0, length($c), '');
3754
3755                         # remove inline comments
3756                         $s =~ s/$;/ /g;
3757                         $c =~ s/$;/ /g;
3758
3759                         # Find out how long the conditional actually is.
3760                         my @newlines = ($c =~ /\n/gs);
3761                         my $cond_lines = 1 + $#newlines;
3762
3763                         # Make sure we remove the line prefixes as we have
3764                         # none on the first line, and are going to readd them
3765                         # where necessary.
3766                         $s =~ s/\n./\n/gs;
3767                         while ($s =~ /\n\s+\\\n/) {
3768                                 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3769                         }
3770
3771                         # We want to check the first line inside the block
3772                         # starting at the end of the conditional, so remove:
3773                         #  1) any blank line termination
3774                         #  2) any opening brace { on end of the line
3775                         #  3) any do (...) {
3776                         my $continuation = 0;
3777                         my $check = 0;
3778                         $s =~ s/^.*\bdo\b//;
3779                         $s =~ s/^\s*{//;
3780                         if ($s =~ s/^\s*\\//) {
3781                                 $continuation = 1;
3782                         }
3783                         if ($s =~ s/^\s*?\n//) {
3784                                 $check = 1;
3785                                 $cond_lines++;
3786                         }
3787
3788                         # Also ignore a loop construct at the end of a
3789                         # preprocessor statement.
3790                         if (($prevline =~ /^.\s*#\s*define\s/ ||
3791                             $prevline =~ /\\\s*$/) && $continuation == 0) {
3792                                 $check = 0;
3793                         }
3794
3795                         my $cond_ptr = -1;
3796                         $continuation = 0;
3797                         while ($cond_ptr != $cond_lines) {
3798                                 $cond_ptr = $cond_lines;
3799
3800                                 # If we see an #else/#elif then the code
3801                                 # is not linear.
3802                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3803                                         $check = 0;
3804                                 }
3805
3806                                 # Ignore:
3807                                 #  1) blank lines, they should be at 0,
3808                                 #  2) preprocessor lines, and
3809                                 #  3) labels.
3810                                 if ($continuation ||
3811                                     $s =~ /^\s*?\n/ ||
3812                                     $s =~ /^\s*#\s*?/ ||
3813                                     $s =~ /^\s*$Ident\s*:/) {
3814                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3815                                         if ($s =~ s/^.*?\n//) {
3816                                                 $cond_lines++;
3817                                         }
3818                                 }
3819                         }
3820
3821                         my (undef, $sindent) = line_stats("+" . $s);
3822                         my $stat_real = raw_line($linenr, $cond_lines);
3823
3824                         # Check if either of these lines are modified, else
3825                         # this is not this patch's fault.
3826                         if (!defined($stat_real) ||
3827                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3828                                 $check = 0;
3829                         }
3830                         if (defined($stat_real) && $cond_lines > 1) {
3831                                 $stat_real = "[...]\n$stat_real";
3832                         }
3833
3834                         #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";
3835
3836                         if ($check && $s ne '' &&
3837                             (($sindent % $tabsize) != 0 ||
3838                              ($sindent < $indent) ||
3839                              ($sindent == $indent &&
3840                               ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3841                              ($sindent > $indent + $tabsize))) {
3842                                 WARN("SUSPECT_CODE_INDENT",
3843                                      "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3844                         }
3845                 }
3846
3847                 # Track the 'values' across context and added lines.
3848                 my $opline = $line; $opline =~ s/^./ /;
3849                 my ($curr_values, $curr_vars) =
3850                                 annotate_values($opline . "\n", $prev_values);
3851                 $curr_values = $prev_values . $curr_values;
3852                 if ($dbg_values) {
3853                         my $outline = $opline; $outline =~ s/\t/ /g;
3854                         print "$linenr > .$outline\n";
3855                         print "$linenr > $curr_values\n";
3856                         print "$linenr >  $curr_vars\n";
3857                 }
3858                 $prev_values = substr($curr_values, -1);
3859
3860 #ignore lines not being added
3861                 next if ($line =~ /^[^\+]/);
3862
3863 # check for dereferences that span multiple lines
3864                 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3865                     $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3866                         $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3867                         my $ref = $1;
3868                         $line =~ /^.\s*($Lval)/;
3869                         $ref .= $1;
3870                         $ref =~ s/\s//g;
3871                         WARN("MULTILINE_DEREFERENCE",
3872                              "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3873                 }
3874
3875 # check for declarations of signed or unsigned without int
3876                 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3877                         my $type = $1;
3878                         my $var = $2;
3879                         $var = "" if (!defined $var);
3880                         if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3881                                 my $sign = $1;
3882                                 my $pointer = $2;
3883
3884                                 $pointer = "" if (!defined $pointer);
3885
3886                                 if (WARN("UNSPECIFIED_INT",
3887                                          "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3888                                     $fix) {
3889                                         my $decl = trim($sign) . " int ";
3890                                         my $comp_pointer = $pointer;
3891                                         $comp_pointer =~ s/\s//g;
3892                                         $decl .= $comp_pointer;
3893                                         $decl = rtrim($decl) if ($var eq "");
3894                                         $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3895                                 }
3896                         }
3897                 }
3898
3899 # TEST: allow direct testing of the type matcher.
3900                 if ($dbg_type) {
3901                         if ($line =~ /^.\s*$Declare\s*$/) {
3902                                 ERROR("TEST_TYPE",
3903                                       "TEST: is type\n" . $herecurr);
3904                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3905                                 ERROR("TEST_NOT_TYPE",
3906                                       "TEST: is not type ($1 is)\n". $herecurr);
3907                         }
3908                         next;
3909                 }
3910 # TEST: allow direct testing of the attribute matcher.
3911                 if ($dbg_attr) {
3912                         if ($line =~ /^.\s*$Modifier\s*$/) {
3913                                 ERROR("TEST_ATTR",
3914                                       "TEST: is attr\n" . $herecurr);
3915                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3916                                 ERROR("TEST_NOT_ATTR",
3917                                       "TEST: is not attr ($1 is)\n". $herecurr);
3918                         }
3919                         next;
3920                 }
3921
3922 # check for initialisation to aggregates open brace on the next line
3923                 if ($line =~ /^.\s*{/ &&
3924                     $prevline =~ /(?:^|[^=])=\s*$/) {
3925                         if (ERROR("OPEN_BRACE",
3926                                   "that open brace { should be on the previous line\n" . $hereprev) &&
3927                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3928                                 fix_delete_line($fixlinenr - 1, $prevrawline);
3929                                 fix_delete_line($fixlinenr, $rawline);
3930                                 my $fixedline = $prevrawline;
3931                                 $fixedline =~ s/\s*=\s*$/ = {/;
3932                                 fix_insert_line($fixlinenr, $fixedline);
3933                                 $fixedline = $line;
3934                                 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3935                                 fix_insert_line($fixlinenr, $fixedline);
3936                         }
3937                 }
3938
3939 #
3940 # Checks which are anchored on the added line.
3941 #
3942
3943 # check for malformed paths in #include statements (uses RAW line)
3944                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3945                         my $path = $1;
3946                         if ($path =~ m{//}) {
3947                                 ERROR("MALFORMED_INCLUDE",
3948                                       "malformed #include filename\n" . $herecurr);
3949                         }
3950                         if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3951                                 ERROR("UAPI_INCLUDE",
3952                                       "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3953                         }
3954                 }
3955
3956 # no C99 // comments
3957                 if ($line =~ m{//}) {
3958                         if (ERROR("C99_COMMENTS",
3959                                   "do not use C99 // comments\n" . $herecurr) &&
3960                             $fix) {
3961                                 my $line = $fixed[$fixlinenr];
3962                                 if ($line =~ /\/\/(.*)$/) {
3963                                         my $comment = trim($1);
3964                                         $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3965                                 }
3966                         }
3967                 }
3968                 # Remove C99 comments.
3969                 $line =~ s@//.*@@;
3970                 $opline =~ s@//.*@@;
3971
3972 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3973 # the whole statement.
3974 #print "APW <$lines[$realline_next - 1]>\n";
3975                 if (defined $realline_next &&
3976                     exists $lines[$realline_next - 1] &&
3977                     !defined $suppress_export{$realline_next} &&
3978                     ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3979                      $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3980                         # Handle definitions which produce identifiers with
3981                         # a prefix:
3982                         #   XXX(foo);
3983                         #   EXPORT_SYMBOL(something_foo);
3984                         my $name = $1;
3985                         if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3986                             $name =~ /^${Ident}_$2/) {
3987 #print "FOO C name<$name>\n";
3988                                 $suppress_export{$realline_next} = 1;
3989
3990                         } elsif ($stat !~ /(?:
3991                                 \n.}\s*$|
3992                                 ^.DEFINE_$Ident\(\Q$name\E\)|
3993                                 ^.DECLARE_$Ident\(\Q$name\E\)|
3994                                 ^.LIST_HEAD\(\Q$name\E\)|
3995                                 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3996                                 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3997                             )/x) {
3998 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3999                                 $suppress_export{$realline_next} = 2;
4000                         } else {
4001                                 $suppress_export{$realline_next} = 1;
4002                         }
4003                 }
4004                 if (!defined $suppress_export{$linenr} &&
4005                     $prevline =~ /^.\s*$/ &&
4006                     ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4007                      $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4008 #print "FOO B <$lines[$linenr - 1]>\n";
4009                         $suppress_export{$linenr} = 2;
4010                 }
4011                 if (defined $suppress_export{$linenr} &&
4012                     $suppress_export{$linenr} == 2) {
4013                         WARN("EXPORT_SYMBOL",
4014                              "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4015                 }
4016
4017 # check for global initialisers.
4018                 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4019                         if (ERROR("GLOBAL_INITIALISERS",
4020                                   "do not initialise globals to $1\n" . $herecurr) &&
4021                             $fix) {
4022                                 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4023                         }
4024                 }
4025 # check for static initialisers.
4026                 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4027                         if (ERROR("INITIALISED_STATIC",
4028                                   "do not initialise statics to $1\n" .
4029                                       $herecurr) &&
4030                             $fix) {
4031                                 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4032                         }
4033                 }
4034
4035 # check for misordered declarations of char/short/int/long with signed/unsigned
4036                 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4037                         my $tmp = trim($1);
4038                         WARN("MISORDERED_TYPE",
4039                              "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4040                 }
4041
4042 # check for unnecessary <signed> int declarations of short/long/long long
4043                 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4044                         my $type = trim($1);
4045                         next if ($type !~ /\bint\b/);
4046                         next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4047                         my $new_type = $type;
4048                         $new_type =~ s/\b\s*int\s*\b/ /;
4049                         $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4050                         $new_type =~ s/^const\s+//;
4051                         $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4052                         $new_type = "const $new_type" if ($type =~ /^const\b/);
4053                         $new_type =~ s/\s+/ /g;
4054                         $new_type = trim($new_type);
4055                         if (WARN("UNNECESSARY_INT",
4056                                  "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4057                             $fix) {
4058                                 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4059                         }
4060                 }
4061
4062 # check for static const char * arrays.
4063                 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4064                         WARN("STATIC_CONST_CHAR_ARRAY",
4065                              "static const char * array should probably be static const char * const\n" .
4066                                 $herecurr);
4067                 }
4068
4069 # check for initialized const char arrays that should be static const
4070                 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4071                         if (WARN("STATIC_CONST_CHAR_ARRAY",
4072                                  "const array should probably be static const\n" . $herecurr) &&
4073                             $fix) {
4074                                 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4075                         }
4076                 }
4077
4078 # check for static char foo[] = "bar" declarations.
4079                 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4080                         WARN("STATIC_CONST_CHAR_ARRAY",
4081                              "static char array declaration should probably be static const char\n" .
4082                                 $herecurr);
4083                 }
4084
4085 # check for const <foo> const where <foo> is not a pointer or array type
4086                 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4087                         my $found = $1;
4088                         if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4089                                 WARN("CONST_CONST",
4090                                      "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4091                         } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4092                                 WARN("CONST_CONST",
4093                                      "'const $found const' should probably be 'const $found'\n" . $herecurr);
4094                         }
4095                 }
4096
4097 # check for non-global char *foo[] = {"bar", ...} declarations.
4098                 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4099                         WARN("STATIC_CONST_CHAR_ARRAY",
4100                              "char * array declaration might be better as static const\n" .
4101                                 $herecurr);
4102                }
4103
4104 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4105                 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4106                         my $array = $1;
4107                         if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4108                                 my $array_div = $1;
4109                                 if (WARN("ARRAY_SIZE",
4110                                          "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4111                                     $fix) {
4112                                         $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4113                                 }
4114                         }
4115                 }
4116
4117 # check for function declarations without arguments like "int foo()"
4118                 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4119                         if (ERROR("FUNCTION_WITHOUT_ARGS",
4120                                   "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4121                             $fix) {
4122                                 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4123                         }
4124                 }
4125
4126 # check for new typedefs, only function parameters and sparse annotations
4127 # make sense.
4128                 if ($line =~ /\btypedef\s/ &&
4129                     $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4130                     $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4131                     $line !~ /\b$typeTypedefs\b/ &&
4132                     $line !~ /\b__bitwise\b/) {
4133                         WARN("NEW_TYPEDEFS",
4134                              "do not add new typedefs\n" . $herecurr);
4135                 }
4136
4137 # * goes on variable not on type
4138                 # (char*[ const])
4139                 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4140                         #print "AA<$1>\n";
4141                         my ($ident, $from, $to) = ($1, $2, $2);
4142
4143                         # Should start with a space.
4144                         $to =~ s/^(\S)/ $1/;
4145                         # Should not end with a space.
4146                         $to =~ s/\s+$//;
4147                         # '*'s should not have spaces between.
4148                         while ($to =~ s/\*\s+\*/\*\*/) {
4149                         }
4150
4151 ##                      print "1: from<$from> to<$to> ident<$ident>\n";
4152                         if ($from ne $to) {
4153                                 if (ERROR("POINTER_LOCATION",
4154                                           "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4155                                     $fix) {
4156                                         my $sub_from = $ident;
4157                                         my $sub_to = $ident;
4158                                         $sub_to =~ s/\Q$from\E/$to/;
4159                                         $fixed[$fixlinenr] =~
4160                                             s@\Q$sub_from\E@$sub_to@;
4161                                 }
4162                         }
4163                 }
4164                 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4165                         #print "BB<$1>\n";
4166                         my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4167
4168                         # Should start with a space.
4169                         $to =~ s/^(\S)/ $1/;
4170                         # Should not end with a space.
4171                         $to =~ s/\s+$//;
4172                         # '*'s should not have spaces between.
4173                         while ($to =~ s/\*\s+\*/\*\*/) {
4174                         }
4175                         # Modifiers should have spaces.
4176                         $to =~ s/(\b$Modifier$)/$1 /;
4177
4178 ##                      print "2: from<$from> to<$to> ident<$ident>\n";
4179                         if ($from ne $to && $ident !~ /^$Modifier$/) {
4180                                 if (ERROR("POINTER_LOCATION",
4181                                           "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4182                                     $fix) {
4183
4184                                         my $sub_from = $match;
4185                                         my $sub_to = $match;
4186                                         $sub_to =~ s/\Q$from\E/$to/;
4187                                         $fixed[$fixlinenr] =~
4188                                             s@\Q$sub_from\E@$sub_to@;
4189                                 }
4190                         }
4191                 }
4192
4193 # avoid BUG() or BUG_ON()
4194                 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4195                         my $msg_level = \&WARN;
4196                         $msg_level = \&CHK if ($file);
4197                         &{$msg_level}("AVOID_BUG",
4198                                       "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4199                 }
4200
4201 # avoid LINUX_VERSION_CODE
4202                 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4203                         WARN("LINUX_VERSION_CODE",
4204                              "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4205                 }
4206
4207 # check for uses of printk_ratelimit
4208                 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4209                         WARN("PRINTK_RATELIMITED",
4210                              "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4211                 }
4212
4213 # printk should use KERN_* levels
4214                 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4215                         WARN("PRINTK_WITHOUT_KERN_LEVEL",
4216                              "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4217                 }
4218
4219                 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4220                         my $orig = $1;
4221                         my $level = lc($orig);
4222                         $level = "warn" if ($level eq "warning");
4223                         my $level2 = $level;
4224                         $level2 = "dbg" if ($level eq "debug");
4225                         WARN("PREFER_PR_LEVEL",
4226                              "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
4227                 }
4228
4229                 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4230                         my $orig = $1;
4231                         my $level = lc($orig);
4232                         $level = "warn" if ($level eq "warning");
4233                         $level = "dbg" if ($level eq "debug");
4234                         WARN("PREFER_DEV_LEVEL",
4235                              "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4236                 }
4237
4238 # ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4239 # number of false positives, but assembly files are not checked, so at
4240 # least the arch entry code will not trigger this warning.
4241                 if ($line =~ /\bENOSYS\b/) {
4242                         WARN("ENOSYS",
4243                              "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4244                 }
4245
4246 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4247 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4248 # Similarly to ENOSYS warning a small number of false positives is expected.
4249                 if (!$file && $line =~ /\bENOTSUPP\b/) {
4250                         if (WARN("ENOTSUPP",
4251                                  "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4252                             $fix) {
4253                                 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4254                         }
4255                 }
4256
4257 # function brace can't be on same line, except for #defines of do while,
4258 # or if closed on same line
4259                 if ($perl_version_ok &&
4260                     $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4261                     $sline !~ /\#\s*define\b.*do\s*\{/ &&
4262                     $sline !~ /}/) {
4263                         if (ERROR("OPEN_BRACE",
4264                                   "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4265                             $fix) {
4266                                 fix_delete_line($fixlinenr, $rawline);
4267                                 my $fixed_line = $rawline;
4268                                 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4269                                 my $line1 = $1;
4270                                 my $line2 = $2;
4271                                 fix_insert_line($fixlinenr, ltrim($line1));
4272                                 fix_insert_line($fixlinenr, "\+{");
4273                                 if ($line2 !~ /^\s*$/) {
4274                                         fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4275                                 }
4276                         }
4277                 }
4278
4279 # open braces for enum, union and struct go on the same line.
4280                 if ($line =~ /^.\s*{/ &&
4281                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4282                         if (ERROR("OPEN_BRACE",
4283                                   "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4284                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4285                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4286                                 fix_delete_line($fixlinenr, $rawline);
4287                                 my $fixedline = rtrim($prevrawline) . " {";
4288                                 fix_insert_line($fixlinenr, $fixedline);
4289                                 $fixedline = $rawline;
4290                                 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4291                                 if ($fixedline !~ /^\+\s*$/) {
4292                                         fix_insert_line($fixlinenr, $fixedline);
4293                                 }
4294                         }
4295                 }
4296
4297 # missing space after union, struct or enum definition
4298                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4299                         if (WARN("SPACING",
4300                                  "missing space after $1 definition\n" . $herecurr) &&
4301                             $fix) {
4302                                 $fixed[$fixlinenr] =~
4303                                     s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4304                         }
4305                 }
4306
4307 # Function pointer declarations
4308 # check spacing between type, funcptr, and args
4309 # canonical declaration is "type (*funcptr)(args...)"
4310                 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4311                         my $declare = $1;
4312                         my $pre_pointer_space = $2;
4313                         my $post_pointer_space = $3;
4314                         my $funcname = $4;
4315                         my $post_funcname_space = $5;
4316                         my $pre_args_space = $6;
4317
4318 # the $Declare variable will capture all spaces after the type
4319 # so check it for a missing trailing missing space but pointer return types
4320 # don't need a space so don't warn for those.
4321                         my $post_declare_space = "";
4322                         if ($declare =~ /(\s+)$/) {
4323                                 $post_declare_space = $1;
4324                                 $declare = rtrim($declare);
4325                         }
4326                         if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4327                                 WARN("SPACING",
4328                                      "missing space after return type\n" . $herecurr);
4329                                 $post_declare_space = " ";
4330                         }
4331
4332 # unnecessary space "type  (*funcptr)(args...)"
4333 # This test is not currently implemented because these declarations are
4334 # equivalent to
4335 #       int  foo(int bar, ...)
4336 # and this is form shouldn't/doesn't generate a checkpatch warning.
4337 #
4338 #                       elsif ($declare =~ /\s{2,}$/) {
4339 #                               WARN("SPACING",
4340 #                                    "Multiple spaces after return type\n" . $herecurr);
4341 #                       }
4342
4343 # unnecessary space "type ( *funcptr)(args...)"
4344                         if (defined $pre_pointer_space &&
4345                             $pre_pointer_space =~ /^\s/) {
4346                                 WARN("SPACING",
4347                                      "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4348                         }
4349
4350 # unnecessary space "type (* funcptr)(args...)"
4351                         if (defined $post_pointer_space &&
4352                             $post_pointer_space =~ /^\s/) {
4353                                 WARN("SPACING",
4354                                      "Unnecessary space before function pointer name\n" . $herecurr);
4355                         }
4356
4357 # unnecessary space "type (*funcptr )(args...)"
4358                         if (defined $post_funcname_space &&
4359                             $post_funcname_space =~ /^\s/) {
4360                                 WARN("SPACING",
4361                                      "Unnecessary space after function pointer name\n" . $herecurr);
4362                         }
4363
4364 # unnecessary space "type (*funcptr) (args...)"
4365                         if (defined $pre_args_space &&
4366                             $pre_args_space =~ /^\s/) {
4367                                 WARN("SPACING",
4368                                      "Unnecessary space before function pointer arguments\n" . $herecurr);
4369                         }
4370
4371                         if (show_type("SPACING") && $fix) {
4372                                 $fixed[$fixlinenr] =~
4373                                     s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4374                         }
4375                 }
4376
4377 # check for spacing round square brackets; allowed:
4378 #  1. with a type on the left -- int [] a;
4379 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4380 #  3. inside a curly brace -- = { [0...10] = 5 }
4381                 while ($line =~ /(.*?\s)\[/g) {
4382                         my ($where, $prefix) = ($-[1], $1);
4383                         if ($prefix !~ /$Type\s+$/ &&
4384                             ($where != 0 || $prefix !~ /^.\s+$/) &&
4385                             $prefix !~ /[{,:]\s+$/) {
4386                                 if (ERROR("BRACKET_SPACE",
4387                                           "space prohibited before open square bracket '['\n" . $herecurr) &&
4388                                     $fix) {
4389                                     $fixed[$fixlinenr] =~
4390                                         s/^(\+.*?)\s+\[/$1\[/;
4391                                 }
4392                         }
4393                 }
4394
4395 # check for spaces between functions and their parentheses.
4396                 while ($line =~ /($Ident)\s+\(/g) {
4397                         my $name = $1;
4398                         my $ctx_before = substr($line, 0, $-[1]);
4399                         my $ctx = "$ctx_before$name";
4400
4401                         # Ignore those directives where spaces _are_ permitted.
4402                         if ($name =~ /^(?:
4403                                 if|for|while|switch|return|case|
4404                                 volatile|__volatile__|
4405                                 __attribute__|format|__extension__|
4406                                 asm|__asm__)$/x)
4407                         {
4408                         # cpp #define statements have non-optional spaces, ie
4409                         # if there is a space between the name and the open
4410                         # parenthesis it is simply not a parameter group.
4411                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4412
4413                         # cpp #elif statement condition may start with a (
4414                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4415
4416                         # If this whole things ends with a type its most
4417                         # likely a typedef for a function.
4418                         } elsif ($ctx =~ /$Type$/) {
4419
4420                         } else {
4421                                 if (WARN("SPACING",
4422                                          "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4423                                              $fix) {
4424                                         $fixed[$fixlinenr] =~
4425                                             s/\b$name\s+\(/$name\(/;
4426                                 }
4427                         }
4428                 }
4429
4430 # Check operator spacing.
4431                 if (!($line=~/\#\s*include/)) {
4432                         my $fixed_line = "";
4433                         my $line_fixed = 0;
4434
4435                         my $ops = qr{
4436                                 <<=|>>=|<=|>=|==|!=|
4437                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4438                                 =>|->|<<|>>|<|>|=|!|~|
4439                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4440                                 \?:|\?|:
4441                         }x;
4442                         my @elements = split(/($ops|;)/, $opline);
4443
4444 ##                      print("element count: <" . $#elements . ">\n");
4445 ##                      foreach my $el (@elements) {
4446 ##                              print("el: <$el>\n");
4447 ##                      }
4448
4449                         my @fix_elements = ();
4450                         my $off = 0;
4451
4452                         foreach my $el (@elements) {
4453                                 push(@fix_elements, substr($rawline, $off, length($el)));
4454                                 $off += length($el);
4455                         }
4456
4457                         $off = 0;
4458
4459                         my $blank = copy_spacing($opline);
4460                         my $last_after = -1;
4461
4462                         for (my $n = 0; $n < $#elements; $n += 2) {
4463
4464                                 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4465
4466 ##                              print("n: <$n> good: <$good>\n");
4467
4468                                 $off += length($elements[$n]);
4469
4470                                 # Pick up the preceding and succeeding characters.
4471                                 my $ca = substr($opline, 0, $off);
4472                                 my $cc = '';
4473                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4474                                         $cc = substr($opline, $off + length($elements[$n + 1]));
4475                                 }
4476                                 my $cb = "$ca$;$cc";
4477
4478                                 my $a = '';
4479                                 $a = 'V' if ($elements[$n] ne '');
4480                                 $a = 'W' if ($elements[$n] =~ /\s$/);
4481                                 $a = 'C' if ($elements[$n] =~ /$;$/);
4482                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4483                                 $a = 'O' if ($elements[$n] eq '');
4484                                 $a = 'E' if ($ca =~ /^\s*$/);
4485
4486                                 my $op = $elements[$n + 1];
4487
4488                                 my $c = '';
4489                                 if (defined $elements[$n + 2]) {
4490                                         $c = 'V' if ($elements[$n + 2] ne '');
4491                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4492                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4493                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4494                                         $c = 'O' if ($elements[$n + 2] eq '');
4495                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4496                                 } else {
4497                                         $c = 'E';
4498                                 }
4499
4500                                 my $ctx = "${a}x${c}";
4501
4502                                 my $at = "(ctx:$ctx)";
4503
4504                                 my $ptr = substr($blank, 0, $off) . "^";
4505                                 my $hereptr = "$hereline$ptr\n";
4506
4507                                 # Pull out the value of this operator.
4508                                 my $op_type = substr($curr_values, $off + 1, 1);
4509
4510                                 # Get the full operator variant.
4511                                 my $opv = $op . substr($curr_vars, $off, 1);
4512
4513                                 # Ignore operators passed as parameters.
4514                                 if ($op_type ne 'V' &&
4515                                     $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4516
4517 #                               # Ignore comments
4518 #                               } elsif ($op =~ /^$;+$/) {
4519
4520                                 # ; should have either the end of line or a space or \ after it
4521                                 } elsif ($op eq ';') {
4522                                         if ($ctx !~ /.x[WEBC]/ &&
4523                                             $cc !~ /^\\/ && $cc !~ /^;/) {
4524                                                 if (ERROR("SPACING",
4525                                                           "space required after that '$op' $at\n" . $hereptr)) {
4526                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4527                                                         $line_fixed = 1;
4528                                                 }
4529                                         }
4530
4531                                 # // is a comment
4532                                 } elsif ($op eq '//') {
4533
4534                                 #   :   when part of a bitfield
4535                                 } elsif ($opv eq ':B') {
4536                                         # skip the bitfield test for now
4537
4538                                 # No spaces for:
4539                                 #   ->
4540                                 } elsif ($op eq '->') {
4541                                         if ($ctx =~ /Wx.|.xW/) {
4542                                                 if (ERROR("SPACING",
4543                                                           "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4544                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4545                                                         if (defined $fix_elements[$n + 2]) {
4546                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4547                                                         }
4548                                                         $line_fixed = 1;
4549                                                 }
4550                                         }
4551
4552                                 # , must not have a space before and must have a space on the right.
4553                                 } elsif ($op eq ',') {
4554                                         my $rtrim_before = 0;
4555                                         my $space_after = 0;
4556                                         if ($ctx =~ /Wx./) {
4557                                                 if (ERROR("SPACING",
4558                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4559                                                         $line_fixed = 1;
4560                                                         $rtrim_before = 1;
4561                                                 }
4562                                         }
4563                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4564                                                 if (ERROR("SPACING",
4565                                                           "space required after that '$op' $at\n" . $hereptr)) {
4566                                                         $line_fixed = 1;
4567                                                         $last_after = $n;
4568                                                         $space_after = 1;
4569                                                 }
4570                                         }
4571                                         if ($rtrim_before || $space_after) {
4572                                                 if ($rtrim_before) {
4573                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4574                                                 } else {
4575                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4576                                                 }
4577                                                 if ($space_after) {
4578                                                         $good .= " ";
4579                                                 }
4580                                         }
4581
4582                                 # '*' as part of a type definition -- reported already.
4583                                 } elsif ($opv eq '*_') {
4584                                         #warn "'*' is part of type\n";
4585
4586                                 # unary operators should have a space before and
4587                                 # none after.  May be left adjacent to another
4588                                 # unary operator, or a cast
4589                                 } elsif ($op eq '!' || $op eq '~' ||
4590                                          $opv eq '*U' || $opv eq '-U' ||
4591                                          $opv eq '&U' || $opv eq '&&U') {
4592                                         if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4593                                                 if (ERROR("SPACING",
4594                                                           "space required before that '$op' $at\n" . $hereptr)) {
4595                                                         if ($n != $last_after + 2) {
4596                                                                 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4597                                                                 $line_fixed = 1;
4598                                                         }
4599                                                 }
4600                                         }
4601                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4602                                                 # A unary '*' may be const
4603
4604                                         } elsif ($ctx =~ /.xW/) {
4605                                                 if (ERROR("SPACING",
4606                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
4607                                                         $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4608                                                         if (defined $fix_elements[$n + 2]) {
4609                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4610                                                         }
4611                                                         $line_fixed = 1;
4612                                                 }
4613                                         }
4614
4615                                 # unary ++ and unary -- are allowed no space on one side.
4616                                 } elsif ($op eq '++' or $op eq '--') {
4617                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4618                                                 if (ERROR("SPACING",
4619                                                           "space required one side of that '$op' $at\n" . $hereptr)) {
4620                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4621                                                         $line_fixed = 1;
4622                                                 }
4623                                         }
4624                                         if ($ctx =~ /Wx[BE]/ ||
4625                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4626                                                 if (ERROR("SPACING",
4627                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4628                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4629                                                         $line_fixed = 1;
4630                                                 }
4631                                         }
4632                                         if ($ctx =~ /ExW/) {
4633                                                 if (ERROR("SPACING",
4634                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
4635                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4636                                                         if (defined $fix_elements[$n + 2]) {
4637                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4638                                                         }
4639                                                         $line_fixed = 1;
4640                                                 }
4641                                         }
4642
4643                                 # << and >> may either have or not have spaces both sides
4644                                 } elsif ($op eq '<<' or $op eq '>>' or
4645                                          $op eq '&' or $op eq '^' or $op eq '|' or
4646                                          $op eq '+' or $op eq '-' or
4647                                          $op eq '*' or $op eq '/' or
4648                                          $op eq '%')
4649                                 {
4650                                         if ($check) {
4651                                                 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4652                                                         if (CHK("SPACING",
4653                                                                 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4654                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4655                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4656                                                                 $line_fixed = 1;
4657                                                         }
4658                                                 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4659                                                         if (CHK("SPACING",
4660                                                                 "space preferred before that '$op' $at\n" . $hereptr)) {
4661                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4662                                                                 $line_fixed = 1;
4663                                                         }
4664                                                 }
4665                                         } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4666                                                 if (ERROR("SPACING",
4667                                                           "need consistent spacing around '$op' $at\n" . $hereptr)) {
4668                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4669                                                         if (defined $fix_elements[$n + 2]) {
4670                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4671                                                         }
4672                                                         $line_fixed = 1;
4673                                                 }
4674                                         }
4675
4676                                 # A colon needs no spaces before when it is
4677                                 # terminating a case value or a label.
4678                                 } elsif ($opv eq ':C' || $opv eq ':L') {
4679                                         if ($ctx =~ /Wx./) {
4680                                                 if (ERROR("SPACING",
4681                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4682                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4683                                                         $line_fixed = 1;
4684                                                 }
4685                                         }
4686
4687                                 # All the others need spaces both sides.
4688                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4689                                         my $ok = 0;
4690
4691                                         # Ignore email addresses <foo@bar>
4692                                         if (($op eq '<' &&
4693                                              $cc =~ /^\S+\@\S+>/) ||
4694                                             ($op eq '>' &&
4695                                              $ca =~ /<\S+\@\S+$/))
4696                                         {
4697                                                 $ok = 1;
4698                                         }
4699
4700                                         # for asm volatile statements
4701                                         # ignore a colon with another
4702                                         # colon immediately before or after
4703                                         if (($op eq ':') &&
4704                                             ($ca =~ /:$/ || $cc =~ /^:/)) {
4705                                                 $ok = 1;
4706                                         }
4707
4708                                         # messages are ERROR, but ?: are CHK
4709                                         if ($ok == 0) {
4710                                                 my $msg_level = \&ERROR;
4711                                                 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4712
4713                                                 if (&{$msg_level}("SPACING",
4714                                                                   "spaces required around that '$op' $at\n" . $hereptr)) {
4715                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4716                                                         if (defined $fix_elements[$n + 2]) {
4717                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4718                                                         }
4719                                                         $line_fixed = 1;
4720                                                 }
4721                                         }
4722                                 }
4723                                 $off += length($elements[$n + 1]);
4724
4725 ##                              print("n: <$n> GOOD: <$good>\n");
4726
4727                                 $fixed_line = $fixed_line . $good;
4728                         }
4729
4730                         if (($#elements % 2) == 0) {
4731                                 $fixed_line = $fixed_line . $fix_elements[$#elements];
4732                         }
4733
4734                         if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4735                                 $fixed[$fixlinenr] = $fixed_line;
4736                         }
4737
4738
4739                 }
4740
4741 # check for whitespace before a non-naked semicolon
4742                 if ($line =~ /^\+.*\S\s+;\s*$/) {
4743                         if (WARN("SPACING",
4744                                  "space prohibited before semicolon\n" . $herecurr) &&
4745                             $fix) {
4746                                 1 while $fixed[$fixlinenr] =~
4747                                     s/^(\+.*\S)\s+;/$1;/;
4748                         }
4749                 }
4750
4751 # check for multiple assignments
4752                 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4753                         CHK("MULTIPLE_ASSIGNMENTS",
4754                             "multiple assignments should be avoided\n" . $herecurr);
4755                 }
4756
4757 ## # check for multiple declarations, allowing for a function declaration
4758 ## # continuation.
4759 ##              if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4760 ##                  $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4761 ##
4762 ##                      # Remove any bracketed sections to ensure we do not
4763 ##                      # falsly report the parameters of functions.
4764 ##                      my $ln = $line;
4765 ##                      while ($ln =~ s/\([^\(\)]*\)//g) {
4766 ##                      }
4767 ##                      if ($ln =~ /,/) {
4768 ##                              WARN("MULTIPLE_DECLARATION",
4769 ##                                   "declaring multiple variables together should be avoided\n" . $herecurr);
4770 ##                      }
4771 ##              }
4772
4773 #need space before brace following if, while, etc
4774                 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4775                     $line =~ /\b(?:else|do)\{/) {
4776                         if (ERROR("SPACING",
4777                                   "space required before the open brace '{'\n" . $herecurr) &&
4778                             $fix) {
4779                                 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4780                         }
4781                 }
4782
4783 ## # check for blank lines before declarations
4784 ##              if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4785 ##                  $prevrawline =~ /^.\s*$/) {
4786 ##                      WARN("SPACING",
4787 ##                           "No blank lines before declarations\n" . $hereprev);
4788 ##              }
4789 ##
4790
4791 # closing brace should have a space following it when it has anything
4792 # on the line
4793                 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4794                         if (ERROR("SPACING",
4795                                   "space required after that close brace '}'\n" . $herecurr) &&
4796                             $fix) {
4797                                 $fixed[$fixlinenr] =~
4798                                     s/}((?!(?:,|;|\)))\S)/} $1/;
4799                         }
4800                 }
4801
4802 # check spacing on square brackets
4803                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4804                         if (ERROR("SPACING",
4805                                   "space prohibited after that open square bracket '['\n" . $herecurr) &&
4806                             $fix) {
4807                                 $fixed[$fixlinenr] =~
4808                                     s/\[\s+/\[/;
4809                         }
4810                 }
4811                 if ($line =~ /\s\]/) {
4812                         if (ERROR("SPACING",
4813                                   "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4814                             $fix) {
4815                                 $fixed[$fixlinenr] =~
4816                                     s/\s+\]/\]/;
4817                         }
4818                 }
4819
4820 # check spacing on parentheses
4821                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4822                     $line !~ /for\s*\(\s+;/) {
4823                         if (ERROR("SPACING",
4824                                   "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4825                             $fix) {
4826                                 $fixed[$fixlinenr] =~
4827                                     s/\(\s+/\(/;
4828                         }
4829                 }
4830                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4831                     $line !~ /for\s*\(.*;\s+\)/ &&
4832                     $line !~ /:\s+\)/) {
4833                         if (ERROR("SPACING",
4834                                   "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4835                             $fix) {
4836                                 $fixed[$fixlinenr] =~
4837                                     s/\s+\)/\)/;
4838                         }
4839                 }
4840
4841 # check unnecessary parentheses around addressof/dereference single $Lvals
4842 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4843
4844                 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4845                         my $var = $1;
4846                         if (CHK("UNNECESSARY_PARENTHESES",
4847                                 "Unnecessary parentheses around $var\n" . $herecurr) &&
4848                             $fix) {
4849                                 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4850                         }
4851                 }
4852
4853 # check for unnecessary parentheses around function pointer uses
4854 # ie: (foo->bar)(); should be foo->bar();
4855 # but not "if (foo->bar) (" to avoid some false positives
4856                 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4857                         my $var = $2;
4858                         if (CHK("UNNECESSARY_PARENTHESES",
4859                                 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4860                             $fix) {
4861                                 my $var2 = deparenthesize($var);
4862                                 $var2 =~ s/\s//g;
4863                                 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4864                         }
4865                 }
4866
4867 # check for unnecessary parentheses around comparisons in if uses
4868 # when !drivers/staging or command-line uses --strict
4869                 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4870                     $perl_version_ok && defined($stat) &&
4871                     $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4872                         my $if_stat = $1;
4873                         my $test = substr($2, 1, -1);
4874                         my $herectx;
4875                         while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4876                                 my $match = $1;
4877                                 # avoid parentheses around potential macro args
4878                                 next if ($match =~ /^\s*\w+\s*$/);
4879                                 if (!defined($herectx)) {
4880                                         $herectx = $here . "\n";
4881                                         my $cnt = statement_rawlines($if_stat);
4882                                         for (my $n = 0; $n < $cnt; $n++) {
4883                                                 my $rl = raw_line($linenr, $n);
4884                                                 $herectx .=  $rl . "\n";
4885                                                 last if $rl =~ /^[ \+].*\{/;
4886                                         }
4887                                 }
4888                                 CHK("UNNECESSARY_PARENTHESES",
4889                                     "Unnecessary parentheses around '$match'\n" . $herectx);
4890                         }
4891                 }
4892
4893 #goto labels aren't indented, allow a single space however
4894                 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4895                    !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4896                         if (WARN("INDENTED_LABEL",
4897                                  "labels should not be indented\n" . $herecurr) &&
4898                             $fix) {
4899                                 $fixed[$fixlinenr] =~
4900                                     s/^(.)\s+/$1/;
4901                         }
4902                 }
4903
4904 # return is not a function
4905                 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4906                         my $spacing = $1;
4907                         if ($perl_version_ok &&
4908                             $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4909                                 my $value = $1;
4910                                 $value = deparenthesize($value);
4911                                 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4912                                         ERROR("RETURN_PARENTHESES",
4913                                               "return is not a function, parentheses are not required\n" . $herecurr);
4914                                 }
4915                         } elsif ($spacing !~ /\s+/) {
4916                                 ERROR("SPACING",
4917                                       "space required before the open parenthesis '('\n" . $herecurr);
4918                         }
4919                 }
4920
4921 # unnecessary return in a void function
4922 # at end-of-function, with the previous line a single leading tab, then return;
4923 # and the line before that not a goto label target like "out:"
4924                 if ($sline =~ /^[ \+]}\s*$/ &&
4925                     $prevline =~ /^\+\treturn\s*;\s*$/ &&
4926                     $linenr >= 3 &&
4927                     $lines[$linenr - 3] =~ /^[ +]/ &&
4928                     $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4929                         WARN("RETURN_VOID",
4930                              "void function return statements are not generally useful\n" . $hereprev);
4931                }
4932
4933 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4934                 if ($perl_version_ok &&
4935                     $line =~ /\bif\s*((?:\(\s*){2,})/) {
4936                         my $openparens = $1;
4937                         my $count = $openparens =~ tr@\(@\(@;
4938                         my $msg = "";
4939                         if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4940                                 my $comp = $4;  #Not $1 because of $LvalOrFunc
4941                                 $msg = " - maybe == should be = ?" if ($comp eq "==");
4942                                 WARN("UNNECESSARY_PARENTHESES",
4943                                      "Unnecessary parentheses$msg\n" . $herecurr);
4944                         }
4945                 }
4946
4947 # comparisons with a constant or upper case identifier on the left
4948 #       avoid cases like "foo + BAR < baz"
4949 #       only fix matches surrounded by parentheses to avoid incorrect
4950 #       conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4951                 if ($perl_version_ok &&
4952                     $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4953                         my $lead = $1;
4954                         my $const = $2;
4955                         my $comp = $3;
4956                         my $to = $4;
4957                         my $newcomp = $comp;
4958                         if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4959                             $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4960                             WARN("CONSTANT_COMPARISON",
4961                                  "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4962                             $fix) {
4963                                 if ($comp eq "<") {
4964                                         $newcomp = ">";
4965                                 } elsif ($comp eq "<=") {
4966                                         $newcomp = ">=";
4967                                 } elsif ($comp eq ">") {
4968                                         $newcomp = "<";
4969                                 } elsif ($comp eq ">=") {
4970                                         $newcomp = "<=";
4971                                 }
4972                                 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4973                         }
4974                 }
4975
4976 # Return of what appears to be an errno should normally be negative
4977                 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4978                         my $name = $1;
4979                         if ($name ne 'EOF' && $name ne 'ERROR') {
4980                                 WARN("USE_NEGATIVE_ERRNO",
4981                                      "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4982                         }
4983                 }
4984
4985 # Need a space before open parenthesis after if, while etc
4986                 if ($line =~ /\b(if|while|for|switch)\(/) {
4987                         if (ERROR("SPACING",
4988                                   "space required before the open parenthesis '('\n" . $herecurr) &&
4989                             $fix) {
4990                                 $fixed[$fixlinenr] =~
4991                                     s/\b(if|while|for|switch)\(/$1 \(/;
4992                         }
4993                 }
4994
4995 # Check for illegal assignment in if conditional -- and check for trailing
4996 # statements after the conditional.
4997                 if ($line =~ /do\s*(?!{)/) {
4998                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4999                                 ctx_statement_block($linenr, $realcnt, 0)
5000                                         if (!defined $stat);
5001                         my ($stat_next) = ctx_statement_block($line_nr_next,
5002                                                 $remain_next, $off_next);
5003                         $stat_next =~ s/\n./\n /g;
5004                         ##print "stat<$stat> stat_next<$stat_next>\n";
5005
5006                         if ($stat_next =~ /^\s*while\b/) {
5007                                 # If the statement carries leading newlines,
5008                                 # then count those as offsets.
5009                                 my ($whitespace) =
5010                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5011                                 my $offset =
5012                                         statement_rawlines($whitespace) - 1;
5013
5014                                 $suppress_whiletrailers{$line_nr_next +
5015                                                                 $offset} = 1;
5016                         }
5017                 }
5018                 if (!defined $suppress_whiletrailers{$linenr} &&
5019                     defined($stat) && defined($cond) &&
5020                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5021                         my ($s, $c) = ($stat, $cond);
5022
5023                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5024                                 ERROR("ASSIGN_IN_IF",
5025                                       "do not use assignment in if condition\n" . $herecurr);
5026                         }
5027
5028                         # Find out what is on the end of the line after the
5029                         # conditional.
5030                         substr($s, 0, length($c), '');
5031                         $s =~ s/\n.*//g;
5032                         $s =~ s/$;//g;  # Remove any comments
5033                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5034                             $c !~ /}\s*while\s*/)
5035                         {
5036                                 # Find out how long the conditional actually is.
5037                                 my @newlines = ($c =~ /\n/gs);
5038                                 my $cond_lines = 1 + $#newlines;
5039                                 my $stat_real = '';
5040
5041                                 $stat_real = raw_line($linenr, $cond_lines)
5042                                                         . "\n" if ($cond_lines);
5043                                 if (defined($stat_real) && $cond_lines > 1) {
5044                                         $stat_real = "[...]\n$stat_real";
5045                                 }
5046
5047                                 ERROR("TRAILING_STATEMENTS",
5048                                       "trailing statements should be on next line\n" . $herecurr . $stat_real);
5049                         }
5050                 }
5051
5052 # Check for bitwise tests written as boolean
5053                 if ($line =~ /
5054                         (?:
5055                                 (?:\[|\(|\&\&|\|\|)
5056                                 \s*0[xX][0-9]+\s*
5057                                 (?:\&\&|\|\|)
5058                         |
5059                                 (?:\&\&|\|\|)
5060                                 \s*0[xX][0-9]+\s*
5061                                 (?:\&\&|\|\||\)|\])
5062                         )/x)
5063                 {
5064                         WARN("HEXADECIMAL_BOOLEAN_TEST",
5065                              "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5066                 }
5067
5068 # if and else should not have general statements after it
5069                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5070                         my $s = $1;
5071                         $s =~ s/$;//g;  # Remove any comments
5072                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5073                                 ERROR("TRAILING_STATEMENTS",
5074                                       "trailing statements should be on next line\n" . $herecurr);
5075                         }
5076                 }
5077 # if should not continue a brace
5078                 if ($line =~ /}\s*if\b/) {
5079                         ERROR("TRAILING_STATEMENTS",
5080                               "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5081                                 $herecurr);
5082                 }
5083 # case and default should not have general statements after them
5084                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5085                     $line !~ /\G(?:
5086                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5087                         \s*return\s+
5088                     )/xg)
5089                 {
5090                         ERROR("TRAILING_STATEMENTS",
5091                               "trailing statements should be on next line\n" . $herecurr);
5092                 }
5093
5094                 # Check for }<nl>else {, these must be at the same
5095                 # indent level to be relevant to each other.
5096                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5097                     $previndent == $indent) {
5098                         if (ERROR("ELSE_AFTER_BRACE",
5099                                   "else should follow close brace '}'\n" . $hereprev) &&
5100                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5101                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5102                                 fix_delete_line($fixlinenr, $rawline);
5103                                 my $fixedline = $prevrawline;
5104                                 $fixedline =~ s/}\s*$//;
5105                                 if ($fixedline !~ /^\+\s*$/) {
5106                                         fix_insert_line($fixlinenr, $fixedline);
5107                                 }
5108                                 $fixedline = $rawline;
5109                                 $fixedline =~ s/^(.\s*)else/$1} else/;
5110                                 fix_insert_line($fixlinenr, $fixedline);
5111                         }
5112                 }
5113
5114                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5115                     $previndent == $indent) {
5116                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5117
5118                         # Find out what is on the end of the line after the
5119                         # conditional.
5120                         substr($s, 0, length($c), '');
5121                         $s =~ s/\n.*//g;
5122
5123                         if ($s =~ /^\s*;/) {
5124                                 if (ERROR("WHILE_AFTER_BRACE",
5125                                           "while should follow close brace '}'\n" . $hereprev) &&
5126                                     $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5127                                         fix_delete_line($fixlinenr - 1, $prevrawline);
5128                                         fix_delete_line($fixlinenr, $rawline);
5129                                         my $fixedline = $prevrawline;
5130                                         my $trailing = $rawline;
5131                                         $trailing =~ s/^\+//;
5132                                         $trailing = trim($trailing);
5133                                         $fixedline =~ s/}\s*$/} $trailing/;
5134                                         fix_insert_line($fixlinenr, $fixedline);
5135                                 }
5136                         }
5137                 }
5138
5139 #Specific variable tests
5140                 while ($line =~ m{($Constant|$Lval)}g) {
5141                         my $var = $1;
5142
5143 #CamelCase
5144                         if ($var !~ /^$Constant$/ &&
5145                             $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5146 #Ignore Page<foo> variants
5147                             $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5148 #Ignore SI style variants like nS, mV and dB
5149 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5150                             $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5151 #Ignore some three character SI units explicitly, like MiB and KHz
5152                             $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5153                                 while ($var =~ m{($Ident)}g) {
5154                                         my $word = $1;
5155                                         next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5156                                         if ($check) {
5157                                                 seed_camelcase_includes();
5158                                                 if (!$file && !$camelcase_file_seeded) {
5159                                                         seed_camelcase_file($realfile);
5160                                                         $camelcase_file_seeded = 1;
5161                                                 }
5162                                         }
5163                                         if (!defined $camelcase{$word}) {
5164                                                 $camelcase{$word} = 1;
5165                                                 CHK("CAMELCASE",
5166                                                     "Avoid CamelCase: <$word>\n" . $herecurr);
5167                                         }
5168                                 }
5169                         }
5170                 }
5171
5172 #no spaces allowed after \ in define
5173                 if ($line =~ /\#\s*define.*\\\s+$/) {
5174                         if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5175                                  "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5176                             $fix) {
5177                                 $fixed[$fixlinenr] =~ s/\s+$//;
5178                         }
5179                 }
5180
5181 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5182 # itself <asm/foo.h> (uses RAW line)
5183                 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5184                         my $file = "$1.h";
5185                         my $checkfile = "include/linux/$file";
5186                         if (-f "$root/$checkfile" &&
5187                             $realfile ne $checkfile &&
5188                             $1 !~ /$allowed_asm_includes/)
5189                         {
5190                                 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5191                                 if ($asminclude > 0) {
5192                                         if ($realfile =~ m{^arch/}) {
5193                                                 CHK("ARCH_INCLUDE_LINUX",
5194                                                     "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5195                                         } else {
5196                                                 WARN("INCLUDE_LINUX",
5197                                                      "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5198                                         }
5199                                 }
5200                         }
5201                 }
5202
5203 # multi-statement macros should be enclosed in a do while loop, grab the
5204 # first statement and ensure its the whole macro if its not enclosed
5205 # in a known good container
5206                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5207                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5208                         my $ln = $linenr;
5209                         my $cnt = $realcnt;
5210                         my ($off, $dstat, $dcond, $rest);
5211                         my $ctx = '';
5212                         my $has_flow_statement = 0;
5213                         my $has_arg_concat = 0;
5214                         ($dstat, $dcond, $ln, $cnt, $off) =
5215                                 ctx_statement_block($linenr, $realcnt, 0);
5216                         $ctx = $dstat;
5217                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5218                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5219
5220                         $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5221                         $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5222
5223                         $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5224                         my $define_args = $1;
5225                         my $define_stmt = $dstat;
5226                         my @def_args = ();
5227
5228                         if (defined $define_args && $define_args ne "") {
5229                                 $define_args = substr($define_args, 1, length($define_args) - 2);
5230                                 $define_args =~ s/\s*//g;
5231                                 $define_args =~ s/\\\+?//g;
5232                                 @def_args = split(",", $define_args);
5233                         }
5234
5235                         $dstat =~ s/$;//g;
5236                         $dstat =~ s/\\\n.//g;
5237                         $dstat =~ s/^\s*//s;
5238                         $dstat =~ s/\s*$//s;
5239
5240                         # Flatten any parentheses and braces
5241                         while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5242                                $dstat =~ s/\{[^\{\}]*\}/1/ ||
5243                                $dstat =~ s/.\[[^\[\]]*\]/1/)
5244                         {
5245                         }
5246
5247                         # Flatten any obvious string concatenation.
5248                         while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5249                                $dstat =~ s/$Ident\s*($String)/$1/)
5250                         {
5251                         }
5252
5253                         # Make asm volatile uses seem like a generic function
5254                         $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5255
5256                         my $exceptions = qr{
5257                                 $Declare|
5258                                 module_param_named|
5259                                 MODULE_PARM_DESC|
5260                                 DECLARE_PER_CPU|
5261                                 DEFINE_PER_CPU|
5262                                 __typeof__\(|
5263                                 union|
5264                                 struct|
5265                                 \.$Ident\s*=\s*|
5266                                 ^\"|\"$|
5267                                 ^\[
5268                         }x;
5269                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5270
5271                         $ctx =~ s/\n*$//;
5272                         my $stmt_cnt = statement_rawlines($ctx);
5273                         my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5274
5275                         if ($dstat ne '' &&
5276                             $dstat !~ /^(?:$Ident|-?$Constant),$/ &&                    # 10, // foo(),
5277                             $dstat !~ /^(?:$Ident|-?$Constant);$/ &&                    # foo();
5278                             $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&          # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5279                             $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&                  # character constants
5280                             $dstat !~ /$exceptions/ &&
5281                             $dstat !~ /^\.$Ident\s*=/ &&                                # .foo =
5282                             $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&          # stringification #foo
5283                             $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&       # do {...} while (...); // do {...} while (...)
5284                             $dstat !~ /^for\s*$Constant$/ &&                            # for (...)
5285                             $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&   # for (...) bar()
5286                             $dstat !~ /^do\s*{/ &&                                      # do {...
5287                             $dstat !~ /^\(\{/ &&                                                # ({...
5288                             $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5289                         {
5290                                 if ($dstat =~ /^\s*if\b/) {
5291                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5292                                               "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5293                                 } elsif ($dstat =~ /;/) {
5294                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5295                                               "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5296                                 } else {
5297                                         ERROR("COMPLEX_MACRO",
5298                                               "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5299                                 }
5300
5301                         }
5302
5303                         # Make $define_stmt single line, comment-free, etc
5304                         my @stmt_array = split('\n', $define_stmt);
5305                         my $first = 1;
5306                         $define_stmt = "";
5307                         foreach my $l (@stmt_array) {
5308                                 $l =~ s/\\$//;
5309                                 if ($first) {
5310                                         $define_stmt = $l;
5311                                         $first = 0;
5312                                 } elsif ($l =~ /^[\+ ]/) {
5313                                         $define_stmt .= substr($l, 1);
5314                                 }
5315                         }
5316                         $define_stmt =~ s/$;//g;
5317                         $define_stmt =~ s/\s+/ /g;
5318                         $define_stmt = trim($define_stmt);
5319
5320 # check if any macro arguments are reused (ignore '...' and 'type')
5321                         foreach my $arg (@def_args) {
5322                                 next if ($arg =~ /\.\.\./);
5323                                 next if ($arg =~ /^type$/i);
5324                                 my $tmp_stmt = $define_stmt;
5325                                 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5326                                 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5327                                 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5328                                 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5329                                 if ($use_cnt > 1) {
5330                                         CHK("MACRO_ARG_REUSE",
5331                                             "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5332                                     }
5333 # check if any macro arguments may have other precedence issues
5334                                 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5335                                     ((defined($1) && $1 ne ',') ||
5336                                      (defined($2) && $2 ne ','))) {
5337                                         CHK("MACRO_ARG_PRECEDENCE",
5338                                             "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5339                                 }
5340                         }
5341
5342 # check for macros with flow control, but without ## concatenation
5343 # ## concatenation is commonly a macro that defines a function so ignore those
5344                         if ($has_flow_statement && !$has_arg_concat) {
5345                                 my $cnt = statement_rawlines($ctx);
5346                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5347
5348                                 WARN("MACRO_WITH_FLOW_CONTROL",
5349                                      "Macros with flow control statements should be avoided\n" . "$herectx");
5350                         }
5351
5352 # check for line continuations outside of #defines, preprocessor #, and asm
5353
5354                 } else {
5355                         if ($prevline !~ /^..*\\$/ &&
5356                             $line !~ /^\+\s*\#.*\\$/ &&         # preprocessor
5357                             $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&   # asm
5358                             $line =~ /^\+.*\\$/) {
5359                                 WARN("LINE_CONTINUATIONS",
5360                                      "Avoid unnecessary line continuations\n" . $herecurr);
5361                         }
5362                 }
5363
5364 # do {} while (0) macro tests:
5365 # single-statement macros do not need to be enclosed in do while (0) loop,
5366 # macro should not end with a semicolon
5367                 if ($perl_version_ok &&
5368                     $realfile !~ m@/vmlinux.lds.h$@ &&
5369                     $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5370                         my $ln = $linenr;
5371                         my $cnt = $realcnt;
5372                         my ($off, $dstat, $dcond, $rest);
5373                         my $ctx = '';
5374                         ($dstat, $dcond, $ln, $cnt, $off) =
5375                                 ctx_statement_block($linenr, $realcnt, 0);
5376                         $ctx = $dstat;
5377
5378                         $dstat =~ s/\\\n.//g;
5379                         $dstat =~ s/$;/ /g;
5380
5381                         if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5382                                 my $stmts = $2;
5383                                 my $semis = $3;
5384
5385                                 $ctx =~ s/\n*$//;
5386                                 my $cnt = statement_rawlines($ctx);
5387                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5388
5389                                 if (($stmts =~ tr/;/;/) == 1 &&
5390                                     $stmts !~ /^\s*(if|while|for|switch)\b/) {
5391                                         WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5392                                              "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5393                                 }
5394                                 if (defined $semis && $semis ne "") {
5395                                         WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5396                                              "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5397                                 }
5398                         } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5399                                 $ctx =~ s/\n*$//;
5400                                 my $cnt = statement_rawlines($ctx);
5401                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5402
5403                                 WARN("TRAILING_SEMICOLON",
5404                                      "macros should not use a trailing semicolon\n" . "$herectx");
5405                         }
5406                 }
5407
5408 # check for redundant bracing round if etc
5409                 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5410                         my ($level, $endln, @chunks) =
5411                                 ctx_statement_full($linenr, $realcnt, 1);
5412                         #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5413                         #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5414                         if ($#chunks > 0 && $level == 0) {
5415                                 my @allowed = ();
5416                                 my $allow = 0;
5417                                 my $seen = 0;
5418                                 my $herectx = $here . "\n";
5419                                 my $ln = $linenr - 1;
5420                                 for my $chunk (@chunks) {
5421                                         my ($cond, $block) = @{$chunk};
5422
5423                                         # If the condition carries leading newlines, then count those as offsets.
5424                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5425                                         my $offset = statement_rawlines($whitespace) - 1;
5426
5427                                         $allowed[$allow] = 0;
5428                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5429
5430                                         # We have looked at and allowed this specific line.
5431                                         $suppress_ifbraces{$ln + $offset} = 1;
5432
5433                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5434                                         $ln += statement_rawlines($block) - 1;
5435
5436                                         substr($block, 0, length($cond), '');
5437
5438                                         $seen++ if ($block =~ /^\s*{/);
5439
5440                                         #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5441                                         if (statement_lines($cond) > 1) {
5442                                                 #print "APW: ALLOWED: cond<$cond>\n";
5443                                                 $allowed[$allow] = 1;
5444                                         }
5445                                         if ($block =~/\b(?:if|for|while)\b/) {
5446                                                 #print "APW: ALLOWED: block<$block>\n";
5447                                                 $allowed[$allow] = 1;
5448                                         }
5449                                         if (statement_block_size($block) > 1) {
5450                                                 #print "APW: ALLOWED: lines block<$block>\n";
5451                                                 $allowed[$allow] = 1;
5452                                         }
5453                                         $allow++;
5454                                 }
5455                                 if ($seen) {
5456                                         my $sum_allowed = 0;
5457                                         foreach (@allowed) {
5458                                                 $sum_allowed += $_;
5459                                         }
5460                                         if ($sum_allowed == 0) {
5461                                                 WARN("BRACES",
5462                                                      "braces {} are not necessary for any arm of this statement\n" . $herectx);
5463                                         } elsif ($sum_allowed != $allow &&
5464                                                  $seen != $allow) {
5465                                                 CHK("BRACES",
5466                                                     "braces {} should be used on all arms of this statement\n" . $herectx);
5467                                         }
5468                                 }
5469                         }
5470                 }
5471                 if (!defined $suppress_ifbraces{$linenr - 1} &&
5472                                         $line =~ /\b(if|while|for|else)\b/) {
5473                         my $allowed = 0;
5474
5475                         # Check the pre-context.
5476                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5477                                 #print "APW: ALLOWED: pre<$1>\n";
5478                                 $allowed = 1;
5479                         }
5480
5481                         my ($level, $endln, @chunks) =
5482                                 ctx_statement_full($linenr, $realcnt, $-[0]);
5483
5484                         # Check the condition.
5485                         my ($cond, $block) = @{$chunks[0]};
5486                         #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5487                         if (defined $cond) {
5488                                 substr($block, 0, length($cond), '');
5489                         }
5490                         if (statement_lines($cond) > 1) {
5491                                 #print "APW: ALLOWED: cond<$cond>\n";
5492                                 $allowed = 1;
5493                         }
5494                         if ($block =~/\b(?:if|for|while)\b/) {
5495                                 #print "APW: ALLOWED: block<$block>\n";
5496                                 $allowed = 1;
5497                         }
5498                         if (statement_block_size($block) > 1) {
5499                                 #print "APW: ALLOWED: lines block<$block>\n";
5500                                 $allowed = 1;
5501                         }
5502                         # Check the post-context.
5503                         if (defined $chunks[1]) {
5504                                 my ($cond, $block) = @{$chunks[1]};
5505                                 if (defined $cond) {
5506                                         substr($block, 0, length($cond), '');
5507                                 }
5508                                 if ($block =~ /^\s*\{/) {
5509                                         #print "APW: ALLOWED: chunk-1 block<$block>\n";
5510                                         $allowed = 1;
5511                                 }
5512                         }
5513                         if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5514                                 my $cnt = statement_rawlines($block);
5515                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5516
5517                                 WARN("BRACES",
5518                                      "braces {} are not necessary for single statement blocks\n" . $herectx);
5519                         }
5520                 }
5521
5522 # check for single line unbalanced braces
5523                 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5524                     $sline =~ /^.\s*else\s*\{\s*$/) {
5525                         CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5526                 }
5527
5528 # check for unnecessary blank lines around braces
5529                 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5530                         if (CHK("BRACES",
5531                                 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5532                             $fix && $prevrawline =~ /^\+/) {
5533                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5534                         }
5535                 }
5536                 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5537                         if (CHK("BRACES",
5538                                 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5539                             $fix) {
5540                                 fix_delete_line($fixlinenr, $rawline);
5541                         }
5542                 }
5543
5544 # no volatiles please
5545                 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5546                 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5547                         WARN("VOLATILE",
5548                              "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5549                 }
5550
5551 # Check for user-visible strings broken across lines, which breaks the ability
5552 # to grep for the string.  Make exceptions when the previous string ends in a
5553 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5554 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5555                 if ($line =~ /^\+\s*$String/ &&
5556                     $prevline =~ /"\s*$/ &&
5557                     $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5558                         if (WARN("SPLIT_STRING",
5559                                  "quoted string split across lines\n" . $hereprev) &&
5560                                      $fix &&
5561                                      $prevrawline =~ /^\+.*"\s*$/ &&
5562                                      $last_coalesced_string_linenr != $linenr - 1) {
5563                                 my $extracted_string = get_quoted_string($line, $rawline);
5564                                 my $comma_close = "";
5565                                 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5566                                         $comma_close = $1;
5567                                 }
5568
5569                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5570                                 fix_delete_line($fixlinenr, $rawline);
5571                                 my $fixedline = $prevrawline;
5572                                 $fixedline =~ s/"\s*$//;
5573                                 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5574                                 fix_insert_line($fixlinenr - 1, $fixedline);
5575                                 $fixedline = $rawline;
5576                                 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5577                                 if ($fixedline !~ /\+\s*$/) {
5578                                         fix_insert_line($fixlinenr, $fixedline);
5579                                 }
5580                                 $last_coalesced_string_linenr = $linenr;
5581                         }
5582                 }
5583
5584 # check for missing a space in a string concatenation
5585                 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5586                         WARN('MISSING_SPACE',
5587                              "break quoted strings at a space character\n" . $hereprev);
5588                 }
5589
5590 # check for an embedded function name in a string when the function is known
5591 # This does not work very well for -f --file checking as it depends on patch
5592 # context providing the function name or a single line form for in-file
5593 # function declarations
5594                 if ($line =~ /^\+.*$String/ &&
5595                     defined($context_function) &&
5596                     get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5597                     length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5598                         WARN("EMBEDDED_FUNCTION_NAME",
5599                              "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5600                 }
5601
5602 # check for spaces before a quoted newline
5603                 if ($rawline =~ /^.*\".*\s\\n/) {
5604                         if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5605                                  "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5606                             $fix) {
5607                                 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5608                         }
5609
5610                 }
5611
5612 # concatenated string without spaces between elements
5613                 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5614                         if (CHK("CONCATENATED_STRING",
5615                                 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5616                             $fix) {
5617                                 while ($line =~ /($String)/g) {
5618                                         my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5619                                         $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5620                                         $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5621                                 }
5622                         }
5623                 }
5624
5625 # uncoalesced string fragments
5626                 if ($line =~ /$String\s*"/) {
5627                         if (WARN("STRING_FRAGMENTS",
5628                                  "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5629                             $fix) {
5630                                 while ($line =~ /($String)(?=\s*")/g) {
5631                                         my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5632                                         $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5633                                 }
5634                         }
5635                 }
5636
5637 # check for non-standard and hex prefixed decimal printf formats
5638                 my $show_L = 1; #don't show the same defect twice
5639                 my $show_Z = 1;
5640                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5641                         my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5642                         $string =~ s/%%/__/g;
5643                         # check for %L
5644                         if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5645                                 WARN("PRINTF_L",
5646                                      "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5647                                 $show_L = 0;
5648                         }
5649                         # check for %Z
5650                         if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5651                                 WARN("PRINTF_Z",
5652                                      "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5653                                 $show_Z = 0;
5654                         }
5655                         # check for 0x<decimal>
5656                         if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5657                                 ERROR("PRINTF_0XDECIMAL",
5658                                       "Prefixing 0x with decimal output is defective\n" . $herecurr);
5659                         }
5660                 }
5661
5662 # check for line continuations in quoted strings with odd counts of "
5663                 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5664                         WARN("LINE_CONTINUATIONS",
5665                              "Avoid line continuations in quoted strings\n" . $herecurr);
5666                 }
5667
5668 # warn about #if 0
5669                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5670                         WARN("IF_0",
5671                              "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5672                 }
5673
5674 # warn about #if 1
5675                 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5676                         WARN("IF_1",
5677                              "Consider removing the #if 1 and its #endif\n" . $herecurr);
5678                 }
5679
5680 # check for needless "if (<foo>) fn(<foo>)" uses
5681                 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5682                         my $tested = quotemeta($1);
5683                         my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5684                         if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5685                                 my $func = $1;
5686                                 if (WARN('NEEDLESS_IF',
5687                                          "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5688                                     $fix) {
5689                                         my $do_fix = 1;
5690                                         my $leading_tabs = "";
5691                                         my $new_leading_tabs = "";
5692                                         if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5693                                                 $leading_tabs = $1;
5694                                         } else {
5695                                                 $do_fix = 0;
5696                                         }
5697                                         if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5698                                                 $new_leading_tabs = $1;
5699                                                 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5700                                                         $do_fix = 0;
5701                                                 }
5702                                         } else {
5703                                                 $do_fix = 0;
5704                                         }
5705                                         if ($do_fix) {
5706                                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5707                                                 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5708                                         }
5709                                 }
5710                         }
5711                 }
5712
5713 # check for unnecessary "Out of Memory" messages
5714                 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5715                     $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5716                     (defined $1 || defined $3) &&
5717                     $linenr > 3) {
5718                         my $testval = $2;
5719                         my $testline = $lines[$linenr - 3];
5720
5721                         my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5722 #                       print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5723
5724                         if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5725                             $s !~ /\b__GFP_NOWARN\b/ ) {
5726                                 WARN("OOM_MESSAGE",
5727                                      "Possible unnecessary 'out of memory' message\n" . $hereprev);
5728                         }
5729                 }
5730
5731 # check for logging functions with KERN_<LEVEL>
5732                 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5733                     $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5734                         my $level = $1;
5735                         if (WARN("UNNECESSARY_KERN_LEVEL",
5736                                  "Possible unnecessary $level\n" . $herecurr) &&
5737                             $fix) {
5738                                 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5739                         }
5740                 }
5741
5742 # check for logging continuations
5743                 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5744                         WARN("LOGGING_CONTINUATION",
5745                              "Avoid logging continuation uses where feasible\n" . $herecurr);
5746                 }
5747
5748 # check for mask then right shift without a parentheses
5749                 if ($perl_version_ok &&
5750                     $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5751                     $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5752                         WARN("MASK_THEN_SHIFT",
5753                              "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5754                 }
5755
5756 # check for pointer comparisons to NULL
5757                 if ($perl_version_ok) {
5758                         while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5759                                 my $val = $1;
5760                                 my $equal = "!";
5761                                 $equal = "" if ($4 eq "!=");
5762                                 if (CHK("COMPARISON_TO_NULL",
5763                                         "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5764                                             $fix) {
5765                                         $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5766                                 }
5767                         }
5768                 }
5769
5770 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5771                 if ($line =~ /(\b$InitAttribute\b)/) {
5772                         my $attr = $1;
5773                         if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5774                                 my $ptr = $1;
5775                                 my $var = $2;
5776                                 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5777                                       ERROR("MISPLACED_INIT",
5778                                             "$attr should be placed after $var\n" . $herecurr)) ||
5779                                      ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5780                                       WARN("MISPLACED_INIT",
5781                                            "$attr should be placed after $var\n" . $herecurr))) &&
5782                                     $fix) {
5783                                         $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;
5784                                 }
5785                         }
5786                 }
5787
5788 # check for $InitAttributeData (ie: __initdata) with const
5789                 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5790                         my $attr = $1;
5791                         $attr =~ /($InitAttributePrefix)(.*)/;
5792                         my $attr_prefix = $1;
5793                         my $attr_type = $2;
5794                         if (ERROR("INIT_ATTRIBUTE",
5795                                   "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5796                             $fix) {
5797                                 $fixed[$fixlinenr] =~
5798                                     s/$InitAttributeData/${attr_prefix}initconst/;
5799                         }
5800                 }
5801
5802 # check for $InitAttributeConst (ie: __initconst) without const
5803                 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5804                         my $attr = $1;
5805                         if (ERROR("INIT_ATTRIBUTE",
5806                                   "Use of $attr requires a separate use of const\n" . $herecurr) &&
5807                             $fix) {
5808                                 my $lead = $fixed[$fixlinenr] =~
5809                                     /(^\+\s*(?:static\s+))/;
5810                                 $lead = rtrim($1);
5811                                 $lead = "$lead " if ($lead !~ /^\+$/);
5812                                 $lead = "${lead}const ";
5813                                 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5814                         }
5815                 }
5816
5817 # check for __read_mostly with const non-pointer (should just be const)
5818                 if ($line =~ /\b__read_mostly\b/ &&
5819                     $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5820                         if (ERROR("CONST_READ_MOSTLY",
5821                                   "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5822                             $fix) {
5823                                 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5824                         }
5825                 }
5826
5827 # don't use __constant_<foo> functions outside of include/uapi/
5828                 if ($realfile !~ m@^include/uapi/@ &&
5829                     $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5830                         my $constant_func = $1;
5831                         my $func = $constant_func;
5832                         $func =~ s/^__constant_//;
5833                         if (WARN("CONSTANT_CONVERSION",
5834                                  "$constant_func should be $func\n" . $herecurr) &&
5835                             $fix) {
5836                                 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5837                         }
5838                 }
5839
5840 # prefer usleep_range over udelay
5841                 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5842                         my $delay = $1;
5843                         # ignore udelay's < 10, however
5844                         if (! ($delay < 10) ) {
5845                                 CHK("USLEEP_RANGE",
5846                                     "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5847                         }
5848                         if ($delay > 2000) {
5849                                 WARN("LONG_UDELAY",
5850                                      "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5851                         }
5852                 }
5853
5854 # warn about unexpectedly long msleep's
5855                 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5856                         if ($1 < 20) {
5857                                 WARN("MSLEEP",
5858                                      "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5859                         }
5860                 }
5861
5862 # check for comparisons of jiffies
5863                 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5864                         WARN("JIFFIES_COMPARISON",
5865                              "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5866                 }
5867
5868 # check for comparisons of get_jiffies_64()
5869                 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5870                         WARN("JIFFIES_COMPARISON",
5871                              "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5872                 }
5873
5874 # warn about #ifdefs in C files
5875 #               if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5876 #                       print "#ifdef in C files should be avoided\n";
5877 #                       print "$herecurr";
5878 #                       $clean = 0;
5879 #               }
5880
5881 # warn about spacing in #ifdefs
5882                 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5883                         if (ERROR("SPACING",
5884                                   "exactly one space required after that #$1\n" . $herecurr) &&
5885                             $fix) {
5886                                 $fixed[$fixlinenr] =~
5887                                     s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5888                         }
5889
5890                 }
5891
5892 # check for spinlock_t definitions without a comment.
5893                 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5894                     $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5895                         my $which = $1;
5896                         if (!ctx_has_comment($first_line, $linenr)) {
5897                                 CHK("UNCOMMENTED_DEFINITION",
5898                                     "$1 definition without comment\n" . $herecurr);
5899                         }
5900                 }
5901 # check for memory barriers without a comment.
5902
5903                 my $barriers = qr{
5904                         mb|
5905                         rmb|
5906                         wmb|
5907                         read_barrier_depends
5908                 }x;
5909                 my $barrier_stems = qr{
5910                         mb__before_atomic|
5911                         mb__after_atomic|
5912                         store_release|
5913                         load_acquire|
5914                         store_mb|
5915                         (?:$barriers)
5916                 }x;
5917                 my $all_barriers = qr{
5918                         (?:$barriers)|
5919                         smp_(?:$barrier_stems)|
5920                         virt_(?:$barrier_stems)
5921                 }x;
5922
5923                 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5924                         if (!ctx_has_comment($first_line, $linenr)) {
5925                                 WARN("MEMORY_BARRIER",
5926                                      "memory barrier without comment\n" . $herecurr);
5927                         }
5928                 }
5929
5930                 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5931
5932                 if ($realfile !~ m@^include/asm-generic/@ &&
5933                     $realfile !~ m@/barrier\.h$@ &&
5934                     $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5935                     $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5936                         WARN("MEMORY_BARRIER",
5937                              "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5938                 }
5939
5940 # check for waitqueue_active without a comment.
5941                 if ($line =~ /\bwaitqueue_active\s*\(/) {
5942                         if (!ctx_has_comment($first_line, $linenr)) {
5943                                 WARN("WAITQUEUE_ACTIVE",
5944                                      "waitqueue_active without comment\n" . $herecurr);
5945                         }
5946                 }
5947
5948 # check for data_race without a comment.
5949                 if ($line =~ /\bdata_race\s*\(/) {
5950                         if (!ctx_has_comment($first_line, $linenr)) {
5951                                 WARN("DATA_RACE",
5952                                      "data_race without comment\n" . $herecurr);
5953                         }
5954                 }
5955
5956 # check for smp_read_barrier_depends and read_barrier_depends
5957                 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5958                         WARN("READ_BARRIER_DEPENDS",
5959                              "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5960                 }
5961
5962 # check of hardware specific defines
5963                 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5964                         CHK("ARCH_DEFINES",
5965                             "architecture specific defines should be avoided\n" .  $herecurr);
5966                 }
5967
5968 # check that the storage class is not after a type
5969                 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5970                         WARN("STORAGE_CLASS",
5971                              "storage class '$2' should be located before type '$1'\n" . $herecurr);
5972                 }
5973 # Check that the storage class is at the beginning of a declaration
5974                 if ($line =~ /\b$Storage\b/ &&
5975                     $line !~ /^.\s*$Storage/ &&
5976                     $line =~ /^.\s*(.+?)\$Storage\s/ &&
5977                     $1 !~ /[\,\)]\s*$/) {
5978                         WARN("STORAGE_CLASS",
5979                              "storage class should be at the beginning of the declaration\n" . $herecurr);
5980                 }
5981
5982 # check the location of the inline attribute, that it is between
5983 # storage class and type.
5984                 if ($line =~ /\b$Type\s+$Inline\b/ ||
5985                     $line =~ /\b$Inline\s+$Storage\b/) {
5986                         ERROR("INLINE_LOCATION",
5987                               "inline keyword should sit between storage class and type\n" . $herecurr);
5988                 }
5989
5990 # Check for __inline__ and __inline, prefer inline
5991                 if ($realfile !~ m@\binclude/uapi/@ &&
5992                     $line =~ /\b(__inline__|__inline)\b/) {
5993                         if (WARN("INLINE",
5994                                  "plain inline is preferred over $1\n" . $herecurr) &&
5995                             $fix) {
5996                                 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5997
5998                         }
5999                 }
6000
6001 # Check for __attribute__ packed, prefer __packed
6002                 if ($realfile !~ m@\binclude/uapi/@ &&
6003                     $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
6004                         WARN("PREFER_PACKED",
6005                              "__packed is preferred over __attribute__((packed))\n" . $herecurr);
6006                 }
6007
6008 # Check for __attribute__ aligned, prefer __aligned
6009                 if ($realfile !~ m@\binclude/uapi/@ &&
6010                     $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
6011                         WARN("PREFER_ALIGNED",
6012                              "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
6013                 }
6014
6015 # Check for __attribute__ section, prefer __section
6016                 if ($realfile !~ m@\binclude/uapi/@ &&
6017                     $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
6018                         my $old = substr($rawline, $-[1], $+[1] - $-[1]);
6019                         my $new = substr($old, 1, -1);
6020                         if (WARN("PREFER_SECTION",
6021                                  "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
6022                             $fix) {
6023                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
6024                         }
6025                 }
6026
6027 # Check for __attribute__ format(printf, prefer __printf
6028                 if ($realfile !~ m@\binclude/uapi/@ &&
6029                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
6030                         if (WARN("PREFER_PRINTF",
6031                                  "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
6032                             $fix) {
6033                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
6034
6035                         }
6036                 }
6037
6038 # Check for __attribute__ format(scanf, prefer __scanf
6039                 if ($realfile !~ m@\binclude/uapi/@ &&
6040                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
6041                         if (WARN("PREFER_SCANF",
6042                                  "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
6043                             $fix) {
6044                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
6045                         }
6046                 }
6047
6048 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6049                 if ($perl_version_ok &&
6050                     $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6051                     ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6052                      $line =~ /\b__weak\b/)) {
6053                         ERROR("WEAK_DECLARATION",
6054                               "Using weak declarations can have unintended link defects\n" . $herecurr);
6055                 }
6056
6057 # check for c99 types like uint8_t used outside of uapi/ and tools/
6058                 if ($realfile !~ m@\binclude/uapi/@ &&
6059                     $realfile !~ m@\btools/@ &&
6060                     $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6061                         my $type = $1;
6062                         if ($type =~ /\b($typeC99Typedefs)\b/) {
6063                                 $type = $1;
6064                                 my $kernel_type = 'u';
6065                                 $kernel_type = 's' if ($type =~ /^_*[si]/);
6066                                 $type =~ /(\d+)/;
6067                                 $kernel_type .= $1;
6068                                 if (CHK("PREFER_KERNEL_TYPES",
6069                                         "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6070                                     $fix) {
6071                                         $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6072                                 }
6073                         }
6074                 }
6075
6076 # check for cast of C90 native int or longer types constants
6077                 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6078                         my $cast = $1;
6079                         my $const = $2;
6080                         if (WARN("TYPECAST_INT_CONSTANT",
6081                                  "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6082                             $fix) {
6083                                 my $suffix = "";
6084                                 my $newconst = $const;
6085                                 $newconst =~ s/${Int_type}$//;
6086                                 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6087                                 if ($cast =~ /\blong\s+long\b/) {
6088                                         $suffix .= 'LL';
6089                                 } elsif ($cast =~ /\blong\b/) {
6090                                         $suffix .= 'L';
6091                                 }
6092                                 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6093                         }
6094                 }
6095
6096 # check for sizeof(&)
6097                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6098                         WARN("SIZEOF_ADDRESS",
6099                              "sizeof(& should be avoided\n" . $herecurr);
6100                 }
6101
6102 # check for sizeof without parenthesis
6103                 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6104                         if (WARN("SIZEOF_PARENTHESIS",
6105                                  "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6106                             $fix) {
6107                                 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6108                         }
6109                 }
6110
6111 # check for struct spinlock declarations
6112                 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6113                         WARN("USE_SPINLOCK_T",
6114                              "struct spinlock should be spinlock_t\n" . $herecurr);
6115                 }
6116
6117 # check for seq_printf uses that could be seq_puts
6118                 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6119                         my $fmt = get_quoted_string($line, $rawline);
6120                         $fmt =~ s/%%//g;
6121                         if ($fmt !~ /%/) {
6122                                 if (WARN("PREFER_SEQ_PUTS",
6123                                          "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6124                                     $fix) {
6125                                         $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6126                                 }
6127                         }
6128                 }
6129
6130 # check for vsprintf extension %p<foo> misuses
6131                 if ($perl_version_ok &&
6132                     defined $stat &&
6133                     $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6134                     $1 !~ /^_*volatile_*$/) {
6135                         my $stat_real;
6136
6137                         my $lc = $stat =~ tr@\n@@;
6138                         $lc = $lc + $linenr;
6139                         for (my $count = $linenr; $count <= $lc; $count++) {
6140                                 my $specifier;
6141                                 my $extension;
6142                                 my $qualifier;
6143                                 my $bad_specifier = "";
6144                                 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6145                                 $fmt =~ s/%%//g;
6146
6147                                 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6148                                         $specifier = $1;
6149                                         $extension = $2;
6150                                         $qualifier = $3;
6151                                         if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6152                                             ($extension eq "f" &&
6153                                              defined $qualifier && $qualifier !~ /^w/)) {
6154                                                 $bad_specifier = $specifier;
6155                                                 last;
6156                                         }
6157                                         if ($extension eq "x" && !defined($stat_real)) {
6158                                                 if (!defined($stat_real)) {
6159                                                         $stat_real = get_stat_real($linenr, $lc);
6160                                                 }
6161                                                 WARN("VSPRINTF_SPECIFIER_PX",
6162                                                      "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");
6163                                         }
6164                                 }
6165                                 if ($bad_specifier ne "") {
6166                                         my $stat_real = get_stat_real($linenr, $lc);
6167                                         my $ext_type = "Invalid";
6168                                         my $use = "";
6169                                         if ($bad_specifier =~ /p[Ff]/) {
6170                                                 $use = " - use %pS instead";
6171                                                 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6172                                         }
6173
6174                                         WARN("VSPRINTF_POINTER_EXTENSION",
6175                                              "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6176                                 }
6177                         }
6178                 }
6179
6180 # Check for misused memsets
6181                 if ($perl_version_ok &&
6182                     defined $stat &&
6183                     $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6184
6185                         my $ms_addr = $2;
6186                         my $ms_val = $7;
6187                         my $ms_size = $12;
6188
6189                         if ($ms_size =~ /^(0x|)0$/i) {
6190                                 ERROR("MEMSET",
6191                                       "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6192                         } elsif ($ms_size =~ /^(0x|)1$/i) {
6193                                 WARN("MEMSET",
6194                                      "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6195                         }
6196                 }
6197
6198 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6199 #               if ($perl_version_ok &&
6200 #                   defined $stat &&
6201 #                   $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6202 #                       if (WARN("PREFER_ETHER_ADDR_COPY",
6203 #                                "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6204 #                           $fix) {
6205 #                               $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6206 #                       }
6207 #               }
6208
6209 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6210 #               if ($perl_version_ok &&
6211 #                   defined $stat &&
6212 #                   $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6213 #                       WARN("PREFER_ETHER_ADDR_EQUAL",
6214 #                            "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6215 #               }
6216
6217 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6218 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6219 #               if ($perl_version_ok &&
6220 #                   defined $stat &&
6221 #                   $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6222 #
6223 #                       my $ms_val = $7;
6224 #
6225 #                       if ($ms_val =~ /^(?:0x|)0+$/i) {
6226 #                               if (WARN("PREFER_ETH_ZERO_ADDR",
6227 #                                        "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6228 #                                   $fix) {
6229 #                                       $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6230 #                               }
6231 #                       } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6232 #                               if (WARN("PREFER_ETH_BROADCAST_ADDR",
6233 #                                        "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6234 #                                   $fix) {
6235 #                                       $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6236 #                               }
6237 #                       }
6238 #               }
6239
6240 # typecasts on min/max could be min_t/max_t
6241                 if ($perl_version_ok &&
6242                     defined $stat &&
6243                     $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6244                         if (defined $2 || defined $7) {
6245                                 my $call = $1;
6246                                 my $cast1 = deparenthesize($2);
6247                                 my $arg1 = $3;
6248                                 my $cast2 = deparenthesize($7);
6249                                 my $arg2 = $8;
6250                                 my $cast;
6251
6252                                 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6253                                         $cast = "$cast1 or $cast2";
6254                                 } elsif ($cast1 ne "") {
6255                                         $cast = $cast1;
6256                                 } else {
6257                                         $cast = $cast2;
6258                                 }
6259                                 WARN("MINMAX",
6260                                      "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6261                         }
6262                 }
6263
6264 # check usleep_range arguments
6265                 if ($perl_version_ok &&
6266                     defined $stat &&
6267                     $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6268                         my $min = $1;
6269                         my $max = $7;
6270                         if ($min eq $max) {
6271                                 WARN("USLEEP_RANGE",
6272                                      "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6273                         } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6274                                  $min > $max) {
6275                                 WARN("USLEEP_RANGE",
6276                                      "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6277                         }
6278                 }
6279
6280 # check for naked sscanf
6281                 if ($perl_version_ok &&
6282                     defined $stat &&
6283                     $line =~ /\bsscanf\b/ &&
6284                     ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6285                      $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6286                      $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6287                         my $lc = $stat =~ tr@\n@@;
6288                         $lc = $lc + $linenr;
6289                         my $stat_real = get_stat_real($linenr, $lc);
6290                         WARN("NAKED_SSCANF",
6291                              "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6292                 }
6293
6294 # check for simple sscanf that should be kstrto<foo>
6295                 if ($perl_version_ok &&
6296                     defined $stat &&
6297                     $line =~ /\bsscanf\b/) {
6298                         my $lc = $stat =~ tr@\n@@;
6299                         $lc = $lc + $linenr;
6300                         my $stat_real = get_stat_real($linenr, $lc);
6301                         if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6302                                 my $format = $6;
6303                                 my $count = $format =~ tr@%@%@;
6304                                 if ($count == 1 &&
6305                                     $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6306                                         WARN("SSCANF_TO_KSTRTO",
6307                                              "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6308                                 }
6309                         }
6310                 }
6311
6312 # check for new externs in .h files.
6313                 if ($realfile =~ /\.h$/ &&
6314                     $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6315                         if (CHK("AVOID_EXTERNS",
6316                                 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6317                             $fix) {
6318                                 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6319                         }
6320                 }
6321
6322 # check for new externs in .c files.
6323                 if ($realfile =~ /\.c$/ && defined $stat &&
6324                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6325                 {
6326                         my $function_name = $1;
6327                         my $paren_space = $2;
6328
6329                         my $s = $stat;
6330                         if (defined $cond) {
6331                                 substr($s, 0, length($cond), '');
6332                         }
6333                         if ($s =~ /^\s*;/ &&
6334                             $function_name ne 'uninitialized_var')
6335                         {
6336                                 WARN("AVOID_EXTERNS",
6337                                      "externs should be avoided in .c files\n" .  $herecurr);
6338                         }
6339
6340                         if ($paren_space =~ /\n/) {
6341                                 WARN("FUNCTION_ARGUMENTS",
6342                                      "arguments for function declarations should follow identifier\n" . $herecurr);
6343                         }
6344
6345                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6346                     $stat =~ /^.\s*extern\s+/)
6347                 {
6348                         WARN("AVOID_EXTERNS",
6349                              "externs should be avoided in .c files\n" .  $herecurr);
6350                 }
6351
6352 # check for function declarations that have arguments without identifier names
6353 # while avoiding uninitialized_var(x)
6354                 if (defined $stat &&
6355                     $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:($Ident)|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6356                     (!defined($1) ||
6357                      (defined($1) && $1 ne "uninitialized_var")) &&
6358                      $2 ne "void") {
6359                         my $args = trim($2);
6360                         while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6361                                 my $arg = trim($1);
6362                                 if ($arg =~ /^$Type$/ &&
6363                                         $arg !~ /enum\s+$Ident$/) {
6364                                         WARN("FUNCTION_ARGUMENTS",
6365                                              "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6366                                 }
6367                         }
6368                 }
6369
6370 # check for function definitions
6371                 if ($perl_version_ok &&
6372                     defined $stat &&
6373                     $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6374                         $context_function = $1;
6375
6376 # check for multiline function definition with misplaced open brace
6377                         my $ok = 0;
6378                         my $cnt = statement_rawlines($stat);
6379                         my $herectx = $here . "\n";
6380                         for (my $n = 0; $n < $cnt; $n++) {
6381                                 my $rl = raw_line($linenr, $n);
6382                                 $herectx .=  $rl . "\n";
6383                                 $ok = 1 if ($rl =~ /^[ \+]\{/);
6384                                 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6385                                 last if $rl =~ /^[ \+].*\{/;
6386                         }
6387                         if (!$ok) {
6388                                 ERROR("OPEN_BRACE",
6389                                       "open brace '{' following function definitions go on the next line\n" . $herectx);
6390                         }
6391                 }
6392
6393 # checks for new __setup's
6394                 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6395                         my $name = $1;
6396
6397                         if (!grep(/$name/, @setup_docs)) {
6398                                 CHK("UNDOCUMENTED_SETUP",
6399                                     "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6400                         }
6401                 }
6402
6403 # check for pointless casting of alloc functions
6404                 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6405                         WARN("UNNECESSARY_CASTS",
6406                              "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6407                 }
6408
6409 # alloc style
6410 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6411                 if ($perl_version_ok &&
6412                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6413                         CHK("ALLOC_SIZEOF_STRUCT",
6414                             "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6415                 }
6416
6417 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6418                 if ($perl_version_ok &&
6419                     defined $stat &&
6420                     $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6421                         my $oldfunc = $3;
6422                         my $a1 = $4;
6423                         my $a2 = $10;
6424                         my $newfunc = "kmalloc_array";
6425                         $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6426                         my $r1 = $a1;
6427                         my $r2 = $a2;
6428                         if ($a1 =~ /^sizeof\s*\S/) {
6429                                 $r1 = $a2;
6430                                 $r2 = $a1;
6431                         }
6432                         if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6433                             !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6434                                 my $cnt = statement_rawlines($stat);
6435                                 my $herectx = get_stat_here($linenr, $cnt, $here);
6436
6437                                 if (WARN("ALLOC_WITH_MULTIPLY",
6438                                          "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6439                                     $cnt == 1 &&
6440                                     $fix) {
6441                                         $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;
6442                                 }
6443                         }
6444                 }
6445
6446 # check for krealloc arg reuse
6447                 if ($perl_version_ok &&
6448                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6449                     $1 eq $3) {
6450                         WARN("KREALLOC_ARG_REUSE",
6451                              "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6452                 }
6453
6454 # check for alloc argument mismatch
6455                 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6456                         WARN("ALLOC_ARRAY_ARGS",
6457                              "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6458                 }
6459
6460 # check for multiple semicolons
6461                 if ($line =~ /;\s*;\s*$/) {
6462                         if (WARN("ONE_SEMICOLON",
6463                                  "Statements terminations use 1 semicolon\n" . $herecurr) &&
6464                             $fix) {
6465                                 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6466                         }
6467                 }
6468
6469 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6470                 if ($realfile !~ m@^include/uapi/@ &&
6471                     $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6472                         my $ull = "";
6473                         $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6474                         if (CHK("BIT_MACRO",
6475                                 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6476                             $fix) {
6477                                 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6478                         }
6479                 }
6480
6481 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6482                 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6483                         my $config = $1;
6484                         if (WARN("PREFER_IS_ENABLED",
6485                                  "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6486                             $fix) {
6487                                 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6488                         }
6489                 }
6490
6491 # check for case / default statements not preceded by break/fallthrough/switch
6492                 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6493                         my $has_break = 0;
6494                         my $has_statement = 0;
6495                         my $count = 0;
6496                         my $prevline = $linenr;
6497                         while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6498                                 $prevline--;
6499                                 my $rline = $rawlines[$prevline - 1];
6500                                 my $fline = $lines[$prevline - 1];
6501                                 last if ($fline =~ /^\@\@/);
6502                                 next if ($fline =~ /^\-/);
6503                                 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6504                                 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6505                                 next if ($fline =~ /^.[\s$;]*$/);
6506                                 $has_statement = 1;
6507                                 $count++;
6508                                 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6509                         }
6510                         if (!$has_break && $has_statement) {
6511                                 WARN("MISSING_BREAK",
6512                                      "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6513                         }
6514                 }
6515
6516 # check for /* fallthrough */ like comment, prefer fallthrough;
6517                 my @fallthroughs = (
6518                         'fallthrough',
6519                         '@fallthrough@',
6520                         'lint -fallthrough[ \t]*',
6521                         'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6522                         '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6523                         'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6524                         'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6525                     );
6526                 if ($raw_comment ne '') {
6527                         foreach my $ft (@fallthroughs) {
6528                                 if ($raw_comment =~ /$ft/) {
6529                                         my $msg_level = \&WARN;
6530                                         $msg_level = \&CHK if ($file);
6531                                         &{$msg_level}("PREFER_FALLTHROUGH",
6532                                                       "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6533                                         last;
6534                                 }
6535                         }
6536                 }
6537
6538 # check for switch/default statements without a break;
6539                 if ($perl_version_ok &&
6540                     defined $stat &&
6541                     $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6542                         my $cnt = statement_rawlines($stat);
6543                         my $herectx = get_stat_here($linenr, $cnt, $here);
6544
6545                         WARN("DEFAULT_NO_BREAK",
6546                              "switch default: should use break\n" . $herectx);
6547                 }
6548
6549 # check for gcc specific __FUNCTION__
6550                 if ($line =~ /\b__FUNCTION__\b/) {
6551                         if (WARN("USE_FUNC",
6552                                  "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
6553                             $fix) {
6554                                 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6555                         }
6556                 }
6557
6558 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6559                 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6560                         ERROR("DATE_TIME",
6561                               "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6562                 }
6563
6564 # check for use of yield()
6565                 if ($line =~ /\byield\s*\(\s*\)/) {
6566                         WARN("YIELD",
6567                              "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
6568                 }
6569
6570 # check for comparisons against true and false
6571                 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6572                         my $lead = $1;
6573                         my $arg = $2;
6574                         my $test = $3;
6575                         my $otype = $4;
6576                         my $trail = $5;
6577                         my $op = "!";
6578
6579                         ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6580
6581                         my $type = lc($otype);
6582                         if ($type =~ /^(?:true|false)$/) {
6583                                 if (("$test" eq "==" && "$type" eq "true") ||
6584                                     ("$test" eq "!=" && "$type" eq "false")) {
6585                                         $op = "";
6586                                 }
6587
6588                                 CHK("BOOL_COMPARISON",
6589                                     "Using comparison to $otype is error prone\n" . $herecurr);
6590
6591 ## maybe suggesting a correct construct would better
6592 ##                                  "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6593
6594                         }
6595                 }
6596
6597 # check for semaphores initialized locked
6598                 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6599                         WARN("CONSIDER_COMPLETION",
6600                              "consider using a completion\n" . $herecurr);
6601                 }
6602
6603 # recommend kstrto* over simple_strto* and strict_strto*
6604                 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6605                         WARN("CONSIDER_KSTRTO",
6606                              "$1 is obsolete, use k$3 instead\n" . $herecurr);
6607                 }
6608
6609 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6610                 if ($line =~ /^.\s*__initcall\s*\(/) {
6611                         WARN("USE_DEVICE_INITCALL",
6612                              "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6613                 }
6614
6615 # check for spin_is_locked(), suggest lockdep instead
6616                 if ($line =~ /\bspin_is_locked\(/) {
6617                         WARN("USE_LOCKDEP",
6618                              "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6619                 }
6620
6621 # check for deprecated apis
6622                 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6623                         my $deprecated_api = $1;
6624                         my $new_api = $deprecated_apis{$deprecated_api};
6625                         WARN("DEPRECATED_API",
6626                              "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6627                 }
6628
6629 # check for various structs that are normally const (ops, kgdb, device_tree)
6630 # and avoid what seem like struct definitions 'struct foo {'
6631                 if ($line !~ /\bconst\b/ &&
6632                     $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6633                         WARN("CONST_STRUCT",
6634                              "struct $1 should normally be const\n" . $herecurr);
6635                 }
6636
6637 # use of NR_CPUS is usually wrong
6638 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6639                 if ($line =~ /\bNR_CPUS\b/ &&
6640                     $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6641                     $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6642                     $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6643                     $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6644                     $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6645                 {
6646                         WARN("NR_CPUS",
6647                              "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6648                 }
6649
6650 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6651                 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6652                         ERROR("DEFINE_ARCH_HAS",
6653                               "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6654                 }
6655
6656 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6657                 if ($perl_version_ok &&
6658                     $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6659                         WARN("LIKELY_MISUSE",
6660                              "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6661                 }
6662
6663 # nested likely/unlikely calls
6664                 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6665                         WARN("LIKELY_MISUSE",
6666                              "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6667                 }
6668
6669 # whine mightly about in_atomic
6670                 if ($line =~ /\bin_atomic\s*\(/) {
6671                         if ($realfile =~ m@^drivers/@) {
6672                                 ERROR("IN_ATOMIC",
6673                                       "do not use in_atomic in drivers\n" . $herecurr);
6674                         } elsif ($realfile !~ m@^kernel/@) {
6675                                 WARN("IN_ATOMIC",
6676                                      "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6677                         }
6678                 }
6679
6680 # check for mutex_trylock_recursive usage
6681                 if ($line =~ /mutex_trylock_recursive/) {
6682                         ERROR("LOCKING",
6683                               "recursive locking is bad, do not use this ever.\n" . $herecurr);
6684                 }
6685
6686 # check for lockdep_set_novalidate_class
6687                 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6688                     $line =~ /__lockdep_no_validate__\s*\)/ ) {
6689                         if ($realfile !~ m@^kernel/lockdep@ &&
6690                             $realfile !~ m@^include/linux/lockdep@ &&
6691                             $realfile !~ m@^drivers/base/core@) {
6692                                 ERROR("LOCKDEP",
6693                                       "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6694                         }
6695                 }
6696
6697                 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6698                     $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6699                         WARN("EXPORTED_WORLD_WRITABLE",
6700                              "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6701                 }
6702
6703 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6704 # and whether or not function naming is typical and if
6705 # DEVICE_ATTR permissions uses are unusual too
6706                 if ($perl_version_ok &&
6707                     defined $stat &&
6708                     $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*\)/) {
6709                         my $var = $1;
6710                         my $perms = $2;
6711                         my $show = $3;
6712                         my $store = $4;
6713                         my $octal_perms = perms_to_octal($perms);
6714                         if ($show =~ /^${var}_show$/ &&
6715                             $store =~ /^${var}_store$/ &&
6716                             $octal_perms eq "0644") {
6717                                 if (WARN("DEVICE_ATTR_RW",
6718                                          "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6719                                     $fix) {
6720                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6721                                 }
6722                         } elsif ($show =~ /^${var}_show$/ &&
6723                                  $store =~ /^NULL$/ &&
6724                                  $octal_perms eq "0444") {
6725                                 if (WARN("DEVICE_ATTR_RO",
6726                                          "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6727                                     $fix) {
6728                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6729                                 }
6730                         } elsif ($show =~ /^NULL$/ &&
6731                                  $store =~ /^${var}_store$/ &&
6732                                  $octal_perms eq "0200") {
6733                                 if (WARN("DEVICE_ATTR_WO",
6734                                          "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6735                                     $fix) {
6736                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6737                                 }
6738                         } elsif ($octal_perms eq "0644" ||
6739                                  $octal_perms eq "0444" ||
6740                                  $octal_perms eq "0200") {
6741                                 my $newshow = "$show";
6742                                 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6743                                 my $newstore = $store;
6744                                 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6745                                 my $rename = "";
6746                                 if ($show ne $newshow) {
6747                                         $rename .= " '$show' to '$newshow'";
6748                                 }
6749                                 if ($store ne $newstore) {
6750                                         $rename .= " '$store' to '$newstore'";
6751                                 }
6752                                 WARN("DEVICE_ATTR_FUNCTIONS",
6753                                      "Consider renaming function(s)$rename\n" . $herecurr);
6754                         } else {
6755                                 WARN("DEVICE_ATTR_PERMS",
6756                                      "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6757                         }
6758                 }
6759
6760 # Mode permission misuses where it seems decimal should be octal
6761 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6762 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6763 #   specific definition of not visible in sysfs.
6764 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6765 #   use the default permissions
6766                 if ($perl_version_ok &&
6767                     defined $stat &&
6768                     $line =~ /$mode_perms_search/) {
6769                         foreach my $entry (@mode_permission_funcs) {
6770                                 my $func = $entry->[0];
6771                                 my $arg_pos = $entry->[1];
6772
6773                                 my $lc = $stat =~ tr@\n@@;
6774                                 $lc = $lc + $linenr;
6775                                 my $stat_real = get_stat_real($linenr, $lc);
6776
6777                                 my $skip_args = "";
6778                                 if ($arg_pos > 1) {
6779                                         $arg_pos--;
6780                                         $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6781                                 }
6782                                 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6783                                 if ($stat =~ /$test/) {
6784                                         my $val = $1;
6785                                         $val = $6 if ($skip_args ne "");
6786                                         if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6787                                             (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6788                                              ($val =~ /^$Octal$/ && length($val) ne 4))) {
6789                                                 ERROR("NON_OCTAL_PERMISSIONS",
6790                                                       "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6791                                         }
6792                                         if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6793                                                 ERROR("EXPORTED_WORLD_WRITABLE",
6794                                                       "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6795                                         }
6796                                 }
6797                         }
6798                 }
6799
6800 # check for uses of S_<PERMS> that could be octal for readability
6801                 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6802                         my $oval = $1;
6803                         my $octal = perms_to_octal($oval);
6804                         if (WARN("SYMBOLIC_PERMS",
6805                                  "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6806                             $fix) {
6807                                 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6808                         }
6809                 }
6810
6811 # validate content of MODULE_LICENSE against list from include/linux/module.h
6812                 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6813                         my $extracted_string = get_quoted_string($line, $rawline);
6814                         my $valid_licenses = qr{
6815                                                 GPL|
6816                                                 GPL\ v2|
6817                                                 GPL\ and\ additional\ rights|
6818                                                 Dual\ BSD/GPL|
6819                                                 Dual\ MIT/GPL|
6820                                                 Dual\ MPL/GPL|
6821                                                 Proprietary
6822                                         }x;
6823                         if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6824                                 WARN("MODULE_LICENSE",
6825                                      "unknown module license " . $extracted_string . "\n" . $herecurr);
6826                         }
6827                 }
6828
6829 # check for sysctl duplicate constants
6830                 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6831                         WARN("DUPLICATED_SYSCTL_CONST",
6832                                 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6833                 }
6834         }
6835
6836         # If we have no input at all, then there is nothing to report on
6837         # so just keep quiet.
6838         if ($#rawlines == -1) {
6839                 exit(0);
6840         }
6841
6842         # In mailback mode only produce a report in the negative, for
6843         # things that appear to be patches.
6844         if ($mailback && ($clean == 1 || !$is_patch)) {
6845                 exit(0);
6846         }
6847
6848         # This is not a patch, and we are are in 'no-patch' mode so
6849         # just keep quiet.
6850         if (!$chk_patch && !$is_patch) {
6851                 exit(0);
6852         }
6853
6854         if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6855                 ERROR("NOT_UNIFIED_DIFF",
6856                       "Does not appear to be a unified-diff format patch\n");
6857         }
6858         if ($is_patch && $has_commit_log && $chk_signoff) {
6859                 if ($signoff == 0) {
6860                         ERROR("MISSING_SIGN_OFF",
6861                               "Missing Signed-off-by: line(s)\n");
6862                 } elsif (!$authorsignoff) {
6863                         WARN("NO_AUTHOR_SIGN_OFF",
6864                              "Missing Signed-off-by: line by nominal patch author '$author'\n");
6865                 }
6866         }
6867
6868         print report_dump();
6869         if ($summary && !($clean == 1 && $quiet == 1)) {
6870                 print "$filename " if ($summary_file);
6871                 print "total: $cnt_error errors, $cnt_warn warnings, " .
6872                         (($check)? "$cnt_chk checks, " : "") .
6873                         "$cnt_lines lines checked\n";
6874         }
6875
6876         if ($quiet == 0) {
6877                 # If there were any defects found and not already fixing them
6878                 if (!$clean and !$fix) {
6879                         print << "EOM"
6880
6881 NOTE: For some of the reported defects, checkpatch may be able to
6882       mechanically convert to the typical style using --fix or --fix-inplace.
6883 EOM
6884                 }
6885                 # If there were whitespace errors which cleanpatch can fix
6886                 # then suggest that.
6887                 if ($rpt_cleaners) {
6888                         $rpt_cleaners = 0;
6889                         print << "EOM"
6890
6891 NOTE: Whitespace errors detected.
6892       You may wish to use scripts/cleanpatch or scripts/cleanfile
6893 EOM
6894                 }
6895         }
6896
6897         if ($clean == 0 && $fix &&
6898             ("@rawlines" ne "@fixed" ||
6899              $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6900                 my $newfile = $filename;
6901                 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6902                 my $linecount = 0;
6903                 my $f;
6904
6905                 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6906
6907                 open($f, '>', $newfile)
6908                     or die "$P: Can't open $newfile for write\n";
6909                 foreach my $fixed_line (@fixed) {
6910                         $linecount++;
6911                         if ($file) {
6912                                 if ($linecount > 3) {
6913                                         $fixed_line =~ s/^\+//;
6914                                         print $f $fixed_line . "\n";
6915                                 }
6916                         } else {
6917                                 print $f $fixed_line . "\n";
6918                         }
6919                 }
6920                 close($f);
6921
6922                 if (!$quiet) {
6923                         print << "EOM";
6924
6925 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6926
6927 Do _NOT_ trust the results written to this file.
6928 Do _NOT_ submit these changes without inspecting them for correctness.
6929
6930 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6931 No warranties, expressed or implied...
6932 EOM
6933                 }
6934         }
6935
6936         if ($quiet == 0) {
6937                 print "\n";
6938                 if ($clean == 1) {
6939                         print "$vname has no obvious style problems and is ready for submission.\n";
6940                 } else {
6941                         print "$vname has style problems, please review.\n";
6942                 }
6943         }
6944         return $clean;
6945 }