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