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