blob: c843c6cc6b8fbcaeee8a8cecd5f92d1826cb5c52 [file] [log] [blame]
Martin Roth387dec82017-09-17 19:20:46 -06001#!/usr/bin/env perl
Martin Roth60915b32018-08-10 21:04:05 -06002# SPDX-License-Identifier: GPL-2.0
3#
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004# (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>
Martin Roth60915b32018-08-10 21:04:05 -06008# (c) 2010-2018 Joe Perches <joe@perches.com>
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01009
10use strict;
Martin Roth387dec82017-09-17 19:20:46 -060011use warnings;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010012use POSIX;
13use File::Basename;
14use Cwd 'abs_path';
Stefan Reinauerc6080c62016-07-29 16:01:40 -070015use Term::ANSIColor qw(:constants);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010016
17my $P = $0;
18my $D = dirname(abs_path($P));
19
20my $V = '0.32';
21
22use Getopt::Long qw(:config no_auto_abbrev);
23
24my $quiet = 0;
Elyes Haouas84ef4fb2022-04-07 09:40:15 +020025my $verbose = 0;
26my %verbose_messages = ();
27my %verbose_emitted = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010028my $tree = 1;
29my $chk_signoff = 1;
30my $chk_patch = 1;
31my $tst_only;
32my $emacs = 0;
33my $terse = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070034my $showfile = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010035my $file = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070036my $git = 0;
37my %git_commits = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010038my $check = 0;
39my $check_orig = 0;
40my $summary = 1;
41my $mailback = 0;
42my $summary_file = 0;
43my $show_types = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070044my $list_types = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010045my $fix = 0;
46my $fix_inplace = 0;
Martin Rothedd591d2017-03-14 10:16:29 -060047my $root = $P; #coreboot
Elyes HAOUAS18ef5202022-01-29 08:27:14 +010048my $gitroot = $ENV{'GIT_DIR'};
49$gitroot = ".git" if !defined($gitroot);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010050my %debug;
51my %camelcase = ();
52my %use_type = ();
53my @use = ();
54my %ignore_type = ();
55my @ignore = ();
Martin Rothedd591d2017-03-14 10:16:29 -060056my @exclude = (); #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010057my $help = 0;
58my $configuration_file = ".checkpatch.conf";
Elyes Haouas0b1a03c2022-04-07 10:13:54 +020059my $max_line_length = 100;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010060my $ignore_perl_version = 0;
61my $minimum_perl_version = 5.10.0;
62my $min_conf_desc_length = 4;
63my $spelling_file = "$D/spelling.txt";
Stefan Reinauerc6080c62016-07-29 16:01:40 -070064my $codespell = 0;
65my $codespellfile = "/usr/share/codespell/dictionary.txt";
Elyes Haouas84ef4fb2022-04-07 09:40:15 +020066my $user_codespellfile = "";
Martin Rothedd591d2017-03-14 10:16:29 -060067my $conststructsfile = "$D/const_structs.checkpatch";
Elyes Haouas46b07e52022-04-07 10:07:34 +020068my $docsfile = "";
69my $typedefsfile;
Martin Roth387dec82017-09-17 19:20:46 -060070my $color = "auto";
Elyes Haouas8f599602022-04-12 12:55:43 +020071my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +010072my $git_command ='git'; # coreboot
Elyes HAOUAS96771bf2022-01-29 07:28:45 +010073my $tabsize = 8;
Elyes Haouasf62a9892022-04-12 12:17:50 +020074my ${CONFIG_} = "CONFIG_";
Martin Roth1f3daea2017-08-30 13:53:58 -060075# For coreboot jenkins
76# If taint mode is enabled, Untaint the path - files must be in /bin, /usr/bin or /usr/local/bin
77if ( ${^TAINT} ) {
78 $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
79 delete @ENV{ 'IFS', 'CDPATH', 'ENV', 'BASH_ENV' };
80}
81
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010082sub help {
83 my ($exitcode) = @_;
84
85 print << "EOM";
86Usage: $P [OPTION]... [FILE]...
87Version: $V
88
89Options:
90 -q, --quiet quiet
Elyes Haouas46b07e52022-04-07 10:07:34 +020091 -v, --verbose verbose mode
Stefan Reinauerc6080c62016-07-29 16:01:40 -070092 --no-tree run without a kernel tree
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010093 --no-signoff do not check for 'Signed-off-by' line
94 --patch treat FILE as patchfile (default)
95 --emacs emacs compile window format
96 --terse one line per report
Stefan Reinauerc6080c62016-07-29 16:01:40 -070097 --showfile emit diffed file position, not input file position
98 -g, --git treat FILE as a single commit or git revision range
99 single git commit with:
100 <rev>
101 <rev>^
102 <rev>~n
103 multiple git commits with:
104 <rev1>..<rev2>
105 <rev1>...<rev2>
106 <rev>-<count>
107 git merges are ignored
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100108 -f, --file treat FILE as regular source file
109 --subjective, --strict enable more subjective tests
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700110 --list-types list the possible message types
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100111 --types TYPE(,TYPE2...) show only these comma separated message types
112 --ignore TYPE(,TYPE2...) ignore various comma separated message types
Martin Rotha3cac872017-03-04 18:17:35 -0700113 --exclude DIR(,DIR22...) exclude directories
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700114 --show-types show the specific message type in the output
Elyes Haouas0b1a03c2022-04-07 10:13:54 +0200115 --max-line-length=n set the maximum line length, (default $max_line_length)
116 if exceeded, warn on patches
117 requires --strict for use with --file
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100118 --min-conf-desc-length=n set the min description length, if shorter, warn
Elyes Haouas41d43f52022-04-12 19:54:37 +0200119 --tab-size=n set the number of spaces for tab (default $tabsize)
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700120 --root=PATH PATH to the kernel tree root
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100121 --no-summary suppress the per-file summary
122 --mailback only produce a report in case of warnings/errors
123 --summary-file include the filename in summary
124 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
125 'values', 'possible', 'type', and 'attr' (default
126 is all off)
127 --test-only=WORD report only warnings/errors containing WORD
128 literally
129 --fix EXPERIMENTAL - may create horrible results
130 If correctable single-line errors exist, create
131 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
132 with potential errors corrected to the preferred
133 checkpatch style
134 --fix-inplace EXPERIMENTAL - may create horrible results
135 Is the same as --fix, but overwrites the input
136 file. It's your fault if there's no backup or git
137 --ignore-perl-version override checking of perl version. expect
138 runtime errors.
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700139 --codespell Use the codespell dictionary for spelling/typos
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200140 (default:$codespellfile)
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700141 --codespellfile Use this codespell dictionary
Martin Roth387dec82017-09-17 19:20:46 -0600142 --typedefsfile Read additional types from this file
143 --color[=WHEN] Use colors 'always', 'never', or only when output
144 is a terminal ('auto'). Default is 'auto'.
Elyes Haouasf62a9892022-04-12 12:17:50 +0200145 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
146 ${CONFIG_})
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100147 -h, --help, --version display this help and exit
148
149When FILE is - read standard input.
150EOM
151
152 exit($exitcode);
153}
154
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700155sub uniq {
156 my %seen;
157 return grep { !$seen{$_}++ } @_;
158}
159
160sub list_types {
161 my ($exitcode) = @_;
162
163 my $count = 0;
164
165 local $/ = undef;
166
167 open(my $script, '<', abs_path($P)) or
168 die "$P: Can't read '$P' $!\n";
169
170 my $text = <$script>;
171 close($script);
172
Elyes Haouas46b07e52022-04-07 10:07:34 +0200173 my %types = ();
Martin Roth387dec82017-09-17 19:20:46 -0600174 # Also catch when type or level is passed through a variable
Elyes Haouas46b07e52022-04-07 10:07:34 +0200175 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
176 if (defined($1)) {
177 if (exists($types{$2})) {
178 $types{$2} .= ",$1" if ($types{$2} ne $1);
179 } else {
180 $types{$2} = $1;
181 }
182 } else {
183 $types{$2} = "UNDETERMINED";
184 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700185 }
Elyes Haouas46b07e52022-04-07 10:07:34 +0200186
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700187 print("#\tMessage type\n\n");
Elyes Haouas46b07e52022-04-07 10:07:34 +0200188 if ($color) {
189 print(" ( Color coding: ");
190 print(RED . "ERROR" . RESET);
191 print(" | ");
192 print(YELLOW . "WARNING" . RESET);
193 print(" | ");
194 print(GREEN . "CHECK" . RESET);
195 print(" | ");
196 print("Multiple levels / Undetermined");
197 print(" )\n\n");
198 }
199
200 foreach my $type (sort keys %types) {
201 my $orig_type = $type;
202 if ($color) {
203 my $level = $types{$type};
204 if ($level eq "ERROR") {
205 $type = RED . $type . RESET;
206 } elsif ($level eq "WARN") {
207 $type = YELLOW . $type . RESET;
208 } elsif ($level eq "CHK") {
209 $type = GREEN . $type . RESET;
210 }
211 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700212 print(++$count . "\t" . $type . "\n");
Elyes Haouas46b07e52022-04-07 10:07:34 +0200213 if ($verbose && exists($verbose_messages{$orig_type})) {
214 my $message = $verbose_messages{$orig_type};
215 $message =~ s/\n/\n\t/g;
216 print("\t" . $message . "\n\n");
217 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700218 }
219
220 exit($exitcode);
221}
222
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100223my $conf = which_conf($configuration_file);
224if (-f $conf) {
225 my @conf_args;
226 open(my $conffile, '<', "$conf")
227 or warn "$P: Can't find a readable $configuration_file file $!\n";
228
229 while (<$conffile>) {
230 my $line = $_;
231
232 $line =~ s/\s*\n?$//g;
233 $line =~ s/^\s*//g;
234 $line =~ s/\s+/ /g;
235
236 next if ($line =~ m/^\s*#/);
237 next if ($line =~ m/^\s*$/);
238
239 my @words = split(" ", $line);
240 foreach my $word (@words) {
241 last if ($word =~ m/^#/);
242 push (@conf_args, $word);
243 }
244 }
245 close($conffile);
246 unshift(@ARGV, @conf_args) if @conf_args;
247}
248
Elyes Haouas46b07e52022-04-07 10:07:34 +0200249sub load_docs {
250 open(my $docs, '<', "$docsfile")
251 or warn "$P: Can't read the documentation file $docsfile $!\n";
252
253 my $type = '';
254 my $desc = '';
255 my $in_desc = 0;
256
257 while (<$docs>) {
258 chomp;
259 my $line = $_;
260 $line =~ s/\s+$//;
261
262 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
263 if ($desc ne '') {
264 $verbose_messages{$type} = trim($desc);
265 }
266 $type = $1;
267 $desc = '';
268 $in_desc = 1;
269 } elsif ($in_desc) {
270 if ($line =~ /^(?:\s{4,}|$)/) {
271 $line =~ s/^\s{4}//;
272 $desc .= $line;
273 $desc .= "\n";
274 } else {
275 $verbose_messages{$type} = trim($desc);
276 $type = '';
277 $desc = '';
278 $in_desc = 0;
279 }
280 }
281 }
282
283 if ($desc ne '') {
284 $verbose_messages{$type} = trim($desc);
285 }
286 close($docs);
287}
288
Martin Roth387dec82017-09-17 19:20:46 -0600289# Perl's Getopt::Long allows options to take optional arguments after a space.
290# Prevent --color by itself from consuming other arguments
291foreach (@ARGV) {
292 if ($_ eq "--color" || $_ eq "-color") {
293 $_ = "--color=$color";
294 }
295}
296
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100297GetOptions(
298 'q|quiet+' => \$quiet,
Elyes Haouas46b07e52022-04-07 10:07:34 +0200299 'v|verbose!' => \$verbose,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100300 'tree!' => \$tree,
301 'signoff!' => \$chk_signoff,
302 'patch!' => \$chk_patch,
303 'emacs!' => \$emacs,
304 'terse!' => \$terse,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700305 'showfile!' => \$showfile,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100306 'f|file!' => \$file,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700307 'g|git!' => \$git,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100308 'subjective!' => \$check,
309 'strict!' => \$check,
310 'ignore=s' => \@ignore,
Martin Rothedd591d2017-03-14 10:16:29 -0600311 'exclude=s' => \@exclude, #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100312 'types=s' => \@use,
313 'show-types!' => \$show_types,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700314 'list-types!' => \$list_types,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100315 'max-line-length=i' => \$max_line_length,
316 'min-conf-desc-length=i' => \$min_conf_desc_length,
Elyes Haouas41d43f52022-04-12 19:54:37 +0200317 'tab-size=i' => \$tabsize,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100318 'root=s' => \$root,
319 'summary!' => \$summary,
320 'mailback!' => \$mailback,
321 'summary-file!' => \$summary_file,
322 'fix!' => \$fix,
323 'fix-inplace!' => \$fix_inplace,
324 'ignore-perl-version!' => \$ignore_perl_version,
325 'debug=s' => \%debug,
326 'test-only=s' => \$tst_only,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700327 'codespell!' => \$codespell,
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200328 'codespellfile=s' => \$user_codespellfile,
Martin Roth387dec82017-09-17 19:20:46 -0600329 'typedefsfile=s' => \$typedefsfile,
330 'color=s' => \$color,
331 'no-color' => \$color, #keep old behaviors of -nocolor
332 'nocolor' => \$color, #keep old behaviors of -nocolor
Elyes Haouasf62a9892022-04-12 12:17:50 +0200333 'kconfig-prefix=s' => \${CONFIG_},
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100334 'h|help' => \$help,
335 'version' => \$help
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200336) or $help = 2;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100337
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200338if ($user_codespellfile) {
339 # Use the user provided codespell file unconditionally
340 $codespellfile = $user_codespellfile;
341} elsif (!(-f $codespellfile)) {
342 # If /usr/share/codespell/dictionary.txt is not present, try to find it
343 # under codespell's install directory: <codespell_root>/data/dictionary.txt
344 if (($codespell || $help) && which("python3") ne "") {
345 my $python_codespell_dict = << "EOF";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100346
Elyes Haouas84ef4fb2022-04-07 09:40:15 +0200347import os.path as op
348import codespell_lib
349codespell_dir = op.dirname(codespell_lib.__file__)
350codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
351print(codespell_file, end='')
352EOF
353
354 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
355 $codespellfile = $codespell_dict if (-f $codespell_dict);
356 }
357}
358
359# $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
360# $help is 2 if invalid option is passed - exitcode: 1
361help($help - 1) if ($help);
362
363die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
364die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
365
366if ($color =~ /^[01]$/) {
367 $color = !$color;
368} elsif ($color =~ /^always$/i) {
369 $color = 1;
370} elsif ($color =~ /^never$/i) {
371 $color = 0;
372} elsif ($color =~ /^auto$/i) {
373 $color = (-t STDOUT);
374} else {
375 die "$P: Invalid color mode: $color\n";
376}
377
378load_docs() if ($verbose);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700379list_types(0) if ($list_types);
380
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100381$fix = 1 if ($fix_inplace);
382$check_orig = $check;
383
384my $exit = 0;
385
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100386my $perl_version_ok = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100387if ($^V && $^V lt $minimum_perl_version) {
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100388 $perl_version_ok = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100389 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +0100390 exit(1) if (!$ignore_perl_version);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100391}
392
Martin Rothedd591d2017-03-14 10:16:29 -0600393#if no filenames are given, push '-' to read patch from stdin
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100394if ($#ARGV < 0) {
Martin Rothedd591d2017-03-14 10:16:29 -0600395 push(@ARGV, '-');
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100396}
397
Elyes Haouas41d43f52022-04-12 19:54:37 +0200398# skip TAB size 1 to avoid additional checks on $tabsize - 1
399die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
400
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100401sub hash_save_array_words {
402 my ($hashRef, $arrayRef) = @_;
403
404 my @array = split(/,/, join(',', @$arrayRef));
405 foreach my $word (@array) {
406 $word =~ s/\s*\n?$//g;
407 $word =~ s/^\s*//g;
408 $word =~ s/\s+/ /g;
409 $word =~ tr/[a-z]/[A-Z]/;
410
411 next if ($word =~ m/^\s*#/);
412 next if ($word =~ m/^\s*$/);
413
414 $hashRef->{$word}++;
415 }
416}
417
418sub hash_show_words {
419 my ($hashRef, $prefix) = @_;
420
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700421 if (keys %$hashRef) {
422 print "\nNOTE: $prefix message types:";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100423 foreach my $word (sort keys %$hashRef) {
424 print " $word";
425 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700426 print "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100427 }
428}
429
430hash_save_array_words(\%ignore_type, \@ignore);
431hash_save_array_words(\%use_type, \@use);
432
433my $dbg_values = 0;
434my $dbg_possible = 0;
435my $dbg_type = 0;
436my $dbg_attr = 0;
437for my $key (keys %debug) {
438 ## no critic
439 eval "\${dbg_$key} = '$debug{$key}';";
440 die "$@" if ($@);
441}
442
443my $rpt_cleaners = 0;
444
445if ($terse) {
446 $emacs = 1;
447 $quiet++;
448}
449
450if ($tree) {
451 if (defined $root) {
452 if (!top_of_kernel_tree($root)) {
453 die "$P: $root: --root does not point at a valid tree\n";
454 }
455 } else {
456 if (top_of_kernel_tree('.')) {
457 $root = '.';
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700458 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100459 top_of_kernel_tree($1)) {
460 $root = $1;
461 }
462 }
463
464 if (!defined $root) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700465 print "Must be run from the top-level dir. of a kernel tree\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100466 exit(2);
467 }
468}
469
470my $emitted_corrupt = 0;
471
472our $Ident = qr{
473 [A-Za-z_][A-Za-z\d_]*
474 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
475 }x;
476our $Storage = qr{extern|static|asmlinkage};
477our $Sparse = qr{
478 __user|
479 __kernel|
480 __force|
481 __iomem|
482 __must_check|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100483 __kprobes|
484 __ref|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200485 __refconst|
486 __refdata|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700487 __rcu|
488 __private
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100489 }x;
490our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
491our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
492our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
493our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
494our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
495
496# Notes to $Attribute:
497# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
498our $Attribute = qr{
499 const|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200500 volatile|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100501 __percpu|
502 __nocast|
503 __safe|
Martin Rothedd591d2017-03-14 10:16:29 -0600504 __bitwise|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100505 __packed__|
506 __packed2__|
507 __naked|
508 __maybe_unused|
509 __always_unused|
510 __noreturn|
511 __used|
512 __cold|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700513 __pure|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100514 __noclone|
515 __deprecated|
516 __read_mostly|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200517 __ro_after_init|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100518 __kprobes|
519 $InitAttribute|
520 ____cacheline_aligned|
521 ____cacheline_aligned_in_smp|
522 ____cacheline_internodealigned_in_smp|
Elyes Haouas26e0b942022-05-22 11:11:11 +0200523 __weak|
524 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100525 }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?};
Elyes Haouas26e0b942022-05-22 11:11:11 +0200536our $String = qr{(?:\b[Lu])?"[X\t]*"};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100537our $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
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700553our $BasicType;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100554our $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
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700577our $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:
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100583 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
584 atomic_t
585)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700586our $typeTypedefs = qr{(?x:
587 $typeC99Typedefs\b|
588 $typeOtherOSTypedefs\b|
589 $typeKernelTypedefs\b
590)};
591
592our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100593
594our $logFunctions = qr{(?x:
Martin Rothedd591d2017-03-14 10:16:29 -0600595 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100596 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
Martin Roth60915b32018-08-10 21:04:05 -0600597 TP_printk|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100598 WARN(?:_RATELIMIT|_ONCE|)|
599 panic|
600 MODULE_[A-Z_]+|
601 seq_vprintf|seq_printf|seq_puts
602)};
603
Elyes Haouasa7b0d382022-05-23 18:33:15 +0200604our $allocFunctions = qr{(?x:
605 (?:(?:devm_)?
606 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
607 kstrdup(?:_const)? |
608 kmemdup(?:_nul)?) |
609 (?:\w+)?alloc_skb(?:_ip_align)? |
610 # dev_alloc_skb/netdev_alloc_skb, et al
611 dma_alloc_coherent
612)};
613
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100614our $signature_tags = qr{(?xi:
615 Signed-off-by:|
616 Acked-by:|
617 Tested-by:|
618 Reviewed-by:|
619 Reported-by:|
620 Suggested-by:|
Michael Niewöhner8cfd3f82022-11-02 18:17:57 +0100621 Co-authored-by:|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100622 To:|
623 Cc:
624)};
625
626our @typeListMisordered = (
627 qr{char\s+(?:un)?signed},
628 qr{int\s+(?:(?:un)?signed\s+)?short\s},
629 qr{int\s+short(?:\s+(?:un)?signed)},
630 qr{short\s+int(?:\s+(?:un)?signed)},
631 qr{(?:un)?signed\s+int\s+short},
632 qr{short\s+(?:un)?signed},
633 qr{long\s+int\s+(?:un)?signed},
634 qr{int\s+long\s+(?:un)?signed},
635 qr{long\s+(?:un)?signed\s+int},
636 qr{int\s+(?:un)?signed\s+long},
637 qr{int\s+(?:un)?signed},
638 qr{int\s+long\s+long\s+(?:un)?signed},
639 qr{long\s+long\s+int\s+(?:un)?signed},
640 qr{long\s+long\s+(?:un)?signed\s+int},
641 qr{long\s+long\s+(?:un)?signed},
642 qr{long\s+(?:un)?signed},
643);
644
645our @typeList = (
646 qr{void},
647 qr{(?:(?:un)?signed\s+)?char},
648 qr{(?:(?:un)?signed\s+)?short\s+int},
649 qr{(?:(?:un)?signed\s+)?short},
650 qr{(?:(?:un)?signed\s+)?int},
651 qr{(?:(?:un)?signed\s+)?long\s+int},
652 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
653 qr{(?:(?:un)?signed\s+)?long\s+long},
654 qr{(?:(?:un)?signed\s+)?long},
655 qr{(?:un)?signed},
656 qr{float},
657 qr{double},
658 qr{bool},
659 qr{struct\s+$Ident},
660 qr{union\s+$Ident},
661 qr{enum\s+$Ident},
662 qr{${Ident}_t},
663 qr{${Ident}_handler},
664 qr{${Ident}_handler_fn},
665 @typeListMisordered,
666);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700667
668our $C90_int_types = qr{(?x:
669 long\s+long\s+int\s+(?:un)?signed|
670 long\s+long\s+(?:un)?signed\s+int|
671 long\s+long\s+(?:un)?signed|
672 (?:(?:un)?signed\s+)?long\s+long\s+int|
673 (?:(?:un)?signed\s+)?long\s+long|
674 int\s+long\s+long\s+(?:un)?signed|
675 int\s+(?:(?:un)?signed\s+)?long\s+long|
676
677 long\s+int\s+(?:un)?signed|
678 long\s+(?:un)?signed\s+int|
679 long\s+(?:un)?signed|
680 (?:(?:un)?signed\s+)?long\s+int|
681 (?:(?:un)?signed\s+)?long|
682 int\s+long\s+(?:un)?signed|
683 int\s+(?:(?:un)?signed\s+)?long|
684
685 int\s+(?:un)?signed|
686 (?:(?:un)?signed\s+)?int
687)};
688
689our @typeListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100690our @typeListWithAttr = (
691 @typeList,
692 qr{struct\s+$InitAttribute\s+$Ident},
693 qr{union\s+$InitAttribute\s+$Ident},
694);
695
696our @modifierList = (
697 qr{fastcall},
698);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700699our @modifierListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100700
701our @mode_permission_funcs = (
702 ["module_param", 3],
703 ["module_param_(?:array|named|string)", 4],
704 ["module_param_array_named", 5],
705 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
706 ["proc_create(?:_data|)", 2],
Martin Rothedd591d2017-03-14 10:16:29 -0600707 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
708 ["IIO_DEV_ATTR_[A-Z_]+", 1],
709 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
710 ["SENSOR_TEMPLATE(?:_2|)", 3],
711 ["__ATTR", 2],
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100712);
713
Elyes Haouas84083a22022-04-12 12:28:32 +0200714my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
715
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100716#Create a search pattern for all these functions to speed up a loop below
717our $mode_perms_search = "";
718foreach my $entry (@mode_permission_funcs) {
719 $mode_perms_search .= '|' if ($mode_perms_search ne "");
720 $mode_perms_search .= $entry->[0];
721}
Martin Roth60915b32018-08-10 21:04:05 -0600722$mode_perms_search = "(?:${mode_perms_search})";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100723
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700724our $mode_perms_world_writable = qr{
725 S_IWUGO |
726 S_IWOTH |
727 S_IRWXUGO |
728 S_IALLUGO |
729 0[0-7][0-7][2367]
730}x;
731
Martin Rothedd591d2017-03-14 10:16:29 -0600732our %mode_permission_string_types = (
733 "S_IRWXU" => 0700,
734 "S_IRUSR" => 0400,
735 "S_IWUSR" => 0200,
736 "S_IXUSR" => 0100,
737 "S_IRWXG" => 0070,
738 "S_IRGRP" => 0040,
739 "S_IWGRP" => 0020,
740 "S_IXGRP" => 0010,
741 "S_IRWXO" => 0007,
742 "S_IROTH" => 0004,
743 "S_IWOTH" => 0002,
744 "S_IXOTH" => 0001,
745 "S_IRWXUGO" => 0777,
746 "S_IRUGO" => 0444,
747 "S_IWUGO" => 0222,
748 "S_IXUGO" => 0111,
749);
750
751#Create a search pattern for all these strings to speed up a loop below
752our $mode_perms_string_search = "";
753foreach my $entry (keys %mode_permission_string_types) {
754 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
755 $mode_perms_string_search .= $entry;
756}
Martin Roth60915b32018-08-10 21:04:05 -0600757our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
758our $multi_mode_perms_string_search = qr{
759 ${single_mode_perms_string_search}
760 (?:\s*\|\s*${single_mode_perms_string_search})*
761}x;
762
763sub perms_to_octal {
764 my ($string) = @_;
765
766 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
767
768 my $val = "";
769 my $oval = "";
770 my $to = 0;
771 my $curpos = 0;
772 my $lastpos = 0;
773 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
774 $curpos = pos($string);
775 my $match = $2;
776 my $omatch = $1;
777 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
778 $lastpos = $curpos;
779 $to |= $mode_permission_string_types{$match};
780 $val .= '\s*\|\s*' if ($val ne "");
781 $val .= $match;
782 $oval .= $omatch;
783 }
784 $oval =~ s/^\s*\|\s*//;
785 $oval =~ s/\s*\|\s*$//;
786 return sprintf("%04o", $to);
787}
Martin Rothedd591d2017-03-14 10:16:29 -0600788
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100789our $allowed_asm_includes = qr{(?x:
790 irq|
791 memory|
792 time|
793 reboot
794)};
795# memory.h: ARM has a custom one
796
797# Load common spelling mistakes and build regular expression list.
798my $misspellings;
799my %spelling_fix;
800
801if (open(my $spelling, '<', $spelling_file)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100802 while (<$spelling>) {
803 my $line = $_;
804
805 $line =~ s/\s*\n?$//g;
806 $line =~ s/^\s*//g;
807
808 next if ($line =~ m/^\s*#/);
809 next if ($line =~ m/^\s*$/);
810
811 my ($suspect, $fix) = split(/\|\|/, $line);
812
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100813 $spelling_fix{$suspect} = $fix;
814 }
815 close($spelling);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100816} else {
817 warn "No typos will be found - file '$spelling_file': $!\n";
818}
819
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700820if ($codespell) {
821 if (open(my $spelling, '<', $codespellfile)) {
822 while (<$spelling>) {
823 my $line = $_;
824
825 $line =~ s/\s*\n?$//g;
826 $line =~ s/^\s*//g;
827
828 next if ($line =~ m/^\s*#/);
829 next if ($line =~ m/^\s*$/);
830 next if ($line =~ m/, disabled/i);
831
832 $line =~ s/,.*$//;
833
834 my ($suspect, $fix) = split(/->/, $line);
835
836 $spelling_fix{$suspect} = $fix;
837 }
838 close($spelling);
839 } else {
840 warn "No codespell typos will be found - file '$codespellfile': $!\n";
841 }
842}
843
844$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
845
Martin Roth387dec82017-09-17 19:20:46 -0600846sub read_words {
847 my ($wordsRef, $file) = @_;
Martin Rothedd591d2017-03-14 10:16:29 -0600848
Martin Roth387dec82017-09-17 19:20:46 -0600849 if (open(my $words, '<', $file)) {
850 while (<$words>) {
851 my $line = $_;
Martin Rothedd591d2017-03-14 10:16:29 -0600852
Martin Roth387dec82017-09-17 19:20:46 -0600853 $line =~ s/\s*\n?$//g;
854 $line =~ s/^\s*//g;
855
856 next if ($line =~ m/^\s*#/);
857 next if ($line =~ m/^\s*$/);
858 if ($line =~ /\s/) {
859 print("$file: '$line' invalid - ignored\n");
860 next;
861 }
862
Elyes Haouas14c49e32022-05-08 10:11:40 +0200863 $$wordsRef .= '|' if (defined $$wordsRef);
Martin Roth387dec82017-09-17 19:20:46 -0600864 $$wordsRef .= $line;
Martin Rothedd591d2017-03-14 10:16:29 -0600865 }
Martin Roth387dec82017-09-17 19:20:46 -0600866 close($file);
867 return 1;
Martin Rothedd591d2017-03-14 10:16:29 -0600868 }
Martin Roth387dec82017-09-17 19:20:46 -0600869
870 return 0;
Martin Rothedd591d2017-03-14 10:16:29 -0600871}
872
Elyes Haouas43529c82022-04-12 13:19:50 +0200873my $const_structs;
874if (show_type("CONST_STRUCT")) {
875 read_words(\$const_structs, $conststructsfile)
876 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
877}
Martin Roth387dec82017-09-17 19:20:46 -0600878
Elyes Haouas26e0b942022-05-22 11:11:11 +0200879if (defined($typedefsfile)) {
880 my $typeOtherTypedefs;
Martin Roth387dec82017-09-17 19:20:46 -0600881 read_words(\$typeOtherTypedefs, $typedefsfile)
882 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
Elyes Haouas26e0b942022-05-22 11:11:11 +0200883 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
Martin Roth387dec82017-09-17 19:20:46 -0600884}
Martin Roth387dec82017-09-17 19:20:46 -0600885
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100886sub build_types {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700887 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
888 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100889 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
890 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
891 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700892 $BasicType = qr{
893 (?:$typeTypedefs\b)|
894 (?:${all}\b)
895 }x;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100896 $NonptrType = qr{
897 (?:$Modifier\s+|const\s+)*
898 (?:
899 (?:typeof|__typeof__)\s*\([^\)]*\)|
900 (?:$typeTypedefs\b)|
901 (?:${all}\b)
902 )
903 (?:\s+$Modifier|\s+const)*
904 }x;
905 $NonptrTypeMisordered = qr{
906 (?:$Modifier\s+|const\s+)*
907 (?:
908 (?:${Misordered}\b)
909 )
910 (?:\s+$Modifier|\s+const)*
911 }x;
912 $NonptrTypeWithAttr = qr{
913 (?:$Modifier\s+|const\s+)*
914 (?:
915 (?:typeof|__typeof__)\s*\([^\)]*\)|
916 (?:$typeTypedefs\b)|
917 (?:${allWithAttr}\b)
918 )
919 (?:\s+$Modifier|\s+const)*
920 }x;
921 $Type = qr{
922 $NonptrType
Elyes Haouas26e0b942022-05-22 11:11:11 +0200923 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100924 (?:\s+$Inline|\s+$Modifier)*
925 }x;
926 $TypeMisordered = qr{
927 $NonptrTypeMisordered
Elyes Haouas26e0b942022-05-22 11:11:11 +0200928 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100929 (?:\s+$Inline|\s+$Modifier)*
930 }x;
931 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
932 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
933}
934build_types();
935
936our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
937
938# Using $balanced_parens, $LvalOrFunc, or $FuncArg
939# requires at least perl version v5.10.0
940# Any use must be runtime checked with $^V
941
942our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
943our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700944our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100945
946our $declaration_macros = qr{(?x:
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700947 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
Martin Roth387dec82017-09-17 19:20:46 -0600948 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
Elyes Haouasd27b2e82022-09-05 11:50:48 +0200949 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
950 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100951)};
952
Elyes Haouas84083a22022-04-12 12:28:32 +0200953our %allow_repeated_words = (
954 add => '',
955 added => '',
956 bad => '',
957 be => '',
958);
959
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100960sub deparenthesize {
961 my ($string) = @_;
962 return "" if (!defined($string));
963
964 while ($string =~ /^\s*\(.*\)\s*$/) {
965 $string =~ s@^\s*\(\s*@@;
966 $string =~ s@\s*\)\s*$@@;
967 }
968
969 $string =~ s@\s+@ @g;
970
971 return $string;
972}
973
974sub seed_camelcase_file {
975 my ($file) = @_;
976
977 return if (!(-f $file));
978
979 local $/;
980
981 open(my $include_file, '<', "$file")
982 or warn "$P: Can't read '$file' $!\n";
983 my $text = <$include_file>;
984 close($include_file);
985
986 my @lines = split('\n', $text);
987
988 foreach my $line (@lines) {
989 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
990 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
991 $camelcase{$1} = 1;
992 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
993 $camelcase{$1} = 1;
994 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
995 $camelcase{$1} = 1;
996 }
997 }
998}
999
Martin Rothedd591d2017-03-14 10:16:29 -06001000sub is_maintained_obsolete {
1001 my ($filename) = @_;
1002
1003 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1004
1005 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1006
1007 return $status =~ /obsolete/i;
1008}
1009
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001010my $camelcase_seeded = 0;
1011sub seed_camelcase_includes {
1012 return if ($camelcase_seeded);
1013
1014 my $files;
1015 my $camelcase_cache = "";
1016 my @include_files = ();
1017
1018 $camelcase_seeded = 1;
1019
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001020 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001021 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001022 chomp $git_last_include_commit;
1023 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1024 } else {
1025 my $last_mod_date = 0;
1026 $files = `find $root/include -name "*.h"`;
1027 @include_files = split('\n', $files);
1028 foreach my $file (@include_files) {
1029 my $date = POSIX::strftime("%Y%m%d%H%M",
1030 localtime((stat $file)[9]));
1031 $last_mod_date = $date if ($last_mod_date < $date);
1032 }
1033 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1034 }
1035
1036 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1037 open(my $camelcase_file, '<', "$camelcase_cache")
1038 or warn "$P: Can't read '$camelcase_cache' $!\n";
1039 while (<$camelcase_file>) {
1040 chomp;
1041 $camelcase{$_} = 1;
1042 }
1043 close($camelcase_file);
1044
1045 return;
1046 }
1047
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001048 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001049 $files = `${git_command} ls-files "include/*.h"`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001050 @include_files = split('\n', $files);
1051 }
1052
1053 foreach my $file (@include_files) {
1054 seed_camelcase_file($file);
1055 }
1056
1057 if ($camelcase_cache ne "") {
1058 unlink glob ".checkpatch-camelcase.*";
1059 open(my $camelcase_file, '>', "$camelcase_cache")
1060 or warn "$P: Can't write '$camelcase_cache' $!\n";
1061 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1062 print $camelcase_file ("$_\n");
1063 }
1064 close($camelcase_file);
1065 }
1066}
1067
1068sub git_commit_info {
1069 my ($commit, $id, $desc) = @_;
1070
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001071 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001072
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001073 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001074 $output =~ s/^\s*//gm;
1075 my @lines = split("\n", $output);
1076
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001077 return ($id, $desc) if ($#lines < 0);
1078
Elyes Haouas26e0b942022-05-22 11:11:11 +02001079 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001080# Maybe one day convert this block of bash into something that returns
1081# all matching commit ids, but it's very slow...
1082#
1083# echo "checking commits $1..."
1084# git rev-list --remotes | grep -i "^$1" |
1085# while read line ; do
1086# git log --format='%H %s' -1 $line |
1087# echo "commit $(cut -c 1-12,41-)"
1088# done
Elyes Haouas26e0b942022-05-22 11:11:11 +02001089 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1090 $lines[0] =~ /^fatal: bad object $commit/) {
Martin Roth387dec82017-09-17 19:20:46 -06001091 $id = undef;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001092 } else {
1093 $id = substr($lines[0], 0, 12);
1094 $desc = substr($lines[0], 41);
1095 }
1096
1097 return ($id, $desc);
1098}
1099
1100$chk_signoff = 0 if ($file);
1101
1102my @rawlines = ();
1103my @lines = ();
1104my @fixed = ();
1105my @fixed_inserted = ();
1106my @fixed_deleted = ();
1107my $fixlinenr = -1;
1108
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001109# If input is git commits, extract all commits from the commit expressions.
1110# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001111die "$P: No git repository found\n" if ($git && !-e "$gitroot");
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001112
1113if ($git) {
1114 my @commits = ();
1115 foreach my $commit_expr (@ARGV) {
1116 my $git_range;
1117 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1118 $git_range = "-$2 $1";
1119 } elsif ($commit_expr =~ m/\.\./) {
1120 $git_range = "$commit_expr";
1121 } else {
1122 $git_range = "-1 $commit_expr";
1123 }
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001124 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001125 foreach my $line (split(/\n/, $lines)) {
1126 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1127 next if (!defined($1) || !defined($2));
1128 my $sha1 = $1;
1129 my $subject = $2;
1130 unshift(@commits, $sha1);
1131 $git_commits{$sha1} = $subject;
1132 }
1133 }
1134 die "$P: no git commits after extraction!\n" if (@commits == 0);
1135 @ARGV = @commits;
1136}
1137
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001138my $vname;
Elyes Haouas8f599602022-04-12 12:55:43 +02001139$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
Martin Roth387dec82017-09-17 19:20:46 -06001140for my $filename (@ARGV) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001141 my $FILE;
Martin Rotha9868b22018-01-27 17:31:42 -07001142
1143 # coreboot: Mark filename as untainted
1144 $filename =~ /^(.*)$/s or die; $filename = $1;
1145
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001146 if ($git) {
1147 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1148 die "$P: $filename: git format-patch failed - $!\n";
1149 } elsif ($file) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001150 open($FILE, '-|', "diff -u /dev/null $filename") ||
1151 die "$P: $filename: diff failed - $!\n";
1152 } elsif ($filename eq '-') {
1153 open($FILE, '<&STDIN');
1154 } else {
1155 open($FILE, '<', "$filename") ||
1156 die "$P: $filename: open failed - $!\n";
1157 }
1158 if ($filename eq '-') {
1159 $vname = 'Your patch';
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001160 } elsif ($git) {
1161 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001162 } else {
1163 $vname = $filename;
1164 }
1165 while (<$FILE>) {
1166 chomp;
1167 push(@rawlines, $_);
1168 }
1169 close($FILE);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001170
1171 if ($#ARGV > 0 && $quiet == 0) {
1172 print '-' x length($vname) . "\n";
1173 print "$vname\n";
1174 print '-' x length($vname) . "\n";
1175 }
1176
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001177 if (!process($filename)) {
1178 $exit = 1;
1179 }
1180 @rawlines = ();
1181 @lines = ();
1182 @fixed = ();
1183 @fixed_inserted = ();
1184 @fixed_deleted = ();
1185 $fixlinenr = -1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001186 @modifierListFile = ();
1187 @typeListFile = ();
1188 build_types();
1189}
1190
1191if (!$quiet) {
1192 hash_show_words(\%use_type, "Used");
1193 hash_show_words(\%ignore_type, "Ignored");
1194
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001195 if (!$perl_version_ok) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001196 print << "EOM"
1197
1198NOTE: perl $^V is not modern enough to detect all possible issues.
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001199 An upgrade to at least perl $minimum_perl_version is suggested.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001200EOM
1201 }
1202 if ($exit) {
1203 print << "EOM"
1204
1205NOTE: If any of the errors are false positives, please report
1206 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1207EOM
1208 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001209}
1210
1211exit($exit);
1212
1213sub top_of_kernel_tree {
1214 my ($root) = @_;
1215
1216 my @tree_check = (
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001217 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1218 "README", "Documentation", "arch", "include", "drivers",
1219 "fs", "init", "ipc", "kernel", "lib", "scripts",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001220 );
1221
1222 foreach my $check (@tree_check) {
1223 if (! -e $root . '/' . $check) {
1224 return 0;
1225 }
1226 }
1227 return 1;
1228}
1229
1230sub parse_email {
1231 my ($formatted_email) = @_;
1232
1233 my $name = "";
1234 my $address = "";
1235 my $comment = "";
1236
1237 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1238 $name = $1;
1239 $address = $2;
1240 $comment = $3 if defined $3;
1241 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1242 $address = $1;
1243 $comment = $2 if defined $2;
1244 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1245 $address = $1;
1246 $comment = $2 if defined $2;
Martin Roth60915b32018-08-10 21:04:05 -06001247 $formatted_email =~ s/\Q$address\E.*$//;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001248 $name = $formatted_email;
1249 $name = trim($name);
1250 $name =~ s/^\"|\"$//g;
1251 # If there's a name left after stripping spaces and
1252 # leading quotes, and the address doesn't have both
1253 # leading and trailing angle brackets, the address
1254 # is invalid. ie:
1255 # "joe smith joe@smith.com" bad
1256 # "joe smith <joe@smith.com" bad
1257 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1258 $name = "";
1259 $address = "";
1260 $comment = "";
1261 }
1262 }
1263
1264 $name = trim($name);
1265 $name =~ s/^\"|\"$//g;
1266 $address = trim($address);
1267 $address =~ s/^\<|\>$//g;
1268
1269 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1270 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1271 $name = "\"$name\"";
1272 }
1273
1274 return ($name, $address, $comment);
1275}
1276
1277sub format_email {
1278 my ($name, $address) = @_;
1279
1280 my $formatted_email;
1281
1282 $name = trim($name);
1283 $name =~ s/^\"|\"$//g;
1284 $address = trim($address);
1285
1286 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1287 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1288 $name = "\"$name\"";
1289 }
1290
1291 if ("$name" eq "") {
1292 $formatted_email = "$address";
1293 } else {
1294 $formatted_email = "$name <$address>";
1295 }
1296
1297 return $formatted_email;
1298}
1299
1300sub which {
1301 my ($bin) = @_;
1302
1303 foreach my $path (split(/:/, $ENV{PATH})) {
1304 if (-e "$path/$bin") {
1305 return "$path/$bin";
1306 }
1307 }
1308
1309 return "";
1310}
1311
1312sub which_conf {
1313 my ($conf) = @_;
1314
1315 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1316 if (-e "$path/$conf") {
1317 return "$path/$conf";
1318 }
1319 }
1320
1321 return "";
1322}
1323
1324sub expand_tabs {
1325 my ($str) = @_;
1326
1327 my $res = '';
1328 my $n = 0;
1329 for my $c (split(//, $str)) {
1330 if ($c eq "\t") {
1331 $res .= ' ';
1332 $n++;
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01001333 for (; ($n % $tabsize) != 0; $n++) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001334 $res .= ' ';
1335 }
1336 next;
1337 }
1338 $res .= $c;
1339 $n++;
1340 }
1341
1342 return $res;
1343}
1344sub copy_spacing {
1345 (my $res = shift) =~ tr/\t/ /c;
1346 return $res;
1347}
1348
1349sub line_stats {
1350 my ($line) = @_;
1351
Elyes Haouas26e0b942022-05-22 11:11:11 +02001352 # Drop the diff line leader and expand tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001353 $line =~ s/^.//;
Julius Werner218906d2021-03-25 21:12:49 -07001354
1355 # Treat labels like whitespace when counting indentation
1356 $line =~ s/^( ?$Ident:)/" " x length($1)/e;
1357
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001358 $line = expand_tabs($line);
1359
1360 # Pick the indent from the front of the line.
1361 my ($white) = ($line =~ /^(\s*)/);
1362
1363 return (length($line), length($white));
1364}
1365
1366my $sanitise_quote = '';
1367
1368sub sanitise_line_reset {
1369 my ($in_comment) = @_;
1370
1371 if ($in_comment) {
1372 $sanitise_quote = '*/';
1373 } else {
1374 $sanitise_quote = '';
1375 }
1376}
1377sub sanitise_line {
1378 my ($line) = @_;
1379
1380 my $res = '';
1381 my $l = '';
1382
1383 my $qlen = 0;
1384 my $off = 0;
1385 my $c;
1386
1387 # Always copy over the diff marker.
1388 $res = substr($line, 0, 1);
1389
1390 for ($off = 1; $off < length($line); $off++) {
1391 $c = substr($line, $off, 1);
1392
Martin Roth60915b32018-08-10 21:04:05 -06001393 # Comments we are whacking completely including the begin
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001394 # and end, all to $;.
1395 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1396 $sanitise_quote = '*/';
1397
1398 substr($res, $off, 2, "$;$;");
1399 $off++;
1400 next;
1401 }
1402 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1403 $sanitise_quote = '';
1404 substr($res, $off, 2, "$;$;");
1405 $off++;
1406 next;
1407 }
1408 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1409 $sanitise_quote = '//';
1410
1411 substr($res, $off, 2, $sanitise_quote);
1412 $off++;
1413 next;
1414 }
1415
1416 # A \ in a string means ignore the next character.
1417 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1418 $c eq "\\") {
1419 substr($res, $off, 2, 'XX');
1420 $off++;
1421 next;
1422 }
1423 # Regular quotes.
1424 if ($c eq "'" || $c eq '"') {
1425 if ($sanitise_quote eq '') {
1426 $sanitise_quote = $c;
1427
1428 substr($res, $off, 1, $c);
1429 next;
1430 } elsif ($sanitise_quote eq $c) {
1431 $sanitise_quote = '';
1432 }
1433 }
1434
1435 #print "c<$c> SQ<$sanitise_quote>\n";
1436 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1437 substr($res, $off, 1, $;);
1438 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1439 substr($res, $off, 1, $;);
1440 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1441 substr($res, $off, 1, 'X');
1442 } else {
1443 substr($res, $off, 1, $c);
1444 }
1445 }
1446
1447 if ($sanitise_quote eq '//') {
1448 $sanitise_quote = '';
1449 }
1450
1451 # The pathname on a #include may be surrounded by '<' and '>'.
1452 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1453 my $clean = 'X' x length($1);
1454 $res =~ s@\<.*\>@<$clean>@;
1455
1456 # The whole of a #error is a string.
1457 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1458 my $clean = 'X' x length($1);
1459 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1460 }
1461
Martin Rothedd591d2017-03-14 10:16:29 -06001462 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1463 my $match = $1;
1464 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1465 }
1466
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001467 return $res;
1468}
1469
1470sub get_quoted_string {
1471 my ($line, $rawline) = @_;
1472
Martin Roth60915b32018-08-10 21:04:05 -06001473 return "" if (!defined($line) || !defined($rawline));
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001474 return "" if ($line !~ m/($String)/g);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001475 return substr($rawline, $-[0], $+[0] - $-[0]);
1476}
1477
1478sub ctx_statement_block {
1479 my ($linenr, $remain, $off) = @_;
1480 my $line = $linenr - 1;
1481 my $blk = '';
1482 my $soff = $off;
1483 my $coff = $off - 1;
1484 my $coff_set = 0;
1485
1486 my $loff = 0;
1487
1488 my $type = '';
1489 my $level = 0;
Julius Werner218906d2021-03-25 21:12:49 -07001490 my @stack = (['', $level]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001491 my $p;
1492 my $c;
1493 my $len = 0;
1494
1495 my $remainder;
1496 while (1) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001497 #warn "CSB: blk<$blk> remain<$remain>\n";
1498 # If we are about to drop off the end, pull in more
1499 # context.
1500 if ($off >= $len) {
1501 for (; $remain > 0; $line++) {
1502 last if (!defined $lines[$line]);
1503 next if ($lines[$line] =~ /^-/);
1504 $remain--;
1505 $loff = $len;
1506 $blk .= $lines[$line] . "\n";
1507 $len = length($blk);
1508 $line++;
1509 last;
1510 }
1511 # Bail if there is no further context.
1512 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1513 if ($off >= $len) {
1514 last;
1515 }
1516 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1517 $level++;
1518 $type = '#';
1519 }
1520 }
1521 $p = $c;
1522 $c = substr($blk, $off, 1);
1523 $remainder = substr($blk, $off);
1524
1525 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1526
1527 # Handle nested #if/#else.
1528 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1529 push(@stack, [ $type, $level ]);
Julius Werner218906d2021-03-25 21:12:49 -07001530 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/ && $#stack > 0) {
1531 ($type, $level) = @{$stack[$#stack]};
1532 } elsif ($remainder =~ /^#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001533 ($type, $level) = @{pop(@stack)};
1534 }
1535
1536 # Statement ends at the ';' or a close '}' at the
1537 # outermost level.
1538 if ($level == 0 && $c eq ';') {
1539 last;
1540 }
1541
1542 # An else is really a conditional as long as its not else if
1543 if ($level == 0 && $coff_set == 0 &&
1544 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1545 $remainder =~ /^(else)(?:\s|{)/ &&
1546 $remainder !~ /^else\s+if\b/) {
1547 $coff = $off + length($1) - 1;
1548 $coff_set = 1;
1549 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1550 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1551 }
1552
1553 if (($type eq '' || $type eq '(') && $c eq '(') {
1554 $level++;
1555 $type = '(';
1556 }
1557 if ($type eq '(' && $c eq ')') {
1558 $level--;
1559 $type = ($level != 0)? '(' : '';
1560
1561 if ($level == 0 && $coff < $soff) {
1562 $coff = $off;
1563 $coff_set = 1;
1564 #warn "CSB: mark coff<$coff>\n";
1565 }
1566 }
1567 if (($type eq '' || $type eq '{') && $c eq '{') {
1568 $level++;
1569 $type = '{';
1570 }
1571 if ($type eq '{' && $c eq '}') {
1572 $level--;
1573 $type = ($level != 0)? '{' : '';
1574
1575 if ($level == 0) {
1576 if (substr($blk, $off + 1, 1) eq ';') {
1577 $off++;
1578 }
1579 last;
1580 }
1581 }
1582 # Preprocessor commands end at the newline unless escaped.
1583 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1584 $level--;
1585 $type = '';
1586 $off++;
1587 last;
1588 }
1589 $off++;
1590 }
1591 # We are truly at the end, so shuffle to the next line.
1592 if ($off == $len) {
1593 $loff = $len + 1;
1594 $line++;
1595 $remain--;
1596 }
1597
1598 my $statement = substr($blk, $soff, $off - $soff + 1);
1599 my $condition = substr($blk, $soff, $coff - $soff + 1);
1600
1601 #warn "STATEMENT<$statement>\n";
1602 #warn "CONDITION<$condition>\n";
1603
1604 #print "coff<$coff> soff<$off> loff<$loff>\n";
1605
1606 return ($statement, $condition,
1607 $line, $remain + 1, $off - $loff + 1, $level);
1608}
1609
1610sub statement_lines {
1611 my ($stmt) = @_;
1612
1613 # Strip the diff line prefixes and rip blank lines at start and end.
1614 $stmt =~ s/(^|\n)./$1/g;
1615 $stmt =~ s/^\s*//;
1616 $stmt =~ s/\s*$//;
1617
1618 my @stmt_lines = ($stmt =~ /\n/g);
1619
1620 return $#stmt_lines + 2;
1621}
1622
1623sub statement_rawlines {
1624 my ($stmt) = @_;
1625
1626 my @stmt_lines = ($stmt =~ /\n/g);
1627
1628 return $#stmt_lines + 2;
1629}
1630
1631sub statement_block_size {
1632 my ($stmt) = @_;
1633
1634 $stmt =~ s/(^|\n)./$1/g;
1635 $stmt =~ s/^\s*{//;
1636 $stmt =~ s/}\s*$//;
1637 $stmt =~ s/^\s*//;
1638 $stmt =~ s/\s*$//;
1639
1640 my @stmt_lines = ($stmt =~ /\n/g);
1641 my @stmt_statements = ($stmt =~ /;/g);
1642
1643 my $stmt_lines = $#stmt_lines + 2;
1644 my $stmt_statements = $#stmt_statements + 1;
1645
1646 if ($stmt_lines > $stmt_statements) {
1647 return $stmt_lines;
1648 } else {
1649 return $stmt_statements;
1650 }
1651}
1652
1653sub ctx_statement_full {
1654 my ($linenr, $remain, $off) = @_;
1655 my ($statement, $condition, $level);
1656
1657 my (@chunks);
1658
1659 # Grab the first conditional/block pair.
1660 ($statement, $condition, $linenr, $remain, $off, $level) =
1661 ctx_statement_block($linenr, $remain, $off);
1662 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1663 push(@chunks, [ $condition, $statement ]);
1664 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1665 return ($level, $linenr, @chunks);
1666 }
1667
1668 # Pull in the following conditional/block pairs and see if they
1669 # could continue the statement.
1670 for (;;) {
1671 ($statement, $condition, $linenr, $remain, $off, $level) =
1672 ctx_statement_block($linenr, $remain, $off);
1673 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1674 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1675 #print "C: push\n";
1676 push(@chunks, [ $condition, $statement ]);
1677 }
1678
1679 return ($level, $linenr, @chunks);
1680}
1681
1682sub ctx_block_get {
1683 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1684 my $line;
1685 my $start = $linenr - 1;
1686 my $blk = '';
1687 my @o;
1688 my @c;
1689 my @res = ();
1690
1691 my $level = 0;
1692 my @stack = ($level);
1693 for ($line = $start; $remain > 0; $line++) {
1694 next if ($rawlines[$line] =~ /^-/);
1695 $remain--;
1696
1697 $blk .= $rawlines[$line];
1698
1699 # Handle nested #if/#else.
1700 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1701 push(@stack, $level);
Julius Werner218906d2021-03-25 21:12:49 -07001702 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/ && $#stack > 0) {
1703 $level = $stack[$#stack];
1704 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001705 $level = pop(@stack);
1706 }
1707
1708 foreach my $c (split(//, $lines[$line])) {
1709 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1710 if ($off > 0) {
1711 $off--;
1712 next;
1713 }
1714
1715 if ($c eq $close && $level > 0) {
1716 $level--;
1717 last if ($level == 0);
1718 } elsif ($c eq $open) {
1719 $level++;
1720 }
1721 }
1722
1723 if (!$outer || $level <= 1) {
1724 push(@res, $rawlines[$line]);
1725 }
1726
1727 last if ($level == 0);
1728 }
1729
1730 return ($level, @res);
1731}
1732sub ctx_block_outer {
1733 my ($linenr, $remain) = @_;
1734
1735 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1736 return @r;
1737}
1738sub ctx_block {
1739 my ($linenr, $remain) = @_;
1740
1741 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1742 return @r;
1743}
1744sub ctx_statement {
1745 my ($linenr, $remain, $off) = @_;
1746
1747 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1748 return @r;
1749}
1750sub ctx_block_level {
1751 my ($linenr, $remain) = @_;
1752
1753 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1754}
1755sub ctx_statement_level {
1756 my ($linenr, $remain, $off) = @_;
1757
1758 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1759}
1760
1761sub ctx_locate_comment {
1762 my ($first_line, $end_line) = @_;
1763
Elyes Haouas26e0b942022-05-22 11:11:11 +02001764 # If c99 comment on the current line, or the line before or after
1765 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1766 return $current_comment if (defined $current_comment);
1767 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1768 return $current_comment if (defined $current_comment);
1769 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1770 return $current_comment if (defined $current_comment);
1771
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001772 # Catch a comment on the end of the line itself.
Elyes Haouas26e0b942022-05-22 11:11:11 +02001773 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001774 return $current_comment if (defined $current_comment);
1775
1776 # Look through the context and try and figure out if there is a
1777 # comment.
1778 my $in_comment = 0;
1779 $current_comment = '';
1780 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1781 my $line = $rawlines[$linenr - 1];
1782 #warn " $line\n";
1783 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1784 $in_comment = 1;
1785 }
1786 if ($line =~ m@/\*@) {
1787 $in_comment = 1;
1788 }
1789 if (!$in_comment && $current_comment ne '') {
1790 $current_comment = '';
1791 }
1792 $current_comment .= $line . "\n" if ($in_comment);
1793 if ($line =~ m@\*/@) {
1794 $in_comment = 0;
1795 }
1796 }
1797
1798 chomp($current_comment);
1799 return($current_comment);
1800}
1801sub ctx_has_comment {
1802 my ($first_line, $end_line) = @_;
1803 my $cmt = ctx_locate_comment($first_line, $end_line);
1804
1805 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1806 ##print "CMMT: $cmt\n";
1807
1808 return ($cmt ne '');
1809}
1810
1811sub raw_line {
1812 my ($linenr, $cnt) = @_;
1813
1814 my $offset = $linenr - 1;
1815 $cnt++;
1816
1817 my $line;
1818 while ($cnt) {
1819 $line = $rawlines[$offset++];
1820 next if (defined($line) && $line =~ /^-/);
1821 $cnt--;
1822 }
1823
Martin Roth96a48f12016-08-29 15:30:23 -06001824 # coreboot: This probably shouldn't happen, but it does.
1825 # Return a defined value so we don't get an error.
1826 if (defined $line) {
1827 return $line;
1828 } else {
1829 return "";
1830 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001831}
1832
Martin Roth60915b32018-08-10 21:04:05 -06001833sub get_stat_real {
1834 my ($linenr, $lc) = @_;
1835
1836 my $stat_real = raw_line($linenr, 0);
1837 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1838 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1839 }
1840
1841 return $stat_real;
1842}
1843
1844sub get_stat_here {
1845 my ($linenr, $cnt, $here) = @_;
1846
1847 my $herectx = $here . "\n";
1848 for (my $n = 0; $n < $cnt; $n++) {
1849 $herectx .= raw_line($linenr, $n) . "\n";
1850 }
1851
1852 return $herectx;
1853}
1854
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001855sub cat_vet {
1856 my ($vet) = @_;
1857 my ($res, $coded);
1858
1859 $res = '';
1860 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1861 $res .= $1;
1862 if ($2 ne '') {
1863 $coded = sprintf("^%c", unpack('C', $2) + 64);
1864 $res .= $coded;
1865 }
1866 }
1867 $res =~ s/$/\$/;
1868
1869 return $res;
1870}
1871
1872my $av_preprocessor = 0;
1873my $av_pending;
1874my @av_paren_type;
1875my $av_pend_colon;
1876
1877sub annotate_reset {
1878 $av_preprocessor = 0;
1879 $av_pending = '_';
1880 @av_paren_type = ('E');
1881 $av_pend_colon = 'O';
1882}
1883
1884sub annotate_values {
1885 my ($stream, $type) = @_;
1886
1887 my $res;
1888 my $var = '_' x length($stream);
1889 my $cur = $stream;
1890
1891 print "$stream\n" if ($dbg_values > 1);
1892
1893 while (length($cur)) {
1894 @av_paren_type = ('E') if ($#av_paren_type < 0);
1895 print " <" . join('', @av_paren_type) .
1896 "> <$type> <$av_pending>" if ($dbg_values > 1);
1897 if ($cur =~ /^(\s+)/o) {
1898 print "WS($1)\n" if ($dbg_values > 1);
1899 if ($1 =~ /\n/ && $av_preprocessor) {
1900 $type = pop(@av_paren_type);
1901 $av_preprocessor = 0;
1902 }
1903
1904 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1905 print "CAST($1)\n" if ($dbg_values > 1);
1906 push(@av_paren_type, $type);
1907 $type = 'c';
1908
1909 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1910 print "DECLARE($1)\n" if ($dbg_values > 1);
1911 $type = 'T';
1912
1913 } elsif ($cur =~ /^($Modifier)\s*/) {
1914 print "MODIFIER($1)\n" if ($dbg_values > 1);
1915 $type = 'T';
1916
1917 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1918 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1919 $av_preprocessor = 1;
1920 push(@av_paren_type, $type);
1921 if ($2 ne '') {
1922 $av_pending = 'N';
1923 }
1924 $type = 'E';
1925
1926 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1927 print "UNDEF($1)\n" if ($dbg_values > 1);
1928 $av_preprocessor = 1;
1929 push(@av_paren_type, $type);
1930
1931 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1932 print "PRE_START($1)\n" if ($dbg_values > 1);
1933 $av_preprocessor = 1;
1934
1935 push(@av_paren_type, $type);
1936 push(@av_paren_type, $type);
1937 $type = 'E';
1938
1939 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1940 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1941 $av_preprocessor = 1;
1942
1943 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1944
1945 $type = 'E';
1946
1947 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1948 print "PRE_END($1)\n" if ($dbg_values > 1);
1949
1950 $av_preprocessor = 1;
1951
1952 # Assume all arms of the conditional end as this
1953 # one does, and continue as if the #endif was not here.
1954 pop(@av_paren_type);
1955 push(@av_paren_type, $type);
1956 $type = 'E';
1957
1958 } elsif ($cur =~ /^(\\\n)/o) {
1959 print "PRECONT($1)\n" if ($dbg_values > 1);
1960
1961 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1962 print "ATTR($1)\n" if ($dbg_values > 1);
1963 $av_pending = $type;
1964 $type = 'N';
1965
1966 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1967 print "SIZEOF($1)\n" if ($dbg_values > 1);
1968 if (defined $2) {
1969 $av_pending = 'V';
1970 }
1971 $type = 'N';
1972
1973 } elsif ($cur =~ /^(if|while|for)\b/o) {
1974 print "COND($1)\n" if ($dbg_values > 1);
1975 $av_pending = 'E';
1976 $type = 'N';
1977
1978 } elsif ($cur =~/^(case)/o) {
1979 print "CASE($1)\n" if ($dbg_values > 1);
1980 $av_pend_colon = 'C';
1981 $type = 'N';
1982
1983 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1984 print "KEYWORD($1)\n" if ($dbg_values > 1);
1985 $type = 'N';
1986
1987 } elsif ($cur =~ /^(\()/o) {
1988 print "PAREN('$1')\n" if ($dbg_values > 1);
1989 push(@av_paren_type, $av_pending);
1990 $av_pending = '_';
1991 $type = 'N';
1992
1993 } elsif ($cur =~ /^(\))/o) {
1994 my $new_type = pop(@av_paren_type);
1995 if ($new_type ne '_') {
1996 $type = $new_type;
1997 print "PAREN('$1') -> $type\n"
1998 if ($dbg_values > 1);
1999 } else {
2000 print "PAREN('$1')\n" if ($dbg_values > 1);
2001 }
2002
2003 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2004 print "FUNC($1)\n" if ($dbg_values > 1);
2005 $type = 'V';
2006 $av_pending = 'V';
2007
2008 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2009 if (defined $2 && $type eq 'C' || $type eq 'T') {
2010 $av_pend_colon = 'B';
2011 } elsif ($type eq 'E') {
2012 $av_pend_colon = 'L';
2013 }
2014 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2015 $type = 'V';
2016
2017 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2018 print "IDENT($1)\n" if ($dbg_values > 1);
2019 $type = 'V';
2020
2021 } elsif ($cur =~ /^($Assignment)/o) {
2022 print "ASSIGN($1)\n" if ($dbg_values > 1);
2023 $type = 'N';
2024
2025 } elsif ($cur =~/^(;|{|})/) {
2026 print "END($1)\n" if ($dbg_values > 1);
2027 $type = 'E';
2028 $av_pend_colon = 'O';
2029
2030 } elsif ($cur =~/^(,)/) {
2031 print "COMMA($1)\n" if ($dbg_values > 1);
2032 $type = 'C';
2033
2034 } elsif ($cur =~ /^(\?)/o) {
2035 print "QUESTION($1)\n" if ($dbg_values > 1);
2036 $type = 'N';
2037
2038 } elsif ($cur =~ /^(:)/o) {
2039 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2040
2041 substr($var, length($res), 1, $av_pend_colon);
2042 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2043 $type = 'E';
2044 } else {
2045 $type = 'N';
2046 }
2047 $av_pend_colon = 'O';
2048
2049 } elsif ($cur =~ /^(\[)/o) {
2050 print "CLOSE($1)\n" if ($dbg_values > 1);
2051 $type = 'N';
2052
2053 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2054 my $variant;
2055
2056 print "OPV($1)\n" if ($dbg_values > 1);
2057 if ($type eq 'V') {
2058 $variant = 'B';
2059 } else {
2060 $variant = 'U';
2061 }
2062
2063 substr($var, length($res), 1, $variant);
2064 $type = 'N';
2065
2066 } elsif ($cur =~ /^($Operators)/o) {
2067 print "OP($1)\n" if ($dbg_values > 1);
2068 if ($1 ne '++' && $1 ne '--') {
2069 $type = 'N';
2070 }
2071
2072 } elsif ($cur =~ /(^.)/o) {
2073 print "C($1)\n" if ($dbg_values > 1);
2074 }
2075 if (defined $1) {
2076 $cur = substr($cur, length($1));
2077 $res .= $type x length($1);
2078 }
2079 }
2080
2081 return ($res, $var);
2082}
2083
2084sub possible {
2085 my ($possible, $line) = @_;
2086 my $notPermitted = qr{(?:
2087 ^(?:
2088 $Modifier|
2089 $Storage|
2090 $Type|
2091 DEFINE_\S+
2092 )$|
2093 ^(?:
2094 goto|
2095 return|
2096 case|
2097 else|
2098 asm|__asm__|
2099 do|
2100 \#|
2101 \#\#|
2102 )(?:\s|$)|
2103 ^(?:typedef|struct|enum)\b
2104 )}x;
2105 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2106 if ($possible !~ $notPermitted) {
2107 # Check for modifiers.
2108 $possible =~ s/\s*$Storage\s*//g;
2109 $possible =~ s/\s*$Sparse\s*//g;
2110 if ($possible =~ /^\s*$/) {
2111
2112 } elsif ($possible =~ /\s/) {
2113 $possible =~ s/\s*$Type\s*//g;
2114 for my $modifier (split(' ', $possible)) {
2115 if ($modifier !~ $notPermitted) {
2116 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002117 push(@modifierListFile, $modifier);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002118 }
2119 }
2120
2121 } else {
2122 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002123 push(@typeListFile, $possible);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002124 }
2125 build_types();
2126 } else {
2127 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2128 }
2129}
2130
2131my $prefix = '';
2132
2133sub show_type {
2134 my ($type) = @_;
2135
Martin Rothedd591d2017-03-14 10:16:29 -06002136 $type =~ tr/[a-z]/[A-Z]/;
2137
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002138 return defined $use_type{$type} if (scalar keys %use_type > 0);
2139
2140 return !defined $ignore_type{$type};
2141}
2142
2143sub report {
2144 my ($level, $type, $msg) = @_;
2145
2146 if (!show_type($type) ||
2147 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2148 return 0;
2149 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002150 my $output = '';
Martin Roth387dec82017-09-17 19:20:46 -06002151 if ($color) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002152 if ($level eq 'ERROR') {
2153 $output .= RED;
2154 } elsif ($level eq 'WARNING') {
2155 $output .= YELLOW;
2156 } else {
2157 $output .= GREEN;
2158 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002159 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002160 $output .= $prefix . $level . ':';
2161 if ($show_types) {
Martin Roth387dec82017-09-17 19:20:46 -06002162 $output .= BLUE if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002163 $output .= "$type:";
2164 }
Martin Roth387dec82017-09-17 19:20:46 -06002165 $output .= RESET if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002166 $output .= ' ' . $msg . "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002167
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002168 if ($showfile) {
2169 my @lines = split("\n", $output, -1);
2170 splice(@lines, 1, 1);
2171 $output = join("\n", @lines);
2172 }
Elyes Haouas46b07e52022-04-07 10:07:34 +02002173
2174 if ($terse) {
2175 $output = (split('\n', $output))[0] . "\n";
2176 }
2177
2178 if ($verbose && exists($verbose_messages{$type}) &&
2179 !exists($verbose_emitted{$type})) {
2180 $output .= $verbose_messages{$type} . "\n\n";
2181 $verbose_emitted{$type} = 1;
2182 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002183
2184 push(our @report, $output);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002185
2186 return 1;
2187}
2188
2189sub report_dump {
2190 our @report;
2191}
2192
2193sub fixup_current_range {
2194 my ($lineRef, $offset, $length) = @_;
2195
2196 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2197 my $o = $1;
2198 my $l = $2;
2199 my $no = $o + $offset;
2200 my $nl = $l + $length;
2201 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2202 }
2203}
2204
2205sub fix_inserted_deleted_lines {
2206 my ($linesRef, $insertedRef, $deletedRef) = @_;
2207
2208 my $range_last_linenr = 0;
2209 my $delta_offset = 0;
2210
2211 my $old_linenr = 0;
2212 my $new_linenr = 0;
2213
2214 my $next_insert = 0;
2215 my $next_delete = 0;
2216
2217 my @lines = ();
2218
2219 my $inserted = @{$insertedRef}[$next_insert++];
2220 my $deleted = @{$deletedRef}[$next_delete++];
2221
2222 foreach my $old_line (@{$linesRef}) {
2223 my $save_line = 1;
2224 my $line = $old_line; #don't modify the array
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002225 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002226 $delta_offset = 0;
2227 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2228 $range_last_linenr = $new_linenr;
2229 fixup_current_range(\$line, $delta_offset, 0);
2230 }
2231
2232 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2233 $deleted = @{$deletedRef}[$next_delete++];
2234 $save_line = 0;
2235 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2236 }
2237
2238 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2239 push(@lines, ${$inserted}{'LINE'});
2240 $inserted = @{$insertedRef}[$next_insert++];
2241 $new_linenr++;
2242 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2243 }
2244
2245 if ($save_line) {
2246 push(@lines, $line);
2247 $new_linenr++;
2248 }
2249
2250 $old_linenr++;
2251 }
2252
2253 return @lines;
2254}
2255
2256sub fix_insert_line {
2257 my ($linenr, $line) = @_;
2258
2259 my $inserted = {
2260 LINENR => $linenr,
2261 LINE => $line,
2262 };
2263 push(@fixed_inserted, $inserted);
2264}
2265
2266sub fix_delete_line {
2267 my ($linenr, $line) = @_;
2268
2269 my $deleted = {
2270 LINENR => $linenr,
2271 LINE => $line,
2272 };
2273
2274 push(@fixed_deleted, $deleted);
2275}
2276
2277sub ERROR {
2278 my ($type, $msg) = @_;
2279
2280 if (report("ERROR", $type, $msg)) {
2281 our $clean = 0;
2282 our $cnt_error++;
2283 return 1;
2284 }
2285 return 0;
2286}
2287sub WARN {
2288 my ($type, $msg) = @_;
2289
2290 if (report("WARNING", $type, $msg)) {
2291 our $clean = 0;
2292 our $cnt_warn++;
2293 return 1;
2294 }
2295 return 0;
2296}
2297sub CHK {
2298 my ($type, $msg) = @_;
2299
2300 if ($check && report("CHECK", $type, $msg)) {
2301 our $clean = 0;
2302 our $cnt_chk++;
2303 return 1;
2304 }
2305 return 0;
2306}
2307
2308sub check_absolute_file {
2309 my ($absolute, $herecurr) = @_;
2310 my $file = $absolute;
2311
2312 ##print "absolute<$absolute>\n";
2313
2314 # See if any suffix of this path is a path within the tree.
2315 while ($file =~ s@^[^/]*/@@) {
2316 if (-f "$root/$file") {
2317 ##print "file<$file>\n";
2318 last;
2319 }
2320 }
2321 if (! -f _) {
2322 return 0;
2323 }
2324
2325 # It is, so see if the prefix is acceptable.
2326 my $prefix = $absolute;
2327 substr($prefix, -length($file)) = '';
2328
2329 ##print "prefix<$prefix>\n";
2330 if ($prefix ne ".../") {
2331 WARN("USE_RELATIVE_PATH",
2332 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2333 }
2334}
2335
2336sub trim {
2337 my ($string) = @_;
2338
2339 $string =~ s/^\s+|\s+$//g;
2340
2341 return $string;
2342}
2343
2344sub ltrim {
2345 my ($string) = @_;
2346
2347 $string =~ s/^\s+//;
2348
2349 return $string;
2350}
2351
2352sub rtrim {
2353 my ($string) = @_;
2354
2355 $string =~ s/\s+$//;
2356
2357 return $string;
2358}
2359
2360sub string_find_replace {
2361 my ($string, $find, $replace) = @_;
2362
2363 $string =~ s/$find/$replace/g;
2364
2365 return $string;
2366}
2367
2368sub tabify {
2369 my ($leading) = @_;
2370
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01002371 my $source_indent = $tabsize;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002372 my $max_spaces_before_tab = $source_indent - 1;
2373 my $spaces_to_tab = " " x $source_indent;
2374
2375 #convert leading spaces to tabs
2376 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2377 #Remove spaces before a tab
2378 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2379
2380 return "$leading";
2381}
2382
2383sub pos_last_openparen {
2384 my ($line) = @_;
2385
2386 my $pos = 0;
2387
2388 my $opens = $line =~ tr/\(/\(/;
2389 my $closes = $line =~ tr/\)/\)/;
2390
2391 my $last_openparen = 0;
2392
2393 if (($opens == 0) || ($closes >= $opens)) {
2394 return -1;
2395 }
2396
2397 my $len = length($line);
2398
2399 for ($pos = 0; $pos < $len; $pos++) {
2400 my $string = substr($line, $pos);
2401 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2402 $pos += length($1) - 1;
2403 } elsif (substr($line, $pos, 1) eq '(') {
2404 $last_openparen = $pos;
2405 } elsif (index($string, '(') == -1) {
2406 last;
2407 }
2408 }
2409
2410 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2411}
2412
Elyes Haouasf62a9892022-04-12 12:17:50 +02002413sub get_raw_comment {
2414 my ($line, $rawline) = @_;
2415 my $comment = '';
2416
2417 for my $i (0 .. (length($line) - 1)) {
2418 if (substr($line, $i, 1) eq "$;") {
2419 $comment .= substr($rawline, $i, 1);
2420 }
2421 }
2422
2423 return $comment;
2424}
2425
2426sub exclude_global_initialisers {
2427 my ($realfile) = @_;
2428
2429 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2430 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2431 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2432 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2433}
2434
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002435sub process {
2436 my $filename = shift;
2437
2438 my $linenr=0;
2439 my $prevline="";
2440 my $prevrawline="";
2441 my $stashline="";
2442 my $stashrawline="";
2443
2444 my $length;
2445 my $indent;
2446 my $previndent=0;
2447 my $stashindent=0;
2448
2449 our $clean = 1;
2450 my $signoff = 0;
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002451 my $author = '';
2452 my $authorsignoff = 0;
2453 my $author_sob = '';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002454 my $is_patch = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002455 my $in_header_lines = $file ? 0 : 1;
2456 my $in_commit_log = 0; #Scanning lines before patch
Elyes Haouascb346842022-07-13 17:05:19 +02002457 my $has_patch_separator = 0; #Found a --- line
Martin Rothedd591d2017-03-14 10:16:29 -06002458 my $has_commit_log = 0; #Encountered lines before patch
Elyes Haouase83e0902022-07-13 17:40:30 +02002459 my $commit_log_lines = 0; #Number of commit log lines
Martin Rothedd591d2017-03-14 10:16:29 -06002460 my $commit_log_possible_stack_dump = 0;
Elyes Haouas26e0b942022-05-22 11:11:11 +02002461 my $commit_log_long_line = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002462 my $commit_log_has_diff = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002463 my $reported_maintainer_file = 0;
2464 my $non_utf8_charset = 0;
2465
2466 my $last_blank_line = 0;
2467 my $last_coalesced_string_linenr = -1;
2468
2469 our @report = ();
2470 our $cnt_lines = 0;
2471 our $cnt_error = 0;
2472 our $cnt_warn = 0;
2473 our $cnt_chk = 0;
2474
2475 # Trace the real file/line as we go.
2476 my $realfile = '';
2477 my $realline = 0;
2478 my $realcnt = 0;
2479 my $here = '';
Martin Rothedd591d2017-03-14 10:16:29 -06002480 my $context_function; #undef'd unless there's a known function
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002481 my $in_comment = 0;
2482 my $comment_edge = 0;
2483 my $first_line = 0;
2484 my $p1_prefix = '';
2485
2486 my $prev_values = 'E';
2487
2488 # suppression flags
2489 my %suppress_ifbraces;
2490 my %suppress_whiletrailers;
2491 my %suppress_export;
2492 my $suppress_statement = 0;
2493
2494 my %signatures = ();
2495
2496 # Pre-scan the patch sanitizing the lines.
2497 # Pre-scan the patch looking for any __setup documentation.
2498 #
2499 my @setup_docs = ();
2500 my $setup_docs = 0;
2501
2502 my $camelcase_file_seeded = 0;
2503
Martin Roth60915b32018-08-10 21:04:05 -06002504 my $checklicenseline = 1;
2505
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002506 sanitise_line_reset();
2507 my $line;
2508 foreach my $rawline (@rawlines) {
2509 $linenr++;
2510 $line = $rawline;
2511
2512 push(@fixed, $rawline) if ($fix);
2513
2514 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2515 $setup_docs = 0;
Martin Rothedd591d2017-03-14 10:16:29 -06002516 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002517 $setup_docs = 1;
2518 }
2519 #next;
2520 }
Martin Roth387dec82017-09-17 19:20:46 -06002521 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002522 $realline=$1-1;
2523 if (defined $2) {
2524 $realcnt=$3+1;
2525 } else {
2526 $realcnt=1+1;
2527 }
2528 $in_comment = 0;
2529
2530 # Guestimate if this is a continuing comment. Run
2531 # the context looking for a comment "edge". If this
2532 # edge is a close comment then we must be in a comment
2533 # at context start.
2534 my $edge;
2535 my $cnt = $realcnt;
2536 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2537 next if (defined $rawlines[$ln - 1] &&
2538 $rawlines[$ln - 1] =~ /^-/);
2539 $cnt--;
2540 #print "RAW<$rawlines[$ln - 1]>\n";
2541 last if (!defined $rawlines[$ln - 1]);
2542 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2543 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2544 ($edge) = $1;
2545 last;
2546 }
2547 }
2548 if (defined $edge && $edge eq '*/') {
2549 $in_comment = 1;
2550 }
2551
2552 # Guestimate if this is a continuing comment. If this
2553 # is the start of a diff block and this line starts
2554 # ' *' then it is very likely a comment.
2555 if (!defined $edge &&
2556 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2557 {
2558 $in_comment = 1;
2559 }
2560
2561 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2562 sanitise_line_reset($in_comment);
2563
2564 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2565 # Standardise the strings and chars within the input to
2566 # simplify matching -- only bother with positive lines.
2567 $line = sanitise_line($rawline);
2568 }
2569 push(@lines, $line);
2570
2571 if ($realcnt > 1) {
2572 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2573 } else {
2574 $realcnt = 0;
2575 }
2576
2577 #print "==>$rawline\n";
2578 #print "-->$line\n";
2579
2580 if ($setup_docs && $line =~ /^\+/) {
2581 push(@setup_docs, $line);
2582 }
2583 }
2584
2585 $prefix = '';
2586
2587 $realcnt = 0;
2588 $linenr = 0;
2589 $fixlinenr = -1;
2590 foreach my $line (@lines) {
2591 $linenr++;
2592 $fixlinenr++;
2593 my $sline = $line; #copy of $line
2594 $sline =~ s/$;/ /g; #with comments as spaces
2595
2596 my $rawline = $rawlines[$linenr - 1];
Elyes Haouasf62a9892022-04-12 12:17:50 +02002597 my $raw_comment = get_raw_comment($line, $rawline);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002598
Martin Roth60915b32018-08-10 21:04:05 -06002599# check if it's a mode change, rename or start of a patch
2600 if (!$in_commit_log &&
2601 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2602 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2603 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2604 $is_patch = 1;
2605 }
2606
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002607#extract the line range in the file after the patch is applied
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002608 if (!$in_commit_log &&
Martin Roth387dec82017-09-17 19:20:46 -06002609 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2610 my $context = $4;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002611 $is_patch = 1;
2612 $first_line = $linenr + 1;
2613 $realline=$1-1;
2614 if (defined $2) {
2615 $realcnt=$3+1;
2616 } else {
2617 $realcnt=1+1;
2618 }
2619 annotate_reset();
2620 $prev_values = 'E';
2621
2622 %suppress_ifbraces = ();
2623 %suppress_whiletrailers = ();
2624 %suppress_export = ();
2625 $suppress_statement = 0;
Martin Roth387dec82017-09-17 19:20:46 -06002626 if ($context =~ /\b(\w+)\s*\(/) {
2627 $context_function = $1;
2628 } else {
2629 undef $context_function;
2630 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002631 next;
2632
2633# track the line number as we move through the hunk, note that
2634# new versions of GNU diff omit the leading space on completely
2635# blank context lines so we need to count that too.
2636 } elsif ($line =~ /^( |\+|$)/) {
2637 $realline++;
2638 $realcnt-- if ($realcnt != 0);
2639
2640 # Measure the line length and indent.
2641 ($length, $indent) = line_stats($rawline);
2642
2643 # Track the previous line.
2644 ($prevline, $stashline) = ($stashline, $line);
2645 ($previndent, $stashindent) = ($stashindent, $indent);
2646 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2647
2648 #warn "line<$line>\n";
2649
2650 } elsif ($realcnt == 1) {
2651 $realcnt--;
2652 }
2653
2654 my $hunk_line = ($realcnt != 0);
2655
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002656 $here = "#$linenr: " if (!$file);
2657 $here = "#$realline: " if ($file);
2658
2659 my $found_file = 0;
2660 # extract the filename as it passes
2661 if ($line =~ /^diff --git.*?(\S+)$/) {
2662 $realfile = $1;
2663 $realfile =~ s@^([^/]*)/@@ if (!$file);
2664 $in_commit_log = 0;
2665 $found_file = 1;
2666 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2667 $realfile = $1;
2668 $realfile =~ s@^([^/]*)/@@ if (!$file);
2669 $in_commit_log = 0;
2670
2671 $p1_prefix = $1;
2672 if (!$file && $tree && $p1_prefix ne '' &&
2673 -e "$root/$p1_prefix") {
2674 WARN("PATCH_PREFIX",
2675 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2676 }
2677
2678 if ($realfile =~ m@^include/asm/@) {
2679 ERROR("MODIFIED_INCLUDE_ASM",
2680 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2681 }
2682 $found_file = 1;
2683 }
2684
Martin Rothedd591d2017-03-14 10:16:29 -06002685 # coreboot
Martin Rotha3cac872017-03-04 18:17:35 -07002686 my $skipme = 0;
2687 foreach (@exclude) {
2688 if ($realfile =~ m@^(?:$_/)@) {
2689 $skipme = 1;
2690 }
2691 }
2692 if ($skipme) {
2693 next;
2694 }
2695
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002696#make up the handle for any error we report on this line
2697 if ($showfile) {
2698 $prefix = "$realfile:$realline: "
2699 } elsif ($emacs) {
2700 if ($file) {
2701 $prefix = "$filename:$realline: ";
2702 } else {
2703 $prefix = "$filename:$linenr: ";
2704 }
2705 }
2706
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002707 if ($found_file) {
Martin Rothedd591d2017-03-14 10:16:29 -06002708 if (is_maintained_obsolete($realfile)) {
2709 WARN("OBSOLETE",
2710 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2711 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002712 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002713 $check = 1;
2714 } else {
2715 $check = $check_orig;
2716 }
Martin Roth60915b32018-08-10 21:04:05 -06002717 $checklicenseline = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002718 next;
2719 }
2720
2721 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2722
2723 my $hereline = "$here\n$rawline\n";
2724 my $herecurr = "$here\n$rawline\n";
2725 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2726
2727 $cnt_lines++ if ($realcnt != 0);
2728
Elyes Haouase83e0902022-07-13 17:40:30 +02002729# Verify the existence of a commit log if appropriate
2730# 2 is used because a $signature is counted in $commit_log_lines
2731 if ($in_commit_log) {
2732 if ($line !~ /^\s*$/) {
2733 $commit_log_lines++; #could be a $signature
2734 }
2735 } elsif ($has_commit_log && $commit_log_lines < 2) {
2736 WARN("COMMIT_MESSAGE",
2737 "Missing commit description - Add an appropriate one\n");
2738 $commit_log_lines = 2; #warn only once
2739 }
2740
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002741# Check if the commit log has what seems like a diff which can confuse patch
2742 if ($in_commit_log && !$commit_log_has_diff &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02002743 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2744 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002745 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2746 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2747 ERROR("DIFF_IN_COMMIT_MSG",
2748 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2749 $commit_log_has_diff = 1;
2750 }
2751
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002752# Check for incorrect file permissions
2753 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2754 my $permhere = $here . "FILE: $realfile\n";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002755 if ($realfile !~ m@scripts/@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002756 $realfile !~ /\.(py|pl|awk|sh)$/) {
2757 ERROR("EXECUTE_PERMISSIONS",
2758 "do not set execute permissions for source files\n" . $permhere);
2759 }
2760 }
2761
2762# Check the patch for a signoff:
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002763 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002764 $signoff++;
2765 $in_commit_log = 0;
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02002766 if ($author ne '' && $authorsignoff != 1) {
2767 if (same_email_addresses($1, $author)) {
2768 $authorsignoff = 1;
2769 } else {
2770 my $ctx = $1;
2771 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2772 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2773
2774 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2775 $author_sob = $ctx;
2776 $authorsignoff = 2;
2777 } elsif (lc $email_address eq lc $author_address) {
2778 $author_sob = $ctx;
2779 $authorsignoff = 3;
2780 } elsif ($email_name eq $author_name) {
2781 $author_sob = $ctx;
2782 $authorsignoff = 4;
2783
2784 my $address1 = $email_address;
2785 my $address2 = $author_address;
2786
2787 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2788 $address1 = "$1$2";
2789 }
2790 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2791 $address2 = "$1$2";
2792 }
2793 if ($address1 eq $address2) {
2794 $authorsignoff = 5;
2795 }
2796 }
2797 }
2798 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002799 }
2800
Elyes Haouascb346842022-07-13 17:05:19 +02002801# Check for patch separator
2802 if ($line =~ /^---$/) {
2803 $has_patch_separator = 1;
2804 $in_commit_log = 0;
2805 }
2806
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002807# Check if MAINTAINERS is being updated. If so, there's probably no need to
2808# emit the "does MAINTAINERS need updating?" message on file add/move/delete
2809 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2810 $reported_maintainer_file = 1;
2811 }
2812
2813# Check signature styles
2814 if (!$in_header_lines &&
2815 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2816 my $space_before = $1;
2817 my $sign_off = $2;
2818 my $space_after = $3;
2819 my $email = $4;
2820 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2821
2822 if ($sign_off !~ /$signature_tags/) {
2823 WARN("BAD_SIGN_OFF",
2824 "Non-standard signature: $sign_off\n" . $herecurr);
2825 }
2826 if (defined $space_before && $space_before ne "") {
2827 if (WARN("BAD_SIGN_OFF",
2828 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2829 $fix) {
2830 $fixed[$fixlinenr] =
2831 "$ucfirst_sign_off $email";
2832 }
2833 }
2834 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2835 if (WARN("BAD_SIGN_OFF",
2836 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2837 $fix) {
2838 $fixed[$fixlinenr] =
2839 "$ucfirst_sign_off $email";
2840 }
2841
2842 }
2843 if (!defined $space_after || $space_after ne " ") {
2844 if (WARN("BAD_SIGN_OFF",
2845 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2846 $fix) {
2847 $fixed[$fixlinenr] =
2848 "$ucfirst_sign_off $email";
2849 }
2850 }
2851
2852 my ($email_name, $email_address, $comment) = parse_email($email);
2853 my $suggested_email = format_email(($email_name, $email_address));
2854 if ($suggested_email eq "") {
2855 ERROR("BAD_SIGN_OFF",
2856 "Unrecognized email address: '$email'\n" . $herecurr);
2857 } else {
2858 my $dequoted = $suggested_email;
2859 $dequoted =~ s/^"//;
2860 $dequoted =~ s/" </ </;
2861 # Don't force email to have quotes
2862 # Allow just an angle bracketed address
2863 if ("$dequoted$comment" ne $email &&
2864 "<$email_address>$comment" ne $email &&
2865 "$suggested_email$comment" ne $email) {
2866 WARN("BAD_SIGN_OFF",
2867 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2868 }
2869 }
2870
2871# Check for duplicate signatures
2872 my $sig_nospace = $line;
2873 $sig_nospace =~ s/\s//g;
2874 $sig_nospace = lc($sig_nospace);
2875 if (defined $signatures{$sig_nospace}) {
2876 WARN("BAD_SIGN_OFF",
2877 "Duplicate signature\n" . $herecurr);
2878 } else {
2879 $signatures{$sig_nospace} = 1;
2880 }
2881 }
2882
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002883# Check email subject for common tools that don't need to be mentioned
2884 if ($in_header_lines &&
2885 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2886 WARN("EMAIL_SUBJECT",
2887 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2888 }
2889
Elyes Haouascb346842022-07-13 17:05:19 +02002890# Check for Gerrit Change-Ids not in any patch context
2891 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2892 if (ERROR("GERRIT_CHANGE_ID",
2893 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
2894 $fix) {
2895 fix_delete_line($fixlinenr, $rawline);
2896 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002897 }
2898
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002899# Check if the commit log is in a possible stack dump
2900 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2901 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2902 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2903 # timestamp
Elyes Haouas26e0b942022-05-22 11:11:11 +02002904 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2905 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2906 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2907 # stack dump address styles
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002908 $commit_log_possible_stack_dump = 1;
2909 }
2910
Martin Roth10d34b72022-03-22 16:24:44 -06002911# coreboot: The line length limit is 72
2912# Check for line lengths > 72 in commit log
2913 if ($in_commit_log && length($line) > 72 &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002914 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2915 # file delta changes
Elyes HAOUASac690492022-01-29 07:59:17 +01002916 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002917 # filename then :
Elyes HAOUASac690492022-01-29 07:59:17 +01002918 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
2919 # A Fixes: or Link: line or signature tag line
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002920 $commit_log_possible_stack_dump)) {
2921 WARN("COMMIT_LOG_LONG_LINE",
Paul Menzeldd1ee272021-12-09 12:49:35 +01002922 "Possible unwrapped commit description (prefer a maximum 72 chars per line)\n" . $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02002923 $commit_log_long_line = 1;
Martin Roth10d34b72022-03-22 16:24:44 -06002924 }
2925
2926# coreboot: The line subject limit is 65
2927# Check for line lengths > 65 in commit subject
Martin Roth97e7eea2022-03-22 18:06:15 -06002928# coreboot: Check for a period at the end of the subject line
Martin Roth10d34b72022-03-22 16:24:44 -06002929 if ($in_header_lines &&
2930 $line =~ /^Subject: /) {
2931 $line = $line.$rawlines[$linenr];
2932 $line =~ s/^Subject: \[PATCH\] //;
Martin Roth341a53d2022-05-24 18:46:45 -06002933 if (length($line) - length("Subject: [PATCH] ") > 65) {
2934 WARN("COMMIT_LOG_LONG_LINE",
2935 "Possible long commit subject (prefer a maximum 65 characters)\n" . $herecurr);
Martin Roth10d34b72022-03-22 16:24:44 -06002936 }
Martin Roth97e7eea2022-03-22 18:06:15 -06002937 if ($line =~ /\.$/) {
2938 WARN("SUBJECT_HAS_FULL_STOP",
2939 "Subject line should not end with a period.\n" . $herecurr);
2940 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002941 }
2942
2943# Reset possible stack dump if a blank line is found
2944 if ($in_commit_log && $commit_log_possible_stack_dump &&
2945 $line =~ /^\s*$/) {
2946 $commit_log_possible_stack_dump = 0;
2947 }
2948
2949# Check for git id commit length and improperly formed commit descriptions
2950 if ($in_commit_log && !$commit_log_possible_stack_dump &&
Martin Rothedd591d2017-03-14 10:16:29 -06002951 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
Martin Roth387dec82017-09-17 19:20:46 -06002952 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002953 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06002954 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002955 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2956 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2957 my $init_char = "c";
2958 my $orig_commit = "";
2959 my $short = 1;
2960 my $long = 0;
2961 my $case = 1;
2962 my $space = 1;
2963 my $hasdesc = 0;
2964 my $hasparens = 0;
2965 my $id = '0123456789ab';
2966 my $orig_desc = "commit description";
2967 my $description = "";
2968
2969 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2970 $init_char = $1;
2971 $orig_commit = lc($2);
2972 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2973 $orig_commit = lc($1);
2974 }
2975
2976 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2977 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2978 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2979 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2980 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2981 $orig_desc = $1;
2982 $hasparens = 1;
2983 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2984 defined $rawlines[$linenr] &&
2985 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2986 $orig_desc = $1;
2987 $hasparens = 1;
2988 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2989 defined $rawlines[$linenr] &&
2990 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2991 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2992 $orig_desc = $1;
2993 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2994 $orig_desc .= " " . $1;
2995 $hasparens = 1;
2996 }
2997
2998 ($id, $description) = git_commit_info($orig_commit,
2999 $id, $orig_desc);
3000
Martin Roth387dec82017-09-17 19:20:46 -06003001 if (defined($id) &&
3002 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003003 ERROR("GIT_COMMIT_ID",
3004 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
3005 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003006 }
3007
3008# Check for added, moved or deleted files
3009 if (!$reported_maintainer_file && !$in_commit_log &&
3010 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3011 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3012 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3013 (defined($1) || defined($2))))) {
Martin Rothedd591d2017-03-14 10:16:29 -06003014 $is_patch = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003015 $reported_maintainer_file = 1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003016 WARN("FILE_PATH_CHANGES",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003017 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3018 }
3019
3020# Check for wrappage within a valid hunk of the file
3021 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3022 ERROR("CORRUPTED_PATCH",
3023 "patch seems to be corrupt (line wrapped?)\n" .
3024 $herecurr) if (!$emitted_corrupt++);
3025 }
3026
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003027# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3028 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3029 $rawline !~ m/^$UTF8*$/) {
3030 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3031
3032 my $blank = copy_spacing($rawline);
3033 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3034 my $hereptr = "$hereline$ptr\n";
3035
3036 CHK("INVALID_UTF8",
3037 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3038 }
3039
3040# Check if it's the start of a commit log
3041# (not a header line and we haven't seen the patch filename)
3042 if ($in_header_lines && $realfile =~ /^$/ &&
Martin Roth387dec82017-09-17 19:20:46 -06003043 !($rawline =~ /^\s+(?:\S|$)/ ||
3044 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003045 $in_header_lines = 0;
3046 $in_commit_log = 1;
Martin Rothedd591d2017-03-14 10:16:29 -06003047 $has_commit_log = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003048 }
3049
3050# Check if there is UTF-8 in a commit log when a mail header has explicitly
3051# declined it, i.e defined some charset where it is missing.
3052 if ($in_header_lines &&
3053 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3054 $1 !~ /utf-8/i) {
3055 $non_utf8_charset = 1;
3056 }
3057
3058 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3059 $rawline =~ /$NON_ASCII_UTF8/) {
3060 WARN("UTF8_BEFORE_PATCH",
3061 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3062 }
3063
Martin Rothedd591d2017-03-14 10:16:29 -06003064# Check for absolute kernel paths in commit message
3065 if ($tree && $in_commit_log) {
3066 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3067 my $file = $1;
3068
3069 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3070 check_absolute_file($1, $herecurr)) {
3071 #
3072 } else {
3073 check_absolute_file($file, $herecurr);
3074 }
3075 }
3076 }
3077
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003078# Check for various typo / spelling mistakes
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003079 if (defined($misspellings) &&
3080 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02003081 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003082 my $typo = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003083 my $blank = copy_spacing($rawline);
3084 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3085 my $hereptr = "$hereline$ptr\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003086 my $typo_fix = $spelling_fix{lc($typo)};
3087 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3088 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
Martin Roth387dec82017-09-17 19:20:46 -06003089 my $msg_level = \&WARN;
3090 $msg_level = \&CHK if ($file);
3091 if (&{$msg_level}("TYPO_SPELLING",
Elyes Haouas26e0b942022-05-22 11:11:11 +02003092 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003093 $fix) {
3094 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3095 }
3096 }
3097 }
Elyes Haouas84083a22022-04-12 12:28:32 +02003098# check for repeated words separated by a single space
3099# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3100 if (($rawline =~ /^\+/ || $in_commit_log) &&
3101 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3102 pos($rawline) = 1 if (!$in_commit_log);
3103 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3104
3105 my $first = $1;
3106 my $second = $2;
3107 my $start_pos = $-[1];
3108 my $end_pos = $+[2];
3109 if ($first =~ /(?:struct|union|enum)/) {
3110 pos($rawline) += length($first) + length($second) + 1;
3111 next;
3112 }
3113
3114 next if (lc($first) ne lc($second));
3115 next if ($first eq 'long');
3116
3117 # check for character before and after the word matches
3118 my $start_char = '';
3119 my $end_char = '';
3120 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3121 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3122
3123 next if ($start_char =~ /^\S$/);
3124 next if (index(" \t.,;?!", $end_char) == -1);
3125
3126 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3127 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3128 next if (!exists($allow_repeated_words{lc($first)}));
3129 }
3130
3131 if (WARN("REPEATED_WORD",
3132 "Possible repeated word: '$first'\n" . $herecurr) &&
3133 $fix) {
3134 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3135 }
3136 }
3137
3138 # if it's a repeated word on consecutive lines in a comment block
3139 if ($prevline =~ /$;+\s*$/ &&
3140 $prevrawline =~ /($word_pattern)\s*$/) {
3141 my $last_word = $1;
3142 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3143 if (WARN("REPEATED_WORD",
3144 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3145 $fix) {
3146 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3147 }
3148 }
3149 }
3150 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003151
3152# ignore non-hunk lines and lines being removed
3153 next if (!$hunk_line || $line =~ /^-/);
3154
3155#trailing whitespace
3156 if ($line =~ /^\+.*\015/) {
3157 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3158 if (ERROR("DOS_LINE_ENDINGS",
3159 "DOS line endings\n" . $herevet) &&
3160 $fix) {
3161 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3162 }
3163 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3164 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3165 if (ERROR("TRAILING_WHITESPACE",
3166 "trailing whitespace\n" . $herevet) &&
3167 $fix) {
3168 $fixed[$fixlinenr] =~ s/\s+$//;
3169 }
3170
3171 $rpt_cleaners = 1;
3172 }
3173
3174# Check for FSF mailing addresses.
3175 if ($rawline =~ /\bwrite to the Free/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06003176 $rawline =~ /\b675\s+Mass\s+Ave/i ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003177 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3178 $rawline =~ /\b51\s+Franklin\s+St/i) {
3179 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
Martin Roth387dec82017-09-17 19:20:46 -06003180 my $msg_level = \&ERROR;
3181 $msg_level = \&CHK if ($file);
3182 &{$msg_level}("FSF_MAILING_ADDRESS",
3183 "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)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003184 }
3185
3186# check for Kconfig help text having a real description
3187# Only applies when adding the entry originally, after that we do not have
3188# sufficient context to determine whether it is indeed long enough.
3189 if ($realfile =~ /Kconfig/ &&
Martin Roth60915b32018-08-10 21:04:05 -06003190 # 'choice' is usually the last thing on the line (though
3191 # Kconfig supports named choices), so use a word boundary
3192 # (\b) rather than a whitespace character (\s)
3193 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
Elyes Haouasf62a9892022-04-12 12:17:50 +02003194 my $ln = $linenr;
3195 my $needs_help = 0;
3196 my $has_help = 0;
3197 my $help_length = 0;
3198 while (defined $lines[$ln]) {
3199 my $f = $lines[$ln++];
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003200
3201 next if ($f =~ /^-/);
Elyes Haouasf62a9892022-04-12 12:17:50 +02003202 last if ($f !~ /^[\+ ]/); # !patch context
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003203
Elyes Haouasf62a9892022-04-12 12:17:50 +02003204 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3205 $needs_help = 1;
3206 next;
3207 }
3208 if ($f =~ /^\+\s*help\s*$/) {
3209 $has_help = 1;
3210 next;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003211 }
3212
Elyes Haouasf62a9892022-04-12 12:17:50 +02003213 $f =~ s/^.//; # strip patch context [+ ]
3214 $f =~ s/#.*//; # strip # directives
3215 $f =~ s/^\s+//; # strip leading blanks
3216 next if ($f =~ /^$/); # skip blank lines
Martin Roth60915b32018-08-10 21:04:05 -06003217
Elyes Haouasf62a9892022-04-12 12:17:50 +02003218 # At the end of this Kconfig block:
Martin Roth60915b32018-08-10 21:04:05 -06003219 # This only checks context lines in the patch
3220 # and so hopefully shouldn't trigger false
3221 # positives, even though some of these are
3222 # common words in help texts
Elyes Haouasf62a9892022-04-12 12:17:50 +02003223 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3224 if|endif|menu|endmenu|source)\b/x) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003225 last;
3226 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003227 $help_length++ if ($has_help);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003228 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003229 if ($needs_help &&
3230 $help_length < $min_conf_desc_length) {
3231 my $stat_real = get_stat_real($linenr, $ln - 1);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003232 WARN("CONFIG_DESCRIPTION",
Elyes Haouasf62a9892022-04-12 12:17:50 +02003233 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003234 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003235 }
3236
Martin Roth387dec82017-09-17 19:20:46 -06003237# check for MAINTAINERS entries that don't have the right form
3238 if ($realfile =~ /^MAINTAINERS$/ &&
3239 $rawline =~ /^\+[A-Z]:/ &&
3240 $rawline !~ /^\+[A-Z]:\t\S/) {
3241 if (WARN("MAINTAINERS_STYLE",
3242 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3243 $fix) {
3244 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3245 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003246 }
3247
3248 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3249 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3250 my $flag = $1;
3251 my $replacement = {
3252 'EXTRA_AFLAGS' => 'asflags-y',
3253 'EXTRA_CFLAGS' => 'ccflags-y',
3254 'EXTRA_CPPFLAGS' => 'cppflags-y',
3255 'EXTRA_LDFLAGS' => 'ldflags-y',
3256 };
3257
3258 WARN("DEPRECATED_VARIABLE",
3259 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3260 }
3261
3262# check for DT compatible documentation
3263 if (defined $root &&
3264 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3265 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3266
3267 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3268
3269 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3270 my $vp_file = $dt_path . "vendor-prefixes.txt";
3271
3272 foreach my $compat (@compats) {
3273 my $compat2 = $compat;
3274 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3275 my $compat3 = $compat;
3276 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3277 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3278 if ( $? >> 8 ) {
3279 WARN("UNDOCUMENTED_DT_STRING",
3280 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3281 }
3282
3283 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3284 my $vendor = $1;
3285 `grep -Eq "^$vendor\\b" $vp_file`;
3286 if ( $? >> 8 ) {
3287 WARN("UNDOCUMENTED_DT_STRING",
3288 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3289 }
3290 }
3291 }
3292
Martin Roth60915b32018-08-10 21:04:05 -06003293# check for using SPDX license tag at beginning of files
3294 if ($realline == $checklicenseline) {
3295 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3296 $checklicenseline = 2;
3297 } elsif ($rawline =~ /^\+/) {
3298 my $comment = "";
3299 if ($realfile =~ /\.(h|s|S)$/) {
3300 $comment = '/*';
3301 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3302 $comment = '//';
3303 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3304 $comment = '#';
3305 } elsif ($realfile =~ /\.rst$/) {
3306 $comment = '..';
3307 }
3308
3309 if ($comment !~ /^$/ &&
3310 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3311 WARN("SPDX_LICENSE_TAG",
3312 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3313 }
3314 }
3315 }
3316
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003317# check we are in a valid source file if not then ignore this hunk
Martin Rothedd591d2017-03-14 10:16:29 -06003318 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003319
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003320# line length limit (with some exclusions)
3321#
3322# There are a few types of lines that may extend beyond $max_line_length:
3323# logging functions like pr_info that end in a string
3324# lines with a single string
3325# #defines that are a single string
Martin Roth60915b32018-08-10 21:04:05 -06003326# lines with an RFC3986 like URL
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003327#
3328# There are 3 different line length message types:
Martin Roth387dec82017-09-17 19:20:46 -06003329# LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003330# LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3331# LONG_LINE all other lines longer than $max_line_length
3332#
3333# if LONG_LINE is ignored, the other 2 types are also ignored
3334#
3335
Michael Niewöhner8eb7b352022-10-25 23:29:18 +02003336 $max_line_length += 1; # consider leading + in patches
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003337 if ($line =~ /^\+/ && $length > $max_line_length) {
3338 my $msg_type = "LONG_LINE";
3339
3340 # Check the allowed long line types first
3341
3342 # logging functions that end in a string that starts
3343 # before $max_line_length
3344 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3345 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3346 $msg_type = "";
3347
3348 # lines with only strings (w/ possible termination)
3349 # #defines with only strings
3350 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3351 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3352 $msg_type = "";
3353
Martin Roth60915b32018-08-10 21:04:05 -06003354 # More special cases
3355 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3356 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3357 $msg_type = "";
3358
3359 # URL ($rawline is used in case the URL is in a comment)
3360 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
Martin Rothedd591d2017-03-14 10:16:29 -06003361 $msg_type = "";
3362
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003363 # Otherwise set the alternate message types
3364
3365 # a comment starts before $max_line_length
3366 } elsif ($line =~ /($;[\s$;]*)$/ &&
3367 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3368 $msg_type = "LONG_LINE_COMMENT"
3369
3370 # a quoted string starts before $max_line_length
3371 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3372 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3373 $msg_type = "LONG_LINE_STRING"
3374 }
3375
3376 if ($msg_type ne "" &&
3377 (show_type("LONG_LINE") || show_type($msg_type))) {
Elyes Haouas0b1a03c2022-04-07 10:13:54 +02003378 my $msg_level = \&WARN;
3379 $msg_level = \&CHK if ($file);
3380 &{$msg_level}($msg_type,
3381 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003382 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003383 }
3384
3385# check for adding lines without a newline.
3386 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
Elyes Haouas86e4a3a2022-07-13 16:32:45 +02003387 if (WARN("MISSING_EOF_NEWLINE",
3388 "adding a line without newline at end of file\n" . $herecurr) &&
3389 $fix) {
3390 fix_delete_line($fixlinenr+1, "No newline at end of file");
3391 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003392 }
3393
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003394# check we are in a valid source file C or perl if not then ignore this hunk
3395 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3396
3397# at the beginning of a line any tabs must come first and anything
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003398# more than $tabsize must use tabs.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003399 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3400 $rawline =~ /^\+\s* \s*/) {
3401 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3402 $rpt_cleaners = 1;
3403 if (ERROR("CODE_INDENT",
3404 "code indent should use tabs where possible\n" . $herevet) &&
3405 $fix) {
3406 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3407 }
3408 }
3409
3410# check for space before tabs.
3411 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3412 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3413 if (WARN("SPACE_BEFORE_TAB",
3414 "please, no space before tabs\n" . $herevet) &&
3415 $fix) {
3416 while ($fixed[$fixlinenr] =~
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003417 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003418 while ($fixed[$fixlinenr] =~
3419 s/(^\+.*) +\t/$1\t/) {}
3420 }
3421 }
3422
Martin Roth60915b32018-08-10 21:04:05 -06003423# check for assignments on the start of a line
3424 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
Elyes Haouasc5ede532022-07-13 16:29:14 +02003425 my $operator = $1;
3426 if (CHK("ASSIGNMENT_CONTINUATIONS",
3427 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3428 $fix && $prevrawline =~ /^\+/) {
3429 # add assignment operator to the previous line, remove from current line
3430 $fixed[$fixlinenr - 1] .= " $operator";
3431 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3432 }
Martin Roth60915b32018-08-10 21:04:05 -06003433 }
3434
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003435# check for && or || at the start of a line
3436 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
Elyes Haouasd92fcf42022-07-13 16:34:29 +02003437 my $operator = $1;
3438 if (CHK("LOGICAL_CONTINUATIONS",
3439 "Logical continuations should be on the previous line\n" . $hereprev) &&
3440 $fix && $prevrawline =~ /^\+/) {
3441 # insert logical operator at last non-comment, non-whitepsace char on previous line
3442 $prevline =~ /[\s$;]*$/;
3443 my $line_end = substr($prevrawline, $-[0]);
3444 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3445 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3446 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003447 }
3448
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003449# check indentation starts on a tab stop
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003450 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06003451 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003452 my $indent = length($1);
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003453 if ($indent % $tabsize) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003454 if (WARN("TABSTOP",
3455 "Statements should start on a tabstop\n" . $herecurr) &&
3456 $fix) {
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003457 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003458 }
3459 }
3460 }
3461
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003462# check multi-line statement indentation matches previous line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003463 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06003464 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003465 $prevline =~ /^\+(\t*)(.*)$/;
3466 my $oldindent = $1;
3467 my $rest = $2;
3468
3469 my $pos = pos_last_openparen($rest);
3470 if ($pos >= 0) {
3471 $line =~ /^(\+| )([ \t]*)/;
3472 my $newindent = $2;
3473
3474 my $goodtabindent = $oldindent .
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003475 "\t" x ($pos / $tabsize) .
3476 " " x ($pos % $tabsize);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003477 my $goodspaceindent = $oldindent . " " x $pos;
3478
3479 if ($newindent ne $goodtabindent &&
3480 $newindent ne $goodspaceindent) {
3481
3482 if (CHK("PARENTHESIS_ALIGNMENT",
3483 "Alignment should match open parenthesis\n" . $hereprev) &&
3484 $fix && $line =~ /^\+/) {
3485 $fixed[$fixlinenr] =~
3486 s/^\+[ \t]*/\+$goodtabindent/;
3487 }
3488 }
3489 }
3490 }
3491
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003492# check for space after cast like "(int) foo" or "(struct foo) bar"
3493# avoid checking a few false positives:
3494# "sizeof(<type>)" or "__alignof__(<type>)"
3495# function pointer declarations like "(*foo)(int) = bar;"
3496# structure definitions like "(struct foo) { 0 };"
3497# multiline macros that define functions
3498# known attributes or the __attribute__ keyword
3499 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3500 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003501 if (CHK("SPACING",
3502 "No space is necessary after a cast\n" . $herecurr) &&
3503 $fix) {
3504 $fixed[$fixlinenr] =~
3505 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3506 }
3507 }
3508
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003509# Block comment styles
3510# Networking with an initial /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003511 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3512 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3513 $rawline =~ /^\+[ \t]*\*/ &&
3514 $realline > 2) {
3515 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3516 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3517 }
3518
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003519# Block comments use * on subsequent lines
3520 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3521 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003522 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3523 $rawline =~ /^\+/ && #line is new
3524 $rawline !~ /^\+[ \t]*\*/) { #no leading *
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003525 WARN("BLOCK_COMMENT_STYLE",
3526 "Block comments use * on subsequent lines\n" . $hereprev);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003527 }
3528
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003529# Block comments use */ on trailing lines
3530 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003531 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3532 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3533 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003534 WARN("BLOCK_COMMENT_STYLE",
3535 "Block comments use a trailing */ on a separate line\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003536 }
3537
Martin Rothedd591d2017-03-14 10:16:29 -06003538# Block comment * alignment
3539 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3540 $line =~ /^\+[ \t]*$;/ && #leading comment
3541 $rawline =~ /^\+[ \t]*\*/ && #leading *
3542 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3543 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3544 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3545 my $oldindent;
3546 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3547 if (defined($1)) {
3548 $oldindent = expand_tabs($1);
3549 } else {
3550 $prevrawline =~ m@^\+(.*/?)\*@;
3551 $oldindent = expand_tabs($1);
3552 }
3553 $rawline =~ m@^\+([ \t]*)\*@;
3554 my $newindent = $1;
3555 $newindent = expand_tabs($newindent);
3556 if (length($oldindent) ne length($newindent)) {
3557 WARN("BLOCK_COMMENT_STYLE",
3558 "Block comments should align the * on each line\n" . $hereprev);
3559 }
3560 }
3561
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003562# check for missing blank lines after struct/union declarations
3563# with exceptions for various attributes and macros
3564 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3565 $line =~ /^\+/ &&
3566 !($line =~ /^\+\s*$/ ||
3567 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3568 $line =~ /^\+\s*MODULE_/i ||
3569 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3570 $line =~ /^\+[a-z_]*init/ ||
3571 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3572 $line =~ /^\+\s*DECLARE/ ||
Martin Roth60915b32018-08-10 21:04:05 -06003573 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003574 $line =~ /^\+\s*__setup/)) {
3575 if (CHK("LINE_SPACING",
3576 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3577 $fix) {
3578 fix_insert_line($fixlinenr, "\+");
3579 }
3580 }
3581
3582# check for multiple consecutive blank lines
3583 if ($prevline =~ /^[\+ ]\s*$/ &&
3584 $line =~ /^\+\s*$/ &&
3585 $last_blank_line != ($linenr - 1)) {
3586 if (CHK("LINE_SPACING",
3587 "Please don't use multiple blank lines\n" . $hereprev) &&
3588 $fix) {
3589 fix_delete_line($fixlinenr, $rawline);
3590 }
3591
3592 $last_blank_line = $linenr;
3593 }
3594
3595# check for missing blank lines after declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003596# (declarations must have the same indentation and not be at the start of line)
3597 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3598 # use temporaries
3599 my $sl = $sline;
3600 my $pl = $prevline;
3601 # remove $Attribute/$Sparse uses to simplify comparisons
3602 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3603 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3604 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003605 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003606 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003607 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003608 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003609 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003610 $pl =~ /^\+\s+$declaration_macros/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003611 # for "else if" which can look like "$Ident $Ident"
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003612 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003613 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003614 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003615 # not starting a section or a macro "\" extended line
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003616 $pl =~ /(?:\{\s*|\\)$/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003617 # looks like a declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003618 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003619 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003620 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003621 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003622 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003623 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003624 $sl =~ /^\+\s+$declaration_macros/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003625 # start of struct or union or enum
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003626 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003627 # start or end of block or continuation of declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003628 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003629 # bitfield continuation
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003630 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003631 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003632 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3633 if (WARN("LINE_SPACING",
3634 "Missing a blank line after declarations\n" . $hereprev) &&
3635 $fix) {
3636 fix_insert_line($fixlinenr, "\+");
3637 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003638 }
3639 }
3640
3641# check for spaces at the beginning of a line.
3642# Exceptions:
3643# 1) within comments
3644# 2) indented preprocessor commands
3645# 3) hanging labels
3646 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3647 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3648 if (WARN("LEADING_SPACE",
3649 "please, no spaces at the start of a line\n" . $herevet) &&
3650 $fix) {
3651 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3652 }
3653 }
3654
3655# check we are in a valid C source file if not then ignore this hunk
3656 next if ($realfile !~ /\.(h|c)$/);
3657
Martin Roth60915b32018-08-10 21:04:05 -06003658# check for unusual line ending [ or (
3659 if ($line =~ /^\+.*([\[\(])\s*$/) {
3660 CHK("OPEN_ENDED_LINE",
3661 "Lines should not end with a '$1'\n" . $herecurr);
3662 }
3663
Martin Roth387dec82017-09-17 19:20:46 -06003664# check if this appears to be the start function declaration, save the name
3665 if ($sline =~ /^\+\{\s*$/ &&
3666 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3667 $context_function = $1;
3668 }
3669
3670# check if this appears to be the end of function declaration
3671 if ($sline =~ /^\+\}\s*$/) {
3672 undef $context_function;
3673 }
3674
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003675# check indentation of any line with a bare else
3676# (but not if it is a multiple line "if (foo) return bar; else return baz;")
3677# if the previous line is a break or return and is indented 1 tab more...
3678 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3679 my $tabs = length($1) + 1;
3680 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3681 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3682 defined $lines[$linenr] &&
3683 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3684 WARN("UNNECESSARY_ELSE",
3685 "else is not generally useful after a break or return\n" . $hereprev);
3686 }
3687 }
3688
3689# check indentation of a line with a break;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003690# if the previous line is a goto, return or break
3691# and is indented the same # of tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003692 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3693 my $tabs = $1;
Elyes Haouasa59a87c2022-07-13 16:36:25 +02003694 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3695 if (WARN("UNNECESSARY_BREAK",
3696 "break is not useful after a $1\n" . $hereprev) &&
3697 $fix) {
3698 fix_delete_line($fixlinenr, $rawline);
3699 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003700 }
3701 }
3702
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003703# check for RCS/CVS revision markers
3704 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3705 WARN("CVS_KEYWORD",
3706 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3707 }
3708
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003709# check for old HOTPLUG __dev<foo> section markings
3710 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3711 WARN("HOTPLUG_SECTION",
3712 "Using $1 is unnecessary\n" . $herecurr);
3713 }
3714
3715# Check for potential 'bare' types
3716 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3717 $realline_next);
3718#print "LINE<$line>\n";
Martin Roth387dec82017-09-17 19:20:46 -06003719 if ($linenr > $suppress_statement &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003720 $realcnt && $sline =~ /.\s*\S/) {
3721 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3722 ctx_statement_block($linenr, $realcnt, 0);
3723 $stat =~ s/\n./\n /g;
3724 $cond =~ s/\n./\n /g;
3725
3726#print "linenr<$linenr> <$stat>\n";
3727 # If this statement has no statement boundaries within
3728 # it there is no point in retrying a statement scan
3729 # until we hit end of it.
3730 my $frag = $stat; $frag =~ s/;+\s*$//;
3731 if ($frag !~ /(?:{|;)/) {
3732#print "skip<$line_nr_next>\n";
3733 $suppress_statement = $line_nr_next;
3734 }
3735
3736 # Find the real next line.
3737 $realline_next = $line_nr_next;
3738 if (defined $realline_next &&
3739 (!defined $lines[$realline_next - 1] ||
3740 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3741 $realline_next++;
3742 }
3743
3744 my $s = $stat;
3745 $s =~ s/{.*$//s;
3746
3747 # Ignore goto labels.
3748 if ($s =~ /$Ident:\*$/s) {
3749
3750 # Ignore functions being called
3751 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3752
3753 } elsif ($s =~ /^.\s*else\b/s) {
3754
3755 # declarations always start with types
3756 } 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) {
3757 my $type = $1;
3758 $type =~ s/\s+/ /g;
3759 possible($type, "A:" . $s);
3760
3761 # definitions in global scope can only start with types
3762 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3763 possible($1, "B:" . $s);
3764 }
3765
3766 # any (foo ... *) is a pointer cast, and foo is a type
3767 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3768 possible($1, "C:" . $s);
3769 }
3770
3771 # Check for any sort of function declaration.
3772 # int foo(something bar, other baz);
3773 # void (*store_gdt)(x86_descr_ptr *);
3774 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3775 my ($name_len) = length($1);
3776
3777 my $ctx = $s;
3778 substr($ctx, 0, $name_len + 1, '');
3779 $ctx =~ s/\)[^\)]*$//;
3780
3781 for my $arg (split(/\s*,\s*/, $ctx)) {
3782 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3783
3784 possible($1, "D:" . $s);
3785 }
3786 }
3787 }
3788
3789 }
3790
3791#
3792# Checks which may be anchored in the context.
3793#
3794
3795# Check for switch () and associated case and default
3796# statements should be at the same indent.
3797 if ($line=~/\bswitch\s*\(.*\)/) {
3798 my $err = '';
3799 my $sep = '';
3800 my @ctx = ctx_block_outer($linenr, $realcnt);
3801 shift(@ctx);
3802 for my $ctx (@ctx) {
3803 my ($clen, $cindent) = line_stats($ctx);
3804 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3805 $indent != $cindent) {
3806 $err .= "$sep$ctx\n";
3807 $sep = '';
3808 } else {
3809 $sep = "[...]\n";
3810 }
3811 }
3812 if ($err ne '') {
3813 ERROR("SWITCH_CASE_INDENT_LEVEL",
3814 "switch and case should be at the same indent\n$hereline$err");
3815 }
3816 }
3817
3818# if/while/etc brace do not go on next line, unless defining a do while loop,
3819# or if that brace on the next line is for something else
3820 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3821 my $pre_ctx = "$1$2";
3822
3823 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3824
3825 if ($line =~ /^\+\t{6,}/) {
3826 WARN("DEEP_INDENTATION",
3827 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3828 }
3829
3830 my $ctx_cnt = $realcnt - $#ctx - 1;
3831 my $ctx = join("\n", @ctx);
3832
3833 my $ctx_ln = $linenr;
3834 my $ctx_skip = $realcnt;
3835
3836 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3837 defined $lines[$ctx_ln - 1] &&
3838 $lines[$ctx_ln - 1] =~ /^-/)) {
3839 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3840 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3841 $ctx_ln++;
3842 }
3843
3844 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3845 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3846
3847 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3848 ERROR("OPEN_BRACE",
3849 "that open brace { should be on the previous line\n" .
3850 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3851 }
3852 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3853 $ctx =~ /\)\s*\;\s*$/ &&
3854 defined $lines[$ctx_ln - 1])
3855 {
3856 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3857 if ($nindent > $indent) {
3858 WARN("TRAILING_SEMICOLON",
3859 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3860 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3861 }
3862 }
3863 }
3864
3865# Check relative indent for conditionals and blocks.
Martin Roth387dec82017-09-17 19:20:46 -06003866 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003867 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3868 ctx_statement_block($linenr, $realcnt, 0)
3869 if (!defined $stat);
3870 my ($s, $c) = ($stat, $cond);
3871
3872 substr($s, 0, length($c), '');
3873
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003874 # remove inline comments
3875 $s =~ s/$;/ /g;
3876 $c =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003877
3878 # Find out how long the conditional actually is.
3879 my @newlines = ($c =~ /\n/gs);
3880 my $cond_lines = 1 + $#newlines;
3881
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003882 # Make sure we remove the line prefixes as we have
3883 # none on the first line, and are going to readd them
3884 # where necessary.
3885 $s =~ s/\n./\n/gs;
3886 while ($s =~ /\n\s+\\\n/) {
3887 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3888 }
3889
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003890 # We want to check the first line inside the block
3891 # starting at the end of the conditional, so remove:
3892 # 1) any blank line termination
3893 # 2) any opening brace { on end of the line
3894 # 3) any do (...) {
3895 my $continuation = 0;
3896 my $check = 0;
3897 $s =~ s/^.*\bdo\b//;
3898 $s =~ s/^\s*{//;
3899 if ($s =~ s/^\s*\\//) {
3900 $continuation = 1;
3901 }
3902 if ($s =~ s/^\s*?\n//) {
3903 $check = 1;
3904 $cond_lines++;
3905 }
3906
3907 # Also ignore a loop construct at the end of a
3908 # preprocessor statement.
3909 if (($prevline =~ /^.\s*#\s*define\s/ ||
3910 $prevline =~ /\\\s*$/) && $continuation == 0) {
3911 $check = 0;
3912 }
3913
3914 my $cond_ptr = -1;
3915 $continuation = 0;
3916 while ($cond_ptr != $cond_lines) {
3917 $cond_ptr = $cond_lines;
3918
3919 # If we see an #else/#elif then the code
3920 # is not linear.
3921 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3922 $check = 0;
3923 }
3924
3925 # Ignore:
3926 # 1) blank lines, they should be at 0,
3927 # 2) preprocessor lines, and
3928 # 3) labels.
3929 if ($continuation ||
3930 $s =~ /^\s*?\n/ ||
3931 $s =~ /^\s*#\s*?/ ||
3932 $s =~ /^\s*$Ident\s*:/) {
3933 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3934 if ($s =~ s/^.*?\n//) {
3935 $cond_lines++;
3936 }
3937 }
3938 }
3939
3940 my (undef, $sindent) = line_stats("+" . $s);
3941 my $stat_real = raw_line($linenr, $cond_lines);
3942
3943 # Check if either of these lines are modified, else
3944 # this is not this patch's fault.
3945 if (!defined($stat_real) ||
3946 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3947 $check = 0;
3948 }
3949 if (defined($stat_real) && $cond_lines > 1) {
3950 $stat_real = "[...]\n$stat_real";
3951 }
3952
3953 #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";
3954
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003955 if ($check && $s ne '' &&
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003956 (($sindent % $tabsize) != 0 ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003957 ($sindent < $indent) ||
Martin Roth387dec82017-09-17 19:20:46 -06003958 ($sindent == $indent &&
3959 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003960 ($sindent > $indent + $tabsize))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003961 WARN("SUSPECT_CODE_INDENT",
3962 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3963 }
Julius Werner218906d2021-03-25 21:12:49 -07003964
3965# Also check if the next statement after the previous condition has the same indent
3966 my ($stat_next, undef, $line_nr_next_next) =
3967 ctx_statement_block($line_nr_next, $remain_next, $off_next);
3968 my $s_next = $stat_next;
3969
3970 # Remove line prefixes
3971 $s_next =~ s/\n./\n/g;
3972
3973 # Remove any comments
3974 $s_next =~ s/$;//g;
3975
3976 # Remove any leading labels
3977 $s_next =~ s/\n( ?$Ident:)/"\n" . " " x length($1)/eg;
3978
3979 # Skip this check for in case next statement starts with 'else'
3980 if ($s_next !~ /\belse\b/) {
3981
3982 # Remove while that belongs to a do {} while
3983 if ($stat =~ /\bdo\b/) {
3984 $s_next =~ s/^.*\bwhile\b\s*($balanced_parens)\s*?//;
3985 }
3986
3987 # Remove blank lines
3988 $s_next =~ s/\s*\\?\n//g;
3989
3990 # Get the real next lines
3991 my $next_nof_lines = $line_nr_next_next - $line_nr_next;
3992 my $stat_next_real = raw_line($line_nr_next, $next_nof_lines);
3993 if (!defined($stat_next_real)) {
3994 $stat_next_real = "";
3995 } elsif ($next_nof_lines > 1) {
3996 $stat_next_real = "[...]\n$stat_next_real";
3997 }
3998 my (undef, $nindent) = line_stats('+' . $s_next);
3999
4000 #print "stat_next<$stat_next> stat<$stat> indent<$indent> nindent<$nindent> s_next<$s_next> stat_next_real<$stat_next_real>\n";
4001
4002 if ($nindent > $indent) {
4003 WARN("SUSPICIOUS_CODE_INDENT",
4004 "suspicious code indentation after conditional statements\n" .
4005 $herecurr . "$stat_real\n$stat_next_real\n");
4006 }
4007 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004008 }
4009
4010 # Track the 'values' across context and added lines.
4011 my $opline = $line; $opline =~ s/^./ /;
4012 my ($curr_values, $curr_vars) =
4013 annotate_values($opline . "\n", $prev_values);
4014 $curr_values = $prev_values . $curr_values;
4015 if ($dbg_values) {
4016 my $outline = $opline; $outline =~ s/\t/ /g;
4017 print "$linenr > .$outline\n";
4018 print "$linenr > $curr_values\n";
4019 print "$linenr > $curr_vars\n";
4020 }
4021 $prev_values = substr($curr_values, -1);
4022
4023#ignore lines not being added
4024 next if ($line =~ /^[^\+]/);
4025
Elyes Haouasf9a3554a2022-07-13 18:03:47 +02004026# check for self assignments used to avoid compiler warnings
4027# e.g.: int foo = foo, *bar = NULL;
4028# struct foo bar = *(&(bar));
4029 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4030 my $var = $1;
4031 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4032 WARN("SELF_ASSIGNMENT",
4033 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4034 }
4035 }
4036
Martin Rothedd591d2017-03-14 10:16:29 -06004037# check for dereferences that span multiple lines
4038 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4039 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4040 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4041 my $ref = $1;
4042 $line =~ /^.\s*($Lval)/;
4043 $ref .= $1;
4044 $ref =~ s/\s//g;
4045 WARN("MULTILINE_DEREFERENCE",
4046 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4047 }
4048
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004049# check for declarations of signed or unsigned without int
Martin Rothedd591d2017-03-14 10:16:29 -06004050 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004051 my $type = $1;
4052 my $var = $2;
4053 $var = "" if (!defined $var);
4054 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4055 my $sign = $1;
4056 my $pointer = $2;
4057
4058 $pointer = "" if (!defined $pointer);
4059
4060 if (WARN("UNSPECIFIED_INT",
4061 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4062 $fix) {
4063 my $decl = trim($sign) . " int ";
4064 my $comp_pointer = $pointer;
4065 $comp_pointer =~ s/\s//g;
4066 $decl .= $comp_pointer;
4067 $decl = rtrim($decl) if ($var eq "");
4068 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4069 }
4070 }
4071 }
4072
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004073# TEST: allow direct testing of the type matcher.
4074 if ($dbg_type) {
4075 if ($line =~ /^.\s*$Declare\s*$/) {
4076 ERROR("TEST_TYPE",
4077 "TEST: is type\n" . $herecurr);
4078 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4079 ERROR("TEST_NOT_TYPE",
4080 "TEST: is not type ($1 is)\n". $herecurr);
4081 }
4082 next;
4083 }
4084# TEST: allow direct testing of the attribute matcher.
4085 if ($dbg_attr) {
4086 if ($line =~ /^.\s*$Modifier\s*$/) {
4087 ERROR("TEST_ATTR",
4088 "TEST: is attr\n" . $herecurr);
4089 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4090 ERROR("TEST_NOT_ATTR",
4091 "TEST: is not attr ($1 is)\n". $herecurr);
4092 }
4093 next;
4094 }
4095
4096# check for initialisation to aggregates open brace on the next line
4097 if ($line =~ /^.\s*{/ &&
4098 $prevline =~ /(?:^|[^=])=\s*$/) {
4099 if (ERROR("OPEN_BRACE",
4100 "that open brace { should be on the previous line\n" . $hereprev) &&
4101 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4102 fix_delete_line($fixlinenr - 1, $prevrawline);
4103 fix_delete_line($fixlinenr, $rawline);
4104 my $fixedline = $prevrawline;
4105 $fixedline =~ s/\s*=\s*$/ = {/;
4106 fix_insert_line($fixlinenr, $fixedline);
4107 $fixedline = $line;
Martin Roth387dec82017-09-17 19:20:46 -06004108 $fixedline =~ s/^(.\s*)\{\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004109 fix_insert_line($fixlinenr, $fixedline);
4110 }
4111 }
4112
4113#
4114# Checks which are anchored on the added line.
4115#
4116
4117# check for malformed paths in #include statements (uses RAW line)
4118 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4119 my $path = $1;
4120 if ($path =~ m{//}) {
4121 ERROR("MALFORMED_INCLUDE",
4122 "malformed #include filename\n" . $herecurr);
4123 }
4124 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4125 ERROR("UAPI_INCLUDE",
4126 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4127 }
4128 }
4129
4130# no C99 // comments
4131 if ($line =~ m{//}) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004132 if (ERROR("C99_COMMENTS",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004133 "do not use C99 // comments\n" . $herecurr) &&
4134 $fix) {
4135 my $line = $fixed[$fixlinenr];
4136 if ($line =~ /\/\/(.*)$/) {
4137 my $comment = trim($1);
4138 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4139 }
4140 }
4141 }
4142 # Remove C99 comments.
4143 $line =~ s@//.*@@;
4144 $opline =~ s@//.*@@;
4145
4146# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4147# the whole statement.
4148#print "APW <$lines[$realline_next - 1]>\n";
4149 if (defined $realline_next &&
4150 exists $lines[$realline_next - 1] &&
4151 !defined $suppress_export{$realline_next} &&
4152 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4153 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4154 # Handle definitions which produce identifiers with
4155 # a prefix:
4156 # XXX(foo);
4157 # EXPORT_SYMBOL(something_foo);
4158 my $name = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004159 $name =~ s/^\s*($Ident).*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004160 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4161 $name =~ /^${Ident}_$2/) {
4162#print "FOO C name<$name>\n";
4163 $suppress_export{$realline_next} = 1;
4164
4165 } elsif ($stat !~ /(?:
4166 \n.}\s*$|
4167 ^.DEFINE_$Ident\(\Q$name\E\)|
4168 ^.DECLARE_$Ident\(\Q$name\E\)|
4169 ^.LIST_HEAD\(\Q$name\E\)|
4170 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4171 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4172 )/x) {
4173#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4174 $suppress_export{$realline_next} = 2;
4175 } else {
4176 $suppress_export{$realline_next} = 1;
4177 }
4178 }
4179 if (!defined $suppress_export{$linenr} &&
4180 $prevline =~ /^.\s*$/ &&
4181 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4182 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4183#print "FOO B <$lines[$linenr - 1]>\n";
4184 $suppress_export{$linenr} = 2;
4185 }
4186 if (defined $suppress_export{$linenr} &&
4187 $suppress_export{$linenr} == 2) {
4188 WARN("EXPORT_SYMBOL",
4189 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4190 }
4191
4192# check for global initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004193 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004194 if (ERROR("GLOBAL_INITIALISERS",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004195 "do not initialise globals to $1\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004196 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004197 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004198 }
4199 }
4200# check for static initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004201 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004202 if (ERROR("INITIALISED_STATIC",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004203 "do not initialise statics to $1\n" .
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004204 $herecurr) &&
4205 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004206 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004207 }
4208 }
4209
4210# check for misordered declarations of char/short/int/long with signed/unsigned
4211 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4212 my $tmp = trim($1);
4213 WARN("MISORDERED_TYPE",
4214 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4215 }
4216
4217# check for static const char * arrays.
4218 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4219 WARN("STATIC_CONST_CHAR_ARRAY",
4220 "static const char * array should probably be static const char * const\n" .
4221 $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02004222 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004223
Elyes Haouasdcb59dc2023-08-01 18:18:32 +02004224# check for initialized const char arrays that should be static const
4225 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4226 if (WARN("STATIC_CONST_CHAR_ARRAY",
4227 "const array should probably be static const\n" . $herecurr) &&
4228 $fix) {
4229 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4230 }
4231 }
4232
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004233# check for static char foo[] = "bar" declarations.
4234 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4235 WARN("STATIC_CONST_CHAR_ARRAY",
4236 "static char array declaration should probably be static const char\n" .
4237 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004238 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004239
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004240# check for const <foo> const where <foo> is not a pointer or array type
4241 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4242 my $found = $1;
4243 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4244 WARN("CONST_CONST",
4245 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4246 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4247 WARN("CONST_CONST",
4248 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4249 }
4250 }
4251
Elyes Haouase5727652023-08-01 18:21:26 +02004252# check for const static or static <non ptr type> const declarations
4253# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4254 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4255 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4256 if (WARN("STATIC_CONST",
4257 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4258 $fix) {
4259 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4260 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4261 }
4262 }
4263
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004264# check for non-global char *foo[] = {"bar", ...} declarations.
4265 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4266 WARN("STATIC_CONST_CHAR_ARRAY",
4267 "char * array declaration might be better as static const\n" .
4268 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004269 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004270
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004271# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4272 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4273 my $array = $1;
4274 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4275 my $array_div = $1;
4276 if (WARN("ARRAY_SIZE",
4277 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4278 $fix) {
4279 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4280 }
4281 }
4282 }
4283
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004284# check for function declarations without arguments like "int foo()"
Elyes Haouas26e0b942022-05-22 11:11:11 +02004285 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004286 if (ERROR("FUNCTION_WITHOUT_ARGS",
4287 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4288 $fix) {
4289 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4290 }
4291 }
4292
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004293# check for new typedefs, only function parameters and sparse annotations
4294# make sense.
4295 if ($line =~ /\btypedef\s/ &&
4296 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4297 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4298 $line !~ /\b$typeTypedefs\b/ &&
Martin Rothedd591d2017-03-14 10:16:29 -06004299 $line !~ /\b__bitwise\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004300 WARN("NEW_TYPEDEFS",
4301 "do not add new typedefs\n" . $herecurr);
4302 }
4303
4304# * goes on variable not on type
4305 # (char*[ const])
4306 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4307 #print "AA<$1>\n";
4308 my ($ident, $from, $to) = ($1, $2, $2);
4309
4310 # Should start with a space.
4311 $to =~ s/^(\S)/ $1/;
4312 # Should not end with a space.
4313 $to =~ s/\s+$//;
4314 # '*'s should not have spaces between.
4315 while ($to =~ s/\*\s+\*/\*\*/) {
4316 }
4317
4318## print "1: from<$from> to<$to> ident<$ident>\n";
4319 if ($from ne $to) {
4320 if (ERROR("POINTER_LOCATION",
4321 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4322 $fix) {
4323 my $sub_from = $ident;
4324 my $sub_to = $ident;
4325 $sub_to =~ s/\Q$from\E/$to/;
4326 $fixed[$fixlinenr] =~
4327 s@\Q$sub_from\E@$sub_to@;
4328 }
4329 }
4330 }
4331 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4332 #print "BB<$1>\n";
4333 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4334
4335 # Should start with a space.
4336 $to =~ s/^(\S)/ $1/;
4337 # Should not end with a space.
4338 $to =~ s/\s+$//;
4339 # '*'s should not have spaces between.
4340 while ($to =~ s/\*\s+\*/\*\*/) {
4341 }
4342 # Modifiers should have spaces.
4343 $to =~ s/(\b$Modifier$)/$1 /;
4344
4345## print "2: from<$from> to<$to> ident<$ident>\n";
4346 if ($from ne $to && $ident !~ /^$Modifier$/) {
4347 if (ERROR("POINTER_LOCATION",
4348 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4349 $fix) {
4350
4351 my $sub_from = $match;
4352 my $sub_to = $match;
4353 $sub_to =~ s/\Q$from\E/$to/;
4354 $fixed[$fixlinenr] =~
4355 s@\Q$sub_from\E@$sub_to@;
4356 }
4357 }
4358 }
4359
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004360# avoid BUG() or BUG_ON()
4361 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
Martin Roth387dec82017-09-17 19:20:46 -06004362 my $msg_level = \&WARN;
4363 $msg_level = \&CHK if ($file);
4364 &{$msg_level}("AVOID_BUG",
4365 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004366 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004367
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004368# avoid LINUX_VERSION_CODE
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004369 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4370 WARN("LINUX_VERSION_CODE",
4371 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4372 }
4373
4374# check for uses of printk_ratelimit
4375 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4376 WARN("PRINTK_RATELIMITED",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004377 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004378 }
4379
Martin Roth60915b32018-08-10 21:04:05 -06004380# printk should use KERN_* levels
4381 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4382 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4383 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004384 }
4385
4386 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4387 my $orig = $1;
4388 my $level = lc($orig);
4389 $level = "warn" if ($level eq "warning");
4390 my $level2 = $level;
4391 $level2 = "dbg" if ($level eq "debug");
4392 WARN("PREFER_PR_LEVEL",
4393 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4394 }
4395
4396 if ($line =~ /\bpr_warning\s*\(/) {
4397 if (WARN("PREFER_PR_LEVEL",
4398 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4399 $fix) {
4400 $fixed[$fixlinenr] =~
4401 s/\bpr_warning\b/pr_warn/;
4402 }
4403 }
4404
4405 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4406 my $orig = $1;
4407 my $level = lc($orig);
4408 $level = "warn" if ($level eq "warning");
4409 $level = "dbg" if ($level eq "debug");
4410 WARN("PREFER_DEV_LEVEL",
4411 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4412 }
4413
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004414# ENOSYS means "bad syscall nr" and nothing else. This will have a small
4415# number of false positives, but assembly files are not checked, so at
4416# least the arch entry code will not trigger this warning.
4417 if ($line =~ /\bENOSYS\b/) {
4418 WARN("ENOSYS",
4419 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4420 }
4421
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004422# function brace can't be on same line, except for #defines of do while,
4423# or if closed on same line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004424 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06004425 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4426 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4427 $sline !~ /}/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004428 if (ERROR("OPEN_BRACE",
Martin Roth60915b32018-08-10 21:04:05 -06004429 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004430 $fix) {
4431 fix_delete_line($fixlinenr, $rawline);
4432 my $fixed_line = $rawline;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004433 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004434 my $line1 = $1;
4435 my $line2 = $2;
4436 fix_insert_line($fixlinenr, ltrim($line1));
4437 fix_insert_line($fixlinenr, "\+{");
4438 if ($line2 !~ /^\s*$/) {
4439 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4440 }
4441 }
4442 }
4443
4444# open braces for enum, union and struct go on the same line.
4445 if ($line =~ /^.\s*{/ &&
4446 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4447 if (ERROR("OPEN_BRACE",
4448 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4449 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4450 fix_delete_line($fixlinenr - 1, $prevrawline);
4451 fix_delete_line($fixlinenr, $rawline);
4452 my $fixedline = rtrim($prevrawline) . " {";
4453 fix_insert_line($fixlinenr, $fixedline);
4454 $fixedline = $rawline;
Martin Roth387dec82017-09-17 19:20:46 -06004455 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004456 if ($fixedline !~ /^\+\s*$/) {
4457 fix_insert_line($fixlinenr, $fixedline);
4458 }
4459 }
4460 }
4461
4462# missing space after union, struct or enum definition
4463 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4464 if (WARN("SPACING",
4465 "missing space after $1 definition\n" . $herecurr) &&
4466 $fix) {
4467 $fixed[$fixlinenr] =~
4468 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4469 }
4470 }
4471
4472# Function pointer declarations
4473# check spacing between type, funcptr, and args
4474# canonical declaration is "type (*funcptr)(args...)"
4475 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4476 my $declare = $1;
4477 my $pre_pointer_space = $2;
4478 my $post_pointer_space = $3;
4479 my $funcname = $4;
4480 my $post_funcname_space = $5;
4481 my $pre_args_space = $6;
4482
4483# the $Declare variable will capture all spaces after the type
4484# so check it for a missing trailing missing space but pointer return types
4485# don't need a space so don't warn for those.
4486 my $post_declare_space = "";
4487 if ($declare =~ /(\s+)$/) {
4488 $post_declare_space = $1;
4489 $declare = rtrim($declare);
4490 }
4491 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4492 WARN("SPACING",
4493 "missing space after return type\n" . $herecurr);
4494 $post_declare_space = " ";
4495 }
4496
4497# unnecessary space "type (*funcptr)(args...)"
4498# This test is not currently implemented because these declarations are
4499# equivalent to
4500# int foo(int bar, ...)
4501# and this is form shouldn't/doesn't generate a checkpatch warning.
4502#
4503# elsif ($declare =~ /\s{2,}$/) {
4504# WARN("SPACING",
4505# "Multiple spaces after return type\n" . $herecurr);
4506# }
4507
4508# unnecessary space "type ( *funcptr)(args...)"
4509 if (defined $pre_pointer_space &&
4510 $pre_pointer_space =~ /^\s/) {
4511 WARN("SPACING",
4512 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4513 }
4514
4515# unnecessary space "type (* funcptr)(args...)"
4516 if (defined $post_pointer_space &&
4517 $post_pointer_space =~ /^\s/) {
4518 WARN("SPACING",
4519 "Unnecessary space before function pointer name\n" . $herecurr);
4520 }
4521
4522# unnecessary space "type (*funcptr )(args...)"
4523 if (defined $post_funcname_space &&
4524 $post_funcname_space =~ /^\s/) {
4525 WARN("SPACING",
4526 "Unnecessary space after function pointer name\n" . $herecurr);
4527 }
4528
4529# unnecessary space "type (*funcptr) (args...)"
4530 if (defined $pre_args_space &&
4531 $pre_args_space =~ /^\s/) {
4532 WARN("SPACING",
4533 "Unnecessary space before function pointer arguments\n" . $herecurr);
4534 }
4535
4536 if (show_type("SPACING") && $fix) {
4537 $fixed[$fixlinenr] =~
4538 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4539 }
4540 }
4541
4542# check for spacing round square brackets; allowed:
4543# 1. with a type on the left -- int [] a;
4544# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4545# 3. inside a curly brace -- = { [0...10] = 5 }
Martin Rothedd591d2017-03-14 10:16:29 -06004546# 4. in an extended asm instruction -- : [r0]"r"(r0) (coreboot)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004547 while ($line =~ /(.*?\s)\[/g) {
4548 my ($where, $prefix) = ($-[1], $1);
4549 if ($prefix !~ /$Type\s+$/ &&
4550 ($where != 0 || $prefix !~ /^.\s+$/) &&
Martin Rothedd591d2017-03-14 10:16:29 -06004551 $prefix !~ /[{,:]\s+$/) { #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004552 if (ERROR("BRACKET_SPACE",
4553 "space prohibited before open square bracket '['\n" . $herecurr) &&
4554 $fix) {
4555 $fixed[$fixlinenr] =~
4556 s/^(\+.*?)\s+\[/$1\[/;
4557 }
4558 }
4559 }
4560
4561# check for spaces between functions and their parentheses.
4562 while ($line =~ /($Ident)\s+\(/g) {
4563 my $name = $1;
4564 my $ctx_before = substr($line, 0, $-[1]);
4565 my $ctx = "$ctx_before$name";
4566
4567 # Ignore those directives where spaces _are_ permitted.
4568 if ($name =~ /^(?:
4569 if|for|while|switch|return|case|
4570 volatile|__volatile__|
4571 __attribute__|format|__extension__|
4572 asm|__asm__)$/x)
4573 {
4574 # cpp #define statements have non-optional spaces, ie
4575 # if there is a space between the name and the open
4576 # parenthesis it is simply not a parameter group.
4577 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4578
4579 # cpp #elif statement condition may start with a (
4580 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4581
4582 # If this whole things ends with a type its most
4583 # likely a typedef for a function.
4584 } elsif ($ctx =~ /$Type$/) {
4585
4586 } else {
4587 if (WARN("SPACING",
4588 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4589 $fix) {
4590 $fixed[$fixlinenr] =~
4591 s/\b$name\s+\(/$name\(/;
4592 }
4593 }
4594 }
4595
4596# Check operator spacing.
4597 if (!($line=~/\#\s*include/)) {
4598 my $fixed_line = "";
4599 my $line_fixed = 0;
4600
4601 my $ops = qr{
4602 <<=|>>=|<=|>=|==|!=|
4603 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4604 =>|->|<<|>>|<|>|=|!|~|
4605 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4606 \?:|\?|:
4607 }x;
4608 my @elements = split(/($ops|;)/, $opline);
4609
4610## print("element count: <" . $#elements . ">\n");
4611## foreach my $el (@elements) {
4612## print("el: <$el>\n");
4613## }
4614
4615 my @fix_elements = ();
4616 my $off = 0;
4617
4618 foreach my $el (@elements) {
4619 push(@fix_elements, substr($rawline, $off, length($el)));
4620 $off += length($el);
4621 }
4622
4623 $off = 0;
4624
4625 my $blank = copy_spacing($opline);
4626 my $last_after = -1;
4627
4628 for (my $n = 0; $n < $#elements; $n += 2) {
4629
4630 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4631
4632## print("n: <$n> good: <$good>\n");
4633
4634 $off += length($elements[$n]);
4635
4636 # Pick up the preceding and succeeding characters.
4637 my $ca = substr($opline, 0, $off);
4638 my $cc = '';
4639 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4640 $cc = substr($opline, $off + length($elements[$n + 1]));
4641 }
4642 my $cb = "$ca$;$cc";
4643
4644 my $a = '';
4645 $a = 'V' if ($elements[$n] ne '');
4646 $a = 'W' if ($elements[$n] =~ /\s$/);
4647 $a = 'C' if ($elements[$n] =~ /$;$/);
4648 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4649 $a = 'O' if ($elements[$n] eq '');
4650 $a = 'E' if ($ca =~ /^\s*$/);
4651
4652 my $op = $elements[$n + 1];
4653
4654 my $c = '';
4655 if (defined $elements[$n + 2]) {
4656 $c = 'V' if ($elements[$n + 2] ne '');
4657 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4658 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4659 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4660 $c = 'O' if ($elements[$n + 2] eq '');
4661 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4662 } else {
4663 $c = 'E';
4664 }
4665
4666 my $ctx = "${a}x${c}";
4667
4668 my $at = "(ctx:$ctx)";
4669
4670 my $ptr = substr($blank, 0, $off) . "^";
4671 my $hereptr = "$hereline$ptr\n";
4672
4673 # Pull out the value of this operator.
4674 my $op_type = substr($curr_values, $off + 1, 1);
4675
4676 # Get the full operator variant.
4677 my $opv = $op . substr($curr_vars, $off, 1);
4678
4679 # Ignore operators passed as parameters.
4680 if ($op_type ne 'V' &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004681 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004682
4683# # Ignore comments
4684# } elsif ($op =~ /^$;+$/) {
4685
4686 # ; should have either the end of line or a space or \ after it
4687 } elsif ($op eq ';') {
4688 if ($ctx !~ /.x[WEBC]/ &&
4689 $cc !~ /^\\/ && $cc !~ /^;/) {
4690 if (ERROR("SPACING",
4691 "space required after that '$op' $at\n" . $hereptr)) {
4692 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4693 $line_fixed = 1;
4694 }
4695 }
4696
4697 # // is a comment
4698 } elsif ($op eq '//') {
4699
4700 # : when part of a bitfield
4701 } elsif ($opv eq ':B') {
4702 # skip the bitfield test for now
4703
4704 # No spaces for:
4705 # ->
4706 } elsif ($op eq '->') {
4707 if ($ctx =~ /Wx.|.xW/) {
4708 if (ERROR("SPACING",
4709 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4710 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4711 if (defined $fix_elements[$n + 2]) {
4712 $fix_elements[$n + 2] =~ s/^\s+//;
4713 }
4714 $line_fixed = 1;
4715 }
4716 }
4717
4718 # , must not have a space before and must have a space on the right.
4719 } elsif ($op eq ',') {
4720 my $rtrim_before = 0;
4721 my $space_after = 0;
4722 if ($ctx =~ /Wx./) {
4723 if (ERROR("SPACING",
4724 "space prohibited before that '$op' $at\n" . $hereptr)) {
4725 $line_fixed = 1;
4726 $rtrim_before = 1;
4727 }
4728 }
4729 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4730 if (ERROR("SPACING",
4731 "space required after that '$op' $at\n" . $hereptr)) {
4732 $line_fixed = 1;
4733 $last_after = $n;
4734 $space_after = 1;
4735 }
4736 }
4737 if ($rtrim_before || $space_after) {
4738 if ($rtrim_before) {
4739 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4740 } else {
4741 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4742 }
4743 if ($space_after) {
4744 $good .= " ";
4745 }
4746 }
4747
4748 # '*' as part of a type definition -- reported already.
4749 } elsif ($opv eq '*_') {
4750 #warn "'*' is part of type\n";
4751
4752 # unary operators should have a space before and
4753 # none after. May be left adjacent to another
4754 # unary operator, or a cast
4755 } elsif ($op eq '!' || $op eq '~' ||
4756 $opv eq '*U' || $opv eq '-U' ||
4757 $opv eq '&U' || $opv eq '&&U') {
4758 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4759 if (ERROR("SPACING",
4760 "space required before that '$op' $at\n" . $hereptr)) {
4761 if ($n != $last_after + 2) {
4762 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4763 $line_fixed = 1;
4764 }
4765 }
4766 }
4767 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4768 # A unary '*' may be const
4769
4770 } elsif ($ctx =~ /.xW/) {
4771 if (ERROR("SPACING",
4772 "space prohibited after that '$op' $at\n" . $hereptr)) {
4773 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4774 if (defined $fix_elements[$n + 2]) {
4775 $fix_elements[$n + 2] =~ s/^\s+//;
4776 }
4777 $line_fixed = 1;
4778 }
4779 }
4780
4781 # unary ++ and unary -- are allowed no space on one side.
4782 } elsif ($op eq '++' or $op eq '--') {
4783 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4784 if (ERROR("SPACING",
4785 "space required one side of that '$op' $at\n" . $hereptr)) {
4786 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4787 $line_fixed = 1;
4788 }
4789 }
4790 if ($ctx =~ /Wx[BE]/ ||
4791 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4792 if (ERROR("SPACING",
4793 "space prohibited before that '$op' $at\n" . $hereptr)) {
4794 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4795 $line_fixed = 1;
4796 }
4797 }
4798 if ($ctx =~ /ExW/) {
4799 if (ERROR("SPACING",
4800 "space prohibited after that '$op' $at\n" . $hereptr)) {
4801 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4802 if (defined $fix_elements[$n + 2]) {
4803 $fix_elements[$n + 2] =~ s/^\s+//;
4804 }
4805 $line_fixed = 1;
4806 }
4807 }
4808
4809 # << and >> may either have or not have spaces both sides
4810 } elsif ($op eq '<<' or $op eq '>>' or
4811 $op eq '&' or $op eq '^' or $op eq '|' or
4812 $op eq '+' or $op eq '-' or
4813 $op eq '*' or $op eq '/' or
4814 $op eq '%')
4815 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004816 if ($check) {
4817 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4818 if (CHK("SPACING",
4819 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4820 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4821 $fix_elements[$n + 2] =~ s/^\s+//;
4822 $line_fixed = 1;
4823 }
4824 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4825 if (CHK("SPACING",
4826 "space preferred before that '$op' $at\n" . $hereptr)) {
4827 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4828 $line_fixed = 1;
4829 }
4830 }
4831 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004832 if (ERROR("SPACING",
4833 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4834 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4835 if (defined $fix_elements[$n + 2]) {
4836 $fix_elements[$n + 2] =~ s/^\s+//;
4837 }
4838 $line_fixed = 1;
4839 }
4840 }
4841
4842 # A colon needs no spaces before when it is
4843 # terminating a case value or a label.
4844 } elsif ($opv eq ':C' || $opv eq ':L') {
4845 if ($ctx =~ /Wx./) {
4846 if (ERROR("SPACING",
4847 "space prohibited before that '$op' $at\n" . $hereptr)) {
4848 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4849 $line_fixed = 1;
4850 }
4851 }
4852
4853 # All the others need spaces both sides.
4854 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4855 my $ok = 0;
4856
4857 # Ignore email addresses <foo@bar>
4858 if (($op eq '<' &&
4859 $cc =~ /^\S+\@\S+>/) ||
4860 ($op eq '>' &&
4861 $ca =~ /<\S+\@\S+$/))
4862 {
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004863 $ok = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004864 }
4865
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004866 # for asm volatile statements
4867 # ignore a colon with another
4868 # colon immediately before or after
4869 if (($op eq ':') &&
4870 ($ca =~ /:$/ || $cc =~ /^:/)) {
4871 $ok = 1;
4872 }
4873
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004874 # messages are ERROR, but ?: are CHK
4875 if ($ok == 0) {
Martin Roth387dec82017-09-17 19:20:46 -06004876 my $msg_level = \&ERROR;
4877 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004878
Martin Roth387dec82017-09-17 19:20:46 -06004879 if (&{$msg_level}("SPACING",
4880 "spaces required around that '$op' $at\n" . $hereptr)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004881 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4882 if (defined $fix_elements[$n + 2]) {
4883 $fix_elements[$n + 2] =~ s/^\s+//;
4884 }
4885 $line_fixed = 1;
4886 }
4887 }
4888 }
4889 $off += length($elements[$n + 1]);
4890
4891## print("n: <$n> GOOD: <$good>\n");
4892
4893 $fixed_line = $fixed_line . $good;
4894 }
4895
4896 if (($#elements % 2) == 0) {
4897 $fixed_line = $fixed_line . $fix_elements[$#elements];
4898 }
4899
4900 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4901 $fixed[$fixlinenr] = $fixed_line;
4902 }
4903
4904
4905 }
4906
4907# check for whitespace before a non-naked semicolon
4908 if ($line =~ /^\+.*\S\s+;\s*$/) {
4909 if (WARN("SPACING",
4910 "space prohibited before semicolon\n" . $herecurr) &&
4911 $fix) {
4912 1 while $fixed[$fixlinenr] =~
4913 s/^(\+.*\S)\s+;/$1;/;
4914 }
4915 }
4916
4917# check for multiple assignments
4918 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4919 CHK("MULTIPLE_ASSIGNMENTS",
4920 "multiple assignments should be avoided\n" . $herecurr);
4921 }
4922
4923## # check for multiple declarations, allowing for a function declaration
4924## # continuation.
4925## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4926## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4927##
4928## # Remove any bracketed sections to ensure we do not
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004929## # falsely report the parameters of functions.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004930## my $ln = $line;
4931## while ($ln =~ s/\([^\(\)]*\)//g) {
4932## }
4933## if ($ln =~ /,/) {
4934## WARN("MULTIPLE_DECLARATION",
4935## "declaring multiple variables together should be avoided\n" . $herecurr);
4936## }
4937## }
4938
4939#need space before brace following if, while, etc
Alexander Couzensebef00f2016-04-11 00:52:01 +02004940 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
Elyes Haouas26e0b942022-05-22 11:11:11 +02004941 $line =~ /\b(?:else|do)\{/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004942 if (ERROR("SPACING",
4943 "space required before the open brace '{'\n" . $herecurr) &&
4944 $fix) {
Martin Roth387dec82017-09-17 19:20:46 -06004945 #coreboot - Open braces must be escaped in regex
Elyes Haouas26e0b942022-05-22 11:11:11 +02004946 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 \{/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004947 }
4948 }
4949
4950## # check for blank lines before declarations
4951## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4952## $prevrawline =~ /^.\s*$/) {
4953## WARN("SPACING",
4954## "No blank lines before declarations\n" . $hereprev);
4955## }
4956##
4957
4958# closing brace should have a space following it when it has anything
4959# on the line
Elyes Haouas26e0b942022-05-22 11:11:11 +02004960 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004961 if (ERROR("SPACING",
4962 "space required after that close brace '}'\n" . $herecurr) &&
4963 $fix) {
4964 $fixed[$fixlinenr] =~
4965 s/}((?!(?:,|;|\)))\S)/} $1/;
4966 }
4967 }
4968
4969# check spacing on square brackets
4970 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4971 if (ERROR("SPACING",
4972 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4973 $fix) {
4974 $fixed[$fixlinenr] =~
4975 s/\[\s+/\[/;
4976 }
4977 }
4978 if ($line =~ /\s\]/) {
4979 if (ERROR("SPACING",
4980 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4981 $fix) {
4982 $fixed[$fixlinenr] =~
4983 s/\s+\]/\]/;
4984 }
4985 }
4986
4987# check spacing on parentheses
4988 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4989 $line !~ /for\s*\(\s+;/) {
4990 if (ERROR("SPACING",
4991 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4992 $fix) {
4993 $fixed[$fixlinenr] =~
4994 s/\(\s+/\(/;
4995 }
4996 }
4997 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4998 $line !~ /for\s*\(.*;\s+\)/ &&
4999 $line !~ /:\s+\)/) {
5000 if (ERROR("SPACING",
5001 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5002 $fix) {
5003 $fixed[$fixlinenr] =~
5004 s/\s+\)/\)/;
5005 }
5006 }
5007
5008# check unnecessary parentheses around addressof/dereference single $Lvals
5009# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5010
5011 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5012 my $var = $1;
5013 if (CHK("UNNECESSARY_PARENTHESES",
5014 "Unnecessary parentheses around $var\n" . $herecurr) &&
5015 $fix) {
5016 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5017 }
5018 }
5019
5020# check for unnecessary parentheses around function pointer uses
5021# ie: (foo->bar)(); should be foo->bar();
5022# but not "if (foo->bar) (" to avoid some false positives
5023 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5024 my $var = $2;
5025 if (CHK("UNNECESSARY_PARENTHESES",
5026 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5027 $fix) {
5028 my $var2 = deparenthesize($var);
5029 $var2 =~ s/\s//g;
5030 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5031 }
5032 }
5033
Martin Roth387dec82017-09-17 19:20:46 -06005034# check for unnecessary parentheses around comparisons in if uses
Martin Roth60915b32018-08-10 21:04:05 -06005035# when !drivers/staging or command-line uses --strict
5036 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005037 $perl_version_ok && defined($stat) &&
Martin Roth387dec82017-09-17 19:20:46 -06005038 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5039 my $if_stat = $1;
5040 my $test = substr($2, 1, -1);
5041 my $herectx;
5042 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5043 my $match = $1;
5044 # avoid parentheses around potential macro args
5045 next if ($match =~ /^\s*\w+\s*$/);
5046 if (!defined($herectx)) {
5047 $herectx = $here . "\n";
5048 my $cnt = statement_rawlines($if_stat);
5049 for (my $n = 0; $n < $cnt; $n++) {
5050 my $rl = raw_line($linenr, $n);
5051 $herectx .= $rl . "\n";
5052 last if $rl =~ /^[ \+].*\{/;
5053 }
5054 }
5055 CHK("UNNECESSARY_PARENTHESES",
5056 "Unnecessary parentheses around '$match'\n" . $herectx);
5057 }
5058 }
5059
Elyes Haouas26e0b942022-05-22 11:11:11 +02005060# check that goto labels aren't indented (allow a single space indentation)
5061# and ignore bitfield definitions like foo:1
5062# Strictly, labels can have whitespace after the identifier and before the :
5063# but this is not allowed here as many ?: uses would appear to be labels
5064 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5065 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5066 $sline !~ /^.\s+default:/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005067 if (WARN("INDENTED_LABEL",
5068 "labels should not be indented\n" . $herecurr) &&
5069 $fix) {
5070 $fixed[$fixlinenr] =~
5071 s/^(.)\s+/$1/;
5072 }
5073 }
5074
Elyes Haouas50eef652022-07-13 18:07:58 +02005075# check if a statement with a comma should be two statements like:
5076# foo = bar(), /* comma should be semicolon */
5077# bar = baz();
5078 if (defined($stat) &&
5079 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5080 my $cnt = statement_rawlines($stat);
5081 my $herectx = get_stat_here($linenr, $cnt, $here);
5082 WARN("SUSPECT_COMMA_SEMICOLON",
5083 "Possible comma where semicolon could be used\n" . $herectx);
5084 }
5085
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005086# return is not a function
5087 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5088 my $spacing = $1;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005089 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005090 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5091 my $value = $1;
5092 $value = deparenthesize($value);
5093 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5094 ERROR("RETURN_PARENTHESES",
5095 "return is not a function, parentheses are not required\n" . $herecurr);
5096 }
5097 } elsif ($spacing !~ /\s+/) {
5098 ERROR("SPACING",
5099 "space required before the open parenthesis '('\n" . $herecurr);
5100 }
5101 }
5102
5103# unnecessary return in a void function
5104# at end-of-function, with the previous line a single leading tab, then return;
5105# and the line before that not a goto label target like "out:"
5106 if ($sline =~ /^[ \+]}\s*$/ &&
5107 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5108 $linenr >= 3 &&
5109 $lines[$linenr - 3] =~ /^[ +]/ &&
5110 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5111 WARN("RETURN_VOID",
5112 "void function return statements are not generally useful\n" . $hereprev);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005113 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005114
5115# if statements using unnecessary parentheses - ie: if ((foo == bar))
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005116 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005117 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5118 my $openparens = $1;
5119 my $count = $openparens =~ tr@\(@\(@;
5120 my $msg = "";
5121 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5122 my $comp = $4; #Not $1 because of $LvalOrFunc
5123 $msg = " - maybe == should be = ?" if ($comp eq "==");
5124 WARN("UNNECESSARY_PARENTHESES",
5125 "Unnecessary parentheses$msg\n" . $herecurr);
5126 }
5127 }
5128
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005129# comparisons with a constant or upper case identifier on the left
5130# avoid cases like "foo + BAR < baz"
5131# only fix matches surrounded by parentheses to avoid incorrect
5132# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005133 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005134 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5135 my $lead = $1;
5136 my $const = $2;
5137 my $comp = $3;
5138 my $to = $4;
5139 my $newcomp = $comp;
5140 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5141 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5142 WARN("CONSTANT_COMPARISON",
5143 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5144 $fix) {
5145 if ($comp eq "<") {
5146 $newcomp = ">";
5147 } elsif ($comp eq "<=") {
5148 $newcomp = ">=";
5149 } elsif ($comp eq ">") {
5150 $newcomp = "<";
5151 } elsif ($comp eq ">=") {
5152 $newcomp = "<=";
5153 }
5154 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5155 }
5156 }
5157
5158# Return of what appears to be an errno should normally be negative
5159 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005160 my $name = $1;
5161 if ($name ne 'EOF' && $name ne 'ERROR') {
5162 WARN("USE_NEGATIVE_ERRNO",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005163 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005164 }
5165 }
5166
5167# Need a space before open parenthesis after if, while etc
5168 if ($line =~ /\b(if|while|for|switch)\(/) {
5169 if (ERROR("SPACING",
5170 "space required before the open parenthesis '('\n" . $herecurr) &&
5171 $fix) {
5172 $fixed[$fixlinenr] =~
5173 s/\b(if|while|for|switch)\(/$1 \(/;
5174 }
5175 }
5176
5177# Check for illegal assignment in if conditional -- and check for trailing
5178# statements after the conditional.
5179 if ($line =~ /do\s*(?!{)/) {
5180 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5181 ctx_statement_block($linenr, $realcnt, 0)
5182 if (!defined $stat);
5183 my ($stat_next) = ctx_statement_block($line_nr_next,
5184 $remain_next, $off_next);
5185 $stat_next =~ s/\n./\n /g;
5186 ##print "stat<$stat> stat_next<$stat_next>\n";
5187
5188 if ($stat_next =~ /^\s*while\b/) {
5189 # If the statement carries leading newlines,
5190 # then count those as offsets.
5191 my ($whitespace) =
5192 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5193 my $offset =
5194 statement_rawlines($whitespace) - 1;
5195
5196 $suppress_whiletrailers{$line_nr_next +
5197 $offset} = 1;
5198 }
5199 }
5200 if (!defined $suppress_whiletrailers{$linenr} &&
5201 defined($stat) && defined($cond) &&
5202 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5203 my ($s, $c) = ($stat, $cond);
Elyes Haouasd2bb4852023-08-01 18:12:47 +02005204 my $fixed_assign_in_if = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005205
5206 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
Elyes Haouasd2bb4852023-08-01 18:12:47 +02005207 if (ERROR("ASSIGN_IN_IF",
5208 "do not use assignment in if condition\n" . $herecurr) &&
5209 $fix && $perl_version_ok) {
5210 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5211 my $space = $1;
5212 my $not = $2;
5213 my $statement = $3;
5214 my $assigned = $4;
5215 my $test = $8;
5216 my $against = $9;
5217 my $brace = $15;
5218 fix_delete_line($fixlinenr, $rawline);
5219 fix_insert_line($fixlinenr, "$space$statement;");
5220 my $newline = "${space}if (";
5221 $newline .= '!' if defined($not);
5222 $newline .= '(' if (defined $not && defined($test) && defined($against));
5223 $newline .= "$assigned";
5224 $newline .= " $test $against" if (defined($test) && defined($against));
5225 $newline .= ')' if (defined $not && defined($test) && defined($against));
5226 $newline .= ')';
5227 $newline .= " {" if (defined($brace));
5228 fix_insert_line($fixlinenr + 1, $newline);
5229 $fixed_assign_in_if = 1;
5230 }
5231 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005232 }
5233
5234 # Find out what is on the end of the line after the
5235 # conditional.
5236 substr($s, 0, length($c), '');
5237 $s =~ s/\n.*//g;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005238 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005239 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5240 $c !~ /}\s*while\s*/)
5241 {
5242 # Find out how long the conditional actually is.
5243 my @newlines = ($c =~ /\n/gs);
5244 my $cond_lines = 1 + $#newlines;
5245 my $stat_real = '';
5246
5247 $stat_real = raw_line($linenr, $cond_lines)
5248 . "\n" if ($cond_lines);
5249 if (defined($stat_real) && $cond_lines > 1) {
5250 $stat_real = "[...]\n$stat_real";
5251 }
5252
Elyes Haouas32cae132023-08-01 18:15:19 +02005253 if (ERROR("TRAILING_STATEMENTS",
5254 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5255 !$fixed_assign_in_if &&
5256 $cond_lines == 0 &&
5257 $fix && $perl_version_ok &&
5258 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5259 my $indent = $1;
5260 my $test = $2;
5261 my $rest = rtrim($4);
5262 if ($rest =~ /;$/) {
5263 $fixed[$fixlinenr] = "\+$indent$test";
5264 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5265 }
5266 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005267 }
5268 }
5269
5270# Check for bitwise tests written as boolean
5271 if ($line =~ /
5272 (?:
5273 (?:\[|\(|\&\&|\|\|)
5274 \s*0[xX][0-9]+\s*
5275 (?:\&\&|\|\|)
5276 |
5277 (?:\&\&|\|\|)
5278 \s*0[xX][0-9]+\s*
5279 (?:\&\&|\|\||\)|\])
5280 )/x)
5281 {
5282 WARN("HEXADECIMAL_BOOLEAN_TEST",
5283 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5284 }
5285
5286# if and else should not have general statements after it
5287 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5288 my $s = $1;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005289 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005290 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5291 ERROR("TRAILING_STATEMENTS",
5292 "trailing statements should be on next line\n" . $herecurr);
5293 }
5294 }
5295# if should not continue a brace
5296 if ($line =~ /}\s*if\b/) {
5297 ERROR("TRAILING_STATEMENTS",
5298 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5299 $herecurr);
5300 }
5301# case and default should not have general statements after them
5302 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5303 $line !~ /\G(?:
5304 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5305 \s*return\s+
5306 )/xg)
5307 {
5308 ERROR("TRAILING_STATEMENTS",
5309 "trailing statements should be on next line\n" . $herecurr);
5310 }
5311
5312 # Check for }<nl>else {, these must be at the same
5313 # indent level to be relevant to each other.
5314 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5315 $previndent == $indent) {
5316 if (ERROR("ELSE_AFTER_BRACE",
5317 "else should follow close brace '}'\n" . $hereprev) &&
5318 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5319 fix_delete_line($fixlinenr - 1, $prevrawline);
5320 fix_delete_line($fixlinenr, $rawline);
5321 my $fixedline = $prevrawline;
5322 $fixedline =~ s/}\s*$//;
5323 if ($fixedline !~ /^\+\s*$/) {
5324 fix_insert_line($fixlinenr, $fixedline);
5325 }
5326 $fixedline = $rawline;
5327 $fixedline =~ s/^(.\s*)else/$1} else/;
5328 fix_insert_line($fixlinenr, $fixedline);
5329 }
5330 }
5331
5332 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5333 $previndent == $indent) {
5334 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5335
5336 # Find out what is on the end of the line after the
5337 # conditional.
5338 substr($s, 0, length($c), '');
5339 $s =~ s/\n.*//g;
5340
5341 if ($s =~ /^\s*;/) {
5342 if (ERROR("WHILE_AFTER_BRACE",
5343 "while should follow close brace '}'\n" . $hereprev) &&
5344 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5345 fix_delete_line($fixlinenr - 1, $prevrawline);
5346 fix_delete_line($fixlinenr, $rawline);
5347 my $fixedline = $prevrawline;
5348 my $trailing = $rawline;
5349 $trailing =~ s/^\+//;
5350 $trailing = trim($trailing);
5351 $fixedline =~ s/}\s*$/} $trailing/;
5352 fix_insert_line($fixlinenr, $fixedline);
5353 }
5354 }
5355 }
5356
5357#Specific variable tests
5358 while ($line =~ m{($Constant|$Lval)}g) {
5359 my $var = $1;
5360
5361#gcc binary extension
5362 if ($var =~ /^$Binary$/) {
5363 if (WARN("GCC_BINARY_CONSTANT",
5364 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
5365 $fix) {
5366 my $hexval = sprintf("0x%x", oct($var));
5367 $fixed[$fixlinenr] =~
5368 s/\b$var\b/$hexval/;
5369 }
5370 }
5371
5372#CamelCase
5373 if ($var !~ /^$Constant$/ &&
5374 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5375#Ignore Page<foo> variants
5376 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02005377#Ignore SI style variants like nS, mV and dB
5378#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5379 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005380#Ignore some three character SI units explicitly, like MiB and KHz
5381 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
Elyes Haouas0d42db62022-09-05 11:24:00 +02005382 while ($var =~ m{\b($Ident)}g) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005383 my $word = $1;
5384 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5385 if ($check) {
5386 seed_camelcase_includes();
5387 if (!$file && !$camelcase_file_seeded) {
5388 seed_camelcase_file($realfile);
5389 $camelcase_file_seeded = 1;
5390 }
5391 }
5392 if (!defined $camelcase{$word}) {
5393 $camelcase{$word} = 1;
5394 CHK("CAMELCASE",
5395 "Avoid CamelCase: <$word>\n" . $herecurr);
5396 }
5397 }
5398 }
5399 }
5400
5401#no spaces allowed after \ in define
5402 if ($line =~ /\#\s*define.*\\\s+$/) {
5403 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5404 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5405 $fix) {
5406 $fixed[$fixlinenr] =~ s/\s+$//;
5407 }
5408 }
5409
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005410# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5411# itself <asm/foo.h> (uses RAW line)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005412 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5413 my $file = "$1.h";
5414 my $checkfile = "include/linux/$file";
5415 if (-f "$root/$checkfile" &&
5416 $realfile ne $checkfile &&
5417 $1 !~ /$allowed_asm_includes/)
5418 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005419 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5420 if ($asminclude > 0) {
5421 if ($realfile =~ m{^arch/}) {
5422 CHK("ARCH_INCLUDE_LINUX",
5423 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5424 } else {
5425 WARN("INCLUDE_LINUX",
5426 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5427 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005428 }
5429 }
5430 }
5431
5432# multi-statement macros should be enclosed in a do while loop, grab the
5433# first statement and ensure its the whole macro if its not enclosed
5434# in a known good container
5435 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5436 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5437 my $ln = $linenr;
5438 my $cnt = $realcnt;
5439 my ($off, $dstat, $dcond, $rest);
5440 my $ctx = '';
5441 my $has_flow_statement = 0;
5442 my $has_arg_concat = 0;
5443 ($dstat, $dcond, $ln, $cnt, $off) =
5444 ctx_statement_block($linenr, $realcnt, 0);
5445 $ctx = $dstat;
5446 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5447 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5448
5449 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005450 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005451
Martin Rothedd591d2017-03-14 10:16:29 -06005452 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5453 my $define_args = $1;
5454 my $define_stmt = $dstat;
5455 my @def_args = ();
5456
5457 if (defined $define_args && $define_args ne "") {
5458 $define_args = substr($define_args, 1, length($define_args) - 2);
5459 $define_args =~ s/\s*//g;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005460 $define_args =~ s/\\\+?//g;
Martin Rothedd591d2017-03-14 10:16:29 -06005461 @def_args = split(",", $define_args);
5462 }
5463
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005464 $dstat =~ s/$;//g;
5465 $dstat =~ s/\\\n.//g;
5466 $dstat =~ s/^\s*//s;
5467 $dstat =~ s/\s*$//s;
5468
5469 # Flatten any parentheses and braces
Elyes Haouas26e0b942022-05-22 11:11:11 +02005470 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5471 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5472 $dstat =~ s/.\[[^\[\]]*\]/1u/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005473 {
5474 }
5475
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005476 # Flatten any obvious string concatenation.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005477 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5478 $dstat =~ s/$Ident\s*($String)/$1/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005479 {
5480 }
5481
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005482 # Make asm volatile uses seem like a generic function
5483 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5484
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005485 my $exceptions = qr{
5486 $Declare|
5487 module_param_named|
5488 MODULE_PARM_DESC|
5489 DECLARE_PER_CPU|
5490 DEFINE_PER_CPU|
5491 __typeof__\(|
5492 union|
5493 struct|
5494 \.$Ident\s*=\s*|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005495 ^\"|\"$|
5496 ^\[
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005497 }x;
5498 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
Martin Rothedd591d2017-03-14 10:16:29 -06005499
5500 $ctx =~ s/\n*$//;
Martin Rothedd591d2017-03-14 10:16:29 -06005501 my $stmt_cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005502 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
Martin Rothedd591d2017-03-14 10:16:29 -06005503
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005504 if ($dstat ne '' &&
5505 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5506 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5507 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5508 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5509 $dstat !~ /$exceptions/ &&
5510 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5511 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5512 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
Elyes Haouas26e0b942022-05-22 11:11:11 +02005513 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005514 $dstat !~ /^for\s*$Constant$/ && # for (...)
5515 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
Martin Rothedd591d2017-03-14 10:16:29 -06005516 $dstat !~ /^do\s*{/ && # do {...
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005517 $dstat !~ /^\(\{/ && # ({...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005518 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5519 {
Martin Roth387dec82017-09-17 19:20:46 -06005520 if ($dstat =~ /^\s*if\b/) {
5521 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5522 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5523 } elsif ($dstat =~ /;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005524 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5525 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5526 } else {
5527 ERROR("COMPLEX_MACRO",
5528 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5529 }
Martin Rothedd591d2017-03-14 10:16:29 -06005530
5531 }
5532
5533 # Make $define_stmt single line, comment-free, etc
5534 my @stmt_array = split('\n', $define_stmt);
5535 my $first = 1;
5536 $define_stmt = "";
5537 foreach my $l (@stmt_array) {
5538 $l =~ s/\\$//;
5539 if ($first) {
5540 $define_stmt = $l;
5541 $first = 0;
5542 } elsif ($l =~ /^[\+ ]/) {
5543 $define_stmt .= substr($l, 1);
5544 }
5545 }
5546 $define_stmt =~ s/$;//g;
5547 $define_stmt =~ s/\s+/ /g;
5548 $define_stmt = trim($define_stmt);
5549
5550# check if any macro arguments are reused (ignore '...' and 'type')
5551 foreach my $arg (@def_args) {
5552 next if ($arg =~ /\.\.\./);
5553 next if ($arg =~ /^type$/i);
Martin Roth387dec82017-09-17 19:20:46 -06005554 my $tmp_stmt = $define_stmt;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005555 $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;
Martin Roth387dec82017-09-17 19:20:46 -06005556 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5557 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
Martin Roth60915b32018-08-10 21:04:05 -06005558 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005559 if ($use_cnt > 1) {
5560 CHK("MACRO_ARG_REUSE",
5561 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5562 }
5563# check if any macro arguments may have other precedence issues
Martin Roth387dec82017-09-17 19:20:46 -06005564 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
Martin Rothedd591d2017-03-14 10:16:29 -06005565 ((defined($1) && $1 ne ',') ||
5566 (defined($2) && $2 ne ','))) {
5567 CHK("MACRO_ARG_PRECEDENCE",
5568 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5569 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005570 }
5571
5572# check for macros with flow control, but without ## concatenation
5573# ## concatenation is commonly a macro that defines a function so ignore those
5574 if ($has_flow_statement && !$has_arg_concat) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005575 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005576 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005577
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005578 WARN("MACRO_WITH_FLOW_CONTROL",
5579 "Macros with flow control statements should be avoided\n" . "$herectx");
5580 }
5581
5582# check for line continuations outside of #defines, preprocessor #, and asm
5583
5584 } else {
5585 if ($prevline !~ /^..*\\$/ &&
5586 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5587 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5588 $line =~ /^\+.*\\$/) {
5589 WARN("LINE_CONTINUATIONS",
5590 "Avoid unnecessary line continuations\n" . $herecurr);
5591 }
5592 }
5593
5594# do {} while (0) macro tests:
5595# single-statement macros do not need to be enclosed in do while (0) loop,
5596# macro should not end with a semicolon
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005597 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005598 $realfile !~ m@/vmlinux.lds.h$@ &&
5599 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5600 my $ln = $linenr;
5601 my $cnt = $realcnt;
5602 my ($off, $dstat, $dcond, $rest);
5603 my $ctx = '';
5604 ($dstat, $dcond, $ln, $cnt, $off) =
5605 ctx_statement_block($linenr, $realcnt, 0);
5606 $ctx = $dstat;
5607
5608 $dstat =~ s/\\\n.//g;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005609 $dstat =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005610
5611 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5612 my $stmts = $2;
5613 my $semis = $3;
5614
5615 $ctx =~ s/\n*$//;
5616 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005617 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005618
5619 if (($stmts =~ tr/;/;/) == 1 &&
5620 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5621 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5622 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5623 }
5624 if (defined $semis && $semis ne "") {
5625 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5626 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5627 }
5628 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5629 $ctx =~ s/\n*$//;
5630 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005631 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005632
5633 WARN("TRAILING_SEMICOLON",
5634 "macros should not use a trailing semicolon\n" . "$herectx");
5635 }
5636 }
5637
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005638# check for redundant bracing round if etc
5639 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5640 my ($level, $endln, @chunks) =
5641 ctx_statement_full($linenr, $realcnt, 1);
5642 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5643 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5644 if ($#chunks > 0 && $level == 0) {
5645 my @allowed = ();
5646 my $allow = 0;
5647 my $seen = 0;
5648 my $herectx = $here . "\n";
5649 my $ln = $linenr - 1;
5650 for my $chunk (@chunks) {
5651 my ($cond, $block) = @{$chunk};
5652
5653 # If the condition carries leading newlines, then count those as offsets.
5654 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5655 my $offset = statement_rawlines($whitespace) - 1;
5656
5657 $allowed[$allow] = 0;
5658 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5659
5660 # We have looked at and allowed this specific line.
5661 $suppress_ifbraces{$ln + $offset} = 1;
5662
5663 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5664 $ln += statement_rawlines($block) - 1;
5665
5666 substr($block, 0, length($cond), '');
5667
5668 $seen++ if ($block =~ /^\s*{/);
5669
5670 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5671 if (statement_lines($cond) > 1) {
5672 #print "APW: ALLOWED: cond<$cond>\n";
5673 $allowed[$allow] = 1;
5674 }
5675 if ($block =~/\b(?:if|for|while)\b/) {
5676 #print "APW: ALLOWED: block<$block>\n";
5677 $allowed[$allow] = 1;
5678 }
5679 if (statement_block_size($block) > 1) {
5680 #print "APW: ALLOWED: lines block<$block>\n";
5681 $allowed[$allow] = 1;
5682 }
5683 $allow++;
5684 }
5685 if ($seen) {
5686 my $sum_allowed = 0;
5687 foreach (@allowed) {
5688 $sum_allowed += $_;
5689 }
5690 if ($sum_allowed == 0) {
Martin Roth57f11622023-03-06 11:18:25 -07005691 # coreboot has decided to allow braces around single line statement blocks
5692 #WARN("BRACES",
5693 # "braces {} are not necessary for any arm of this statement\n" . $herectx);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005694 } elsif ($sum_allowed != $allow &&
5695 $seen != $allow) {
5696 CHK("BRACES",
5697 "braces {} should be used on all arms of this statement\n" . $herectx);
5698 }
5699 }
5700 }
5701 }
5702 if (!defined $suppress_ifbraces{$linenr - 1} &&
5703 $line =~ /\b(if|while|for|else)\b/) {
5704 my $allowed = 0;
5705
5706 # Check the pre-context.
5707 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5708 #print "APW: ALLOWED: pre<$1>\n";
5709 $allowed = 1;
5710 }
5711
5712 my ($level, $endln, @chunks) =
5713 ctx_statement_full($linenr, $realcnt, $-[0]);
5714
5715 # Check the condition.
5716 my ($cond, $block) = @{$chunks[0]};
5717 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5718 if (defined $cond) {
5719 substr($block, 0, length($cond), '');
5720 }
5721 if (statement_lines($cond) > 1) {
5722 #print "APW: ALLOWED: cond<$cond>\n";
5723 $allowed = 1;
5724 }
5725 if ($block =~/\b(?:if|for|while)\b/) {
5726 #print "APW: ALLOWED: block<$block>\n";
5727 $allowed = 1;
5728 }
5729 if (statement_block_size($block) > 1) {
5730 #print "APW: ALLOWED: lines block<$block>\n";
5731 $allowed = 1;
5732 }
5733 # Check the post-context.
5734 if (defined $chunks[1]) {
5735 my ($cond, $block) = @{$chunks[1]};
5736 if (defined $cond) {
5737 substr($block, 0, length($cond), '');
5738 }
5739 if ($block =~ /^\s*\{/) {
5740 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5741 $allowed = 1;
5742 }
5743 }
Martin Roth57f11622023-03-06 11:18:25 -07005744 # coreboot has decided to allow braces around single line statement blocks
5745 #if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5746 # my $cnt = statement_rawlines($block);
5747 # my $herectx = get_stat_here($linenr, $cnt, $here);
5748 #
5749 # WARN("BRACES",
5750 # "braces {} are not necessary for single statement blocks\n" . $herectx);
5751 #}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005752 }
5753
Martin Rothedd591d2017-03-14 10:16:29 -06005754# check for single line unbalanced braces
5755 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5756 $sline =~ /^.\s*else\s*\{\s*$/) {
5757 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5758 }
5759
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005760# check for unnecessary blank lines around braces
5761 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005762 if (CHK("BRACES",
5763 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5764 $fix && $prevrawline =~ /^\+/) {
5765 fix_delete_line($fixlinenr - 1, $prevrawline);
5766 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005767 }
5768 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005769 if (CHK("BRACES",
5770 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5771 $fix) {
5772 fix_delete_line($fixlinenr, $rawline);
5773 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005774 }
5775
5776# no volatiles please
5777 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5778 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5779 WARN("VOLATILE",
Martin Rothedd591d2017-03-14 10:16:29 -06005780 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005781 }
5782
5783# Check for user-visible strings broken across lines, which breaks the ability
5784# to grep for the string. Make exceptions when the previous string ends in a
5785# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5786# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005787 if ($line =~ /^\+\s*$String/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005788 $prevline =~ /"\s*$/ &&
5789 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5790 if (WARN("SPLIT_STRING",
5791 "quoted string split across lines\n" . $hereprev) &&
5792 $fix &&
5793 $prevrawline =~ /^\+.*"\s*$/ &&
5794 $last_coalesced_string_linenr != $linenr - 1) {
5795 my $extracted_string = get_quoted_string($line, $rawline);
5796 my $comma_close = "";
5797 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5798 $comma_close = $1;
5799 }
5800
5801 fix_delete_line($fixlinenr - 1, $prevrawline);
5802 fix_delete_line($fixlinenr, $rawline);
5803 my $fixedline = $prevrawline;
5804 $fixedline =~ s/"\s*$//;
5805 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5806 fix_insert_line($fixlinenr - 1, $fixedline);
5807 $fixedline = $rawline;
5808 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5809 if ($fixedline !~ /\+\s*$/) {
5810 fix_insert_line($fixlinenr, $fixedline);
5811 }
5812 $last_coalesced_string_linenr = $linenr;
5813 }
5814 }
5815
5816# check for missing a space in a string concatenation
5817 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5818 WARN('MISSING_SPACE',
5819 "break quoted strings at a space character\n" . $hereprev);
5820 }
5821
Martin Roth387dec82017-09-17 19:20:46 -06005822# check for an embedded function name in a string when the function is known
5823# This does not work very well for -f --file checking as it depends on patch
5824# context providing the function name or a single line form for in-file
5825# function declarations
Martin Rothedd591d2017-03-14 10:16:29 -06005826 if ($line =~ /^\+.*$String/ &&
5827 defined($context_function) &&
Martin Roth387dec82017-09-17 19:20:46 -06005828 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5829 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
Martin Rothedd591d2017-03-14 10:16:29 -06005830 WARN("EMBEDDED_FUNCTION_NAME",
Martin Roth387dec82017-09-17 19:20:46 -06005831 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
Martin Rothedd591d2017-03-14 10:16:29 -06005832 }
5833
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005834# check for spaces before a quoted newline
5835 if ($rawline =~ /^.*\".*\s\\n/) {
5836 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5837 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5838 $fix) {
5839 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5840 }
5841
5842 }
5843
5844# concatenated string without spaces between elements
Elyes Haouas71bfcf52022-07-13 16:51:20 +02005845 if ($line =~ /$String[A-Z_]/ ||
5846 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
5847 if (CHK("CONCATENATED_STRING",
5848 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5849 $fix) {
5850 while ($line =~ /($String)/g) {
5851 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5852 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5853 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5854 }
5855 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005856 }
5857
5858# uncoalesced string fragments
Elyes Haouase235a0d2022-07-13 16:52:48 +02005859 if ($line =~ /$String\s*[Lu]?"/) {
5860 if (WARN("STRING_FRAGMENTS",
5861 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5862 $fix) {
5863 while ($line =~ /($String)(?=\s*")/g) {
5864 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5865 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5866 }
5867 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005868 }
5869
Martin Rothedd591d2017-03-14 10:16:29 -06005870# check for non-standard and hex prefixed decimal printf formats
5871 my $show_L = 1; #don't show the same defect twice
5872 my $show_Z = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005873 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
Martin Rothedd591d2017-03-14 10:16:29 -06005874 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005875 $string =~ s/%%/__/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005876 # check for %L
5877 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005878 WARN("PRINTF_L",
Martin Rothedd591d2017-03-14 10:16:29 -06005879 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5880 $show_L = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005881 }
Martin Rothedd591d2017-03-14 10:16:29 -06005882 # check for %Z
5883 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5884 WARN("PRINTF_Z",
5885 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5886 $show_Z = 0;
5887 }
5888 # check for 0x<decimal>
5889 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5890 ERROR("PRINTF_0XDECIMAL",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005891 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5892 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005893 }
5894
5895# check for line continuations in quoted strings with odd counts of "
Martin Roth60915b32018-08-10 21:04:05 -06005896 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005897 WARN("LINE_CONTINUATIONS",
5898 "Avoid line continuations in quoted strings\n" . $herecurr);
5899 }
5900
5901# warn about #if 0
5902 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02005903 WARN("IF_0",
5904 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5905 }
5906
5907# warn about #if 1
5908 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5909 WARN("IF_1",
5910 "Consider removing the #if 1 and its #endif\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005911 }
5912
5913# check for needless "if (<foo>) fn(<foo>)" uses
5914 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005915 my $tested = quotemeta($1);
5916 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5917 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5918 my $func = $1;
5919 if (WARN('NEEDLESS_IF',
5920 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5921 $fix) {
5922 my $do_fix = 1;
5923 my $leading_tabs = "";
5924 my $new_leading_tabs = "";
5925 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5926 $leading_tabs = $1;
5927 } else {
5928 $do_fix = 0;
5929 }
5930 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5931 $new_leading_tabs = $1;
5932 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5933 $do_fix = 0;
5934 }
5935 } else {
5936 $do_fix = 0;
5937 }
5938 if ($do_fix) {
5939 fix_delete_line($fixlinenr - 1, $prevrawline);
5940 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5941 }
5942 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005943 }
5944 }
5945
5946# check for unnecessary "Out of Memory" messages
5947 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5948 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5949 (defined $1 || defined $3) &&
5950 $linenr > 3) {
5951 my $testval = $2;
5952 my $testline = $lines[$linenr - 3];
5953
5954 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5955# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5956
Elyes Haouasa7b0d382022-05-23 18:33:15 +02005957 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5958 $s !~ /\b__GFP_NOWARN\b/ ) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005959 WARN("OOM_MESSAGE",
5960 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5961 }
5962 }
5963
5964# check for logging functions with KERN_<LEVEL>
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005965 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005966 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5967 my $level = $1;
5968 if (WARN("UNNECESSARY_KERN_LEVEL",
5969 "Possible unnecessary $level\n" . $herecurr) &&
5970 $fix) {
5971 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5972 }
5973 }
5974
Martin Rothedd591d2017-03-14 10:16:29 -06005975# check for logging continuations
5976 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5977 WARN("LOGGING_CONTINUATION",
5978 "Avoid logging continuation uses where feasible\n" . $herecurr);
5979 }
5980
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005981# check for mask then right shift without a parentheses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005982 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005983 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5984 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5985 WARN("MASK_THEN_SHIFT",
5986 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5987 }
5988
5989# check for pointer comparisons to NULL
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005990 if ($perl_version_ok) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005991 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5992 my $val = $1;
5993 my $equal = "!";
5994 $equal = "" if ($4 eq "!=");
5995 if (CHK("COMPARISON_TO_NULL",
5996 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5997 $fix) {
5998 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5999 }
6000 }
6001 }
6002
6003# check for bad placement of section $InitAttribute (e.g.: __initdata)
6004 if ($line =~ /(\b$InitAttribute\b)/) {
6005 my $attr = $1;
6006 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6007 my $ptr = $1;
6008 my $var = $2;
6009 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6010 ERROR("MISPLACED_INIT",
6011 "$attr should be placed after $var\n" . $herecurr)) ||
6012 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6013 WARN("MISPLACED_INIT",
6014 "$attr should be placed after $var\n" . $herecurr))) &&
6015 $fix) {
6016 $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;
6017 }
6018 }
6019 }
6020
6021# check for $InitAttributeData (ie: __initdata) with const
6022 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6023 my $attr = $1;
6024 $attr =~ /($InitAttributePrefix)(.*)/;
6025 my $attr_prefix = $1;
6026 my $attr_type = $2;
6027 if (ERROR("INIT_ATTRIBUTE",
6028 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6029 $fix) {
6030 $fixed[$fixlinenr] =~
6031 s/$InitAttributeData/${attr_prefix}initconst/;
6032 }
6033 }
6034
6035# check for $InitAttributeConst (ie: __initconst) without const
6036 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6037 my $attr = $1;
6038 if (ERROR("INIT_ATTRIBUTE",
6039 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6040 $fix) {
6041 my $lead = $fixed[$fixlinenr] =~
6042 /(^\+\s*(?:static\s+))/;
6043 $lead = rtrim($1);
6044 $lead = "$lead " if ($lead !~ /^\+$/);
6045 $lead = "${lead}const ";
6046 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6047 }
6048 }
6049
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006050# check for __read_mostly with const non-pointer (should just be const)
6051 if ($line =~ /\b__read_mostly\b/ &&
6052 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6053 if (ERROR("CONST_READ_MOSTLY",
6054 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6055 $fix) {
6056 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6057 }
6058 }
6059
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006060# don't use __constant_<foo> functions outside of include/uapi/
6061 if ($realfile !~ m@^include/uapi/@ &&
6062 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6063 my $constant_func = $1;
6064 my $func = $constant_func;
6065 $func =~ s/^__constant_//;
6066 if (WARN("CONSTANT_CONVERSION",
6067 "$constant_func should be $func\n" . $herecurr) &&
6068 $fix) {
6069 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6070 }
6071 }
6072
6073# prefer usleep_range over udelay
6074 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6075 my $delay = $1;
6076 # ignore udelay's < 10, however
6077 if (! ($delay < 10) ) {
6078 CHK("USLEEP_RANGE",
6079 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
6080 }
6081 if ($delay > 2000) {
6082 WARN("LONG_UDELAY",
6083 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6084 }
6085 }
6086
6087# warn about unexpectedly long msleep's
6088 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6089 if ($1 < 20) {
6090 WARN("MSLEEP",
6091 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
6092 }
6093 }
6094
6095# check for comparisons of jiffies
6096 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6097 WARN("JIFFIES_COMPARISON",
6098 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6099 }
6100
6101# check for comparisons of get_jiffies_64()
6102 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6103 WARN("JIFFIES_COMPARISON",
6104 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6105 }
6106
6107# warn about #ifdefs in C files
6108# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6109# print "#ifdef in C files should be avoided\n";
6110# print "$herecurr";
6111# $clean = 0;
6112# }
6113
6114# warn about spacing in #ifdefs
6115 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6116 if (ERROR("SPACING",
6117 "exactly one space required after that #$1\n" . $herecurr) &&
6118 $fix) {
6119 $fixed[$fixlinenr] =~
6120 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6121 }
6122
6123 }
6124
6125# check for spinlock_t definitions without a comment.
6126 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6127 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6128 my $which = $1;
6129 if (!ctx_has_comment($first_line, $linenr)) {
6130 CHK("UNCOMMENTED_DEFINITION",
6131 "$1 definition without comment\n" . $herecurr);
6132 }
6133 }
6134# check for memory barriers without a comment.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006135
6136 my $barriers = qr{
6137 mb|
6138 rmb|
Elyes Haouas26e0b942022-05-22 11:11:11 +02006139 wmb
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006140 }x;
6141 my $barrier_stems = qr{
6142 mb__before_atomic|
6143 mb__after_atomic|
6144 store_release|
6145 load_acquire|
6146 store_mb|
6147 (?:$barriers)
6148 }x;
6149 my $all_barriers = qr{
6150 (?:$barriers)|
6151 smp_(?:$barrier_stems)|
6152 virt_(?:$barrier_stems)
6153 }x;
6154
6155 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006156 if (!ctx_has_comment($first_line, $linenr)) {
6157 WARN("MEMORY_BARRIER",
6158 "memory barrier without comment\n" . $herecurr);
6159 }
6160 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006161
6162 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6163
6164 if ($realfile !~ m@^include/asm-generic/@ &&
6165 $realfile !~ m@/barrier\.h$@ &&
6166 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6167 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6168 WARN("MEMORY_BARRIER",
6169 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6170 }
6171
6172# check for waitqueue_active without a comment.
6173 if ($line =~ /\bwaitqueue_active\s*\(/) {
6174 if (!ctx_has_comment($first_line, $linenr)) {
6175 WARN("WAITQUEUE_ACTIVE",
6176 "waitqueue_active without comment\n" . $herecurr);
6177 }
6178 }
6179
Elyes Haouas26e0b942022-05-22 11:11:11 +02006180# check for data_race without a comment.
6181 if ($line =~ /\bdata_race\s*\(/) {
6182 if (!ctx_has_comment($first_line, $linenr)) {
6183 WARN("DATA_RACE",
6184 "data_race without comment\n" . $herecurr);
6185 }
Martin Roth60915b32018-08-10 21:04:05 -06006186 }
6187
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006188# check of hardware specific defines
6189 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6190 CHK("ARCH_DEFINES",
6191 "architecture specific defines should be avoided\n" . $herecurr);
6192 }
6193
Martin Roth387dec82017-09-17 19:20:46 -06006194# check that the storage class is not after a type
6195 if ($line =~ /\b($Type)\s+($Storage)\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006196 WARN("STORAGE_CLASS",
Martin Roth387dec82017-09-17 19:20:46 -06006197 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6198 }
6199# Check that the storage class is at the beginning of a declaration
6200 if ($line =~ /\b$Storage\b/ &&
6201 $line !~ /^.\s*$Storage/ &&
6202 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6203 $1 !~ /[\,\)]\s*$/) {
6204 WARN("STORAGE_CLASS",
6205 "storage class should be at the beginning of the declaration\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006206 }
6207
6208# check the location of the inline attribute, that it is between
6209# storage class and type.
6210 if ($line =~ /\b$Type\s+$Inline\b/ ||
6211 $line =~ /\b$Inline\s+$Storage\b/) {
6212 ERROR("INLINE_LOCATION",
6213 "inline keyword should sit between storage class and type\n" . $herecurr);
6214 }
6215
6216# Check for __inline__ and __inline, prefer inline
6217 if ($realfile !~ m@\binclude/uapi/@ &&
6218 $line =~ /\b(__inline__|__inline)\b/) {
6219 if (WARN("INLINE",
6220 "plain inline is preferred over $1\n" . $herecurr) &&
6221 $fix) {
6222 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6223
6224 }
6225 }
6226
Elyes Haouas069dfe32022-05-23 18:38:19 +02006227# Check for compiler attributes
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006228 if ($realfile !~ m@\binclude/uapi/@ &&
Elyes Haouas069dfe32022-05-23 18:38:19 +02006229 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6230 my $attr = $1;
6231 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006232
Elyes Haouas069dfe32022-05-23 18:38:19 +02006233 my %attr_list = (
6234 "alias" => "__alias",
6235 "aligned" => "__aligned",
6236 "always_inline" => "__always_inline",
6237 "assume_aligned" => "__assume_aligned",
6238 "cold" => "__cold",
6239 "const" => "__attribute_const__",
6240 "copy" => "__copy",
6241 "designated_init" => "__designated_init",
6242 "externally_visible" => "__visible",
6243 "format" => "printf|scanf",
6244 "gnu_inline" => "__gnu_inline",
6245 "malloc" => "__malloc",
6246 "mode" => "__mode",
6247 "no_caller_saved_registers" => "__no_caller_saved_registers",
6248 "noclone" => "__noclone",
6249 "noinline" => "noinline",
6250 "nonstring" => "__nonstring",
6251 "noreturn" => "__noreturn",
6252 "packed" => "__packed",
6253 "pure" => "__pure",
6254 "section" => "__section",
6255 "used" => "__used",
6256 "weak" => "__weak"
6257 );
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006258
Elyes Haouas069dfe32022-05-23 18:38:19 +02006259 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6260 my $orig_attr = $1;
6261 my $params = '';
6262 $params = $2 if defined($2);
6263 my $curr_attr = $orig_attr;
6264 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6265 if (exists($attr_list{$curr_attr})) {
6266 my $new = $attr_list{$curr_attr};
6267 if ($curr_attr eq "format" && $params) {
6268 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6269 $new = "__$1\($2";
6270 } else {
6271 $new = "$new$params";
6272 }
6273 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6274 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6275 $fix) {
6276 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6277 $fixed[$fixlinenr] =~ s/$remove//;
6278 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6279 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6280 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6281 }
6282 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006283 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006284
Elyes Haouas069dfe32022-05-23 18:38:19 +02006285 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6286 if ($attr =~ /^_*unused/) {
6287 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6288 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006289 }
6290 }
6291
6292# Check for __attribute__ weak, or __weak declarations (may have link issues)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006293 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006294 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6295 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6296 $line =~ /\b__weak\b/)) {
6297 ERROR("WEAK_DECLARATION",
6298 "Using weak declarations can have unintended link defects\n" . $herecurr);
6299 }
6300
Martin Rothedd591d2017-03-14 10:16:29 -06006301# check for c99 types like uint8_t used outside of uapi/ and tools/
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006302 if ($realfile !~ m@\binclude/uapi/@ &&
Martin Rothedd591d2017-03-14 10:16:29 -06006303 $realfile !~ m@\btools/@ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006304 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6305 my $type = $1;
6306 if ($type =~ /\b($typeC99Typedefs)\b/) {
6307 $type = $1;
6308 my $kernel_type = 'u';
6309 $kernel_type = 's' if ($type =~ /^_*[si]/);
6310 $type =~ /(\d+)/;
6311 $kernel_type .= $1;
6312 if (CHK("PREFER_KERNEL_TYPES",
6313 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6314 $fix) {
6315 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6316 }
6317 }
6318 }
6319
6320# check for cast of C90 native int or longer types constants
6321 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6322 my $cast = $1;
6323 my $const = $2;
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006324 my $suffix = "";
6325 my $newconst = $const;
6326 $newconst =~ s/${Int_type}$//;
6327 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6328 if ($cast =~ /\blong\s+long\b/) {
6329 $suffix .= 'LL';
6330 } elsif ($cast =~ /\blong\b/) {
6331 $suffix .= 'L';
6332 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006333 if (WARN("TYPECAST_INT_CONSTANT",
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006334 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006335 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006336 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6337 }
6338 }
6339
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006340# check for sizeof(&)
6341 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6342 WARN("SIZEOF_ADDRESS",
6343 "sizeof(& should be avoided\n" . $herecurr);
6344 }
6345
6346# check for sizeof without parenthesis
6347 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6348 if (WARN("SIZEOF_PARENTHESIS",
6349 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6350 $fix) {
6351 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6352 }
6353 }
6354
6355# check for struct spinlock declarations
6356 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6357 WARN("USE_SPINLOCK_T",
6358 "struct spinlock should be spinlock_t\n" . $herecurr);
6359 }
6360
6361# check for seq_printf uses that could be seq_puts
6362 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6363 my $fmt = get_quoted_string($line, $rawline);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006364 $fmt =~ s/%%//g;
6365 if ($fmt !~ /%/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006366 if (WARN("PREFER_SEQ_PUTS",
6367 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6368 $fix) {
6369 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6370 }
6371 }
6372 }
6373
Martin Roth60915b32018-08-10 21:04:05 -06006374# check for vsprintf extension %p<foo> misuses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006375 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006376 defined $stat &&
6377 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6378 $1 !~ /^_*volatile_*$/) {
Martin Roth60915b32018-08-10 21:04:05 -06006379 my $stat_real;
6380
Martin Roth387dec82017-09-17 19:20:46 -06006381 my $lc = $stat =~ tr@\n@@;
6382 $lc = $lc + $linenr;
6383 for (my $count = $linenr; $count <= $lc; $count++) {
Martin Roth60915b32018-08-10 21:04:05 -06006384 my $specifier;
6385 my $extension;
6386 my $bad_specifier = "";
Martin Roth387dec82017-09-17 19:20:46 -06006387 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6388 $fmt =~ s/%%//g;
Martin Roth60915b32018-08-10 21:04:05 -06006389
6390 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
6391 $specifier = $1;
6392 $extension = $2;
6393 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
6394 $bad_specifier = $specifier;
6395 last;
6396 }
6397 if ($extension eq "x" && !defined($stat_real)) {
6398 if (!defined($stat_real)) {
6399 $stat_real = get_stat_real($linenr, $lc);
6400 }
6401 WARN("VSPRINTF_SPECIFIER_PX",
6402 "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");
6403 }
Martin Roth387dec82017-09-17 19:20:46 -06006404 }
Martin Roth60915b32018-08-10 21:04:05 -06006405 if ($bad_specifier ne "") {
6406 my $stat_real = get_stat_real($linenr, $lc);
6407 my $ext_type = "Invalid";
6408 my $use = "";
6409 if ($bad_specifier =~ /p[Ff]/) {
6410 $ext_type = "Deprecated";
6411 $use = " - use %pS instead";
6412 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6413 }
6414
6415 WARN("VSPRINTF_POINTER_EXTENSION",
6416 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
Martin Roth387dec82017-09-17 19:20:46 -06006417 }
Martin Roth387dec82017-09-17 19:20:46 -06006418 }
6419 }
6420
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006421# Check for misused memsets
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006422 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006423 defined $stat &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006424 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006425
6426 my $ms_addr = $2;
6427 my $ms_val = $7;
6428 my $ms_size = $12;
6429
6430 if ($ms_size =~ /^(0x|)0$/i) {
6431 ERROR("MEMSET",
6432 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6433 } elsif ($ms_size =~ /^(0x|)1$/i) {
6434 WARN("MEMSET",
6435 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6436 }
6437 }
6438
6439# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006440# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006441# defined $stat &&
6442# $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6443# if (WARN("PREFER_ETHER_ADDR_COPY",
6444# "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6445# $fix) {
6446# $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6447# }
6448# }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006449
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006450# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006451# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006452# defined $stat &&
6453# $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6454# WARN("PREFER_ETHER_ADDR_EQUAL",
6455# "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6456# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006457
6458# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6459# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006460# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006461# defined $stat &&
6462# $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6463#
6464# my $ms_val = $7;
6465#
6466# if ($ms_val =~ /^(?:0x|)0+$/i) {
6467# if (WARN("PREFER_ETH_ZERO_ADDR",
6468# "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6469# $fix) {
6470# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6471# }
6472# } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6473# if (WARN("PREFER_ETH_BROADCAST_ADDR",
6474# "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6475# $fix) {
6476# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6477# }
6478# }
6479# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006480
Elyes Haouasf0e150c2022-04-12 13:12:19 +02006481# strlcpy uses that should likely be strscpy
6482 if ($line =~ /\bstrlcpy\s*\(/) {
6483 WARN("STRLCPY",
6484 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6485 }
6486
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006487# typecasts on min/max could be min_t/max_t
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006488 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006489 defined $stat &&
6490 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6491 if (defined $2 || defined $7) {
6492 my $call = $1;
6493 my $cast1 = deparenthesize($2);
6494 my $arg1 = $3;
6495 my $cast2 = deparenthesize($7);
6496 my $arg2 = $8;
6497 my $cast;
6498
6499 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6500 $cast = "$cast1 or $cast2";
6501 } elsif ($cast1 ne "") {
6502 $cast = $cast1;
6503 } else {
6504 $cast = $cast2;
6505 }
6506 WARN("MINMAX",
6507 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6508 }
6509 }
6510
6511# check usleep_range arguments
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006512 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006513 defined $stat &&
6514 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6515 my $min = $1;
6516 my $max = $7;
6517 if ($min eq $max) {
6518 WARN("USLEEP_RANGE",
6519 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6520 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6521 $min > $max) {
6522 WARN("USLEEP_RANGE",
6523 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6524 }
6525 }
6526
6527# check for naked sscanf
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006528 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006529 defined $stat &&
6530 $line =~ /\bsscanf\b/ &&
6531 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6532 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6533 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6534 my $lc = $stat =~ tr@\n@@;
6535 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006536 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006537 WARN("NAKED_SSCANF",
6538 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6539 }
6540
6541# check for simple sscanf that should be kstrto<foo>
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006542 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006543 defined $stat &&
6544 $line =~ /\bsscanf\b/) {
6545 my $lc = $stat =~ tr@\n@@;
6546 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006547 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006548 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6549 my $format = $6;
6550 my $count = $format =~ tr@%@%@;
6551 if ($count == 1 &&
6552 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6553 WARN("SSCANF_TO_KSTRTO",
6554 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6555 }
6556 }
6557 }
6558
6559# check for new externs in .h files.
6560 if ($realfile =~ /\.h$/ &&
6561 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6562 if (CHK("AVOID_EXTERNS",
6563 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6564 $fix) {
6565 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6566 }
6567 }
6568
6569# check for new externs in .c files.
6570 if ($realfile =~ /\.c$/ && defined $stat &&
6571 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6572 {
6573 my $function_name = $1;
6574 my $paren_space = $2;
6575
6576 my $s = $stat;
6577 if (defined $cond) {
6578 substr($s, 0, length($cond), '');
6579 }
Elyes Haouas26e0b942022-05-22 11:11:11 +02006580 if ($s =~ /^\s*;/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006581 {
6582 WARN("AVOID_EXTERNS",
6583 "externs should be avoided in .c files\n" . $herecurr);
6584 }
6585
6586 if ($paren_space =~ /\n/) {
6587 WARN("FUNCTION_ARGUMENTS",
6588 "arguments for function declarations should follow identifier\n" . $herecurr);
6589 }
6590
6591 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6592 $stat =~ /^.\s*extern\s+/)
6593 {
6594 WARN("AVOID_EXTERNS",
6595 "externs should be avoided in .c files\n" . $herecurr);
6596 }
6597
Martin Roth387dec82017-09-17 19:20:46 -06006598# check for function declarations that have arguments without identifier names
6599 if (defined $stat &&
Martin Roth60915b32018-08-10 21:04:05 -06006600 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
Martin Rothedd591d2017-03-14 10:16:29 -06006601 $1 ne "void") {
6602 my $args = trim($1);
6603 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6604 my $arg = trim($1);
6605 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6606 WARN("FUNCTION_ARGUMENTS",
6607 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6608 }
6609 }
6610 }
6611
Martin Roth387dec82017-09-17 19:20:46 -06006612# check for function definitions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006613 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006614 defined $stat &&
6615 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6616 $context_function = $1;
6617
6618# check for multiline function definition with misplaced open brace
6619 my $ok = 0;
6620 my $cnt = statement_rawlines($stat);
6621 my $herectx = $here . "\n";
6622 for (my $n = 0; $n < $cnt; $n++) {
6623 my $rl = raw_line($linenr, $n);
6624 $herectx .= $rl . "\n";
6625 $ok = 1 if ($rl =~ /^[ \+]\{/);
6626 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6627 last if $rl =~ /^[ \+].*\{/;
6628 }
6629 if (!$ok) {
6630 ERROR("OPEN_BRACE",
6631 "open brace '{' following function definitions go on the next line\n" . $herectx);
6632 }
6633 }
6634
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006635# checks for new __setup's
6636 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6637 my $name = $1;
6638
6639 if (!grep(/$name/, @setup_docs)) {
6640 CHK("UNDOCUMENTED_SETUP",
Martin Rothedd591d2017-03-14 10:16:29 -06006641 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006642 }
6643 }
6644
Elyes Haouasa7b0d382022-05-23 18:33:15 +02006645# check for pointless casting of alloc functions
6646 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006647 WARN("UNNECESSARY_CASTS",
6648 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6649 }
6650
6651# alloc style
6652# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006653 if ($perl_version_ok &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02006654 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006655 CHK("ALLOC_SIZEOF_STRUCT",
6656 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6657 }
6658
Elyes Haouas709fdb12022-05-28 10:03:10 +02006659# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006660 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006661 defined $stat &&
Elyes Haouas709fdb12022-05-28 10:03:10 +02006662 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006663 my $oldfunc = $3;
6664 my $a1 = $4;
6665 my $a2 = $10;
6666 my $newfunc = "kmalloc_array";
Elyes Haouas709fdb12022-05-28 10:03:10 +02006667 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
6668 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006669 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6670 my $r1 = $a1;
6671 my $r2 = $a2;
6672 if ($a1 =~ /^sizeof\s*\S/) {
6673 $r1 = $a2;
6674 $r2 = $a1;
6675 }
6676 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6677 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
Martin Roth387dec82017-09-17 19:20:46 -06006678 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006679 my $herectx = get_stat_here($linenr, $cnt, $here);
6680
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006681 if (WARN("ALLOC_WITH_MULTIPLY",
Martin Roth387dec82017-09-17 19:20:46 -06006682 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6683 $cnt == 1 &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006684 $fix) {
Elyes Haouas709fdb12022-05-28 10:03:10 +02006685 $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;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006686 }
6687 }
6688 }
6689
6690# check for krealloc arg reuse
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006691 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006692 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
6693 WARN("KREALLOC_ARG_REUSE",
6694 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6695 }
6696
6697# check for alloc argument mismatch
6698 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6699 WARN("ALLOC_ARRAY_ARGS",
6700 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6701 }
6702
6703# check for multiple semicolons
6704 if ($line =~ /;\s*;\s*$/) {
6705 if (WARN("ONE_SEMICOLON",
6706 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6707 $fix) {
6708 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6709 }
6710 }
6711
Martin Rothedd591d2017-03-14 10:16:29 -06006712# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6713 if ($realfile !~ m@^include/uapi/@ &&
6714 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006715 my $ull = "";
6716 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6717 if (CHK("BIT_MACRO",
6718 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6719 $fix) {
6720 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6721 }
6722 }
6723
Elyes Haouasf62a9892022-04-12 12:17:50 +02006724# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6725 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6726 WARN("IS_ENABLED_CONFIG",
6727 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6728 }
6729
6730# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6731 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6732 my $config = $1;
6733 if (WARN("PREFER_IS_ENABLED",
6734 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6735 $fix) {
6736 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006737 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02006738 }
6739
6740# check for /* fallthrough */ like comment, prefer fallthrough;
6741 my @fallthroughs = (
6742 'fallthrough',
6743 '@fallthrough@',
6744 'lint -fallthrough[ \t]*',
6745 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6746 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6747 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6748 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6749 );
6750 if ($raw_comment ne '') {
6751 foreach my $ft (@fallthroughs) {
6752 if ($raw_comment =~ /$ft/) {
6753 my $msg_level = \&WARN;
6754 $msg_level = \&CHK if ($file);
6755 &{$msg_level}("PREFER_FALLTHROUGH",
6756 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6757 last;
6758 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006759 }
6760 }
6761
6762# check for switch/default statements without a break;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006763 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006764 defined $stat &&
6765 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006766 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006767 my $herectx = get_stat_here($linenr, $cnt, $here);
6768
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006769 WARN("DEFAULT_NO_BREAK",
6770 "switch default: should use break\n" . $herectx);
6771 }
6772
6773# check for gcc specific __FUNCTION__
6774 if ($line =~ /\b__FUNCTION__\b/) {
6775 if (WARN("USE_FUNC",
6776 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6777 $fix) {
6778 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6779 }
6780 }
6781
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006782# check for uses of __DATE__, __TIME__, __TIMESTAMP__
6783 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6784 ERROR("DATE_TIME",
6785 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6786 }
6787
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006788# check for use of yield()
6789 if ($line =~ /\byield\s*\(\s*\)/) {
6790 WARN("YIELD",
6791 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6792 }
6793
6794# check for comparisons against true and false
6795 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6796 my $lead = $1;
6797 my $arg = $2;
6798 my $test = $3;
6799 my $otype = $4;
6800 my $trail = $5;
6801 my $op = "!";
6802
6803 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6804
6805 my $type = lc($otype);
6806 if ($type =~ /^(?:true|false)$/) {
6807 if (("$test" eq "==" && "$type" eq "true") ||
6808 ("$test" eq "!=" && "$type" eq "false")) {
6809 $op = "";
6810 }
6811
6812 CHK("BOOL_COMPARISON",
6813 "Using comparison to $otype is error prone\n" . $herecurr);
6814
6815## maybe suggesting a correct construct would better
6816## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6817
6818 }
6819 }
6820
Martin Roth60915b32018-08-10 21:04:05 -06006821# check for bool bitfields
6822 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6823 WARN("BOOL_BITFIELD",
6824 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6825 }
6826
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006827# check for semaphores initialized locked
6828 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6829 WARN("CONSIDER_COMPLETION",
6830 "consider using a completion\n" . $herecurr);
6831 }
6832
6833# recommend kstrto* over simple_strto* and strict_strto*
6834 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6835 WARN("CONSIDER_KSTRTO",
6836 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6837 }
6838
6839# check for __initcall(), use device_initcall() explicitly or more appropriate function please
6840 if ($line =~ /^.\s*__initcall\s*\(/) {
6841 WARN("USE_DEVICE_INITCALL",
6842 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6843 }
6844
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006845# check for various structs that are normally const (ops, kgdb, device_tree)
Martin Roth387dec82017-09-17 19:20:46 -06006846# and avoid what seem like struct definitions 'struct foo {'
Elyes Haouas43529c82022-04-12 13:19:50 +02006847 if (defined($const_structs) &&
6848 $line !~ /\bconst\b/ &&
Martin Roth387dec82017-09-17 19:20:46 -06006849 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006850 WARN("CONST_STRUCT",
Martin Roth387dec82017-09-17 19:20:46 -06006851 "struct $1 should normally be const\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006852 }
6853
6854# use of NR_CPUS is usually wrong
6855# ignore definitions of NR_CPUS and usage to define arrays as likely right
6856 if ($line =~ /\bNR_CPUS\b/ &&
6857 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6858 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6859 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6860 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6861 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6862 {
6863 WARN("NR_CPUS",
6864 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6865 }
6866
6867# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6868 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6869 ERROR("DEFINE_ARCH_HAS",
6870 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6871 }
6872
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006873# likely/unlikely comparisons similar to "(likely(foo) > 0)"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006874 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006875 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6876 WARN("LIKELY_MISUSE",
6877 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6878 }
6879
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006880# whine mightly about in_atomic
6881 if ($line =~ /\bin_atomic\s*\(/) {
6882 if ($realfile =~ m@^drivers/@) {
6883 ERROR("IN_ATOMIC",
6884 "do not use in_atomic in drivers\n" . $herecurr);
6885 } elsif ($realfile !~ m@^kernel/@) {
6886 WARN("IN_ATOMIC",
6887 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6888 }
6889 }
6890
Martin Rothedd591d2017-03-14 10:16:29 -06006891# check for mutex_trylock_recursive usage
6892 if ($line =~ /mutex_trylock_recursive/) {
6893 ERROR("LOCKING",
6894 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6895 }
6896
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006897# check for lockdep_set_novalidate_class
6898 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6899 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6900 if ($realfile !~ m@^kernel/lockdep@ &&
6901 $realfile !~ m@^include/linux/lockdep@ &&
6902 $realfile !~ m@^drivers/base/core@) {
6903 ERROR("LOCKDEP",
6904 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6905 }
6906 }
6907
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006908 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6909 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006910 WARN("EXPORTED_WORLD_WRITABLE",
6911 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6912 }
6913
Martin Roth60915b32018-08-10 21:04:05 -06006914# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6915# and whether or not function naming is typical and if
6916# DEVICE_ATTR permissions uses are unusual too
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006917 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06006918 defined $stat &&
6919 $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*\)/) {
6920 my $var = $1;
6921 my $perms = $2;
6922 my $show = $3;
6923 my $store = $4;
6924 my $octal_perms = perms_to_octal($perms);
6925 if ($show =~ /^${var}_show$/ &&
6926 $store =~ /^${var}_store$/ &&
6927 $octal_perms eq "0644") {
6928 if (WARN("DEVICE_ATTR_RW",
6929 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6930 $fix) {
6931 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6932 }
6933 } elsif ($show =~ /^${var}_show$/ &&
6934 $store =~ /^NULL$/ &&
6935 $octal_perms eq "0444") {
6936 if (WARN("DEVICE_ATTR_RO",
6937 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6938 $fix) {
6939 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6940 }
6941 } elsif ($show =~ /^NULL$/ &&
6942 $store =~ /^${var}_store$/ &&
6943 $octal_perms eq "0200") {
6944 if (WARN("DEVICE_ATTR_WO",
6945 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6946 $fix) {
6947 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6948 }
6949 } elsif ($octal_perms eq "0644" ||
6950 $octal_perms eq "0444" ||
6951 $octal_perms eq "0200") {
6952 my $newshow = "$show";
6953 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6954 my $newstore = $store;
6955 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6956 my $rename = "";
6957 if ($show ne $newshow) {
6958 $rename .= " '$show' to '$newshow'";
6959 }
6960 if ($store ne $newstore) {
6961 $rename .= " '$store' to '$newstore'";
6962 }
6963 WARN("DEVICE_ATTR_FUNCTIONS",
6964 "Consider renaming function(s)$rename\n" . $herecurr);
6965 } else {
6966 WARN("DEVICE_ATTR_PERMS",
6967 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6968 }
6969 }
6970
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006971# Mode permission misuses where it seems decimal should be octal
6972# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
Martin Roth60915b32018-08-10 21:04:05 -06006973# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6974# specific definition of not visible in sysfs.
6975# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6976# use the default permissions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006977 if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006978 defined $stat &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006979 $line =~ /$mode_perms_search/) {
6980 foreach my $entry (@mode_permission_funcs) {
6981 my $func = $entry->[0];
6982 my $arg_pos = $entry->[1];
6983
Martin Rothedd591d2017-03-14 10:16:29 -06006984 my $lc = $stat =~ tr@\n@@;
6985 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006986 my $stat_real = get_stat_real($linenr, $lc);
Martin Rothedd591d2017-03-14 10:16:29 -06006987
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006988 my $skip_args = "";
6989 if ($arg_pos > 1) {
6990 $arg_pos--;
6991 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6992 }
Martin Rothedd591d2017-03-14 10:16:29 -06006993 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6994 if ($stat =~ /$test/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006995 my $val = $1;
6996 $val = $6 if ($skip_args ne "");
Martin Roth60915b32018-08-10 21:04:05 -06006997 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6998 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6999 ($val =~ /^$Octal$/ && length($val) ne 4))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007000 ERROR("NON_OCTAL_PERMISSIONS",
Martin Rothedd591d2017-03-14 10:16:29 -06007001 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7002 }
7003 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007004 ERROR("EXPORTED_WORLD_WRITABLE",
Martin Rothedd591d2017-03-14 10:16:29 -06007005 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007006 }
7007 }
7008 }
7009 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007010
Martin Rothedd591d2017-03-14 10:16:29 -06007011# check for uses of S_<PERMS> that could be octal for readability
Martin Roth60915b32018-08-10 21:04:05 -06007012 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7013 my $oval = $1;
7014 my $octal = perms_to_octal($oval);
Martin Rothedd591d2017-03-14 10:16:29 -06007015 if (WARN("SYMBOLIC_PERMS",
7016 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7017 $fix) {
Martin Roth60915b32018-08-10 21:04:05 -06007018 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
Martin Rothedd591d2017-03-14 10:16:29 -06007019 }
7020 }
7021
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007022# validate content of MODULE_LICENSE against list from include/linux/module.h
7023 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7024 my $extracted_string = get_quoted_string($line, $rawline);
7025 my $valid_licenses = qr{
7026 GPL|
7027 GPL\ v2|
7028 GPL\ and\ additional\ rights|
7029 Dual\ BSD/GPL|
7030 Dual\ MIT/GPL|
7031 Dual\ MPL/GPL|
7032 Proprietary
7033 }x;
7034 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7035 WARN("MODULE_LICENSE",
7036 "unknown module license " . $extracted_string . "\n" . $herecurr);
7037 }
7038 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007039 }
7040
7041 # If we have no input at all, then there is nothing to report on
7042 # so just keep quiet.
7043 if ($#rawlines == -1) {
7044 exit(0);
7045 }
7046
7047 # In mailback mode only produce a report in the negative, for
7048 # things that appear to be patches.
7049 if ($mailback && ($clean == 1 || !$is_patch)) {
7050 exit(0);
7051 }
7052
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01007053 # This is not a patch, and we are in 'no-patch' mode so
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007054 # just keep quiet.
7055 if (!$chk_patch && !$is_patch) {
7056 exit(0);
7057 }
7058
Martin Roth60915b32018-08-10 21:04:05 -06007059 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007060 ERROR("NOT_UNIFIED_DIFF",
7061 "Does not appear to be a unified-diff format patch\n");
7062 }
Elyes Haouas6e84c2c2022-07-13 17:35:43 +02007063 if ($is_patch && $has_commit_log && $chk_signoff) {
7064 if ($signoff == 0) {
7065 ERROR("MISSING_SIGN_OFF",
7066 "Missing Signed-off-by: line(s)\n");
7067 } elsif ($authorsignoff != 1) {
7068 # authorsignoff values:
7069 # 0 -> missing sign off
7070 # 1 -> sign off identical
7071 # 2 -> names and addresses match, comments mismatch
7072 # 3 -> addresses match, names different
7073 # 4 -> names match, addresses different
7074 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7075
7076 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7077
7078 if ($authorsignoff == 0) {
7079 ERROR("NO_AUTHOR_SIGN_OFF",
7080 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7081 } elsif ($authorsignoff == 2) {
7082 CHK("FROM_SIGN_OFF_MISMATCH",
7083 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7084 } elsif ($authorsignoff == 3) {
7085 WARN("FROM_SIGN_OFF_MISMATCH",
7086 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7087 } elsif ($authorsignoff == 4) {
7088 WARN("FROM_SIGN_OFF_MISMATCH",
7089 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7090 } elsif ($authorsignoff == 5) {
7091 WARN("FROM_SIGN_OFF_MISMATCH",
7092 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7093 }
7094 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007095 }
7096
7097 print report_dump();
7098 if ($summary && !($clean == 1 && $quiet == 1)) {
7099 print "$filename " if ($summary_file);
7100 print "total: $cnt_error errors, $cnt_warn warnings, " .
7101 (($check)? "$cnt_chk checks, " : "") .
7102 "$cnt_lines lines checked\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007103 }
7104
7105 if ($quiet == 0) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007106 # If there were any defects found and not already fixing them
7107 if (!$clean and !$fix) {
7108 print << "EOM"
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007109
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007110NOTE: For some of the reported defects, checkpatch may be able to
7111 mechanically convert to the typical style using --fix or --fix-inplace.
7112EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007113 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007114 # If there were whitespace errors which cleanpatch can fix
7115 # then suggest that.
7116 if ($rpt_cleaners) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007117 $rpt_cleaners = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007118 print << "EOM"
7119
7120NOTE: Whitespace errors detected.
7121 You may wish to use scripts/cleanpatch or scripts/cleanfile
7122EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007123 }
7124 }
7125
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007126 if ($clean == 0 && $fix &&
7127 ("@rawlines" ne "@fixed" ||
7128 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7129 my $newfile = $filename;
7130 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7131 my $linecount = 0;
7132 my $f;
7133
7134 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7135
7136 open($f, '>', $newfile)
7137 or die "$P: Can't open $newfile for write\n";
7138 foreach my $fixed_line (@fixed) {
7139 $linecount++;
7140 if ($file) {
7141 if ($linecount > 3) {
7142 $fixed_line =~ s/^\+//;
7143 print $f $fixed_line . "\n";
7144 }
7145 } else {
7146 print $f $fixed_line . "\n";
7147 }
7148 }
7149 close($f);
7150
7151 if (!$quiet) {
7152 print << "EOM";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007153
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007154Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7155
7156Do _NOT_ trust the results written to this file.
7157Do _NOT_ submit these changes without inspecting them for correctness.
7158
7159This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7160No warranties, expressed or implied...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007161EOM
7162 }
7163 }
7164
Stefan Reinauerc6080c62016-07-29 16:01:40 -07007165 if ($quiet == 0) {
7166 print "\n";
7167 if ($clean == 1) {
7168 print "$vname has no obvious style problems and is ready for submission.\n";
7169 } else {
7170 print "$vname has style problems, please review.\n";
7171 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007172 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01007173 return $clean;
7174}