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