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