blob: 22f2d3e3726590916761874875eca10d7cf58a96 [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:|
621 To:|
622 Cc:
623)};
624
625our @typeListMisordered = (
626 qr{char\s+(?:un)?signed},
627 qr{int\s+(?:(?:un)?signed\s+)?short\s},
628 qr{int\s+short(?:\s+(?:un)?signed)},
629 qr{short\s+int(?:\s+(?:un)?signed)},
630 qr{(?:un)?signed\s+int\s+short},
631 qr{short\s+(?:un)?signed},
632 qr{long\s+int\s+(?:un)?signed},
633 qr{int\s+long\s+(?:un)?signed},
634 qr{long\s+(?:un)?signed\s+int},
635 qr{int\s+(?:un)?signed\s+long},
636 qr{int\s+(?:un)?signed},
637 qr{int\s+long\s+long\s+(?:un)?signed},
638 qr{long\s+long\s+int\s+(?:un)?signed},
639 qr{long\s+long\s+(?:un)?signed\s+int},
640 qr{long\s+long\s+(?:un)?signed},
641 qr{long\s+(?:un)?signed},
642);
643
644our @typeList = (
645 qr{void},
646 qr{(?:(?:un)?signed\s+)?char},
647 qr{(?:(?:un)?signed\s+)?short\s+int},
648 qr{(?:(?:un)?signed\s+)?short},
649 qr{(?:(?:un)?signed\s+)?int},
650 qr{(?:(?:un)?signed\s+)?long\s+int},
651 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
652 qr{(?:(?:un)?signed\s+)?long\s+long},
653 qr{(?:(?:un)?signed\s+)?long},
654 qr{(?:un)?signed},
655 qr{float},
656 qr{double},
657 qr{bool},
658 qr{struct\s+$Ident},
659 qr{union\s+$Ident},
660 qr{enum\s+$Ident},
661 qr{${Ident}_t},
662 qr{${Ident}_handler},
663 qr{${Ident}_handler_fn},
664 @typeListMisordered,
665);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700666
667our $C90_int_types = qr{(?x:
668 long\s+long\s+int\s+(?:un)?signed|
669 long\s+long\s+(?:un)?signed\s+int|
670 long\s+long\s+(?:un)?signed|
671 (?:(?:un)?signed\s+)?long\s+long\s+int|
672 (?:(?:un)?signed\s+)?long\s+long|
673 int\s+long\s+long\s+(?:un)?signed|
674 int\s+(?:(?:un)?signed\s+)?long\s+long|
675
676 long\s+int\s+(?:un)?signed|
677 long\s+(?:un)?signed\s+int|
678 long\s+(?:un)?signed|
679 (?:(?:un)?signed\s+)?long\s+int|
680 (?:(?:un)?signed\s+)?long|
681 int\s+long\s+(?:un)?signed|
682 int\s+(?:(?:un)?signed\s+)?long|
683
684 int\s+(?:un)?signed|
685 (?:(?:un)?signed\s+)?int
686)};
687
688our @typeListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100689our @typeListWithAttr = (
690 @typeList,
691 qr{struct\s+$InitAttribute\s+$Ident},
692 qr{union\s+$InitAttribute\s+$Ident},
693);
694
695our @modifierList = (
696 qr{fastcall},
697);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700698our @modifierListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100699
700our @mode_permission_funcs = (
701 ["module_param", 3],
702 ["module_param_(?:array|named|string)", 4],
703 ["module_param_array_named", 5],
704 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
705 ["proc_create(?:_data|)", 2],
Martin Rothedd591d2017-03-14 10:16:29 -0600706 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
707 ["IIO_DEV_ATTR_[A-Z_]+", 1],
708 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
709 ["SENSOR_TEMPLATE(?:_2|)", 3],
710 ["__ATTR", 2],
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100711);
712
Elyes Haouas84083a22022-04-12 12:28:32 +0200713my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
714
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100715#Create a search pattern for all these functions to speed up a loop below
716our $mode_perms_search = "";
717foreach my $entry (@mode_permission_funcs) {
718 $mode_perms_search .= '|' if ($mode_perms_search ne "");
719 $mode_perms_search .= $entry->[0];
720}
Martin Roth60915b32018-08-10 21:04:05 -0600721$mode_perms_search = "(?:${mode_perms_search})";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100722
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700723our $mode_perms_world_writable = qr{
724 S_IWUGO |
725 S_IWOTH |
726 S_IRWXUGO |
727 S_IALLUGO |
728 0[0-7][0-7][2367]
729}x;
730
Martin Rothedd591d2017-03-14 10:16:29 -0600731our %mode_permission_string_types = (
732 "S_IRWXU" => 0700,
733 "S_IRUSR" => 0400,
734 "S_IWUSR" => 0200,
735 "S_IXUSR" => 0100,
736 "S_IRWXG" => 0070,
737 "S_IRGRP" => 0040,
738 "S_IWGRP" => 0020,
739 "S_IXGRP" => 0010,
740 "S_IRWXO" => 0007,
741 "S_IROTH" => 0004,
742 "S_IWOTH" => 0002,
743 "S_IXOTH" => 0001,
744 "S_IRWXUGO" => 0777,
745 "S_IRUGO" => 0444,
746 "S_IWUGO" => 0222,
747 "S_IXUGO" => 0111,
748);
749
750#Create a search pattern for all these strings to speed up a loop below
751our $mode_perms_string_search = "";
752foreach my $entry (keys %mode_permission_string_types) {
753 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
754 $mode_perms_string_search .= $entry;
755}
Martin Roth60915b32018-08-10 21:04:05 -0600756our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
757our $multi_mode_perms_string_search = qr{
758 ${single_mode_perms_string_search}
759 (?:\s*\|\s*${single_mode_perms_string_search})*
760}x;
761
762sub perms_to_octal {
763 my ($string) = @_;
764
765 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
766
767 my $val = "";
768 my $oval = "";
769 my $to = 0;
770 my $curpos = 0;
771 my $lastpos = 0;
772 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
773 $curpos = pos($string);
774 my $match = $2;
775 my $omatch = $1;
776 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
777 $lastpos = $curpos;
778 $to |= $mode_permission_string_types{$match};
779 $val .= '\s*\|\s*' if ($val ne "");
780 $val .= $match;
781 $oval .= $omatch;
782 }
783 $oval =~ s/^\s*\|\s*//;
784 $oval =~ s/\s*\|\s*$//;
785 return sprintf("%04o", $to);
786}
Martin Rothedd591d2017-03-14 10:16:29 -0600787
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100788our $allowed_asm_includes = qr{(?x:
789 irq|
790 memory|
791 time|
792 reboot
793)};
794# memory.h: ARM has a custom one
795
796# Load common spelling mistakes and build regular expression list.
797my $misspellings;
798my %spelling_fix;
799
800if (open(my $spelling, '<', $spelling_file)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100801 while (<$spelling>) {
802 my $line = $_;
803
804 $line =~ s/\s*\n?$//g;
805 $line =~ s/^\s*//g;
806
807 next if ($line =~ m/^\s*#/);
808 next if ($line =~ m/^\s*$/);
809
810 my ($suspect, $fix) = split(/\|\|/, $line);
811
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100812 $spelling_fix{$suspect} = $fix;
813 }
814 close($spelling);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100815} else {
816 warn "No typos will be found - file '$spelling_file': $!\n";
817}
818
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700819if ($codespell) {
820 if (open(my $spelling, '<', $codespellfile)) {
821 while (<$spelling>) {
822 my $line = $_;
823
824 $line =~ s/\s*\n?$//g;
825 $line =~ s/^\s*//g;
826
827 next if ($line =~ m/^\s*#/);
828 next if ($line =~ m/^\s*$/);
829 next if ($line =~ m/, disabled/i);
830
831 $line =~ s/,.*$//;
832
833 my ($suspect, $fix) = split(/->/, $line);
834
835 $spelling_fix{$suspect} = $fix;
836 }
837 close($spelling);
838 } else {
839 warn "No codespell typos will be found - file '$codespellfile': $!\n";
840 }
841}
842
843$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
844
Martin Roth387dec82017-09-17 19:20:46 -0600845sub read_words {
846 my ($wordsRef, $file) = @_;
Martin Rothedd591d2017-03-14 10:16:29 -0600847
Martin Roth387dec82017-09-17 19:20:46 -0600848 if (open(my $words, '<', $file)) {
849 while (<$words>) {
850 my $line = $_;
Martin Rothedd591d2017-03-14 10:16:29 -0600851
Martin Roth387dec82017-09-17 19:20:46 -0600852 $line =~ s/\s*\n?$//g;
853 $line =~ s/^\s*//g;
854
855 next if ($line =~ m/^\s*#/);
856 next if ($line =~ m/^\s*$/);
857 if ($line =~ /\s/) {
858 print("$file: '$line' invalid - ignored\n");
859 next;
860 }
861
Elyes Haouas14c49e32022-05-08 10:11:40 +0200862 $$wordsRef .= '|' if (defined $$wordsRef);
Martin Roth387dec82017-09-17 19:20:46 -0600863 $$wordsRef .= $line;
Martin Rothedd591d2017-03-14 10:16:29 -0600864 }
Martin Roth387dec82017-09-17 19:20:46 -0600865 close($file);
866 return 1;
Martin Rothedd591d2017-03-14 10:16:29 -0600867 }
Martin Roth387dec82017-09-17 19:20:46 -0600868
869 return 0;
Martin Rothedd591d2017-03-14 10:16:29 -0600870}
871
Elyes Haouas43529c82022-04-12 13:19:50 +0200872my $const_structs;
873if (show_type("CONST_STRUCT")) {
874 read_words(\$const_structs, $conststructsfile)
875 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
876}
Martin Roth387dec82017-09-17 19:20:46 -0600877
Elyes Haouas26e0b942022-05-22 11:11:11 +0200878if (defined($typedefsfile)) {
879 my $typeOtherTypedefs;
Martin Roth387dec82017-09-17 19:20:46 -0600880 read_words(\$typeOtherTypedefs, $typedefsfile)
881 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
Elyes Haouas26e0b942022-05-22 11:11:11 +0200882 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
Martin Roth387dec82017-09-17 19:20:46 -0600883}
Martin Roth387dec82017-09-17 19:20:46 -0600884
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100885sub build_types {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700886 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
887 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100888 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
889 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
890 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700891 $BasicType = qr{
892 (?:$typeTypedefs\b)|
893 (?:${all}\b)
894 }x;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100895 $NonptrType = qr{
896 (?:$Modifier\s+|const\s+)*
897 (?:
898 (?:typeof|__typeof__)\s*\([^\)]*\)|
899 (?:$typeTypedefs\b)|
900 (?:${all}\b)
901 )
902 (?:\s+$Modifier|\s+const)*
903 }x;
904 $NonptrTypeMisordered = qr{
905 (?:$Modifier\s+|const\s+)*
906 (?:
907 (?:${Misordered}\b)
908 )
909 (?:\s+$Modifier|\s+const)*
910 }x;
911 $NonptrTypeWithAttr = qr{
912 (?:$Modifier\s+|const\s+)*
913 (?:
914 (?:typeof|__typeof__)\s*\([^\)]*\)|
915 (?:$typeTypedefs\b)|
916 (?:${allWithAttr}\b)
917 )
918 (?:\s+$Modifier|\s+const)*
919 }x;
920 $Type = qr{
921 $NonptrType
Elyes Haouas26e0b942022-05-22 11:11:11 +0200922 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100923 (?:\s+$Inline|\s+$Modifier)*
924 }x;
925 $TypeMisordered = qr{
926 $NonptrTypeMisordered
Elyes Haouas26e0b942022-05-22 11:11:11 +0200927 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100928 (?:\s+$Inline|\s+$Modifier)*
929 }x;
930 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
931 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
932}
933build_types();
934
935our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
936
937# Using $balanced_parens, $LvalOrFunc, or $FuncArg
938# requires at least perl version v5.10.0
939# Any use must be runtime checked with $^V
940
941our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
942our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700943our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100944
945our $declaration_macros = qr{(?x:
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700946 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
Martin Roth387dec82017-09-17 19:20:46 -0600947 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
Martin Roth60915b32018-08-10 21:04:05 -0600948 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100949)};
950
Elyes Haouas84083a22022-04-12 12:28:32 +0200951our %allow_repeated_words = (
952 add => '',
953 added => '',
954 bad => '',
955 be => '',
956);
957
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100958sub deparenthesize {
959 my ($string) = @_;
960 return "" if (!defined($string));
961
962 while ($string =~ /^\s*\(.*\)\s*$/) {
963 $string =~ s@^\s*\(\s*@@;
964 $string =~ s@\s*\)\s*$@@;
965 }
966
967 $string =~ s@\s+@ @g;
968
969 return $string;
970}
971
972sub seed_camelcase_file {
973 my ($file) = @_;
974
975 return if (!(-f $file));
976
977 local $/;
978
979 open(my $include_file, '<', "$file")
980 or warn "$P: Can't read '$file' $!\n";
981 my $text = <$include_file>;
982 close($include_file);
983
984 my @lines = split('\n', $text);
985
986 foreach my $line (@lines) {
987 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
988 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
989 $camelcase{$1} = 1;
990 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
991 $camelcase{$1} = 1;
992 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
993 $camelcase{$1} = 1;
994 }
995 }
996}
997
Martin Rothedd591d2017-03-14 10:16:29 -0600998sub is_maintained_obsolete {
999 my ($filename) = @_;
1000
1001 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1002
1003 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1004
1005 return $status =~ /obsolete/i;
1006}
1007
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001008my $camelcase_seeded = 0;
1009sub seed_camelcase_includes {
1010 return if ($camelcase_seeded);
1011
1012 my $files;
1013 my $camelcase_cache = "";
1014 my @include_files = ();
1015
1016 $camelcase_seeded = 1;
1017
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001018 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001019 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001020 chomp $git_last_include_commit;
1021 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1022 } else {
1023 my $last_mod_date = 0;
1024 $files = `find $root/include -name "*.h"`;
1025 @include_files = split('\n', $files);
1026 foreach my $file (@include_files) {
1027 my $date = POSIX::strftime("%Y%m%d%H%M",
1028 localtime((stat $file)[9]));
1029 $last_mod_date = $date if ($last_mod_date < $date);
1030 }
1031 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1032 }
1033
1034 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1035 open(my $camelcase_file, '<', "$camelcase_cache")
1036 or warn "$P: Can't read '$camelcase_cache' $!\n";
1037 while (<$camelcase_file>) {
1038 chomp;
1039 $camelcase{$_} = 1;
1040 }
1041 close($camelcase_file);
1042
1043 return;
1044 }
1045
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001046 if (-e "$gitroot") {
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001047 $files = `${git_command} ls-files "include/*.h"`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001048 @include_files = split('\n', $files);
1049 }
1050
1051 foreach my $file (@include_files) {
1052 seed_camelcase_file($file);
1053 }
1054
1055 if ($camelcase_cache ne "") {
1056 unlink glob ".checkpatch-camelcase.*";
1057 open(my $camelcase_file, '>', "$camelcase_cache")
1058 or warn "$P: Can't write '$camelcase_cache' $!\n";
1059 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1060 print $camelcase_file ("$_\n");
1061 }
1062 close($camelcase_file);
1063 }
1064}
1065
1066sub git_commit_info {
1067 my ($commit, $id, $desc) = @_;
1068
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001069 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001070
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001071 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001072 $output =~ s/^\s*//gm;
1073 my @lines = split("\n", $output);
1074
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001075 return ($id, $desc) if ($#lines < 0);
1076
Elyes Haouas26e0b942022-05-22 11:11:11 +02001077 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001078# Maybe one day convert this block of bash into something that returns
1079# all matching commit ids, but it's very slow...
1080#
1081# echo "checking commits $1..."
1082# git rev-list --remotes | grep -i "^$1" |
1083# while read line ; do
1084# git log --format='%H %s' -1 $line |
1085# echo "commit $(cut -c 1-12,41-)"
1086# done
Elyes Haouas26e0b942022-05-22 11:11:11 +02001087 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1088 $lines[0] =~ /^fatal: bad object $commit/) {
Martin Roth387dec82017-09-17 19:20:46 -06001089 $id = undef;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001090 } else {
1091 $id = substr($lines[0], 0, 12);
1092 $desc = substr($lines[0], 41);
1093 }
1094
1095 return ($id, $desc);
1096}
1097
1098$chk_signoff = 0 if ($file);
1099
1100my @rawlines = ();
1101my @lines = ();
1102my @fixed = ();
1103my @fixed_inserted = ();
1104my @fixed_deleted = ();
1105my $fixlinenr = -1;
1106
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001107# If input is git commits, extract all commits from the commit expressions.
1108# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
Elyes HAOUAS18ef5202022-01-29 08:27:14 +01001109die "$P: No git repository found\n" if ($git && !-e "$gitroot");
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001110
1111if ($git) {
1112 my @commits = ();
1113 foreach my $commit_expr (@ARGV) {
1114 my $git_range;
1115 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1116 $git_range = "-$2 $1";
1117 } elsif ($commit_expr =~ m/\.\./) {
1118 $git_range = "$commit_expr";
1119 } else {
1120 $git_range = "-1 $commit_expr";
1121 }
Elyes HAOUASf2a9c8d2022-01-29 08:31:06 +01001122 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001123 foreach my $line (split(/\n/, $lines)) {
1124 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1125 next if (!defined($1) || !defined($2));
1126 my $sha1 = $1;
1127 my $subject = $2;
1128 unshift(@commits, $sha1);
1129 $git_commits{$sha1} = $subject;
1130 }
1131 }
1132 die "$P: no git commits after extraction!\n" if (@commits == 0);
1133 @ARGV = @commits;
1134}
1135
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001136my $vname;
Elyes Haouas8f599602022-04-12 12:55:43 +02001137$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
Martin Roth387dec82017-09-17 19:20:46 -06001138for my $filename (@ARGV) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001139 my $FILE;
Martin Rotha9868b22018-01-27 17:31:42 -07001140
1141 # coreboot: Mark filename as untainted
1142 $filename =~ /^(.*)$/s or die; $filename = $1;
1143
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001144 if ($git) {
1145 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1146 die "$P: $filename: git format-patch failed - $!\n";
1147 } elsif ($file) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001148 open($FILE, '-|', "diff -u /dev/null $filename") ||
1149 die "$P: $filename: diff failed - $!\n";
1150 } elsif ($filename eq '-') {
1151 open($FILE, '<&STDIN');
1152 } else {
1153 open($FILE, '<', "$filename") ||
1154 die "$P: $filename: open failed - $!\n";
1155 }
1156 if ($filename eq '-') {
1157 $vname = 'Your patch';
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001158 } elsif ($git) {
1159 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001160 } else {
1161 $vname = $filename;
1162 }
1163 while (<$FILE>) {
1164 chomp;
1165 push(@rawlines, $_);
1166 }
1167 close($FILE);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001168
1169 if ($#ARGV > 0 && $quiet == 0) {
1170 print '-' x length($vname) . "\n";
1171 print "$vname\n";
1172 print '-' x length($vname) . "\n";
1173 }
1174
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001175 if (!process($filename)) {
1176 $exit = 1;
1177 }
1178 @rawlines = ();
1179 @lines = ();
1180 @fixed = ();
1181 @fixed_inserted = ();
1182 @fixed_deleted = ();
1183 $fixlinenr = -1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001184 @modifierListFile = ();
1185 @typeListFile = ();
1186 build_types();
1187}
1188
1189if (!$quiet) {
1190 hash_show_words(\%use_type, "Used");
1191 hash_show_words(\%ignore_type, "Ignored");
1192
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001193 if (!$perl_version_ok) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001194 print << "EOM"
1195
1196NOTE: perl $^V is not modern enough to detect all possible issues.
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01001197 An upgrade to at least perl $minimum_perl_version is suggested.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001198EOM
1199 }
1200 if ($exit) {
1201 print << "EOM"
1202
1203NOTE: If any of the errors are false positives, please report
1204 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1205EOM
1206 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001207}
1208
1209exit($exit);
1210
1211sub top_of_kernel_tree {
1212 my ($root) = @_;
1213
1214 my @tree_check = (
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001215 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1216 "README", "Documentation", "arch", "include", "drivers",
1217 "fs", "init", "ipc", "kernel", "lib", "scripts",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001218 );
1219
1220 foreach my $check (@tree_check) {
1221 if (! -e $root . '/' . $check) {
1222 return 0;
1223 }
1224 }
1225 return 1;
1226}
1227
1228sub parse_email {
1229 my ($formatted_email) = @_;
1230
1231 my $name = "";
1232 my $address = "";
1233 my $comment = "";
1234
1235 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1236 $name = $1;
1237 $address = $2;
1238 $comment = $3 if defined $3;
1239 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1240 $address = $1;
1241 $comment = $2 if defined $2;
1242 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1243 $address = $1;
1244 $comment = $2 if defined $2;
Martin Roth60915b32018-08-10 21:04:05 -06001245 $formatted_email =~ s/\Q$address\E.*$//;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001246 $name = $formatted_email;
1247 $name = trim($name);
1248 $name =~ s/^\"|\"$//g;
1249 # If there's a name left after stripping spaces and
1250 # leading quotes, and the address doesn't have both
1251 # leading and trailing angle brackets, the address
1252 # is invalid. ie:
1253 # "joe smith joe@smith.com" bad
1254 # "joe smith <joe@smith.com" bad
1255 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1256 $name = "";
1257 $address = "";
1258 $comment = "";
1259 }
1260 }
1261
1262 $name = trim($name);
1263 $name =~ s/^\"|\"$//g;
1264 $address = trim($address);
1265 $address =~ s/^\<|\>$//g;
1266
1267 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1268 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1269 $name = "\"$name\"";
1270 }
1271
1272 return ($name, $address, $comment);
1273}
1274
1275sub format_email {
1276 my ($name, $address) = @_;
1277
1278 my $formatted_email;
1279
1280 $name = trim($name);
1281 $name =~ s/^\"|\"$//g;
1282 $address = trim($address);
1283
1284 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1285 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1286 $name = "\"$name\"";
1287 }
1288
1289 if ("$name" eq "") {
1290 $formatted_email = "$address";
1291 } else {
1292 $formatted_email = "$name <$address>";
1293 }
1294
1295 return $formatted_email;
1296}
1297
1298sub which {
1299 my ($bin) = @_;
1300
1301 foreach my $path (split(/:/, $ENV{PATH})) {
1302 if (-e "$path/$bin") {
1303 return "$path/$bin";
1304 }
1305 }
1306
1307 return "";
1308}
1309
1310sub which_conf {
1311 my ($conf) = @_;
1312
1313 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1314 if (-e "$path/$conf") {
1315 return "$path/$conf";
1316 }
1317 }
1318
1319 return "";
1320}
1321
1322sub expand_tabs {
1323 my ($str) = @_;
1324
1325 my $res = '';
1326 my $n = 0;
1327 for my $c (split(//, $str)) {
1328 if ($c eq "\t") {
1329 $res .= ' ';
1330 $n++;
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01001331 for (; ($n % $tabsize) != 0; $n++) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001332 $res .= ' ';
1333 }
1334 next;
1335 }
1336 $res .= $c;
1337 $n++;
1338 }
1339
1340 return $res;
1341}
1342sub copy_spacing {
1343 (my $res = shift) =~ tr/\t/ /c;
1344 return $res;
1345}
1346
1347sub line_stats {
1348 my ($line) = @_;
1349
Elyes Haouas26e0b942022-05-22 11:11:11 +02001350 # Drop the diff line leader and expand tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001351 $line =~ s/^.//;
Julius Werner218906d2021-03-25 21:12:49 -07001352
1353 # Treat labels like whitespace when counting indentation
1354 $line =~ s/^( ?$Ident:)/" " x length($1)/e;
1355
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001356 $line = expand_tabs($line);
1357
1358 # Pick the indent from the front of the line.
1359 my ($white) = ($line =~ /^(\s*)/);
1360
1361 return (length($line), length($white));
1362}
1363
1364my $sanitise_quote = '';
1365
1366sub sanitise_line_reset {
1367 my ($in_comment) = @_;
1368
1369 if ($in_comment) {
1370 $sanitise_quote = '*/';
1371 } else {
1372 $sanitise_quote = '';
1373 }
1374}
1375sub sanitise_line {
1376 my ($line) = @_;
1377
1378 my $res = '';
1379 my $l = '';
1380
1381 my $qlen = 0;
1382 my $off = 0;
1383 my $c;
1384
1385 # Always copy over the diff marker.
1386 $res = substr($line, 0, 1);
1387
1388 for ($off = 1; $off < length($line); $off++) {
1389 $c = substr($line, $off, 1);
1390
Martin Roth60915b32018-08-10 21:04:05 -06001391 # Comments we are whacking completely including the begin
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001392 # and end, all to $;.
1393 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1394 $sanitise_quote = '*/';
1395
1396 substr($res, $off, 2, "$;$;");
1397 $off++;
1398 next;
1399 }
1400 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1401 $sanitise_quote = '';
1402 substr($res, $off, 2, "$;$;");
1403 $off++;
1404 next;
1405 }
1406 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1407 $sanitise_quote = '//';
1408
1409 substr($res, $off, 2, $sanitise_quote);
1410 $off++;
1411 next;
1412 }
1413
1414 # A \ in a string means ignore the next character.
1415 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1416 $c eq "\\") {
1417 substr($res, $off, 2, 'XX');
1418 $off++;
1419 next;
1420 }
1421 # Regular quotes.
1422 if ($c eq "'" || $c eq '"') {
1423 if ($sanitise_quote eq '') {
1424 $sanitise_quote = $c;
1425
1426 substr($res, $off, 1, $c);
1427 next;
1428 } elsif ($sanitise_quote eq $c) {
1429 $sanitise_quote = '';
1430 }
1431 }
1432
1433 #print "c<$c> SQ<$sanitise_quote>\n";
1434 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1435 substr($res, $off, 1, $;);
1436 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1437 substr($res, $off, 1, $;);
1438 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1439 substr($res, $off, 1, 'X');
1440 } else {
1441 substr($res, $off, 1, $c);
1442 }
1443 }
1444
1445 if ($sanitise_quote eq '//') {
1446 $sanitise_quote = '';
1447 }
1448
1449 # The pathname on a #include may be surrounded by '<' and '>'.
1450 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1451 my $clean = 'X' x length($1);
1452 $res =~ s@\<.*\>@<$clean>@;
1453
1454 # The whole of a #error is a string.
1455 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1456 my $clean = 'X' x length($1);
1457 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1458 }
1459
Martin Rothedd591d2017-03-14 10:16:29 -06001460 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1461 my $match = $1;
1462 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1463 }
1464
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001465 return $res;
1466}
1467
1468sub get_quoted_string {
1469 my ($line, $rawline) = @_;
1470
Martin Roth60915b32018-08-10 21:04:05 -06001471 return "" if (!defined($line) || !defined($rawline));
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001472 return "" if ($line !~ m/($String)/g);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001473 return substr($rawline, $-[0], $+[0] - $-[0]);
1474}
1475
1476sub ctx_statement_block {
1477 my ($linenr, $remain, $off) = @_;
1478 my $line = $linenr - 1;
1479 my $blk = '';
1480 my $soff = $off;
1481 my $coff = $off - 1;
1482 my $coff_set = 0;
1483
1484 my $loff = 0;
1485
1486 my $type = '';
1487 my $level = 0;
Julius Werner218906d2021-03-25 21:12:49 -07001488 my @stack = (['', $level]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001489 my $p;
1490 my $c;
1491 my $len = 0;
1492
1493 my $remainder;
1494 while (1) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001495 #warn "CSB: blk<$blk> remain<$remain>\n";
1496 # If we are about to drop off the end, pull in more
1497 # context.
1498 if ($off >= $len) {
1499 for (; $remain > 0; $line++) {
1500 last if (!defined $lines[$line]);
1501 next if ($lines[$line] =~ /^-/);
1502 $remain--;
1503 $loff = $len;
1504 $blk .= $lines[$line] . "\n";
1505 $len = length($blk);
1506 $line++;
1507 last;
1508 }
1509 # Bail if there is no further context.
1510 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1511 if ($off >= $len) {
1512 last;
1513 }
1514 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1515 $level++;
1516 $type = '#';
1517 }
1518 }
1519 $p = $c;
1520 $c = substr($blk, $off, 1);
1521 $remainder = substr($blk, $off);
1522
1523 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1524
1525 # Handle nested #if/#else.
1526 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1527 push(@stack, [ $type, $level ]);
Julius Werner218906d2021-03-25 21:12:49 -07001528 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/ && $#stack > 0) {
1529 ($type, $level) = @{$stack[$#stack]};
1530 } elsif ($remainder =~ /^#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001531 ($type, $level) = @{pop(@stack)};
1532 }
1533
1534 # Statement ends at the ';' or a close '}' at the
1535 # outermost level.
1536 if ($level == 0 && $c eq ';') {
1537 last;
1538 }
1539
1540 # An else is really a conditional as long as its not else if
1541 if ($level == 0 && $coff_set == 0 &&
1542 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1543 $remainder =~ /^(else)(?:\s|{)/ &&
1544 $remainder !~ /^else\s+if\b/) {
1545 $coff = $off + length($1) - 1;
1546 $coff_set = 1;
1547 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1548 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1549 }
1550
1551 if (($type eq '' || $type eq '(') && $c eq '(') {
1552 $level++;
1553 $type = '(';
1554 }
1555 if ($type eq '(' && $c eq ')') {
1556 $level--;
1557 $type = ($level != 0)? '(' : '';
1558
1559 if ($level == 0 && $coff < $soff) {
1560 $coff = $off;
1561 $coff_set = 1;
1562 #warn "CSB: mark coff<$coff>\n";
1563 }
1564 }
1565 if (($type eq '' || $type eq '{') && $c eq '{') {
1566 $level++;
1567 $type = '{';
1568 }
1569 if ($type eq '{' && $c eq '}') {
1570 $level--;
1571 $type = ($level != 0)? '{' : '';
1572
1573 if ($level == 0) {
1574 if (substr($blk, $off + 1, 1) eq ';') {
1575 $off++;
1576 }
1577 last;
1578 }
1579 }
1580 # Preprocessor commands end at the newline unless escaped.
1581 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1582 $level--;
1583 $type = '';
1584 $off++;
1585 last;
1586 }
1587 $off++;
1588 }
1589 # We are truly at the end, so shuffle to the next line.
1590 if ($off == $len) {
1591 $loff = $len + 1;
1592 $line++;
1593 $remain--;
1594 }
1595
1596 my $statement = substr($blk, $soff, $off - $soff + 1);
1597 my $condition = substr($blk, $soff, $coff - $soff + 1);
1598
1599 #warn "STATEMENT<$statement>\n";
1600 #warn "CONDITION<$condition>\n";
1601
1602 #print "coff<$coff> soff<$off> loff<$loff>\n";
1603
1604 return ($statement, $condition,
1605 $line, $remain + 1, $off - $loff + 1, $level);
1606}
1607
1608sub statement_lines {
1609 my ($stmt) = @_;
1610
1611 # Strip the diff line prefixes and rip blank lines at start and end.
1612 $stmt =~ s/(^|\n)./$1/g;
1613 $stmt =~ s/^\s*//;
1614 $stmt =~ s/\s*$//;
1615
1616 my @stmt_lines = ($stmt =~ /\n/g);
1617
1618 return $#stmt_lines + 2;
1619}
1620
1621sub statement_rawlines {
1622 my ($stmt) = @_;
1623
1624 my @stmt_lines = ($stmt =~ /\n/g);
1625
1626 return $#stmt_lines + 2;
1627}
1628
1629sub statement_block_size {
1630 my ($stmt) = @_;
1631
1632 $stmt =~ s/(^|\n)./$1/g;
1633 $stmt =~ s/^\s*{//;
1634 $stmt =~ s/}\s*$//;
1635 $stmt =~ s/^\s*//;
1636 $stmt =~ s/\s*$//;
1637
1638 my @stmt_lines = ($stmt =~ /\n/g);
1639 my @stmt_statements = ($stmt =~ /;/g);
1640
1641 my $stmt_lines = $#stmt_lines + 2;
1642 my $stmt_statements = $#stmt_statements + 1;
1643
1644 if ($stmt_lines > $stmt_statements) {
1645 return $stmt_lines;
1646 } else {
1647 return $stmt_statements;
1648 }
1649}
1650
1651sub ctx_statement_full {
1652 my ($linenr, $remain, $off) = @_;
1653 my ($statement, $condition, $level);
1654
1655 my (@chunks);
1656
1657 # Grab the first conditional/block pair.
1658 ($statement, $condition, $linenr, $remain, $off, $level) =
1659 ctx_statement_block($linenr, $remain, $off);
1660 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1661 push(@chunks, [ $condition, $statement ]);
1662 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1663 return ($level, $linenr, @chunks);
1664 }
1665
1666 # Pull in the following conditional/block pairs and see if they
1667 # could continue the statement.
1668 for (;;) {
1669 ($statement, $condition, $linenr, $remain, $off, $level) =
1670 ctx_statement_block($linenr, $remain, $off);
1671 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1672 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1673 #print "C: push\n";
1674 push(@chunks, [ $condition, $statement ]);
1675 }
1676
1677 return ($level, $linenr, @chunks);
1678}
1679
1680sub ctx_block_get {
1681 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1682 my $line;
1683 my $start = $linenr - 1;
1684 my $blk = '';
1685 my @o;
1686 my @c;
1687 my @res = ();
1688
1689 my $level = 0;
1690 my @stack = ($level);
1691 for ($line = $start; $remain > 0; $line++) {
1692 next if ($rawlines[$line] =~ /^-/);
1693 $remain--;
1694
1695 $blk .= $rawlines[$line];
1696
1697 # Handle nested #if/#else.
1698 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1699 push(@stack, $level);
Julius Werner218906d2021-03-25 21:12:49 -07001700 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/ && $#stack > 0) {
1701 $level = $stack[$#stack];
1702 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/ && $#stack > 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001703 $level = pop(@stack);
1704 }
1705
1706 foreach my $c (split(//, $lines[$line])) {
1707 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1708 if ($off > 0) {
1709 $off--;
1710 next;
1711 }
1712
1713 if ($c eq $close && $level > 0) {
1714 $level--;
1715 last if ($level == 0);
1716 } elsif ($c eq $open) {
1717 $level++;
1718 }
1719 }
1720
1721 if (!$outer || $level <= 1) {
1722 push(@res, $rawlines[$line]);
1723 }
1724
1725 last if ($level == 0);
1726 }
1727
1728 return ($level, @res);
1729}
1730sub ctx_block_outer {
1731 my ($linenr, $remain) = @_;
1732
1733 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1734 return @r;
1735}
1736sub ctx_block {
1737 my ($linenr, $remain) = @_;
1738
1739 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1740 return @r;
1741}
1742sub ctx_statement {
1743 my ($linenr, $remain, $off) = @_;
1744
1745 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1746 return @r;
1747}
1748sub ctx_block_level {
1749 my ($linenr, $remain) = @_;
1750
1751 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1752}
1753sub ctx_statement_level {
1754 my ($linenr, $remain, $off) = @_;
1755
1756 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1757}
1758
1759sub ctx_locate_comment {
1760 my ($first_line, $end_line) = @_;
1761
Elyes Haouas26e0b942022-05-22 11:11:11 +02001762 # If c99 comment on the current line, or the line before or after
1763 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1764 return $current_comment if (defined $current_comment);
1765 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1766 return $current_comment if (defined $current_comment);
1767 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1768 return $current_comment if (defined $current_comment);
1769
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001770 # Catch a comment on the end of the line itself.
Elyes Haouas26e0b942022-05-22 11:11:11 +02001771 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001772 return $current_comment if (defined $current_comment);
1773
1774 # Look through the context and try and figure out if there is a
1775 # comment.
1776 my $in_comment = 0;
1777 $current_comment = '';
1778 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1779 my $line = $rawlines[$linenr - 1];
1780 #warn " $line\n";
1781 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1782 $in_comment = 1;
1783 }
1784 if ($line =~ m@/\*@) {
1785 $in_comment = 1;
1786 }
1787 if (!$in_comment && $current_comment ne '') {
1788 $current_comment = '';
1789 }
1790 $current_comment .= $line . "\n" if ($in_comment);
1791 if ($line =~ m@\*/@) {
1792 $in_comment = 0;
1793 }
1794 }
1795
1796 chomp($current_comment);
1797 return($current_comment);
1798}
1799sub ctx_has_comment {
1800 my ($first_line, $end_line) = @_;
1801 my $cmt = ctx_locate_comment($first_line, $end_line);
1802
1803 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1804 ##print "CMMT: $cmt\n";
1805
1806 return ($cmt ne '');
1807}
1808
1809sub raw_line {
1810 my ($linenr, $cnt) = @_;
1811
1812 my $offset = $linenr - 1;
1813 $cnt++;
1814
1815 my $line;
1816 while ($cnt) {
1817 $line = $rawlines[$offset++];
1818 next if (defined($line) && $line =~ /^-/);
1819 $cnt--;
1820 }
1821
Martin Roth96a48f12016-08-29 15:30:23 -06001822 # coreboot: This probably shouldn't happen, but it does.
1823 # Return a defined value so we don't get an error.
1824 if (defined $line) {
1825 return $line;
1826 } else {
1827 return "";
1828 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001829}
1830
Martin Roth60915b32018-08-10 21:04:05 -06001831sub get_stat_real {
1832 my ($linenr, $lc) = @_;
1833
1834 my $stat_real = raw_line($linenr, 0);
1835 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1836 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1837 }
1838
1839 return $stat_real;
1840}
1841
1842sub get_stat_here {
1843 my ($linenr, $cnt, $here) = @_;
1844
1845 my $herectx = $here . "\n";
1846 for (my $n = 0; $n < $cnt; $n++) {
1847 $herectx .= raw_line($linenr, $n) . "\n";
1848 }
1849
1850 return $herectx;
1851}
1852
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001853sub cat_vet {
1854 my ($vet) = @_;
1855 my ($res, $coded);
1856
1857 $res = '';
1858 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1859 $res .= $1;
1860 if ($2 ne '') {
1861 $coded = sprintf("^%c", unpack('C', $2) + 64);
1862 $res .= $coded;
1863 }
1864 }
1865 $res =~ s/$/\$/;
1866
1867 return $res;
1868}
1869
1870my $av_preprocessor = 0;
1871my $av_pending;
1872my @av_paren_type;
1873my $av_pend_colon;
1874
1875sub annotate_reset {
1876 $av_preprocessor = 0;
1877 $av_pending = '_';
1878 @av_paren_type = ('E');
1879 $av_pend_colon = 'O';
1880}
1881
1882sub annotate_values {
1883 my ($stream, $type) = @_;
1884
1885 my $res;
1886 my $var = '_' x length($stream);
1887 my $cur = $stream;
1888
1889 print "$stream\n" if ($dbg_values > 1);
1890
1891 while (length($cur)) {
1892 @av_paren_type = ('E') if ($#av_paren_type < 0);
1893 print " <" . join('', @av_paren_type) .
1894 "> <$type> <$av_pending>" if ($dbg_values > 1);
1895 if ($cur =~ /^(\s+)/o) {
1896 print "WS($1)\n" if ($dbg_values > 1);
1897 if ($1 =~ /\n/ && $av_preprocessor) {
1898 $type = pop(@av_paren_type);
1899 $av_preprocessor = 0;
1900 }
1901
1902 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1903 print "CAST($1)\n" if ($dbg_values > 1);
1904 push(@av_paren_type, $type);
1905 $type = 'c';
1906
1907 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1908 print "DECLARE($1)\n" if ($dbg_values > 1);
1909 $type = 'T';
1910
1911 } elsif ($cur =~ /^($Modifier)\s*/) {
1912 print "MODIFIER($1)\n" if ($dbg_values > 1);
1913 $type = 'T';
1914
1915 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1916 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1917 $av_preprocessor = 1;
1918 push(@av_paren_type, $type);
1919 if ($2 ne '') {
1920 $av_pending = 'N';
1921 }
1922 $type = 'E';
1923
1924 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1925 print "UNDEF($1)\n" if ($dbg_values > 1);
1926 $av_preprocessor = 1;
1927 push(@av_paren_type, $type);
1928
1929 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1930 print "PRE_START($1)\n" if ($dbg_values > 1);
1931 $av_preprocessor = 1;
1932
1933 push(@av_paren_type, $type);
1934 push(@av_paren_type, $type);
1935 $type = 'E';
1936
1937 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1938 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1939 $av_preprocessor = 1;
1940
1941 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1942
1943 $type = 'E';
1944
1945 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1946 print "PRE_END($1)\n" if ($dbg_values > 1);
1947
1948 $av_preprocessor = 1;
1949
1950 # Assume all arms of the conditional end as this
1951 # one does, and continue as if the #endif was not here.
1952 pop(@av_paren_type);
1953 push(@av_paren_type, $type);
1954 $type = 'E';
1955
1956 } elsif ($cur =~ /^(\\\n)/o) {
1957 print "PRECONT($1)\n" if ($dbg_values > 1);
1958
1959 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1960 print "ATTR($1)\n" if ($dbg_values > 1);
1961 $av_pending = $type;
1962 $type = 'N';
1963
1964 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1965 print "SIZEOF($1)\n" if ($dbg_values > 1);
1966 if (defined $2) {
1967 $av_pending = 'V';
1968 }
1969 $type = 'N';
1970
1971 } elsif ($cur =~ /^(if|while|for)\b/o) {
1972 print "COND($1)\n" if ($dbg_values > 1);
1973 $av_pending = 'E';
1974 $type = 'N';
1975
1976 } elsif ($cur =~/^(case)/o) {
1977 print "CASE($1)\n" if ($dbg_values > 1);
1978 $av_pend_colon = 'C';
1979 $type = 'N';
1980
1981 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1982 print "KEYWORD($1)\n" if ($dbg_values > 1);
1983 $type = 'N';
1984
1985 } elsif ($cur =~ /^(\()/o) {
1986 print "PAREN('$1')\n" if ($dbg_values > 1);
1987 push(@av_paren_type, $av_pending);
1988 $av_pending = '_';
1989 $type = 'N';
1990
1991 } elsif ($cur =~ /^(\))/o) {
1992 my $new_type = pop(@av_paren_type);
1993 if ($new_type ne '_') {
1994 $type = $new_type;
1995 print "PAREN('$1') -> $type\n"
1996 if ($dbg_values > 1);
1997 } else {
1998 print "PAREN('$1')\n" if ($dbg_values > 1);
1999 }
2000
2001 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2002 print "FUNC($1)\n" if ($dbg_values > 1);
2003 $type = 'V';
2004 $av_pending = 'V';
2005
2006 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2007 if (defined $2 && $type eq 'C' || $type eq 'T') {
2008 $av_pend_colon = 'B';
2009 } elsif ($type eq 'E') {
2010 $av_pend_colon = 'L';
2011 }
2012 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2013 $type = 'V';
2014
2015 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2016 print "IDENT($1)\n" if ($dbg_values > 1);
2017 $type = 'V';
2018
2019 } elsif ($cur =~ /^($Assignment)/o) {
2020 print "ASSIGN($1)\n" if ($dbg_values > 1);
2021 $type = 'N';
2022
2023 } elsif ($cur =~/^(;|{|})/) {
2024 print "END($1)\n" if ($dbg_values > 1);
2025 $type = 'E';
2026 $av_pend_colon = 'O';
2027
2028 } elsif ($cur =~/^(,)/) {
2029 print "COMMA($1)\n" if ($dbg_values > 1);
2030 $type = 'C';
2031
2032 } elsif ($cur =~ /^(\?)/o) {
2033 print "QUESTION($1)\n" if ($dbg_values > 1);
2034 $type = 'N';
2035
2036 } elsif ($cur =~ /^(:)/o) {
2037 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2038
2039 substr($var, length($res), 1, $av_pend_colon);
2040 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2041 $type = 'E';
2042 } else {
2043 $type = 'N';
2044 }
2045 $av_pend_colon = 'O';
2046
2047 } elsif ($cur =~ /^(\[)/o) {
2048 print "CLOSE($1)\n" if ($dbg_values > 1);
2049 $type = 'N';
2050
2051 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2052 my $variant;
2053
2054 print "OPV($1)\n" if ($dbg_values > 1);
2055 if ($type eq 'V') {
2056 $variant = 'B';
2057 } else {
2058 $variant = 'U';
2059 }
2060
2061 substr($var, length($res), 1, $variant);
2062 $type = 'N';
2063
2064 } elsif ($cur =~ /^($Operators)/o) {
2065 print "OP($1)\n" if ($dbg_values > 1);
2066 if ($1 ne '++' && $1 ne '--') {
2067 $type = 'N';
2068 }
2069
2070 } elsif ($cur =~ /(^.)/o) {
2071 print "C($1)\n" if ($dbg_values > 1);
2072 }
2073 if (defined $1) {
2074 $cur = substr($cur, length($1));
2075 $res .= $type x length($1);
2076 }
2077 }
2078
2079 return ($res, $var);
2080}
2081
2082sub possible {
2083 my ($possible, $line) = @_;
2084 my $notPermitted = qr{(?:
2085 ^(?:
2086 $Modifier|
2087 $Storage|
2088 $Type|
2089 DEFINE_\S+
2090 )$|
2091 ^(?:
2092 goto|
2093 return|
2094 case|
2095 else|
2096 asm|__asm__|
2097 do|
2098 \#|
2099 \#\#|
2100 )(?:\s|$)|
2101 ^(?:typedef|struct|enum)\b
2102 )}x;
2103 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2104 if ($possible !~ $notPermitted) {
2105 # Check for modifiers.
2106 $possible =~ s/\s*$Storage\s*//g;
2107 $possible =~ s/\s*$Sparse\s*//g;
2108 if ($possible =~ /^\s*$/) {
2109
2110 } elsif ($possible =~ /\s/) {
2111 $possible =~ s/\s*$Type\s*//g;
2112 for my $modifier (split(' ', $possible)) {
2113 if ($modifier !~ $notPermitted) {
2114 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002115 push(@modifierListFile, $modifier);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002116 }
2117 }
2118
2119 } else {
2120 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002121 push(@typeListFile, $possible);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002122 }
2123 build_types();
2124 } else {
2125 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2126 }
2127}
2128
2129my $prefix = '';
2130
2131sub show_type {
2132 my ($type) = @_;
2133
Martin Rothedd591d2017-03-14 10:16:29 -06002134 $type =~ tr/[a-z]/[A-Z]/;
2135
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002136 return defined $use_type{$type} if (scalar keys %use_type > 0);
2137
2138 return !defined $ignore_type{$type};
2139}
2140
2141sub report {
2142 my ($level, $type, $msg) = @_;
2143
2144 if (!show_type($type) ||
2145 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2146 return 0;
2147 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002148 my $output = '';
Martin Roth387dec82017-09-17 19:20:46 -06002149 if ($color) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002150 if ($level eq 'ERROR') {
2151 $output .= RED;
2152 } elsif ($level eq 'WARNING') {
2153 $output .= YELLOW;
2154 } else {
2155 $output .= GREEN;
2156 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002157 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002158 $output .= $prefix . $level . ':';
2159 if ($show_types) {
Martin Roth387dec82017-09-17 19:20:46 -06002160 $output .= BLUE if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002161 $output .= "$type:";
2162 }
Martin Roth387dec82017-09-17 19:20:46 -06002163 $output .= RESET if ($color);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002164 $output .= ' ' . $msg . "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002165
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002166 if ($showfile) {
2167 my @lines = split("\n", $output, -1);
2168 splice(@lines, 1, 1);
2169 $output = join("\n", @lines);
2170 }
Elyes Haouas46b07e52022-04-07 10:07:34 +02002171
2172 if ($terse) {
2173 $output = (split('\n', $output))[0] . "\n";
2174 }
2175
2176 if ($verbose && exists($verbose_messages{$type}) &&
2177 !exists($verbose_emitted{$type})) {
2178 $output .= $verbose_messages{$type} . "\n\n";
2179 $verbose_emitted{$type} = 1;
2180 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002181
2182 push(our @report, $output);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002183
2184 return 1;
2185}
2186
2187sub report_dump {
2188 our @report;
2189}
2190
2191sub fixup_current_range {
2192 my ($lineRef, $offset, $length) = @_;
2193
2194 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2195 my $o = $1;
2196 my $l = $2;
2197 my $no = $o + $offset;
2198 my $nl = $l + $length;
2199 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2200 }
2201}
2202
2203sub fix_inserted_deleted_lines {
2204 my ($linesRef, $insertedRef, $deletedRef) = @_;
2205
2206 my $range_last_linenr = 0;
2207 my $delta_offset = 0;
2208
2209 my $old_linenr = 0;
2210 my $new_linenr = 0;
2211
2212 my $next_insert = 0;
2213 my $next_delete = 0;
2214
2215 my @lines = ();
2216
2217 my $inserted = @{$insertedRef}[$next_insert++];
2218 my $deleted = @{$deletedRef}[$next_delete++];
2219
2220 foreach my $old_line (@{$linesRef}) {
2221 my $save_line = 1;
2222 my $line = $old_line; #don't modify the array
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002223 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002224 $delta_offset = 0;
2225 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2226 $range_last_linenr = $new_linenr;
2227 fixup_current_range(\$line, $delta_offset, 0);
2228 }
2229
2230 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2231 $deleted = @{$deletedRef}[$next_delete++];
2232 $save_line = 0;
2233 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2234 }
2235
2236 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2237 push(@lines, ${$inserted}{'LINE'});
2238 $inserted = @{$insertedRef}[$next_insert++];
2239 $new_linenr++;
2240 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2241 }
2242
2243 if ($save_line) {
2244 push(@lines, $line);
2245 $new_linenr++;
2246 }
2247
2248 $old_linenr++;
2249 }
2250
2251 return @lines;
2252}
2253
2254sub fix_insert_line {
2255 my ($linenr, $line) = @_;
2256
2257 my $inserted = {
2258 LINENR => $linenr,
2259 LINE => $line,
2260 };
2261 push(@fixed_inserted, $inserted);
2262}
2263
2264sub fix_delete_line {
2265 my ($linenr, $line) = @_;
2266
2267 my $deleted = {
2268 LINENR => $linenr,
2269 LINE => $line,
2270 };
2271
2272 push(@fixed_deleted, $deleted);
2273}
2274
2275sub ERROR {
2276 my ($type, $msg) = @_;
2277
2278 if (report("ERROR", $type, $msg)) {
2279 our $clean = 0;
2280 our $cnt_error++;
2281 return 1;
2282 }
2283 return 0;
2284}
2285sub WARN {
2286 my ($type, $msg) = @_;
2287
2288 if (report("WARNING", $type, $msg)) {
2289 our $clean = 0;
2290 our $cnt_warn++;
2291 return 1;
2292 }
2293 return 0;
2294}
2295sub CHK {
2296 my ($type, $msg) = @_;
2297
2298 if ($check && report("CHECK", $type, $msg)) {
2299 our $clean = 0;
2300 our $cnt_chk++;
2301 return 1;
2302 }
2303 return 0;
2304}
2305
2306sub check_absolute_file {
2307 my ($absolute, $herecurr) = @_;
2308 my $file = $absolute;
2309
2310 ##print "absolute<$absolute>\n";
2311
2312 # See if any suffix of this path is a path within the tree.
2313 while ($file =~ s@^[^/]*/@@) {
2314 if (-f "$root/$file") {
2315 ##print "file<$file>\n";
2316 last;
2317 }
2318 }
2319 if (! -f _) {
2320 return 0;
2321 }
2322
2323 # It is, so see if the prefix is acceptable.
2324 my $prefix = $absolute;
2325 substr($prefix, -length($file)) = '';
2326
2327 ##print "prefix<$prefix>\n";
2328 if ($prefix ne ".../") {
2329 WARN("USE_RELATIVE_PATH",
2330 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2331 }
2332}
2333
2334sub trim {
2335 my ($string) = @_;
2336
2337 $string =~ s/^\s+|\s+$//g;
2338
2339 return $string;
2340}
2341
2342sub ltrim {
2343 my ($string) = @_;
2344
2345 $string =~ s/^\s+//;
2346
2347 return $string;
2348}
2349
2350sub rtrim {
2351 my ($string) = @_;
2352
2353 $string =~ s/\s+$//;
2354
2355 return $string;
2356}
2357
2358sub string_find_replace {
2359 my ($string, $find, $replace) = @_;
2360
2361 $string =~ s/$find/$replace/g;
2362
2363 return $string;
2364}
2365
2366sub tabify {
2367 my ($leading) = @_;
2368
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01002369 my $source_indent = $tabsize;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002370 my $max_spaces_before_tab = $source_indent - 1;
2371 my $spaces_to_tab = " " x $source_indent;
2372
2373 #convert leading spaces to tabs
2374 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2375 #Remove spaces before a tab
2376 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2377
2378 return "$leading";
2379}
2380
2381sub pos_last_openparen {
2382 my ($line) = @_;
2383
2384 my $pos = 0;
2385
2386 my $opens = $line =~ tr/\(/\(/;
2387 my $closes = $line =~ tr/\)/\)/;
2388
2389 my $last_openparen = 0;
2390
2391 if (($opens == 0) || ($closes >= $opens)) {
2392 return -1;
2393 }
2394
2395 my $len = length($line);
2396
2397 for ($pos = 0; $pos < $len; $pos++) {
2398 my $string = substr($line, $pos);
2399 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2400 $pos += length($1) - 1;
2401 } elsif (substr($line, $pos, 1) eq '(') {
2402 $last_openparen = $pos;
2403 } elsif (index($string, '(') == -1) {
2404 last;
2405 }
2406 }
2407
2408 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2409}
2410
Elyes Haouasf62a9892022-04-12 12:17:50 +02002411sub get_raw_comment {
2412 my ($line, $rawline) = @_;
2413 my $comment = '';
2414
2415 for my $i (0 .. (length($line) - 1)) {
2416 if (substr($line, $i, 1) eq "$;") {
2417 $comment .= substr($rawline, $i, 1);
2418 }
2419 }
2420
2421 return $comment;
2422}
2423
2424sub exclude_global_initialisers {
2425 my ($realfile) = @_;
2426
2427 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2428 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2429 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2430 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2431}
2432
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002433sub process {
2434 my $filename = shift;
2435
2436 my $linenr=0;
2437 my $prevline="";
2438 my $prevrawline="";
2439 my $stashline="";
2440 my $stashrawline="";
2441
2442 my $length;
2443 my $indent;
2444 my $previndent=0;
2445 my $stashindent=0;
2446
2447 our $clean = 1;
2448 my $signoff = 0;
2449 my $is_patch = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002450 my $in_header_lines = $file ? 0 : 1;
2451 my $in_commit_log = 0; #Scanning lines before patch
Martin Rothedd591d2017-03-14 10:16:29 -06002452 my $has_commit_log = 0; #Encountered lines before patch
2453 my $commit_log_possible_stack_dump = 0;
Elyes Haouas26e0b942022-05-22 11:11:11 +02002454 my $commit_log_long_line = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002455 my $commit_log_has_diff = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002456 my $reported_maintainer_file = 0;
2457 my $non_utf8_charset = 0;
2458
2459 my $last_blank_line = 0;
2460 my $last_coalesced_string_linenr = -1;
2461
2462 our @report = ();
2463 our $cnt_lines = 0;
2464 our $cnt_error = 0;
2465 our $cnt_warn = 0;
2466 our $cnt_chk = 0;
2467
2468 # Trace the real file/line as we go.
2469 my $realfile = '';
2470 my $realline = 0;
2471 my $realcnt = 0;
2472 my $here = '';
Martin Rothedd591d2017-03-14 10:16:29 -06002473 my $context_function; #undef'd unless there's a known function
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002474 my $in_comment = 0;
2475 my $comment_edge = 0;
2476 my $first_line = 0;
2477 my $p1_prefix = '';
2478
2479 my $prev_values = 'E';
2480
2481 # suppression flags
2482 my %suppress_ifbraces;
2483 my %suppress_whiletrailers;
2484 my %suppress_export;
2485 my $suppress_statement = 0;
2486
2487 my %signatures = ();
2488
2489 # Pre-scan the patch sanitizing the lines.
2490 # Pre-scan the patch looking for any __setup documentation.
2491 #
2492 my @setup_docs = ();
2493 my $setup_docs = 0;
2494
2495 my $camelcase_file_seeded = 0;
2496
Martin Roth60915b32018-08-10 21:04:05 -06002497 my $checklicenseline = 1;
2498
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002499 sanitise_line_reset();
2500 my $line;
2501 foreach my $rawline (@rawlines) {
2502 $linenr++;
2503 $line = $rawline;
2504
2505 push(@fixed, $rawline) if ($fix);
2506
2507 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2508 $setup_docs = 0;
Martin Rothedd591d2017-03-14 10:16:29 -06002509 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002510 $setup_docs = 1;
2511 }
2512 #next;
2513 }
Martin Roth387dec82017-09-17 19:20:46 -06002514 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002515 $realline=$1-1;
2516 if (defined $2) {
2517 $realcnt=$3+1;
2518 } else {
2519 $realcnt=1+1;
2520 }
2521 $in_comment = 0;
2522
2523 # Guestimate if this is a continuing comment. Run
2524 # the context looking for a comment "edge". If this
2525 # edge is a close comment then we must be in a comment
2526 # at context start.
2527 my $edge;
2528 my $cnt = $realcnt;
2529 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2530 next if (defined $rawlines[$ln - 1] &&
2531 $rawlines[$ln - 1] =~ /^-/);
2532 $cnt--;
2533 #print "RAW<$rawlines[$ln - 1]>\n";
2534 last if (!defined $rawlines[$ln - 1]);
2535 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2536 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2537 ($edge) = $1;
2538 last;
2539 }
2540 }
2541 if (defined $edge && $edge eq '*/') {
2542 $in_comment = 1;
2543 }
2544
2545 # Guestimate if this is a continuing comment. If this
2546 # is the start of a diff block and this line starts
2547 # ' *' then it is very likely a comment.
2548 if (!defined $edge &&
2549 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2550 {
2551 $in_comment = 1;
2552 }
2553
2554 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2555 sanitise_line_reset($in_comment);
2556
2557 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2558 # Standardise the strings and chars within the input to
2559 # simplify matching -- only bother with positive lines.
2560 $line = sanitise_line($rawline);
2561 }
2562 push(@lines, $line);
2563
2564 if ($realcnt > 1) {
2565 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2566 } else {
2567 $realcnt = 0;
2568 }
2569
2570 #print "==>$rawline\n";
2571 #print "-->$line\n";
2572
2573 if ($setup_docs && $line =~ /^\+/) {
2574 push(@setup_docs, $line);
2575 }
2576 }
2577
2578 $prefix = '';
2579
2580 $realcnt = 0;
2581 $linenr = 0;
2582 $fixlinenr = -1;
2583 foreach my $line (@lines) {
2584 $linenr++;
2585 $fixlinenr++;
2586 my $sline = $line; #copy of $line
2587 $sline =~ s/$;/ /g; #with comments as spaces
2588
2589 my $rawline = $rawlines[$linenr - 1];
Elyes Haouasf62a9892022-04-12 12:17:50 +02002590 my $raw_comment = get_raw_comment($line, $rawline);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002591
Martin Roth60915b32018-08-10 21:04:05 -06002592# check if it's a mode change, rename or start of a patch
2593 if (!$in_commit_log &&
2594 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2595 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2596 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2597 $is_patch = 1;
2598 }
2599
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002600#extract the line range in the file after the patch is applied
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002601 if (!$in_commit_log &&
Martin Roth387dec82017-09-17 19:20:46 -06002602 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2603 my $context = $4;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002604 $is_patch = 1;
2605 $first_line = $linenr + 1;
2606 $realline=$1-1;
2607 if (defined $2) {
2608 $realcnt=$3+1;
2609 } else {
2610 $realcnt=1+1;
2611 }
2612 annotate_reset();
2613 $prev_values = 'E';
2614
2615 %suppress_ifbraces = ();
2616 %suppress_whiletrailers = ();
2617 %suppress_export = ();
2618 $suppress_statement = 0;
Martin Roth387dec82017-09-17 19:20:46 -06002619 if ($context =~ /\b(\w+)\s*\(/) {
2620 $context_function = $1;
2621 } else {
2622 undef $context_function;
2623 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002624 next;
2625
2626# track the line number as we move through the hunk, note that
2627# new versions of GNU diff omit the leading space on completely
2628# blank context lines so we need to count that too.
2629 } elsif ($line =~ /^( |\+|$)/) {
2630 $realline++;
2631 $realcnt-- if ($realcnt != 0);
2632
2633 # Measure the line length and indent.
2634 ($length, $indent) = line_stats($rawline);
2635
2636 # Track the previous line.
2637 ($prevline, $stashline) = ($stashline, $line);
2638 ($previndent, $stashindent) = ($stashindent, $indent);
2639 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2640
2641 #warn "line<$line>\n";
2642
2643 } elsif ($realcnt == 1) {
2644 $realcnt--;
2645 }
2646
2647 my $hunk_line = ($realcnt != 0);
2648
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002649 $here = "#$linenr: " if (!$file);
2650 $here = "#$realline: " if ($file);
2651
2652 my $found_file = 0;
2653 # extract the filename as it passes
2654 if ($line =~ /^diff --git.*?(\S+)$/) {
2655 $realfile = $1;
2656 $realfile =~ s@^([^/]*)/@@ if (!$file);
2657 $in_commit_log = 0;
2658 $found_file = 1;
2659 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2660 $realfile = $1;
2661 $realfile =~ s@^([^/]*)/@@ if (!$file);
2662 $in_commit_log = 0;
2663
2664 $p1_prefix = $1;
2665 if (!$file && $tree && $p1_prefix ne '' &&
2666 -e "$root/$p1_prefix") {
2667 WARN("PATCH_PREFIX",
2668 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2669 }
2670
2671 if ($realfile =~ m@^include/asm/@) {
2672 ERROR("MODIFIED_INCLUDE_ASM",
2673 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2674 }
2675 $found_file = 1;
2676 }
2677
Martin Rothedd591d2017-03-14 10:16:29 -06002678 # coreboot
Martin Rotha3cac872017-03-04 18:17:35 -07002679 my $skipme = 0;
2680 foreach (@exclude) {
2681 if ($realfile =~ m@^(?:$_/)@) {
2682 $skipme = 1;
2683 }
2684 }
2685 if ($skipme) {
2686 next;
2687 }
2688
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002689#make up the handle for any error we report on this line
2690 if ($showfile) {
2691 $prefix = "$realfile:$realline: "
2692 } elsif ($emacs) {
2693 if ($file) {
2694 $prefix = "$filename:$realline: ";
2695 } else {
2696 $prefix = "$filename:$linenr: ";
2697 }
2698 }
2699
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002700 if ($found_file) {
Martin Rothedd591d2017-03-14 10:16:29 -06002701 if (is_maintained_obsolete($realfile)) {
2702 WARN("OBSOLETE",
2703 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2704 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002705 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002706 $check = 1;
2707 } else {
2708 $check = $check_orig;
2709 }
Martin Roth60915b32018-08-10 21:04:05 -06002710 $checklicenseline = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002711 next;
2712 }
2713
2714 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2715
2716 my $hereline = "$here\n$rawline\n";
2717 my $herecurr = "$here\n$rawline\n";
2718 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2719
2720 $cnt_lines++ if ($realcnt != 0);
2721
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002722# Check if the commit log has what seems like a diff which can confuse patch
2723 if ($in_commit_log && !$commit_log_has_diff &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02002724 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2725 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002726 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2727 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2728 ERROR("DIFF_IN_COMMIT_MSG",
2729 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2730 $commit_log_has_diff = 1;
2731 }
2732
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002733# Check for incorrect file permissions
2734 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2735 my $permhere = $here . "FILE: $realfile\n";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002736 if ($realfile !~ m@scripts/@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002737 $realfile !~ /\.(py|pl|awk|sh)$/) {
2738 ERROR("EXECUTE_PERMISSIONS",
2739 "do not set execute permissions for source files\n" . $permhere);
2740 }
2741 }
2742
2743# Check the patch for a signoff:
2744 if ($line =~ /^\s*signed-off-by:/i) {
2745 $signoff++;
2746 $in_commit_log = 0;
2747 }
2748
2749# Check if MAINTAINERS is being updated. If so, there's probably no need to
2750# emit the "does MAINTAINERS need updating?" message on file add/move/delete
2751 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2752 $reported_maintainer_file = 1;
2753 }
2754
2755# Check signature styles
2756 if (!$in_header_lines &&
2757 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2758 my $space_before = $1;
2759 my $sign_off = $2;
2760 my $space_after = $3;
2761 my $email = $4;
2762 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2763
2764 if ($sign_off !~ /$signature_tags/) {
2765 WARN("BAD_SIGN_OFF",
2766 "Non-standard signature: $sign_off\n" . $herecurr);
2767 }
2768 if (defined $space_before && $space_before ne "") {
2769 if (WARN("BAD_SIGN_OFF",
2770 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2771 $fix) {
2772 $fixed[$fixlinenr] =
2773 "$ucfirst_sign_off $email";
2774 }
2775 }
2776 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2777 if (WARN("BAD_SIGN_OFF",
2778 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2779 $fix) {
2780 $fixed[$fixlinenr] =
2781 "$ucfirst_sign_off $email";
2782 }
2783
2784 }
2785 if (!defined $space_after || $space_after ne " ") {
2786 if (WARN("BAD_SIGN_OFF",
2787 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2788 $fix) {
2789 $fixed[$fixlinenr] =
2790 "$ucfirst_sign_off $email";
2791 }
2792 }
2793
2794 my ($email_name, $email_address, $comment) = parse_email($email);
2795 my $suggested_email = format_email(($email_name, $email_address));
2796 if ($suggested_email eq "") {
2797 ERROR("BAD_SIGN_OFF",
2798 "Unrecognized email address: '$email'\n" . $herecurr);
2799 } else {
2800 my $dequoted = $suggested_email;
2801 $dequoted =~ s/^"//;
2802 $dequoted =~ s/" </ </;
2803 # Don't force email to have quotes
2804 # Allow just an angle bracketed address
2805 if ("$dequoted$comment" ne $email &&
2806 "<$email_address>$comment" ne $email &&
2807 "$suggested_email$comment" ne $email) {
2808 WARN("BAD_SIGN_OFF",
2809 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2810 }
2811 }
2812
2813# Check for duplicate signatures
2814 my $sig_nospace = $line;
2815 $sig_nospace =~ s/\s//g;
2816 $sig_nospace = lc($sig_nospace);
2817 if (defined $signatures{$sig_nospace}) {
2818 WARN("BAD_SIGN_OFF",
2819 "Duplicate signature\n" . $herecurr);
2820 } else {
2821 $signatures{$sig_nospace} = 1;
2822 }
2823 }
2824
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002825# Check email subject for common tools that don't need to be mentioned
2826 if ($in_header_lines &&
2827 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2828 WARN("EMAIL_SUBJECT",
2829 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2830 }
2831
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002832# Check for unwanted Gerrit info
2833 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2834 ERROR("GERRIT_CHANGE_ID",
2835 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2836 }
2837
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002838# Check if the commit log is in a possible stack dump
2839 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2840 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2841 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2842 # timestamp
Elyes Haouas26e0b942022-05-22 11:11:11 +02002843 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2844 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2845 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2846 # stack dump address styles
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002847 $commit_log_possible_stack_dump = 1;
2848 }
2849
Martin Roth10d34b72022-03-22 16:24:44 -06002850# coreboot: The line length limit is 72
2851# Check for line lengths > 72 in commit log
2852 if ($in_commit_log && length($line) > 72 &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002853 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2854 # file delta changes
Elyes HAOUASac690492022-01-29 07:59:17 +01002855 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002856 # filename then :
Elyes HAOUASac690492022-01-29 07:59:17 +01002857 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
2858 # A Fixes: or Link: line or signature tag line
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002859 $commit_log_possible_stack_dump)) {
2860 WARN("COMMIT_LOG_LONG_LINE",
Paul Menzeldd1ee272021-12-09 12:49:35 +01002861 "Possible unwrapped commit description (prefer a maximum 72 chars per line)\n" . $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02002862 $commit_log_long_line = 1;
Martin Roth10d34b72022-03-22 16:24:44 -06002863 }
2864
2865# coreboot: The line subject limit is 65
2866# Check for line lengths > 65 in commit subject
Martin Roth97e7eea2022-03-22 18:06:15 -06002867# coreboot: Check for a period at the end of the subject line
Martin Roth10d34b72022-03-22 16:24:44 -06002868 if ($in_header_lines &&
2869 $line =~ /^Subject: /) {
2870 $line = $line.$rawlines[$linenr];
2871 $line =~ s/^Subject: \[PATCH\] //;
Martin Roth341a53d2022-05-24 18:46:45 -06002872 if (length($line) - length("Subject: [PATCH] ") > 65) {
2873 WARN("COMMIT_LOG_LONG_LINE",
2874 "Possible long commit subject (prefer a maximum 65 characters)\n" . $herecurr);
Martin Roth10d34b72022-03-22 16:24:44 -06002875 }
Martin Roth97e7eea2022-03-22 18:06:15 -06002876 if ($line =~ /\.$/) {
2877 WARN("SUBJECT_HAS_FULL_STOP",
2878 "Subject line should not end with a period.\n" . $herecurr);
2879 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002880 }
2881
2882# Reset possible stack dump if a blank line is found
2883 if ($in_commit_log && $commit_log_possible_stack_dump &&
2884 $line =~ /^\s*$/) {
2885 $commit_log_possible_stack_dump = 0;
2886 }
2887
2888# Check for git id commit length and improperly formed commit descriptions
2889 if ($in_commit_log && !$commit_log_possible_stack_dump &&
Martin Rothedd591d2017-03-14 10:16:29 -06002890 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
Martin Roth387dec82017-09-17 19:20:46 -06002891 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002892 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06002893 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002894 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2895 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2896 my $init_char = "c";
2897 my $orig_commit = "";
2898 my $short = 1;
2899 my $long = 0;
2900 my $case = 1;
2901 my $space = 1;
2902 my $hasdesc = 0;
2903 my $hasparens = 0;
2904 my $id = '0123456789ab';
2905 my $orig_desc = "commit description";
2906 my $description = "";
2907
2908 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2909 $init_char = $1;
2910 $orig_commit = lc($2);
2911 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2912 $orig_commit = lc($1);
2913 }
2914
2915 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2916 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2917 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2918 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2919 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2920 $orig_desc = $1;
2921 $hasparens = 1;
2922 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2923 defined $rawlines[$linenr] &&
2924 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2925 $orig_desc = $1;
2926 $hasparens = 1;
2927 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2928 defined $rawlines[$linenr] &&
2929 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2930 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2931 $orig_desc = $1;
2932 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2933 $orig_desc .= " " . $1;
2934 $hasparens = 1;
2935 }
2936
2937 ($id, $description) = git_commit_info($orig_commit,
2938 $id, $orig_desc);
2939
Martin Roth387dec82017-09-17 19:20:46 -06002940 if (defined($id) &&
2941 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002942 ERROR("GIT_COMMIT_ID",
2943 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2944 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002945 }
2946
2947# Check for added, moved or deleted files
2948 if (!$reported_maintainer_file && !$in_commit_log &&
2949 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2950 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2951 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2952 (defined($1) || defined($2))))) {
Martin Rothedd591d2017-03-14 10:16:29 -06002953 $is_patch = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002954 $reported_maintainer_file = 1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002955 WARN("FILE_PATH_CHANGES",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002956 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2957 }
2958
2959# Check for wrappage within a valid hunk of the file
2960 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2961 ERROR("CORRUPTED_PATCH",
2962 "patch seems to be corrupt (line wrapped?)\n" .
2963 $herecurr) if (!$emitted_corrupt++);
2964 }
2965
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002966# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2967 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2968 $rawline !~ m/^$UTF8*$/) {
2969 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2970
2971 my $blank = copy_spacing($rawline);
2972 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2973 my $hereptr = "$hereline$ptr\n";
2974
2975 CHK("INVALID_UTF8",
2976 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2977 }
2978
2979# Check if it's the start of a commit log
2980# (not a header line and we haven't seen the patch filename)
2981 if ($in_header_lines && $realfile =~ /^$/ &&
Martin Roth387dec82017-09-17 19:20:46 -06002982 !($rawline =~ /^\s+(?:\S|$)/ ||
2983 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002984 $in_header_lines = 0;
2985 $in_commit_log = 1;
Martin Rothedd591d2017-03-14 10:16:29 -06002986 $has_commit_log = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002987 }
2988
2989# Check if there is UTF-8 in a commit log when a mail header has explicitly
2990# declined it, i.e defined some charset where it is missing.
2991 if ($in_header_lines &&
2992 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2993 $1 !~ /utf-8/i) {
2994 $non_utf8_charset = 1;
2995 }
2996
2997 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2998 $rawline =~ /$NON_ASCII_UTF8/) {
2999 WARN("UTF8_BEFORE_PATCH",
3000 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3001 }
3002
Martin Rothedd591d2017-03-14 10:16:29 -06003003# Check for absolute kernel paths in commit message
3004 if ($tree && $in_commit_log) {
3005 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3006 my $file = $1;
3007
3008 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3009 check_absolute_file($1, $herecurr)) {
3010 #
3011 } else {
3012 check_absolute_file($file, $herecurr);
3013 }
3014 }
3015 }
3016
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003017# Check for various typo / spelling mistakes
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003018 if (defined($misspellings) &&
3019 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02003020 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003021 my $typo = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003022 my $blank = copy_spacing($rawline);
3023 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3024 my $hereptr = "$hereline$ptr\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003025 my $typo_fix = $spelling_fix{lc($typo)};
3026 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3027 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
Martin Roth387dec82017-09-17 19:20:46 -06003028 my $msg_level = \&WARN;
3029 $msg_level = \&CHK if ($file);
3030 if (&{$msg_level}("TYPO_SPELLING",
Elyes Haouas26e0b942022-05-22 11:11:11 +02003031 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003032 $fix) {
3033 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3034 }
3035 }
3036 }
Elyes Haouas84083a22022-04-12 12:28:32 +02003037# check for repeated words separated by a single space
3038# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3039 if (($rawline =~ /^\+/ || $in_commit_log) &&
3040 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3041 pos($rawline) = 1 if (!$in_commit_log);
3042 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3043
3044 my $first = $1;
3045 my $second = $2;
3046 my $start_pos = $-[1];
3047 my $end_pos = $+[2];
3048 if ($first =~ /(?:struct|union|enum)/) {
3049 pos($rawline) += length($first) + length($second) + 1;
3050 next;
3051 }
3052
3053 next if (lc($first) ne lc($second));
3054 next if ($first eq 'long');
3055
3056 # check for character before and after the word matches
3057 my $start_char = '';
3058 my $end_char = '';
3059 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3060 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3061
3062 next if ($start_char =~ /^\S$/);
3063 next if (index(" \t.,;?!", $end_char) == -1);
3064
3065 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3066 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3067 next if (!exists($allow_repeated_words{lc($first)}));
3068 }
3069
3070 if (WARN("REPEATED_WORD",
3071 "Possible repeated word: '$first'\n" . $herecurr) &&
3072 $fix) {
3073 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3074 }
3075 }
3076
3077 # if it's a repeated word on consecutive lines in a comment block
3078 if ($prevline =~ /$;+\s*$/ &&
3079 $prevrawline =~ /($word_pattern)\s*$/) {
3080 my $last_word = $1;
3081 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3082 if (WARN("REPEATED_WORD",
3083 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3084 $fix) {
3085 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3086 }
3087 }
3088 }
3089 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003090
3091# ignore non-hunk lines and lines being removed
3092 next if (!$hunk_line || $line =~ /^-/);
3093
3094#trailing whitespace
3095 if ($line =~ /^\+.*\015/) {
3096 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3097 if (ERROR("DOS_LINE_ENDINGS",
3098 "DOS line endings\n" . $herevet) &&
3099 $fix) {
3100 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3101 }
3102 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3103 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3104 if (ERROR("TRAILING_WHITESPACE",
3105 "trailing whitespace\n" . $herevet) &&
3106 $fix) {
3107 $fixed[$fixlinenr] =~ s/\s+$//;
3108 }
3109
3110 $rpt_cleaners = 1;
3111 }
3112
3113# Check for FSF mailing addresses.
3114 if ($rawline =~ /\bwrite to the Free/i ||
Martin Rothedd591d2017-03-14 10:16:29 -06003115 $rawline =~ /\b675\s+Mass\s+Ave/i ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003116 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3117 $rawline =~ /\b51\s+Franklin\s+St/i) {
3118 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
Martin Roth387dec82017-09-17 19:20:46 -06003119 my $msg_level = \&ERROR;
3120 $msg_level = \&CHK if ($file);
3121 &{$msg_level}("FSF_MAILING_ADDRESS",
3122 "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 +01003123 }
3124
3125# check for Kconfig help text having a real description
3126# Only applies when adding the entry originally, after that we do not have
3127# sufficient context to determine whether it is indeed long enough.
3128 if ($realfile =~ /Kconfig/ &&
Martin Roth60915b32018-08-10 21:04:05 -06003129 # 'choice' is usually the last thing on the line (though
3130 # Kconfig supports named choices), so use a word boundary
3131 # (\b) rather than a whitespace character (\s)
3132 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
Elyes Haouasf62a9892022-04-12 12:17:50 +02003133 my $ln = $linenr;
3134 my $needs_help = 0;
3135 my $has_help = 0;
3136 my $help_length = 0;
3137 while (defined $lines[$ln]) {
3138 my $f = $lines[$ln++];
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003139
3140 next if ($f =~ /^-/);
Elyes Haouasf62a9892022-04-12 12:17:50 +02003141 last if ($f !~ /^[\+ ]/); # !patch context
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003142
Elyes Haouasf62a9892022-04-12 12:17:50 +02003143 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3144 $needs_help = 1;
3145 next;
3146 }
3147 if ($f =~ /^\+\s*help\s*$/) {
3148 $has_help = 1;
3149 next;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003150 }
3151
Elyes Haouasf62a9892022-04-12 12:17:50 +02003152 $f =~ s/^.//; # strip patch context [+ ]
3153 $f =~ s/#.*//; # strip # directives
3154 $f =~ s/^\s+//; # strip leading blanks
3155 next if ($f =~ /^$/); # skip blank lines
Martin Roth60915b32018-08-10 21:04:05 -06003156
Elyes Haouasf62a9892022-04-12 12:17:50 +02003157 # At the end of this Kconfig block:
Martin Roth60915b32018-08-10 21:04:05 -06003158 # This only checks context lines in the patch
3159 # and so hopefully shouldn't trigger false
3160 # positives, even though some of these are
3161 # common words in help texts
Elyes Haouasf62a9892022-04-12 12:17:50 +02003162 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3163 if|endif|menu|endmenu|source)\b/x) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003164 last;
3165 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003166 $help_length++ if ($has_help);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003167 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02003168 if ($needs_help &&
3169 $help_length < $min_conf_desc_length) {
3170 my $stat_real = get_stat_real($linenr, $ln - 1);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003171 WARN("CONFIG_DESCRIPTION",
Elyes Haouasf62a9892022-04-12 12:17:50 +02003172 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003173 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003174 }
3175
Martin Roth387dec82017-09-17 19:20:46 -06003176# check for MAINTAINERS entries that don't have the right form
3177 if ($realfile =~ /^MAINTAINERS$/ &&
3178 $rawline =~ /^\+[A-Z]:/ &&
3179 $rawline !~ /^\+[A-Z]:\t\S/) {
3180 if (WARN("MAINTAINERS_STYLE",
3181 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3182 $fix) {
3183 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3184 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003185 }
3186
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003187# discourage the use of boolean for type definition attributes of Kconfig options
3188 if ($realfile =~ /Kconfig/ &&
3189 $line =~ /^\+\s*\bboolean\b/) {
3190 WARN("CONFIG_TYPE_BOOLEAN",
3191 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3192 }
3193
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003194 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3195 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3196 my $flag = $1;
3197 my $replacement = {
3198 'EXTRA_AFLAGS' => 'asflags-y',
3199 'EXTRA_CFLAGS' => 'ccflags-y',
3200 'EXTRA_CPPFLAGS' => 'cppflags-y',
3201 'EXTRA_LDFLAGS' => 'ldflags-y',
3202 };
3203
3204 WARN("DEPRECATED_VARIABLE",
3205 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3206 }
3207
3208# check for DT compatible documentation
3209 if (defined $root &&
3210 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3211 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3212
3213 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3214
3215 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3216 my $vp_file = $dt_path . "vendor-prefixes.txt";
3217
3218 foreach my $compat (@compats) {
3219 my $compat2 = $compat;
3220 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3221 my $compat3 = $compat;
3222 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3223 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3224 if ( $? >> 8 ) {
3225 WARN("UNDOCUMENTED_DT_STRING",
3226 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3227 }
3228
3229 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3230 my $vendor = $1;
3231 `grep -Eq "^$vendor\\b" $vp_file`;
3232 if ( $? >> 8 ) {
3233 WARN("UNDOCUMENTED_DT_STRING",
3234 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3235 }
3236 }
3237 }
3238
Martin Roth60915b32018-08-10 21:04:05 -06003239# check for using SPDX license tag at beginning of files
3240 if ($realline == $checklicenseline) {
3241 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3242 $checklicenseline = 2;
3243 } elsif ($rawline =~ /^\+/) {
3244 my $comment = "";
3245 if ($realfile =~ /\.(h|s|S)$/) {
3246 $comment = '/*';
3247 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3248 $comment = '//';
3249 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3250 $comment = '#';
3251 } elsif ($realfile =~ /\.rst$/) {
3252 $comment = '..';
3253 }
3254
3255 if ($comment !~ /^$/ &&
3256 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3257 WARN("SPDX_LICENSE_TAG",
3258 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3259 }
3260 }
3261 }
3262
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003263# check we are in a valid source file if not then ignore this hunk
Martin Rothedd591d2017-03-14 10:16:29 -06003264 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003265
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003266# line length limit (with some exclusions)
3267#
3268# There are a few types of lines that may extend beyond $max_line_length:
3269# logging functions like pr_info that end in a string
3270# lines with a single string
3271# #defines that are a single string
Martin Roth60915b32018-08-10 21:04:05 -06003272# lines with an RFC3986 like URL
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003273#
3274# There are 3 different line length message types:
Martin Roth387dec82017-09-17 19:20:46 -06003275# LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003276# LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3277# LONG_LINE all other lines longer than $max_line_length
3278#
3279# if LONG_LINE is ignored, the other 2 types are also ignored
3280#
3281
3282 if ($line =~ /^\+/ && $length > $max_line_length) {
3283 my $msg_type = "LONG_LINE";
3284
3285 # Check the allowed long line types first
3286
3287 # logging functions that end in a string that starts
3288 # before $max_line_length
3289 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3290 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3291 $msg_type = "";
3292
3293 # lines with only strings (w/ possible termination)
3294 # #defines with only strings
3295 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3296 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3297 $msg_type = "";
3298
Martin Roth60915b32018-08-10 21:04:05 -06003299 # More special cases
3300 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3301 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3302 $msg_type = "";
3303
3304 # URL ($rawline is used in case the URL is in a comment)
3305 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
Martin Rothedd591d2017-03-14 10:16:29 -06003306 $msg_type = "";
3307
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003308 # Otherwise set the alternate message types
3309
3310 # a comment starts before $max_line_length
3311 } elsif ($line =~ /($;[\s$;]*)$/ &&
3312 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3313 $msg_type = "LONG_LINE_COMMENT"
3314
3315 # a quoted string starts before $max_line_length
3316 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3317 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3318 $msg_type = "LONG_LINE_STRING"
3319 }
3320
3321 if ($msg_type ne "" &&
3322 (show_type("LONG_LINE") || show_type($msg_type))) {
Elyes Haouas0b1a03c2022-04-07 10:13:54 +02003323 my $msg_level = \&WARN;
3324 $msg_level = \&CHK if ($file);
3325 &{$msg_level}($msg_type,
3326 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003327 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003328 }
3329
3330# check for adding lines without a newline.
3331 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3332 WARN("MISSING_EOF_NEWLINE",
3333 "adding a line without newline at end of file\n" . $herecurr);
3334 }
3335
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003336# check we are in a valid source file C or perl if not then ignore this hunk
3337 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3338
3339# at the beginning of a line any tabs must come first and anything
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003340# more than $tabsize must use tabs.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003341 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3342 $rawline =~ /^\+\s* \s*/) {
3343 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3344 $rpt_cleaners = 1;
3345 if (ERROR("CODE_INDENT",
3346 "code indent should use tabs where possible\n" . $herevet) &&
3347 $fix) {
3348 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3349 }
3350 }
3351
3352# check for space before tabs.
3353 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3354 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3355 if (WARN("SPACE_BEFORE_TAB",
3356 "please, no space before tabs\n" . $herevet) &&
3357 $fix) {
3358 while ($fixed[$fixlinenr] =~
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003359 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003360 while ($fixed[$fixlinenr] =~
3361 s/(^\+.*) +\t/$1\t/) {}
3362 }
3363 }
3364
Martin Roth60915b32018-08-10 21:04:05 -06003365# check for assignments on the start of a line
3366 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3367 CHK("ASSIGNMENT_CONTINUATIONS",
3368 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3369 }
3370
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003371# check for && or || at the start of a line
3372 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3373 CHK("LOGICAL_CONTINUATIONS",
3374 "Logical continuations should be on the previous line\n" . $hereprev);
3375 }
3376
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003377# check indentation starts on a tab stop
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003378 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06003379 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003380 my $indent = length($1);
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003381 if ($indent % $tabsize) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003382 if (WARN("TABSTOP",
3383 "Statements should start on a tabstop\n" . $herecurr) &&
3384 $fix) {
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003385 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003386 }
3387 }
3388 }
3389
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003390# check multi-line statement indentation matches previous line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01003391 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06003392 $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 +01003393 $prevline =~ /^\+(\t*)(.*)$/;
3394 my $oldindent = $1;
3395 my $rest = $2;
3396
3397 my $pos = pos_last_openparen($rest);
3398 if ($pos >= 0) {
3399 $line =~ /^(\+| )([ \t]*)/;
3400 my $newindent = $2;
3401
3402 my $goodtabindent = $oldindent .
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003403 "\t" x ($pos / $tabsize) .
3404 " " x ($pos % $tabsize);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003405 my $goodspaceindent = $oldindent . " " x $pos;
3406
3407 if ($newindent ne $goodtabindent &&
3408 $newindent ne $goodspaceindent) {
3409
3410 if (CHK("PARENTHESIS_ALIGNMENT",
3411 "Alignment should match open parenthesis\n" . $hereprev) &&
3412 $fix && $line =~ /^\+/) {
3413 $fixed[$fixlinenr] =~
3414 s/^\+[ \t]*/\+$goodtabindent/;
3415 }
3416 }
3417 }
3418 }
3419
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003420# check for space after cast like "(int) foo" or "(struct foo) bar"
3421# avoid checking a few false positives:
3422# "sizeof(<type>)" or "__alignof__(<type>)"
3423# function pointer declarations like "(*foo)(int) = bar;"
3424# structure definitions like "(struct foo) { 0 };"
3425# multiline macros that define functions
3426# known attributes or the __attribute__ keyword
3427 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3428 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003429 if (CHK("SPACING",
3430 "No space is necessary after a cast\n" . $herecurr) &&
3431 $fix) {
3432 $fixed[$fixlinenr] =~
3433 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3434 }
3435 }
3436
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003437# Block comment styles
3438# Networking with an initial /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003439 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3440 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3441 $rawline =~ /^\+[ \t]*\*/ &&
3442 $realline > 2) {
3443 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3444 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3445 }
3446
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003447# Block comments use * on subsequent lines
3448 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3449 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003450 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3451 $rawline =~ /^\+/ && #line is new
3452 $rawline !~ /^\+[ \t]*\*/) { #no leading *
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003453 WARN("BLOCK_COMMENT_STYLE",
3454 "Block comments use * on subsequent lines\n" . $hereprev);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003455 }
3456
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003457# Block comments use */ on trailing lines
3458 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003459 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3460 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3461 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003462 WARN("BLOCK_COMMENT_STYLE",
3463 "Block comments use a trailing */ on a separate line\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003464 }
3465
Martin Rothedd591d2017-03-14 10:16:29 -06003466# Block comment * alignment
3467 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3468 $line =~ /^\+[ \t]*$;/ && #leading comment
3469 $rawline =~ /^\+[ \t]*\*/ && #leading *
3470 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3471 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3472 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3473 my $oldindent;
3474 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3475 if (defined($1)) {
3476 $oldindent = expand_tabs($1);
3477 } else {
3478 $prevrawline =~ m@^\+(.*/?)\*@;
3479 $oldindent = expand_tabs($1);
3480 }
3481 $rawline =~ m@^\+([ \t]*)\*@;
3482 my $newindent = $1;
3483 $newindent = expand_tabs($newindent);
3484 if (length($oldindent) ne length($newindent)) {
3485 WARN("BLOCK_COMMENT_STYLE",
3486 "Block comments should align the * on each line\n" . $hereprev);
3487 }
3488 }
3489
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003490# check for missing blank lines after struct/union declarations
3491# with exceptions for various attributes and macros
3492 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3493 $line =~ /^\+/ &&
3494 !($line =~ /^\+\s*$/ ||
3495 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3496 $line =~ /^\+\s*MODULE_/i ||
3497 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3498 $line =~ /^\+[a-z_]*init/ ||
3499 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3500 $line =~ /^\+\s*DECLARE/ ||
Martin Roth60915b32018-08-10 21:04:05 -06003501 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003502 $line =~ /^\+\s*__setup/)) {
3503 if (CHK("LINE_SPACING",
3504 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3505 $fix) {
3506 fix_insert_line($fixlinenr, "\+");
3507 }
3508 }
3509
3510# check for multiple consecutive blank lines
3511 if ($prevline =~ /^[\+ ]\s*$/ &&
3512 $line =~ /^\+\s*$/ &&
3513 $last_blank_line != ($linenr - 1)) {
3514 if (CHK("LINE_SPACING",
3515 "Please don't use multiple blank lines\n" . $hereprev) &&
3516 $fix) {
3517 fix_delete_line($fixlinenr, $rawline);
3518 }
3519
3520 $last_blank_line = $linenr;
3521 }
3522
3523# check for missing blank lines after declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003524# (declarations must have the same indentation and not be at the start of line)
3525 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3526 # use temporaries
3527 my $sl = $sline;
3528 my $pl = $prevline;
3529 # remove $Attribute/$Sparse uses to simplify comparisons
3530 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3531 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3532 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003533 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003534 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003535 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003536 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003537 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003538 $pl =~ /^\+\s+$declaration_macros/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003539 # for "else if" which can look like "$Ident $Ident"
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003540 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003541 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003542 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003543 # not starting a section or a macro "\" extended line
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003544 $pl =~ /(?:\{\s*|\\)$/) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003545 # looks like a declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003546 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003547 # function pointer declarations
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003548 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003549 # foo bar; where foo is some local typedef or #define
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003550 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003551 # known declaration macros
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003552 $sl =~ /^\+\s+$declaration_macros/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003553 # start of struct or union or enum
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003554 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003555 # start or end of block or continuation of declaration
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003556 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003557 # bitfield continuation
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003558 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003559 # other possible extensions of declaration lines
Elyes HAOUAS249c4042022-01-29 08:11:50 +01003560 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3561 if (WARN("LINE_SPACING",
3562 "Missing a blank line after declarations\n" . $hereprev) &&
3563 $fix) {
3564 fix_insert_line($fixlinenr, "\+");
3565 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003566 }
3567 }
3568
3569# check for spaces at the beginning of a line.
3570# Exceptions:
3571# 1) within comments
3572# 2) indented preprocessor commands
3573# 3) hanging labels
3574 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3575 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3576 if (WARN("LEADING_SPACE",
3577 "please, no spaces at the start of a line\n" . $herevet) &&
3578 $fix) {
3579 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3580 }
3581 }
3582
3583# check we are in a valid C source file if not then ignore this hunk
3584 next if ($realfile !~ /\.(h|c)$/);
3585
Martin Roth60915b32018-08-10 21:04:05 -06003586# check for unusual line ending [ or (
3587 if ($line =~ /^\+.*([\[\(])\s*$/) {
3588 CHK("OPEN_ENDED_LINE",
3589 "Lines should not end with a '$1'\n" . $herecurr);
3590 }
3591
Martin Roth387dec82017-09-17 19:20:46 -06003592# check if this appears to be the start function declaration, save the name
3593 if ($sline =~ /^\+\{\s*$/ &&
3594 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3595 $context_function = $1;
3596 }
3597
3598# check if this appears to be the end of function declaration
3599 if ($sline =~ /^\+\}\s*$/) {
3600 undef $context_function;
3601 }
3602
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003603# check indentation of any line with a bare else
3604# (but not if it is a multiple line "if (foo) return bar; else return baz;")
3605# if the previous line is a break or return and is indented 1 tab more...
3606 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3607 my $tabs = length($1) + 1;
3608 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3609 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3610 defined $lines[$linenr] &&
3611 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3612 WARN("UNNECESSARY_ELSE",
3613 "else is not generally useful after a break or return\n" . $hereprev);
3614 }
3615 }
3616
3617# check indentation of a line with a break;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003618# if the previous line is a goto, return or break
3619# and is indented the same # of tabs
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003620 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3621 my $tabs = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02003622 if ($prevline =~ /^\+$tabs(?:goto|return|break)\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003623 WARN("UNNECESSARY_BREAK",
Elyes Haouas26e0b942022-05-22 11:11:11 +02003624 "break is not useful after a $1\n" . $hereprev);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003625 }
3626 }
3627
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003628# check for RCS/CVS revision markers
3629 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3630 WARN("CVS_KEYWORD",
3631 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3632 }
3633
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003634# check for old HOTPLUG __dev<foo> section markings
3635 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3636 WARN("HOTPLUG_SECTION",
3637 "Using $1 is unnecessary\n" . $herecurr);
3638 }
3639
3640# Check for potential 'bare' types
3641 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3642 $realline_next);
3643#print "LINE<$line>\n";
Martin Roth387dec82017-09-17 19:20:46 -06003644 if ($linenr > $suppress_statement &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003645 $realcnt && $sline =~ /.\s*\S/) {
3646 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3647 ctx_statement_block($linenr, $realcnt, 0);
3648 $stat =~ s/\n./\n /g;
3649 $cond =~ s/\n./\n /g;
3650
3651#print "linenr<$linenr> <$stat>\n";
3652 # If this statement has no statement boundaries within
3653 # it there is no point in retrying a statement scan
3654 # until we hit end of it.
3655 my $frag = $stat; $frag =~ s/;+\s*$//;
3656 if ($frag !~ /(?:{|;)/) {
3657#print "skip<$line_nr_next>\n";
3658 $suppress_statement = $line_nr_next;
3659 }
3660
3661 # Find the real next line.
3662 $realline_next = $line_nr_next;
3663 if (defined $realline_next &&
3664 (!defined $lines[$realline_next - 1] ||
3665 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3666 $realline_next++;
3667 }
3668
3669 my $s = $stat;
3670 $s =~ s/{.*$//s;
3671
3672 # Ignore goto labels.
3673 if ($s =~ /$Ident:\*$/s) {
3674
3675 # Ignore functions being called
3676 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3677
3678 } elsif ($s =~ /^.\s*else\b/s) {
3679
3680 # declarations always start with types
3681 } 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) {
3682 my $type = $1;
3683 $type =~ s/\s+/ /g;
3684 possible($type, "A:" . $s);
3685
3686 # definitions in global scope can only start with types
3687 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3688 possible($1, "B:" . $s);
3689 }
3690
3691 # any (foo ... *) is a pointer cast, and foo is a type
3692 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3693 possible($1, "C:" . $s);
3694 }
3695
3696 # Check for any sort of function declaration.
3697 # int foo(something bar, other baz);
3698 # void (*store_gdt)(x86_descr_ptr *);
3699 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3700 my ($name_len) = length($1);
3701
3702 my $ctx = $s;
3703 substr($ctx, 0, $name_len + 1, '');
3704 $ctx =~ s/\)[^\)]*$//;
3705
3706 for my $arg (split(/\s*,\s*/, $ctx)) {
3707 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3708
3709 possible($1, "D:" . $s);
3710 }
3711 }
3712 }
3713
3714 }
3715
3716#
3717# Checks which may be anchored in the context.
3718#
3719
3720# Check for switch () and associated case and default
3721# statements should be at the same indent.
3722 if ($line=~/\bswitch\s*\(.*\)/) {
3723 my $err = '';
3724 my $sep = '';
3725 my @ctx = ctx_block_outer($linenr, $realcnt);
3726 shift(@ctx);
3727 for my $ctx (@ctx) {
3728 my ($clen, $cindent) = line_stats($ctx);
3729 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3730 $indent != $cindent) {
3731 $err .= "$sep$ctx\n";
3732 $sep = '';
3733 } else {
3734 $sep = "[...]\n";
3735 }
3736 }
3737 if ($err ne '') {
3738 ERROR("SWITCH_CASE_INDENT_LEVEL",
3739 "switch and case should be at the same indent\n$hereline$err");
3740 }
3741 }
3742
3743# if/while/etc brace do not go on next line, unless defining a do while loop,
3744# or if that brace on the next line is for something else
3745 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3746 my $pre_ctx = "$1$2";
3747
3748 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3749
3750 if ($line =~ /^\+\t{6,}/) {
3751 WARN("DEEP_INDENTATION",
3752 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3753 }
3754
3755 my $ctx_cnt = $realcnt - $#ctx - 1;
3756 my $ctx = join("\n", @ctx);
3757
3758 my $ctx_ln = $linenr;
3759 my $ctx_skip = $realcnt;
3760
3761 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3762 defined $lines[$ctx_ln - 1] &&
3763 $lines[$ctx_ln - 1] =~ /^-/)) {
3764 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3765 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3766 $ctx_ln++;
3767 }
3768
3769 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3770 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3771
3772 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3773 ERROR("OPEN_BRACE",
3774 "that open brace { should be on the previous line\n" .
3775 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3776 }
3777 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3778 $ctx =~ /\)\s*\;\s*$/ &&
3779 defined $lines[$ctx_ln - 1])
3780 {
3781 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3782 if ($nindent > $indent) {
3783 WARN("TRAILING_SEMICOLON",
3784 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3785 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3786 }
3787 }
3788 }
3789
3790# Check relative indent for conditionals and blocks.
Martin Roth387dec82017-09-17 19:20:46 -06003791 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 +01003792 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3793 ctx_statement_block($linenr, $realcnt, 0)
3794 if (!defined $stat);
3795 my ($s, $c) = ($stat, $cond);
3796
3797 substr($s, 0, length($c), '');
3798
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003799 # remove inline comments
3800 $s =~ s/$;/ /g;
3801 $c =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003802
3803 # Find out how long the conditional actually is.
3804 my @newlines = ($c =~ /\n/gs);
3805 my $cond_lines = 1 + $#newlines;
3806
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003807 # Make sure we remove the line prefixes as we have
3808 # none on the first line, and are going to readd them
3809 # where necessary.
3810 $s =~ s/\n./\n/gs;
3811 while ($s =~ /\n\s+\\\n/) {
3812 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3813 }
3814
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003815 # We want to check the first line inside the block
3816 # starting at the end of the conditional, so remove:
3817 # 1) any blank line termination
3818 # 2) any opening brace { on end of the line
3819 # 3) any do (...) {
3820 my $continuation = 0;
3821 my $check = 0;
3822 $s =~ s/^.*\bdo\b//;
3823 $s =~ s/^\s*{//;
3824 if ($s =~ s/^\s*\\//) {
3825 $continuation = 1;
3826 }
3827 if ($s =~ s/^\s*?\n//) {
3828 $check = 1;
3829 $cond_lines++;
3830 }
3831
3832 # Also ignore a loop construct at the end of a
3833 # preprocessor statement.
3834 if (($prevline =~ /^.\s*#\s*define\s/ ||
3835 $prevline =~ /\\\s*$/) && $continuation == 0) {
3836 $check = 0;
3837 }
3838
3839 my $cond_ptr = -1;
3840 $continuation = 0;
3841 while ($cond_ptr != $cond_lines) {
3842 $cond_ptr = $cond_lines;
3843
3844 # If we see an #else/#elif then the code
3845 # is not linear.
3846 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3847 $check = 0;
3848 }
3849
3850 # Ignore:
3851 # 1) blank lines, they should be at 0,
3852 # 2) preprocessor lines, and
3853 # 3) labels.
3854 if ($continuation ||
3855 $s =~ /^\s*?\n/ ||
3856 $s =~ /^\s*#\s*?/ ||
3857 $s =~ /^\s*$Ident\s*:/) {
3858 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3859 if ($s =~ s/^.*?\n//) {
3860 $cond_lines++;
3861 }
3862 }
3863 }
3864
3865 my (undef, $sindent) = line_stats("+" . $s);
3866 my $stat_real = raw_line($linenr, $cond_lines);
3867
3868 # Check if either of these lines are modified, else
3869 # this is not this patch's fault.
3870 if (!defined($stat_real) ||
3871 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3872 $check = 0;
3873 }
3874 if (defined($stat_real) && $cond_lines > 1) {
3875 $stat_real = "[...]\n$stat_real";
3876 }
3877
3878 #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";
3879
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003880 if ($check && $s ne '' &&
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003881 (($sindent % $tabsize) != 0 ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003882 ($sindent < $indent) ||
Martin Roth387dec82017-09-17 19:20:46 -06003883 ($sindent == $indent &&
3884 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
Elyes HAOUAS96771bf2022-01-29 07:28:45 +01003885 ($sindent > $indent + $tabsize))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003886 WARN("SUSPECT_CODE_INDENT",
3887 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3888 }
Julius Werner218906d2021-03-25 21:12:49 -07003889
3890# Also check if the next statement after the previous condition has the same indent
3891 my ($stat_next, undef, $line_nr_next_next) =
3892 ctx_statement_block($line_nr_next, $remain_next, $off_next);
3893 my $s_next = $stat_next;
3894
3895 # Remove line prefixes
3896 $s_next =~ s/\n./\n/g;
3897
3898 # Remove any comments
3899 $s_next =~ s/$;//g;
3900
3901 # Remove any leading labels
3902 $s_next =~ s/\n( ?$Ident:)/"\n" . " " x length($1)/eg;
3903
3904 # Skip this check for in case next statement starts with 'else'
3905 if ($s_next !~ /\belse\b/) {
3906
3907 # Remove while that belongs to a do {} while
3908 if ($stat =~ /\bdo\b/) {
3909 $s_next =~ s/^.*\bwhile\b\s*($balanced_parens)\s*?//;
3910 }
3911
3912 # Remove blank lines
3913 $s_next =~ s/\s*\\?\n//g;
3914
3915 # Get the real next lines
3916 my $next_nof_lines = $line_nr_next_next - $line_nr_next;
3917 my $stat_next_real = raw_line($line_nr_next, $next_nof_lines);
3918 if (!defined($stat_next_real)) {
3919 $stat_next_real = "";
3920 } elsif ($next_nof_lines > 1) {
3921 $stat_next_real = "[...]\n$stat_next_real";
3922 }
3923 my (undef, $nindent) = line_stats('+' . $s_next);
3924
3925 #print "stat_next<$stat_next> stat<$stat> indent<$indent> nindent<$nindent> s_next<$s_next> stat_next_real<$stat_next_real>\n";
3926
3927 if ($nindent > $indent) {
3928 WARN("SUSPICIOUS_CODE_INDENT",
3929 "suspicious code indentation after conditional statements\n" .
3930 $herecurr . "$stat_real\n$stat_next_real\n");
3931 }
3932 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003933 }
3934
3935 # Track the 'values' across context and added lines.
3936 my $opline = $line; $opline =~ s/^./ /;
3937 my ($curr_values, $curr_vars) =
3938 annotate_values($opline . "\n", $prev_values);
3939 $curr_values = $prev_values . $curr_values;
3940 if ($dbg_values) {
3941 my $outline = $opline; $outline =~ s/\t/ /g;
3942 print "$linenr > .$outline\n";
3943 print "$linenr > $curr_values\n";
3944 print "$linenr > $curr_vars\n";
3945 }
3946 $prev_values = substr($curr_values, -1);
3947
3948#ignore lines not being added
3949 next if ($line =~ /^[^\+]/);
3950
Martin Rothedd591d2017-03-14 10:16:29 -06003951# check for dereferences that span multiple lines
3952 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3953 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3954 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3955 my $ref = $1;
3956 $line =~ /^.\s*($Lval)/;
3957 $ref .= $1;
3958 $ref =~ s/\s//g;
3959 WARN("MULTILINE_DEREFERENCE",
3960 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3961 }
3962
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003963# check for declarations of signed or unsigned without int
Martin Rothedd591d2017-03-14 10:16:29 -06003964 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 -07003965 my $type = $1;
3966 my $var = $2;
3967 $var = "" if (!defined $var);
3968 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3969 my $sign = $1;
3970 my $pointer = $2;
3971
3972 $pointer = "" if (!defined $pointer);
3973
3974 if (WARN("UNSPECIFIED_INT",
3975 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3976 $fix) {
3977 my $decl = trim($sign) . " int ";
3978 my $comp_pointer = $pointer;
3979 $comp_pointer =~ s/\s//g;
3980 $decl .= $comp_pointer;
3981 $decl = rtrim($decl) if ($var eq "");
3982 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3983 }
3984 }
3985 }
3986
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003987# TEST: allow direct testing of the type matcher.
3988 if ($dbg_type) {
3989 if ($line =~ /^.\s*$Declare\s*$/) {
3990 ERROR("TEST_TYPE",
3991 "TEST: is type\n" . $herecurr);
3992 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3993 ERROR("TEST_NOT_TYPE",
3994 "TEST: is not type ($1 is)\n". $herecurr);
3995 }
3996 next;
3997 }
3998# TEST: allow direct testing of the attribute matcher.
3999 if ($dbg_attr) {
4000 if ($line =~ /^.\s*$Modifier\s*$/) {
4001 ERROR("TEST_ATTR",
4002 "TEST: is attr\n" . $herecurr);
4003 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4004 ERROR("TEST_NOT_ATTR",
4005 "TEST: is not attr ($1 is)\n". $herecurr);
4006 }
4007 next;
4008 }
4009
4010# check for initialisation to aggregates open brace on the next line
4011 if ($line =~ /^.\s*{/ &&
4012 $prevline =~ /(?:^|[^=])=\s*$/) {
4013 if (ERROR("OPEN_BRACE",
4014 "that open brace { should be on the previous line\n" . $hereprev) &&
4015 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4016 fix_delete_line($fixlinenr - 1, $prevrawline);
4017 fix_delete_line($fixlinenr, $rawline);
4018 my $fixedline = $prevrawline;
4019 $fixedline =~ s/\s*=\s*$/ = {/;
4020 fix_insert_line($fixlinenr, $fixedline);
4021 $fixedline = $line;
Martin Roth387dec82017-09-17 19:20:46 -06004022 $fixedline =~ s/^(.\s*)\{\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004023 fix_insert_line($fixlinenr, $fixedline);
4024 }
4025 }
4026
4027#
4028# Checks which are anchored on the added line.
4029#
4030
4031# check for malformed paths in #include statements (uses RAW line)
4032 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4033 my $path = $1;
4034 if ($path =~ m{//}) {
4035 ERROR("MALFORMED_INCLUDE",
4036 "malformed #include filename\n" . $herecurr);
4037 }
4038 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4039 ERROR("UAPI_INCLUDE",
4040 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4041 }
4042 }
4043
4044# no C99 // comments
4045 if ($line =~ m{//}) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004046 if (ERROR("C99_COMMENTS",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004047 "do not use C99 // comments\n" . $herecurr) &&
4048 $fix) {
4049 my $line = $fixed[$fixlinenr];
4050 if ($line =~ /\/\/(.*)$/) {
4051 my $comment = trim($1);
4052 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4053 }
4054 }
4055 }
4056 # Remove C99 comments.
4057 $line =~ s@//.*@@;
4058 $opline =~ s@//.*@@;
4059
4060# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4061# the whole statement.
4062#print "APW <$lines[$realline_next - 1]>\n";
4063 if (defined $realline_next &&
4064 exists $lines[$realline_next - 1] &&
4065 !defined $suppress_export{$realline_next} &&
4066 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4067 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4068 # Handle definitions which produce identifiers with
4069 # a prefix:
4070 # XXX(foo);
4071 # EXPORT_SYMBOL(something_foo);
4072 my $name = $1;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004073 $name =~ s/^\s*($Ident).*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004074 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4075 $name =~ /^${Ident}_$2/) {
4076#print "FOO C name<$name>\n";
4077 $suppress_export{$realline_next} = 1;
4078
4079 } elsif ($stat !~ /(?:
4080 \n.}\s*$|
4081 ^.DEFINE_$Ident\(\Q$name\E\)|
4082 ^.DECLARE_$Ident\(\Q$name\E\)|
4083 ^.LIST_HEAD\(\Q$name\E\)|
4084 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4085 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4086 )/x) {
4087#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4088 $suppress_export{$realline_next} = 2;
4089 } else {
4090 $suppress_export{$realline_next} = 1;
4091 }
4092 }
4093 if (!defined $suppress_export{$linenr} &&
4094 $prevline =~ /^.\s*$/ &&
4095 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4096 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4097#print "FOO B <$lines[$linenr - 1]>\n";
4098 $suppress_export{$linenr} = 2;
4099 }
4100 if (defined $suppress_export{$linenr} &&
4101 $suppress_export{$linenr} == 2) {
4102 WARN("EXPORT_SYMBOL",
4103 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4104 }
4105
4106# check for global initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004107 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004108 if (ERROR("GLOBAL_INITIALISERS",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004109 "do not initialise globals to $1\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004110 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004111 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004112 }
4113 }
4114# check for static initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004115 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004116 if (ERROR("INITIALISED_STATIC",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004117 "do not initialise statics to $1\n" .
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004118 $herecurr) &&
4119 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004120 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004121 }
4122 }
4123
4124# check for misordered declarations of char/short/int/long with signed/unsigned
4125 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4126 my $tmp = trim($1);
4127 WARN("MISORDERED_TYPE",
4128 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4129 }
4130
4131# check for static const char * arrays.
4132 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4133 WARN("STATIC_CONST_CHAR_ARRAY",
4134 "static const char * array should probably be static const char * const\n" .
4135 $herecurr);
Elyes Haouas26e0b942022-05-22 11:11:11 +02004136 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004137
4138# check for static char foo[] = "bar" declarations.
4139 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4140 WARN("STATIC_CONST_CHAR_ARRAY",
4141 "static char array declaration should probably be static const char\n" .
4142 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004143 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004144
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004145# check for const <foo> const where <foo> is not a pointer or array type
4146 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4147 my $found = $1;
4148 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4149 WARN("CONST_CONST",
4150 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4151 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4152 WARN("CONST_CONST",
4153 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4154 }
4155 }
4156
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004157# check for non-global char *foo[] = {"bar", ...} declarations.
4158 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4159 WARN("STATIC_CONST_CHAR_ARRAY",
4160 "char * array declaration might be better as static const\n" .
4161 $herecurr);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004162 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004163
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004164# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4165 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4166 my $array = $1;
4167 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4168 my $array_div = $1;
4169 if (WARN("ARRAY_SIZE",
4170 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4171 $fix) {
4172 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4173 }
4174 }
4175 }
4176
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004177# check for function declarations without arguments like "int foo()"
Elyes Haouas26e0b942022-05-22 11:11:11 +02004178 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004179 if (ERROR("FUNCTION_WITHOUT_ARGS",
4180 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4181 $fix) {
4182 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4183 }
4184 }
4185
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004186# check for new typedefs, only function parameters and sparse annotations
4187# make sense.
4188 if ($line =~ /\btypedef\s/ &&
4189 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4190 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4191 $line !~ /\b$typeTypedefs\b/ &&
Martin Rothedd591d2017-03-14 10:16:29 -06004192 $line !~ /\b__bitwise\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004193 WARN("NEW_TYPEDEFS",
4194 "do not add new typedefs\n" . $herecurr);
4195 }
4196
4197# * goes on variable not on type
4198 # (char*[ const])
4199 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4200 #print "AA<$1>\n";
4201 my ($ident, $from, $to) = ($1, $2, $2);
4202
4203 # Should start with a space.
4204 $to =~ s/^(\S)/ $1/;
4205 # Should not end with a space.
4206 $to =~ s/\s+$//;
4207 # '*'s should not have spaces between.
4208 while ($to =~ s/\*\s+\*/\*\*/) {
4209 }
4210
4211## print "1: from<$from> to<$to> ident<$ident>\n";
4212 if ($from ne $to) {
4213 if (ERROR("POINTER_LOCATION",
4214 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4215 $fix) {
4216 my $sub_from = $ident;
4217 my $sub_to = $ident;
4218 $sub_to =~ s/\Q$from\E/$to/;
4219 $fixed[$fixlinenr] =~
4220 s@\Q$sub_from\E@$sub_to@;
4221 }
4222 }
4223 }
4224 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4225 #print "BB<$1>\n";
4226 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4227
4228 # Should start with a space.
4229 $to =~ s/^(\S)/ $1/;
4230 # Should not end with a space.
4231 $to =~ s/\s+$//;
4232 # '*'s should not have spaces between.
4233 while ($to =~ s/\*\s+\*/\*\*/) {
4234 }
4235 # Modifiers should have spaces.
4236 $to =~ s/(\b$Modifier$)/$1 /;
4237
4238## print "2: from<$from> to<$to> ident<$ident>\n";
4239 if ($from ne $to && $ident !~ /^$Modifier$/) {
4240 if (ERROR("POINTER_LOCATION",
4241 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4242 $fix) {
4243
4244 my $sub_from = $match;
4245 my $sub_to = $match;
4246 $sub_to =~ s/\Q$from\E/$to/;
4247 $fixed[$fixlinenr] =~
4248 s@\Q$sub_from\E@$sub_to@;
4249 }
4250 }
4251 }
4252
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004253# avoid BUG() or BUG_ON()
4254 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
Martin Roth387dec82017-09-17 19:20:46 -06004255 my $msg_level = \&WARN;
4256 $msg_level = \&CHK if ($file);
4257 &{$msg_level}("AVOID_BUG",
4258 "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 -07004259 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004260
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004261# avoid LINUX_VERSION_CODE
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004262 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4263 WARN("LINUX_VERSION_CODE",
4264 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4265 }
4266
4267# check for uses of printk_ratelimit
4268 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4269 WARN("PRINTK_RATELIMITED",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004270 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004271 }
4272
Martin Roth60915b32018-08-10 21:04:05 -06004273# printk should use KERN_* levels
4274 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4275 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4276 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004277 }
4278
4279 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4280 my $orig = $1;
4281 my $level = lc($orig);
4282 $level = "warn" if ($level eq "warning");
4283 my $level2 = $level;
4284 $level2 = "dbg" if ($level eq "debug");
4285 WARN("PREFER_PR_LEVEL",
4286 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4287 }
4288
4289 if ($line =~ /\bpr_warning\s*\(/) {
4290 if (WARN("PREFER_PR_LEVEL",
4291 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4292 $fix) {
4293 $fixed[$fixlinenr] =~
4294 s/\bpr_warning\b/pr_warn/;
4295 }
4296 }
4297
4298 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4299 my $orig = $1;
4300 my $level = lc($orig);
4301 $level = "warn" if ($level eq "warning");
4302 $level = "dbg" if ($level eq "debug");
4303 WARN("PREFER_DEV_LEVEL",
4304 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4305 }
4306
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004307# ENOSYS means "bad syscall nr" and nothing else. This will have a small
4308# number of false positives, but assembly files are not checked, so at
4309# least the arch entry code will not trigger this warning.
4310 if ($line =~ /\bENOSYS\b/) {
4311 WARN("ENOSYS",
4312 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4313 }
4314
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004315# function brace can't be on same line, except for #defines of do while,
4316# or if closed on same line
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004317 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06004318 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4319 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4320 $sline !~ /}/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004321 if (ERROR("OPEN_BRACE",
Martin Roth60915b32018-08-10 21:04:05 -06004322 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004323 $fix) {
4324 fix_delete_line($fixlinenr, $rawline);
4325 my $fixed_line = $rawline;
Elyes Haouas26e0b942022-05-22 11:11:11 +02004326 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004327 my $line1 = $1;
4328 my $line2 = $2;
4329 fix_insert_line($fixlinenr, ltrim($line1));
4330 fix_insert_line($fixlinenr, "\+{");
4331 if ($line2 !~ /^\s*$/) {
4332 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4333 }
4334 }
4335 }
4336
4337# open braces for enum, union and struct go on the same line.
4338 if ($line =~ /^.\s*{/ &&
4339 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4340 if (ERROR("OPEN_BRACE",
4341 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4342 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4343 fix_delete_line($fixlinenr - 1, $prevrawline);
4344 fix_delete_line($fixlinenr, $rawline);
4345 my $fixedline = rtrim($prevrawline) . " {";
4346 fix_insert_line($fixlinenr, $fixedline);
4347 $fixedline = $rawline;
Martin Roth387dec82017-09-17 19:20:46 -06004348 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004349 if ($fixedline !~ /^\+\s*$/) {
4350 fix_insert_line($fixlinenr, $fixedline);
4351 }
4352 }
4353 }
4354
4355# missing space after union, struct or enum definition
4356 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4357 if (WARN("SPACING",
4358 "missing space after $1 definition\n" . $herecurr) &&
4359 $fix) {
4360 $fixed[$fixlinenr] =~
4361 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4362 }
4363 }
4364
4365# Function pointer declarations
4366# check spacing between type, funcptr, and args
4367# canonical declaration is "type (*funcptr)(args...)"
4368 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4369 my $declare = $1;
4370 my $pre_pointer_space = $2;
4371 my $post_pointer_space = $3;
4372 my $funcname = $4;
4373 my $post_funcname_space = $5;
4374 my $pre_args_space = $6;
4375
4376# the $Declare variable will capture all spaces after the type
4377# so check it for a missing trailing missing space but pointer return types
4378# don't need a space so don't warn for those.
4379 my $post_declare_space = "";
4380 if ($declare =~ /(\s+)$/) {
4381 $post_declare_space = $1;
4382 $declare = rtrim($declare);
4383 }
4384 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4385 WARN("SPACING",
4386 "missing space after return type\n" . $herecurr);
4387 $post_declare_space = " ";
4388 }
4389
4390# unnecessary space "type (*funcptr)(args...)"
4391# This test is not currently implemented because these declarations are
4392# equivalent to
4393# int foo(int bar, ...)
4394# and this is form shouldn't/doesn't generate a checkpatch warning.
4395#
4396# elsif ($declare =~ /\s{2,}$/) {
4397# WARN("SPACING",
4398# "Multiple spaces after return type\n" . $herecurr);
4399# }
4400
4401# unnecessary space "type ( *funcptr)(args...)"
4402 if (defined $pre_pointer_space &&
4403 $pre_pointer_space =~ /^\s/) {
4404 WARN("SPACING",
4405 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4406 }
4407
4408# unnecessary space "type (* funcptr)(args...)"
4409 if (defined $post_pointer_space &&
4410 $post_pointer_space =~ /^\s/) {
4411 WARN("SPACING",
4412 "Unnecessary space before function pointer name\n" . $herecurr);
4413 }
4414
4415# unnecessary space "type (*funcptr )(args...)"
4416 if (defined $post_funcname_space &&
4417 $post_funcname_space =~ /^\s/) {
4418 WARN("SPACING",
4419 "Unnecessary space after function pointer name\n" . $herecurr);
4420 }
4421
4422# unnecessary space "type (*funcptr) (args...)"
4423 if (defined $pre_args_space &&
4424 $pre_args_space =~ /^\s/) {
4425 WARN("SPACING",
4426 "Unnecessary space before function pointer arguments\n" . $herecurr);
4427 }
4428
4429 if (show_type("SPACING") && $fix) {
4430 $fixed[$fixlinenr] =~
4431 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4432 }
4433 }
4434
4435# check for spacing round square brackets; allowed:
4436# 1. with a type on the left -- int [] a;
4437# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4438# 3. inside a curly brace -- = { [0...10] = 5 }
Martin Rothedd591d2017-03-14 10:16:29 -06004439# 4. in an extended asm instruction -- : [r0]"r"(r0) (coreboot)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004440 while ($line =~ /(.*?\s)\[/g) {
4441 my ($where, $prefix) = ($-[1], $1);
4442 if ($prefix !~ /$Type\s+$/ &&
4443 ($where != 0 || $prefix !~ /^.\s+$/) &&
Martin Rothedd591d2017-03-14 10:16:29 -06004444 $prefix !~ /[{,:]\s+$/) { #coreboot
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004445 if (ERROR("BRACKET_SPACE",
4446 "space prohibited before open square bracket '['\n" . $herecurr) &&
4447 $fix) {
4448 $fixed[$fixlinenr] =~
4449 s/^(\+.*?)\s+\[/$1\[/;
4450 }
4451 }
4452 }
4453
4454# check for spaces between functions and their parentheses.
4455 while ($line =~ /($Ident)\s+\(/g) {
4456 my $name = $1;
4457 my $ctx_before = substr($line, 0, $-[1]);
4458 my $ctx = "$ctx_before$name";
4459
4460 # Ignore those directives where spaces _are_ permitted.
4461 if ($name =~ /^(?:
4462 if|for|while|switch|return|case|
4463 volatile|__volatile__|
4464 __attribute__|format|__extension__|
4465 asm|__asm__)$/x)
4466 {
4467 # cpp #define statements have non-optional spaces, ie
4468 # if there is a space between the name and the open
4469 # parenthesis it is simply not a parameter group.
4470 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4471
4472 # cpp #elif statement condition may start with a (
4473 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4474
4475 # If this whole things ends with a type its most
4476 # likely a typedef for a function.
4477 } elsif ($ctx =~ /$Type$/) {
4478
4479 } else {
4480 if (WARN("SPACING",
4481 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4482 $fix) {
4483 $fixed[$fixlinenr] =~
4484 s/\b$name\s+\(/$name\(/;
4485 }
4486 }
4487 }
4488
4489# Check operator spacing.
4490 if (!($line=~/\#\s*include/)) {
4491 my $fixed_line = "";
4492 my $line_fixed = 0;
4493
4494 my $ops = qr{
4495 <<=|>>=|<=|>=|==|!=|
4496 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4497 =>|->|<<|>>|<|>|=|!|~|
4498 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4499 \?:|\?|:
4500 }x;
4501 my @elements = split(/($ops|;)/, $opline);
4502
4503## print("element count: <" . $#elements . ">\n");
4504## foreach my $el (@elements) {
4505## print("el: <$el>\n");
4506## }
4507
4508 my @fix_elements = ();
4509 my $off = 0;
4510
4511 foreach my $el (@elements) {
4512 push(@fix_elements, substr($rawline, $off, length($el)));
4513 $off += length($el);
4514 }
4515
4516 $off = 0;
4517
4518 my $blank = copy_spacing($opline);
4519 my $last_after = -1;
4520
4521 for (my $n = 0; $n < $#elements; $n += 2) {
4522
4523 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4524
4525## print("n: <$n> good: <$good>\n");
4526
4527 $off += length($elements[$n]);
4528
4529 # Pick up the preceding and succeeding characters.
4530 my $ca = substr($opline, 0, $off);
4531 my $cc = '';
4532 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4533 $cc = substr($opline, $off + length($elements[$n + 1]));
4534 }
4535 my $cb = "$ca$;$cc";
4536
4537 my $a = '';
4538 $a = 'V' if ($elements[$n] ne '');
4539 $a = 'W' if ($elements[$n] =~ /\s$/);
4540 $a = 'C' if ($elements[$n] =~ /$;$/);
4541 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4542 $a = 'O' if ($elements[$n] eq '');
4543 $a = 'E' if ($ca =~ /^\s*$/);
4544
4545 my $op = $elements[$n + 1];
4546
4547 my $c = '';
4548 if (defined $elements[$n + 2]) {
4549 $c = 'V' if ($elements[$n + 2] ne '');
4550 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4551 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4552 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4553 $c = 'O' if ($elements[$n + 2] eq '');
4554 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4555 } else {
4556 $c = 'E';
4557 }
4558
4559 my $ctx = "${a}x${c}";
4560
4561 my $at = "(ctx:$ctx)";
4562
4563 my $ptr = substr($blank, 0, $off) . "^";
4564 my $hereptr = "$hereline$ptr\n";
4565
4566 # Pull out the value of this operator.
4567 my $op_type = substr($curr_values, $off + 1, 1);
4568
4569 # Get the full operator variant.
4570 my $opv = $op . substr($curr_vars, $off, 1);
4571
4572 # Ignore operators passed as parameters.
4573 if ($op_type ne 'V' &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004574 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004575
4576# # Ignore comments
4577# } elsif ($op =~ /^$;+$/) {
4578
4579 # ; should have either the end of line or a space or \ after it
4580 } elsif ($op eq ';') {
4581 if ($ctx !~ /.x[WEBC]/ &&
4582 $cc !~ /^\\/ && $cc !~ /^;/) {
4583 if (ERROR("SPACING",
4584 "space required after that '$op' $at\n" . $hereptr)) {
4585 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4586 $line_fixed = 1;
4587 }
4588 }
4589
4590 # // is a comment
4591 } elsif ($op eq '//') {
4592
4593 # : when part of a bitfield
4594 } elsif ($opv eq ':B') {
4595 # skip the bitfield test for now
4596
4597 # No spaces for:
4598 # ->
4599 } elsif ($op eq '->') {
4600 if ($ctx =~ /Wx.|.xW/) {
4601 if (ERROR("SPACING",
4602 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4603 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4604 if (defined $fix_elements[$n + 2]) {
4605 $fix_elements[$n + 2] =~ s/^\s+//;
4606 }
4607 $line_fixed = 1;
4608 }
4609 }
4610
4611 # , must not have a space before and must have a space on the right.
4612 } elsif ($op eq ',') {
4613 my $rtrim_before = 0;
4614 my $space_after = 0;
4615 if ($ctx =~ /Wx./) {
4616 if (ERROR("SPACING",
4617 "space prohibited before that '$op' $at\n" . $hereptr)) {
4618 $line_fixed = 1;
4619 $rtrim_before = 1;
4620 }
4621 }
4622 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4623 if (ERROR("SPACING",
4624 "space required after that '$op' $at\n" . $hereptr)) {
4625 $line_fixed = 1;
4626 $last_after = $n;
4627 $space_after = 1;
4628 }
4629 }
4630 if ($rtrim_before || $space_after) {
4631 if ($rtrim_before) {
4632 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4633 } else {
4634 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4635 }
4636 if ($space_after) {
4637 $good .= " ";
4638 }
4639 }
4640
4641 # '*' as part of a type definition -- reported already.
4642 } elsif ($opv eq '*_') {
4643 #warn "'*' is part of type\n";
4644
4645 # unary operators should have a space before and
4646 # none after. May be left adjacent to another
4647 # unary operator, or a cast
4648 } elsif ($op eq '!' || $op eq '~' ||
4649 $opv eq '*U' || $opv eq '-U' ||
4650 $opv eq '&U' || $opv eq '&&U') {
4651 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4652 if (ERROR("SPACING",
4653 "space required before that '$op' $at\n" . $hereptr)) {
4654 if ($n != $last_after + 2) {
4655 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4656 $line_fixed = 1;
4657 }
4658 }
4659 }
4660 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4661 # A unary '*' may be const
4662
4663 } elsif ($ctx =~ /.xW/) {
4664 if (ERROR("SPACING",
4665 "space prohibited after that '$op' $at\n" . $hereptr)) {
4666 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4667 if (defined $fix_elements[$n + 2]) {
4668 $fix_elements[$n + 2] =~ s/^\s+//;
4669 }
4670 $line_fixed = 1;
4671 }
4672 }
4673
4674 # unary ++ and unary -- are allowed no space on one side.
4675 } elsif ($op eq '++' or $op eq '--') {
4676 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4677 if (ERROR("SPACING",
4678 "space required one side of that '$op' $at\n" . $hereptr)) {
4679 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4680 $line_fixed = 1;
4681 }
4682 }
4683 if ($ctx =~ /Wx[BE]/ ||
4684 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4685 if (ERROR("SPACING",
4686 "space prohibited before that '$op' $at\n" . $hereptr)) {
4687 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4688 $line_fixed = 1;
4689 }
4690 }
4691 if ($ctx =~ /ExW/) {
4692 if (ERROR("SPACING",
4693 "space prohibited after that '$op' $at\n" . $hereptr)) {
4694 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4695 if (defined $fix_elements[$n + 2]) {
4696 $fix_elements[$n + 2] =~ s/^\s+//;
4697 }
4698 $line_fixed = 1;
4699 }
4700 }
4701
4702 # << and >> may either have or not have spaces both sides
4703 } elsif ($op eq '<<' or $op eq '>>' or
4704 $op eq '&' or $op eq '^' or $op eq '|' or
4705 $op eq '+' or $op eq '-' or
4706 $op eq '*' or $op eq '/' or
4707 $op eq '%')
4708 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004709 if ($check) {
4710 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4711 if (CHK("SPACING",
4712 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4713 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4714 $fix_elements[$n + 2] =~ s/^\s+//;
4715 $line_fixed = 1;
4716 }
4717 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4718 if (CHK("SPACING",
4719 "space preferred before that '$op' $at\n" . $hereptr)) {
4720 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4721 $line_fixed = 1;
4722 }
4723 }
4724 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004725 if (ERROR("SPACING",
4726 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4727 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4728 if (defined $fix_elements[$n + 2]) {
4729 $fix_elements[$n + 2] =~ s/^\s+//;
4730 }
4731 $line_fixed = 1;
4732 }
4733 }
4734
4735 # A colon needs no spaces before when it is
4736 # terminating a case value or a label.
4737 } elsif ($opv eq ':C' || $opv eq ':L') {
4738 if ($ctx =~ /Wx./) {
4739 if (ERROR("SPACING",
4740 "space prohibited before that '$op' $at\n" . $hereptr)) {
4741 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4742 $line_fixed = 1;
4743 }
4744 }
4745
4746 # All the others need spaces both sides.
4747 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4748 my $ok = 0;
4749
4750 # Ignore email addresses <foo@bar>
4751 if (($op eq '<' &&
4752 $cc =~ /^\S+\@\S+>/) ||
4753 ($op eq '>' &&
4754 $ca =~ /<\S+\@\S+$/))
4755 {
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004756 $ok = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004757 }
4758
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004759 # for asm volatile statements
4760 # ignore a colon with another
4761 # colon immediately before or after
4762 if (($op eq ':') &&
4763 ($ca =~ /:$/ || $cc =~ /^:/)) {
4764 $ok = 1;
4765 }
4766
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004767 # messages are ERROR, but ?: are CHK
4768 if ($ok == 0) {
Martin Roth387dec82017-09-17 19:20:46 -06004769 my $msg_level = \&ERROR;
4770 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004771
Martin Roth387dec82017-09-17 19:20:46 -06004772 if (&{$msg_level}("SPACING",
4773 "spaces required around that '$op' $at\n" . $hereptr)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004774 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4775 if (defined $fix_elements[$n + 2]) {
4776 $fix_elements[$n + 2] =~ s/^\s+//;
4777 }
4778 $line_fixed = 1;
4779 }
4780 }
4781 }
4782 $off += length($elements[$n + 1]);
4783
4784## print("n: <$n> GOOD: <$good>\n");
4785
4786 $fixed_line = $fixed_line . $good;
4787 }
4788
4789 if (($#elements % 2) == 0) {
4790 $fixed_line = $fixed_line . $fix_elements[$#elements];
4791 }
4792
4793 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4794 $fixed[$fixlinenr] = $fixed_line;
4795 }
4796
4797
4798 }
4799
4800# check for whitespace before a non-naked semicolon
4801 if ($line =~ /^\+.*\S\s+;\s*$/) {
4802 if (WARN("SPACING",
4803 "space prohibited before semicolon\n" . $herecurr) &&
4804 $fix) {
4805 1 while $fixed[$fixlinenr] =~
4806 s/^(\+.*\S)\s+;/$1;/;
4807 }
4808 }
4809
4810# check for multiple assignments
4811 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4812 CHK("MULTIPLE_ASSIGNMENTS",
4813 "multiple assignments should be avoided\n" . $herecurr);
4814 }
4815
4816## # check for multiple declarations, allowing for a function declaration
4817## # continuation.
4818## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4819## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4820##
4821## # Remove any bracketed sections to ensure we do not
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004822## # falsely report the parameters of functions.
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004823## my $ln = $line;
4824## while ($ln =~ s/\([^\(\)]*\)//g) {
4825## }
4826## if ($ln =~ /,/) {
4827## WARN("MULTIPLE_DECLARATION",
4828## "declaring multiple variables together should be avoided\n" . $herecurr);
4829## }
4830## }
4831
4832#need space before brace following if, while, etc
Alexander Couzensebef00f2016-04-11 00:52:01 +02004833 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
Elyes Haouas26e0b942022-05-22 11:11:11 +02004834 $line =~ /\b(?:else|do)\{/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004835 if (ERROR("SPACING",
4836 "space required before the open brace '{'\n" . $herecurr) &&
4837 $fix) {
Martin Roth387dec82017-09-17 19:20:46 -06004838 #coreboot - Open braces must be escaped in regex
Elyes Haouas26e0b942022-05-22 11:11:11 +02004839 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 \{/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004840 }
4841 }
4842
4843## # check for blank lines before declarations
4844## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4845## $prevrawline =~ /^.\s*$/) {
4846## WARN("SPACING",
4847## "No blank lines before declarations\n" . $hereprev);
4848## }
4849##
4850
4851# closing brace should have a space following it when it has anything
4852# on the line
Elyes Haouas26e0b942022-05-22 11:11:11 +02004853 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004854 if (ERROR("SPACING",
4855 "space required after that close brace '}'\n" . $herecurr) &&
4856 $fix) {
4857 $fixed[$fixlinenr] =~
4858 s/}((?!(?:,|;|\)))\S)/} $1/;
4859 }
4860 }
4861
4862# check spacing on square brackets
4863 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4864 if (ERROR("SPACING",
4865 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4866 $fix) {
4867 $fixed[$fixlinenr] =~
4868 s/\[\s+/\[/;
4869 }
4870 }
4871 if ($line =~ /\s\]/) {
4872 if (ERROR("SPACING",
4873 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4874 $fix) {
4875 $fixed[$fixlinenr] =~
4876 s/\s+\]/\]/;
4877 }
4878 }
4879
4880# check spacing on parentheses
4881 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4882 $line !~ /for\s*\(\s+;/) {
4883 if (ERROR("SPACING",
4884 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4885 $fix) {
4886 $fixed[$fixlinenr] =~
4887 s/\(\s+/\(/;
4888 }
4889 }
4890 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4891 $line !~ /for\s*\(.*;\s+\)/ &&
4892 $line !~ /:\s+\)/) {
4893 if (ERROR("SPACING",
4894 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4895 $fix) {
4896 $fixed[$fixlinenr] =~
4897 s/\s+\)/\)/;
4898 }
4899 }
4900
4901# check unnecessary parentheses around addressof/dereference single $Lvals
4902# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4903
4904 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4905 my $var = $1;
4906 if (CHK("UNNECESSARY_PARENTHESES",
4907 "Unnecessary parentheses around $var\n" . $herecurr) &&
4908 $fix) {
4909 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4910 }
4911 }
4912
4913# check for unnecessary parentheses around function pointer uses
4914# ie: (foo->bar)(); should be foo->bar();
4915# but not "if (foo->bar) (" to avoid some false positives
4916 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4917 my $var = $2;
4918 if (CHK("UNNECESSARY_PARENTHESES",
4919 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4920 $fix) {
4921 my $var2 = deparenthesize($var);
4922 $var2 =~ s/\s//g;
4923 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4924 }
4925 }
4926
Martin Roth387dec82017-09-17 19:20:46 -06004927# check for unnecessary parentheses around comparisons in if uses
Martin Roth60915b32018-08-10 21:04:05 -06004928# when !drivers/staging or command-line uses --strict
4929 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004930 $perl_version_ok && defined($stat) &&
Martin Roth387dec82017-09-17 19:20:46 -06004931 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4932 my $if_stat = $1;
4933 my $test = substr($2, 1, -1);
4934 my $herectx;
4935 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4936 my $match = $1;
4937 # avoid parentheses around potential macro args
4938 next if ($match =~ /^\s*\w+\s*$/);
4939 if (!defined($herectx)) {
4940 $herectx = $here . "\n";
4941 my $cnt = statement_rawlines($if_stat);
4942 for (my $n = 0; $n < $cnt; $n++) {
4943 my $rl = raw_line($linenr, $n);
4944 $herectx .= $rl . "\n";
4945 last if $rl =~ /^[ \+].*\{/;
4946 }
4947 }
4948 CHK("UNNECESSARY_PARENTHESES",
4949 "Unnecessary parentheses around '$match'\n" . $herectx);
4950 }
4951 }
4952
Elyes Haouas26e0b942022-05-22 11:11:11 +02004953# check that goto labels aren't indented (allow a single space indentation)
4954# and ignore bitfield definitions like foo:1
4955# Strictly, labels can have whitespace after the identifier and before the :
4956# but this is not allowed here as many ?: uses would appear to be labels
4957 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
4958 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
4959 $sline !~ /^.\s+default:/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004960 if (WARN("INDENTED_LABEL",
4961 "labels should not be indented\n" . $herecurr) &&
4962 $fix) {
4963 $fixed[$fixlinenr] =~
4964 s/^(.)\s+/$1/;
4965 }
4966 }
4967
4968# return is not a function
4969 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4970 my $spacing = $1;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004971 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004972 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4973 my $value = $1;
4974 $value = deparenthesize($value);
4975 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4976 ERROR("RETURN_PARENTHESES",
4977 "return is not a function, parentheses are not required\n" . $herecurr);
4978 }
4979 } elsif ($spacing !~ /\s+/) {
4980 ERROR("SPACING",
4981 "space required before the open parenthesis '('\n" . $herecurr);
4982 }
4983 }
4984
4985# unnecessary return in a void function
4986# at end-of-function, with the previous line a single leading tab, then return;
4987# and the line before that not a goto label target like "out:"
4988 if ($sline =~ /^[ \+]}\s*$/ &&
4989 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4990 $linenr >= 3 &&
4991 $lines[$linenr - 3] =~ /^[ +]/ &&
4992 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4993 WARN("RETURN_VOID",
4994 "void function return statements are not generally useful\n" . $hereprev);
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01004995 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004996
4997# if statements using unnecessary parentheses - ie: if ((foo == bar))
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01004998 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004999 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5000 my $openparens = $1;
5001 my $count = $openparens =~ tr@\(@\(@;
5002 my $msg = "";
5003 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5004 my $comp = $4; #Not $1 because of $LvalOrFunc
5005 $msg = " - maybe == should be = ?" if ($comp eq "==");
5006 WARN("UNNECESSARY_PARENTHESES",
5007 "Unnecessary parentheses$msg\n" . $herecurr);
5008 }
5009 }
5010
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005011# comparisons with a constant or upper case identifier on the left
5012# avoid cases like "foo + BAR < baz"
5013# only fix matches surrounded by parentheses to avoid incorrect
5014# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005015 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005016 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5017 my $lead = $1;
5018 my $const = $2;
5019 my $comp = $3;
5020 my $to = $4;
5021 my $newcomp = $comp;
5022 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5023 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5024 WARN("CONSTANT_COMPARISON",
5025 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5026 $fix) {
5027 if ($comp eq "<") {
5028 $newcomp = ">";
5029 } elsif ($comp eq "<=") {
5030 $newcomp = ">=";
5031 } elsif ($comp eq ">") {
5032 $newcomp = "<";
5033 } elsif ($comp eq ">=") {
5034 $newcomp = "<=";
5035 }
5036 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5037 }
5038 }
5039
5040# Return of what appears to be an errno should normally be negative
5041 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005042 my $name = $1;
5043 if ($name ne 'EOF' && $name ne 'ERROR') {
5044 WARN("USE_NEGATIVE_ERRNO",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005045 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005046 }
5047 }
5048
5049# Need a space before open parenthesis after if, while etc
5050 if ($line =~ /\b(if|while|for|switch)\(/) {
5051 if (ERROR("SPACING",
5052 "space required before the open parenthesis '('\n" . $herecurr) &&
5053 $fix) {
5054 $fixed[$fixlinenr] =~
5055 s/\b(if|while|for|switch)\(/$1 \(/;
5056 }
5057 }
5058
5059# Check for illegal assignment in if conditional -- and check for trailing
5060# statements after the conditional.
5061 if ($line =~ /do\s*(?!{)/) {
5062 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5063 ctx_statement_block($linenr, $realcnt, 0)
5064 if (!defined $stat);
5065 my ($stat_next) = ctx_statement_block($line_nr_next,
5066 $remain_next, $off_next);
5067 $stat_next =~ s/\n./\n /g;
5068 ##print "stat<$stat> stat_next<$stat_next>\n";
5069
5070 if ($stat_next =~ /^\s*while\b/) {
5071 # If the statement carries leading newlines,
5072 # then count those as offsets.
5073 my ($whitespace) =
5074 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5075 my $offset =
5076 statement_rawlines($whitespace) - 1;
5077
5078 $suppress_whiletrailers{$line_nr_next +
5079 $offset} = 1;
5080 }
5081 }
5082 if (!defined $suppress_whiletrailers{$linenr} &&
5083 defined($stat) && defined($cond) &&
5084 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5085 my ($s, $c) = ($stat, $cond);
5086
5087 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5088 ERROR("ASSIGN_IN_IF",
5089 "do not use assignment in if condition\n" . $herecurr);
5090 }
5091
5092 # Find out what is on the end of the line after the
5093 # conditional.
5094 substr($s, 0, length($c), '');
5095 $s =~ s/\n.*//g;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005096 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005097 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5098 $c !~ /}\s*while\s*/)
5099 {
5100 # Find out how long the conditional actually is.
5101 my @newlines = ($c =~ /\n/gs);
5102 my $cond_lines = 1 + $#newlines;
5103 my $stat_real = '';
5104
5105 $stat_real = raw_line($linenr, $cond_lines)
5106 . "\n" if ($cond_lines);
5107 if (defined($stat_real) && $cond_lines > 1) {
5108 $stat_real = "[...]\n$stat_real";
5109 }
5110
5111 ERROR("TRAILING_STATEMENTS",
5112 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5113 }
5114 }
5115
5116# Check for bitwise tests written as boolean
5117 if ($line =~ /
5118 (?:
5119 (?:\[|\(|\&\&|\|\|)
5120 \s*0[xX][0-9]+\s*
5121 (?:\&\&|\|\|)
5122 |
5123 (?:\&\&|\|\|)
5124 \s*0[xX][0-9]+\s*
5125 (?:\&\&|\|\||\)|\])
5126 )/x)
5127 {
5128 WARN("HEXADECIMAL_BOOLEAN_TEST",
5129 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5130 }
5131
5132# if and else should not have general statements after it
5133 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5134 my $s = $1;
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005135 $s =~ s/$;//g; # Remove any comments
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005136 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5137 ERROR("TRAILING_STATEMENTS",
5138 "trailing statements should be on next line\n" . $herecurr);
5139 }
5140 }
5141# if should not continue a brace
5142 if ($line =~ /}\s*if\b/) {
5143 ERROR("TRAILING_STATEMENTS",
5144 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5145 $herecurr);
5146 }
5147# case and default should not have general statements after them
5148 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5149 $line !~ /\G(?:
5150 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5151 \s*return\s+
5152 )/xg)
5153 {
5154 ERROR("TRAILING_STATEMENTS",
5155 "trailing statements should be on next line\n" . $herecurr);
5156 }
5157
5158 # Check for }<nl>else {, these must be at the same
5159 # indent level to be relevant to each other.
5160 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5161 $previndent == $indent) {
5162 if (ERROR("ELSE_AFTER_BRACE",
5163 "else should follow close brace '}'\n" . $hereprev) &&
5164 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5165 fix_delete_line($fixlinenr - 1, $prevrawline);
5166 fix_delete_line($fixlinenr, $rawline);
5167 my $fixedline = $prevrawline;
5168 $fixedline =~ s/}\s*$//;
5169 if ($fixedline !~ /^\+\s*$/) {
5170 fix_insert_line($fixlinenr, $fixedline);
5171 }
5172 $fixedline = $rawline;
5173 $fixedline =~ s/^(.\s*)else/$1} else/;
5174 fix_insert_line($fixlinenr, $fixedline);
5175 }
5176 }
5177
5178 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5179 $previndent == $indent) {
5180 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5181
5182 # Find out what is on the end of the line after the
5183 # conditional.
5184 substr($s, 0, length($c), '');
5185 $s =~ s/\n.*//g;
5186
5187 if ($s =~ /^\s*;/) {
5188 if (ERROR("WHILE_AFTER_BRACE",
5189 "while should follow close brace '}'\n" . $hereprev) &&
5190 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5191 fix_delete_line($fixlinenr - 1, $prevrawline);
5192 fix_delete_line($fixlinenr, $rawline);
5193 my $fixedline = $prevrawline;
5194 my $trailing = $rawline;
5195 $trailing =~ s/^\+//;
5196 $trailing = trim($trailing);
5197 $fixedline =~ s/}\s*$/} $trailing/;
5198 fix_insert_line($fixlinenr, $fixedline);
5199 }
5200 }
5201 }
5202
5203#Specific variable tests
5204 while ($line =~ m{($Constant|$Lval)}g) {
5205 my $var = $1;
5206
5207#gcc binary extension
5208 if ($var =~ /^$Binary$/) {
5209 if (WARN("GCC_BINARY_CONSTANT",
5210 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
5211 $fix) {
5212 my $hexval = sprintf("0x%x", oct($var));
5213 $fixed[$fixlinenr] =~
5214 s/\b$var\b/$hexval/;
5215 }
5216 }
5217
5218#CamelCase
5219 if ($var !~ /^$Constant$/ &&
5220 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5221#Ignore Page<foo> variants
5222 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02005223#Ignore SI style variants like nS, mV and dB
5224#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5225 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005226#Ignore some three character SI units explicitly, like MiB and KHz
5227 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5228 while ($var =~ m{($Ident)}g) {
5229 my $word = $1;
5230 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5231 if ($check) {
5232 seed_camelcase_includes();
5233 if (!$file && !$camelcase_file_seeded) {
5234 seed_camelcase_file($realfile);
5235 $camelcase_file_seeded = 1;
5236 }
5237 }
5238 if (!defined $camelcase{$word}) {
5239 $camelcase{$word} = 1;
5240 CHK("CAMELCASE",
5241 "Avoid CamelCase: <$word>\n" . $herecurr);
5242 }
5243 }
5244 }
5245 }
5246
5247#no spaces allowed after \ in define
5248 if ($line =~ /\#\s*define.*\\\s+$/) {
5249 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5250 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5251 $fix) {
5252 $fixed[$fixlinenr] =~ s/\s+$//;
5253 }
5254 }
5255
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005256# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5257# itself <asm/foo.h> (uses RAW line)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005258 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5259 my $file = "$1.h";
5260 my $checkfile = "include/linux/$file";
5261 if (-f "$root/$checkfile" &&
5262 $realfile ne $checkfile &&
5263 $1 !~ /$allowed_asm_includes/)
5264 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005265 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5266 if ($asminclude > 0) {
5267 if ($realfile =~ m{^arch/}) {
5268 CHK("ARCH_INCLUDE_LINUX",
5269 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5270 } else {
5271 WARN("INCLUDE_LINUX",
5272 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5273 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005274 }
5275 }
5276 }
5277
5278# multi-statement macros should be enclosed in a do while loop, grab the
5279# first statement and ensure its the whole macro if its not enclosed
5280# in a known good container
5281 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5282 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5283 my $ln = $linenr;
5284 my $cnt = $realcnt;
5285 my ($off, $dstat, $dcond, $rest);
5286 my $ctx = '';
5287 my $has_flow_statement = 0;
5288 my $has_arg_concat = 0;
5289 ($dstat, $dcond, $ln, $cnt, $off) =
5290 ctx_statement_block($linenr, $realcnt, 0);
5291 $ctx = $dstat;
5292 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5293 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5294
5295 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005296 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005297
Martin Rothedd591d2017-03-14 10:16:29 -06005298 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5299 my $define_args = $1;
5300 my $define_stmt = $dstat;
5301 my @def_args = ();
5302
5303 if (defined $define_args && $define_args ne "") {
5304 $define_args = substr($define_args, 1, length($define_args) - 2);
5305 $define_args =~ s/\s*//g;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005306 $define_args =~ s/\\\+?//g;
Martin Rothedd591d2017-03-14 10:16:29 -06005307 @def_args = split(",", $define_args);
5308 }
5309
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005310 $dstat =~ s/$;//g;
5311 $dstat =~ s/\\\n.//g;
5312 $dstat =~ s/^\s*//s;
5313 $dstat =~ s/\s*$//s;
5314
5315 # Flatten any parentheses and braces
Elyes Haouas26e0b942022-05-22 11:11:11 +02005316 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5317 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5318 $dstat =~ s/.\[[^\[\]]*\]/1u/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005319 {
5320 }
5321
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01005322 # Flatten any obvious string concatenation.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005323 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5324 $dstat =~ s/$Ident\s*($String)/$1/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005325 {
5326 }
5327
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005328 # Make asm volatile uses seem like a generic function
5329 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5330
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005331 my $exceptions = qr{
5332 $Declare|
5333 module_param_named|
5334 MODULE_PARM_DESC|
5335 DECLARE_PER_CPU|
5336 DEFINE_PER_CPU|
5337 __typeof__\(|
5338 union|
5339 struct|
5340 \.$Ident\s*=\s*|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005341 ^\"|\"$|
5342 ^\[
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005343 }x;
5344 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
Martin Rothedd591d2017-03-14 10:16:29 -06005345
5346 $ctx =~ s/\n*$//;
Martin Rothedd591d2017-03-14 10:16:29 -06005347 my $stmt_cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005348 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
Martin Rothedd591d2017-03-14 10:16:29 -06005349
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005350 if ($dstat ne '' &&
5351 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5352 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5353 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5354 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5355 $dstat !~ /$exceptions/ &&
5356 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5357 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5358 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
Elyes Haouas26e0b942022-05-22 11:11:11 +02005359 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005360 $dstat !~ /^for\s*$Constant$/ && # for (...)
5361 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
Martin Rothedd591d2017-03-14 10:16:29 -06005362 $dstat !~ /^do\s*{/ && # do {...
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005363 $dstat !~ /^\(\{/ && # ({...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005364 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5365 {
Martin Roth387dec82017-09-17 19:20:46 -06005366 if ($dstat =~ /^\s*if\b/) {
5367 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5368 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5369 } elsif ($dstat =~ /;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005370 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5371 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5372 } else {
5373 ERROR("COMPLEX_MACRO",
5374 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5375 }
Martin Rothedd591d2017-03-14 10:16:29 -06005376
5377 }
5378
5379 # Make $define_stmt single line, comment-free, etc
5380 my @stmt_array = split('\n', $define_stmt);
5381 my $first = 1;
5382 $define_stmt = "";
5383 foreach my $l (@stmt_array) {
5384 $l =~ s/\\$//;
5385 if ($first) {
5386 $define_stmt = $l;
5387 $first = 0;
5388 } elsif ($l =~ /^[\+ ]/) {
5389 $define_stmt .= substr($l, 1);
5390 }
5391 }
5392 $define_stmt =~ s/$;//g;
5393 $define_stmt =~ s/\s+/ /g;
5394 $define_stmt = trim($define_stmt);
5395
5396# check if any macro arguments are reused (ignore '...' and 'type')
5397 foreach my $arg (@def_args) {
5398 next if ($arg =~ /\.\.\./);
5399 next if ($arg =~ /^type$/i);
Martin Roth387dec82017-09-17 19:20:46 -06005400 my $tmp_stmt = $define_stmt;
Elyes Haouas26e0b942022-05-22 11:11:11 +02005401 $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 -06005402 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5403 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
Martin Roth60915b32018-08-10 21:04:05 -06005404 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005405 if ($use_cnt > 1) {
5406 CHK("MACRO_ARG_REUSE",
5407 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5408 }
5409# check if any macro arguments may have other precedence issues
Martin Roth387dec82017-09-17 19:20:46 -06005410 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
Martin Rothedd591d2017-03-14 10:16:29 -06005411 ((defined($1) && $1 ne ',') ||
5412 (defined($2) && $2 ne ','))) {
5413 CHK("MACRO_ARG_PRECEDENCE",
5414 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5415 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005416 }
5417
5418# check for macros with flow control, but without ## concatenation
5419# ## concatenation is commonly a macro that defines a function so ignore those
5420 if ($has_flow_statement && !$has_arg_concat) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005421 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005422 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005423
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005424 WARN("MACRO_WITH_FLOW_CONTROL",
5425 "Macros with flow control statements should be avoided\n" . "$herectx");
5426 }
5427
5428# check for line continuations outside of #defines, preprocessor #, and asm
5429
5430 } else {
5431 if ($prevline !~ /^..*\\$/ &&
5432 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5433 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5434 $line =~ /^\+.*\\$/) {
5435 WARN("LINE_CONTINUATIONS",
5436 "Avoid unnecessary line continuations\n" . $herecurr);
5437 }
5438 }
5439
5440# do {} while (0) macro tests:
5441# single-statement macros do not need to be enclosed in do while (0) loop,
5442# macro should not end with a semicolon
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005443 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005444 $realfile !~ m@/vmlinux.lds.h$@ &&
5445 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5446 my $ln = $linenr;
5447 my $cnt = $realcnt;
5448 my ($off, $dstat, $dcond, $rest);
5449 my $ctx = '';
5450 ($dstat, $dcond, $ln, $cnt, $off) =
5451 ctx_statement_block($linenr, $realcnt, 0);
5452 $ctx = $dstat;
5453
5454 $dstat =~ s/\\\n.//g;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005455 $dstat =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005456
5457 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5458 my $stmts = $2;
5459 my $semis = $3;
5460
5461 $ctx =~ s/\n*$//;
5462 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005463 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005464
5465 if (($stmts =~ tr/;/;/) == 1 &&
5466 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5467 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5468 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5469 }
5470 if (defined $semis && $semis ne "") {
5471 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5472 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5473 }
5474 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5475 $ctx =~ s/\n*$//;
5476 my $cnt = statement_rawlines($ctx);
Martin Roth60915b32018-08-10 21:04:05 -06005477 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005478
5479 WARN("TRAILING_SEMICOLON",
5480 "macros should not use a trailing semicolon\n" . "$herectx");
5481 }
5482 }
5483
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005484# check for redundant bracing round if etc
5485 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5486 my ($level, $endln, @chunks) =
5487 ctx_statement_full($linenr, $realcnt, 1);
5488 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5489 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5490 if ($#chunks > 0 && $level == 0) {
5491 my @allowed = ();
5492 my $allow = 0;
5493 my $seen = 0;
5494 my $herectx = $here . "\n";
5495 my $ln = $linenr - 1;
5496 for my $chunk (@chunks) {
5497 my ($cond, $block) = @{$chunk};
5498
5499 # If the condition carries leading newlines, then count those as offsets.
5500 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5501 my $offset = statement_rawlines($whitespace) - 1;
5502
5503 $allowed[$allow] = 0;
5504 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5505
5506 # We have looked at and allowed this specific line.
5507 $suppress_ifbraces{$ln + $offset} = 1;
5508
5509 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5510 $ln += statement_rawlines($block) - 1;
5511
5512 substr($block, 0, length($cond), '');
5513
5514 $seen++ if ($block =~ /^\s*{/);
5515
5516 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5517 if (statement_lines($cond) > 1) {
5518 #print "APW: ALLOWED: cond<$cond>\n";
5519 $allowed[$allow] = 1;
5520 }
5521 if ($block =~/\b(?:if|for|while)\b/) {
5522 #print "APW: ALLOWED: block<$block>\n";
5523 $allowed[$allow] = 1;
5524 }
5525 if (statement_block_size($block) > 1) {
5526 #print "APW: ALLOWED: lines block<$block>\n";
5527 $allowed[$allow] = 1;
5528 }
5529 $allow++;
5530 }
5531 if ($seen) {
5532 my $sum_allowed = 0;
5533 foreach (@allowed) {
5534 $sum_allowed += $_;
5535 }
5536 if ($sum_allowed == 0) {
5537 WARN("BRACES",
5538 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5539 } elsif ($sum_allowed != $allow &&
5540 $seen != $allow) {
5541 CHK("BRACES",
5542 "braces {} should be used on all arms of this statement\n" . $herectx);
5543 }
5544 }
5545 }
5546 }
5547 if (!defined $suppress_ifbraces{$linenr - 1} &&
5548 $line =~ /\b(if|while|for|else)\b/) {
5549 my $allowed = 0;
5550
5551 # Check the pre-context.
5552 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5553 #print "APW: ALLOWED: pre<$1>\n";
5554 $allowed = 1;
5555 }
5556
5557 my ($level, $endln, @chunks) =
5558 ctx_statement_full($linenr, $realcnt, $-[0]);
5559
5560 # Check the condition.
5561 my ($cond, $block) = @{$chunks[0]};
5562 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5563 if (defined $cond) {
5564 substr($block, 0, length($cond), '');
5565 }
5566 if (statement_lines($cond) > 1) {
5567 #print "APW: ALLOWED: cond<$cond>\n";
5568 $allowed = 1;
5569 }
5570 if ($block =~/\b(?:if|for|while)\b/) {
5571 #print "APW: ALLOWED: block<$block>\n";
5572 $allowed = 1;
5573 }
5574 if (statement_block_size($block) > 1) {
5575 #print "APW: ALLOWED: lines block<$block>\n";
5576 $allowed = 1;
5577 }
5578 # Check the post-context.
5579 if (defined $chunks[1]) {
5580 my ($cond, $block) = @{$chunks[1]};
5581 if (defined $cond) {
5582 substr($block, 0, length($cond), '');
5583 }
5584 if ($block =~ /^\s*\{/) {
5585 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5586 $allowed = 1;
5587 }
5588 }
5589 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005590 my $cnt = statement_rawlines($block);
Martin Roth60915b32018-08-10 21:04:05 -06005591 my $herectx = get_stat_here($linenr, $cnt, $here);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005592
5593 WARN("BRACES",
5594 "braces {} are not necessary for single statement blocks\n" . $herectx);
5595 }
5596 }
5597
Martin Rothedd591d2017-03-14 10:16:29 -06005598# check for single line unbalanced braces
5599 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5600 $sline =~ /^.\s*else\s*\{\s*$/) {
5601 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5602 }
5603
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005604# check for unnecessary blank lines around braces
5605 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005606 if (CHK("BRACES",
5607 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5608 $fix && $prevrawline =~ /^\+/) {
5609 fix_delete_line($fixlinenr - 1, $prevrawline);
5610 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005611 }
5612 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005613 if (CHK("BRACES",
5614 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5615 $fix) {
5616 fix_delete_line($fixlinenr, $rawline);
5617 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005618 }
5619
5620# no volatiles please
5621 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5622 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5623 WARN("VOLATILE",
Martin Rothedd591d2017-03-14 10:16:29 -06005624 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005625 }
5626
5627# Check for user-visible strings broken across lines, which breaks the ability
5628# to grep for the string. Make exceptions when the previous string ends in a
5629# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5630# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005631 if ($line =~ /^\+\s*$String/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005632 $prevline =~ /"\s*$/ &&
5633 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5634 if (WARN("SPLIT_STRING",
5635 "quoted string split across lines\n" . $hereprev) &&
5636 $fix &&
5637 $prevrawline =~ /^\+.*"\s*$/ &&
5638 $last_coalesced_string_linenr != $linenr - 1) {
5639 my $extracted_string = get_quoted_string($line, $rawline);
5640 my $comma_close = "";
5641 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5642 $comma_close = $1;
5643 }
5644
5645 fix_delete_line($fixlinenr - 1, $prevrawline);
5646 fix_delete_line($fixlinenr, $rawline);
5647 my $fixedline = $prevrawline;
5648 $fixedline =~ s/"\s*$//;
5649 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5650 fix_insert_line($fixlinenr - 1, $fixedline);
5651 $fixedline = $rawline;
5652 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5653 if ($fixedline !~ /\+\s*$/) {
5654 fix_insert_line($fixlinenr, $fixedline);
5655 }
5656 $last_coalesced_string_linenr = $linenr;
5657 }
5658 }
5659
5660# check for missing a space in a string concatenation
5661 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5662 WARN('MISSING_SPACE',
5663 "break quoted strings at a space character\n" . $hereprev);
5664 }
5665
Martin Roth387dec82017-09-17 19:20:46 -06005666# check for an embedded function name in a string when the function is known
5667# This does not work very well for -f --file checking as it depends on patch
5668# context providing the function name or a single line form for in-file
5669# function declarations
Martin Rothedd591d2017-03-14 10:16:29 -06005670 if ($line =~ /^\+.*$String/ &&
5671 defined($context_function) &&
Martin Roth387dec82017-09-17 19:20:46 -06005672 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5673 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
Martin Rothedd591d2017-03-14 10:16:29 -06005674 WARN("EMBEDDED_FUNCTION_NAME",
Martin Roth387dec82017-09-17 19:20:46 -06005675 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
Martin Rothedd591d2017-03-14 10:16:29 -06005676 }
5677
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005678# check for spaces before a quoted newline
5679 if ($rawline =~ /^.*\".*\s\\n/) {
5680 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5681 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5682 $fix) {
5683 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5684 }
5685
5686 }
5687
5688# concatenated string without spaces between elements
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005689 if ($line =~ /$String[A-Z_]/ || $line =~ /[A-Za-z0-9_]$String/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005690 CHK("CONCATENATED_STRING",
5691 "Concatenated strings should use spaces between elements\n" . $herecurr);
5692 }
5693
5694# uncoalesced string fragments
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005695 if ($line =~ /$String\s*"/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005696 WARN("STRING_FRAGMENTS",
5697 "Consecutive strings are generally better as a single string\n" . $herecurr);
5698 }
5699
Martin Rothedd591d2017-03-14 10:16:29 -06005700# check for non-standard and hex prefixed decimal printf formats
5701 my $show_L = 1; #don't show the same defect twice
5702 my $show_Z = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005703 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
Martin Rothedd591d2017-03-14 10:16:29 -06005704 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005705 $string =~ s/%%/__/g;
Martin Rothedd591d2017-03-14 10:16:29 -06005706 # check for %L
5707 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005708 WARN("PRINTF_L",
Martin Rothedd591d2017-03-14 10:16:29 -06005709 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5710 $show_L = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005711 }
Martin Rothedd591d2017-03-14 10:16:29 -06005712 # check for %Z
5713 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5714 WARN("PRINTF_Z",
5715 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5716 $show_Z = 0;
5717 }
5718 # check for 0x<decimal>
5719 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5720 ERROR("PRINTF_0XDECIMAL",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005721 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5722 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005723 }
5724
5725# check for line continuations in quoted strings with odd counts of "
Martin Roth60915b32018-08-10 21:04:05 -06005726 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005727 WARN("LINE_CONTINUATIONS",
5728 "Avoid line continuations in quoted strings\n" . $herecurr);
5729 }
5730
5731# warn about #if 0
5732 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
Elyes Haouas26e0b942022-05-22 11:11:11 +02005733 WARN("IF_0",
5734 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5735 }
5736
5737# warn about #if 1
5738 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5739 WARN("IF_1",
5740 "Consider removing the #if 1 and its #endif\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005741 }
5742
5743# check for needless "if (<foo>) fn(<foo>)" uses
5744 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005745 my $tested = quotemeta($1);
5746 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5747 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5748 my $func = $1;
5749 if (WARN('NEEDLESS_IF',
5750 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5751 $fix) {
5752 my $do_fix = 1;
5753 my $leading_tabs = "";
5754 my $new_leading_tabs = "";
5755 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5756 $leading_tabs = $1;
5757 } else {
5758 $do_fix = 0;
5759 }
5760 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5761 $new_leading_tabs = $1;
5762 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5763 $do_fix = 0;
5764 }
5765 } else {
5766 $do_fix = 0;
5767 }
5768 if ($do_fix) {
5769 fix_delete_line($fixlinenr - 1, $prevrawline);
5770 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5771 }
5772 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005773 }
5774 }
5775
5776# check for unnecessary "Out of Memory" messages
5777 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5778 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5779 (defined $1 || defined $3) &&
5780 $linenr > 3) {
5781 my $testval = $2;
5782 my $testline = $lines[$linenr - 3];
5783
5784 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5785# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5786
Elyes Haouasa7b0d382022-05-23 18:33:15 +02005787 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5788 $s !~ /\b__GFP_NOWARN\b/ ) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005789 WARN("OOM_MESSAGE",
5790 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5791 }
5792 }
5793
5794# check for logging functions with KERN_<LEVEL>
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005795 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005796 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5797 my $level = $1;
5798 if (WARN("UNNECESSARY_KERN_LEVEL",
5799 "Possible unnecessary $level\n" . $herecurr) &&
5800 $fix) {
5801 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5802 }
5803 }
5804
Martin Rothedd591d2017-03-14 10:16:29 -06005805# check for logging continuations
5806 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5807 WARN("LOGGING_CONTINUATION",
5808 "Avoid logging continuation uses where feasible\n" . $herecurr);
5809 }
5810
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005811# check for mask then right shift without a parentheses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005812 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005813 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5814 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5815 WARN("MASK_THEN_SHIFT",
5816 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5817 }
5818
5819# check for pointer comparisons to NULL
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01005820 if ($perl_version_ok) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005821 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5822 my $val = $1;
5823 my $equal = "!";
5824 $equal = "" if ($4 eq "!=");
5825 if (CHK("COMPARISON_TO_NULL",
5826 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5827 $fix) {
5828 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5829 }
5830 }
5831 }
5832
5833# check for bad placement of section $InitAttribute (e.g.: __initdata)
5834 if ($line =~ /(\b$InitAttribute\b)/) {
5835 my $attr = $1;
5836 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5837 my $ptr = $1;
5838 my $var = $2;
5839 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5840 ERROR("MISPLACED_INIT",
5841 "$attr should be placed after $var\n" . $herecurr)) ||
5842 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5843 WARN("MISPLACED_INIT",
5844 "$attr should be placed after $var\n" . $herecurr))) &&
5845 $fix) {
5846 $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;
5847 }
5848 }
5849 }
5850
5851# check for $InitAttributeData (ie: __initdata) with const
5852 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5853 my $attr = $1;
5854 $attr =~ /($InitAttributePrefix)(.*)/;
5855 my $attr_prefix = $1;
5856 my $attr_type = $2;
5857 if (ERROR("INIT_ATTRIBUTE",
5858 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5859 $fix) {
5860 $fixed[$fixlinenr] =~
5861 s/$InitAttributeData/${attr_prefix}initconst/;
5862 }
5863 }
5864
5865# check for $InitAttributeConst (ie: __initconst) without const
5866 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5867 my $attr = $1;
5868 if (ERROR("INIT_ATTRIBUTE",
5869 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5870 $fix) {
5871 my $lead = $fixed[$fixlinenr] =~
5872 /(^\+\s*(?:static\s+))/;
5873 $lead = rtrim($1);
5874 $lead = "$lead " if ($lead !~ /^\+$/);
5875 $lead = "${lead}const ";
5876 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5877 }
5878 }
5879
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005880# check for __read_mostly with const non-pointer (should just be const)
5881 if ($line =~ /\b__read_mostly\b/ &&
5882 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5883 if (ERROR("CONST_READ_MOSTLY",
5884 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5885 $fix) {
5886 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5887 }
5888 }
5889
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005890# don't use __constant_<foo> functions outside of include/uapi/
5891 if ($realfile !~ m@^include/uapi/@ &&
5892 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5893 my $constant_func = $1;
5894 my $func = $constant_func;
5895 $func =~ s/^__constant_//;
5896 if (WARN("CONSTANT_CONVERSION",
5897 "$constant_func should be $func\n" . $herecurr) &&
5898 $fix) {
5899 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5900 }
5901 }
5902
5903# prefer usleep_range over udelay
5904 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5905 my $delay = $1;
5906 # ignore udelay's < 10, however
5907 if (! ($delay < 10) ) {
5908 CHK("USLEEP_RANGE",
5909 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5910 }
5911 if ($delay > 2000) {
5912 WARN("LONG_UDELAY",
5913 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5914 }
5915 }
5916
5917# warn about unexpectedly long msleep's
5918 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5919 if ($1 < 20) {
5920 WARN("MSLEEP",
5921 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5922 }
5923 }
5924
5925# check for comparisons of jiffies
5926 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5927 WARN("JIFFIES_COMPARISON",
5928 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5929 }
5930
5931# check for comparisons of get_jiffies_64()
5932 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5933 WARN("JIFFIES_COMPARISON",
5934 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5935 }
5936
5937# warn about #ifdefs in C files
5938# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5939# print "#ifdef in C files should be avoided\n";
5940# print "$herecurr";
5941# $clean = 0;
5942# }
5943
5944# warn about spacing in #ifdefs
5945 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5946 if (ERROR("SPACING",
5947 "exactly one space required after that #$1\n" . $herecurr) &&
5948 $fix) {
5949 $fixed[$fixlinenr] =~
5950 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5951 }
5952
5953 }
5954
5955# check for spinlock_t definitions without a comment.
5956 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5957 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5958 my $which = $1;
5959 if (!ctx_has_comment($first_line, $linenr)) {
5960 CHK("UNCOMMENTED_DEFINITION",
5961 "$1 definition without comment\n" . $herecurr);
5962 }
5963 }
5964# check for memory barriers without a comment.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005965
5966 my $barriers = qr{
5967 mb|
5968 rmb|
Elyes Haouas26e0b942022-05-22 11:11:11 +02005969 wmb
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005970 }x;
5971 my $barrier_stems = qr{
5972 mb__before_atomic|
5973 mb__after_atomic|
5974 store_release|
5975 load_acquire|
5976 store_mb|
5977 (?:$barriers)
5978 }x;
5979 my $all_barriers = qr{
5980 (?:$barriers)|
5981 smp_(?:$barrier_stems)|
5982 virt_(?:$barrier_stems)
5983 }x;
5984
5985 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005986 if (!ctx_has_comment($first_line, $linenr)) {
5987 WARN("MEMORY_BARRIER",
5988 "memory barrier without comment\n" . $herecurr);
5989 }
5990 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005991
5992 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5993
5994 if ($realfile !~ m@^include/asm-generic/@ &&
5995 $realfile !~ m@/barrier\.h$@ &&
5996 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5997 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5998 WARN("MEMORY_BARRIER",
5999 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6000 }
6001
6002# check for waitqueue_active without a comment.
6003 if ($line =~ /\bwaitqueue_active\s*\(/) {
6004 if (!ctx_has_comment($first_line, $linenr)) {
6005 WARN("WAITQUEUE_ACTIVE",
6006 "waitqueue_active without comment\n" . $herecurr);
6007 }
6008 }
6009
Elyes Haouas26e0b942022-05-22 11:11:11 +02006010# check for data_race without a comment.
6011 if ($line =~ /\bdata_race\s*\(/) {
6012 if (!ctx_has_comment($first_line, $linenr)) {
6013 WARN("DATA_RACE",
6014 "data_race without comment\n" . $herecurr);
6015 }
Martin Roth60915b32018-08-10 21:04:05 -06006016 }
6017
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006018# check of hardware specific defines
6019 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6020 CHK("ARCH_DEFINES",
6021 "architecture specific defines should be avoided\n" . $herecurr);
6022 }
6023
Martin Roth387dec82017-09-17 19:20:46 -06006024# check that the storage class is not after a type
6025 if ($line =~ /\b($Type)\s+($Storage)\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006026 WARN("STORAGE_CLASS",
Martin Roth387dec82017-09-17 19:20:46 -06006027 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6028 }
6029# Check that the storage class is at the beginning of a declaration
6030 if ($line =~ /\b$Storage\b/ &&
6031 $line !~ /^.\s*$Storage/ &&
6032 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6033 $1 !~ /[\,\)]\s*$/) {
6034 WARN("STORAGE_CLASS",
6035 "storage class should be at the beginning of the declaration\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006036 }
6037
6038# check the location of the inline attribute, that it is between
6039# storage class and type.
6040 if ($line =~ /\b$Type\s+$Inline\b/ ||
6041 $line =~ /\b$Inline\s+$Storage\b/) {
6042 ERROR("INLINE_LOCATION",
6043 "inline keyword should sit between storage class and type\n" . $herecurr);
6044 }
6045
6046# Check for __inline__ and __inline, prefer inline
6047 if ($realfile !~ m@\binclude/uapi/@ &&
6048 $line =~ /\b(__inline__|__inline)\b/) {
6049 if (WARN("INLINE",
6050 "plain inline is preferred over $1\n" . $herecurr) &&
6051 $fix) {
6052 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6053
6054 }
6055 }
6056
Elyes Haouas069dfe32022-05-23 18:38:19 +02006057# Check for compiler attributes
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006058 if ($realfile !~ m@\binclude/uapi/@ &&
Elyes Haouas069dfe32022-05-23 18:38:19 +02006059 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6060 my $attr = $1;
6061 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006062
Elyes Haouas069dfe32022-05-23 18:38:19 +02006063 my %attr_list = (
6064 "alias" => "__alias",
6065 "aligned" => "__aligned",
6066 "always_inline" => "__always_inline",
6067 "assume_aligned" => "__assume_aligned",
6068 "cold" => "__cold",
6069 "const" => "__attribute_const__",
6070 "copy" => "__copy",
6071 "designated_init" => "__designated_init",
6072 "externally_visible" => "__visible",
6073 "format" => "printf|scanf",
6074 "gnu_inline" => "__gnu_inline",
6075 "malloc" => "__malloc",
6076 "mode" => "__mode",
6077 "no_caller_saved_registers" => "__no_caller_saved_registers",
6078 "noclone" => "__noclone",
6079 "noinline" => "noinline",
6080 "nonstring" => "__nonstring",
6081 "noreturn" => "__noreturn",
6082 "packed" => "__packed",
6083 "pure" => "__pure",
6084 "section" => "__section",
6085 "used" => "__used",
6086 "weak" => "__weak"
6087 );
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006088
Elyes Haouas069dfe32022-05-23 18:38:19 +02006089 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6090 my $orig_attr = $1;
6091 my $params = '';
6092 $params = $2 if defined($2);
6093 my $curr_attr = $orig_attr;
6094 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6095 if (exists($attr_list{$curr_attr})) {
6096 my $new = $attr_list{$curr_attr};
6097 if ($curr_attr eq "format" && $params) {
6098 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6099 $new = "__$1\($2";
6100 } else {
6101 $new = "$new$params";
6102 }
6103 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6104 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6105 $fix) {
6106 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6107 $fixed[$fixlinenr] =~ s/$remove//;
6108 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6109 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6110 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6111 }
6112 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006113 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006114
Elyes Haouas069dfe32022-05-23 18:38:19 +02006115 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6116 if ($attr =~ /^_*unused/) {
6117 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6118 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006119 }
6120 }
6121
6122# Check for __attribute__ weak, or __weak declarations (may have link issues)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006123 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006124 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6125 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6126 $line =~ /\b__weak\b/)) {
6127 ERROR("WEAK_DECLARATION",
6128 "Using weak declarations can have unintended link defects\n" . $herecurr);
6129 }
6130
Martin Rothedd591d2017-03-14 10:16:29 -06006131# check for c99 types like uint8_t used outside of uapi/ and tools/
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006132 if ($realfile !~ m@\binclude/uapi/@ &&
Martin Rothedd591d2017-03-14 10:16:29 -06006133 $realfile !~ m@\btools/@ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006134 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6135 my $type = $1;
6136 if ($type =~ /\b($typeC99Typedefs)\b/) {
6137 $type = $1;
6138 my $kernel_type = 'u';
6139 $kernel_type = 's' if ($type =~ /^_*[si]/);
6140 $type =~ /(\d+)/;
6141 $kernel_type .= $1;
6142 if (CHK("PREFER_KERNEL_TYPES",
6143 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6144 $fix) {
6145 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6146 }
6147 }
6148 }
6149
6150# check for cast of C90 native int or longer types constants
6151 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6152 my $cast = $1;
6153 my $const = $2;
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006154 my $suffix = "";
6155 my $newconst = $const;
6156 $newconst =~ s/${Int_type}$//;
6157 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6158 if ($cast =~ /\blong\s+long\b/) {
6159 $suffix .= 'LL';
6160 } elsif ($cast =~ /\blong\b/) {
6161 $suffix .= 'L';
6162 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006163 if (WARN("TYPECAST_INT_CONSTANT",
Elyes Haouas00d8ffd2022-04-12 12:50:02 +02006164 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006165 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006166 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6167 }
6168 }
6169
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006170# check for sizeof(&)
6171 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6172 WARN("SIZEOF_ADDRESS",
6173 "sizeof(& should be avoided\n" . $herecurr);
6174 }
6175
6176# check for sizeof without parenthesis
6177 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6178 if (WARN("SIZEOF_PARENTHESIS",
6179 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6180 $fix) {
6181 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6182 }
6183 }
6184
6185# check for struct spinlock declarations
6186 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6187 WARN("USE_SPINLOCK_T",
6188 "struct spinlock should be spinlock_t\n" . $herecurr);
6189 }
6190
6191# check for seq_printf uses that could be seq_puts
6192 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6193 my $fmt = get_quoted_string($line, $rawline);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006194 $fmt =~ s/%%//g;
6195 if ($fmt !~ /%/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006196 if (WARN("PREFER_SEQ_PUTS",
6197 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6198 $fix) {
6199 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6200 }
6201 }
6202 }
6203
Martin Roth60915b32018-08-10 21:04:05 -06006204# check for vsprintf extension %p<foo> misuses
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006205 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006206 defined $stat &&
6207 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6208 $1 !~ /^_*volatile_*$/) {
Martin Roth60915b32018-08-10 21:04:05 -06006209 my $stat_real;
6210
Martin Roth387dec82017-09-17 19:20:46 -06006211 my $lc = $stat =~ tr@\n@@;
6212 $lc = $lc + $linenr;
6213 for (my $count = $linenr; $count <= $lc; $count++) {
Martin Roth60915b32018-08-10 21:04:05 -06006214 my $specifier;
6215 my $extension;
6216 my $bad_specifier = "";
Martin Roth387dec82017-09-17 19:20:46 -06006217 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6218 $fmt =~ s/%%//g;
Martin Roth60915b32018-08-10 21:04:05 -06006219
6220 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
6221 $specifier = $1;
6222 $extension = $2;
6223 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
6224 $bad_specifier = $specifier;
6225 last;
6226 }
6227 if ($extension eq "x" && !defined($stat_real)) {
6228 if (!defined($stat_real)) {
6229 $stat_real = get_stat_real($linenr, $lc);
6230 }
6231 WARN("VSPRINTF_SPECIFIER_PX",
6232 "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");
6233 }
Martin Roth387dec82017-09-17 19:20:46 -06006234 }
Martin Roth60915b32018-08-10 21:04:05 -06006235 if ($bad_specifier ne "") {
6236 my $stat_real = get_stat_real($linenr, $lc);
6237 my $ext_type = "Invalid";
6238 my $use = "";
6239 if ($bad_specifier =~ /p[Ff]/) {
6240 $ext_type = "Deprecated";
6241 $use = " - use %pS instead";
6242 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6243 }
6244
6245 WARN("VSPRINTF_POINTER_EXTENSION",
6246 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
Martin Roth387dec82017-09-17 19:20:46 -06006247 }
Martin Roth387dec82017-09-17 19:20:46 -06006248 }
6249 }
6250
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006251# Check for misused memsets
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006252 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006253 defined $stat &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006254 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006255
6256 my $ms_addr = $2;
6257 my $ms_val = $7;
6258 my $ms_size = $12;
6259
6260 if ($ms_size =~ /^(0x|)0$/i) {
6261 ERROR("MEMSET",
6262 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6263 } elsif ($ms_size =~ /^(0x|)1$/i) {
6264 WARN("MEMSET",
6265 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6266 }
6267 }
6268
6269# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006270# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006271# defined $stat &&
6272# $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6273# if (WARN("PREFER_ETHER_ADDR_COPY",
6274# "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6275# $fix) {
6276# $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6277# }
6278# }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006279
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006280# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006281# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006282# defined $stat &&
6283# $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6284# WARN("PREFER_ETHER_ADDR_EQUAL",
6285# "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6286# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006287
6288# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6289# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006290# if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006291# defined $stat &&
6292# $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6293#
6294# my $ms_val = $7;
6295#
6296# if ($ms_val =~ /^(?:0x|)0+$/i) {
6297# if (WARN("PREFER_ETH_ZERO_ADDR",
6298# "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6299# $fix) {
6300# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6301# }
6302# } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6303# if (WARN("PREFER_ETH_BROADCAST_ADDR",
6304# "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6305# $fix) {
6306# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6307# }
6308# }
6309# }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006310
Elyes Haouasf0e150c2022-04-12 13:12:19 +02006311# strlcpy uses that should likely be strscpy
6312 if ($line =~ /\bstrlcpy\s*\(/) {
6313 WARN("STRLCPY",
6314 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6315 }
6316
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006317# typecasts on min/max could be min_t/max_t
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006318 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006319 defined $stat &&
6320 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6321 if (defined $2 || defined $7) {
6322 my $call = $1;
6323 my $cast1 = deparenthesize($2);
6324 my $arg1 = $3;
6325 my $cast2 = deparenthesize($7);
6326 my $arg2 = $8;
6327 my $cast;
6328
6329 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6330 $cast = "$cast1 or $cast2";
6331 } elsif ($cast1 ne "") {
6332 $cast = $cast1;
6333 } else {
6334 $cast = $cast2;
6335 }
6336 WARN("MINMAX",
6337 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6338 }
6339 }
6340
6341# check usleep_range arguments
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006342 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006343 defined $stat &&
6344 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6345 my $min = $1;
6346 my $max = $7;
6347 if ($min eq $max) {
6348 WARN("USLEEP_RANGE",
6349 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6350 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6351 $min > $max) {
6352 WARN("USLEEP_RANGE",
6353 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6354 }
6355 }
6356
6357# check for naked sscanf
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006358 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006359 defined $stat &&
6360 $line =~ /\bsscanf\b/ &&
6361 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6362 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6363 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6364 my $lc = $stat =~ tr@\n@@;
6365 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006366 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006367 WARN("NAKED_SSCANF",
6368 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6369 }
6370
6371# check for simple sscanf that should be kstrto<foo>
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006372 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006373 defined $stat &&
6374 $line =~ /\bsscanf\b/) {
6375 my $lc = $stat =~ tr@\n@@;
6376 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006377 my $stat_real = get_stat_real($linenr, $lc);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006378 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6379 my $format = $6;
6380 my $count = $format =~ tr@%@%@;
6381 if ($count == 1 &&
6382 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6383 WARN("SSCANF_TO_KSTRTO",
6384 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6385 }
6386 }
6387 }
6388
6389# check for new externs in .h files.
6390 if ($realfile =~ /\.h$/ &&
6391 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6392 if (CHK("AVOID_EXTERNS",
6393 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6394 $fix) {
6395 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6396 }
6397 }
6398
6399# check for new externs in .c files.
6400 if ($realfile =~ /\.c$/ && defined $stat &&
6401 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6402 {
6403 my $function_name = $1;
6404 my $paren_space = $2;
6405
6406 my $s = $stat;
6407 if (defined $cond) {
6408 substr($s, 0, length($cond), '');
6409 }
Elyes Haouas26e0b942022-05-22 11:11:11 +02006410 if ($s =~ /^\s*;/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006411 {
6412 WARN("AVOID_EXTERNS",
6413 "externs should be avoided in .c files\n" . $herecurr);
6414 }
6415
6416 if ($paren_space =~ /\n/) {
6417 WARN("FUNCTION_ARGUMENTS",
6418 "arguments for function declarations should follow identifier\n" . $herecurr);
6419 }
6420
6421 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6422 $stat =~ /^.\s*extern\s+/)
6423 {
6424 WARN("AVOID_EXTERNS",
6425 "externs should be avoided in .c files\n" . $herecurr);
6426 }
6427
Martin Roth387dec82017-09-17 19:20:46 -06006428# check for function declarations that have arguments without identifier names
6429 if (defined $stat &&
Martin Roth60915b32018-08-10 21:04:05 -06006430 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
Martin Rothedd591d2017-03-14 10:16:29 -06006431 $1 ne "void") {
6432 my $args = trim($1);
6433 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6434 my $arg = trim($1);
6435 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6436 WARN("FUNCTION_ARGUMENTS",
6437 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6438 }
6439 }
6440 }
6441
Martin Roth387dec82017-09-17 19:20:46 -06006442# check for function definitions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006443 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006444 defined $stat &&
6445 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6446 $context_function = $1;
6447
6448# check for multiline function definition with misplaced open brace
6449 my $ok = 0;
6450 my $cnt = statement_rawlines($stat);
6451 my $herectx = $here . "\n";
6452 for (my $n = 0; $n < $cnt; $n++) {
6453 my $rl = raw_line($linenr, $n);
6454 $herectx .= $rl . "\n";
6455 $ok = 1 if ($rl =~ /^[ \+]\{/);
6456 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6457 last if $rl =~ /^[ \+].*\{/;
6458 }
6459 if (!$ok) {
6460 ERROR("OPEN_BRACE",
6461 "open brace '{' following function definitions go on the next line\n" . $herectx);
6462 }
6463 }
6464
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006465# checks for new __setup's
6466 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6467 my $name = $1;
6468
6469 if (!grep(/$name/, @setup_docs)) {
6470 CHK("UNDOCUMENTED_SETUP",
Martin Rothedd591d2017-03-14 10:16:29 -06006471 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006472 }
6473 }
6474
Elyes Haouasa7b0d382022-05-23 18:33:15 +02006475# check for pointless casting of alloc functions
6476 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006477 WARN("UNNECESSARY_CASTS",
6478 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6479 }
6480
6481# alloc style
6482# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006483 if ($perl_version_ok &&
Elyes Haouas26e0b942022-05-22 11:11:11 +02006484 $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 +01006485 CHK("ALLOC_SIZEOF_STRUCT",
6486 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6487 }
6488
6489# check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006490 if ($perl_version_ok &&
Martin Roth387dec82017-09-17 19:20:46 -06006491 defined $stat &&
6492 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006493 my $oldfunc = $3;
6494 my $a1 = $4;
6495 my $a2 = $10;
6496 my $newfunc = "kmalloc_array";
6497 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6498 my $r1 = $a1;
6499 my $r2 = $a2;
6500 if ($a1 =~ /^sizeof\s*\S/) {
6501 $r1 = $a2;
6502 $r2 = $a1;
6503 }
6504 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6505 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
Martin Roth387dec82017-09-17 19:20:46 -06006506 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006507 my $herectx = get_stat_here($linenr, $cnt, $here);
6508
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006509 if (WARN("ALLOC_WITH_MULTIPLY",
Martin Roth387dec82017-09-17 19:20:46 -06006510 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6511 $cnt == 1 &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006512 $fix) {
6513 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006514 }
6515 }
6516 }
6517
6518# check for krealloc arg reuse
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006519 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006520 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
6521 WARN("KREALLOC_ARG_REUSE",
6522 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6523 }
6524
6525# check for alloc argument mismatch
6526 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6527 WARN("ALLOC_ARRAY_ARGS",
6528 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6529 }
6530
6531# check for multiple semicolons
6532 if ($line =~ /;\s*;\s*$/) {
6533 if (WARN("ONE_SEMICOLON",
6534 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6535 $fix) {
6536 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6537 }
6538 }
6539
Martin Rothedd591d2017-03-14 10:16:29 -06006540# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6541 if ($realfile !~ m@^include/uapi/@ &&
6542 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006543 my $ull = "";
6544 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6545 if (CHK("BIT_MACRO",
6546 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6547 $fix) {
6548 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6549 }
6550 }
6551
Elyes Haouasf62a9892022-04-12 12:17:50 +02006552# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6553 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6554 WARN("IS_ENABLED_CONFIG",
6555 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6556 }
6557
6558# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6559 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6560 my $config = $1;
6561 if (WARN("PREFER_IS_ENABLED",
6562 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6563 $fix) {
6564 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006565 }
Elyes Haouasf62a9892022-04-12 12:17:50 +02006566 }
6567
6568# check for /* fallthrough */ like comment, prefer fallthrough;
6569 my @fallthroughs = (
6570 'fallthrough',
6571 '@fallthrough@',
6572 'lint -fallthrough[ \t]*',
6573 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6574 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6575 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6576 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6577 );
6578 if ($raw_comment ne '') {
6579 foreach my $ft (@fallthroughs) {
6580 if ($raw_comment =~ /$ft/) {
6581 my $msg_level = \&WARN;
6582 $msg_level = \&CHK if ($file);
6583 &{$msg_level}("PREFER_FALLTHROUGH",
6584 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6585 last;
6586 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006587 }
6588 }
6589
6590# check for switch/default statements without a break;
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006591 if ($perl_version_ok &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006592 defined $stat &&
6593 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006594 my $cnt = statement_rawlines($stat);
Martin Roth60915b32018-08-10 21:04:05 -06006595 my $herectx = get_stat_here($linenr, $cnt, $here);
6596
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006597 WARN("DEFAULT_NO_BREAK",
6598 "switch default: should use break\n" . $herectx);
6599 }
6600
6601# check for gcc specific __FUNCTION__
6602 if ($line =~ /\b__FUNCTION__\b/) {
6603 if (WARN("USE_FUNC",
6604 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6605 $fix) {
6606 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6607 }
6608 }
6609
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006610# check for uses of __DATE__, __TIME__, __TIMESTAMP__
6611 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6612 ERROR("DATE_TIME",
6613 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6614 }
6615
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006616# check for use of yield()
6617 if ($line =~ /\byield\s*\(\s*\)/) {
6618 WARN("YIELD",
6619 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6620 }
6621
6622# check for comparisons against true and false
6623 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6624 my $lead = $1;
6625 my $arg = $2;
6626 my $test = $3;
6627 my $otype = $4;
6628 my $trail = $5;
6629 my $op = "!";
6630
6631 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6632
6633 my $type = lc($otype);
6634 if ($type =~ /^(?:true|false)$/) {
6635 if (("$test" eq "==" && "$type" eq "true") ||
6636 ("$test" eq "!=" && "$type" eq "false")) {
6637 $op = "";
6638 }
6639
6640 CHK("BOOL_COMPARISON",
6641 "Using comparison to $otype is error prone\n" . $herecurr);
6642
6643## maybe suggesting a correct construct would better
6644## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6645
6646 }
6647 }
6648
Martin Roth60915b32018-08-10 21:04:05 -06006649# check for bool bitfields
6650 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6651 WARN("BOOL_BITFIELD",
6652 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6653 }
6654
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006655# check for semaphores initialized locked
6656 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6657 WARN("CONSIDER_COMPLETION",
6658 "consider using a completion\n" . $herecurr);
6659 }
6660
6661# recommend kstrto* over simple_strto* and strict_strto*
6662 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6663 WARN("CONSIDER_KSTRTO",
6664 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6665 }
6666
6667# check for __initcall(), use device_initcall() explicitly or more appropriate function please
6668 if ($line =~ /^.\s*__initcall\s*\(/) {
6669 WARN("USE_DEVICE_INITCALL",
6670 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6671 }
6672
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006673# check for various structs that are normally const (ops, kgdb, device_tree)
Martin Roth387dec82017-09-17 19:20:46 -06006674# and avoid what seem like struct definitions 'struct foo {'
Elyes Haouas43529c82022-04-12 13:19:50 +02006675 if (defined($const_structs) &&
6676 $line !~ /\bconst\b/ &&
Martin Roth387dec82017-09-17 19:20:46 -06006677 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006678 WARN("CONST_STRUCT",
Martin Roth387dec82017-09-17 19:20:46 -06006679 "struct $1 should normally be const\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006680 }
6681
6682# use of NR_CPUS is usually wrong
6683# ignore definitions of NR_CPUS and usage to define arrays as likely right
6684 if ($line =~ /\bNR_CPUS\b/ &&
6685 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6686 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6687 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6688 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6689 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6690 {
6691 WARN("NR_CPUS",
6692 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6693 }
6694
6695# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6696 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6697 ERROR("DEFINE_ARCH_HAS",
6698 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6699 }
6700
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006701# likely/unlikely comparisons similar to "(likely(foo) > 0)"
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006702 if ($perl_version_ok &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006703 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6704 WARN("LIKELY_MISUSE",
6705 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6706 }
6707
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006708# whine mightly about in_atomic
6709 if ($line =~ /\bin_atomic\s*\(/) {
6710 if ($realfile =~ m@^drivers/@) {
6711 ERROR("IN_ATOMIC",
6712 "do not use in_atomic in drivers\n" . $herecurr);
6713 } elsif ($realfile !~ m@^kernel/@) {
6714 WARN("IN_ATOMIC",
6715 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6716 }
6717 }
6718
Martin Rothedd591d2017-03-14 10:16:29 -06006719# check for mutex_trylock_recursive usage
6720 if ($line =~ /mutex_trylock_recursive/) {
6721 ERROR("LOCKING",
6722 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6723 }
6724
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006725# check for lockdep_set_novalidate_class
6726 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6727 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6728 if ($realfile !~ m@^kernel/lockdep@ &&
6729 $realfile !~ m@^include/linux/lockdep@ &&
6730 $realfile !~ m@^drivers/base/core@) {
6731 ERROR("LOCKDEP",
6732 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6733 }
6734 }
6735
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006736 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6737 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006738 WARN("EXPORTED_WORLD_WRITABLE",
6739 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6740 }
6741
Martin Roth60915b32018-08-10 21:04:05 -06006742# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6743# and whether or not function naming is typical and if
6744# DEVICE_ATTR permissions uses are unusual too
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006745 if ($perl_version_ok &&
Martin Roth60915b32018-08-10 21:04:05 -06006746 defined $stat &&
6747 $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*\)/) {
6748 my $var = $1;
6749 my $perms = $2;
6750 my $show = $3;
6751 my $store = $4;
6752 my $octal_perms = perms_to_octal($perms);
6753 if ($show =~ /^${var}_show$/ &&
6754 $store =~ /^${var}_store$/ &&
6755 $octal_perms eq "0644") {
6756 if (WARN("DEVICE_ATTR_RW",
6757 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6758 $fix) {
6759 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6760 }
6761 } elsif ($show =~ /^${var}_show$/ &&
6762 $store =~ /^NULL$/ &&
6763 $octal_perms eq "0444") {
6764 if (WARN("DEVICE_ATTR_RO",
6765 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6766 $fix) {
6767 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6768 }
6769 } elsif ($show =~ /^NULL$/ &&
6770 $store =~ /^${var}_store$/ &&
6771 $octal_perms eq "0200") {
6772 if (WARN("DEVICE_ATTR_WO",
6773 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6774 $fix) {
6775 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6776 }
6777 } elsif ($octal_perms eq "0644" ||
6778 $octal_perms eq "0444" ||
6779 $octal_perms eq "0200") {
6780 my $newshow = "$show";
6781 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6782 my $newstore = $store;
6783 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6784 my $rename = "";
6785 if ($show ne $newshow) {
6786 $rename .= " '$show' to '$newshow'";
6787 }
6788 if ($store ne $newstore) {
6789 $rename .= " '$store' to '$newstore'";
6790 }
6791 WARN("DEVICE_ATTR_FUNCTIONS",
6792 "Consider renaming function(s)$rename\n" . $herecurr);
6793 } else {
6794 WARN("DEVICE_ATTR_PERMS",
6795 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6796 }
6797 }
6798
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006799# Mode permission misuses where it seems decimal should be octal
6800# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
Martin Roth60915b32018-08-10 21:04:05 -06006801# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6802# specific definition of not visible in sysfs.
6803# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6804# use the default permissions
Elyes HAOUAS48cb78b2022-01-29 07:42:58 +01006805 if ($perl_version_ok &&
Martin Rothedd591d2017-03-14 10:16:29 -06006806 defined $stat &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006807 $line =~ /$mode_perms_search/) {
6808 foreach my $entry (@mode_permission_funcs) {
6809 my $func = $entry->[0];
6810 my $arg_pos = $entry->[1];
6811
Martin Rothedd591d2017-03-14 10:16:29 -06006812 my $lc = $stat =~ tr@\n@@;
6813 $lc = $lc + $linenr;
Martin Roth60915b32018-08-10 21:04:05 -06006814 my $stat_real = get_stat_real($linenr, $lc);
Martin Rothedd591d2017-03-14 10:16:29 -06006815
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006816 my $skip_args = "";
6817 if ($arg_pos > 1) {
6818 $arg_pos--;
6819 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6820 }
Martin Rothedd591d2017-03-14 10:16:29 -06006821 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6822 if ($stat =~ /$test/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006823 my $val = $1;
6824 $val = $6 if ($skip_args ne "");
Martin Roth60915b32018-08-10 21:04:05 -06006825 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6826 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6827 ($val =~ /^$Octal$/ && length($val) ne 4))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006828 ERROR("NON_OCTAL_PERMISSIONS",
Martin Rothedd591d2017-03-14 10:16:29 -06006829 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6830 }
6831 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006832 ERROR("EXPORTED_WORLD_WRITABLE",
Martin Rothedd591d2017-03-14 10:16:29 -06006833 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006834 }
6835 }
6836 }
6837 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006838
Martin Rothedd591d2017-03-14 10:16:29 -06006839# check for uses of S_<PERMS> that could be octal for readability
Martin Roth60915b32018-08-10 21:04:05 -06006840 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6841 my $oval = $1;
6842 my $octal = perms_to_octal($oval);
Martin Rothedd591d2017-03-14 10:16:29 -06006843 if (WARN("SYMBOLIC_PERMS",
6844 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6845 $fix) {
Martin Roth60915b32018-08-10 21:04:05 -06006846 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
Martin Rothedd591d2017-03-14 10:16:29 -06006847 }
6848 }
6849
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006850# validate content of MODULE_LICENSE against list from include/linux/module.h
6851 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6852 my $extracted_string = get_quoted_string($line, $rawline);
6853 my $valid_licenses = qr{
6854 GPL|
6855 GPL\ v2|
6856 GPL\ and\ additional\ rights|
6857 Dual\ BSD/GPL|
6858 Dual\ MIT/GPL|
6859 Dual\ MPL/GPL|
6860 Proprietary
6861 }x;
6862 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6863 WARN("MODULE_LICENSE",
6864 "unknown module license " . $extracted_string . "\n" . $herecurr);
6865 }
6866 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006867 }
6868
6869 # If we have no input at all, then there is nothing to report on
6870 # so just keep quiet.
6871 if ($#rawlines == -1) {
6872 exit(0);
6873 }
6874
6875 # In mailback mode only produce a report in the negative, for
6876 # things that appear to be patches.
6877 if ($mailback && ($clean == 1 || !$is_patch)) {
6878 exit(0);
6879 }
6880
Elyes HAOUAS919b0c72022-01-29 07:48:52 +01006881 # This is not a patch, and we are in 'no-patch' mode so
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006882 # just keep quiet.
6883 if (!$chk_patch && !$is_patch) {
6884 exit(0);
6885 }
6886
Martin Roth60915b32018-08-10 21:04:05 -06006887 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006888 ERROR("NOT_UNIFIED_DIFF",
6889 "Does not appear to be a unified-diff format patch\n");
6890 }
Martin Rothedd591d2017-03-14 10:16:29 -06006891 if ($is_patch && $has_commit_log && $chk_signoff && $signoff == 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006892 ERROR("MISSING_SIGN_OFF",
6893 "Missing Signed-off-by: line(s)\n");
6894 }
6895
6896 print report_dump();
6897 if ($summary && !($clean == 1 && $quiet == 1)) {
6898 print "$filename " if ($summary_file);
6899 print "total: $cnt_error errors, $cnt_warn warnings, " .
6900 (($check)? "$cnt_chk checks, " : "") .
6901 "$cnt_lines lines checked\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006902 }
6903
6904 if ($quiet == 0) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006905 # If there were any defects found and not already fixing them
6906 if (!$clean and !$fix) {
6907 print << "EOM"
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006908
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006909NOTE: For some of the reported defects, checkpatch may be able to
6910 mechanically convert to the typical style using --fix or --fix-inplace.
6911EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006912 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006913 # If there were whitespace errors which cleanpatch can fix
6914 # then suggest that.
6915 if ($rpt_cleaners) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006916 $rpt_cleaners = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006917 print << "EOM"
6918
6919NOTE: Whitespace errors detected.
6920 You may wish to use scripts/cleanpatch or scripts/cleanfile
6921EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006922 }
6923 }
6924
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006925 if ($clean == 0 && $fix &&
6926 ("@rawlines" ne "@fixed" ||
6927 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6928 my $newfile = $filename;
6929 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6930 my $linecount = 0;
6931 my $f;
6932
6933 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6934
6935 open($f, '>', $newfile)
6936 or die "$P: Can't open $newfile for write\n";
6937 foreach my $fixed_line (@fixed) {
6938 $linecount++;
6939 if ($file) {
6940 if ($linecount > 3) {
6941 $fixed_line =~ s/^\+//;
6942 print $f $fixed_line . "\n";
6943 }
6944 } else {
6945 print $f $fixed_line . "\n";
6946 }
6947 }
6948 close($f);
6949
6950 if (!$quiet) {
6951 print << "EOM";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006952
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006953Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6954
6955Do _NOT_ trust the results written to this file.
6956Do _NOT_ submit these changes without inspecting them for correctness.
6957
6958This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6959No warranties, expressed or implied...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006960EOM
6961 }
6962 }
6963
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006964 if ($quiet == 0) {
6965 print "\n";
6966 if ($clean == 1) {
6967 print "$vname has no obvious style problems and is ready for submission.\n";
6968 } else {
6969 print "$vname has style problems, please review.\n";
6970 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006971 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006972 return $clean;
6973}