master
pl 3,447 lines 94.7 KB
Raw
1 #!/usr/bin/env perl
2 # (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
8 use strict;
9 use warnings;
10 use Term::ANSIColor qw(:constants);
11
12 my $P = $0;
13 $P =~ s@.*/@@g;
14
15 our $SrcFile = qr{\.(?:(h|c)(\.inc)?|cpp|s|S|pl|py|sh)$};
16
17 my $V = '0.31';
18
19 use Getopt::Long qw(:config no_auto_abbrev);
20
21 my $quiet = 0;
22 my $tree = 1;
23 my $chk_signoff = 1;
24 my $chk_patch = undef;
25 my $chk_branch = undef;
26 my $tst_only;
27 my $emacs = 0;
28 my $terse = 0;
29 my $file = undef;
30 my $color = "auto";
31 my $no_warnings = 0;
32 my $summary = 1;
33 my $mailback = 0;
34 my $summary_file = 0;
35 my $root;
36 my %debug;
37 my $help = 0;
38 my $codespell = 0;
39 my $codespellfile = "/usr/share/codespell/dictionary.txt";
40 my $user_codespellfile = "";
41
42 sub help {
43 my ($exitcode) = @_;
44
45 print << "EOM";
46 Usage:
47
48 $P [OPTION]... [FILE]...
49 $P [OPTION]... [GIT-REV-LIST]
50
51 Version: $V
52
53 Options:
54 -q, --quiet quiet
55 --no-tree run without a qemu tree
56 --no-signoff do not check for 'Signed-off-by' line
57 --patch treat FILE as patchfile
58 --branch treat args as GIT revision list
59 --emacs emacs compile window format
60 --terse one line per report
61 -f, --file treat FILE as regular source file
62 --strict fail if only warnings are found
63 --root=PATH PATH to the qemu tree root
64 --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
72 --codespell Use the codespell dictionary for spelling/typos
73 (default: $codespellfile)
74 --codespellfile Use this codespell dictionary
75 --color[=WHEN] Use colors 'always', 'never', or only when output
76 is a terminal ('auto'). Default is 'auto'.
77 -h, --help, --version display this help and exit
78
79 When FILE is - read standard input.
80 EOM
81
82 exit($exitcode);
83 }
84
85 # Perl's Getopt::Long allows options to take optional arguments after a space.
86 # Prevent --color by itself from consuming other arguments
87 foreach (@ARGV) {
88 if ($_ eq "--color" || $_ eq "-color") {
89 $_ = "--color=$color";
90 }
91 }
92
93 GetOptions(
94 '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
115 ) or help(1);
116
117 if ($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
126 import os.path as op
127 import codespell_lib
128 codespell_dir = op.dirname(codespell_lib.__file__)
129 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
130 print(codespell_file, end='')
131 EOF
132
133 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
134 $codespellfile = $codespell_dict if (-f $codespell_dict);
135 }
136 }
137
138 help(0) if ($help);
139
140 my $exit = 0;
141
142 if ($#ARGV < 0) {
143 print "$P: no input files\n";
144 exit(1);
145 }
146
147 if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
148 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
149 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
150 $chk_patch = $chk_branch || $file ? 0 : 1;
151 } elsif (!defined $chk_branch && !defined $chk_patch) {
152 if ($file) {
153 $chk_branch = $chk_patch = 0;
154 } else {
155 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
156 $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 {
162 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
163 $file = $chk_branch ? 0 : 1;
164 }
165 } elsif (!defined $chk_patch && !defined $file) {
166 if ($chk_branch) {
167 $chk_patch = $file = 0;
168 } else {
169 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
170 $chk_patch = $file ? 0 : 1;
171 }
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
180 if (($chk_patch && $chk_branch) ||
181 ($chk_patch && $file) ||
182 ($chk_branch && $file)) {
183 die "Only one of --file, --branch, --patch is permitted\n";
184 }
185 if (!$chk_patch && !$chk_branch && !$file) {
186 die "One of --file, --branch, --patch is required\n";
187 }
188
189 if ($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
199 my $dbg_values = 0;
200 my $dbg_possible = 0;
201 my $dbg_type = 0;
202 my $dbg_attr = 0;
203 my $dbg_adv_dcs = 0;
204 my $dbg_adv_checking = 0;
205 my $dbg_adv_apw = 0;
206 for my $key (keys %debug) {
207 ## no critic
208 eval "\${dbg_$key} = '$debug{$key}';";
209 die "$@" if ($@);
210 }
211
212 my $rpt_cleaners = 0;
213
214 if ($terse) {
215 $emacs = 1;
216 $quiet++;
217 }
218
219 if ($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) {
234 print "Must be run from the top-level dir. of a qemu tree\n";
235 exit(2);
236 }
237 }
238
239 my $emitted_corrupt = 0;
240
241 our $Ident = qr{
242 [A-Za-z_][A-Za-z\d_]*
243 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
244 }x;
245 our $Storage = qr{extern|static|asmlinkage};
246 our $Sparse = qr{
247 __force
248 }x;
249
250 # Notes to $Attribute:
251 our $Attribute = qr{
252 const|
253 volatile|
254 G_NORETURN|
255 G_GNUC_WARN_UNUSED_RESULT|
256 G_GNUC_NULL_TERMINATED|
257 QEMU_PACKED|
258 G_GNUC_PRINTF
259 }x;
260 our $Modifier;
261 our $Inline = qr{inline};
262 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
263 our $Lval = qr{$Ident(?:$Member)*};
264
265 our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
266 our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
267 our $Compare = qr{<=|>=|==|!=|<|>};
268 our $Operators = qr{
269 <=|>=|==|!=|
270 =>|->|<<|>>|<|>|!|~|
271 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
272 }x;
273
274 our $NonptrType;
275 our $Type;
276 our $Declare;
277
278 our $NON_ASCII_UTF8 = qr{
279 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
280 | \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
288 our $UTF8 = qr{
289 [\x09\x0A\x0D\x20-\x7E] # ASCII
290 | $NON_ASCII_UTF8
291 }x;
292
293 # 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.
296 our $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
306 # There are still some false positives, but this catches most
307 # common cases.
308 our $typeTypedefs = qr{(?x:
309 (?![KMGTPE]iB) # IEC binary prefix (do not match)
310 [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
314 )};
315
316 our @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},
335 qr{target_(?:u)?long},
336 qr{hwaddr},
337 # external libraries
338 qr{xen\w+_handle},
339 # 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},
366 );
367
368 # Match text found in common license boilerplate comments:
369 # for new files the SPDX-License-Identifier line is sufficient.
370 our @LICENSE_BOILERPLATE = (
371 "licensed under the GPL version 2",
372 "licensed under the terms of the GNU GPL",
373 "under the terms of the GNU General Public License",
374 "under the terms of the GNU Lesser General Public",
375 "Permission is hereby granted, free of charge",
376 "GNU GPL, version 2 or later",
377 "See the COPYING file",
378 "terms and conditions of the GNU General Public",
379 );
380 our $LICENSE_BOILERPLATE_RE = join("|", @LICENSE_BOILERPLATE);
381
382 # Load common spelling mistakes and build regular expression list.
383 my $misspellings;
384 my %spelling_fix;
385
386 if ($codespell) {
387 if (open(my $spelling, '<', $codespellfile)) {
388 while (<$spelling>) {
389 my $line = $_;
390
391 $line =~ s/\s*\n?$//g;
392 $line =~ s/^\s*//g;
393
394 next if ($line =~ m/^\s*#/);
395 next if ($line =~ m/^\s*$/);
396 next if ($line =~ m/, disabled/i);
397
398 $line =~ s/,.*$//;
399
400 my ($suspect, $fix) = split(/->/, $line);
401
402 $spelling_fix{$suspect} = $fix;
403 }
404 close($spelling);
405 } else {
406 warn "No codespell typos will be found - file '$codespellfile': $!\n";
407 }
408 }
409
410 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
411
412 # This can be modified by sub possible. Since it can be empty, be careful
413 # about regexes that always match, because they can cause infinite loops.
414 our @modifierList = (
415 );
416
417 sub build_types {
418 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
419 if (@modifierList > 0) {
420 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
421 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
422 } else {
423 $Modifier = qr{(?:$Attribute|$Sparse)};
424 }
425 $NonptrType = qr{
426 (?:$Modifier\s+|const\s+)*
427 (?:
428 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
429 (?:$typeTypedefs\b)|
430 (?:${all}\b)
431 )
432 (?:\s+$Modifier|\s+const)*
433 }x;
434 $Type = qr{
435 $NonptrType
436 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
437 (?:\s+$Inline|\s+$Modifier)*
438 }x;
439 $Declare = qr{(?:$Storage\s+)?$Type};
440 }
441 build_types();
442
443 $chk_signoff = 0 if ($file);
444
445 my @rawlines = ();
446 my @lines = ();
447 my $vname;
448 if ($chk_branch) {
449 my @patches;
450 my %git_commits = ();
451 my $HASH;
452 open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--no-mailmap", "--format=%H %s", $ARGV[0]) ||
453 die "$P: git log --reverse --no-merges --no-mailmap --format='%H %s' $ARGV[0] failed - $!\n";
454
455 for my $line (<$HASH>) {
456 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
457 next if (!defined($1) || !defined($2));
458 my $sha1 = $1;
459 my $subject = $2;
460 push(@patches, $sha1);
461 $git_commits{$sha1} = $subject;
462 }
463
464 close $HASH;
465
466 die "$P: no revisions returned for revlist '$ARGV[0]'\n"
467 unless @patches;
468
469 my $i = 1;
470 my $num_patches = @patches;
471 for my $hash (@patches) {
472 my $FILE;
473 open($FILE, '-|', "git",
474 "-c", "diff.renamelimit=0",
475 "-c", "diff.renames=True",
476 "-c", "diff.algorithm=histogram",
477 "show", "--no-mailmap",
478 "--patch-with-stat", $hash) ||
479 die "$P: git show $hash - $!\n";
480 while (<$FILE>) {
481 chomp;
482 push(@rawlines, $_);
483 }
484 close($FILE);
485 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
486 if ($num_patches > 1 && $quiet == 0) {
487 my $prefix = "$i/$num_patches";
488 $prefix = BLUE . BOLD . $prefix . RESET if $color;
489 print "$prefix Checking commit $vname\n";
490 $vname = "Patch $i/$num_patches";
491 } else {
492 $vname = "Commit " . $vname;
493 }
494 if (!process($hash)) {
495 $exit = 1;
496 print "\n" if ($num_patches > 1 && $quiet == 0);
497 }
498 @rawlines = ();
499 @lines = ();
500 $i++;
501 }
502 } else {
503 for my $filename (@ARGV) {
504 my $FILE;
505 if ($file) {
506 open($FILE, '-|', "diff -u /dev/null $filename") ||
507 die "$P: $filename: diff failed - $!\n";
508 } elsif ($filename eq '-') {
509 open($FILE, '<&STDIN');
510 } else {
511 open($FILE, '<', "$filename") ||
512 die "$P: $filename: open failed - $!\n";
513 }
514 if ($filename eq '-') {
515 $vname = 'Your patch';
516 } else {
517 $vname = $filename;
518 }
519 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
520 while (<$FILE>) {
521 chomp;
522 push(@rawlines, $_);
523 }
524 close($FILE);
525 if (!process($filename)) {
526 $exit = 1;
527 }
528 @rawlines = ();
529 @lines = ();
530 }
531 }
532
533 exit($exit);
534
535 sub top_of_kernel_tree {
536 my ($root) = @_;
537
538 my @tree_check = (
539 "COPYING", "MAINTAINERS", "Makefile",
540 "README.rst", "docs", "VERSION",
541 "linux-user", "system"
542 );
543
544 foreach my $check (@tree_check) {
545 if (! -e $root . '/' . $check) {
546 return 0;
547 }
548 }
549 return 1;
550 }
551
552 sub which {
553 my ($bin) = @_;
554
555 foreach my $path (split(/:/, $ENV{PATH})) {
556 if (-e "$path/$bin") {
557 return "$path/$bin";
558 }
559 }
560
561 return "";
562 }
563
564 sub expand_tabs {
565 my ($str) = @_;
566
567 my $res = '';
568 my $n = 0;
569 for my $c (split(//, $str)) {
570 if ($c eq "\t") {
571 $res .= ' ';
572 $n++;
573 for (; ($n % 8) != 0; $n++) {
574 $res .= ' ';
575 }
576 next;
577 }
578 $res .= $c;
579 $n++;
580 }
581
582 return $res;
583 }
584 sub copy_spacing {
585 (my $res = shift) =~ tr/\t/ /c;
586 return $res;
587 }
588
589 sub line_stats {
590 my ($line) = @_;
591
592 # Drop the diff line leader and expand tabs
593 $line =~ s/^.//;
594 $line = expand_tabs($line);
595
596 # Pick the indent from the front of the line.
597 my ($white) = ($line =~ /^(\s*)/);
598
599 return (length($line), length($white));
600 }
601
602 my $sanitise_quote = '';
603
604 sub sanitise_line_reset {
605 my ($in_comment) = @_;
606
607 if ($in_comment) {
608 $sanitise_quote = '*/';
609 } else {
610 $sanitise_quote = '';
611 }
612 }
613 sub sanitise_line {
614 my ($line) = @_;
615
616 my $res = '';
617 my $l = '';
618
619 my $qlen = 0;
620 my $off = 0;
621 my $c;
622
623 # Always copy over the diff marker.
624 $res = substr($line, 0, 1);
625
626 for ($off = 1; $off < length($line); $off++) {
627 $c = substr($line, $off, 1);
628
629 # Comments we are wacking completely including the begin
630 # and end, all to $;.
631 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
632 $sanitise_quote = '*/';
633
634 substr($res, $off, 2, "$;$;");
635 $off++;
636 next;
637 }
638 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
639 $sanitise_quote = '';
640 substr($res, $off, 2, "$;$;");
641 $off++;
642 next;
643 }
644 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
645 $sanitise_quote = '//';
646
647 substr($res, $off, 2, $sanitise_quote);
648 $off++;
649 next;
650 }
651
652 # A \ in a string means ignore the next character.
653 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
654 $c eq "\\") {
655 substr($res, $off, 2, 'XX');
656 $off++;
657 next;
658 }
659 # Regular quotes.
660 if ($c eq "'" || $c eq '"') {
661 if ($sanitise_quote eq '') {
662 $sanitise_quote = $c;
663
664 substr($res, $off, 1, $c);
665 next;
666 } elsif ($sanitise_quote eq $c) {
667 $sanitise_quote = '';
668 }
669 }
670
671 #print "c<$c> SQ<$sanitise_quote>\n";
672 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
673 substr($res, $off, 1, $;);
674 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
675 substr($res, $off, 1, $;);
676 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
677 substr($res, $off, 1, 'X');
678 } else {
679 substr($res, $off, 1, $c);
680 }
681 }
682
683 if ($sanitise_quote eq '//') {
684 $sanitise_quote = '';
685 }
686
687 # The pathname on a #include may be surrounded by '<' and '>'.
688 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
689 my $clean = 'X' x length($1);
690 $res =~ s@\<.*\>@<$clean>@;
691
692 # The whole of a #error is a string.
693 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
694 my $clean = 'X' x length($1);
695 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
696 }
697
698 return $res;
699 }
700
701 sub ctx_statement_block {
702 my ($linenr, $remain, $off) = @_;
703 my $line = $linenr - 1;
704 my $blk = '';
705 my $soff = $off;
706 my $coff = $off - 1;
707 my $coff_set = 0;
708
709 my $loff = 0;
710
711 my $type = '';
712 my $level = 0;
713 my @stack = ();
714 my $p;
715 my $c;
716 my $len = 0;
717
718 my $remainder;
719 while (1) {
720 @stack = (['', 0]) if ($#stack == -1);
721
722 #warn "CSB: blk<$blk> remain<$remain>\n";
723 # If we are about to drop off the end, pull in more
724 # context.
725 if ($off >= $len) {
726 for (; $remain > 0; $line++) {
727 last if (!defined $lines[$line]);
728 next if ($lines[$line] =~ /^-/);
729 $remain--;
730 $loff = $len;
731 $blk .= $lines[$line] . "\n";
732 $len = length($blk);
733 $line++;
734 last;
735 }
736 # Bail if there is no further context.
737 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
738 if ($off >= $len) {
739 last;
740 }
741 }
742 $p = $c;
743 $c = substr($blk, $off, 1);
744 $remainder = substr($blk, $off);
745
746 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
747
748 # Handle nested #if/#else.
749 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
750 push(@stack, [ $type, $level ]);
751 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
752 ($type, $level) = @{$stack[$#stack - 1]};
753 } elsif ($remainder =~ /^#\s*endif\b/) {
754 ($type, $level) = @{pop(@stack)};
755 }
756
757 # Statement ends at the ';' or a close '}' at the
758 # outermost level.
759 if ($level == 0 && $c eq ';') {
760 last;
761 }
762
763 # An else is really a conditional as long as its not else if
764 if ($level == 0 && $coff_set == 0 &&
765 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
766 $remainder =~ /^(else)(?:\s|{)/ &&
767 $remainder !~ /^else\s+if\b/) {
768 $coff = $off + length($1) - 1;
769 $coff_set = 1;
770 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
771 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\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 && $coff < $soff) {
783 $coff = $off;
784 $coff_set = 1;
785 #warn "CSB: mark coff<$coff>\n";
786 }
787 }
788 if (($type eq '' || $type eq '{') && $c eq '{') {
789 $level++;
790 $type = '{';
791 }
792 if ($type eq '{' && $c eq '}') {
793 $level--;
794 $type = ($level != 0)? '{' : '';
795
796 if ($level == 0) {
797 if (substr($blk, $off + 1, 1) eq ';') {
798 $off++;
799 }
800 last;
801 }
802 }
803 $off++;
804 }
805 # We are truly at the end, so shuffle to the next line.
806 if ($off == $len) {
807 $loff = $len + 1;
808 $line++;
809 $remain--;
810 }
811
812 my $statement = substr($blk, $soff, $off - $soff + 1);
813 my $condition = substr($blk, $soff, $coff - $soff + 1);
814
815 #warn "STATEMENT<$statement>\n";
816 #warn "CONDITION<$condition>\n";
817
818 #print "coff<$coff> soff<$off> loff<$loff>\n";
819
820 return ($statement, $condition,
821 $line, $remain + 1, $off - $loff + 1, $level);
822 }
823
824 sub statement_lines {
825 my ($stmt) = @_;
826
827 # Strip the diff line prefixes and rip blank lines at start and end.
828 $stmt =~ s/(^|\n)./$1/g;
829 $stmt =~ s/^\s*//;
830 $stmt =~ s/\s*$//;
831
832 my @stmt_lines = ($stmt =~ /\n/g);
833
834 return $#stmt_lines + 2;
835 }
836
837 sub statement_rawlines {
838 my ($stmt) = @_;
839
840 my @stmt_lines = ($stmt =~ /\n/g);
841
842 return $#stmt_lines + 2;
843 }
844
845 sub statement_block_size {
846 my ($stmt) = @_;
847
848 $stmt =~ s/(^|\n)./$1/g;
849 $stmt =~ s/^\s*\{//;
850 $stmt =~ s/}\s*$//;
851 $stmt =~ s/^\s*//;
852 $stmt =~ s/\s*$//;
853
854 my @stmt_lines = ($stmt =~ /\n/g);
855 my @stmt_statements = ($stmt =~ /;/g);
856
857 my $stmt_lines = $#stmt_lines + 2;
858 my $stmt_statements = $#stmt_statements + 1;
859
860 if ($stmt_lines > $stmt_statements) {
861 return $stmt_lines;
862 } else {
863 return $stmt_statements;
864 }
865 }
866
867 sub ctx_statement_full {
868 my ($linenr, $remain, $off) = @_;
869 my ($statement, $condition, $level);
870
871 my (@chunks);
872
873 # Grab the first conditional/block pair.
874 ($statement, $condition, $linenr, $remain, $off, $level) =
875 ctx_statement_block($linenr, $remain, $off);
876 #print "F: c<$condition> s<$statement> remain<$remain>\n";
877 push(@chunks, [ $condition, $statement ]);
878 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
879 return ($level, $linenr, @chunks);
880 }
881
882 # Pull in the following conditional/block pairs and see if they
883 # could continue the statement.
884 for (;;) {
885 ($statement, $condition, $linenr, $remain, $off, $level) =
886 ctx_statement_block($linenr, $remain, $off);
887 #print "C: c<$condition> s<$statement> remain<$remain>\n";
888 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
889 #print "C: push\n";
890 push(@chunks, [ $condition, $statement ]);
891 }
892
893 return ($level, $linenr, @chunks);
894 }
895
896 sub ctx_block_get {
897 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
898 my $line;
899 my $start = $linenr - 1;
900 my $blk = '';
901 my @o;
902 my @c;
903 my @res = ();
904
905 my $level = 0;
906 my @stack = ($level);
907 for ($line = $start; $remain > 0; $line++) {
908 next if ($rawlines[$line] =~ /^-/);
909 $remain--;
910
911 $blk .= $rawlines[$line];
912
913 # Handle nested #if/#else.
914 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
915 push(@stack, $level);
916 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
917 $level = $stack[$#stack - 1];
918 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
919 $level = pop(@stack);
920 }
921
922 foreach my $c (split(//, $lines[$line])) {
923 ##print "C<$c>L<$level><$open$close>O<$off>\n";
924 if ($off > 0) {
925 $off--;
926 next;
927 }
928
929 if ($c eq $close && $level > 0) {
930 $level--;
931 last if ($level == 0);
932 } elsif ($c eq $open) {
933 $level++;
934 }
935 }
936
937 if (!$outer || $level <= 1) {
938 push(@res, $rawlines[$line]);
939 }
940
941 last if ($level == 0);
942 }
943
944 return ($level, @res);
945 }
946 sub ctx_block_outer {
947 my ($linenr, $remain) = @_;
948
949 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
950 return @r;
951 }
952 sub ctx_block {
953 my ($linenr, $remain) = @_;
954
955 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
956 return @r;
957 }
958 sub ctx_statement {
959 my ($linenr, $remain, $off) = @_;
960
961 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
962 return @r;
963 }
964 sub ctx_block_level {
965 my ($linenr, $remain) = @_;
966
967 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
968 }
969 sub ctx_statement_level {
970 my ($linenr, $remain, $off) = @_;
971
972 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
973 }
974
975 sub ctx_locate_comment {
976 my ($first_line, $end_line) = @_;
977
978 # Catch a comment on the end of the line itself.
979 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
980 return $current_comment if (defined $current_comment);
981
982 # Look through the context and try and figure out if there is a
983 # comment.
984 my $in_comment = 0;
985 $current_comment = '';
986 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
987 my $line = $rawlines[$linenr - 1];
988 #warn " $line\n";
989 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
990 $in_comment = 1;
991 }
992 if ($line =~ m@/\*@) {
993 $in_comment = 1;
994 }
995 if (!$in_comment && $current_comment ne '') {
996 $current_comment = '';
997 }
998 $current_comment .= $line . "\n" if ($in_comment);
999 if ($line =~ m@\*/@) {
1000 $in_comment = 0;
1001 }
1002 }
1003
1004 chomp($current_comment);
1005 return($current_comment);
1006 }
1007 sub ctx_has_comment {
1008 my ($first_line, $end_line) = @_;
1009 my $cmt = ctx_locate_comment($first_line, $end_line);
1010
1011 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1012 ##print "CMMT: $cmt\n";
1013
1014 return ($cmt ne '');
1015 }
1016
1017 sub raw_line {
1018 my ($linenr, $cnt) = @_;
1019
1020 my $offset = $linenr - 1;
1021 $cnt++;
1022
1023 my $line;
1024 while ($cnt) {
1025 $line = $rawlines[$offset++];
1026 next if (defined($line) && $line =~ /^-/);
1027 $cnt--;
1028 }
1029
1030 return $line;
1031 }
1032
1033 sub cat_vet {
1034 my ($vet) = @_;
1035 my ($res, $coded);
1036
1037 $res = '';
1038 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1039 $res .= $1;
1040 if ($2 ne '') {
1041 $coded = sprintf("^%c", unpack('C', $2) + 64);
1042 $res .= $coded;
1043 }
1044 }
1045 $res =~ s/$/\$/;
1046
1047 return $res;
1048 }
1049
1050 my $av_preprocessor = 0;
1051 my $av_pending;
1052 my @av_paren_type;
1053 my $av_pend_colon;
1054
1055 sub annotate_reset {
1056 $av_preprocessor = 0;
1057 $av_pending = '_';
1058 @av_paren_type = ('E');
1059 $av_pend_colon = 'O';
1060 }
1061
1062 sub annotate_values {
1063 my ($stream, $type) = @_;
1064
1065 my $res;
1066 my $var = '_' x length($stream);
1067 my $cur = $stream;
1068
1069 print "$stream\n" if ($dbg_values > 1);
1070
1071 while (length($cur)) {
1072 @av_paren_type = ('E') if ($#av_paren_type < 0);
1073 print " <" . join('', @av_paren_type) .
1074 "> <$type> <$av_pending>" if ($dbg_values > 1);
1075 if ($cur =~ /^(\s+)/o) {
1076 print "WS($1)\n" if ($dbg_values > 1);
1077 if ($1 =~ /\n/ && $av_preprocessor) {
1078 $type = pop(@av_paren_type);
1079 $av_preprocessor = 0;
1080 }
1081
1082 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1083 print "CAST($1)\n" if ($dbg_values > 1);
1084 push(@av_paren_type, $type);
1085 $type = 'C';
1086
1087 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1088 print "DECLARE($1)\n" if ($dbg_values > 1);
1089 $type = 'T';
1090
1091 } elsif ($cur =~ /^($Modifier)\s*/) {
1092 print "MODIFIER($1)\n" if ($dbg_values > 1);
1093 $type = 'T';
1094
1095 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1096 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1097 $av_preprocessor = 1;
1098 push(@av_paren_type, $type);
1099 if ($2 ne '') {
1100 $av_pending = 'N';
1101 }
1102 $type = 'E';
1103
1104 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1105 print "UNDEF($1)\n" if ($dbg_values > 1);
1106 $av_preprocessor = 1;
1107 push(@av_paren_type, $type);
1108
1109 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1110 print "PRE_START($1)\n" if ($dbg_values > 1);
1111 $av_preprocessor = 1;
1112
1113 push(@av_paren_type, $type);
1114 push(@av_paren_type, $type);
1115 $type = 'E';
1116
1117 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1118 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1119 $av_preprocessor = 1;
1120
1121 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1122
1123 $type = 'E';
1124
1125 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1126 print "PRE_END($1)\n" if ($dbg_values > 1);
1127
1128 $av_preprocessor = 1;
1129
1130 # Assume all arms of the conditional end as this
1131 # one does, and continue as if the #endif was not here.
1132 pop(@av_paren_type);
1133 push(@av_paren_type, $type);
1134 $type = 'E';
1135
1136 } elsif ($cur =~ /^(\\\n)/o) {
1137 print "PRECONT($1)\n" if ($dbg_values > 1);
1138
1139 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1140 print "ATTR($1)\n" if ($dbg_values > 1);
1141 $av_pending = $type;
1142 $type = 'N';
1143
1144 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1145 print "SIZEOF($1)\n" if ($dbg_values > 1);
1146 if (defined $2) {
1147 $av_pending = 'V';
1148 }
1149 $type = 'N';
1150
1151 } elsif ($cur =~ /^(if|while|for)\b/o) {
1152 print "COND($1)\n" if ($dbg_values > 1);
1153 $av_pending = 'E';
1154 $type = 'N';
1155
1156 } elsif ($cur =~/^(case)/o) {
1157 print "CASE($1)\n" if ($dbg_values > 1);
1158 $av_pend_colon = 'C';
1159 $type = 'N';
1160
1161 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1162 print "KEYWORD($1)\n" if ($dbg_values > 1);
1163 $type = 'N';
1164
1165 } elsif ($cur =~ /^(\()/o) {
1166 print "PAREN('$1')\n" if ($dbg_values > 1);
1167 push(@av_paren_type, $av_pending);
1168 $av_pending = '_';
1169 $type = 'N';
1170
1171 } elsif ($cur =~ /^(\))/o) {
1172 my $new_type = pop(@av_paren_type);
1173 if ($new_type ne '_') {
1174 $type = $new_type;
1175 print "PAREN('$1') -> $type\n"
1176 if ($dbg_values > 1);
1177 } else {
1178 print "PAREN('$1')\n" if ($dbg_values > 1);
1179 }
1180
1181 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1182 print "FUNC($1)\n" if ($dbg_values > 1);
1183 $type = 'V';
1184 $av_pending = 'V';
1185
1186 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1187 if (defined $2 && $type eq 'C' || $type eq 'T') {
1188 $av_pend_colon = 'B';
1189 } elsif ($type eq 'E') {
1190 $av_pend_colon = 'L';
1191 }
1192 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1193 $type = 'V';
1194
1195 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1196 print "IDENT($1)\n" if ($dbg_values > 1);
1197 $type = 'V';
1198
1199 } elsif ($cur =~ /^($Assignment)/o) {
1200 print "ASSIGN($1)\n" if ($dbg_values > 1);
1201 $type = 'N';
1202
1203 } elsif ($cur =~/^(;|{|})/) {
1204 print "END($1)\n" if ($dbg_values > 1);
1205 $type = 'E';
1206 $av_pend_colon = 'O';
1207
1208 } elsif ($cur =~/^(,)/) {
1209 print "COMMA($1)\n" if ($dbg_values > 1);
1210 $type = 'C';
1211
1212 } elsif ($cur =~ /^(\?)/o) {
1213 print "QUESTION($1)\n" if ($dbg_values > 1);
1214 $type = 'N';
1215
1216 } elsif ($cur =~ /^(:)/o) {
1217 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1218
1219 substr($var, length($res), 1, $av_pend_colon);
1220 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1221 $type = 'E';
1222 } else {
1223 $type = 'N';
1224 }
1225 $av_pend_colon = 'O';
1226
1227 } elsif ($cur =~ /^(\[)/o) {
1228 print "CLOSE($1)\n" if ($dbg_values > 1);
1229 $type = 'N';
1230
1231 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1232 my $variant;
1233
1234 print "OPV($1)\n" if ($dbg_values > 1);
1235 if ($type eq 'V') {
1236 $variant = 'B';
1237 } else {
1238 $variant = 'U';
1239 }
1240
1241 substr($var, length($res), 1, $variant);
1242 $type = 'N';
1243
1244 } elsif ($cur =~ /^($Operators)/o) {
1245 print "OP($1)\n" if ($dbg_values > 1);
1246 if ($1 ne '++' && $1 ne '--') {
1247 $type = 'N';
1248 }
1249
1250 } elsif ($cur =~ /(^.)/o) {
1251 print "C($1)\n" if ($dbg_values > 1);
1252 }
1253 if (defined $1) {
1254 $cur = substr($cur, length($1));
1255 $res .= $type x length($1);
1256 }
1257 }
1258
1259 return ($res, $var);
1260 }
1261
1262 sub possible {
1263 my ($possible, $line) = @_;
1264 my $notPermitted = qr{(?:
1265 ^(?:
1266 $Modifier|
1267 $Storage|
1268 $Type|
1269 DEFINE_\S+
1270 )$|
1271 ^(?:
1272 goto|
1273 return|
1274 case|
1275 else|
1276 asm|__asm__|
1277 do
1278 )(?:\s|$)|
1279 ^(?:typedef|struct|enum)\b|
1280 ^\#
1281 )}x;
1282 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1283 if ($possible !~ $notPermitted) {
1284 # Check for modifiers.
1285 $possible =~ s/\s*$Storage\s*//g;
1286 $possible =~ s/\s*$Sparse\s*//g;
1287 if ($possible =~ /^\s*$/) {
1288
1289 } elsif ($possible =~ /\s/) {
1290 $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
1291 for my $modifier (split(' ', $possible)) {
1292 if ($modifier !~ $notPermitted) {
1293 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1294 push(@modifierList, $modifier);
1295 }
1296 }
1297
1298 } else {
1299 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1300 push(@typeList, $possible);
1301 }
1302 build_types();
1303 } else {
1304 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1305 }
1306 }
1307
1308 my $prefix = '';
1309
1310 sub report {
1311 my ($level, $msg) = @_;
1312 if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
1313 return 0;
1314 }
1315
1316 my $output = '';
1317 $output .= BOLD if $color;
1318 $output .= $prefix;
1319 $output .= RED if $color && $level eq 'ERROR';
1320 $output .= MAGENTA if $color && $level eq 'WARNING';
1321 $output .= $level . ':';
1322 $output .= RESET if $color;
1323 $output .= ' ' . $msg . "\n";
1324
1325 $output = (split('\n', $output))[0] . "\n" if ($terse);
1326
1327 push(our @report, $output);
1328
1329 return 1;
1330 }
1331 sub report_dump {
1332 our @report;
1333 }
1334 sub ERROR {
1335 if (report("ERROR", $_[0])) {
1336 our $clean = 0;
1337 our $cnt_error++;
1338 }
1339 }
1340 sub WARN {
1341 if (report("WARNING", $_[0])) {
1342 our $clean = 0;
1343 our $cnt_warn++;
1344 }
1345 }
1346
1347 sub checkspdx {
1348 my ($file, $expr) = @_;
1349
1350 # Imported Linux headers probably have SPDX tags, but if they
1351 # don't we're not requiring contributors to fix this, as these
1352 # files are not expected to be modified locally in QEMU.
1353 # Also don't accidentally detect own checking code.
1354 if ($file =~ m,include/standard-headers, ||
1355 $file =~ m,linux-headers, ||
1356 $file =~ m,checkpatch.pl,) {
1357 return;
1358 }
1359
1360 my $origexpr = $expr;
1361
1362 # Flatten sub-expressions
1363 $expr =~ s/\(|\)/ /g;
1364 $expr =~ s/OR|AND/ /g;
1365
1366 # Merge WITH exceptions to the license
1367 $expr =~ s/\s+WITH\s+/-WITH-/g;
1368
1369 # Cull more leading/trailing whitespace
1370 $expr =~ s/^\s*//g;
1371 $expr =~ s/\s*$//g;
1372
1373 # Cull C comment end
1374 $expr =~ s/\*\/.*//;
1375
1376 my @bits = split / +/, $expr;
1377
1378 my $prefer = "GPL-2.0-or-later";
1379 my @valid = qw(
1380 GPL-2.0-only
1381 LGPL-2.1-only
1382 LGPL-2.1-or-later
1383 BSD-2-Clause
1384 BSD-3-Clause
1385 MIT
1386 );
1387
1388 my $nonpreferred = 0;
1389 my @unknown = ();
1390 foreach my $bit (@bits) {
1391 if ($bit eq $prefer) {
1392 next;
1393 }
1394 if (grep /^$bit$/, @valid) {
1395 $nonpreferred = 1;
1396 } else {
1397 push @unknown, $bit;
1398 }
1399 }
1400 if (@unknown) {
1401 ERROR("Saw unacceptable licenses '" . join(',', @unknown) .
1402 "', valid choices for QEMU are:\n" . join("\n", $prefer, @valid));
1403 }
1404
1405 if ($nonpreferred) {
1406 WARN("Saw acceptable license '$origexpr' but note '$prefer' is " .
1407 "preferred for new files unless the code is derived from a " .
1408 "source file with an existing declared license that must be " .
1409 "retained. Please explain the license choice in the commit " .
1410 "message.");
1411 }
1412 }
1413
1414 # All three of the methods below take a 'file info' record
1415 # which is a hash ref containing
1416 #
1417 # 'isgit': 1 if an enhanced git diff or 0 for a plain diff
1418 # 'githeader': 1 if still parsing git patch header, 0 otherwise
1419 # 'linestart': line number of start of file diff
1420 # 'lineend': line number of end of file diff
1421 # 'filenew': the new filename
1422 # 'fileold': the old filename (same as 'new filename' except
1423 # for renames in git diffs)
1424 # 'action': one of 'modified' (always) or 'new' or 'deleted' or
1425 # 'renamed' (git diffs only)
1426 # 'mode': file mode for new/deleted files (git diffs only)
1427 # 'similarity': file similarity when renamed (git diffs only)
1428 # 'facts': hash ref for storing any metadata related to checks
1429 #
1430
1431 # Called at the end of each patch, with the list of
1432 # real filenames that were seen in the patch
1433 sub process_file_list {
1434 my @fileinfos = @_;
1435
1436 # According to tests/qtest/bios-tables-test.c: do not
1437 # change expected file in the same commit with adding test
1438 my @acpi_testexpected;
1439 my @acpi_nontestexpected;
1440
1441 foreach my $fileinfo (@fileinfos) {
1442 # Note: shell script that rebuilds the expected files is in
1443 # the same directory as files themselves.
1444 # Note: allowed diff list can be changed both when changing
1445 # expected files and when changing tests.
1446 if ($fileinfo->{filenew} =~ m#^tests/data/acpi/# &&
1447 $fileinfo->{filenew} !~ m#^\.sh$#) {
1448 push @acpi_testexpected, $fileinfo->{filenew};
1449 } elsif ($fileinfo->{filenew} !~
1450 m#^tests/qtest/bios-tables-test-allowed-diff.h$#) {
1451 push @acpi_nontestexpected, $fileinfo->{filenew};
1452 }
1453 }
1454 if (int(@acpi_testexpected) > 0 and int(@acpi_nontestexpected) > 0) {
1455 ERROR("Do not add expected files together with tests, " .
1456 "follow instructions in " .
1457 "tests/qtest/bios-tables-test.c. Files\n\n " .
1458 join("\n ", @acpi_testexpected) .
1459 "\n\nand\n\n " .
1460 join("\n ", @acpi_nontestexpected) .
1461 "\n\nfound in the same patch\n");
1462 }
1463
1464 my $sawmaintainers = 0;
1465 my @maybemaintainers;
1466 foreach my $fileinfo (@fileinfos) {
1467 if ($fileinfo->{action} ne "modified" &&
1468 $fileinfo->{filenew} !~ m#^tests/data/acpi/#) {
1469 push @maybemaintainers, $fileinfo->{filenew};
1470 }
1471 if ($fileinfo->{filenew} eq "MAINTAINERS") {
1472 $sawmaintainers = 1;
1473 }
1474 }
1475
1476 # If we don't see a MAINTAINERS update, prod the user to check
1477 if (int(@maybemaintainers) > 0 && !$sawmaintainers) {
1478 WARN("added, moved or deleted file(s),"
1479 . " does MAINTAINERS need updating?\n "
1480 . join("\n ", @maybemaintainers));
1481 }
1482 }
1483
1484 # Called at the start of processing a diff hunk for a file
1485 sub process_start_of_file {
1486 my $fileinfo = shift;
1487
1488 # Check for incorrect file permissions
1489 if ($fileinfo->{action} eq "new" && ($fileinfo->{mode} & 0111)) {
1490 my $permhere = $fileinfo->{linestart} . "FILE: " .
1491 $fileinfo->{filenew} . "\n";
1492 if ($fileinfo->{filenew} =~
1493 /(\bMakefile.*|\.(c|cc|cpp|h|mak|s|S))$/) {
1494 ERROR("do not set execute permissions for source " .
1495 "files\n" . $permhere);
1496 }
1497 }
1498 }
1499
1500 # Called at the end of processing a diff hunk for a file
1501 sub process_end_of_file {
1502 my $fileinfo = shift;
1503
1504 if ($fileinfo->{action} eq "new" &&
1505 !exists $fileinfo->{facts}->{sawspdx}) {
1506 if ($fileinfo->{filenew} =~
1507 /(\.(c|h|py|pl|sh|json|inc|rs)|Makefile.*)$/) {
1508 # source code files MUST have SPDX license declared
1509 ERROR("New file '" . $fileinfo->{filenew} .
1510 "' requires 'SPDX-License-Identifier'");
1511 } else {
1512 # Other files MAY have SPDX license if appropriate
1513 WARN("Does new file '" . $fileinfo->{filenew} .
1514 "' need 'SPDX-License-Identifier'?");
1515 }
1516 }
1517 if ($fileinfo->{action} eq "new" &&
1518 exists $fileinfo->{facts}->{sawboilerplate}) {
1519 ERROR("New file '" . $fileinfo->{filenew} . "' must " .
1520 "not have license boilerplate header text, only " .
1521 "the SPDX-License-Identifier, unless this file was " .
1522 "copied from existing code already having such text.");
1523 }
1524 }
1525
1526 sub process {
1527 my $filename = shift;
1528
1529 my $linenr=0;
1530 my $prevline="";
1531 my $prevrawline="";
1532 my $stashline="";
1533 my $stashrawline="";
1534
1535 my $length;
1536 my $indent;
1537 my $previndent=0;
1538 my $stashindent=0;
1539
1540 our $clean = 1;
1541 my $signoff = 0;
1542 my $is_patch = 0;
1543
1544 my $in_header_lines = $file ? 0 : 1;
1545 my $in_commit_log = 0; #Scanning lines before patch
1546 my $reported_mixing_imported_file = 0;
1547 my $in_imported_file = 0;
1548 my $in_no_imported_file = 0;
1549 my $non_utf8_charset = 0;
1550
1551 our @report = ();
1552 our $cnt_lines = 0;
1553 our $cnt_error = 0;
1554 our $cnt_warn = 0;
1555 our $cnt_chk = 0;
1556
1557 # Trace the real file/line as we go.
1558 my $realfile = '';
1559 my $realline = 0;
1560 my $realcnt = 0;
1561 my $fileinfo;
1562 my @fileinfolist;
1563 my $here = '';
1564 my $oldhere = '';
1565 my $in_comment = 0;
1566 my $comment_edge = 0;
1567 my $first_line = 0;
1568 my $p1_prefix = '';
1569
1570 my $prev_values = 'E';
1571
1572 # suppression flags
1573 my %suppress_ifbraces;
1574 my %suppress_whiletrailers;
1575 my %suppress_export;
1576
1577 # Pre-scan the patch sanitizing the lines.
1578
1579 sanitise_line_reset();
1580 my $line;
1581 foreach my $rawline (@rawlines) {
1582 $linenr++;
1583 $line = $rawline;
1584
1585 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1586 $realline=$1-1;
1587 if (defined $2) {
1588 $realcnt=$3+1;
1589 } else {
1590 $realcnt=1+1;
1591 }
1592 $in_comment = 0;
1593
1594 # Guestimate if this is a continuing comment. Run
1595 # the context looking for a comment "edge". If this
1596 # edge is a close comment then we must be in a comment
1597 # at context start.
1598 my $edge;
1599 my $cnt = $realcnt;
1600 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1601 next if (defined $rawlines[$ln - 1] &&
1602 $rawlines[$ln - 1] =~ /^-/);
1603 $cnt--;
1604 #print "RAW<$rawlines[$ln - 1]>\n";
1605 last if (!defined $rawlines[$ln - 1]);
1606 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1607 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1608 ($edge) = $1;
1609 last;
1610 }
1611 }
1612 if (defined $edge && $edge eq '*/') {
1613 $in_comment = 1;
1614 }
1615
1616 # Guestimate if this is a continuing comment. If this
1617 # is the start of a diff block and this line starts
1618 # ' *' then it is very likely a comment.
1619 if (!defined $edge &&
1620 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1621 {
1622 $in_comment = 1;
1623 }
1624
1625 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1626 sanitise_line_reset($in_comment);
1627
1628 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1629 # Standardise the strings and chars within the input to
1630 # simplify matching -- only bother with positive lines.
1631 $line = sanitise_line($rawline);
1632 }
1633 push(@lines, $line);
1634
1635 if ($realcnt > 1) {
1636 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1637 } else {
1638 $realcnt = 0;
1639 }
1640
1641 #print "==>$rawline\n";
1642 #print "-->$line\n";
1643 }
1644
1645 $prefix = '';
1646
1647 $realcnt = 0;
1648 $linenr = 0;
1649 foreach my $line (@lines) {
1650 $linenr++;
1651
1652 my $rawline = $rawlines[$linenr - 1];
1653
1654 #extract the line range in the file after the patch is applied
1655 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1656 $is_patch = 1;
1657 $first_line = $linenr + 1;
1658 $realline=$1-1;
1659 if (defined $2) {
1660 $realcnt=$3+1;
1661 } else {
1662 $realcnt=1+1;
1663 }
1664 annotate_reset();
1665 $prev_values = 'E';
1666
1667 %suppress_ifbraces = ();
1668 %suppress_whiletrailers = ();
1669 %suppress_export = ();
1670 next;
1671
1672 # track the line number as we move through the hunk, note that
1673 # new versions of GNU diff omit the leading space on completely
1674 # blank context lines so we need to count that too.
1675 } elsif ($line =~ /^( |\+|$)/) {
1676 $realline++;
1677 $realcnt-- if ($realcnt != 0);
1678
1679 # Measure the line length and indent.
1680 ($length, $indent) = line_stats($rawline);
1681
1682 # Track the previous line.
1683 ($prevline, $stashline) = ($stashline, $line);
1684 ($previndent, $stashindent) = ($stashindent, $indent);
1685 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1686
1687 #warn "line<$line>\n";
1688
1689 } elsif ($realcnt == 1) {
1690 $realcnt--;
1691 }
1692
1693 my $hunk_line = ($realcnt != 0);
1694
1695 #make up the handle for any error we report on this line
1696 $prefix = "$filename:$realline: " if ($emacs && $file);
1697 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1698
1699 $oldhere = $here;
1700 $here = "#$linenr: " if (!$file);
1701 $here = "#$realline: " if ($file);
1702
1703 # extract the filename as it passes
1704 if ($line =~ /^diff --git\s+(\S+)\s+(\S+)$/) {
1705 my $fileold = $1;
1706 my $filenew = $2;
1707
1708 if (defined $fileinfo) {
1709 $fileinfo->{lineend} = $oldhere;
1710 process_end_of_file($fileinfo)
1711 }
1712 $fileold =~ s@^([^/]*)/@@ if (!$file);
1713 $filenew =~ s@^([^/]*)/@@ if (!$file);
1714 $realfile = $filenew;
1715
1716 $fileinfo = {
1717 "isgit" => 1,
1718 "githeader" => 1,
1719 "linestart" => $here,
1720 "lineend" => 0,
1721 "fileold" => $fileold,
1722 "filenew" => $filenew,
1723 "action" => "modified",
1724 "mode" => 0,
1725 "similarity" => 0,
1726 "facts" => {},
1727 };
1728 push @fileinfolist, $fileinfo;
1729 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1730 $line =~ /^(new|deleted) (?:file )?mode\s+([0-7]+)$/) {
1731 $fileinfo->{action} = $1;
1732 $fileinfo->{mode} = oct($2);
1733 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1734 $line =~ /^similarity index (\d+)%/) {
1735 $fileinfo->{similarity} = int($1);
1736 } elsif (defined $fileinfo && $fileinfo->{githeader} &&
1737 $line =~ /^rename (from|to) [\w\/\.\-]+\s*$/) {
1738 $fileinfo->{action} = "renamed";
1739 # For a no-change rename, we'll never have any "+++..."
1740 # lines, so trigger actions now
1741 if ($1 eq "to" && $fileinfo->{similarity} == 100) {
1742 process_start_of_file($fileinfo);
1743 }
1744 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1745 $realfile = $1;
1746 $realfile =~ s@^[^/]*/@@ if (!$file);
1747
1748 if (defined $fileinfo && !$fileinfo->{isgit}) {
1749 $fileinfo->{lineend} = $oldhere;
1750 process_end_of_file($fileinfo);
1751 }
1752
1753 if (!defined $fileinfo || !$fileinfo->{isgit}) {
1754 $fileinfo = {
1755 "isgit" => 0,
1756 "githeader" => 0,
1757 "linestart" => $here,
1758 "lineend" => 0,
1759 "fileold" => $realfile,
1760 "filenew" => $realfile,
1761 "action" => "modified",
1762 "mode" => 0,
1763 "similarity" => 0,
1764 "facts" => {},
1765 };
1766 push @fileinfolist, $fileinfo;
1767 } else {
1768 $fileinfo->{githeader} = 0;
1769 }
1770 process_start_of_file($fileinfo);
1771
1772 next;
1773 }
1774
1775 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1776
1777 my $hereline = "$here\n$rawline\n";
1778 my $herecurr = "$here\n$rawline\n";
1779 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1780
1781 $cnt_lines++ if ($realcnt != 0);
1782
1783 # Only allow Python 3 interpreter
1784 if ($realline == 1 &&
1785 $line =~ /^\+#!\ *\/usr\/bin\/(?:env )?python$/) {
1786 ERROR("please use python3 interpreter\n" . $herecurr);
1787 }
1788
1789 # Accept git diff extended headers as valid patches
1790 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1791 $is_patch = 1;
1792 }
1793
1794 if ($line =~ /^(Author|From): .* via .*<qemu-\w+\@nongnu\.org>/) {
1795 ERROR("Author email address is mangled by the mailing list\n" . $herecurr);
1796 }
1797
1798 #check the patch for a signoff:
1799 if ($line =~ /^\s*signed-off-by:/i) {
1800 # This is a signoff, if ugly, so do not double report.
1801 $signoff++;
1802 $in_commit_log = 0;
1803
1804 if (!($line =~ /^\s*Signed-off-by:/)) {
1805 ERROR("The correct form is \"Signed-off-by\"\n" .
1806 $herecurr);
1807 }
1808 if ($line =~ /^\s*signed-off-by:\S/i) {
1809 ERROR("space required after Signed-off-by:\n" .
1810 $herecurr);
1811 }
1812 }
1813
1814 # Check SPDX-License-Identifier references a permitted license
1815 if (($rawline =~ m,SPDX-License-Identifier: (.*?)(\*/)?\s*$,) &&
1816 $rawline !~ /^-/) {
1817 $fileinfo->{facts}->{sawspdx} = 1;
1818 &checkspdx($realfile, $1);
1819 }
1820
1821 if ($rawline =~ /$LICENSE_BOILERPLATE_RE/) {
1822 $fileinfo->{facts}->{sawboilerplate} = 1;
1823 }
1824
1825 if ($rawline =~ m,(SPDX-[a-zA-Z0-9-_]+):,) {
1826 my $tag = $1;
1827 my @permitted = qw(
1828 SPDX-License-Identifier
1829 );
1830
1831 unless (grep { /^$tag$/ } @permitted) {
1832 ERROR("Tag $tag not permitted in QEMU code, " .
1833 "valid choices are: " .
1834 join(", ", @permitted));
1835 }
1836 }
1837
1838 # Check for wrappage within a valid hunk of the file
1839 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1840 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1841 $herecurr) if (!$emitted_corrupt++);
1842 }
1843
1844 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1845 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1846 $rawline !~ m/^$UTF8*$/) {
1847 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1848
1849 my $blank = copy_spacing($rawline);
1850 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1851 my $hereptr = "$hereline$ptr\n";
1852
1853 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1854 }
1855
1856 if ($rawline =~ m/$UTF8_MOJIBAKE/) {
1857 ERROR("Doubly-encoded UTF-8\n" . $herecurr);
1858 }
1859 # Check if it's the start of a commit log
1860 # (not a header line and we haven't seen the patch filename)
1861 if ($in_header_lines && $realfile =~ /^$/ &&
1862 !($rawline =~ /^\s+\S/ ||
1863 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1864 $in_header_lines = 0;
1865 $in_commit_log = 1;
1866 }
1867
1868 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1869 # declined it, i.e defined some charset where it is missing.
1870 if ($in_header_lines &&
1871 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1872 $1 !~ /utf-8/i) {
1873 $non_utf8_charset = 1;
1874 }
1875
1876 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1877 $rawline =~ /$NON_ASCII_UTF8/) {
1878 WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1879 }
1880
1881 # Check for various typo / spelling mistakes
1882 if (defined($misspellings) &&
1883 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
1884 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
1885 my $typo = $1;
1886 my $blank = copy_spacing($rawline);
1887 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
1888 my $hereptr = "$hereline$ptr\n";
1889 my $typo_fix = $spelling_fix{lc($typo)};
1890 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
1891 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
1892 WARN("'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr);
1893 }
1894 }
1895
1896 # ignore non-hunk lines and lines being removed
1897 next if (!$hunk_line || $line =~ /^-/);
1898
1899 # Check that updating imported files from Linux are not mixed with other changes
1900 if ($realfile =~ /^(linux-headers|include\/standard-headers)\//) {
1901 if (!$in_imported_file) {
1902 WARN("added, moved or deleted file(s) " .
1903 "imported from Linux, are you using " .
1904 "scripts/update-linux-headers.sh?\n" .
1905 $herecurr);
1906 }
1907 $in_imported_file = 1;
1908 } else {
1909 $in_no_imported_file = 1;
1910 }
1911
1912 if (!$reported_mixing_imported_file &&
1913 $in_imported_file && $in_no_imported_file) {
1914 ERROR("headers imported from Linux should be self-" .
1915 "contained in a patch with no other changes\n" .
1916 $herecurr);
1917 $reported_mixing_imported_file = 1;
1918 }
1919
1920 # ignore files that are being periodically imported from Linux
1921 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1922
1923 #trailing whitespace
1924 if ($line =~ /^\+.*\015/) {
1925 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1926 ERROR("DOS line endings\n" . $herevet);
1927
1928 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1929 $realfile =~ /^docs\/.+\.md/) {
1930 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1931 # TODO: properly check we're in a code block
1932 # (surrounding text is 4-column aligned)
1933 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1934 ERROR("code blocks in documentation should have " .
1935 "empty lines with exactly 4 columns of " .
1936 "whitespace\n" . $herevet);
1937 }
1938 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1939 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1940 ERROR("trailing whitespace\n" . $herevet);
1941 $rpt_cleaners = 1;
1942 }
1943
1944 # checks for trace-events files
1945 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1946 if ($rawline =~ /%[-+ 0]*#/) {
1947 ERROR("Don't use '#' flag of printf format ('%#') in " .
1948 "trace-events, use '0x' prefix instead\n" . $herecurr);
1949 } else {
1950 my $hex =
1951 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1952
1953 # don't consider groups split by [.:/ ], like 2A.20:12ab
1954 my $tmpline = $rawline;
1955 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1956
1957 if ($tmpline =~ /(?<!0x)$hex/) {
1958 ERROR("Hex numbers must be prefixed with '0x'\n" .
1959 $herecurr);
1960 }
1961 }
1962 }
1963
1964 # check we are in a valid source file if not then ignore this hunk
1965 next if ($realfile !~ /$SrcFile/);
1966
1967 #90 column limit; exempt URLs, if no other words on line
1968 if ($line =~ /^\+/ &&
1969 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1970 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1971 $length > 80)
1972 {
1973 if ($length > 90) {
1974 ERROR("line over 90 characters\n" . $herecurr);
1975 } else {
1976 WARN("line over 80 characters\n" . $herecurr);
1977 }
1978 }
1979
1980 # check for spaces before a quoted newline
1981 if ($rawline =~ /^.*\".*\s\\n/) {
1982 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1983 }
1984
1985 # check for adding lines without a newline.
1986 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1987 ERROR("adding a line without newline at end of file\n" . $herecurr);
1988 }
1989
1990 # check for RCS/CVS revision markers
1991 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1992 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1993 }
1994
1995 # tabs are only allowed in assembly source code, and in
1996 # some scripts we imported from other projects.
1997 next if ($realfile =~ /\.(s|S)$/);
1998 next if ($realfile =~ /(checkpatch|get_maintainer)\.pl$/);
1999 next if ($realfile =~ /^target\/hexagon\/imported\/*/);
2000
2001 if ($rawline =~ /^\+.*\t/) {
2002 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2003 ERROR("code indent should never use tabs\n" . $herevet);
2004 $rpt_cleaners = 1;
2005 }
2006
2007 # check we are in a valid C source file if not then ignore this hunk
2008 next if ($realfile !~ /\.((h|c)(\.inc)?|cpp)$/);
2009
2010 # Block comment styles
2011
2012 # Block comments use /* on a line of its own
2013 my $commentline = $rawline;
2014 while ($commentline =~ s@^(\+.*)/\*.*\*/@$1@o) { # remove inline /*...*/
2015 }
2016 if ($commentline =~ m@^\+.*/\*\*?+[ \t]*[^ \t]@) { # /* or /** non-blank
2017 WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
2018 }
2019
2020 # Block comments use * on subsequent lines
2021 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2022 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
2023 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2024 $rawline =~ /^\+/ && #line is new
2025 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2026 WARN("Block comments use * on subsequent lines\n" . $hereprev);
2027 }
2028
2029 # Block comments use */ on trailing lines
2030 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2031 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2032 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2033 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2034 WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
2035 }
2036
2037 # Block comment * alignment
2038 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2039 $line =~ /^\+[ \t]*$;/ && #leading comment
2040 $rawline =~ /^\+[ \t]*\*/ && #leading *
2041 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
2042 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
2043 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
2044 my $oldindent;
2045 $prevrawline =~ m@^\+([ \t]*/?)\*@;
2046 if (defined($1)) {
2047 $oldindent = expand_tabs($1);
2048 } else {
2049 $prevrawline =~ m@^\+(.*/?)\*@;
2050 $oldindent = expand_tabs($1);
2051 }
2052 $rawline =~ m@^\+([ \t]*)\*@;
2053 my $newindent = $1;
2054 $newindent = expand_tabs($newindent);
2055 if (length($oldindent) ne length($newindent)) {
2056 WARN("Block comments should align the * on each line\n" . $hereprev);
2057 }
2058 }
2059
2060 # Check for potential 'bare' types
2061 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2062 $realline_next);
2063 if ($realcnt && $line =~ /.\s*\S/) {
2064 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2065 ctx_statement_block($linenr, $realcnt, 0);
2066 $stat =~ s/\n./\n /g;
2067 $cond =~ s/\n./\n /g;
2068
2069 # Find the real next line.
2070 $realline_next = $line_nr_next;
2071 if (defined $realline_next &&
2072 (!defined $lines[$realline_next - 1] ||
2073 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2074 $realline_next++;
2075 }
2076
2077 my $s = $stat;
2078 $s =~ s/{.*$//s;
2079
2080 # Ignore goto labels.
2081 if ($s =~ /$Ident:\*$/s) {
2082
2083 # Ignore functions being called
2084 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2085
2086 } elsif ($s =~ /^.\s*else\b/s) {
2087
2088 # declarations always start with types
2089 } 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) {
2090 my $type = $1;
2091 $type =~ s/\s+/ /g;
2092 possible($type, "A:" . $s);
2093
2094 # definitions in global scope can only start with types
2095 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2096 possible($1, "B:" . $s);
2097 }
2098
2099 # any (foo ... *) is a pointer cast, and foo is a type
2100 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2101 possible($1, "C:" . $s);
2102 }
2103
2104 # Check for any sort of function declaration.
2105 # int foo(something bar, other baz);
2106 # void (*store_gdt)(x86_descr_ptr *);
2107 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2108 my ($name_len) = length($1);
2109
2110 my $ctx = $s;
2111 substr($ctx, 0, $name_len + 1, '');
2112 $ctx =~ s/\)[^\)]*$//;
2113
2114 for my $arg (split(/\s*,\s*/, $ctx)) {
2115 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2116
2117 possible($1, "D:" . $s);
2118 }
2119 }
2120 }
2121
2122 }
2123
2124 #
2125 # Checks which may be anchored in the context.
2126 #
2127
2128 # Check for switch () and associated case and default
2129 # statements should be at the same indent.
2130 if ($line=~/\bswitch\s*\(.*\)/) {
2131 my $err = '';
2132 my $sep = '';
2133 my @ctx = ctx_block_outer($linenr, $realcnt);
2134 shift(@ctx);
2135 for my $ctx (@ctx) {
2136 my ($clen, $cindent) = line_stats($ctx);
2137 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2138 $indent != $cindent) {
2139 $err .= "$sep$ctx\n";
2140 $sep = '';
2141 } else {
2142 $sep = "[...]\n";
2143 }
2144 }
2145 if ($err ne '') {
2146 ERROR("switch and case should be at the same indent\n$hereline$err");
2147 }
2148 }
2149
2150 # if/while/etc brace do not go on next line, unless defining a do while loop,
2151 # or if that brace on the next line is for something else
2152 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2153 my $pre_ctx = "$1$2";
2154
2155 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2156 my $ctx_cnt = $realcnt - $#ctx - 1;
2157 my $ctx = join("\n", @ctx);
2158
2159 my $ctx_ln = $linenr;
2160 my $ctx_skip = $realcnt;
2161
2162 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2163 defined $lines[$ctx_ln - 1] &&
2164 $lines[$ctx_ln - 1] =~ /^-/)) {
2165 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2166 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2167 $ctx_ln++;
2168 }
2169
2170 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2171 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2172
2173 # The length of the "previous line" is checked against 80 because it
2174 # includes the + at the beginning of the line (if the actual line has
2175 # 79 or 80 characters, it is no longer possible to add a space and an
2176 # opening brace there)
2177 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
2178 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
2179 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
2180 ERROR("that open brace { should be on the previous line\n" .
2181 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2182 }
2183 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2184 $ctx =~ /\)\s*\;\s*$/ &&
2185 defined $lines[$ctx_ln - 1])
2186 {
2187 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2188 if ($nindent > $indent) {
2189 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
2190 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2191 }
2192 }
2193 }
2194
2195 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
2196 if ($line =~ /while\s*\((0|false)\);/) {
2197 ERROR("suspicious ; after while (0)\n" . $herecurr);
2198 }
2199
2200 # Check superfluous trailing ';'
2201 if ($line =~ /;;$/) {
2202 ERROR("superfluous trailing semicolon\n" . $herecurr);
2203 }
2204
2205 # Check relative indent for conditionals and blocks.
2206 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2207 my ($s, $c) = ($stat, $cond);
2208
2209 substr($s, 0, length($c), '');
2210
2211 # Make sure we remove the line prefixes as we have
2212 # none on the first line, and are going to re-add them
2213 # where necessary.
2214 $s =~ s/\n./\n/gs;
2215
2216 # Find out how long the conditional actually is.
2217 my @newlines = ($c =~ /\n/gs);
2218 my $cond_lines = 1 + $#newlines;
2219
2220 # We want to check the first line inside the block
2221 # starting at the end of the conditional, so remove:
2222 # 1) any blank line termination
2223 # 2) any opening brace { on end of the line
2224 # 3) any do (...) {
2225 my $continuation = 0;
2226 my $check = 0;
2227 $s =~ s/^.*\bdo\b//;
2228 $s =~ s/^\s*\{//;
2229 if ($s =~ s/^\s*\\//) {
2230 $continuation = 1;
2231 }
2232 if ($s =~ s/^\s*?\n//) {
2233 $check = 1;
2234 $cond_lines++;
2235 }
2236
2237 # Also ignore a loop construct at the end of a
2238 # preprocessor statement.
2239 if (($prevline =~ /^.\s*#\s*define\s/ ||
2240 $prevline =~ /\\\s*$/) && $continuation == 0) {
2241 $check = 0;
2242 }
2243
2244 my $cond_ptr = -1;
2245 $continuation = 0;
2246 while ($cond_ptr != $cond_lines) {
2247 $cond_ptr = $cond_lines;
2248
2249 # If we see an #else/#elif then the code
2250 # is not linear.
2251 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2252 $check = 0;
2253 }
2254
2255 # Ignore:
2256 # 1) blank lines, they should be at 0,
2257 # 2) preprocessor lines, and
2258 # 3) labels.
2259 if ($continuation ||
2260 $s =~ /^\s*?\n/ ||
2261 $s =~ /^\s*#\s*?/ ||
2262 $s =~ /^\s*$Ident\s*:/) {
2263 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2264 if ($s =~ s/^.*?\n//) {
2265 $cond_lines++;
2266 }
2267 }
2268 }
2269
2270 my (undef, $sindent) = line_stats("+" . $s);
2271 my $stat_real = raw_line($linenr, $cond_lines);
2272
2273 # Check if either of these lines are modified, else
2274 # this is not this patch's fault.
2275 if (!defined($stat_real) ||
2276 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2277 $check = 0;
2278 }
2279 if (defined($stat_real) && $cond_lines > 1) {
2280 $stat_real = "[...]\n$stat_real";
2281 }
2282
2283 #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";
2284
2285 if ($check && (($sindent % 4) != 0 ||
2286 ($sindent <= $indent &&
2287 $s !~ /^\s*(?:\}|\{|else\b)/))) {
2288 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2289 }
2290 }
2291
2292 # Track the 'values' across context and added lines.
2293 my $opline = $line; $opline =~ s/^./ /;
2294 my ($curr_values, $curr_vars) =
2295 annotate_values($opline . "\n", $prev_values);
2296 $curr_values = $prev_values . $curr_values;
2297 if ($dbg_values) {
2298 my $outline = $opline; $outline =~ s/\t/ /g;
2299 print "$linenr > .$outline\n";
2300 print "$linenr > $curr_values\n";
2301 print "$linenr > $curr_vars\n";
2302 }
2303 $prev_values = substr($curr_values, -1);
2304
2305 #ignore lines not being added
2306 if ($line=~/^[^\+]/) {next;}
2307
2308 # TEST: allow direct testing of the type matcher.
2309 if ($dbg_type) {
2310 if ($line =~ /^.\s*$Declare\s*$/) {
2311 ERROR("TEST: is type\n" . $herecurr);
2312 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2313 ERROR("TEST: is not type ($1 is)\n". $herecurr);
2314 }
2315 next;
2316 }
2317 # TEST: allow direct testing of the attribute matcher.
2318 if ($dbg_attr) {
2319 if ($line =~ /^.\s*$Modifier\s*$/) {
2320 ERROR("TEST: is attr\n" . $herecurr);
2321 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2322 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
2323 }
2324 next;
2325 }
2326
2327 # check for initialisation to aggregates open brace on the next line
2328 if ($line =~ /^.\s*\{/ &&
2329 $prevline =~ /(?:^|[^=])=\s*$/) {
2330 ERROR("that open brace { should be on the previous line\n" . $hereprev);
2331 }
2332
2333 #
2334 # Checks which are anchored on the added line.
2335 #
2336
2337 # check for malformed paths in #include statements (uses RAW line)
2338 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2339 my $path = $1;
2340 if ($path =~ m{//}) {
2341 ERROR("malformed #include filename\n" .
2342 $herecurr);
2343 }
2344 }
2345
2346 # no C99 // comments
2347 if ($line =~ m{//} &&
2348 $rawline !~ m{// SPDX-License-Identifier: }) {
2349 ERROR("do not use C99 // comments\n" . $herecurr);
2350 }
2351 # Remove C99 comments.
2352 $line =~ s@//.*@@;
2353 $opline =~ s@//.*@@;
2354
2355 # check for global initialisers.
2356 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
2357 ERROR("do not initialise globals to 0 or NULL\n" .
2358 $herecurr);
2359 }
2360 # check for static initialisers.
2361 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2362 ERROR("do not initialise statics to 0 or NULL\n" .
2363 $herecurr);
2364 }
2365
2366 # * goes on variable not on type
2367 # (char*[ const])
2368 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
2369 my ($from, $to) = ($1, $1);
2370
2371 # Should start with a space.
2372 $to =~ s/^(\S)/ $1/;
2373 # Should not end with a space.
2374 $to =~ s/\s+$//;
2375 # '*'s should not have spaces between.
2376 while ($to =~ s/\*\s+\*/\*\*/) {
2377 }
2378
2379 #print "from<$from> to<$to>\n";
2380 if ($from ne $to) {
2381 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
2382 }
2383 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
2384 my ($from, $to, $ident) = ($1, $1, $2);
2385
2386 # Should start with a space.
2387 $to =~ s/^(\S)/ $1/;
2388 # Should not end with a space.
2389 $to =~ s/\s+$//;
2390 # '*'s should not have spaces between.
2391 while ($to =~ s/\*\s+\*/\*\*/) {
2392 }
2393 # Modifiers should have spaces.
2394 $to =~ s/(\b$Modifier$)/$1 /;
2395
2396 #print "from<$from> to<$to> ident<$ident>\n";
2397 if ($from ne $to && $ident !~ /^$Modifier$/) {
2398 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
2399 }
2400 }
2401
2402 # function brace can't be on same line, except for #defines of do while,
2403 # or if closed on same line
2404 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2405 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
2406 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
2407 }
2408
2409 # open braces for enum, union and struct go on the same line.
2410 if ($line =~ /^.\s*\{/ &&
2411 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2412 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
2413 }
2414
2415 # missing space after union, struct or enum definition
2416 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
2417 ERROR("missing space after $1 definition\n" . $herecurr);
2418 }
2419
2420 # check for spacing round square brackets; allowed:
2421 # 1. with a type on the left -- int [] a;
2422 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2423 # 3. inside a curly brace -- = { [0...10] = 5 }
2424 # 4. after a comma -- [1] = 5, [2] = 6
2425 # 5. in a macro definition -- #define abc(x) [x] = y
2426 my $cpp = $realfile =~ /(\.cpp)$/;
2427 while (!$cpp && $line =~ /(.*?\s)\[/g) {
2428 my ($where, $prefix) = ($-[1], $1);
2429 if ($prefix !~ /$Type\s+$/ &&
2430 ($where != 0 || $prefix !~ /^.\s+$/) &&
2431 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
2432 $prefix !~ /[,{:]\s+$/) {
2433 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
2434 }
2435 }
2436
2437 # check for spaces between functions and their parentheses.
2438 while ($line =~ /($Ident)\s+\(/g) {
2439 my $name = $1;
2440 my $ctx_before = substr($line, 0, $-[1]);
2441 my $ctx = "$ctx_before$name";
2442
2443 # Ignore those directives where spaces _are_ permitted.
2444 if ($name =~ /^(?:
2445 if|for|while|switch|return|case|
2446 volatile|__volatile__|coroutine_fn|
2447 coroutine_mixed_fn|no_coroutine_fn|
2448 __attribute__|format|__extension__|
2449 asm|__asm__)$/x)
2450 {
2451
2452 # Ignore 'catch (...)' in C++
2453 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
2454
2455 # cpp #define statements have non-optional spaces, ie
2456 # if there is a space between the name and the open
2457 # parenthesis it is simply not a parameter group.
2458 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2459
2460 # cpp #elif statement condition may start with a (
2461 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2462
2463 # If this whole things ends with a type its most
2464 # likely a typedef for a function.
2465 } elsif ($ctx =~ /$Type$/) {
2466
2467 } else {
2468 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
2469 }
2470 }
2471 # Check operator spacing.
2472 if (!($line=~/\#\s*(include|import)/)) {
2473 my $ops = qr{
2474 <<=|>>=|<=|>=|==|!=|
2475 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2476 =>|->|<<|>>|<|>|=|!|~|
2477 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2478 \?|::|:
2479 }x;
2480 my @elements = split(/($ops|;)/, $opline);
2481 my $off = 0;
2482
2483 my $blank = copy_spacing($opline);
2484
2485 for (my $n = 0; $n < $#elements; $n += 2) {
2486 $off += length($elements[$n]);
2487
2488 # Pick up the preceding and succeeding characters.
2489 my $ca = substr($opline, 0, $off);
2490 my $cc = '';
2491 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2492 $cc = substr($opline, $off + length($elements[$n + 1]));
2493 }
2494 my $cb = "$ca$;$cc";
2495
2496 my $a = '';
2497 $a = 'V' if ($elements[$n] ne '');
2498 $a = 'W' if ($elements[$n] =~ /\s$/);
2499 $a = 'C' if ($elements[$n] =~ /$;$/);
2500 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2501 $a = 'O' if ($elements[$n] eq '');
2502 $a = 'E' if ($ca =~ /^\s*$/);
2503
2504 my $op = $elements[$n + 1];
2505
2506 my $c = '';
2507 if (defined $elements[$n + 2]) {
2508 $c = 'V' if ($elements[$n + 2] ne '');
2509 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2510 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2511 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2512 $c = 'O' if ($elements[$n + 2] eq '');
2513 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2514 } else {
2515 $c = 'E';
2516 }
2517
2518 my $ctx = "${a}x${c}";
2519
2520 my $at = "(ctx:$ctx)";
2521
2522 my $ptr = substr($blank, 0, $off) . "^";
2523 my $hereptr = "$hereline$ptr\n";
2524
2525 # Pull out the value of this operator.
2526 my $op_type = substr($curr_values, $off + 1, 1);
2527
2528 # Get the full operator variant.
2529 my $opv = $op . substr($curr_vars, $off, 1);
2530
2531 # Ignore operators passed as parameters.
2532 if ($op_type ne 'V' &&
2533 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2534
2535 # # Ignore comments
2536 # } elsif ($op =~ /^$;+$/) {
2537
2538 # ; should have either the end of line or a space or \ after it
2539 } elsif ($op eq ';') {
2540 if ($ctx !~ /.x[WEBC]/ &&
2541 $cc !~ /^\\/ && $cc !~ /^;/) {
2542 ERROR("space required after that '$op' $at\n" . $hereptr);
2543 }
2544
2545 # // is a comment
2546 } elsif ($op eq '//') {
2547
2548 # Ignore : used in class declaration in C++
2549 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2550 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2551
2552 # No spaces for:
2553 # ->
2554 # : when part of a bitfield
2555 } elsif ($op eq '->' || $opv eq ':B') {
2556 if ($ctx =~ /Wx.|.xW/) {
2557 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2558 }
2559
2560 # , must have a space on the right.
2561 # not required when having a single },{ on one line
2562 } elsif ($op eq ',') {
2563 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2564 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2565 ERROR("space required after that '$op' $at\n" . $hereptr);
2566 }
2567
2568 # '*' as part of a type definition -- reported already.
2569 } elsif ($opv eq '*_') {
2570 #warn "'*' is part of type\n";
2571
2572 # unary operators should have a space before and
2573 # none after. May be left adjacent to another
2574 # unary operator, or a cast
2575 } elsif ($op eq '!' || $op eq '~' ||
2576 $opv eq '*U' || $opv eq '-U' ||
2577 $opv eq '&U' || $opv eq '&&U') {
2578 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2579 # '~' used as a name of Destructor
2580
2581 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2582 ERROR("space required before that '$op' $at\n" . $hereptr);
2583 }
2584 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2585 # A unary '*' may be const
2586
2587 } elsif ($ctx =~ /.xW/) {
2588 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2589 }
2590
2591 # unary ++ and unary -- are allowed no space on one side.
2592 } elsif ($op eq '++' or $op eq '--') {
2593 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2594 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2595 }
2596 if ($ctx =~ /Wx[BE]/ ||
2597 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2598 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2599 }
2600 if ($ctx =~ /ExW/) {
2601 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2602 }
2603
2604 # A colon needs no spaces before when it is
2605 # terminating a case value or a label.
2606 } elsif ($opv eq ':C' || $opv eq ':L') {
2607 if ($ctx =~ /Wx./) {
2608 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2609 }
2610
2611 # All the others need spaces both sides.
2612 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2613 my $ok = 0;
2614
2615 if ($realfile =~ /\.cpp|\.h$/) {
2616 # Ignore template arguments <...> in C++
2617 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2618 $ok = 1;
2619 }
2620
2621 # Ignore :: in C++
2622 if ($op eq '::') {
2623 $ok = 1;
2624 }
2625
2626 # Ignore * in C++: templates and
2627 # pointer types are incorrectly
2628 # flagged. Example:
2629 # static_cast<T*>
2630 if ($op eq '*') {
2631 $ok = 1;
2632 }
2633
2634 # Ignore & in C++: & means a
2635 # reference, and this create
2636 # issues with some constructions.
2637 # Example:
2638 # auto &[first, second] = pair;
2639 if ($op eq '&') {
2640 $ok = 1;
2641 }
2642
2643 # Ignore >> in C++
2644 # checkpatch is confused by
2645 # >> closing templates. Example:
2646 # vector<pair<A, B>>
2647 if ($op eq '>>') {
2648 $ok = 1;
2649 }
2650 }
2651
2652 # Ignore email addresses <foo@bar>
2653 if (($op eq '<' &&
2654 $cc =~ /^\S+\@\S+>/) ||
2655 ($op eq '>' &&
2656 $ca =~ /<\S+\@\S+$/))
2657 {
2658 $ok = 1;
2659 }
2660
2661 # Ignore ?:
2662 if (($opv eq ':O' && $ca =~ /\?$/) ||
2663 ($op eq '?' && $cc =~ /^:/)) {
2664 $ok = 1;
2665 }
2666
2667 if ($ok == 0) {
2668 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2669 }
2670 }
2671 $off += length($elements[$n + 1]);
2672 }
2673 }
2674
2675 #need space before brace following if, while, etc
2676 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2677 $line =~ /do\{/) {
2678 ERROR("space required before the open brace '{'\n" . $herecurr);
2679 }
2680
2681 # closing brace should have a space following it when it has anything
2682 # on the line
2683 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2684 ERROR("space required after that close brace '}'\n" . $herecurr);
2685 }
2686
2687 # check spacing on square brackets
2688 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2689 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2690 }
2691 if ($line =~ /\s\]/) {
2692 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2693 }
2694
2695 # check spacing on parentheses
2696 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2697 $line !~ /for\s*\(\s+;/) {
2698 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2699 }
2700 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2701 $line !~ /for\s*\(.*;\s+\)/ &&
2702 $line !~ /:\s+\)/) {
2703 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2704 }
2705
2706 # Return is not a function.
2707 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2708 my $spacing = $1;
2709 my $value = $2;
2710
2711 # Flatten any parentheses
2712 $value =~ s/\(/ \(/g;
2713 $value =~ s/\)/\) /g;
2714 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2715 $value !~ /(?:$Ident|-?$Constant)\s*
2716 $Compare\s*
2717 (?:$Ident|-?$Constant)/x &&
2718 $value =~ s/\([^\(\)]*\)/1/) {
2719 }
2720 #print "value<$value>\n";
2721 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/ &&
2722 $line =~ /;$/) {
2723 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2724
2725 } elsif ($spacing !~ /\s+/) {
2726 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2727 }
2728 }
2729 # Return of what appears to be an errno should normally be -'ve
2730 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2731 my $name = $1;
2732 if ($name ne 'EOF' && $name ne 'ERROR') {
2733 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2734 }
2735 }
2736
2737 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2738 $line !~ /^.typedef/) {
2739 ERROR("named $1 should be typedefed separately\n" . $herecurr);
2740 }
2741
2742 # Need a space before open parenthesis after if, while etc
2743 if ($line=~/\b(if|while|for|switch)\(/) {
2744 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2745 }
2746
2747 # Check for illegal assignment in if conditional -- and check for trailing
2748 # statements after the conditional.
2749 if ($line =~ /do\s*(?!{)/) {
2750 my ($stat_next) = ctx_statement_block($line_nr_next,
2751 $remain_next, $off_next);
2752 $stat_next =~ s/\n./\n /g;
2753 ##print "stat<$stat> stat_next<$stat_next>\n";
2754
2755 if ($stat_next =~ /^\s*while\b/) {
2756 # If the statement carries leading newlines,
2757 # then count those as offsets.
2758 my ($whitespace) =
2759 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2760 my $offset =
2761 statement_rawlines($whitespace) - 1;
2762
2763 $suppress_whiletrailers{$line_nr_next +
2764 $offset} = 1;
2765 }
2766 }
2767 if (!defined $suppress_whiletrailers{$linenr} &&
2768 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2769 my ($s, $c) = ($stat, $cond);
2770
2771 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2772 ERROR("do not use assignment in if condition\n" . $herecurr);
2773 }
2774
2775 # Find out what is on the end of the line after the
2776 # conditional.
2777 substr($s, 0, length($c), '');
2778 $s =~ s/\n.*//g;
2779 $s =~ s/$;//g; # Remove any comments
2780 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2781 $c !~ /}\s*while\s*/)
2782 {
2783 # Find out how long the conditional actually is.
2784 my @newlines = ($c =~ /\n/gs);
2785 my $cond_lines = 1 + $#newlines;
2786 my $stat_real = '';
2787
2788 $stat_real = raw_line($linenr, $cond_lines)
2789 . "\n" if ($cond_lines);
2790 if (defined($stat_real) && $cond_lines > 1) {
2791 $stat_real = "[...]\n$stat_real";
2792 }
2793
2794 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2795 }
2796 }
2797
2798 # Check for bitwise tests written as boolean
2799 if ($line =~ /
2800 (?:
2801 (?:\[|\(|\&\&|\|\|)
2802 \s*0[xX][0-9]+\s*
2803 (?:\&\&|\|\|)
2804 |
2805 (?:\&\&|\|\|)
2806 \s*0[xX][0-9]+\s*
2807 (?:\&\&|\|\||\)|\])
2808 )/x)
2809 {
2810 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2811 }
2812
2813 # if and else should not have general statements after it
2814 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2815 my $s = $1;
2816 $s =~ s/$;//g; # Remove any comments
2817 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2818 ERROR("trailing statements should be on next line\n" . $herecurr);
2819 }
2820 }
2821 # if should not continue a brace
2822 if ($line =~ /}\s*if\b/) {
2823 ERROR("trailing statements should be on next line\n" .
2824 $herecurr);
2825 }
2826 # case and default should not have general statements after them
2827 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2828 $line !~ /\G(?:
2829 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2830 \s*return\s+
2831 )/xg)
2832 {
2833 ERROR("trailing statements should be on next line\n" . $herecurr);
2834 }
2835
2836 # Check for }<nl>else {, these must be at the same
2837 # indent level to be relevant to each other.
2838 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2839 $previndent == $indent) {
2840 ERROR("else should follow close brace '}'\n" . $hereprev);
2841 }
2842
2843 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2844 $previndent == $indent) {
2845 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2846
2847 # Find out what is on the end of the line after the
2848 # conditional.
2849 substr($s, 0, length($c), '');
2850 $s =~ s/\n.*//g;
2851
2852 if ($s =~ /^\s*;/) {
2853 ERROR("while should follow close brace '}'\n" . $hereprev);
2854 }
2855 }
2856
2857 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2858 # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2859 # print "No studly caps, use _\n";
2860 # print "$herecurr";
2861 # $clean = 0;
2862 # }
2863
2864 #no spaces allowed after \ in define
2865 if ($line=~/\#\s*define.*\\\s$/) {
2866 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2867 }
2868
2869 # multi-statement macros should be enclosed in a do while loop, grab the
2870 # first statement and ensure its the whole macro if its not enclosed
2871 # in a known good container
2872 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2873 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2874 my $ln = $linenr;
2875 my $cnt = $realcnt;
2876 my ($off, $dstat, $dcond, $rest);
2877 my $ctx = '';
2878
2879 my $args = defined($1);
2880
2881 # Find the end of the macro and limit our statement
2882 # search to that.
2883 while ($cnt > 0 && defined $lines[$ln - 1] &&
2884 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2885 {
2886 $ctx .= $rawlines[$ln - 1] . "\n";
2887 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2888 $ln++;
2889 }
2890 $ctx .= $rawlines[$ln - 1];
2891
2892 ($dstat, $dcond, $ln, $cnt, $off) =
2893 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2894 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2895 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2896
2897 # Extract the remainder of the define (if any) and
2898 # rip off surrounding spaces, and trailing \'s.
2899 $rest = '';
2900 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2901 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2902 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2903 $rest .= substr($lines[$ln - 1], $off) . "\n";
2904 $cnt--;
2905 }
2906 $ln++;
2907 $off = 0;
2908 }
2909 $rest =~ s/\\\n.//g;
2910 $rest =~ s/^\s*//s;
2911 $rest =~ s/\s*$//s;
2912
2913 # Clean up the original statement.
2914 if ($args) {
2915 substr($dstat, 0, length($dcond), '');
2916 } else {
2917 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2918 }
2919 $dstat =~ s/$;//g;
2920 $dstat =~ s/\\\n.//g;
2921 $dstat =~ s/^\s*//s;
2922 $dstat =~ s/\s*$//s;
2923
2924 # Flatten any parentheses and braces
2925 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2926 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2927 $dstat =~ s/\[[^\{\}]*\]/1/)
2928 {
2929 }
2930
2931 my $exceptions = qr{
2932 $Declare|
2933 module_param_named|
2934 MODULE_PARAM_DESC|
2935 DECLARE_PER_CPU|
2936 DEFINE_PER_CPU|
2937 __typeof__\(|
2938 union|
2939 struct|
2940 \.$Ident\s*=\s*|
2941 ^\"|\"$
2942 }x;
2943 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2944 if ($rest ne '' && $rest ne ',') {
2945 if ($rest !~ /while\s*\(/ &&
2946 $dstat !~ /$exceptions/)
2947 {
2948 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2949 }
2950
2951 } elsif ($ctx !~ /;/) {
2952 if ($dstat ne '' &&
2953 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2954 $dstat !~ /$exceptions/ &&
2955 $dstat !~ /^\.$Ident\s*=/ &&
2956 $dstat =~ /$Operators/)
2957 {
2958 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2959 }
2960 }
2961 }
2962
2963 # check for missing bracing around if etc
2964 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2965 $line !~ /\#\s*if/) {
2966 my $allowed = 0;
2967
2968 # Check the pre-context.
2969 if ($line =~ /(\}.*?)$/) {
2970 my $pre = $1;
2971
2972 if ($line !~ /else/) {
2973 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2974 if $dbg_adv_apw;
2975 $allowed = 1;
2976 }
2977 }
2978 my ($level, $endln, @chunks) =
2979 ctx_statement_full($linenr, $realcnt, 1);
2980 if ($dbg_adv_apw) {
2981 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2982 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2983 if $#chunks >= 1;
2984 }
2985 if ($#chunks >= 0 && $level == 0) {
2986 my $seen = 0;
2987 my $herectx = $here . "\n";
2988 my $ln = $linenr - 1;
2989 for my $chunk (@chunks) {
2990 my ($cond, $block) = @{$chunk};
2991
2992 # If the condition carries leading newlines, then count those as offsets.
2993 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2994 my $offset = statement_rawlines($whitespace) - 1;
2995
2996 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2997
2998 # We have looked at and allowed this specific line.
2999 $suppress_ifbraces{$ln + $offset} = 1;
3000
3001 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3002 $ln += statement_rawlines($block) - 1;
3003
3004 substr($block, 0, length($cond), '');
3005
3006 my $spaced_block = $block;
3007 $spaced_block =~ s/\n\+/ /g;
3008
3009 $seen++ if ($spaced_block =~ /^\s*\{/);
3010
3011 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
3012 if $dbg_adv_apw;
3013 if (statement_lines($cond) > 1) {
3014 print "APW: ALLOWED: cond<$cond>\n"
3015 if $dbg_adv_apw;
3016 $allowed = 1;
3017 }
3018 if ($block =~/\b(?:if|for|while)\b/) {
3019 print "APW: ALLOWED: block<$block>\n"
3020 if $dbg_adv_apw;
3021 $allowed = 1;
3022 }
3023 if (statement_block_size($block) > 1) {
3024 print "APW: ALLOWED: lines block<$block>\n"
3025 if $dbg_adv_apw;
3026 $allowed = 1;
3027 }
3028 }
3029 if ($seen != ($#chunks + 1) && !$allowed) {
3030 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
3031 }
3032 }
3033 }
3034 if (!defined $suppress_ifbraces{$linenr - 1} &&
3035 $line =~ /\b(if|while|for|else)\b/ &&
3036 $line !~ /\#\s*if/ &&
3037 $line !~ /\#\s*else/) {
3038 my $allowed = 0;
3039
3040 # Check the pre-context.
3041 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3042 my $pre = $1;
3043
3044 if ($line !~ /else/) {
3045 print "APW: ALLOWED: pre<$pre> line<$line>\n"
3046 if $dbg_adv_apw;
3047 $allowed = 1;
3048 }
3049 }
3050
3051 my ($level, $endln, @chunks) =
3052 ctx_statement_full($linenr, $realcnt, $-[0]);
3053
3054 # Check the condition.
3055 my ($cond, $block) = @{$chunks[0]};
3056 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
3057 if $dbg_adv_checking;
3058 if (defined $cond) {
3059 substr($block, 0, length($cond), '');
3060 }
3061 if (statement_lines($cond) > 1) {
3062 print "APW: ALLOWED: cond<$cond>\n"
3063 if $dbg_adv_apw;
3064 $allowed = 1;
3065 }
3066 if ($block =~/\b(?:if|for|while)\b/) {
3067 print "APW: ALLOWED: block<$block>\n"
3068 if $dbg_adv_apw;
3069 $allowed = 1;
3070 }
3071 if (statement_block_size($block) > 1) {
3072 print "APW: ALLOWED: lines block<$block>\n"
3073 if $dbg_adv_apw;
3074 $allowed = 1;
3075 }
3076 # Check the post-context.
3077 if (defined $chunks[1]) {
3078 my ($cond, $block) = @{$chunks[1]};
3079 if (defined $cond) {
3080 substr($block, 0, length($cond), '');
3081 }
3082 if ($block =~ /^\s*\{/) {
3083 print "APW: ALLOWED: chunk-1 block<$block>\n"
3084 if $dbg_adv_apw;
3085 $allowed = 1;
3086 }
3087 }
3088 print "DCS: level=$level block<$block> allowed=$allowed\n"
3089 if $dbg_adv_dcs;
3090 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
3091 my $herectx = $here . "\n";;
3092 my $cnt = statement_rawlines($block);
3093
3094 for (my $n = 0; $n < $cnt; $n++) {
3095 $herectx .= raw_line($linenr, $n) . "\n";;
3096 }
3097
3098 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
3099 }
3100 }
3101
3102 # no volatiles please
3103 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3104 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
3105 $line !~ /sig_atomic_t/ &&
3106 !ctx_has_comment($first_line, $linenr)) {
3107 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
3108 ERROR($msg);
3109 }
3110
3111 # warn about #if 0
3112 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3113 ERROR("if this code is redundant consider removing it\n" .
3114 $herecurr);
3115 }
3116
3117 # check for needless g_free() checks
3118 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
3119 my $expr = $1;
3120 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
3121 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
3122 }
3123 }
3124
3125 # warn about #ifdefs in C files
3126 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3127 # print "#ifdef in C files should be avoided\n";
3128 # print "$herecurr";
3129 # $clean = 0;
3130 # }
3131
3132 # warn about spacing in #ifdefs
3133 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3134 ERROR("exactly one space required after that #$1\n" . $herecurr);
3135 }
3136 # check for memory barriers without a comment.
3137 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
3138 if (!ctx_has_comment($first_line, $linenr)) {
3139 ERROR("memory barrier without comment\n" . $herecurr);
3140 }
3141 }
3142 # check of hardware specific defines
3143 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
3144 # where they might be necessary.
3145 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
3146 WARN("architecture specific defines should be avoided\n" . $herecurr);
3147 }
3148
3149 # Check that the storage class is at the beginning of a declaration
3150 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
3151 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
3152 }
3153
3154 # check the location of the inline attribute, that it is between
3155 # storage class and type.
3156 if ($line =~ /\b$Type\s+$Inline\b/ ||
3157 $line =~ /\b$Inline\s+$Storage\b/) {
3158 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
3159 }
3160
3161 # check for sizeof(&)
3162 if ($line =~ /\bsizeof\s*\(\s*\&/) {
3163 ERROR("sizeof(& should be avoided\n" . $herecurr);
3164 }
3165
3166 # check for new externs in .c files.
3167 if ($realfile =~ /\.c$/ && defined $stat &&
3168 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
3169 {
3170 my $function_name = $1;
3171 my $paren_space = $2;
3172
3173 my $s = $stat;
3174 if (defined $cond) {
3175 substr($s, 0, length($cond), '');
3176 }
3177 if ($s =~ /^\s*;/ &&
3178 $function_name ne 'uninitialized_var')
3179 {
3180 ERROR("externs should be avoided in .c files\n" . $herecurr);
3181 }
3182
3183 if ($paren_space =~ /\n/) {
3184 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
3185 }
3186
3187 } elsif ($realfile =~ /\.c$/ && defined $stat &&
3188 $stat =~ /^.\s*extern\s+/)
3189 {
3190 ERROR("externs should be avoided in .c files\n" . $herecurr);
3191 }
3192
3193 # check for pointless casting of g_malloc return
3194 if ($line =~ /\*\s*\)\s*g_(try|)(m|re)alloc(0?)(_n)?\b/) {
3195 if ($2 eq 'm') {
3196 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
3197 } else {
3198 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
3199 }
3200 }
3201
3202 # check for gcc specific __FUNCTION__
3203 if ($line =~ /__FUNCTION__/) {
3204 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
3205 }
3206
3207 # recommend g_path_get_* over g_strdup(basename/dirname(...))
3208 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
3209 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
3210 }
3211
3212 # enforce g_memdup2() over g_memdup()
3213 if ($line =~ /\bg_memdup\s*\(/) {
3214 ERROR("use g_memdup2() instead of unsafe g_memdup()\n" . $herecurr);
3215 }
3216
3217 # recommend qemu_strto* over strto* for numeric conversions
3218 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
3219 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
3220 }
3221 # recommend sigaction over signal for portability, when establishing a handler
3222 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
3223 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
3224 }
3225 # recommend aio_bh_new_guarded instead of legacy qemu_bh_new / qemu_bh_new_guarded
3226 if ($realfile =~ /.*\/hw\/.*/ && $line =~ /\bqemu_bh_new(_guarded)?\s*\(/) {
3227 ERROR("use aio_bh_new_guarded() instead of qemu_bh_new*() to avoid reentrancy problems\n" . $herecurr);
3228 }
3229 # recommend aio_bh_new_guarded instead of aio_bh_new
3230 if ($realfile =~ /.*\/hw\/.*/ && $line =~ /\baio_bh_new\s*\(/) {
3231 ERROR("use aio_bh_new_guarded() instead of aio_bh_new() to avoid reentrancy problems\n" . $herecurr);
3232 }
3233 # check for DEVICE_NATIVE_ENDIAN, use explicit endianness instead
3234 if ($line =~ /\bDEVICE_NATIVE_ENDIAN\b/) {
3235 ERROR("DEVICE_NATIVE_ENDIAN is not allowed, use DEVICE_LITTLE_ENDIAN or DEVICE_BIG_ENDIAN instead\n" . $herecurr);
3236 }
3237 # check for module_init(), use category-specific init macros explicitly please
3238 if ($line =~ /^module_init\s*\(/) {
3239 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
3240 }
3241 # check for various ops structs, ensure they are const.
3242 my $struct_ops = qr{AIOCBInfo|
3243 BdrvActionOps|
3244 BlockDevOps|
3245 BlockJobDriver|
3246 DisplayChangeListenerOps|
3247 GraphicHwOps|
3248 IDEDMAOps|
3249 KVMCapabilityInfo|
3250 MemoryRegionIOMMUOps|
3251 MemoryRegionOps|
3252 MemoryRegionPortio|
3253 QEMUFileOps|
3254 SCSIBusInfo|
3255 SCSIReqOps|
3256 Spice[A-Z][a-zA-Z0-9]*Interface|
3257 TypeInfo|
3258 USBDesc[A-Z][a-zA-Z0-9]*|
3259 VhostOps|
3260 VMStateDescription|
3261 VMStateInfo}x;
3262 if ($line !~ /\bconst\b/ &&
3263 $line =~ /\b($struct_ops)\b.*=/) {
3264 ERROR("initializer for struct $1 should normally be const\n" .
3265 $herecurr);
3266 }
3267
3268 # format strings checks
3269 my $string;
3270 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
3271 $string = substr($rawline, $-[1], $+[1] - $-[1]);
3272 $string =~ s/%%/__/g;
3273 # check for %L{u,d,i} in strings
3274 if ($string =~ /(?<!%)%L[udi]/) {
3275 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
3276 }
3277 # check for %# or %0# in printf-style format strings
3278 if ($string =~ /(?<!%)%0?#/) {
3279 ERROR("Don't use '#' flag of printf format " .
3280 "('%#') in format strings, use '0x' " .
3281 "prefix instead\n" . $herecurr);
3282 }
3283 }
3284
3285 # QEMU specific tests
3286 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
3287 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
3288 }
3289
3290 # Qemu error function tests
3291
3292 # Find newlines in error messages
3293 my $qemu_error_funcs = qr{error_setg|
3294 error_setg_errno|
3295 error_setg_win32|
3296 error_setg_file_open|
3297 error_set|
3298 error_prepend|
3299 warn_reportf_err|
3300 error_reportf_err|
3301 error_vreport|
3302 warn_vreport|
3303 info_vreport|
3304 error_report|
3305 warn_report|
3306 info_report|
3307 g_test_message}x;
3308
3309 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
3310 ERROR("Error messages should not contain newlines\n" . $herecurr);
3311 }
3312
3313 # Continue checking for error messages that contains newlines.
3314 # This check handles cases where string literals are spread
3315 # over multiple lines.
3316 # Example:
3317 # error_report("Error msg line #1"
3318 # "Error msg line #2\n");
3319 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
3320 my $continued_str_literal = qr{\+\s*\".*\"};
3321
3322 if ($rawline =~ /$quoted_newline_regex/) {
3323 # Backtrack to first line that does not contain only
3324 # a quoted literal and assume that it is the start
3325 # of the statement.
3326 my $i = $linenr - 2;
3327
3328 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
3329 $i--;
3330 }
3331
3332 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
3333 ERROR("Error messages should not contain newlines\n" . $herecurr);
3334 }
3335 }
3336
3337 # check for non-portable libc calls that have portable alternatives in QEMU
3338 if ($line =~ /\bffs\(/) {
3339 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
3340 }
3341 if ($line =~ /\bffsl\(/) {
3342 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
3343 }
3344 if ($line =~ /\bffsll\(/) {
3345 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
3346 }
3347 if ($line =~ /\bbzero\(/) {
3348 ERROR("use memset() instead of bzero()\n" . $herecurr);
3349 }
3350 if ($line =~ /\bgetpagesize\(\)/) {
3351 ERROR("use qemu_real_host_page_size() instead of getpagesize()\n" . $herecurr);
3352 }
3353 if ($line =~ /\bsysconf\(_SC_PAGESIZE\)/) {
3354 ERROR("use qemu_real_host_page_size() instead of sysconf(_SC_PAGESIZE)\n" . $herecurr);
3355 }
3356 if ($line =~ /\b(g_)?assert\(0\)/) {
3357 ERROR("use g_assert_not_reached() instead of assert(0)\n" . $herecurr);
3358 }
3359 if ($line =~ /\b(g_)?assert\(false\)/) {
3360 ERROR("use g_assert_not_reached() instead of assert(false)\n" .
3361 $herecurr);
3362 }
3363 if ($line =~ /\bstrerrorname_np\(/) {
3364 ERROR("use strerror() instead of strerrorname_np()\n" . $herecurr);
3365 }
3366 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
3367 g_assert_cmpint|
3368 g_assert_cmpuint|
3369 g_assert_cmphex|
3370 g_assert_cmpfloat|
3371 g_assert_true|
3372 g_assert_false|
3373 g_assert_nonnull|
3374 g_assert_null|
3375 g_assert_no_error|
3376 g_assert_error|
3377 g_test_assert_expected_messages|
3378 g_test_trap_assert_passed|
3379 g_test_trap_assert_stdout|
3380 g_test_trap_assert_stdout_unmatched|
3381 g_test_trap_assert_stderr|
3382 g_test_trap_assert_stderr_unmatched}x;
3383 if ($realfile !~ /^tests\// &&
3384 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
3385 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
3386 }
3387 }
3388
3389 if (defined $fileinfo) {
3390 process_end_of_file($fileinfo);
3391 }
3392 process_file_list(@fileinfolist);
3393
3394 if ($is_patch && $chk_signoff && $signoff == 0) {
3395 ERROR("Missing Signed-off-by: line(s)\n");
3396 }
3397
3398 # If we have no input at all, then there is nothing to report on
3399 # so just keep quiet.
3400 if ($#rawlines == -1) {
3401 return 1;
3402 }
3403
3404 # In mailback mode only produce a report in the negative, for
3405 # things that appear to be patches.
3406 if ($mailback && ($clean == 1 || !$is_patch)) {
3407 return 1;
3408 }
3409
3410 # This is not a patch, and we are are in 'no-patch' mode so
3411 # just keep quiet.
3412 if (!$chk_patch && !$is_patch) {
3413 return 1;
3414 }
3415
3416 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
3417 ERROR("Does not appear to be a unified-diff format patch\n");
3418 }
3419
3420 print report_dump();
3421 if ($summary && !($clean == 1 && $quiet == 1)) {
3422 print "$filename " if ($summary_file);
3423 print "total: $cnt_error errors, $cnt_warn warnings, " .
3424 "$cnt_lines lines checked\n";
3425 print "\n" if ($quiet == 0);
3426 }
3427
3428 if ($quiet == 0) {
3429 # If there were whitespace errors which cleanpatch can fix
3430 # then suggest that.
3431 # if ($rpt_cleaners) {
3432 # print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
3433 # print " scripts/cleanfile\n\n";
3434 # }
3435 }
3436
3437 if ($clean == 1 && $quiet == 0) {
3438 print "$vname has no obvious style problems and is ready for submission.\n"
3439 }
3440 if ($clean == 0 && $quiet == 0) {
3441 print "$vname has style problems, please review. If any of these errors\n";
3442 print "are false positives report them to the maintainer, see\n";
3443 print "CHECKPATCH in MAINTAINERS.\n";
3444 }
3445
3446 return ($no_warnings ? $clean : $cnt_error == 0);
3447 }