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