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