blob: 82ec71e05d954cce4899814e7fc8bbd30124c05b [file] [log] [blame]
Kamil Rytarowskib7d5a9c2017-04-26 15:16:04 +02001#!/usr/bin/env perl
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002# (c) 2001, Dave Jones. (the file handling bit)
3# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6# Licensed under the terms of the GNU GPL License version 2
7
8use strict;
Kamil Rytarowskib7d5a9c2017-04-26 15:16:04 +02009use warnings;
Paolo Bonzini1db42692018-11-29 09:52:58 +010010use Term::ANSIColor qw(:constants);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000011
12my $P = $0;
13$P =~ s@.*/@@g;
14
Matheus Ferst72205282021-05-20 16:51:42 -030015our $SrcFile = qr{\.(?:(h|c)(\.inc)?|cpp|s|S|pl|py|sh)$};
Paolo Bonzini777d05b2017-10-04 16:35:53 +020016
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000017my $V = '0.31';
18
19use Getopt::Long qw(:config no_auto_abbrev);
20
21my $quiet = 0;
22my $tree = 1;
23my $chk_signoff = 1;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +010024my $chk_patch = undef;
25my $chk_branch = undef;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000026my $tst_only;
27my $emacs = 0;
28my $terse = 0;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +010029my $file = undef;
Paolo Bonzini1db42692018-11-29 09:52:58 +010030my $color = "auto";
Paolo Bonzini141de882016-08-09 17:47:44 +020031my $no_warnings = 0;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000032my $summary = 1;
33my $mailback = 0;
34my $summary_file = 0;
35my $root;
36my %debug;
37my $help = 0;
Zhao Liue072af12024-01-05 16:38:48 +080038my $codespell = 0;
39my $codespellfile = "/usr/share/codespell/dictionary.txt";
40my $user_codespellfile = "";
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000041
42sub help {
43 my ($exitcode) = @_;
44
45 print << "EOM";
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +010046Usage:
47
48 $P [OPTION]... [FILE]...
49 $P [OPTION]... [GIT-REV-LIST]
50
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000051Version: $V
52
53Options:
54 -q, --quiet quiet
Aleksandar Markovic143a7682020-06-20 15:32:07 +020055 --no-tree run without a qemu tree
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000056 --no-signoff do not check for 'Signed-off-by' line
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +010057 --patch treat FILE as patchfile
58 --branch treat args as GIT revision list
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000059 --emacs emacs compile window format
60 --terse one line per report
61 -f, --file treat FILE as regular source file
Paolo Bonzini141de882016-08-09 17:47:44 +020062 --strict fail if only warnings are found
Aleksandar Markovic143a7682020-06-20 15:32:07 +020063 --root=PATH PATH to the qemu tree root
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000064 --no-summary suppress the per-file summary
65 --mailback only produce a report in case of warnings/errors
66 --summary-file include the filename in summary
67 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
68 'values', 'possible', 'type', and 'attr' (default
69 is all off)
70 --test-only=WORD report only warnings/errors containing WORD
71 literally
Zhao Liue072af12024-01-05 16:38:48 +080072 --codespell Use the codespell dictionary for spelling/typos
73 (default: $codespellfile)
74 --codespellfile Use this codespell dictionary
Paolo Bonzini1db42692018-11-29 09:52:58 +010075 --color[=WHEN] Use colors 'always', 'never', or only when output
76 is a terminal ('auto'). Default is 'auto'.
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000077 -h, --help, --version display this help and exit
78
79When FILE is - read standard input.
80EOM
81
82 exit($exitcode);
83}
84
Paolo Bonzini1db42692018-11-29 09:52:58 +010085# Perl's Getopt::Long allows options to take optional arguments after a space.
86# Prevent --color by itself from consuming other arguments
87foreach (@ARGV) {
88 if ($_ eq "--color" || $_ eq "-color") {
89 $_ = "--color=$color";
90 }
91}
92
Blue Swirl1ec3f6f2011-01-20 20:54:26 +000093GetOptions(
Zhao Liue072af12024-01-05 16:38:48 +080094 'q|quiet+' => \$quiet,
95 'tree!' => \$tree,
96 'signoff!' => \$chk_signoff,
97 'patch!' => \$chk_patch,
98 'branch!' => \$chk_branch,
99 'emacs!' => \$emacs,
100 'terse!' => \$terse,
101 'f|file!' => \$file,
102 'strict!' => \$no_warnings,
103 'root=s' => \$root,
104 'summary!' => \$summary,
105 'mailback!' => \$mailback,
106 'summary-file!' => \$summary_file,
107 'debug=s' => \%debug,
108 'test-only=s' => \$tst_only,
109 'codespell!' => \$codespell,
110 'codespellfile=s' => \$user_codespellfile,
111 'color=s' => \$color,
112 'no-color' => sub { $color = 'never'; },
113 'h|help' => \$help,
114 'version' => \$help
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000115) or help(1);
116
Zhao Liue072af12024-01-05 16:38:48 +0800117if ($user_codespellfile) {
118 # Use the user provided codespell file unconditionally
119 $codespellfile = $user_codespellfile;
120} elsif (!(-f $codespellfile)) {
121 # If /usr/share/codespell/dictionary.txt is not present, try to find it
122 # under codespell's install directory: <codespell_root>/data/dictionary.txt
123 if (($codespell || $help) && which("python3") ne "") {
124 my $python_codespell_dict = << "EOF";
125
126import os.path as op
127import codespell_lib
128codespell_dir = op.dirname(codespell_lib.__file__)
129codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
130print(codespell_file, end='')
131EOF
132
133 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
134 $codespellfile = $codespell_dict if (-f $codespell_dict);
135 }
136}
137
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000138help(0) if ($help);
139
140my $exit = 0;
141
142if ($#ARGV < 0) {
143 print "$P: no input files\n";
144 exit(1);
145}
146
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100147if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
Paolo Bonzini777d05b2017-10-04 16:35:53 +0200148 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
149 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
150 $chk_patch = $chk_branch || $file ? 0 : 1;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100151} elsif (!defined $chk_branch && !defined $chk_patch) {
152 if ($file) {
153 $chk_branch = $chk_patch = 0;
154 } else {
Paolo Bonzini777d05b2017-10-04 16:35:53 +0200155 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100156 $chk_patch = $chk_branch ? 0 : 1;
157 }
158} elsif (!defined $chk_branch && !defined $file) {
159 if ($chk_patch) {
160 $chk_branch = $file = 0;
161 } else {
Paolo Bonzini777d05b2017-10-04 16:35:53 +0200162 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100163 $file = $chk_branch ? 0 : 1;
164 }
165} elsif (!defined $chk_patch && !defined $file) {
166 if ($chk_branch) {
167 $chk_patch = $file = 0;
168 } else {
Paolo Bonzini777d05b2017-10-04 16:35:53 +0200169 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
170 $chk_patch = $file ? 0 : 1;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100171 }
172} elsif (!defined $chk_branch) {
173 $chk_branch = $chk_patch || $file ? 0 : 1;
174} elsif (!defined $chk_patch) {
175 $chk_patch = $chk_branch || $file ? 0 : 1;
176} elsif (!defined $file) {
177 $file = $chk_patch || $chk_branch ? 0 : 1;
178}
179
180if (($chk_patch && $chk_branch) ||
181 ($chk_patch && $file) ||
182 ($chk_branch && $file)) {
183 die "Only one of --file, --branch, --patch is permitted\n";
184}
185if (!$chk_patch && !$chk_branch && !$file) {
186 die "One of --file, --branch, --patch is required\n";
187}
188
Paolo Bonzini1db42692018-11-29 09:52:58 +0100189if ($color =~ /^always$/i) {
190 $color = 1;
191} elsif ($color =~ /^never$/i) {
192 $color = 0;
193} elsif ($color =~ /^auto$/i) {
194 $color = (-t STDOUT);
195} else {
196 die "Invalid color mode: $color\n";
197}
198
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000199my $dbg_values = 0;
200my $dbg_possible = 0;
201my $dbg_type = 0;
202my $dbg_attr = 0;
Don Slutza99ac042012-09-02 19:22:35 -0400203my $dbg_adv_dcs = 0;
Don Slutz54243022012-09-02 19:22:36 -0400204my $dbg_adv_checking = 0;
Don Slutz69402a62012-09-02 19:22:37 -0400205my $dbg_adv_apw = 0;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000206for my $key (keys %debug) {
207 ## no critic
208 eval "\${dbg_$key} = '$debug{$key}';";
209 die "$@" if ($@);
210}
211
212my $rpt_cleaners = 0;
213
214if ($terse) {
215 $emacs = 1;
216 $quiet++;
217}
218
219if ($tree) {
220 if (defined $root) {
221 if (!top_of_kernel_tree($root)) {
222 die "$P: $root: --root does not point at a valid tree\n";
223 }
224 } else {
225 if (top_of_kernel_tree('.')) {
226 $root = '.';
227 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
228 top_of_kernel_tree($1)) {
229 $root = $1;
230 }
231 }
232
233 if (!defined $root) {
Aleksandar Markovic143a7682020-06-20 15:32:07 +0200234 print "Must be run from the top-level dir. of a qemu tree\n";
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000235 exit(2);
236 }
237}
238
239my $emitted_corrupt = 0;
240
241our $Ident = qr{
242 [A-Za-z_][A-Za-z\d_]*
243 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
244 }x;
245our $Storage = qr{extern|static|asmlinkage};
246our $Sparse = qr{
Paolo Bonzinif1e155b2015-08-16 23:01:19 +0200247 __force
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000248 }x;
249
250# Notes to $Attribute:
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000251our $Attribute = qr{
252 const|
Paolo Bonzini71c47b02015-08-16 23:15:46 +0200253 volatile|
Marc-André Lureau89057702022-04-20 17:26:02 +0400254 G_NORETURN|
Marc-André Lureauc0840172022-02-24 00:58:22 +0400255 G_GNUC_WARN_UNUSED_RESULT|
Marc-André Lureau887ce502022-02-24 00:58:22 +0400256 G_GNUC_NULL_TERMINATED|
Paolo Bonzini71c47b02015-08-16 23:15:46 +0200257 QEMU_PACKED|
Marc-André Lureau9edc6312022-02-20 20:39:25 +0400258 G_GNUC_PRINTF
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000259 }x;
260our $Modifier;
Paolo Bonzini71c47b02015-08-16 23:15:46 +0200261our $Inline = qr{inline};
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000262our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
263our $Lval = qr{$Ident(?:$Member)*};
264
265our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
266our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
267our $Compare = qr{<=|>=|==|!=|<|>};
268our $Operators = qr{
269 <=|>=|==|!=|
270 =>|->|<<|>>|<|>|!|~|
271 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
272 }x;
273
274our $NonptrType;
275our $Type;
276our $Declare;
277
Joe Perchesb37c4aa2018-04-30 13:46:47 +0100278our $NON_ASCII_UTF8 = qr{
279 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000280 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
281 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
282 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
283 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
284 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
285 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
286}x;
287
Joe Perchesb37c4aa2018-04-30 13:46:47 +0100288our $UTF8 = qr{
289 [\x09\x0A\x0D\x20-\x7E] # ASCII
290 | $NON_ASCII_UTF8
291}x;
292
Paolo Bonzini874acb62019-05-17 15:19:00 +0200293# some readers default to ISO-8859-1 when showing email source. detect
294# when UTF-8 is incorrectly interpreted as ISO-8859-1 and reencoded back.
295# False positives are possible but very unlikely.
296our $UTF8_MOJIBAKE = qr{
297 \xC3[\x82-\x9F] \xC2[\x80-\xBF] # c2-df 80-bf
298 | \xC3\xA0 \xC2[\xA0-\xBF] \xC2[\x80-\xBF] # e0 a0-bf 80-bf
299 | \xC3[\xA1-\xAC\xAE\xAF] (?: \xC2[\x80-\xBF]){2} # e1-ec/ee/ef 80-bf 80-bf
300 | \xC3\xAD \xC2[\x80-\x9F] \xC2[\x80-\xBF] # ed 80-9f 80-bf
301 | \xC3\xB0 \xC2[\x90-\xBF] (?: \xC2[\x80-\xBF]){2} # f0 90-bf 80-bf 80-bf
302 | \xC3[\xB1-\xB3] (?: \xC2[\x80-\xBF]){3} # f1-f3 80-bf 80-bf 80-bf
303 | \xC3\xB4 \xC2[\x80-\x8F] (?: \xC2[\x80-\xBF]){2} # f4 80-b8 80-bf 80-bf
304}x;
305
Paolo Bonzinia6859de2014-06-10 10:52:02 +0200306# There are still some false positives, but this catches most
307# common cases.
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000308our $typeTypedefs = qr{(?x:
Philippe Mathieu-Daudé5fa96ca2018-06-25 09:41:56 -0300309 (?![KMGTPE]iB) # IEC binary prefix (do not match)
Paolo Bonzinia6859de2014-06-10 10:52:02 +0200310 [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]* # camelcase
311 | [A-Z][A-Z\d_]*AIOCB # all uppercase
312 | [A-Z][A-Z\d_]*CPU # all uppercase
313 | QEMUBH # all uppercase
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000314)};
315
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000316our @typeList = (
317 qr{void},
318 qr{(?:unsigned\s+)?char},
319 qr{(?:unsigned\s+)?short},
320 qr{(?:unsigned\s+)?int},
321 qr{(?:unsigned\s+)?long},
322 qr{(?:unsigned\s+)?long\s+int},
323 qr{(?:unsigned\s+)?long\s+long},
324 qr{(?:unsigned\s+)?long\s+long\s+int},
325 qr{unsigned},
326 qr{float},
327 qr{double},
328 qr{bool},
329 qr{struct\s+$Ident},
330 qr{union\s+$Ident},
331 qr{enum\s+$Ident},
332 qr{${Ident}_t},
333 qr{${Ident}_handler},
334 qr{${Ident}_handler_fn},
Cédric Le Goaterf0707d22016-04-01 11:40:06 +0200335 qr{target_(?:u)?long},
Greg Kurz825bfa02017-09-14 11:12:07 +0200336 qr{hwaddr},
Peter Xu82870f32018-04-25 15:01:03 +0800337 # external libraries
Paul Durrant8d0f08e2018-05-22 11:42:50 -0700338 qr{xen\w+_handle},
Peter Xu82870f32018-04-25 15:01:03 +0800339 # Glib definitions
340 qr{gchar},
341 qr{gshort},
342 qr{glong},
343 qr{gint},
344 qr{gboolean},
345 qr{guchar},
346 qr{gushort},
347 qr{gulong},
348 qr{guint},
349 qr{gfloat},
350 qr{gdouble},
351 qr{gpointer},
352 qr{gconstpointer},
353 qr{gint8},
354 qr{guint8},
355 qr{gint16},
356 qr{guint16},
357 qr{gint32},
358 qr{guint32},
359 qr{gint64},
360 qr{guint64},
361 qr{gsize},
362 qr{gssize},
363 qr{goffset},
364 qr{gintptr},
365 qr{guintptr},
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000366);
Paolo Bonzinif1e155b2015-08-16 23:01:19 +0200367
Zhao Liue072af12024-01-05 16:38:48 +0800368# Load common spelling mistakes and build regular expression list.
369my $misspellings;
370my %spelling_fix;
371
372if ($codespell) {
373 if (open(my $spelling, '<', $codespellfile)) {
374 while (<$spelling>) {
375 my $line = $_;
376
377 $line =~ s/\s*\n?$//g;
378 $line =~ s/^\s*//g;
379
380 next if ($line =~ m/^\s*#/);
381 next if ($line =~ m/^\s*$/);
382 next if ($line =~ m/, disabled/i);
383
384 $line =~ s/,.*$//;
385
386 my ($suspect, $fix) = split(/->/, $line);
387
388 $spelling_fix{$suspect} = $fix;
389 }
390 close($spelling);
391 } else {
392 warn "No codespell typos will be found - file '$codespellfile': $!\n";
393 }
394}
395
396$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
397
Paolo Bonzinif1e155b2015-08-16 23:01:19 +0200398# This can be modified by sub possible. Since it can be empty, be careful
399# about regexes that always match, because they can cause infinite loops.
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000400our @modifierList = (
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000401);
402
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000403sub build_types {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000404 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
Paolo Bonzinif1e155b2015-08-16 23:01:19 +0200405 if (@modifierList > 0) {
406 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
407 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
408 } else {
409 $Modifier = qr{(?:$Attribute|$Sparse)};
410 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000411 $NonptrType = qr{
412 (?:$Modifier\s+|const\s+)*
413 (?:
414 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
415 (?:$typeTypedefs\b)|
416 (?:${all}\b)
417 )
418 (?:\s+$Modifier|\s+const)*
419 }x;
420 $Type = qr{
421 $NonptrType
422 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
423 (?:\s+$Inline|\s+$Modifier)*
424 }x;
425 $Declare = qr{(?:$Storage\s+)?$Type};
426}
427build_types();
428
429$chk_signoff = 0 if ($file);
430
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000431my @rawlines = ();
432my @lines = ();
433my $vname;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100434if ($chk_branch) {
435 my @patches;
Paolo Bonzinic182b612018-11-29 09:35:47 +0100436 my %git_commits = ();
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100437 my $HASH;
Philippe Mathieu-Daudéaf692fd2024-04-02 13:59:58 +0200438 open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--no-mailmap", "--format=%H %s", $ARGV[0]) ||
439 die "$P: git log --reverse --no-merges --no-mailmap --format='%H %s' $ARGV[0] failed - $!\n";
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100440
Paolo Bonzinic182b612018-11-29 09:35:47 +0100441 for my $line (<$HASH>) {
442 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
443 next if (!defined($1) || !defined($2));
444 my $sha1 = $1;
445 my $subject = $2;
446 push(@patches, $sha1);
447 $git_commits{$sha1} = $subject;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000448 }
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100449
450 close $HASH;
451
Daniel P. Berrangé2d4274d2020-10-21 17:31:35 +0100452 die "$P: no revisions returned for revlist '$ARGV[0]'\n"
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100453 unless @patches;
454
Paolo Bonzinic182b612018-11-29 09:35:47 +0100455 my $i = 1;
456 my $num_patches = @patches;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100457 for my $hash (@patches) {
458 my $FILE;
Alex Bennée66cf7012021-06-23 11:27:44 +0100459 open($FILE, '-|', "git",
460 "-c", "diff.renamelimit=0",
461 "-c", "diff.renames=True",
462 "-c", "diff.algorithm=histogram",
Philippe Mathieu-Daudéaf692fd2024-04-02 13:59:58 +0200463 "show", "--no-mailmap",
Alex Bennée66cf7012021-06-23 11:27:44 +0100464 "--patch-with-stat", $hash) ||
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100465 die "$P: git show $hash - $!\n";
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100466 while (<$FILE>) {
467 chomp;
468 push(@rawlines, $_);
469 }
470 close($FILE);
Paolo Bonzinic182b612018-11-29 09:35:47 +0100471 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
472 if ($num_patches > 1 && $quiet == 0) {
Paolo Bonzini1db42692018-11-29 09:52:58 +0100473 my $prefix = "$i/$num_patches";
474 $prefix = BLUE . BOLD . $prefix . RESET if $color;
475 print "$prefix Checking commit $vname\n";
Paolo Bonzinic182b612018-11-29 09:35:47 +0100476 $vname = "Patch $i/$num_patches";
477 } else {
478 $vname = "Commit " . $vname;
479 }
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100480 if (!process($hash)) {
481 $exit = 1;
Paolo Bonzinic182b612018-11-29 09:35:47 +0100482 print "\n" if ($num_patches > 1 && $quiet == 0);
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100483 }
484 @rawlines = ();
485 @lines = ();
Paolo Bonzinic182b612018-11-29 09:35:47 +0100486 $i++;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000487 }
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100488} else {
489 for my $filename (@ARGV) {
490 my $FILE;
491 if ($file) {
492 open($FILE, '-|', "diff -u /dev/null $filename") ||
493 die "$P: $filename: diff failed - $!\n";
494 } elsif ($filename eq '-') {
495 open($FILE, '<&STDIN');
496 } else {
497 open($FILE, '<', "$filename") ||
498 die "$P: $filename: open failed - $!\n";
499 }
500 if ($filename eq '-') {
501 $vname = 'Your patch';
502 } else {
503 $vname = $filename;
504 }
Paolo Bonzinic182b612018-11-29 09:35:47 +0100505 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
Daniel P. Berrange8e1fe172017-09-13 10:10:00 +0100506 while (<$FILE>) {
507 chomp;
508 push(@rawlines, $_);
509 }
510 close($FILE);
511 if (!process($filename)) {
512 $exit = 1;
513 }
514 @rawlines = ();
515 @lines = ();
516 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000517}
518
519exit($exit);
520
521sub top_of_kernel_tree {
522 my ($root) = @_;
523
524 my @tree_check = (
Blue Swirlb6469682011-01-20 20:58:56 +0000525 "COPYING", "MAINTAINERS", "Makefile",
Daniel P. Berrangé336a7452019-08-23 17:09:24 +0100526 "README.rst", "docs", "VERSION",
Philippe Mathieu-Daudé8d7f2e72023-10-04 11:06:28 +0200527 "linux-user", "system"
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000528 );
529
530 foreach my $check (@tree_check) {
531 if (! -e $root . '/' . $check) {
532 return 0;
533 }
534 }
535 return 1;
536}
537
Zhao Liue072af12024-01-05 16:38:48 +0800538sub which {
539 my ($bin) = @_;
540
541 foreach my $path (split(/:/, $ENV{PATH})) {
542 if (-e "$path/$bin") {
543 return "$path/$bin";
544 }
545 }
546
547 return "";
548}
549
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000550sub expand_tabs {
551 my ($str) = @_;
552
553 my $res = '';
554 my $n = 0;
555 for my $c (split(//, $str)) {
556 if ($c eq "\t") {
557 $res .= ' ';
558 $n++;
559 for (; ($n % 8) != 0; $n++) {
560 $res .= ' ';
561 }
562 next;
563 }
564 $res .= $c;
565 $n++;
566 }
567
568 return $res;
569}
570sub copy_spacing {
571 (my $res = shift) =~ tr/\t/ /c;
572 return $res;
573}
574
575sub line_stats {
576 my ($line) = @_;
577
578 # Drop the diff line leader and expand tabs
579 $line =~ s/^.//;
580 $line = expand_tabs($line);
581
582 # Pick the indent from the front of the line.
583 my ($white) = ($line =~ /^(\s*)/);
584
585 return (length($line), length($white));
586}
587
588my $sanitise_quote = '';
589
590sub sanitise_line_reset {
591 my ($in_comment) = @_;
592
593 if ($in_comment) {
594 $sanitise_quote = '*/';
595 } else {
596 $sanitise_quote = '';
597 }
598}
599sub sanitise_line {
600 my ($line) = @_;
601
602 my $res = '';
603 my $l = '';
604
605 my $qlen = 0;
606 my $off = 0;
607 my $c;
608
609 # Always copy over the diff marker.
610 $res = substr($line, 0, 1);
611
612 for ($off = 1; $off < length($line); $off++) {
613 $c = substr($line, $off, 1);
614
Stefan Weilcb8d4c82016-03-23 15:59:57 +0100615 # Comments we are wacking completely including the begin
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000616 # and end, all to $;.
617 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
618 $sanitise_quote = '*/';
619
620 substr($res, $off, 2, "$;$;");
621 $off++;
622 next;
623 }
624 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
625 $sanitise_quote = '';
626 substr($res, $off, 2, "$;$;");
627 $off++;
628 next;
629 }
630 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
631 $sanitise_quote = '//';
632
633 substr($res, $off, 2, $sanitise_quote);
634 $off++;
635 next;
636 }
637
638 # A \ in a string means ignore the next character.
639 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
640 $c eq "\\") {
641 substr($res, $off, 2, 'XX');
642 $off++;
643 next;
644 }
645 # Regular quotes.
646 if ($c eq "'" || $c eq '"') {
647 if ($sanitise_quote eq '') {
648 $sanitise_quote = $c;
649
650 substr($res, $off, 1, $c);
651 next;
652 } elsif ($sanitise_quote eq $c) {
653 $sanitise_quote = '';
654 }
655 }
656
657 #print "c<$c> SQ<$sanitise_quote>\n";
658 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
659 substr($res, $off, 1, $;);
660 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
661 substr($res, $off, 1, $;);
662 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
663 substr($res, $off, 1, 'X');
664 } else {
665 substr($res, $off, 1, $c);
666 }
667 }
668
669 if ($sanitise_quote eq '//') {
670 $sanitise_quote = '';
671 }
672
673 # The pathname on a #include may be surrounded by '<' and '>'.
674 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
675 my $clean = 'X' x length($1);
676 $res =~ s@\<.*\>@<$clean>@;
677
678 # The whole of a #error is a string.
679 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
680 my $clean = 'X' x length($1);
681 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
682 }
683
684 return $res;
685}
686
687sub ctx_statement_block {
688 my ($linenr, $remain, $off) = @_;
689 my $line = $linenr - 1;
690 my $blk = '';
691 my $soff = $off;
692 my $coff = $off - 1;
693 my $coff_set = 0;
694
695 my $loff = 0;
696
697 my $type = '';
698 my $level = 0;
699 my @stack = ();
700 my $p;
701 my $c;
702 my $len = 0;
703
704 my $remainder;
705 while (1) {
706 @stack = (['', 0]) if ($#stack == -1);
707
708 #warn "CSB: blk<$blk> remain<$remain>\n";
709 # If we are about to drop off the end, pull in more
710 # context.
711 if ($off >= $len) {
712 for (; $remain > 0; $line++) {
713 last if (!defined $lines[$line]);
714 next if ($lines[$line] =~ /^-/);
715 $remain--;
716 $loff = $len;
717 $blk .= $lines[$line] . "\n";
718 $len = length($blk);
719 $line++;
720 last;
721 }
722 # Bail if there is no further context.
723 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
724 if ($off >= $len) {
725 last;
726 }
727 }
728 $p = $c;
729 $c = substr($blk, $off, 1);
730 $remainder = substr($blk, $off);
731
732 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
733
734 # Handle nested #if/#else.
735 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
736 push(@stack, [ $type, $level ]);
737 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
738 ($type, $level) = @{$stack[$#stack - 1]};
739 } elsif ($remainder =~ /^#\s*endif\b/) {
740 ($type, $level) = @{pop(@stack)};
741 }
742
743 # Statement ends at the ';' or a close '}' at the
744 # outermost level.
745 if ($level == 0 && $c eq ';') {
746 last;
747 }
748
749 # An else is really a conditional as long as its not else if
750 if ($level == 0 && $coff_set == 0 &&
751 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
752 $remainder =~ /^(else)(?:\s|{)/ &&
753 $remainder !~ /^else\s+if\b/) {
754 $coff = $off + length($1) - 1;
755 $coff_set = 1;
756 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
757 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
758 }
759
760 if (($type eq '' || $type eq '(') && $c eq '(') {
761 $level++;
762 $type = '(';
763 }
764 if ($type eq '(' && $c eq ')') {
765 $level--;
766 $type = ($level != 0)? '(' : '';
767
768 if ($level == 0 && $coff < $soff) {
769 $coff = $off;
770 $coff_set = 1;
771 #warn "CSB: mark coff<$coff>\n";
772 }
773 }
774 if (($type eq '' || $type eq '{') && $c eq '{') {
775 $level++;
776 $type = '{';
777 }
778 if ($type eq '{' && $c eq '}') {
779 $level--;
780 $type = ($level != 0)? '{' : '';
781
782 if ($level == 0) {
783 if (substr($blk, $off + 1, 1) eq ';') {
784 $off++;
785 }
786 last;
787 }
788 }
789 $off++;
790 }
791 # We are truly at the end, so shuffle to the next line.
792 if ($off == $len) {
793 $loff = $len + 1;
794 $line++;
795 $remain--;
796 }
797
798 my $statement = substr($blk, $soff, $off - $soff + 1);
799 my $condition = substr($blk, $soff, $coff - $soff + 1);
800
801 #warn "STATEMENT<$statement>\n";
802 #warn "CONDITION<$condition>\n";
803
804 #print "coff<$coff> soff<$off> loff<$loff>\n";
805
806 return ($statement, $condition,
807 $line, $remain + 1, $off - $loff + 1, $level);
808}
809
810sub statement_lines {
811 my ($stmt) = @_;
812
813 # Strip the diff line prefixes and rip blank lines at start and end.
814 $stmt =~ s/(^|\n)./$1/g;
815 $stmt =~ s/^\s*//;
816 $stmt =~ s/\s*$//;
817
818 my @stmt_lines = ($stmt =~ /\n/g);
819
820 return $#stmt_lines + 2;
821}
822
823sub statement_rawlines {
824 my ($stmt) = @_;
825
826 my @stmt_lines = ($stmt =~ /\n/g);
827
828 return $#stmt_lines + 2;
829}
830
831sub statement_block_size {
832 my ($stmt) = @_;
833
834 $stmt =~ s/(^|\n)./$1/g;
Fam Zheng04f25622015-09-11 19:07:36 +0800835 $stmt =~ s/^\s*\{//;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +0000836 $stmt =~ s/}\s*$//;
837 $stmt =~ s/^\s*//;
838 $stmt =~ s/\s*$//;
839
840 my @stmt_lines = ($stmt =~ /\n/g);
841 my @stmt_statements = ($stmt =~ /;/g);
842
843 my $stmt_lines = $#stmt_lines + 2;
844 my $stmt_statements = $#stmt_statements + 1;
845
846 if ($stmt_lines > $stmt_statements) {
847 return $stmt_lines;
848 } else {
849 return $stmt_statements;
850 }
851}
852
853sub ctx_statement_full {
854 my ($linenr, $remain, $off) = @_;
855 my ($statement, $condition, $level);
856
857 my (@chunks);
858
859 # Grab the first conditional/block pair.
860 ($statement, $condition, $linenr, $remain, $off, $level) =
861 ctx_statement_block($linenr, $remain, $off);
862 #print "F: c<$condition> s<$statement> remain<$remain>\n";
863 push(@chunks, [ $condition, $statement ]);
864 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
865 return ($level, $linenr, @chunks);
866 }
867
868 # Pull in the following conditional/block pairs and see if they
869 # could continue the statement.
870 for (;;) {
871 ($statement, $condition, $linenr, $remain, $off, $level) =
872 ctx_statement_block($linenr, $remain, $off);
873 #print "C: c<$condition> s<$statement> remain<$remain>\n";
874 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
875 #print "C: push\n";
876 push(@chunks, [ $condition, $statement ]);
877 }
878
879 return ($level, $linenr, @chunks);
880}
881
882sub ctx_block_get {
883 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
884 my $line;
885 my $start = $linenr - 1;
886 my $blk = '';
887 my @o;
888 my @c;
889 my @res = ();
890
891 my $level = 0;
892 my @stack = ($level);
893 for ($line = $start; $remain > 0; $line++) {
894 next if ($rawlines[$line] =~ /^-/);
895 $remain--;
896
897 $blk .= $rawlines[$line];
898
899 # Handle nested #if/#else.
900 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
901 push(@stack, $level);
902 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
903 $level = $stack[$#stack - 1];
904 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
905 $level = pop(@stack);
906 }
907
908 foreach my $c (split(//, $lines[$line])) {
909 ##print "C<$c>L<$level><$open$close>O<$off>\n";
910 if ($off > 0) {
911 $off--;
912 next;
913 }
914
915 if ($c eq $close && $level > 0) {
916 $level--;
917 last if ($level == 0);
918 } elsif ($c eq $open) {
919 $level++;
920 }
921 }
922
923 if (!$outer || $level <= 1) {
924 push(@res, $rawlines[$line]);
925 }
926
927 last if ($level == 0);
928 }
929
930 return ($level, @res);
931}
932sub ctx_block_outer {
933 my ($linenr, $remain) = @_;
934
935 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
936 return @r;
937}
938sub ctx_block {
939 my ($linenr, $remain) = @_;
940
941 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
942 return @r;
943}
944sub ctx_statement {
945 my ($linenr, $remain, $off) = @_;
946
947 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
948 return @r;
949}
950sub ctx_block_level {
951 my ($linenr, $remain) = @_;
952
953 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
954}
955sub ctx_statement_level {
956 my ($linenr, $remain, $off) = @_;
957
958 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
959}
960
961sub ctx_locate_comment {
962 my ($first_line, $end_line) = @_;
963
964 # Catch a comment on the end of the line itself.
965 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
966 return $current_comment if (defined $current_comment);
967
968 # Look through the context and try and figure out if there is a
969 # comment.
970 my $in_comment = 0;
971 $current_comment = '';
972 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
973 my $line = $rawlines[$linenr - 1];
974 #warn " $line\n";
975 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
976 $in_comment = 1;
977 }
978 if ($line =~ m@/\*@) {
979 $in_comment = 1;
980 }
981 if (!$in_comment && $current_comment ne '') {
982 $current_comment = '';
983 }
984 $current_comment .= $line . "\n" if ($in_comment);
985 if ($line =~ m@\*/@) {
986 $in_comment = 0;
987 }
988 }
989
990 chomp($current_comment);
991 return($current_comment);
992}
993sub ctx_has_comment {
994 my ($first_line, $end_line) = @_;
995 my $cmt = ctx_locate_comment($first_line, $end_line);
996
997 ##print "LINE: $rawlines[$end_line - 1 ]\n";
998 ##print "CMMT: $cmt\n";
999
1000 return ($cmt ne '');
1001}
1002
1003sub raw_line {
1004 my ($linenr, $cnt) = @_;
1005
1006 my $offset = $linenr - 1;
1007 $cnt++;
1008
1009 my $line;
1010 while ($cnt) {
1011 $line = $rawlines[$offset++];
1012 next if (defined($line) && $line =~ /^-/);
1013 $cnt--;
1014 }
1015
1016 return $line;
1017}
1018
1019sub cat_vet {
1020 my ($vet) = @_;
1021 my ($res, $coded);
1022
1023 $res = '';
1024 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1025 $res .= $1;
1026 if ($2 ne '') {
1027 $coded = sprintf("^%c", unpack('C', $2) + 64);
1028 $res .= $coded;
1029 }
1030 }
1031 $res =~ s/$/\$/;
1032
1033 return $res;
1034}
1035
1036my $av_preprocessor = 0;
1037my $av_pending;
1038my @av_paren_type;
1039my $av_pend_colon;
1040
1041sub annotate_reset {
1042 $av_preprocessor = 0;
1043 $av_pending = '_';
1044 @av_paren_type = ('E');
1045 $av_pend_colon = 'O';
1046}
1047
1048sub annotate_values {
1049 my ($stream, $type) = @_;
1050
1051 my $res;
1052 my $var = '_' x length($stream);
1053 my $cur = $stream;
1054
1055 print "$stream\n" if ($dbg_values > 1);
1056
1057 while (length($cur)) {
1058 @av_paren_type = ('E') if ($#av_paren_type < 0);
1059 print " <" . join('', @av_paren_type) .
1060 "> <$type> <$av_pending>" if ($dbg_values > 1);
1061 if ($cur =~ /^(\s+)/o) {
1062 print "WS($1)\n" if ($dbg_values > 1);
1063 if ($1 =~ /\n/ && $av_preprocessor) {
1064 $type = pop(@av_paren_type);
1065 $av_preprocessor = 0;
1066 }
1067
Florian Mickler61669f92011-11-25 10:24:16 +01001068 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001069 print "CAST($1)\n" if ($dbg_values > 1);
1070 push(@av_paren_type, $type);
1071 $type = 'C';
1072
1073 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1074 print "DECLARE($1)\n" if ($dbg_values > 1);
1075 $type = 'T';
1076
1077 } elsif ($cur =~ /^($Modifier)\s*/) {
1078 print "MODIFIER($1)\n" if ($dbg_values > 1);
1079 $type = 'T';
1080
1081 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1082 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1083 $av_preprocessor = 1;
1084 push(@av_paren_type, $type);
1085 if ($2 ne '') {
1086 $av_pending = 'N';
1087 }
1088 $type = 'E';
1089
1090 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1091 print "UNDEF($1)\n" if ($dbg_values > 1);
1092 $av_preprocessor = 1;
1093 push(@av_paren_type, $type);
1094
1095 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1096 print "PRE_START($1)\n" if ($dbg_values > 1);
1097 $av_preprocessor = 1;
1098
1099 push(@av_paren_type, $type);
1100 push(@av_paren_type, $type);
1101 $type = 'E';
1102
1103 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1104 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1105 $av_preprocessor = 1;
1106
1107 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1108
1109 $type = 'E';
1110
1111 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1112 print "PRE_END($1)\n" if ($dbg_values > 1);
1113
1114 $av_preprocessor = 1;
1115
1116 # Assume all arms of the conditional end as this
1117 # one does, and continue as if the #endif was not here.
1118 pop(@av_paren_type);
1119 push(@av_paren_type, $type);
1120 $type = 'E';
1121
1122 } elsif ($cur =~ /^(\\\n)/o) {
1123 print "PRECONT($1)\n" if ($dbg_values > 1);
1124
1125 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1126 print "ATTR($1)\n" if ($dbg_values > 1);
1127 $av_pending = $type;
1128 $type = 'N';
1129
1130 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1131 print "SIZEOF($1)\n" if ($dbg_values > 1);
1132 if (defined $2) {
1133 $av_pending = 'V';
1134 }
1135 $type = 'N';
1136
1137 } elsif ($cur =~ /^(if|while|for)\b/o) {
1138 print "COND($1)\n" if ($dbg_values > 1);
1139 $av_pending = 'E';
1140 $type = 'N';
1141
1142 } elsif ($cur =~/^(case)/o) {
1143 print "CASE($1)\n" if ($dbg_values > 1);
1144 $av_pend_colon = 'C';
1145 $type = 'N';
1146
1147 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1148 print "KEYWORD($1)\n" if ($dbg_values > 1);
1149 $type = 'N';
1150
1151 } elsif ($cur =~ /^(\()/o) {
1152 print "PAREN('$1')\n" if ($dbg_values > 1);
1153 push(@av_paren_type, $av_pending);
1154 $av_pending = '_';
1155 $type = 'N';
1156
1157 } elsif ($cur =~ /^(\))/o) {
1158 my $new_type = pop(@av_paren_type);
1159 if ($new_type ne '_') {
1160 $type = $new_type;
1161 print "PAREN('$1') -> $type\n"
1162 if ($dbg_values > 1);
1163 } else {
1164 print "PAREN('$1')\n" if ($dbg_values > 1);
1165 }
1166
1167 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1168 print "FUNC($1)\n" if ($dbg_values > 1);
1169 $type = 'V';
1170 $av_pending = 'V';
1171
1172 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1173 if (defined $2 && $type eq 'C' || $type eq 'T') {
1174 $av_pend_colon = 'B';
1175 } elsif ($type eq 'E') {
1176 $av_pend_colon = 'L';
1177 }
1178 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1179 $type = 'V';
1180
1181 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1182 print "IDENT($1)\n" if ($dbg_values > 1);
1183 $type = 'V';
1184
1185 } elsif ($cur =~ /^($Assignment)/o) {
1186 print "ASSIGN($1)\n" if ($dbg_values > 1);
1187 $type = 'N';
1188
1189 } elsif ($cur =~/^(;|{|})/) {
1190 print "END($1)\n" if ($dbg_values > 1);
1191 $type = 'E';
1192 $av_pend_colon = 'O';
1193
1194 } elsif ($cur =~/^(,)/) {
1195 print "COMMA($1)\n" if ($dbg_values > 1);
1196 $type = 'C';
1197
1198 } elsif ($cur =~ /^(\?)/o) {
1199 print "QUESTION($1)\n" if ($dbg_values > 1);
1200 $type = 'N';
1201
1202 } elsif ($cur =~ /^(:)/o) {
1203 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1204
1205 substr($var, length($res), 1, $av_pend_colon);
1206 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1207 $type = 'E';
1208 } else {
1209 $type = 'N';
1210 }
1211 $av_pend_colon = 'O';
1212
1213 } elsif ($cur =~ /^(\[)/o) {
1214 print "CLOSE($1)\n" if ($dbg_values > 1);
1215 $type = 'N';
1216
1217 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1218 my $variant;
1219
1220 print "OPV($1)\n" if ($dbg_values > 1);
1221 if ($type eq 'V') {
1222 $variant = 'B';
1223 } else {
1224 $variant = 'U';
1225 }
1226
1227 substr($var, length($res), 1, $variant);
1228 $type = 'N';
1229
1230 } elsif ($cur =~ /^($Operators)/o) {
1231 print "OP($1)\n" if ($dbg_values > 1);
1232 if ($1 ne '++' && $1 ne '--') {
1233 $type = 'N';
1234 }
1235
1236 } elsif ($cur =~ /(^.)/o) {
1237 print "C($1)\n" if ($dbg_values > 1);
1238 }
1239 if (defined $1) {
1240 $cur = substr($cur, length($1));
1241 $res .= $type x length($1);
1242 }
1243 }
1244
1245 return ($res, $var);
1246}
1247
1248sub possible {
1249 my ($possible, $line) = @_;
1250 my $notPermitted = qr{(?:
1251 ^(?:
1252 $Modifier|
1253 $Storage|
1254 $Type|
1255 DEFINE_\S+
1256 )$|
1257 ^(?:
1258 goto|
1259 return|
1260 case|
1261 else|
1262 asm|__asm__|
Paolo Bonzinie20122f2018-07-04 18:05:43 +02001263 do
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001264 )(?:\s|$)|
Paolo Bonzinie20122f2018-07-04 18:05:43 +02001265 ^(?:typedef|struct|enum)\b|
1266 ^\#
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001267 )}x;
1268 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1269 if ($possible !~ $notPermitted) {
1270 # Check for modifiers.
1271 $possible =~ s/\s*$Storage\s*//g;
1272 $possible =~ s/\s*$Sparse\s*//g;
1273 if ($possible =~ /^\s*$/) {
1274
1275 } elsif ($possible =~ /\s/) {
Paolo Bonzinie20122f2018-07-04 18:05:43 +02001276 $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001277 for my $modifier (split(' ', $possible)) {
1278 if ($modifier !~ $notPermitted) {
1279 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1280 push(@modifierList, $modifier);
1281 }
1282 }
1283
1284 } else {
1285 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1286 push(@typeList, $possible);
1287 }
1288 build_types();
1289 } else {
1290 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1291 }
1292}
1293
1294my $prefix = '';
1295
1296sub report {
Paolo Bonzini1db42692018-11-29 09:52:58 +01001297 my ($level, $msg) = @_;
1298 if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001299 return 0;
1300 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001301
Paolo Bonzini1db42692018-11-29 09:52:58 +01001302 my $output = '';
1303 $output .= BOLD if $color;
1304 $output .= $prefix;
1305 $output .= RED if $color && $level eq 'ERROR';
1306 $output .= MAGENTA if $color && $level eq 'WARNING';
1307 $output .= $level . ':';
1308 $output .= RESET if $color;
1309 $output .= ' ' . $msg . "\n";
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001310
Paolo Bonzini1db42692018-11-29 09:52:58 +01001311 $output = (split('\n', $output))[0] . "\n" if ($terse);
1312
1313 push(our @report, $output);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001314
1315 return 1;
1316}
1317sub report_dump {
1318 our @report;
1319}
1320sub ERROR {
Paolo Bonzini1db42692018-11-29 09:52:58 +01001321 if (report("ERROR", $_[0])) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001322 our $clean = 0;
1323 our $cnt_error++;
1324 }
1325}
1326sub WARN {
Paolo Bonzini1db42692018-11-29 09:52:58 +01001327 if (report("WARNING", $_[0])) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001328 our $clean = 0;
1329 our $cnt_warn++;
1330 }
1331}
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001332
Daniel P. Berrangé2b96c1a2024-10-07 15:40:28 +01001333sub checkspdx {
1334 my ($file, $expr) = @_;
1335
1336 # Imported Linux headers probably have SPDX tags, but if they
1337 # don't we're not requiring contributors to fix this, as these
1338 # files are not expected to be modified locally in QEMU.
1339 # Also don't accidentally detect own checking code.
1340 if ($file =~ m,include/standard-headers, ||
1341 $file =~ m,linux-headers, ||
1342 $file =~ m,checkpatch.pl,) {
1343 return;
1344 }
1345
1346 my $origexpr = $expr;
1347
1348 # Flatten sub-expressions
1349 $expr =~ s/\(|\)/ /g;
1350 $expr =~ s/OR|AND/ /g;
1351
1352 # Merge WITH exceptions to the license
1353 $expr =~ s/\s+WITH\s+/-WITH-/g;
1354
1355 # Cull more leading/trailing whitespace
1356 $expr =~ s/^\s*//g;
1357 $expr =~ s/\s*$//g;
1358
1359 my @bits = split / +/, $expr;
1360
1361 my $prefer = "GPL-2.0-or-later";
1362 my @valid = qw(
1363 GPL-2.0-only
1364 LGPL-2.1-only
1365 LGPL-2.1-or-later
1366 BSD-2-Clause
1367 BSD-3-Clause
1368 MIT
1369 );
1370
1371 my $nonpreferred = 0;
1372 my @unknown = ();
1373 foreach my $bit (@bits) {
1374 if ($bit eq $prefer) {
1375 next;
1376 }
1377 if (grep /^$bit$/, @valid) {
1378 $nonpreferred = 1;
1379 } else {
1380 push @unknown, $bit;
1381 }
1382 }
1383 if (@unknown) {
1384 ERROR("Saw unacceptable licenses '" . join(',', @unknown) .
1385 "', valid choices for QEMU are:\n" . join("\n", $prefer, @valid));
1386 }
1387
1388 if ($nonpreferred) {
1389 WARN("Saw acceptable license '$origexpr' but note '$prefer' is " .
1390 "preferred for new files unless the code is derived from a " .
1391 "source file with an existing declared license that must be " .
1392 "retained. Please explain the license choice in the commit " .
1393 "message.");
1394 }
1395}
1396
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001397# All three of the methods below take a 'file info' record
1398# which is a hash ref containing
1399#
1400# 'isgit': 1 if an enhanced git diff or 0 for a plain diff
1401# 'githeader': 1 if still parsing git patch header, 0 otherwise
1402# 'linestart': line number of start of file diff
1403# 'lineend': line number of end of file diff
1404# 'filenew': the new filename
1405# 'fileold': the old filename (same as 'new filename' except
1406# for renames in git diffs)
1407# 'action': one of 'modified' (always) or 'new' or 'deleted' or
1408# 'renamed' (git diffs only)
1409# 'mode': file mode for new/deleted files (git diffs only)
1410# 'similarity': file similarity when renamed (git diffs only)
1411# 'facts': hash ref for storing any metadata related to checks
1412#
1413
1414# Called at the end of each patch, with the list of
1415# real filenames that were seen in the patch
1416sub process_file_list {
1417 my @fileinfos = @_;
Daniel P. Berrangé9bec5f92025-05-12 17:48:20 +01001418
1419 # According to tests/qtest/bios-tables-test.c: do not
1420 # change expected file in the same commit with adding test
1421 my @acpi_testexpected;
1422 my @acpi_nontestexpected;
1423
1424 foreach my $fileinfo (@fileinfos) {
1425 # Note: shell script that rebuilds the expected files is in
1426 # the same directory as files themselves.
1427 # Note: allowed diff list can be changed both when changing
1428 # expected files and when changing tests.
1429 if ($fileinfo->{filenew} =~ m#^tests/data/acpi/# &&
1430 $fileinfo->{filenew} !~ m#^\.sh$#) {
1431 push @acpi_testexpected, $fileinfo->{filenew};
1432 } elsif ($fileinfo->{filenew} !~
1433 m#^tests/qtest/bios-tables-test-allowed-diff.h$#) {
1434 push @acpi_nontestexpected, $fileinfo->{filenew};
1435 }
1436 }
1437 if (int(@acpi_testexpected) > 0 and int(@acpi_nontestexpected) > 0) {
1438 ERROR("Do not add expected files together with tests, " .
1439 "follow instructions in " .
1440 "tests/qtest/bios-tables-test.c. Files\n\n " .
1441 join("\n ", @acpi_testexpected) .
1442 "\n\nand\n\n " .
1443 join("\n ", @acpi_nontestexpected) .
1444 "\n\nfound in the same patch\n");
1445 }
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001446}
1447
1448# Called at the start of processing a diff hunk for a file
1449sub process_start_of_file {
1450 my $fileinfo = shift;
Daniel P. Berrangéf48f16e2025-05-12 17:11:55 +01001451
1452 # Check for incorrect file permissions
1453 if ($fileinfo->{action} eq "new" && ($fileinfo->{mode} & 0111)) {
1454 my $permhere = $fileinfo->{linestart} . "FILE: " .
1455 $fileinfo->{filenew} . "\n";
1456 if ($fileinfo->{filenew} =~
Daniel P. Berrangé45abbf22025-05-15 13:57:45 +01001457 /(\bMakefile.*|\.(c|cc|cpp|h|mak|s|S))$/) {
Daniel P. Berrangéf48f16e2025-05-12 17:11:55 +01001458 ERROR("do not set execute permissions for source " .
1459 "files\n" . $permhere);
1460 }
1461 }
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001462}
1463
1464# Called at the end of processing a diff hunk for a file
1465sub process_end_of_file {
1466 my $fileinfo = shift;
1467}
1468
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001469sub process {
1470 my $filename = shift;
1471
1472 my $linenr=0;
1473 my $prevline="";
1474 my $prevrawline="";
1475 my $stashline="";
1476 my $stashrawline="";
1477
1478 my $length;
1479 my $indent;
1480 my $previndent=0;
1481 my $stashindent=0;
1482
1483 our $clean = 1;
1484 my $signoff = 0;
1485 my $is_patch = 0;
1486
Joe Perches5fc7e402018-04-30 13:46:49 +01001487 my $in_header_lines = $file ? 0 : 1;
Joe Perchesb37c4aa2018-04-30 13:46:47 +01001488 my $in_commit_log = 0; #Scanning lines before patch
Joe Perches4be61312018-04-30 13:46:50 +01001489 my $reported_maintainer_file = 0;
Stefano Garzarella503eb472024-08-13 21:23:14 +01001490 my $reported_mixing_imported_file = 0;
1491 my $in_imported_file = 0;
1492 my $in_no_imported_file = 0;
Pasi Savanainenbf139a02018-04-30 13:46:48 +01001493 my $non_utf8_charset = 0;
1494
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001495 our @report = ();
1496 our $cnt_lines = 0;
1497 our $cnt_error = 0;
1498 our $cnt_warn = 0;
1499 our $cnt_chk = 0;
1500
1501 # Trace the real file/line as we go.
1502 my $realfile = '';
1503 my $realline = 0;
1504 my $realcnt = 0;
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001505 my $fileinfo;
1506 my @fileinfolist;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001507 my $here = '';
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001508 my $oldhere = '';
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001509 my $in_comment = 0;
1510 my $comment_edge = 0;
1511 my $first_line = 0;
1512 my $p1_prefix = '';
1513
1514 my $prev_values = 'E';
1515
1516 # suppression flags
1517 my %suppress_ifbraces;
1518 my %suppress_whiletrailers;
1519 my %suppress_export;
1520
1521 # Pre-scan the patch sanitizing the lines.
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001522
1523 sanitise_line_reset();
1524 my $line;
1525 foreach my $rawline (@rawlines) {
1526 $linenr++;
1527 $line = $rawline;
1528
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001529 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1530 $realline=$1-1;
1531 if (defined $2) {
1532 $realcnt=$3+1;
1533 } else {
1534 $realcnt=1+1;
1535 }
1536 $in_comment = 0;
1537
1538 # Guestimate if this is a continuing comment. Run
1539 # the context looking for a comment "edge". If this
1540 # edge is a close comment then we must be in a comment
1541 # at context start.
1542 my $edge;
1543 my $cnt = $realcnt;
1544 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1545 next if (defined $rawlines[$ln - 1] &&
1546 $rawlines[$ln - 1] =~ /^-/);
1547 $cnt--;
1548 #print "RAW<$rawlines[$ln - 1]>\n";
1549 last if (!defined $rawlines[$ln - 1]);
1550 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1551 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1552 ($edge) = $1;
1553 last;
1554 }
1555 }
1556 if (defined $edge && $edge eq '*/') {
1557 $in_comment = 1;
1558 }
1559
1560 # Guestimate if this is a continuing comment. If this
1561 # is the start of a diff block and this line starts
1562 # ' *' then it is very likely a comment.
1563 if (!defined $edge &&
1564 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1565 {
1566 $in_comment = 1;
1567 }
1568
1569 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1570 sanitise_line_reset($in_comment);
1571
1572 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1573 # Standardise the strings and chars within the input to
1574 # simplify matching -- only bother with positive lines.
1575 $line = sanitise_line($rawline);
1576 }
1577 push(@lines, $line);
1578
1579 if ($realcnt > 1) {
1580 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1581 } else {
1582 $realcnt = 0;
1583 }
1584
1585 #print "==>$rawline\n";
1586 #print "-->$line\n";
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001587 }
1588
1589 $prefix = '';
1590
1591 $realcnt = 0;
1592 $linenr = 0;
1593 foreach my $line (@lines) {
1594 $linenr++;
1595
1596 my $rawline = $rawlines[$linenr - 1];
1597
1598#extract the line range in the file after the patch is applied
1599 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1600 $is_patch = 1;
1601 $first_line = $linenr + 1;
1602 $realline=$1-1;
1603 if (defined $2) {
1604 $realcnt=$3+1;
1605 } else {
1606 $realcnt=1+1;
1607 }
1608 annotate_reset();
1609 $prev_values = 'E';
1610
1611 %suppress_ifbraces = ();
1612 %suppress_whiletrailers = ();
1613 %suppress_export = ();
1614 next;
1615
1616# track the line number as we move through the hunk, note that
1617# new versions of GNU diff omit the leading space on completely
1618# blank context lines so we need to count that too.
1619 } elsif ($line =~ /^( |\+|$)/) {
1620 $realline++;
1621 $realcnt-- if ($realcnt != 0);
1622
1623 # Measure the line length and indent.
1624 ($length, $indent) = line_stats($rawline);
1625
1626 # Track the previous line.
1627 ($prevline, $stashline) = ($stashline, $line);
1628 ($previndent, $stashindent) = ($stashindent, $indent);
1629 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1630
1631 #warn "line<$line>\n";
1632
1633 } elsif ($realcnt == 1) {
1634 $realcnt--;
1635 }
1636
1637 my $hunk_line = ($realcnt != 0);
1638
1639#make up the handle for any error we report on this line
1640 $prefix = "$filename:$realline: " if ($emacs && $file);
1641 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1642
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001643 $oldhere = $here;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001644 $here = "#$linenr: " if (!$file);
1645 $here = "#$realline: " if ($file);
1646
1647 # extract the filename as it passes
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001648 if ($line =~ /^diff --git\s+(\S+)\s+(\S+)$/) {
1649 my $fileold = $1;
1650 my $filenew = $2;
1651
1652 if (defined $fileinfo) {
1653 $fileinfo->{lineend} = $oldhere;
1654 process_end_of_file($fileinfo)
1655 }
1656 $fileold =~ s@^([^/]*)/@@ if (!$file);
1657 $filenew =~ s@^([^/]*)/@@ if (!$file);
1658 $realfile = $filenew;
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001659
1660 $fileinfo = {
1661 "isgit" => 1,
1662 "githeader" => 1,
1663 "linestart" => $here,
1664 "lineend" => 0,
1665 "fileold" => $fileold,
1666 "filenew" => $filenew,
1667 "action" => "modified",
1668 "mode" => 0,
1669 "similarity" => 0,
1670 "facts" => {},
1671 };
1672 push @fileinfolist, $fileinfo;
1673 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1674 $line =~ /^(new|deleted) (?:file )?mode\s+([0-7]+)$/) {
1675 $fileinfo->{action} = $1;
1676 $fileinfo->{mode} = oct($2);
1677 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1678 $line =~ /^similarity index (\d+)%/) {
1679 $fileinfo->{similarity} = int($1);
1680 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1681 $line =~ /^rename (from|to) [\w\/\.\-]+\s*$/) {
1682 $fileinfo->{action} = "renamed";
1683 # For a no-change rename, we'll never have any "+++..."
1684 # lines, so trigger actions now
1685 if ($1 eq "to" && $fileinfo->{similarity} == 100) {
1686 process_start_of_file($fileinfo);
1687 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001688 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1689 $realfile = $1;
Paolo Bonzini1a5c63c2018-08-10 16:35:19 +02001690 $realfile =~ s@^([^/]*)/@@ if (!$file);
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001691
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001692 $p1_prefix = $1;
1693 if (!$file && $tree && $p1_prefix ne '' &&
1694 -e "$root/$p1_prefix") {
1695 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1696 }
1697
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01001698 if (defined $fileinfo && !$fileinfo->{isgit}) {
1699 $fileinfo->{lineend} = $oldhere;
1700 process_end_of_file($fileinfo);
1701 }
1702
1703 if (!defined $fileinfo || !$fileinfo->{isgit}) {
1704 $fileinfo = {
1705 "isgit" => 0,
1706 "githeader" => 0,
1707 "linestart" => $here,
1708 "lineend" => 0,
1709 "fileold" => $realfile,
1710 "filenew" => $realfile,
1711 "action" => "modified",
1712 "mode" => 0,
1713 "similarity" => 0,
1714 "facts" => {},
1715 };
1716 push @fileinfolist, $fileinfo;
1717 } else {
1718 $fileinfo->{githeader} = 0;
1719 }
1720 process_start_of_file($fileinfo);
1721
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001722 next;
1723 }
1724
1725 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1726
1727 my $hereline = "$here\n$rawline\n";
1728 my $herecurr = "$here\n$rawline\n";
1729 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1730
1731 $cnt_lines++ if ($realcnt != 0);
1732
Philippe Mathieu-Daudébc7f3b02020-01-30 17:32:21 +01001733# Only allow Python 3 interpreter
1734 if ($realline == 1 &&
1735 $line =~ /^\+#!\ *\/usr\/bin\/(?:env )?python$/) {
1736 ERROR("please use python3 interpreter\n" . $herecurr);
1737 }
1738
Stefan Hajnoczif8dccbb2016-07-15 10:46:54 +01001739# Accept git diff extended headers as valid patches
1740 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1741 $is_patch = 1;
1742 }
1743
Philippe Mathieu-Daudée3812d12024-04-02 13:59:57 +02001744 if ($line =~ /^(Author|From): .* via .*<qemu-\w+\@nongnu\.org>/) {
Daniel P. Berrangéf5177792018-08-23 11:21:43 +01001745 ERROR("Author email address is mangled by the mailing list\n" . $herecurr);
1746 }
1747
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001748#check the patch for a signoff:
1749 if ($line =~ /^\s*signed-off-by:/i) {
1750 # This is a signoff, if ugly, so do not double report.
1751 $signoff++;
Joe Perchesb37c4aa2018-04-30 13:46:47 +01001752 $in_commit_log = 0;
1753
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001754 if (!($line =~ /^\s*Signed-off-by:/)) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02001755 ERROR("The correct form is \"Signed-off-by\"\n" .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001756 $herecurr);
1757 }
1758 if ($line =~ /^\s*signed-off-by:\S/i) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02001759 ERROR("space required after Signed-off-by:\n" .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001760 $herecurr);
1761 }
1762 }
1763
Joe Perches1a6fad02018-04-30 13:46:51 +01001764# Check if MAINTAINERS is being updated. If so, there's probably no need to
1765# emit the "does MAINTAINERS need updating?" message on file add/move/delete
1766 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
1767 $reported_maintainer_file = 1;
1768 }
1769
Joe Perches4be61312018-04-30 13:46:50 +01001770# Check for added, moved or deleted files
1771 if (!$reported_maintainer_file && !$in_commit_log &&
1772 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
1773 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
1774 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
Isaku Yamahatad2f1af02021-02-17 21:51:09 -08001775 (defined($1) || defined($2)))) &&
Daniel P. Berrangé9bec5f92025-05-12 17:48:20 +01001776 $realfile !~ m#^tests/data/acpi/#) {
Joe Perches4be61312018-04-30 13:46:50 +01001777 $reported_maintainer_file = 1;
1778 WARN("added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
1779 }
1780
Daniel P. Berrangé2b96c1a2024-10-07 15:40:28 +01001781# Check SPDX-License-Identifier references a permitted license
1782 if ($rawline =~ m,SPDX-License-Identifier: (.*?)(\*/)?\s*$,) {
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01001783 &checkspdx($realfile, $1);
Daniel P. Berrangé2b96c1a2024-10-07 15:40:28 +01001784 }
1785
Daniel P. Berrangé6b752182024-10-07 16:21:54 +01001786 if ($rawline =~ m,(SPDX-[a-zA-Z0-9-_]+):,) {
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01001787 my $tag = $1;
1788 my @permitted = qw(
1789 SPDX-License-Identifier
1790 );
Daniel P. Berrangé6b752182024-10-07 16:21:54 +01001791
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01001792 unless (grep { /^$tag$/ } @permitted) {
1793 ERROR("Tag $tag not permitted in QEMU code, " .
1794 "valid choices are: " .
1795 join(", ", @permitted));
1796 }
Daniel P. Berrangé6b752182024-10-07 16:21:54 +01001797 }
1798
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001799# Check for wrappage within a valid hunk of the file
1800 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1801 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1802 $herecurr) if (!$emitted_corrupt++);
1803 }
1804
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001805# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1806 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1807 $rawline !~ m/^$UTF8*$/) {
1808 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1809
1810 my $blank = copy_spacing($rawline);
1811 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1812 my $hereptr = "$hereline$ptr\n";
1813
1814 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1815 }
1816
Paolo Bonzini874acb62019-05-17 15:19:00 +02001817 if ($rawline =~ m/$UTF8_MOJIBAKE/) {
1818 ERROR("Doubly-encoded UTF-8\n" . $herecurr);
1819 }
Joe Perchesb37c4aa2018-04-30 13:46:47 +01001820# Check if it's the start of a commit log
1821# (not a header line and we haven't seen the patch filename)
1822 if ($in_header_lines && $realfile =~ /^$/ &&
Joe Perches5fc7e402018-04-30 13:46:49 +01001823 !($rawline =~ /^\s+\S/ ||
1824 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
Joe Perchesb37c4aa2018-04-30 13:46:47 +01001825 $in_header_lines = 0;
1826 $in_commit_log = 1;
1827 }
1828
Pasi Savanainenbf139a02018-04-30 13:46:48 +01001829# Check if there is UTF-8 in a commit log when a mail header has explicitly
1830# declined it, i.e defined some charset where it is missing.
1831 if ($in_header_lines &&
1832 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1833 $1 !~ /utf-8/i) {
1834 $non_utf8_charset = 1;
1835 }
1836
1837 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
Joe Perchesb37c4aa2018-04-30 13:46:47 +01001838 $rawline =~ /$NON_ASCII_UTF8/) {
1839 WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1840 }
1841
Zhao Liue072af12024-01-05 16:38:48 +08001842# Check for various typo / spelling mistakes
1843 if (defined($misspellings) &&
1844 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
1845 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
1846 my $typo = $1;
1847 my $blank = copy_spacing($rawline);
1848 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
1849 my $hereptr = "$hereline$ptr\n";
1850 my $typo_fix = $spelling_fix{lc($typo)};
1851 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
1852 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
1853 WARN("'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr);
1854 }
1855 }
1856
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001857# ignore non-hunk lines and lines being removed
1858 next if (!$hunk_line || $line =~ /^-/);
1859
Stefano Garzarella503eb472024-08-13 21:23:14 +01001860# Check that updating imported files from Linux are not mixed with other changes
1861 if ($realfile =~ /^(linux-headers|include\/standard-headers)\//) {
1862 if (!$in_imported_file) {
1863 WARN("added, moved or deleted file(s) " .
1864 "imported from Linux, are you using " .
1865 "scripts/update-linux-headers.sh?\n" .
1866 $herecurr);
1867 }
1868 $in_imported_file = 1;
1869 } else {
1870 $in_no_imported_file = 1;
1871 }
1872
1873 if (!$reported_mixing_imported_file &&
1874 $in_imported_file && $in_no_imported_file) {
1875 ERROR("headers imported from Linux should be self-" .
1876 "contained in a patch with no other changes\n" .
1877 $herecurr);
1878 $reported_mixing_imported_file = 1;
1879 }
1880
Radim Krčmář93bf13c2016-08-09 19:38:41 +02001881# ignore files that are being periodically imported from Linux
1882 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1883
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001884#trailing whitespace
1885 if ($line =~ /^\+.*\015/) {
1886 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1887 ERROR("DOS line endings\n" . $herevet);
1888
Lluís Vilanova0cebabd2016-09-07 14:49:04 +02001889 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1890 $realfile =~ /^docs\/.+\.md/) {
1891 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1892 # TODO: properly check we're in a code block
1893 # (surrounding text is 4-column aligned)
1894 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1895 ERROR("code blocks in documentation should have " .
1896 "empty lines with exactly 4 columns of " .
1897 "whitespace\n" . $herevet);
1898 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001899 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1900 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1901 ERROR("trailing whitespace\n" . $herevet);
1902 $rpt_cleaners = 1;
1903 }
1904
Vladimir Sementsov-Ogievskiyc3e58752017-07-31 19:01:34 +03001905# checks for trace-events files
1906 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1907 if ($rawline =~ /%[-+ 0]*#/) {
1908 ERROR("Don't use '#' flag of printf format ('%#') in " .
1909 "trace-events, use '0x' prefix instead\n" . $herecurr);
1910 } else {
1911 my $hex =
1912 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1913
Michael Tokarevd30b5bc2023-07-14 14:33:18 +03001914 # don't consider groups split by [.:/ ], like 2A.20:12ab
Vladimir Sementsov-Ogievskiy45042732017-10-04 18:44:20 +03001915 my $tmpline = $rawline;
1916 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
Vladimir Sementsov-Ogievskiyc3e58752017-07-31 19:01:34 +03001917
1918 if ($tmpline =~ /(?<!0x)$hex/) {
1919 ERROR("Hex numbers must be prefixed with '0x'\n" .
1920 $herecurr);
1921 }
1922 }
1923 }
1924
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001925# check we are in a valid source file if not then ignore this hunk
Paolo Bonzini777d05b2017-10-04 16:35:53 +02001926 next if ($realfile !~ /$SrcFile/);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001927
Eric Blake205f31a2018-02-22 15:58:38 -06001928#90 column limit; exempt URLs, if no other words on line
Paolo Bonzinif1e155b2015-08-16 23:01:19 +02001929 if ($line =~ /^\+/ &&
1930 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
Eric Blake205f31a2018-02-22 15:58:38 -06001931 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001932 $length > 80)
1933 {
Paolo Bonzini8fbe3d12015-09-07 11:53:02 +02001934 if ($length > 90) {
1935 ERROR("line over 90 characters\n" . $herecurr);
1936 } else {
1937 WARN("line over 80 characters\n" . $herecurr);
1938 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001939 }
1940
1941# check for spaces before a quoted newline
1942 if ($rawline =~ /^.*\".*\s\\n/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02001943 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001944 }
1945
1946# check for adding lines without a newline.
1947 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02001948 ERROR("adding a line without newline at end of file\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001949 }
1950
Paolo Bonzini93eb8e32016-08-10 10:05:03 +02001951# check for RCS/CVS revision markers
1952 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02001953 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
Paolo Bonzini93eb8e32016-08-10 10:05:03 +02001954 }
1955
Paolo Bonzini906fb132016-08-09 17:47:42 +02001956# tabs are only allowed in assembly source code, and in
1957# some scripts we imported from other projects.
1958 next if ($realfile =~ /\.(s|S)$/);
Peter Maydell7a470a32020-09-25 17:23:13 +01001959 next if ($realfile =~ /(checkpatch|get_maintainer)\.pl$/);
Matheus Tavares Bernardino321b0ca2022-09-20 10:42:28 -03001960 next if ($realfile =~ /^target\/hexagon\/imported\/*/);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001961
Blue Swirlad36ce82011-02-05 13:18:20 +00001962 if ($rawline =~ /^\+.*\t/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001963 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
Blue Swirlb6469682011-01-20 20:58:56 +00001964 ERROR("code indent should never use tabs\n" . $herevet);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001965 $rpt_cleaners = 1;
1966 }
1967
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001968# check we are in a valid C source file if not then ignore this hunk
Matheus Ferst72205282021-05-20 16:51:42 -03001969 next if ($realfile !~ /\.((h|c)(\.inc)?|cpp)$/);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00001970
Peter Maydell8c06fbd2018-12-14 13:30:48 +00001971# Block comment styles
1972
1973 # Block comments use /* on a line of its own
Michael S. Tsirkin1ef47f402022-11-07 09:52:16 -05001974 my $commentline = $rawline;
Michael S. Tsirkin53a3b832022-11-08 08:52:06 -05001975 while ($commentline =~ s@^(\+.*)/\*.*\*/@$1@o) { # remove inline /*...*/
Michael S. Tsirkin1ef47f402022-11-07 09:52:16 -05001976 }
1977 if ($commentline =~ m@^\+.*/\*\*?+[ \t]*[^ \t]@) { # /* or /** non-blank
Peter Maydell8c06fbd2018-12-14 13:30:48 +00001978 WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
1979 }
1980
1981# Block comments use * on subsequent lines
1982 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1983 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
1984 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
1985 $rawline =~ /^\+/ && #line is new
1986 $rawline !~ /^\+[ \t]*\*/) { #no leading *
1987 WARN("Block comments use * on subsequent lines\n" . $hereprev);
1988 }
1989
1990# Block comments use */ on trailing lines
1991 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
1992 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
1993 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
1994 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
1995 WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
1996 }
1997
1998# Block comment * alignment
1999 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2000 $line =~ /^\+[ \t]*$;/ && #leading comment
2001 $rawline =~ /^\+[ \t]*\*/ && #leading *
2002 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
2003 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
2004 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
2005 my $oldindent;
2006 $prevrawline =~ m@^\+([ \t]*/?)\*@;
2007 if (defined($1)) {
2008 $oldindent = expand_tabs($1);
2009 } else {
2010 $prevrawline =~ m@^\+(.*/?)\*@;
2011 $oldindent = expand_tabs($1);
2012 }
2013 $rawline =~ m@^\+([ \t]*)\*@;
2014 my $newindent = $1;
2015 $newindent = expand_tabs($newindent);
2016 if (length($oldindent) ne length($newindent)) {
2017 WARN("Block comments should align the * on each line\n" . $hereprev);
2018 }
2019 }
2020
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002021# Check for potential 'bare' types
2022 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2023 $realline_next);
2024 if ($realcnt && $line =~ /.\s*\S/) {
2025 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2026 ctx_statement_block($linenr, $realcnt, 0);
2027 $stat =~ s/\n./\n /g;
2028 $cond =~ s/\n./\n /g;
2029
2030 # Find the real next line.
2031 $realline_next = $line_nr_next;
2032 if (defined $realline_next &&
2033 (!defined $lines[$realline_next - 1] ||
2034 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2035 $realline_next++;
2036 }
2037
2038 my $s = $stat;
2039 $s =~ s/{.*$//s;
2040
2041 # Ignore goto labels.
2042 if ($s =~ /$Ident:\*$/s) {
2043
2044 # Ignore functions being called
2045 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2046
2047 } elsif ($s =~ /^.\s*else\b/s) {
2048
2049 # declarations always start with types
2050 } 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) {
2051 my $type = $1;
2052 $type =~ s/\s+/ /g;
2053 possible($type, "A:" . $s);
2054
2055 # definitions in global scope can only start with types
2056 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2057 possible($1, "B:" . $s);
2058 }
2059
2060 # any (foo ... *) is a pointer cast, and foo is a type
2061 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2062 possible($1, "C:" . $s);
2063 }
2064
2065 # Check for any sort of function declaration.
2066 # int foo(something bar, other baz);
2067 # void (*store_gdt)(x86_descr_ptr *);
2068 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2069 my ($name_len) = length($1);
2070
2071 my $ctx = $s;
2072 substr($ctx, 0, $name_len + 1, '');
2073 $ctx =~ s/\)[^\)]*$//;
2074
2075 for my $arg (split(/\s*,\s*/, $ctx)) {
2076 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2077
2078 possible($1, "D:" . $s);
2079 }
2080 }
2081 }
2082
2083 }
2084
2085#
2086# Checks which may be anchored in the context.
2087#
2088
2089# Check for switch () and associated case and default
2090# statements should be at the same indent.
2091 if ($line=~/\bswitch\s*\(.*\)/) {
2092 my $err = '';
2093 my $sep = '';
2094 my @ctx = ctx_block_outer($linenr, $realcnt);
2095 shift(@ctx);
2096 for my $ctx (@ctx) {
2097 my ($clen, $cindent) = line_stats($ctx);
2098 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2099 $indent != $cindent) {
2100 $err .= "$sep$ctx\n";
2101 $sep = '';
2102 } else {
2103 $sep = "[...]\n";
2104 }
2105 }
2106 if ($err ne '') {
2107 ERROR("switch and case should be at the same indent\n$hereline$err");
2108 }
2109 }
2110
2111# if/while/etc brace do not go on next line, unless defining a do while loop,
2112# or if that brace on the next line is for something else
2113 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2114 my $pre_ctx = "$1$2";
2115
2116 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2117 my $ctx_cnt = $realcnt - $#ctx - 1;
2118 my $ctx = join("\n", @ctx);
2119
2120 my $ctx_ln = $linenr;
2121 my $ctx_skip = $realcnt;
2122
2123 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2124 defined $lines[$ctx_ln - 1] &&
2125 $lines[$ctx_ln - 1] =~ /^-/)) {
2126 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2127 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2128 $ctx_ln++;
2129 }
2130
2131 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2132 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2133
Max Reitza97ceca2014-11-26 17:20:24 +01002134 # The length of the "previous line" is checked against 80 because it
2135 # includes the + at the beginning of the line (if the actual line has
2136 # 79 or 80 characters, it is no longer possible to add a space and an
2137 # opening brace there)
2138 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
Fam Zheng04f25622015-09-11 19:07:36 +08002139 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
Max Reitza97ceca2014-11-26 17:20:24 +01002140 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002141 ERROR("that open brace { should be on the previous line\n" .
2142 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2143 }
2144 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2145 $ctx =~ /\)\s*\;\s*$/ &&
2146 defined $lines[$ctx_ln - 1])
2147 {
2148 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2149 if ($nindent > $indent) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002150 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002151 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2152 }
2153 }
2154 }
2155
Eric Blakef4bdc132017-12-01 17:24:33 -06002156# 'do ... while (0/false)' only makes sense in macros, without trailing ';'
2157 if ($line =~ /while\s*\((0|false)\);/) {
2158 ERROR("suspicious ; after while (0)\n" . $herecurr);
2159 }
2160
Philippe Mathieu-Daudéee0f3c02020-02-18 10:43:50 +01002161# Check superfluous trailing ';'
2162 if ($line =~ /;;$/) {
2163 ERROR("superfluous trailing semicolon\n" . $herecurr);
2164 }
2165
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002166# Check relative indent for conditionals and blocks.
2167 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2168 my ($s, $c) = ($stat, $cond);
2169
2170 substr($s, 0, length($c), '');
2171
2172 # Make sure we remove the line prefixes as we have
zhaolichang65fdb3c2020-09-17 15:50:23 +08002173 # none on the first line, and are going to re-add them
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002174 # where necessary.
2175 $s =~ s/\n./\n/gs;
2176
2177 # Find out how long the conditional actually is.
2178 my @newlines = ($c =~ /\n/gs);
2179 my $cond_lines = 1 + $#newlines;
2180
2181 # We want to check the first line inside the block
2182 # starting at the end of the conditional, so remove:
2183 # 1) any blank line termination
2184 # 2) any opening brace { on end of the line
2185 # 3) any do (...) {
2186 my $continuation = 0;
2187 my $check = 0;
2188 $s =~ s/^.*\bdo\b//;
Fam Zheng04f25622015-09-11 19:07:36 +08002189 $s =~ s/^\s*\{//;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002190 if ($s =~ s/^\s*\\//) {
2191 $continuation = 1;
2192 }
2193 if ($s =~ s/^\s*?\n//) {
2194 $check = 1;
2195 $cond_lines++;
2196 }
2197
2198 # Also ignore a loop construct at the end of a
2199 # preprocessor statement.
2200 if (($prevline =~ /^.\s*#\s*define\s/ ||
2201 $prevline =~ /\\\s*$/) && $continuation == 0) {
2202 $check = 0;
2203 }
2204
2205 my $cond_ptr = -1;
2206 $continuation = 0;
2207 while ($cond_ptr != $cond_lines) {
2208 $cond_ptr = $cond_lines;
2209
2210 # If we see an #else/#elif then the code
2211 # is not linear.
2212 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2213 $check = 0;
2214 }
2215
2216 # Ignore:
2217 # 1) blank lines, they should be at 0,
2218 # 2) preprocessor lines, and
2219 # 3) labels.
2220 if ($continuation ||
2221 $s =~ /^\s*?\n/ ||
2222 $s =~ /^\s*#\s*?/ ||
2223 $s =~ /^\s*$Ident\s*:/) {
2224 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2225 if ($s =~ s/^.*?\n//) {
2226 $cond_lines++;
2227 }
2228 }
2229 }
2230
2231 my (undef, $sindent) = line_stats("+" . $s);
2232 my $stat_real = raw_line($linenr, $cond_lines);
2233
2234 # Check if either of these lines are modified, else
2235 # this is not this patch's fault.
2236 if (!defined($stat_real) ||
2237 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2238 $check = 0;
2239 }
2240 if (defined($stat_real) && $cond_lines > 1) {
2241 $stat_real = "[...]\n$stat_real";
2242 }
2243
2244 #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";
2245
Blue Swirlb6469682011-01-20 20:58:56 +00002246 if ($check && (($sindent % 4) != 0 ||
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002247 ($sindent <= $indent && $s ne ''))) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002248 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002249 }
2250 }
2251
2252 # Track the 'values' across context and added lines.
2253 my $opline = $line; $opline =~ s/^./ /;
2254 my ($curr_values, $curr_vars) =
2255 annotate_values($opline . "\n", $prev_values);
2256 $curr_values = $prev_values . $curr_values;
2257 if ($dbg_values) {
2258 my $outline = $opline; $outline =~ s/\t/ /g;
2259 print "$linenr > .$outline\n";
2260 print "$linenr > $curr_values\n";
2261 print "$linenr > $curr_vars\n";
2262 }
2263 $prev_values = substr($curr_values, -1);
2264
2265#ignore lines not being added
2266 if ($line=~/^[^\+]/) {next;}
2267
2268# TEST: allow direct testing of the type matcher.
2269 if ($dbg_type) {
2270 if ($line =~ /^.\s*$Declare\s*$/) {
2271 ERROR("TEST: is type\n" . $herecurr);
2272 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2273 ERROR("TEST: is not type ($1 is)\n". $herecurr);
2274 }
2275 next;
2276 }
2277# TEST: allow direct testing of the attribute matcher.
2278 if ($dbg_attr) {
2279 if ($line =~ /^.\s*$Modifier\s*$/) {
2280 ERROR("TEST: is attr\n" . $herecurr);
2281 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2282 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
2283 }
2284 next;
2285 }
2286
2287# check for initialisation to aggregates open brace on the next line
Fam Zheng04f25622015-09-11 19:07:36 +08002288 if ($line =~ /^.\s*\{/ &&
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002289 $prevline =~ /(?:^|[^=])=\s*$/) {
2290 ERROR("that open brace { should be on the previous line\n" . $hereprev);
2291 }
2292
2293#
2294# Checks which are anchored on the added line.
2295#
2296
2297# check for malformed paths in #include statements (uses RAW line)
2298 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2299 my $path = $1;
2300 if ($path =~ m{//}) {
2301 ERROR("malformed #include filename\n" .
2302 $herecurr);
2303 }
2304 }
2305
2306# no C99 // comments
Peter Xu8d061272019-04-26 14:27:05 +08002307 if ($line =~ m{//} &&
2308 $rawline !~ m{// SPDX-License-Identifier: }) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002309 ERROR("do not use C99 // comments\n" . $herecurr);
2310 }
2311 # Remove C99 comments.
2312 $line =~ s@//.*@@;
2313 $opline =~ s@//.*@@;
2314
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002315# check for global initialisers.
2316 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
2317 ERROR("do not initialise globals to 0 or NULL\n" .
2318 $herecurr);
2319 }
2320# check for static initialisers.
2321 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2322 ERROR("do not initialise statics to 0 or NULL\n" .
2323 $herecurr);
2324 }
2325
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002326# * goes on variable not on type
2327 # (char*[ const])
2328 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
2329 my ($from, $to) = ($1, $1);
2330
2331 # Should start with a space.
2332 $to =~ s/^(\S)/ $1/;
2333 # Should not end with a space.
2334 $to =~ s/\s+$//;
2335 # '*'s should not have spaces between.
2336 while ($to =~ s/\*\s+\*/\*\*/) {
2337 }
2338
2339 #print "from<$from> to<$to>\n";
2340 if ($from ne $to) {
2341 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
2342 }
2343 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
2344 my ($from, $to, $ident) = ($1, $1, $2);
2345
2346 # Should start with a space.
2347 $to =~ s/^(\S)/ $1/;
2348 # Should not end with a space.
2349 $to =~ s/\s+$//;
2350 # '*'s should not have spaces between.
2351 while ($to =~ s/\*\s+\*/\*\*/) {
2352 }
2353 # Modifiers should have spaces.
2354 $to =~ s/(\b$Modifier$)/$1 /;
2355
2356 #print "from<$from> to<$to> ident<$ident>\n";
2357 if ($from ne $to && $ident !~ /^$Modifier$/) {
2358 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
2359 }
2360 }
2361
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002362# function brace can't be on same line, except for #defines of do while,
2363# or if closed on same line
Fam Zheng04f25622015-09-11 19:07:36 +08002364 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2365 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002366 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
2367 }
2368
2369# open braces for enum, union and struct go on the same line.
Fam Zheng04f25622015-09-11 19:07:36 +08002370 if ($line =~ /^.\s*\{/ &&
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002371 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2372 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
2373 }
2374
2375# missing space after union, struct or enum definition
2376 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01002377 ERROR("missing space after $1 definition\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002378 }
2379
2380# check for spacing round square brackets; allowed:
2381# 1. with a type on the left -- int [] a;
2382# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2383# 3. inside a curly brace -- = { [0...10] = 5 }
Leonid Bloch409db6e2015-10-29 11:48:37 +02002384# 4. after a comma -- [1] = 5, [2] = 6
Leonid Bloch8800cf02015-10-29 11:48:38 +02002385# 5. in a macro definition -- #define abc(x) [x] = y
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002386 while ($line =~ /(.*?\s)\[/g) {
2387 my ($where, $prefix) = ($-[1], $1);
2388 if ($prefix !~ /$Type\s+$/ &&
2389 ($where != 0 || $prefix !~ /^.\s+$/) &&
Leonid Bloch8800cf02015-10-29 11:48:38 +02002390 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
Heinrich Schuchardt66e9d202018-04-10 16:34:14 -07002391 $prefix !~ /[,{:]\s+$/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002392 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
2393 }
2394 }
2395
2396# check for spaces between functions and their parentheses.
2397 while ($line =~ /($Ident)\s+\(/g) {
2398 my $name = $1;
2399 my $ctx_before = substr($line, 0, $-[1]);
2400 my $ctx = "$ctx_before$name";
2401
2402 # Ignore those directives where spaces _are_ permitted.
2403 if ($name =~ /^(?:
2404 if|for|while|switch|return|case|
Jeff Cody000980c2016-11-01 10:38:35 -04002405 volatile|__volatile__|coroutine_fn|
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002406 __attribute__|format|__extension__|
2407 asm|__asm__)$/x)
2408 {
2409
Tomoki Sekiyama69d5d212013-08-07 11:39:50 -04002410 # Ignore 'catch (...)' in C++
2411 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
2412
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002413 # cpp #define statements have non-optional spaces, ie
2414 # if there is a space between the name and the open
2415 # parenthesis it is simply not a parameter group.
2416 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2417
2418 # cpp #elif statement condition may start with a (
2419 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2420
2421 # If this whole things ends with a type its most
2422 # likely a typedef for a function.
2423 } elsif ($ctx =~ /$Type$/) {
2424
2425 } else {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002426 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002427 }
2428 }
2429# Check operator spacing.
Phil Dennis-Jordan3fbb78c2024-10-24 14:35:55 +02002430 if (!($line=~/\#\s*(include|import)/)) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002431 my $ops = qr{
2432 <<=|>>=|<=|>=|==|!=|
2433 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2434 =>|->|<<|>>|<|>|=|!|~|
2435 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
Tomoki Sekiyama69d5d212013-08-07 11:39:50 -04002436 \?|::|:
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002437 }x;
2438 my @elements = split(/($ops|;)/, $opline);
2439 my $off = 0;
2440
2441 my $blank = copy_spacing($opline);
2442
2443 for (my $n = 0; $n < $#elements; $n += 2) {
2444 $off += length($elements[$n]);
2445
Stefan Weile7d81002011-12-10 00:19:46 +01002446 # Pick up the preceding and succeeding characters.
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002447 my $ca = substr($opline, 0, $off);
2448 my $cc = '';
2449 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2450 $cc = substr($opline, $off + length($elements[$n + 1]));
2451 }
2452 my $cb = "$ca$;$cc";
2453
2454 my $a = '';
2455 $a = 'V' if ($elements[$n] ne '');
2456 $a = 'W' if ($elements[$n] =~ /\s$/);
2457 $a = 'C' if ($elements[$n] =~ /$;$/);
2458 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2459 $a = 'O' if ($elements[$n] eq '');
2460 $a = 'E' if ($ca =~ /^\s*$/);
2461
2462 my $op = $elements[$n + 1];
2463
2464 my $c = '';
2465 if (defined $elements[$n + 2]) {
2466 $c = 'V' if ($elements[$n + 2] ne '');
2467 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2468 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2469 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2470 $c = 'O' if ($elements[$n + 2] eq '');
2471 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2472 } else {
2473 $c = 'E';
2474 }
2475
2476 my $ctx = "${a}x${c}";
2477
2478 my $at = "(ctx:$ctx)";
2479
2480 my $ptr = substr($blank, 0, $off) . "^";
2481 my $hereptr = "$hereline$ptr\n";
2482
2483 # Pull out the value of this operator.
2484 my $op_type = substr($curr_values, $off + 1, 1);
2485
2486 # Get the full operator variant.
2487 my $opv = $op . substr($curr_vars, $off, 1);
2488
2489 # Ignore operators passed as parameters.
2490 if ($op_type ne 'V' &&
2491 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2492
2493# # Ignore comments
2494# } elsif ($op =~ /^$;+$/) {
2495
2496 # ; should have either the end of line or a space or \ after it
2497 } elsif ($op eq ';') {
2498 if ($ctx !~ /.x[WEBC]/ &&
2499 $cc !~ /^\\/ && $cc !~ /^;/) {
2500 ERROR("space required after that '$op' $at\n" . $hereptr);
2501 }
2502
2503 # // is a comment
2504 } elsif ($op eq '//') {
2505
Tomoki Sekiyama69d5d212013-08-07 11:39:50 -04002506 # Ignore : used in class declaration in C++
2507 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2508 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2509
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002510 # No spaces for:
2511 # ->
2512 # : when part of a bitfield
2513 } elsif ($op eq '->' || $opv eq ':B') {
2514 if ($ctx =~ /Wx.|.xW/) {
2515 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2516 }
2517
2518 # , must have a space on the right.
Alexander Graf9fbe4782011-06-29 08:04:27 +02002519 # not required when having a single },{ on one line
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002520 } elsif ($op eq ',') {
Alexander Graf9fbe4782011-06-29 08:04:27 +02002521 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
Fam Zheng04f25622015-09-11 19:07:36 +08002522 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002523 ERROR("space required after that '$op' $at\n" . $hereptr);
2524 }
2525
2526 # '*' as part of a type definition -- reported already.
2527 } elsif ($opv eq '*_') {
2528 #warn "'*' is part of type\n";
2529
2530 # unary operators should have a space before and
2531 # none after. May be left adjacent to another
2532 # unary operator, or a cast
2533 } elsif ($op eq '!' || $op eq '~' ||
2534 $opv eq '*U' || $opv eq '-U' ||
2535 $opv eq '&U' || $opv eq '&&U') {
Tomoki Sekiyama69d5d212013-08-07 11:39:50 -04002536 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2537 # '~' used as a name of Destructor
2538
2539 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002540 ERROR("space required before that '$op' $at\n" . $hereptr);
2541 }
2542 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2543 # A unary '*' may be const
2544
2545 } elsif ($ctx =~ /.xW/) {
2546 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2547 }
2548
2549 # unary ++ and unary -- are allowed no space on one side.
2550 } elsif ($op eq '++' or $op eq '--') {
2551 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2552 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2553 }
2554 if ($ctx =~ /Wx[BE]/ ||
2555 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2556 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2557 }
2558 if ($ctx =~ /ExW/) {
2559 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2560 }
2561
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002562 # A colon needs no spaces before when it is
2563 # terminating a case value or a label.
2564 } elsif ($opv eq ':C' || $opv eq ':L') {
2565 if ($ctx =~ /Wx./) {
2566 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2567 }
2568
2569 # All the others need spaces both sides.
2570 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2571 my $ok = 0;
2572
Tomoki Sekiyama69d5d212013-08-07 11:39:50 -04002573 if ($realfile =~ /\.cpp|\.h$/) {
2574 # Ignore template arguments <...> in C++
2575 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2576 $ok = 1;
2577 }
2578
2579 # Ignore :: in C++
2580 if ($op eq '::') {
2581 $ok = 1;
2582 }
2583 }
2584
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002585 # Ignore email addresses <foo@bar>
2586 if (($op eq '<' &&
2587 $cc =~ /^\S+\@\S+>/) ||
2588 ($op eq '>' &&
2589 $ca =~ /<\S+\@\S+$/))
2590 {
2591 $ok = 1;
2592 }
2593
2594 # Ignore ?:
2595 if (($opv eq ':O' && $ca =~ /\?$/) ||
2596 ($op eq '?' && $cc =~ /^:/)) {
2597 $ok = 1;
2598 }
2599
2600 if ($ok == 0) {
2601 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2602 }
2603 }
2604 $off += length($elements[$n + 1]);
2605 }
2606 }
2607
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002608#need space before brace following if, while, etc
Fam Zheng04f25622015-09-11 19:07:36 +08002609 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2610 $line =~ /do\{/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002611 ERROR("space required before the open brace '{'\n" . $herecurr);
2612 }
2613
2614# closing brace should have a space following it when it has anything
2615# on the line
2616 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2617 ERROR("space required after that close brace '}'\n" . $herecurr);
2618 }
2619
2620# check spacing on square brackets
2621 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2622 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2623 }
2624 if ($line =~ /\s\]/) {
2625 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2626 }
2627
2628# check spacing on parentheses
2629 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2630 $line !~ /for\s*\(\s+;/) {
2631 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2632 }
2633 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2634 $line !~ /for\s*\(.*;\s+\)/ &&
2635 $line !~ /:\s+\)/) {
2636 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2637 }
2638
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002639# Return is not a function.
2640 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2641 my $spacing = $1;
2642 my $value = $2;
2643
2644 # Flatten any parentheses
2645 $value =~ s/\(/ \(/g;
2646 $value =~ s/\)/\) /g;
2647 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2648 $value !~ /(?:$Ident|-?$Constant)\s*
2649 $Compare\s*
2650 (?:$Ident|-?$Constant)/x &&
2651 $value =~ s/\([^\(\)]*\)/1/) {
2652 }
2653#print "value<$value>\n";
Paolo Bonzinic20b1392019-06-21 13:28:54 +02002654 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/ &&
2655 $line =~ /;$/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002656 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2657
2658 } elsif ($spacing !~ /\s+/) {
2659 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2660 }
2661 }
2662# Return of what appears to be an errno should normally be -'ve
2663 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2664 my $name = $1;
2665 if ($name ne 'EOF' && $name ne 'ERROR') {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002666 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002667 }
2668 }
2669
Paolo Bonzini50db69a2018-12-06 12:01:40 +01002670 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2671 $line !~ /^.typedef/) {
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01002672 ERROR("named $1 should be typedefed separately\n" . $herecurr);
Paolo Bonzini50db69a2018-12-06 12:01:40 +01002673 }
2674
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002675# Need a space before open parenthesis after if, while etc
2676 if ($line=~/\b(if|while|for|switch)\(/) {
2677 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2678 }
2679
2680# Check for illegal assignment in if conditional -- and check for trailing
2681# statements after the conditional.
2682 if ($line =~ /do\s*(?!{)/) {
2683 my ($stat_next) = ctx_statement_block($line_nr_next,
2684 $remain_next, $off_next);
2685 $stat_next =~ s/\n./\n /g;
2686 ##print "stat<$stat> stat_next<$stat_next>\n";
2687
2688 if ($stat_next =~ /^\s*while\b/) {
2689 # If the statement carries leading newlines,
2690 # then count those as offsets.
2691 my ($whitespace) =
2692 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2693 my $offset =
2694 statement_rawlines($whitespace) - 1;
2695
2696 $suppress_whiletrailers{$line_nr_next +
2697 $offset} = 1;
2698 }
2699 }
2700 if (!defined $suppress_whiletrailers{$linenr} &&
2701 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2702 my ($s, $c) = ($stat, $cond);
2703
2704 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2705 ERROR("do not use assignment in if condition\n" . $herecurr);
2706 }
2707
2708 # Find out what is on the end of the line after the
2709 # conditional.
2710 substr($s, 0, length($c), '');
2711 $s =~ s/\n.*//g;
2712 $s =~ s/$;//g; # Remove any comments
2713 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2714 $c !~ /}\s*while\s*/)
2715 {
2716 # Find out how long the conditional actually is.
2717 my @newlines = ($c =~ /\n/gs);
2718 my $cond_lines = 1 + $#newlines;
2719 my $stat_real = '';
2720
2721 $stat_real = raw_line($linenr, $cond_lines)
2722 . "\n" if ($cond_lines);
2723 if (defined($stat_real) && $cond_lines > 1) {
2724 $stat_real = "[...]\n$stat_real";
2725 }
2726
2727 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2728 }
2729 }
2730
2731# Check for bitwise tests written as boolean
2732 if ($line =~ /
2733 (?:
2734 (?:\[|\(|\&\&|\|\|)
2735 \s*0[xX][0-9]+\s*
2736 (?:\&\&|\|\|)
2737 |
2738 (?:\&\&|\|\|)
2739 \s*0[xX][0-9]+\s*
2740 (?:\&\&|\|\||\)|\])
2741 )/x)
2742 {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002743 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002744 }
2745
2746# if and else should not have general statements after it
2747 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2748 my $s = $1;
2749 $s =~ s/$;//g; # Remove any comments
2750 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2751 ERROR("trailing statements should be on next line\n" . $herecurr);
2752 }
2753 }
2754# if should not continue a brace
2755 if ($line =~ /}\s*if\b/) {
2756 ERROR("trailing statements should be on next line\n" .
2757 $herecurr);
2758 }
2759# case and default should not have general statements after them
2760 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2761 $line !~ /\G(?:
2762 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2763 \s*return\s+
2764 )/xg)
2765 {
2766 ERROR("trailing statements should be on next line\n" . $herecurr);
2767 }
2768
2769 # Check for }<nl>else {, these must be at the same
2770 # indent level to be relevant to each other.
2771 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2772 $previndent == $indent) {
2773 ERROR("else should follow close brace '}'\n" . $hereprev);
2774 }
2775
2776 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2777 $previndent == $indent) {
2778 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2779
2780 # Find out what is on the end of the line after the
2781 # conditional.
2782 substr($s, 0, length($c), '');
2783 $s =~ s/\n.*//g;
2784
2785 if ($s =~ /^\s*;/) {
2786 ERROR("while should follow close brace '}'\n" . $hereprev);
2787 }
2788 }
2789
2790#studly caps, commented out until figure out how to distinguish between use of existing and adding new
2791# if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2792# print "No studly caps, use _\n";
2793# print "$herecurr";
2794# $clean = 0;
2795# }
2796
2797#no spaces allowed after \ in define
2798 if ($line=~/\#\s*define.*\\\s$/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002799 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002800 }
2801
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002802# multi-statement macros should be enclosed in a do while loop, grab the
2803# first statement and ensure its the whole macro if its not enclosed
2804# in a known good container
2805 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2806 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2807 my $ln = $linenr;
2808 my $cnt = $realcnt;
2809 my ($off, $dstat, $dcond, $rest);
2810 my $ctx = '';
2811
2812 my $args = defined($1);
2813
2814 # Find the end of the macro and limit our statement
2815 # search to that.
2816 while ($cnt > 0 && defined $lines[$ln - 1] &&
2817 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2818 {
2819 $ctx .= $rawlines[$ln - 1] . "\n";
2820 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2821 $ln++;
2822 }
2823 $ctx .= $rawlines[$ln - 1];
2824
2825 ($dstat, $dcond, $ln, $cnt, $off) =
2826 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2827 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2828 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2829
2830 # Extract the remainder of the define (if any) and
2831 # rip off surrounding spaces, and trailing \'s.
2832 $rest = '';
2833 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2834 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2835 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2836 $rest .= substr($lines[$ln - 1], $off) . "\n";
2837 $cnt--;
2838 }
2839 $ln++;
2840 $off = 0;
2841 }
2842 $rest =~ s/\\\n.//g;
2843 $rest =~ s/^\s*//s;
2844 $rest =~ s/\s*$//s;
2845
2846 # Clean up the original statement.
2847 if ($args) {
2848 substr($dstat, 0, length($dcond), '');
2849 } else {
2850 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2851 }
2852 $dstat =~ s/$;//g;
2853 $dstat =~ s/\\\n.//g;
2854 $dstat =~ s/^\s*//s;
2855 $dstat =~ s/\s*$//s;
2856
2857 # Flatten any parentheses and braces
2858 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2859 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2860 $dstat =~ s/\[[^\{\}]*\]/1/)
2861 {
2862 }
2863
2864 my $exceptions = qr{
2865 $Declare|
2866 module_param_named|
2867 MODULE_PARAM_DESC|
2868 DECLARE_PER_CPU|
2869 DEFINE_PER_CPU|
2870 __typeof__\(|
2871 union|
2872 struct|
2873 \.$Ident\s*=\s*|
2874 ^\"|\"$
2875 }x;
2876 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2877 if ($rest ne '' && $rest ne ',') {
2878 if ($rest !~ /while\s*\(/ &&
2879 $dstat !~ /$exceptions/)
2880 {
2881 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2882 }
2883
2884 } elsif ($ctx !~ /;/) {
2885 if ($dstat ne '' &&
2886 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2887 $dstat !~ /$exceptions/ &&
2888 $dstat !~ /^\.$Ident\s*=/ &&
2889 $dstat =~ /$Operators/)
2890 {
2891 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2892 }
2893 }
2894 }
2895
Su Hang2b9aef62018-03-06 15:04:50 +08002896# check for missing bracing around if etc
2897 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2898 $line !~ /\#\s*if/) {
Su Hang053e45d2018-03-26 10:06:22 +08002899 my $allowed = 0;
2900
2901 # Check the pre-context.
2902 if ($line =~ /(\}.*?)$/) {
2903 my $pre = $1;
2904
2905 if ($line !~ /else/) {
2906 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2907 if $dbg_adv_apw;
2908 $allowed = 1;
2909 }
2910 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002911 my ($level, $endln, @chunks) =
2912 ctx_statement_full($linenr, $realcnt, 1);
Don Slutz69402a62012-09-02 19:22:37 -04002913 if ($dbg_adv_apw) {
2914 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2915 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2916 if $#chunks >= 1;
2917 }
Blue Swirlb6469682011-01-20 20:58:56 +00002918 if ($#chunks >= 0 && $level == 0) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002919 my $seen = 0;
2920 my $herectx = $here . "\n";
2921 my $ln = $linenr - 1;
2922 for my $chunk (@chunks) {
2923 my ($cond, $block) = @{$chunk};
2924
2925 # If the condition carries leading newlines, then count those as offsets.
2926 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2927 my $offset = statement_rawlines($whitespace) - 1;
2928
2929 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2930
2931 # We have looked at and allowed this specific line.
2932 $suppress_ifbraces{$ln + $offset} = 1;
2933
2934 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2935 $ln += statement_rawlines($block) - 1;
2936
2937 substr($block, 0, length($cond), '');
2938
Max Reitza97ceca2014-11-26 17:20:24 +01002939 my $spaced_block = $block;
2940 $spaced_block =~ s/\n\+/ /g;
2941
Fam Zheng04f25622015-09-11 19:07:36 +08002942 $seen++ if ($spaced_block =~ /^\s*\{/);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002943
Don Slutz69402a62012-09-02 19:22:37 -04002944 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2945 if $dbg_adv_apw;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002946 if (statement_lines($cond) > 1) {
Don Slutz69402a62012-09-02 19:22:37 -04002947 print "APW: ALLOWED: cond<$cond>\n"
2948 if $dbg_adv_apw;
2949 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002950 }
2951 if ($block =~/\b(?:if|for|while)\b/) {
Don Slutz69402a62012-09-02 19:22:37 -04002952 print "APW: ALLOWED: block<$block>\n"
2953 if $dbg_adv_apw;
2954 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002955 }
2956 if (statement_block_size($block) > 1) {
Don Slutz69402a62012-09-02 19:22:37 -04002957 print "APW: ALLOWED: lines block<$block>\n"
2958 if $dbg_adv_apw;
2959 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002960 }
2961 }
Su Hang053e45d2018-03-26 10:06:22 +08002962 if ($seen != ($#chunks + 1) && !$allowed) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02002963 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002964 }
2965 }
2966 }
2967 if (!defined $suppress_ifbraces{$linenr - 1} &&
Jan Kiszka789f88d2011-01-21 18:19:40 +01002968 $line =~ /\b(if|while|for|else)\b/ &&
Blue Swirld0510af2011-07-15 20:09:10 +00002969 $line !~ /\#\s*if/ &&
Jan Kiszka789f88d2011-01-21 18:19:40 +01002970 $line !~ /\#\s*else/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002971 my $allowed = 0;
2972
Don Slutzdfe70532012-09-02 19:22:38 -04002973 # Check the pre-context.
2974 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2975 my $pre = $1;
2976
2977 if ($line !~ /else/) {
2978 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2979 if $dbg_adv_apw;
2980 $allowed = 1;
2981 }
2982 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002983
2984 my ($level, $endln, @chunks) =
2985 ctx_statement_full($linenr, $realcnt, $-[0]);
2986
2987 # Check the condition.
2988 my ($cond, $block) = @{$chunks[0]};
Don Slutz54243022012-09-02 19:22:36 -04002989 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2990 if $dbg_adv_checking;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002991 if (defined $cond) {
2992 substr($block, 0, length($cond), '');
2993 }
2994 if (statement_lines($cond) > 1) {
Don Slutz69402a62012-09-02 19:22:37 -04002995 print "APW: ALLOWED: cond<$cond>\n"
2996 if $dbg_adv_apw;
2997 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00002998 }
2999 if ($block =~/\b(?:if|for|while)\b/) {
Don Slutz69402a62012-09-02 19:22:37 -04003000 print "APW: ALLOWED: block<$block>\n"
3001 if $dbg_adv_apw;
3002 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003003 }
3004 if (statement_block_size($block) > 1) {
Don Slutz69402a62012-09-02 19:22:37 -04003005 print "APW: ALLOWED: lines block<$block>\n"
3006 if $dbg_adv_apw;
3007 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003008 }
3009 # Check the post-context.
3010 if (defined $chunks[1]) {
3011 my ($cond, $block) = @{$chunks[1]};
3012 if (defined $cond) {
3013 substr($block, 0, length($cond), '');
3014 }
3015 if ($block =~ /^\s*\{/) {
Don Slutz69402a62012-09-02 19:22:37 -04003016 print "APW: ALLOWED: chunk-1 block<$block>\n"
3017 if $dbg_adv_apw;
3018 $allowed = 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003019 }
3020 }
Don Slutza99ac042012-09-02 19:22:35 -04003021 print "DCS: level=$level block<$block> allowed=$allowed\n"
3022 if $dbg_adv_dcs;
Blue Swirlb6469682011-01-20 20:58:56 +00003023 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003024 my $herectx = $here . "\n";;
3025 my $cnt = statement_rawlines($block);
3026
3027 for (my $n = 0; $n < $cnt; $n++) {
3028 $herectx .= raw_line($linenr, $n) . "\n";;
3029 }
3030
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003031 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003032 }
3033 }
3034
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003035# no volatiles please
3036 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
Marc-André Lureau6b012d22017-12-15 19:18:10 +01003037 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
3038 $line !~ /sig_atomic_t/ &&
3039 !ctx_has_comment($first_line, $linenr)) {
3040 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
3041 ERROR($msg);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003042 }
3043
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003044# warn about #if 0
3045 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003046 ERROR("if this code is redundant consider removing it\n" .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003047 $herecurr);
3048 }
3049
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003050# check for needless g_free() checks
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003051 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
3052 my $expr = $1;
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003053 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003054 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003055 }
3056 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003057
3058# warn about #ifdefs in C files
3059# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3060# print "#ifdef in C files should be avoided\n";
3061# print "$herecurr";
3062# $clean = 0;
3063# }
3064
3065# warn about spacing in #ifdefs
3066 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3067 ERROR("exactly one space required after that #$1\n" . $herecurr);
3068 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003069# check for memory barriers without a comment.
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003070 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003071 if (!ctx_has_comment($first_line, $linenr)) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003072 ERROR("memory barrier without comment\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003073 }
3074 }
3075# check of hardware specific defines
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003076# we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
3077# where they might be necessary.
3078 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
Paolo Bonzini63ae8b92016-09-21 18:49:07 +02003079 WARN("architecture specific defines should be avoided\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003080 }
3081
3082# Check that the storage class is at the beginning of a declaration
3083 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003084 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003085 }
3086
3087# check the location of the inline attribute, that it is between
3088# storage class and type.
3089 if ($line =~ /\b$Type\s+$Inline\b/ ||
3090 $line =~ /\b$Inline\s+$Storage\b/) {
3091 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
3092 }
3093
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003094# check for sizeof(&)
3095 if ($line =~ /\bsizeof\s*\(\s*\&/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003096 ERROR("sizeof(& should be avoided\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003097 }
3098
3099# check for new externs in .c files.
3100 if ($realfile =~ /\.c$/ && defined $stat &&
3101 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
3102 {
3103 my $function_name = $1;
3104 my $paren_space = $2;
3105
3106 my $s = $stat;
3107 if (defined $cond) {
3108 substr($s, 0, length($cond), '');
3109 }
3110 if ($s =~ /^\s*;/ &&
3111 $function_name ne 'uninitialized_var')
3112 {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003113 ERROR("externs should be avoided in .c files\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003114 }
3115
3116 if ($paren_space =~ /\n/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003117 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003118 }
3119
3120 } elsif ($realfile =~ /\.c$/ && defined $stat &&
3121 $stat =~ /^.\s*extern\s+/)
3122 {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003123 ERROR("externs should be avoided in .c files\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003124 }
3125
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003126# check for pointless casting of g_malloc return
Paolo Bonzinidfdb4f32022-04-06 14:27:52 +02003127 if ($line =~ /\*\s*\)\s*g_(try|)(m|re)alloc(0?)(_n)?\b/) {
3128 if ($2 eq 'm') {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003129 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003130 } else {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003131 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003132 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003133 }
3134
3135# check for gcc specific __FUNCTION__
3136 if ($line =~ /__FUNCTION__/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003137 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003138 }
3139
Julia Suvorovafb8446d2018-03-02 13:43:19 +03003140# recommend g_path_get_* over g_strdup(basename/dirname(...))
3141 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
3142 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
3143 }
3144
Philippe Mathieu-Daudéce2ff9c2021-09-03 19:45:10 +02003145# enforce g_memdup2() over g_memdup()
3146 if ($line =~ /\bg_memdup\s*\(/) {
3147 ERROR("use g_memdup2() instead of unsafe g_memdup()\n" . $herecurr);
3148 }
3149
Paolo Bonzini5e43efb2015-09-16 18:35:09 +02003150# recommend qemu_strto* over strto* for numeric conversions
Eric Blake01fb8e12016-06-09 20:48:07 -06003151 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003152 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003153 }
Paolo Bonzinie8c20912017-07-04 11:26:37 +02003154# recommend sigaction over signal for portability, when establishing a handler
3155 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
3156 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
3157 }
Alexander Bulekovef56ffb2023-04-27 17:10:08 -04003158# recommend qemu_bh_new_guarded instead of qemu_bh_new
3159 if ($realfile =~ /.*\/hw\/.*/ && $line =~ /\bqemu_bh_new\s*\(/) {
3160 ERROR("use qemu_bh_new_guarded() instead of qemu_bh_new() to avoid reentrancy problems\n" . $herecurr);
3161 }
3162# recommend aio_bh_new_guarded instead of aio_bh_new
3163 if ($realfile =~ /.*\/hw\/.*/ && $line =~ /\baio_bh_new\s*\(/) {
3164 ERROR("use aio_bh_new_guarded() instead of aio_bh_new() to avoid reentrancy problems\n" . $herecurr);
3165 }
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003166# check for module_init(), use category-specific init macros explicitly please
3167 if ($line =~ /^module_init\s*\(/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003168 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003169 }
3170# check for various ops structs, ensure they are const.
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003171 my $struct_ops = qr{AIOCBInfo|
3172 BdrvActionOps|
3173 BlockDevOps|
3174 BlockJobDriver|
3175 DisplayChangeListenerOps|
3176 GraphicHwOps|
3177 IDEDMAOps|
3178 KVMCapabilityInfo|
3179 MemoryRegionIOMMUOps|
3180 MemoryRegionOps|
3181 MemoryRegionPortio|
3182 QEMUFileOps|
3183 SCSIBusInfo|
3184 SCSIReqOps|
3185 Spice[A-Z][a-zA-Z0-9]*Interface|
Bernhard Beschow9a86e022022-01-17 15:58:05 +01003186 TypeInfo|
Paolo Bonzini71c47b02015-08-16 23:15:46 +02003187 USBDesc[A-Z][a-zA-Z0-9]*|
3188 VhostOps|
3189 VMStateDescription|
3190 VMStateInfo}x;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003191 if ($line !~ /\bconst\b/ &&
Paolo Bonzinie20e7182016-10-14 10:45:45 +02003192 $line =~ /\b($struct_ops)\b.*=/) {
3193 ERROR("initializer for struct $1 should normally be const\n" .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003194 $herecurr);
3195 }
3196
Dov Murikbfac6d12020-09-14 17:26:23 +00003197# format strings checks
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003198 my $string;
3199 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
3200 $string = substr($rawline, $-[1], $+[1] - $-[1]);
3201 $string =~ s/%%/__/g;
Dov Murikbfac6d12020-09-14 17:26:23 +00003202 # check for %L{u,d,i} in strings
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003203 if ($string =~ /(?<!%)%L[udi]/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003204 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
Dov Murikbfac6d12020-09-14 17:26:23 +00003205 }
3206 # check for %# or %0# in printf-style format strings
3207 if ($string =~ /(?<!%)%0?#/) {
3208 ERROR("Don't use '#' flag of printf format " .
3209 "('%#') in format strings, use '0x' " .
3210 "prefix instead\n" . $herecurr);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003211 }
3212 }
3213
Stefan Weil9964d8f2012-06-17 06:57:41 +02003214# QEMU specific tests
3215 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003216 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
Stefan Weil9964d8f2012-06-17 06:57:41 +02003217 }
Stefan Hajnoczi8b6ee9a2015-03-23 15:29:31 +00003218
Jason J. Herne5d596c22015-12-11 13:30:42 -05003219# Qemu error function tests
3220
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01003221 # Find newlines in error messages
3222 my $qemu_error_funcs = qr{error_setg|
3223 error_setg_errno|
3224 error_setg_win32|
3225 error_setg_file_open|
3226 error_set|
3227 error_prepend|
3228 warn_reportf_err|
3229 error_reportf_err|
3230 error_vreport|
3231 warn_vreport|
3232 info_vreport|
3233 error_report|
3234 warn_report|
3235 info_report|
3236 g_test_message}x;
Jason J. Herne5d596c22015-12-11 13:30:42 -05003237
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01003238 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
Paolo Bonzinic2df8782016-08-09 17:47:43 +02003239 ERROR("Error messages should not contain newlines\n" . $herecurr);
Jason J. Herne5d596c22015-12-11 13:30:42 -05003240 }
Daniel P. Berrangé619bf372025-05-12 18:11:58 +01003241
3242 # Continue checking for error messages that contains newlines.
3243 # This check handles cases where string literals are spread
3244 # over multiple lines.
3245 # Example:
3246 # error_report("Error msg line #1"
3247 # "Error msg line #2\n");
3248 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
3249 my $continued_str_literal = qr{\+\s*\".*\"};
3250
3251 if ($rawline =~ /$quoted_newline_regex/) {
3252 # Backtrack to first line that does not contain only
3253 # a quoted literal and assume that it is the start
3254 # of the statement.
3255 my $i = $linenr - 2;
3256
3257 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
3258 $i--;
3259 }
3260
3261 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
3262 ERROR("Error messages should not contain newlines\n" . $herecurr);
3263 }
3264 }
Jason J. Herne5d596c22015-12-11 13:30:42 -05003265
Paolo Bonzini3f822cf2016-07-21 11:03:11 +02003266# check for non-portable libc calls that have portable alternatives in QEMU
Stefan Hajnoczi8b6ee9a2015-03-23 15:29:31 +00003267 if ($line =~ /\bffs\(/) {
3268 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
3269 }
3270 if ($line =~ /\bffsl\(/) {
3271 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
3272 }
3273 if ($line =~ /\bffsll\(/) {
3274 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
3275 }
Paolo Bonzini3f822cf2016-07-21 11:03:11 +02003276 if ($line =~ /\bbzero\(/) {
3277 ERROR("use memset() instead of bzero()\n" . $herecurr);
3278 }
Wei Yange31db8a2019-10-17 08:46:33 +08003279 if ($line =~ /\bgetpagesize\(\)/) {
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +04003280 ERROR("use qemu_real_host_page_size() instead of getpagesize()\n" . $herecurr);
Wei Yange31db8a2019-10-17 08:46:33 +08003281 }
3282 if ($line =~ /\bsysconf\(_SC_PAGESIZE\)/) {
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +04003283 ERROR("use qemu_real_host_page_size() instead of sysconf(_SC_PAGESIZE)\n" . $herecurr);
Wei Yange31db8a2019-10-17 08:46:33 +08003284 }
Philippe Mathieu-Daudé837cd582023-02-22 00:00:42 +01003285 if ($line =~ /\b(g_)?assert\(0\)/) {
3286 ERROR("use g_assert_not_reached() instead of assert(0)\n" . $herecurr);
3287 }
Pierrick Bouvier2540a552024-09-18 21:46:41 -07003288 if ($line =~ /\b(g_)?assert\(false\)/) {
3289 ERROR("use g_assert_not_reached() instead of assert(false)\n" .
3290 $herecurr);
3291 }
Daniel Henrique Barbozace1992d2024-04-24 17:24:25 -03003292 if ($line =~ /\bstrerrorname_np\(/) {
3293 ERROR("use strerror() instead of strerrorname_np()\n" . $herecurr);
3294 }
Dr. David Alan Gilbert6e938952017-04-27 17:55:26 +01003295 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
3296 g_assert_cmpint|
3297 g_assert_cmpuint|
3298 g_assert_cmphex|
3299 g_assert_cmpfloat|
3300 g_assert_true|
3301 g_assert_false|
3302 g_assert_nonnull|
3303 g_assert_null|
3304 g_assert_no_error|
3305 g_assert_error|
3306 g_test_assert_expected_messages|
3307 g_test_trap_assert_passed|
3308 g_test_trap_assert_stdout|
3309 g_test_trap_assert_stdout_unmatched|
3310 g_test_trap_assert_stderr|
3311 g_test_trap_assert_stderr_unmatched}x;
3312 if ($realfile !~ /^tests\// &&
3313 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
3314 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
3315 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003316 }
3317
Daniel P. Berrangé25374ba2025-05-12 16:57:38 +01003318 if (defined $fileinfo) {
3319 process_end_of_file($fileinfo);
3320 }
3321 process_file_list(@fileinfolist);
3322
Paolo Bonzinifd9c0cf2018-11-29 09:31:41 +01003323 if ($is_patch && $chk_signoff && $signoff == 0) {
3324 ERROR("Missing Signed-off-by: line(s)\n");
3325 }
3326
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003327 # If we have no input at all, then there is nothing to report on
3328 # so just keep quiet.
3329 if ($#rawlines == -1) {
Paolo Bonzini1ff7ebf2018-11-29 09:30:59 +01003330 return 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003331 }
3332
3333 # In mailback mode only produce a report in the negative, for
3334 # things that appear to be patches.
3335 if ($mailback && ($clean == 1 || !$is_patch)) {
Paolo Bonzini1ff7ebf2018-11-29 09:30:59 +01003336 return 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003337 }
3338
3339 # This is not a patch, and we are are in 'no-patch' mode so
3340 # just keep quiet.
3341 if (!$chk_patch && !$is_patch) {
Paolo Bonzini1ff7ebf2018-11-29 09:30:59 +01003342 return 1;
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003343 }
3344
Stefano Garzarellafb4176d2020-09-17 19:02:12 +02003345 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003346 ERROR("Does not appear to be a unified-diff format patch\n");
3347 }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003348
3349 print report_dump();
3350 if ($summary && !($clean == 1 && $quiet == 1)) {
3351 print "$filename " if ($summary_file);
3352 print "total: $cnt_error errors, $cnt_warn warnings, " .
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003353 "$cnt_lines lines checked\n";
3354 print "\n" if ($quiet == 0);
3355 }
3356
3357 if ($quiet == 0) {
3358 # If there were whitespace errors which cleanpatch can fix
3359 # then suggest that.
Blue Swirlb6469682011-01-20 20:58:56 +00003360# if ($rpt_cleaners) {
3361# print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
3362# print " scripts/cleanfile\n\n";
3363# }
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003364 }
3365
3366 if ($clean == 1 && $quiet == 0) {
3367 print "$vname has no obvious style problems and is ready for submission.\n"
3368 }
3369 if ($clean == 0 && $quiet == 0) {
3370 print "$vname has style problems, please review. If any of these errors\n";
3371 print "are false positives report them to the maintainer, see\n";
3372 print "CHECKPATCH in MAINTAINERS.\n";
3373 }
3374
Paolo Bonzini141de882016-08-09 17:47:44 +02003375 return ($no_warnings ? $clean : $cnt_error == 0);
Blue Swirl1ec3f6f2011-01-20 20:54:26 +00003376}