tcg/mips: mips sync* encode error
[qemu/ar7.git] / scripts / checkpatch.pl
blobe658e6546fe6f4203da6a30695baedab889caffe
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
8 use strict;
9 use warnings;
10 use Term::ANSIColor qw(:constants);
12 my $P = $0;
13 $P =~ s@.*/@@g;
15 our $SrcFile = qr{\.(?:h|c|cpp|s|S|pl|py|sh)$};
17 my $V = '0.31';
19 use Getopt::Long qw(:config no_auto_abbrev);
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 $acpi_testexpected;
39 my $acpi_nontestexpected;
41 sub help {
42 my ($exitcode) = @_;
44 print << "EOM";
45 Usage:
47 $P [OPTION]... [FILE]...
48 $P [OPTION]... [GIT-REV-LIST]
50 Version: $V
52 Options:
53 -q, --quiet quiet
54 --no-tree run without a kernel tree
55 --no-signoff do not check for 'Signed-off-by' line
56 --patch treat FILE as patchfile
57 --branch treat args as GIT revision list
58 --emacs emacs compile window format
59 --terse one line per report
60 -f, --file treat FILE as regular source file
61 --strict fail if only warnings are found
62 --root=PATH PATH to the kernel tree root
63 --no-summary suppress the per-file summary
64 --mailback only produce a report in case of warnings/errors
65 --summary-file include the filename in summary
66 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
67 'values', 'possible', 'type', and 'attr' (default
68 is all off)
69 --test-only=WORD report only warnings/errors containing WORD
70 literally
71 --color[=WHEN] Use colors 'always', 'never', or only when output
72 is a terminal ('auto'). Default is 'auto'.
73 -h, --help, --version display this help and exit
75 When FILE is - read standard input.
76 EOM
78 exit($exitcode);
81 # Perl's Getopt::Long allows options to take optional arguments after a space.
82 # Prevent --color by itself from consuming other arguments
83 foreach (@ARGV) {
84 if ($_ eq "--color" || $_ eq "-color") {
85 $_ = "--color=$color";
89 GetOptions(
90 'q|quiet+' => \$quiet,
91 'tree!' => \$tree,
92 'signoff!' => \$chk_signoff,
93 'patch!' => \$chk_patch,
94 'branch!' => \$chk_branch,
95 'emacs!' => \$emacs,
96 'terse!' => \$terse,
97 'f|file!' => \$file,
98 'strict!' => \$no_warnings,
99 'root=s' => \$root,
100 'summary!' => \$summary,
101 'mailback!' => \$mailback,
102 'summary-file!' => \$summary_file,
104 'debug=s' => \%debug,
105 'test-only=s' => \$tst_only,
106 'color=s' => \$color,
107 'no-color' => sub { $color = 'never'; },
108 'h|help' => \$help,
109 'version' => \$help
110 ) or help(1);
112 help(0) if ($help);
114 my $exit = 0;
116 if ($#ARGV < 0) {
117 print "$P: no input files\n";
118 exit(1);
121 if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
122 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
123 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
124 $chk_patch = $chk_branch || $file ? 0 : 1;
125 } elsif (!defined $chk_branch && !defined $chk_patch) {
126 if ($file) {
127 $chk_branch = $chk_patch = 0;
128 } else {
129 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
130 $chk_patch = $chk_branch ? 0 : 1;
132 } elsif (!defined $chk_branch && !defined $file) {
133 if ($chk_patch) {
134 $chk_branch = $file = 0;
135 } else {
136 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
137 $file = $chk_branch ? 0 : 1;
139 } elsif (!defined $chk_patch && !defined $file) {
140 if ($chk_branch) {
141 $chk_patch = $file = 0;
142 } else {
143 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
144 $chk_patch = $file ? 0 : 1;
146 } elsif (!defined $chk_branch) {
147 $chk_branch = $chk_patch || $file ? 0 : 1;
148 } elsif (!defined $chk_patch) {
149 $chk_patch = $chk_branch || $file ? 0 : 1;
150 } elsif (!defined $file) {
151 $file = $chk_patch || $chk_branch ? 0 : 1;
154 if (($chk_patch && $chk_branch) ||
155 ($chk_patch && $file) ||
156 ($chk_branch && $file)) {
157 die "Only one of --file, --branch, --patch is permitted\n";
159 if (!$chk_patch && !$chk_branch && !$file) {
160 die "One of --file, --branch, --patch is required\n";
163 if ($color =~ /^always$/i) {
164 $color = 1;
165 } elsif ($color =~ /^never$/i) {
166 $color = 0;
167 } elsif ($color =~ /^auto$/i) {
168 $color = (-t STDOUT);
169 } else {
170 die "Invalid color mode: $color\n";
173 my $dbg_values = 0;
174 my $dbg_possible = 0;
175 my $dbg_type = 0;
176 my $dbg_attr = 0;
177 my $dbg_adv_dcs = 0;
178 my $dbg_adv_checking = 0;
179 my $dbg_adv_apw = 0;
180 for my $key (keys %debug) {
181 ## no critic
182 eval "\${dbg_$key} = '$debug{$key}';";
183 die "$@" if ($@);
186 my $rpt_cleaners = 0;
188 if ($terse) {
189 $emacs = 1;
190 $quiet++;
193 if ($tree) {
194 if (defined $root) {
195 if (!top_of_kernel_tree($root)) {
196 die "$P: $root: --root does not point at a valid tree\n";
198 } else {
199 if (top_of_kernel_tree('.')) {
200 $root = '.';
201 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
202 top_of_kernel_tree($1)) {
203 $root = $1;
207 if (!defined $root) {
208 print "Must be run from the top-level dir. of a kernel tree\n";
209 exit(2);
213 my $emitted_corrupt = 0;
215 our $Ident = qr{
216 [A-Za-z_][A-Za-z\d_]*
217 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
219 our $Storage = qr{extern|static|asmlinkage};
220 our $Sparse = qr{
221 __force
224 # Notes to $Attribute:
225 our $Attribute = qr{
226 const|
227 volatile|
228 QEMU_NORETURN|
229 QEMU_WARN_UNUSED_RESULT|
230 QEMU_SENTINEL|
231 QEMU_PACKED|
232 GCC_FMT_ATTR
234 our $Modifier;
235 our $Inline = qr{inline};
236 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
237 our $Lval = qr{$Ident(?:$Member)*};
239 our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
240 our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
241 our $Compare = qr{<=|>=|==|!=|<|>};
242 our $Operators = qr{
243 <=|>=|==|!=|
244 =>|->|<<|>>|<|>|!|~|
245 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
248 our $NonptrType;
249 our $Type;
250 our $Declare;
252 our $NON_ASCII_UTF8 = qr{
253 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
254 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
255 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
256 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
257 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
258 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
259 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
262 our $UTF8 = qr{
263 [\x09\x0A\x0D\x20-\x7E] # ASCII
264 | $NON_ASCII_UTF8
267 # some readers default to ISO-8859-1 when showing email source. detect
268 # when UTF-8 is incorrectly interpreted as ISO-8859-1 and reencoded back.
269 # False positives are possible but very unlikely.
270 our $UTF8_MOJIBAKE = qr{
271 \xC3[\x82-\x9F] \xC2[\x80-\xBF] # c2-df 80-bf
272 | \xC3\xA0 \xC2[\xA0-\xBF] \xC2[\x80-\xBF] # e0 a0-bf 80-bf
273 | \xC3[\xA1-\xAC\xAE\xAF] (?: \xC2[\x80-\xBF]){2} # e1-ec/ee/ef 80-bf 80-bf
274 | \xC3\xAD \xC2[\x80-\x9F] \xC2[\x80-\xBF] # ed 80-9f 80-bf
275 | \xC3\xB0 \xC2[\x90-\xBF] (?: \xC2[\x80-\xBF]){2} # f0 90-bf 80-bf 80-bf
276 | \xC3[\xB1-\xB3] (?: \xC2[\x80-\xBF]){3} # f1-f3 80-bf 80-bf 80-bf
277 | \xC3\xB4 \xC2[\x80-\x8F] (?: \xC2[\x80-\xBF]){2} # f4 80-b8 80-bf 80-bf
280 # There are still some false positives, but this catches most
281 # common cases.
282 our $typeTypedefs = qr{(?x:
283 (?![KMGTPE]iB) # IEC binary prefix (do not match)
284 [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]* # camelcase
285 | [A-Z][A-Z\d_]*AIOCB # all uppercase
286 | [A-Z][A-Z\d_]*CPU # all uppercase
287 | QEMUBH # all uppercase
290 our @typeList = (
291 qr{void},
292 qr{(?:unsigned\s+)?char},
293 qr{(?:unsigned\s+)?short},
294 qr{(?:unsigned\s+)?int},
295 qr{(?:unsigned\s+)?long},
296 qr{(?:unsigned\s+)?long\s+int},
297 qr{(?:unsigned\s+)?long\s+long},
298 qr{(?:unsigned\s+)?long\s+long\s+int},
299 qr{unsigned},
300 qr{float},
301 qr{double},
302 qr{bool},
303 qr{struct\s+$Ident},
304 qr{union\s+$Ident},
305 qr{enum\s+$Ident},
306 qr{${Ident}_t},
307 qr{${Ident}_handler},
308 qr{${Ident}_handler_fn},
309 qr{target_(?:u)?long},
310 qr{hwaddr},
311 # external libraries
312 qr{xml${Ident}},
313 qr{xen\w+_handle},
314 # Glib definitions
315 qr{gchar},
316 qr{gshort},
317 qr{glong},
318 qr{gint},
319 qr{gboolean},
320 qr{guchar},
321 qr{gushort},
322 qr{gulong},
323 qr{guint},
324 qr{gfloat},
325 qr{gdouble},
326 qr{gpointer},
327 qr{gconstpointer},
328 qr{gint8},
329 qr{guint8},
330 qr{gint16},
331 qr{guint16},
332 qr{gint32},
333 qr{guint32},
334 qr{gint64},
335 qr{guint64},
336 qr{gsize},
337 qr{gssize},
338 qr{goffset},
339 qr{gintptr},
340 qr{guintptr},
343 # This can be modified by sub possible. Since it can be empty, be careful
344 # about regexes that always match, because they can cause infinite loops.
345 our @modifierList = (
348 sub build_types {
349 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
350 if (@modifierList > 0) {
351 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
352 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
353 } else {
354 $Modifier = qr{(?:$Attribute|$Sparse)};
356 $NonptrType = qr{
357 (?:$Modifier\s+|const\s+)*
359 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
360 (?:$typeTypedefs\b)|
361 (?:${all}\b)
363 (?:\s+$Modifier|\s+const)*
365 $Type = qr{
366 $NonptrType
367 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
368 (?:\s+$Inline|\s+$Modifier)*
370 $Declare = qr{(?:$Storage\s+)?$Type};
372 build_types();
374 $chk_signoff = 0 if ($file);
376 my @rawlines = ();
377 my @lines = ();
378 my $vname;
379 if ($chk_branch) {
380 my @patches;
381 my %git_commits = ();
382 my $HASH;
383 open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--format=%H %s", $ARGV[0]) ||
384 die "$P: git log --reverse --no-merges --format='%H %s' $ARGV[0] failed - $!\n";
386 for my $line (<$HASH>) {
387 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
388 next if (!defined($1) || !defined($2));
389 my $sha1 = $1;
390 my $subject = $2;
391 push(@patches, $sha1);
392 $git_commits{$sha1} = $subject;
395 close $HASH;
397 die "$P: no revisions returned for revlist '$chk_branch'\n"
398 unless @patches;
400 my $i = 1;
401 my $num_patches = @patches;
402 for my $hash (@patches) {
403 my $FILE;
404 open($FILE, '-|', "git", "show", $hash) ||
405 die "$P: git show $hash - $!\n";
406 while (<$FILE>) {
407 chomp;
408 push(@rawlines, $_);
410 close($FILE);
411 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
412 if ($num_patches > 1 && $quiet == 0) {
413 my $prefix = "$i/$num_patches";
414 $prefix = BLUE . BOLD . $prefix . RESET if $color;
415 print "$prefix Checking commit $vname\n";
416 $vname = "Patch $i/$num_patches";
417 } else {
418 $vname = "Commit " . $vname;
420 if (!process($hash)) {
421 $exit = 1;
422 print "\n" if ($num_patches > 1 && $quiet == 0);
424 @rawlines = ();
425 @lines = ();
426 $i++;
428 } else {
429 for my $filename (@ARGV) {
430 my $FILE;
431 if ($file) {
432 open($FILE, '-|', "diff -u /dev/null $filename") ||
433 die "$P: $filename: diff failed - $!\n";
434 } elsif ($filename eq '-') {
435 open($FILE, '<&STDIN');
436 } else {
437 open($FILE, '<', "$filename") ||
438 die "$P: $filename: open failed - $!\n";
440 if ($filename eq '-') {
441 $vname = 'Your patch';
442 } else {
443 $vname = $filename;
445 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
446 while (<$FILE>) {
447 chomp;
448 push(@rawlines, $_);
450 close($FILE);
451 if (!process($filename)) {
452 $exit = 1;
454 @rawlines = ();
455 @lines = ();
459 exit($exit);
461 sub top_of_kernel_tree {
462 my ($root) = @_;
464 my @tree_check = (
465 "COPYING", "MAINTAINERS", "Makefile",
466 "README.rst", "docs", "VERSION",
467 "linux-user", "softmmu"
470 foreach my $check (@tree_check) {
471 if (! -e $root . '/' . $check) {
472 return 0;
475 return 1;
478 sub expand_tabs {
479 my ($str) = @_;
481 my $res = '';
482 my $n = 0;
483 for my $c (split(//, $str)) {
484 if ($c eq "\t") {
485 $res .= ' ';
486 $n++;
487 for (; ($n % 8) != 0; $n++) {
488 $res .= ' ';
490 next;
492 $res .= $c;
493 $n++;
496 return $res;
498 sub copy_spacing {
499 (my $res = shift) =~ tr/\t/ /c;
500 return $res;
503 sub line_stats {
504 my ($line) = @_;
506 # Drop the diff line leader and expand tabs
507 $line =~ s/^.//;
508 $line = expand_tabs($line);
510 # Pick the indent from the front of the line.
511 my ($white) = ($line =~ /^(\s*)/);
513 return (length($line), length($white));
516 my $sanitise_quote = '';
518 sub sanitise_line_reset {
519 my ($in_comment) = @_;
521 if ($in_comment) {
522 $sanitise_quote = '*/';
523 } else {
524 $sanitise_quote = '';
527 sub sanitise_line {
528 my ($line) = @_;
530 my $res = '';
531 my $l = '';
533 my $qlen = 0;
534 my $off = 0;
535 my $c;
537 # Always copy over the diff marker.
538 $res = substr($line, 0, 1);
540 for ($off = 1; $off < length($line); $off++) {
541 $c = substr($line, $off, 1);
543 # Comments we are wacking completely including the begin
544 # and end, all to $;.
545 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
546 $sanitise_quote = '*/';
548 substr($res, $off, 2, "$;$;");
549 $off++;
550 next;
552 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
553 $sanitise_quote = '';
554 substr($res, $off, 2, "$;$;");
555 $off++;
556 next;
558 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
559 $sanitise_quote = '//';
561 substr($res, $off, 2, $sanitise_quote);
562 $off++;
563 next;
566 # A \ in a string means ignore the next character.
567 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
568 $c eq "\\") {
569 substr($res, $off, 2, 'XX');
570 $off++;
571 next;
573 # Regular quotes.
574 if ($c eq "'" || $c eq '"') {
575 if ($sanitise_quote eq '') {
576 $sanitise_quote = $c;
578 substr($res, $off, 1, $c);
579 next;
580 } elsif ($sanitise_quote eq $c) {
581 $sanitise_quote = '';
585 #print "c<$c> SQ<$sanitise_quote>\n";
586 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
587 substr($res, $off, 1, $;);
588 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
589 substr($res, $off, 1, $;);
590 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
591 substr($res, $off, 1, 'X');
592 } else {
593 substr($res, $off, 1, $c);
597 if ($sanitise_quote eq '//') {
598 $sanitise_quote = '';
601 # The pathname on a #include may be surrounded by '<' and '>'.
602 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
603 my $clean = 'X' x length($1);
604 $res =~ s@\<.*\>@<$clean>@;
606 # The whole of a #error is a string.
607 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
608 my $clean = 'X' x length($1);
609 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
612 return $res;
615 sub ctx_statement_block {
616 my ($linenr, $remain, $off) = @_;
617 my $line = $linenr - 1;
618 my $blk = '';
619 my $soff = $off;
620 my $coff = $off - 1;
621 my $coff_set = 0;
623 my $loff = 0;
625 my $type = '';
626 my $level = 0;
627 my @stack = ();
628 my $p;
629 my $c;
630 my $len = 0;
632 my $remainder;
633 while (1) {
634 @stack = (['', 0]) if ($#stack == -1);
636 #warn "CSB: blk<$blk> remain<$remain>\n";
637 # If we are about to drop off the end, pull in more
638 # context.
639 if ($off >= $len) {
640 for (; $remain > 0; $line++) {
641 last if (!defined $lines[$line]);
642 next if ($lines[$line] =~ /^-/);
643 $remain--;
644 $loff = $len;
645 $blk .= $lines[$line] . "\n";
646 $len = length($blk);
647 $line++;
648 last;
650 # Bail if there is no further context.
651 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
652 if ($off >= $len) {
653 last;
656 $p = $c;
657 $c = substr($blk, $off, 1);
658 $remainder = substr($blk, $off);
660 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
662 # Handle nested #if/#else.
663 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
664 push(@stack, [ $type, $level ]);
665 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
666 ($type, $level) = @{$stack[$#stack - 1]};
667 } elsif ($remainder =~ /^#\s*endif\b/) {
668 ($type, $level) = @{pop(@stack)};
671 # Statement ends at the ';' or a close '}' at the
672 # outermost level.
673 if ($level == 0 && $c eq ';') {
674 last;
677 # An else is really a conditional as long as its not else if
678 if ($level == 0 && $coff_set == 0 &&
679 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
680 $remainder =~ /^(else)(?:\s|{)/ &&
681 $remainder !~ /^else\s+if\b/) {
682 $coff = $off + length($1) - 1;
683 $coff_set = 1;
684 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
685 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
688 if (($type eq '' || $type eq '(') && $c eq '(') {
689 $level++;
690 $type = '(';
692 if ($type eq '(' && $c eq ')') {
693 $level--;
694 $type = ($level != 0)? '(' : '';
696 if ($level == 0 && $coff < $soff) {
697 $coff = $off;
698 $coff_set = 1;
699 #warn "CSB: mark coff<$coff>\n";
702 if (($type eq '' || $type eq '{') && $c eq '{') {
703 $level++;
704 $type = '{';
706 if ($type eq '{' && $c eq '}') {
707 $level--;
708 $type = ($level != 0)? '{' : '';
710 if ($level == 0) {
711 if (substr($blk, $off + 1, 1) eq ';') {
712 $off++;
714 last;
717 $off++;
719 # We are truly at the end, so shuffle to the next line.
720 if ($off == $len) {
721 $loff = $len + 1;
722 $line++;
723 $remain--;
726 my $statement = substr($blk, $soff, $off - $soff + 1);
727 my $condition = substr($blk, $soff, $coff - $soff + 1);
729 #warn "STATEMENT<$statement>\n";
730 #warn "CONDITION<$condition>\n";
732 #print "coff<$coff> soff<$off> loff<$loff>\n";
734 return ($statement, $condition,
735 $line, $remain + 1, $off - $loff + 1, $level);
738 sub statement_lines {
739 my ($stmt) = @_;
741 # Strip the diff line prefixes and rip blank lines at start and end.
742 $stmt =~ s/(^|\n)./$1/g;
743 $stmt =~ s/^\s*//;
744 $stmt =~ s/\s*$//;
746 my @stmt_lines = ($stmt =~ /\n/g);
748 return $#stmt_lines + 2;
751 sub statement_rawlines {
752 my ($stmt) = @_;
754 my @stmt_lines = ($stmt =~ /\n/g);
756 return $#stmt_lines + 2;
759 sub statement_block_size {
760 my ($stmt) = @_;
762 $stmt =~ s/(^|\n)./$1/g;
763 $stmt =~ s/^\s*\{//;
764 $stmt =~ s/}\s*$//;
765 $stmt =~ s/^\s*//;
766 $stmt =~ s/\s*$//;
768 my @stmt_lines = ($stmt =~ /\n/g);
769 my @stmt_statements = ($stmt =~ /;/g);
771 my $stmt_lines = $#stmt_lines + 2;
772 my $stmt_statements = $#stmt_statements + 1;
774 if ($stmt_lines > $stmt_statements) {
775 return $stmt_lines;
776 } else {
777 return $stmt_statements;
781 sub ctx_statement_full {
782 my ($linenr, $remain, $off) = @_;
783 my ($statement, $condition, $level);
785 my (@chunks);
787 # Grab the first conditional/block pair.
788 ($statement, $condition, $linenr, $remain, $off, $level) =
789 ctx_statement_block($linenr, $remain, $off);
790 #print "F: c<$condition> s<$statement> remain<$remain>\n";
791 push(@chunks, [ $condition, $statement ]);
792 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
793 return ($level, $linenr, @chunks);
796 # Pull in the following conditional/block pairs and see if they
797 # could continue the statement.
798 for (;;) {
799 ($statement, $condition, $linenr, $remain, $off, $level) =
800 ctx_statement_block($linenr, $remain, $off);
801 #print "C: c<$condition> s<$statement> remain<$remain>\n";
802 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
803 #print "C: push\n";
804 push(@chunks, [ $condition, $statement ]);
807 return ($level, $linenr, @chunks);
810 sub ctx_block_get {
811 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
812 my $line;
813 my $start = $linenr - 1;
814 my $blk = '';
815 my @o;
816 my @c;
817 my @res = ();
819 my $level = 0;
820 my @stack = ($level);
821 for ($line = $start; $remain > 0; $line++) {
822 next if ($rawlines[$line] =~ /^-/);
823 $remain--;
825 $blk .= $rawlines[$line];
827 # Handle nested #if/#else.
828 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
829 push(@stack, $level);
830 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
831 $level = $stack[$#stack - 1];
832 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
833 $level = pop(@stack);
836 foreach my $c (split(//, $lines[$line])) {
837 ##print "C<$c>L<$level><$open$close>O<$off>\n";
838 if ($off > 0) {
839 $off--;
840 next;
843 if ($c eq $close && $level > 0) {
844 $level--;
845 last if ($level == 0);
846 } elsif ($c eq $open) {
847 $level++;
851 if (!$outer || $level <= 1) {
852 push(@res, $rawlines[$line]);
855 last if ($level == 0);
858 return ($level, @res);
860 sub ctx_block_outer {
861 my ($linenr, $remain) = @_;
863 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
864 return @r;
866 sub ctx_block {
867 my ($linenr, $remain) = @_;
869 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
870 return @r;
872 sub ctx_statement {
873 my ($linenr, $remain, $off) = @_;
875 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
876 return @r;
878 sub ctx_block_level {
879 my ($linenr, $remain) = @_;
881 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
883 sub ctx_statement_level {
884 my ($linenr, $remain, $off) = @_;
886 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
889 sub ctx_locate_comment {
890 my ($first_line, $end_line) = @_;
892 # Catch a comment on the end of the line itself.
893 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
894 return $current_comment if (defined $current_comment);
896 # Look through the context and try and figure out if there is a
897 # comment.
898 my $in_comment = 0;
899 $current_comment = '';
900 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
901 my $line = $rawlines[$linenr - 1];
902 #warn " $line\n";
903 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
904 $in_comment = 1;
906 if ($line =~ m@/\*@) {
907 $in_comment = 1;
909 if (!$in_comment && $current_comment ne '') {
910 $current_comment = '';
912 $current_comment .= $line . "\n" if ($in_comment);
913 if ($line =~ m@\*/@) {
914 $in_comment = 0;
918 chomp($current_comment);
919 return($current_comment);
921 sub ctx_has_comment {
922 my ($first_line, $end_line) = @_;
923 my $cmt = ctx_locate_comment($first_line, $end_line);
925 ##print "LINE: $rawlines[$end_line - 1 ]\n";
926 ##print "CMMT: $cmt\n";
928 return ($cmt ne '');
931 sub raw_line {
932 my ($linenr, $cnt) = @_;
934 my $offset = $linenr - 1;
935 $cnt++;
937 my $line;
938 while ($cnt) {
939 $line = $rawlines[$offset++];
940 next if (defined($line) && $line =~ /^-/);
941 $cnt--;
944 return $line;
947 sub cat_vet {
948 my ($vet) = @_;
949 my ($res, $coded);
951 $res = '';
952 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
953 $res .= $1;
954 if ($2 ne '') {
955 $coded = sprintf("^%c", unpack('C', $2) + 64);
956 $res .= $coded;
959 $res =~ s/$/\$/;
961 return $res;
964 my $av_preprocessor = 0;
965 my $av_pending;
966 my @av_paren_type;
967 my $av_pend_colon;
969 sub annotate_reset {
970 $av_preprocessor = 0;
971 $av_pending = '_';
972 @av_paren_type = ('E');
973 $av_pend_colon = 'O';
976 sub annotate_values {
977 my ($stream, $type) = @_;
979 my $res;
980 my $var = '_' x length($stream);
981 my $cur = $stream;
983 print "$stream\n" if ($dbg_values > 1);
985 while (length($cur)) {
986 @av_paren_type = ('E') if ($#av_paren_type < 0);
987 print " <" . join('', @av_paren_type) .
988 "> <$type> <$av_pending>" if ($dbg_values > 1);
989 if ($cur =~ /^(\s+)/o) {
990 print "WS($1)\n" if ($dbg_values > 1);
991 if ($1 =~ /\n/ && $av_preprocessor) {
992 $type = pop(@av_paren_type);
993 $av_preprocessor = 0;
996 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
997 print "CAST($1)\n" if ($dbg_values > 1);
998 push(@av_paren_type, $type);
999 $type = 'C';
1001 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1002 print "DECLARE($1)\n" if ($dbg_values > 1);
1003 $type = 'T';
1005 } elsif ($cur =~ /^($Modifier)\s*/) {
1006 print "MODIFIER($1)\n" if ($dbg_values > 1);
1007 $type = 'T';
1009 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1010 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1011 $av_preprocessor = 1;
1012 push(@av_paren_type, $type);
1013 if ($2 ne '') {
1014 $av_pending = 'N';
1016 $type = 'E';
1018 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1019 print "UNDEF($1)\n" if ($dbg_values > 1);
1020 $av_preprocessor = 1;
1021 push(@av_paren_type, $type);
1023 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1024 print "PRE_START($1)\n" if ($dbg_values > 1);
1025 $av_preprocessor = 1;
1027 push(@av_paren_type, $type);
1028 push(@av_paren_type, $type);
1029 $type = 'E';
1031 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1032 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1033 $av_preprocessor = 1;
1035 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1037 $type = 'E';
1039 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1040 print "PRE_END($1)\n" if ($dbg_values > 1);
1042 $av_preprocessor = 1;
1044 # Assume all arms of the conditional end as this
1045 # one does, and continue as if the #endif was not here.
1046 pop(@av_paren_type);
1047 push(@av_paren_type, $type);
1048 $type = 'E';
1050 } elsif ($cur =~ /^(\\\n)/o) {
1051 print "PRECONT($1)\n" if ($dbg_values > 1);
1053 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1054 print "ATTR($1)\n" if ($dbg_values > 1);
1055 $av_pending = $type;
1056 $type = 'N';
1058 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1059 print "SIZEOF($1)\n" if ($dbg_values > 1);
1060 if (defined $2) {
1061 $av_pending = 'V';
1063 $type = 'N';
1065 } elsif ($cur =~ /^(if|while|for)\b/o) {
1066 print "COND($1)\n" if ($dbg_values > 1);
1067 $av_pending = 'E';
1068 $type = 'N';
1070 } elsif ($cur =~/^(case)/o) {
1071 print "CASE($1)\n" if ($dbg_values > 1);
1072 $av_pend_colon = 'C';
1073 $type = 'N';
1075 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1076 print "KEYWORD($1)\n" if ($dbg_values > 1);
1077 $type = 'N';
1079 } elsif ($cur =~ /^(\()/o) {
1080 print "PAREN('$1')\n" if ($dbg_values > 1);
1081 push(@av_paren_type, $av_pending);
1082 $av_pending = '_';
1083 $type = 'N';
1085 } elsif ($cur =~ /^(\))/o) {
1086 my $new_type = pop(@av_paren_type);
1087 if ($new_type ne '_') {
1088 $type = $new_type;
1089 print "PAREN('$1') -> $type\n"
1090 if ($dbg_values > 1);
1091 } else {
1092 print "PAREN('$1')\n" if ($dbg_values > 1);
1095 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1096 print "FUNC($1)\n" if ($dbg_values > 1);
1097 $type = 'V';
1098 $av_pending = 'V';
1100 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1101 if (defined $2 && $type eq 'C' || $type eq 'T') {
1102 $av_pend_colon = 'B';
1103 } elsif ($type eq 'E') {
1104 $av_pend_colon = 'L';
1106 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1107 $type = 'V';
1109 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1110 print "IDENT($1)\n" if ($dbg_values > 1);
1111 $type = 'V';
1113 } elsif ($cur =~ /^($Assignment)/o) {
1114 print "ASSIGN($1)\n" if ($dbg_values > 1);
1115 $type = 'N';
1117 } elsif ($cur =~/^(;|{|})/) {
1118 print "END($1)\n" if ($dbg_values > 1);
1119 $type = 'E';
1120 $av_pend_colon = 'O';
1122 } elsif ($cur =~/^(,)/) {
1123 print "COMMA($1)\n" if ($dbg_values > 1);
1124 $type = 'C';
1126 } elsif ($cur =~ /^(\?)/o) {
1127 print "QUESTION($1)\n" if ($dbg_values > 1);
1128 $type = 'N';
1130 } elsif ($cur =~ /^(:)/o) {
1131 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1133 substr($var, length($res), 1, $av_pend_colon);
1134 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1135 $type = 'E';
1136 } else {
1137 $type = 'N';
1139 $av_pend_colon = 'O';
1141 } elsif ($cur =~ /^(\[)/o) {
1142 print "CLOSE($1)\n" if ($dbg_values > 1);
1143 $type = 'N';
1145 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1146 my $variant;
1148 print "OPV($1)\n" if ($dbg_values > 1);
1149 if ($type eq 'V') {
1150 $variant = 'B';
1151 } else {
1152 $variant = 'U';
1155 substr($var, length($res), 1, $variant);
1156 $type = 'N';
1158 } elsif ($cur =~ /^($Operators)/o) {
1159 print "OP($1)\n" if ($dbg_values > 1);
1160 if ($1 ne '++' && $1 ne '--') {
1161 $type = 'N';
1164 } elsif ($cur =~ /(^.)/o) {
1165 print "C($1)\n" if ($dbg_values > 1);
1167 if (defined $1) {
1168 $cur = substr($cur, length($1));
1169 $res .= $type x length($1);
1173 return ($res, $var);
1176 sub possible {
1177 my ($possible, $line) = @_;
1178 my $notPermitted = qr{(?:
1179 ^(?:
1180 $Modifier|
1181 $Storage|
1182 $Type|
1183 DEFINE_\S+
1185 ^(?:
1186 goto|
1187 return|
1188 case|
1189 else|
1190 asm|__asm__|
1192 )(?:\s|$)|
1193 ^(?:typedef|struct|enum)\b|
1195 )}x;
1196 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1197 if ($possible !~ $notPermitted) {
1198 # Check for modifiers.
1199 $possible =~ s/\s*$Storage\s*//g;
1200 $possible =~ s/\s*$Sparse\s*//g;
1201 if ($possible =~ /^\s*$/) {
1203 } elsif ($possible =~ /\s/) {
1204 $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
1205 for my $modifier (split(' ', $possible)) {
1206 if ($modifier !~ $notPermitted) {
1207 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1208 push(@modifierList, $modifier);
1212 } else {
1213 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1214 push(@typeList, $possible);
1216 build_types();
1217 } else {
1218 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1222 my $prefix = '';
1224 sub report {
1225 my ($level, $msg) = @_;
1226 if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
1227 return 0;
1230 my $output = '';
1231 $output .= BOLD if $color;
1232 $output .= $prefix;
1233 $output .= RED if $color && $level eq 'ERROR';
1234 $output .= MAGENTA if $color && $level eq 'WARNING';
1235 $output .= $level . ':';
1236 $output .= RESET if $color;
1237 $output .= ' ' . $msg . "\n";
1239 $output = (split('\n', $output))[0] . "\n" if ($terse);
1241 push(our @report, $output);
1243 return 1;
1245 sub report_dump {
1246 our @report;
1248 sub ERROR {
1249 if (report("ERROR", $_[0])) {
1250 our $clean = 0;
1251 our $cnt_error++;
1254 sub WARN {
1255 if (report("WARNING", $_[0])) {
1256 our $clean = 0;
1257 our $cnt_warn++;
1261 # According to tests/qtest/bios-tables-test.c: do not
1262 # change expected file in the same commit with adding test
1263 sub checkfilename {
1264 my ($name) = @_;
1265 if ($name =~ m#^tests/data/acpi/# and
1266 # make exception for a shell script that rebuilds the files
1267 not $name =~ m#^\.sh$# or
1268 $name =~ m#^tests/qtest/bios-tables-test-allowed-diff.h$#) {
1269 $acpi_testexpected = $name;
1270 } else {
1271 $acpi_nontestexpected = $name;
1273 if (defined $acpi_testexpected and defined $acpi_nontestexpected) {
1274 ERROR("Do not add expected files together with tests, " .
1275 "follow instructions in " .
1276 "tests/qtest/bios-tables-test.c: both " .
1277 $acpi_testexpected . " and " .
1278 $acpi_nontestexpected . " found\n");
1282 sub process {
1283 my $filename = shift;
1285 my $linenr=0;
1286 my $prevline="";
1287 my $prevrawline="";
1288 my $stashline="";
1289 my $stashrawline="";
1291 my $length;
1292 my $indent;
1293 my $previndent=0;
1294 my $stashindent=0;
1296 our $clean = 1;
1297 my $signoff = 0;
1298 my $is_patch = 0;
1300 my $in_header_lines = $file ? 0 : 1;
1301 my $in_commit_log = 0; #Scanning lines before patch
1302 my $reported_maintainer_file = 0;
1303 my $non_utf8_charset = 0;
1305 our @report = ();
1306 our $cnt_lines = 0;
1307 our $cnt_error = 0;
1308 our $cnt_warn = 0;
1309 our $cnt_chk = 0;
1311 # Trace the real file/line as we go.
1312 my $realfile = '';
1313 my $realline = 0;
1314 my $realcnt = 0;
1315 my $here = '';
1316 my $in_comment = 0;
1317 my $comment_edge = 0;
1318 my $first_line = 0;
1319 my $p1_prefix = '';
1321 my $prev_values = 'E';
1323 # suppression flags
1324 my %suppress_ifbraces;
1325 my %suppress_whiletrailers;
1326 my %suppress_export;
1328 # Pre-scan the patch sanitizing the lines.
1330 sanitise_line_reset();
1331 my $line;
1332 foreach my $rawline (@rawlines) {
1333 $linenr++;
1334 $line = $rawline;
1336 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1337 $realline=$1-1;
1338 if (defined $2) {
1339 $realcnt=$3+1;
1340 } else {
1341 $realcnt=1+1;
1343 $in_comment = 0;
1345 # Guestimate if this is a continuing comment. Run
1346 # the context looking for a comment "edge". If this
1347 # edge is a close comment then we must be in a comment
1348 # at context start.
1349 my $edge;
1350 my $cnt = $realcnt;
1351 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1352 next if (defined $rawlines[$ln - 1] &&
1353 $rawlines[$ln - 1] =~ /^-/);
1354 $cnt--;
1355 #print "RAW<$rawlines[$ln - 1]>\n";
1356 last if (!defined $rawlines[$ln - 1]);
1357 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1358 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1359 ($edge) = $1;
1360 last;
1363 if (defined $edge && $edge eq '*/') {
1364 $in_comment = 1;
1367 # Guestimate if this is a continuing comment. If this
1368 # is the start of a diff block and this line starts
1369 # ' *' then it is very likely a comment.
1370 if (!defined $edge &&
1371 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1373 $in_comment = 1;
1376 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1377 sanitise_line_reset($in_comment);
1379 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1380 # Standardise the strings and chars within the input to
1381 # simplify matching -- only bother with positive lines.
1382 $line = sanitise_line($rawline);
1384 push(@lines, $line);
1386 if ($realcnt > 1) {
1387 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1388 } else {
1389 $realcnt = 0;
1392 #print "==>$rawline\n";
1393 #print "-->$line\n";
1396 $prefix = '';
1398 $realcnt = 0;
1399 $linenr = 0;
1400 foreach my $line (@lines) {
1401 $linenr++;
1403 my $rawline = $rawlines[$linenr - 1];
1405 #extract the line range in the file after the patch is applied
1406 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1407 $is_patch = 1;
1408 $first_line = $linenr + 1;
1409 $realline=$1-1;
1410 if (defined $2) {
1411 $realcnt=$3+1;
1412 } else {
1413 $realcnt=1+1;
1415 annotate_reset();
1416 $prev_values = 'E';
1418 %suppress_ifbraces = ();
1419 %suppress_whiletrailers = ();
1420 %suppress_export = ();
1421 next;
1423 # track the line number as we move through the hunk, note that
1424 # new versions of GNU diff omit the leading space on completely
1425 # blank context lines so we need to count that too.
1426 } elsif ($line =~ /^( |\+|$)/) {
1427 $realline++;
1428 $realcnt-- if ($realcnt != 0);
1430 # Measure the line length and indent.
1431 ($length, $indent) = line_stats($rawline);
1433 # Track the previous line.
1434 ($prevline, $stashline) = ($stashline, $line);
1435 ($previndent, $stashindent) = ($stashindent, $indent);
1436 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1438 #warn "line<$line>\n";
1440 } elsif ($realcnt == 1) {
1441 $realcnt--;
1444 my $hunk_line = ($realcnt != 0);
1446 #make up the handle for any error we report on this line
1447 $prefix = "$filename:$realline: " if ($emacs && $file);
1448 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1450 $here = "#$linenr: " if (!$file);
1451 $here = "#$realline: " if ($file);
1453 # extract the filename as it passes
1454 if ($line =~ /^diff --git.*?(\S+)$/) {
1455 $realfile = $1;
1456 $realfile =~ s@^([^/]*)/@@ if (!$file);
1457 checkfilename($realfile);
1458 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1459 $realfile = $1;
1460 $realfile =~ s@^([^/]*)/@@ if (!$file);
1461 checkfilename($realfile);
1463 $p1_prefix = $1;
1464 if (!$file && $tree && $p1_prefix ne '' &&
1465 -e "$root/$p1_prefix") {
1466 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1469 next;
1472 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1474 my $hereline = "$here\n$rawline\n";
1475 my $herecurr = "$here\n$rawline\n";
1476 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1478 $cnt_lines++ if ($realcnt != 0);
1480 # Check for incorrect file permissions
1481 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1482 my $permhere = $here . "FILE: $realfile\n";
1483 if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1484 ERROR("do not set execute permissions for source files\n" . $permhere);
1488 # Only allow Python 3 interpreter
1489 if ($realline == 1 &&
1490 $line =~ /^\+#!\ *\/usr\/bin\/(?:env )?python$/) {
1491 ERROR("please use python3 interpreter\n" . $herecurr);
1494 # Accept git diff extended headers as valid patches
1495 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1496 $is_patch = 1;
1499 if ($line =~ /^Author: .*via Qemu-devel.*<qemu-devel\@nongnu.org>/) {
1500 ERROR("Author email address is mangled by the mailing list\n" . $herecurr);
1503 #check the patch for a signoff:
1504 if ($line =~ /^\s*signed-off-by:/i) {
1505 # This is a signoff, if ugly, so do not double report.
1506 $signoff++;
1507 $in_commit_log = 0;
1509 if (!($line =~ /^\s*Signed-off-by:/)) {
1510 ERROR("The correct form is \"Signed-off-by\"\n" .
1511 $herecurr);
1513 if ($line =~ /^\s*signed-off-by:\S/i) {
1514 ERROR("space required after Signed-off-by:\n" .
1515 $herecurr);
1519 # Check if MAINTAINERS is being updated. If so, there's probably no need to
1520 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
1521 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
1522 $reported_maintainer_file = 1;
1525 # Check for added, moved or deleted files
1526 if (!$reported_maintainer_file && !$in_commit_log &&
1527 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
1528 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
1529 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
1530 (defined($1) || defined($2))))) {
1531 $reported_maintainer_file = 1;
1532 WARN("added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
1535 # Check for wrappage within a valid hunk of the file
1536 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1537 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1538 $herecurr) if (!$emitted_corrupt++);
1541 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1542 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1543 $rawline !~ m/^$UTF8*$/) {
1544 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1546 my $blank = copy_spacing($rawline);
1547 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1548 my $hereptr = "$hereline$ptr\n";
1550 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1553 if ($rawline =~ m/$UTF8_MOJIBAKE/) {
1554 ERROR("Doubly-encoded UTF-8\n" . $herecurr);
1556 # Check if it's the start of a commit log
1557 # (not a header line and we haven't seen the patch filename)
1558 if ($in_header_lines && $realfile =~ /^$/ &&
1559 !($rawline =~ /^\s+\S/ ||
1560 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1561 $in_header_lines = 0;
1562 $in_commit_log = 1;
1565 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1566 # declined it, i.e defined some charset where it is missing.
1567 if ($in_header_lines &&
1568 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1569 $1 !~ /utf-8/i) {
1570 $non_utf8_charset = 1;
1573 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1574 $rawline =~ /$NON_ASCII_UTF8/) {
1575 WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1578 # ignore non-hunk lines and lines being removed
1579 next if (!$hunk_line || $line =~ /^-/);
1581 # ignore files that are being periodically imported from Linux
1582 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1584 #trailing whitespace
1585 if ($line =~ /^\+.*\015/) {
1586 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1587 ERROR("DOS line endings\n" . $herevet);
1589 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1590 $realfile =~ /^docs\/.+\.md/) {
1591 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1592 # TODO: properly check we're in a code block
1593 # (surrounding text is 4-column aligned)
1594 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1595 ERROR("code blocks in documentation should have " .
1596 "empty lines with exactly 4 columns of " .
1597 "whitespace\n" . $herevet);
1599 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1600 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1601 ERROR("trailing whitespace\n" . $herevet);
1602 $rpt_cleaners = 1;
1605 # checks for trace-events files
1606 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1607 if ($rawline =~ /%[-+ 0]*#/) {
1608 ERROR("Don't use '#' flag of printf format ('%#') in " .
1609 "trace-events, use '0x' prefix instead\n" . $herecurr);
1610 } else {
1611 my $hex =
1612 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1614 # don't consider groups splitted by [.:/ ], like 2A.20:12ab
1615 my $tmpline = $rawline;
1616 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1618 if ($tmpline =~ /(?<!0x)$hex/) {
1619 ERROR("Hex numbers must be prefixed with '0x'\n" .
1620 $herecurr);
1625 # check we are in a valid source file if not then ignore this hunk
1626 next if ($realfile !~ /$SrcFile/);
1628 #90 column limit; exempt URLs, if no other words on line
1629 if ($line =~ /^\+/ &&
1630 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1631 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1632 $length > 80)
1634 if ($length > 90) {
1635 ERROR("line over 90 characters\n" . $herecurr);
1636 } else {
1637 WARN("line over 80 characters\n" . $herecurr);
1641 # check for spaces before a quoted newline
1642 if ($rawline =~ /^.*\".*\s\\n/) {
1643 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1646 # check for adding lines without a newline.
1647 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1648 ERROR("adding a line without newline at end of file\n" . $herecurr);
1651 # check for RCS/CVS revision markers
1652 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1653 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1656 # tabs are only allowed in assembly source code, and in
1657 # some scripts we imported from other projects.
1658 next if ($realfile =~ /\.(s|S)$/);
1659 next if ($realfile =~ /(checkpatch|get_maintainer|texi2pod)\.pl$/);
1661 if ($rawline =~ /^\+.*\t/) {
1662 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1663 ERROR("code indent should never use tabs\n" . $herevet);
1664 $rpt_cleaners = 1;
1667 # check we are in a valid C source file if not then ignore this hunk
1668 next if ($realfile !~ /\.(h|c|cpp)$/);
1670 # Block comment styles
1672 # Block comments use /* on a line of its own
1673 if ($rawline !~ m@^\+.*/\*.*\*/[ \t)}]*$@ && #inline /*...*/
1674 $rawline =~ m@^\+.*/\*\*?+[ \t]*[^ \t]@) { # /* or /** non-blank
1675 WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
1678 # Block comments use * on subsequent lines
1679 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1680 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
1681 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
1682 $rawline =~ /^\+/ && #line is new
1683 $rawline !~ /^\+[ \t]*\*/) { #no leading *
1684 WARN("Block comments use * on subsequent lines\n" . $hereprev);
1687 # Block comments use */ on trailing lines
1688 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
1689 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
1690 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
1691 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
1692 WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
1695 # Block comment * alignment
1696 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1697 $line =~ /^\+[ \t]*$;/ && #leading comment
1698 $rawline =~ /^\+[ \t]*\*/ && #leading *
1699 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
1700 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
1701 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
1702 my $oldindent;
1703 $prevrawline =~ m@^\+([ \t]*/?)\*@;
1704 if (defined($1)) {
1705 $oldindent = expand_tabs($1);
1706 } else {
1707 $prevrawline =~ m@^\+(.*/?)\*@;
1708 $oldindent = expand_tabs($1);
1710 $rawline =~ m@^\+([ \t]*)\*@;
1711 my $newindent = $1;
1712 $newindent = expand_tabs($newindent);
1713 if (length($oldindent) ne length($newindent)) {
1714 WARN("Block comments should align the * on each line\n" . $hereprev);
1718 # Check for potential 'bare' types
1719 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1720 $realline_next);
1721 if ($realcnt && $line =~ /.\s*\S/) {
1722 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1723 ctx_statement_block($linenr, $realcnt, 0);
1724 $stat =~ s/\n./\n /g;
1725 $cond =~ s/\n./\n /g;
1727 # Find the real next line.
1728 $realline_next = $line_nr_next;
1729 if (defined $realline_next &&
1730 (!defined $lines[$realline_next - 1] ||
1731 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1732 $realline_next++;
1735 my $s = $stat;
1736 $s =~ s/{.*$//s;
1738 # Ignore goto labels.
1739 if ($s =~ /$Ident:\*$/s) {
1741 # Ignore functions being called
1742 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1744 } elsif ($s =~ /^.\s*else\b/s) {
1746 # declarations always start with types
1747 } 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) {
1748 my $type = $1;
1749 $type =~ s/\s+/ /g;
1750 possible($type, "A:" . $s);
1752 # definitions in global scope can only start with types
1753 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1754 possible($1, "B:" . $s);
1757 # any (foo ... *) is a pointer cast, and foo is a type
1758 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1759 possible($1, "C:" . $s);
1762 # Check for any sort of function declaration.
1763 # int foo(something bar, other baz);
1764 # void (*store_gdt)(x86_descr_ptr *);
1765 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1766 my ($name_len) = length($1);
1768 my $ctx = $s;
1769 substr($ctx, 0, $name_len + 1, '');
1770 $ctx =~ s/\)[^\)]*$//;
1772 for my $arg (split(/\s*,\s*/, $ctx)) {
1773 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1775 possible($1, "D:" . $s);
1783 # Checks which may be anchored in the context.
1786 # Check for switch () and associated case and default
1787 # statements should be at the same indent.
1788 if ($line=~/\bswitch\s*\(.*\)/) {
1789 my $err = '';
1790 my $sep = '';
1791 my @ctx = ctx_block_outer($linenr, $realcnt);
1792 shift(@ctx);
1793 for my $ctx (@ctx) {
1794 my ($clen, $cindent) = line_stats($ctx);
1795 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1796 $indent != $cindent) {
1797 $err .= "$sep$ctx\n";
1798 $sep = '';
1799 } else {
1800 $sep = "[...]\n";
1803 if ($err ne '') {
1804 ERROR("switch and case should be at the same indent\n$hereline$err");
1808 # if/while/etc brace do not go on next line, unless defining a do while loop,
1809 # or if that brace on the next line is for something else
1810 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1811 my $pre_ctx = "$1$2";
1813 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1814 my $ctx_cnt = $realcnt - $#ctx - 1;
1815 my $ctx = join("\n", @ctx);
1817 my $ctx_ln = $linenr;
1818 my $ctx_skip = $realcnt;
1820 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1821 defined $lines[$ctx_ln - 1] &&
1822 $lines[$ctx_ln - 1] =~ /^-/)) {
1823 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1824 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1825 $ctx_ln++;
1828 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1829 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1831 # The length of the "previous line" is checked against 80 because it
1832 # includes the + at the beginning of the line (if the actual line has
1833 # 79 or 80 characters, it is no longer possible to add a space and an
1834 # opening brace there)
1835 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1836 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1837 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1838 ERROR("that open brace { should be on the previous line\n" .
1839 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1841 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1842 $ctx =~ /\)\s*\;\s*$/ &&
1843 defined $lines[$ctx_ln - 1])
1845 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1846 if ($nindent > $indent) {
1847 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1848 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1853 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1854 if ($line =~ /while\s*\((0|false)\);/) {
1855 ERROR("suspicious ; after while (0)\n" . $herecurr);
1858 # Check superfluous trailing ';'
1859 if ($line =~ /;;$/) {
1860 ERROR("superfluous trailing semicolon\n" . $herecurr);
1863 # Check relative indent for conditionals and blocks.
1864 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1865 my ($s, $c) = ($stat, $cond);
1867 substr($s, 0, length($c), '');
1869 # Make sure we remove the line prefixes as we have
1870 # none on the first line, and are going to readd them
1871 # where necessary.
1872 $s =~ s/\n./\n/gs;
1874 # Find out how long the conditional actually is.
1875 my @newlines = ($c =~ /\n/gs);
1876 my $cond_lines = 1 + $#newlines;
1878 # We want to check the first line inside the block
1879 # starting at the end of the conditional, so remove:
1880 # 1) any blank line termination
1881 # 2) any opening brace { on end of the line
1882 # 3) any do (...) {
1883 my $continuation = 0;
1884 my $check = 0;
1885 $s =~ s/^.*\bdo\b//;
1886 $s =~ s/^\s*\{//;
1887 if ($s =~ s/^\s*\\//) {
1888 $continuation = 1;
1890 if ($s =~ s/^\s*?\n//) {
1891 $check = 1;
1892 $cond_lines++;
1895 # Also ignore a loop construct at the end of a
1896 # preprocessor statement.
1897 if (($prevline =~ /^.\s*#\s*define\s/ ||
1898 $prevline =~ /\\\s*$/) && $continuation == 0) {
1899 $check = 0;
1902 my $cond_ptr = -1;
1903 $continuation = 0;
1904 while ($cond_ptr != $cond_lines) {
1905 $cond_ptr = $cond_lines;
1907 # If we see an #else/#elif then the code
1908 # is not linear.
1909 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1910 $check = 0;
1913 # Ignore:
1914 # 1) blank lines, they should be at 0,
1915 # 2) preprocessor lines, and
1916 # 3) labels.
1917 if ($continuation ||
1918 $s =~ /^\s*?\n/ ||
1919 $s =~ /^\s*#\s*?/ ||
1920 $s =~ /^\s*$Ident\s*:/) {
1921 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1922 if ($s =~ s/^.*?\n//) {
1923 $cond_lines++;
1928 my (undef, $sindent) = line_stats("+" . $s);
1929 my $stat_real = raw_line($linenr, $cond_lines);
1931 # Check if either of these lines are modified, else
1932 # this is not this patch's fault.
1933 if (!defined($stat_real) ||
1934 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1935 $check = 0;
1937 if (defined($stat_real) && $cond_lines > 1) {
1938 $stat_real = "[...]\n$stat_real";
1941 #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";
1943 if ($check && (($sindent % 4) != 0 ||
1944 ($sindent <= $indent && $s ne ''))) {
1945 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1949 # Track the 'values' across context and added lines.
1950 my $opline = $line; $opline =~ s/^./ /;
1951 my ($curr_values, $curr_vars) =
1952 annotate_values($opline . "\n", $prev_values);
1953 $curr_values = $prev_values . $curr_values;
1954 if ($dbg_values) {
1955 my $outline = $opline; $outline =~ s/\t/ /g;
1956 print "$linenr > .$outline\n";
1957 print "$linenr > $curr_values\n";
1958 print "$linenr > $curr_vars\n";
1960 $prev_values = substr($curr_values, -1);
1962 #ignore lines not being added
1963 if ($line=~/^[^\+]/) {next;}
1965 # TEST: allow direct testing of the type matcher.
1966 if ($dbg_type) {
1967 if ($line =~ /^.\s*$Declare\s*$/) {
1968 ERROR("TEST: is type\n" . $herecurr);
1969 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1970 ERROR("TEST: is not type ($1 is)\n". $herecurr);
1972 next;
1974 # TEST: allow direct testing of the attribute matcher.
1975 if ($dbg_attr) {
1976 if ($line =~ /^.\s*$Modifier\s*$/) {
1977 ERROR("TEST: is attr\n" . $herecurr);
1978 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1979 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1981 next;
1984 # check for initialisation to aggregates open brace on the next line
1985 if ($line =~ /^.\s*\{/ &&
1986 $prevline =~ /(?:^|[^=])=\s*$/) {
1987 ERROR("that open brace { should be on the previous line\n" . $hereprev);
1991 # Checks which are anchored on the added line.
1994 # check for malformed paths in #include statements (uses RAW line)
1995 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1996 my $path = $1;
1997 if ($path =~ m{//}) {
1998 ERROR("malformed #include filename\n" .
1999 $herecurr);
2003 # no C99 // comments
2004 if ($line =~ m{//} &&
2005 $rawline !~ m{// SPDX-License-Identifier: }) {
2006 ERROR("do not use C99 // comments\n" . $herecurr);
2008 # Remove C99 comments.
2009 $line =~ s@//.*@@;
2010 $opline =~ s@//.*@@;
2012 # check for global initialisers.
2013 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
2014 ERROR("do not initialise globals to 0 or NULL\n" .
2015 $herecurr);
2017 # check for static initialisers.
2018 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2019 ERROR("do not initialise statics to 0 or NULL\n" .
2020 $herecurr);
2023 # * goes on variable not on type
2024 # (char*[ const])
2025 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
2026 my ($from, $to) = ($1, $1);
2028 # Should start with a space.
2029 $to =~ s/^(\S)/ $1/;
2030 # Should not end with a space.
2031 $to =~ s/\s+$//;
2032 # '*'s should not have spaces between.
2033 while ($to =~ s/\*\s+\*/\*\*/) {
2036 #print "from<$from> to<$to>\n";
2037 if ($from ne $to) {
2038 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
2040 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
2041 my ($from, $to, $ident) = ($1, $1, $2);
2043 # Should start with a space.
2044 $to =~ s/^(\S)/ $1/;
2045 # Should not end with a space.
2046 $to =~ s/\s+$//;
2047 # '*'s should not have spaces between.
2048 while ($to =~ s/\*\s+\*/\*\*/) {
2050 # Modifiers should have spaces.
2051 $to =~ s/(\b$Modifier$)/$1 /;
2053 #print "from<$from> to<$to> ident<$ident>\n";
2054 if ($from ne $to && $ident !~ /^$Modifier$/) {
2055 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
2059 # function brace can't be on same line, except for #defines of do while,
2060 # or if closed on same line
2061 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2062 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
2063 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
2066 # open braces for enum, union and struct go on the same line.
2067 if ($line =~ /^.\s*\{/ &&
2068 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2069 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
2072 # missing space after union, struct or enum definition
2073 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
2074 ERROR("missing space after $1 definition\n" . $herecurr);
2077 # check for spacing round square brackets; allowed:
2078 # 1. with a type on the left -- int [] a;
2079 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2080 # 3. inside a curly brace -- = { [0...10] = 5 }
2081 # 4. after a comma -- [1] = 5, [2] = 6
2082 # 5. in a macro definition -- #define abc(x) [x] = y
2083 while ($line =~ /(.*?\s)\[/g) {
2084 my ($where, $prefix) = ($-[1], $1);
2085 if ($prefix !~ /$Type\s+$/ &&
2086 ($where != 0 || $prefix !~ /^.\s+$/) &&
2087 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
2088 $prefix !~ /[,{:]\s+$/) {
2089 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
2093 # check for spaces between functions and their parentheses.
2094 while ($line =~ /($Ident)\s+\(/g) {
2095 my $name = $1;
2096 my $ctx_before = substr($line, 0, $-[1]);
2097 my $ctx = "$ctx_before$name";
2099 # Ignore those directives where spaces _are_ permitted.
2100 if ($name =~ /^(?:
2101 if|for|while|switch|return|case|
2102 volatile|__volatile__|coroutine_fn|
2103 __attribute__|format|__extension__|
2104 asm|__asm__)$/x)
2107 # Ignore 'catch (...)' in C++
2108 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
2110 # cpp #define statements have non-optional spaces, ie
2111 # if there is a space between the name and the open
2112 # parenthesis it is simply not a parameter group.
2113 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2115 # cpp #elif statement condition may start with a (
2116 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2118 # If this whole things ends with a type its most
2119 # likely a typedef for a function.
2120 } elsif ($ctx =~ /$Type$/) {
2122 } else {
2123 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
2126 # Check operator spacing.
2127 if (!($line=~/\#\s*include/)) {
2128 my $ops = qr{
2129 <<=|>>=|<=|>=|==|!=|
2130 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2131 =>|->|<<|>>|<|>|=|!|~|
2132 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2133 \?|::|:
2135 my @elements = split(/($ops|;)/, $opline);
2136 my $off = 0;
2138 my $blank = copy_spacing($opline);
2140 for (my $n = 0; $n < $#elements; $n += 2) {
2141 $off += length($elements[$n]);
2143 # Pick up the preceding and succeeding characters.
2144 my $ca = substr($opline, 0, $off);
2145 my $cc = '';
2146 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2147 $cc = substr($opline, $off + length($elements[$n + 1]));
2149 my $cb = "$ca$;$cc";
2151 my $a = '';
2152 $a = 'V' if ($elements[$n] ne '');
2153 $a = 'W' if ($elements[$n] =~ /\s$/);
2154 $a = 'C' if ($elements[$n] =~ /$;$/);
2155 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2156 $a = 'O' if ($elements[$n] eq '');
2157 $a = 'E' if ($ca =~ /^\s*$/);
2159 my $op = $elements[$n + 1];
2161 my $c = '';
2162 if (defined $elements[$n + 2]) {
2163 $c = 'V' if ($elements[$n + 2] ne '');
2164 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2165 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2166 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2167 $c = 'O' if ($elements[$n + 2] eq '');
2168 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2169 } else {
2170 $c = 'E';
2173 my $ctx = "${a}x${c}";
2175 my $at = "(ctx:$ctx)";
2177 my $ptr = substr($blank, 0, $off) . "^";
2178 my $hereptr = "$hereline$ptr\n";
2180 # Pull out the value of this operator.
2181 my $op_type = substr($curr_values, $off + 1, 1);
2183 # Get the full operator variant.
2184 my $opv = $op . substr($curr_vars, $off, 1);
2186 # Ignore operators passed as parameters.
2187 if ($op_type ne 'V' &&
2188 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2190 # # Ignore comments
2191 # } elsif ($op =~ /^$;+$/) {
2193 # ; should have either the end of line or a space or \ after it
2194 } elsif ($op eq ';') {
2195 if ($ctx !~ /.x[WEBC]/ &&
2196 $cc !~ /^\\/ && $cc !~ /^;/) {
2197 ERROR("space required after that '$op' $at\n" . $hereptr);
2200 # // is a comment
2201 } elsif ($op eq '//') {
2203 # Ignore : used in class declaration in C++
2204 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2205 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2207 # No spaces for:
2208 # ->
2209 # : when part of a bitfield
2210 } elsif ($op eq '->' || $opv eq ':B') {
2211 if ($ctx =~ /Wx.|.xW/) {
2212 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2215 # , must have a space on the right.
2216 # not required when having a single },{ on one line
2217 } elsif ($op eq ',') {
2218 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2219 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2220 ERROR("space required after that '$op' $at\n" . $hereptr);
2223 # '*' as part of a type definition -- reported already.
2224 } elsif ($opv eq '*_') {
2225 #warn "'*' is part of type\n";
2227 # unary operators should have a space before and
2228 # none after. May be left adjacent to another
2229 # unary operator, or a cast
2230 } elsif ($op eq '!' || $op eq '~' ||
2231 $opv eq '*U' || $opv eq '-U' ||
2232 $opv eq '&U' || $opv eq '&&U') {
2233 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2234 # '~' used as a name of Destructor
2236 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2237 ERROR("space required before that '$op' $at\n" . $hereptr);
2239 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2240 # A unary '*' may be const
2242 } elsif ($ctx =~ /.xW/) {
2243 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2246 # unary ++ and unary -- are allowed no space on one side.
2247 } elsif ($op eq '++' or $op eq '--') {
2248 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2249 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2251 if ($ctx =~ /Wx[BE]/ ||
2252 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2253 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2255 if ($ctx =~ /ExW/) {
2256 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2259 # A colon needs no spaces before when it is
2260 # terminating a case value or a label.
2261 } elsif ($opv eq ':C' || $opv eq ':L') {
2262 if ($ctx =~ /Wx./) {
2263 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2266 # All the others need spaces both sides.
2267 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2268 my $ok = 0;
2270 if ($realfile =~ /\.cpp|\.h$/) {
2271 # Ignore template arguments <...> in C++
2272 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2273 $ok = 1;
2276 # Ignore :: in C++
2277 if ($op eq '::') {
2278 $ok = 1;
2282 # Ignore email addresses <foo@bar>
2283 if (($op eq '<' &&
2284 $cc =~ /^\S+\@\S+>/) ||
2285 ($op eq '>' &&
2286 $ca =~ /<\S+\@\S+$/))
2288 $ok = 1;
2291 # Ignore ?:
2292 if (($opv eq ':O' && $ca =~ /\?$/) ||
2293 ($op eq '?' && $cc =~ /^:/)) {
2294 $ok = 1;
2297 if ($ok == 0) {
2298 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2301 $off += length($elements[$n + 1]);
2305 #need space before brace following if, while, etc
2306 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2307 $line =~ /do\{/) {
2308 ERROR("space required before the open brace '{'\n" . $herecurr);
2311 # closing brace should have a space following it when it has anything
2312 # on the line
2313 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2314 ERROR("space required after that close brace '}'\n" . $herecurr);
2317 # check spacing on square brackets
2318 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2319 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2321 if ($line =~ /\s\]/) {
2322 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2325 # check spacing on parentheses
2326 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2327 $line !~ /for\s*\(\s+;/) {
2328 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2330 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2331 $line !~ /for\s*\(.*;\s+\)/ &&
2332 $line !~ /:\s+\)/) {
2333 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2336 # Return is not a function.
2337 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2338 my $spacing = $1;
2339 my $value = $2;
2341 # Flatten any parentheses
2342 $value =~ s/\(/ \(/g;
2343 $value =~ s/\)/\) /g;
2344 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2345 $value !~ /(?:$Ident|-?$Constant)\s*
2346 $Compare\s*
2347 (?:$Ident|-?$Constant)/x &&
2348 $value =~ s/\([^\(\)]*\)/1/) {
2350 #print "value<$value>\n";
2351 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/ &&
2352 $line =~ /;$/) {
2353 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2355 } elsif ($spacing !~ /\s+/) {
2356 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2359 # Return of what appears to be an errno should normally be -'ve
2360 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2361 my $name = $1;
2362 if ($name ne 'EOF' && $name ne 'ERROR') {
2363 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2367 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2368 $line !~ /^.typedef/) {
2369 ERROR("named $1 should be typedefed separately\n" . $herecurr);
2372 # Need a space before open parenthesis after if, while etc
2373 if ($line=~/\b(if|while|for|switch)\(/) {
2374 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2377 # Check for illegal assignment in if conditional -- and check for trailing
2378 # statements after the conditional.
2379 if ($line =~ /do\s*(?!{)/) {
2380 my ($stat_next) = ctx_statement_block($line_nr_next,
2381 $remain_next, $off_next);
2382 $stat_next =~ s/\n./\n /g;
2383 ##print "stat<$stat> stat_next<$stat_next>\n";
2385 if ($stat_next =~ /^\s*while\b/) {
2386 # If the statement carries leading newlines,
2387 # then count those as offsets.
2388 my ($whitespace) =
2389 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2390 my $offset =
2391 statement_rawlines($whitespace) - 1;
2393 $suppress_whiletrailers{$line_nr_next +
2394 $offset} = 1;
2397 if (!defined $suppress_whiletrailers{$linenr} &&
2398 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2399 my ($s, $c) = ($stat, $cond);
2401 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2402 ERROR("do not use assignment in if condition\n" . $herecurr);
2405 # Find out what is on the end of the line after the
2406 # conditional.
2407 substr($s, 0, length($c), '');
2408 $s =~ s/\n.*//g;
2409 $s =~ s/$;//g; # Remove any comments
2410 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2411 $c !~ /}\s*while\s*/)
2413 # Find out how long the conditional actually is.
2414 my @newlines = ($c =~ /\n/gs);
2415 my $cond_lines = 1 + $#newlines;
2416 my $stat_real = '';
2418 $stat_real = raw_line($linenr, $cond_lines)
2419 . "\n" if ($cond_lines);
2420 if (defined($stat_real) && $cond_lines > 1) {
2421 $stat_real = "[...]\n$stat_real";
2424 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2428 # Check for bitwise tests written as boolean
2429 if ($line =~ /
2431 (?:\[|\(|\&\&|\|\|)
2432 \s*0[xX][0-9]+\s*
2433 (?:\&\&|\|\|)
2435 (?:\&\&|\|\|)
2436 \s*0[xX][0-9]+\s*
2437 (?:\&\&|\|\||\)|\])
2438 )/x)
2440 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2443 # if and else should not have general statements after it
2444 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2445 my $s = $1;
2446 $s =~ s/$;//g; # Remove any comments
2447 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2448 ERROR("trailing statements should be on next line\n" . $herecurr);
2451 # if should not continue a brace
2452 if ($line =~ /}\s*if\b/) {
2453 ERROR("trailing statements should be on next line\n" .
2454 $herecurr);
2456 # case and default should not have general statements after them
2457 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2458 $line !~ /\G(?:
2459 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2460 \s*return\s+
2461 )/xg)
2463 ERROR("trailing statements should be on next line\n" . $herecurr);
2466 # Check for }<nl>else {, these must be at the same
2467 # indent level to be relevant to each other.
2468 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2469 $previndent == $indent) {
2470 ERROR("else should follow close brace '}'\n" . $hereprev);
2473 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2474 $previndent == $indent) {
2475 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2477 # Find out what is on the end of the line after the
2478 # conditional.
2479 substr($s, 0, length($c), '');
2480 $s =~ s/\n.*//g;
2482 if ($s =~ /^\s*;/) {
2483 ERROR("while should follow close brace '}'\n" . $hereprev);
2487 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2488 # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2489 # print "No studly caps, use _\n";
2490 # print "$herecurr";
2491 # $clean = 0;
2494 #no spaces allowed after \ in define
2495 if ($line=~/\#\s*define.*\\\s$/) {
2496 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2499 # multi-statement macros should be enclosed in a do while loop, grab the
2500 # first statement and ensure its the whole macro if its not enclosed
2501 # in a known good container
2502 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2503 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2504 my $ln = $linenr;
2505 my $cnt = $realcnt;
2506 my ($off, $dstat, $dcond, $rest);
2507 my $ctx = '';
2509 my $args = defined($1);
2511 # Find the end of the macro and limit our statement
2512 # search to that.
2513 while ($cnt > 0 && defined $lines[$ln - 1] &&
2514 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2516 $ctx .= $rawlines[$ln - 1] . "\n";
2517 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2518 $ln++;
2520 $ctx .= $rawlines[$ln - 1];
2522 ($dstat, $dcond, $ln, $cnt, $off) =
2523 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2524 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2525 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2527 # Extract the remainder of the define (if any) and
2528 # rip off surrounding spaces, and trailing \'s.
2529 $rest = '';
2530 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2531 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2532 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2533 $rest .= substr($lines[$ln - 1], $off) . "\n";
2534 $cnt--;
2536 $ln++;
2537 $off = 0;
2539 $rest =~ s/\\\n.//g;
2540 $rest =~ s/^\s*//s;
2541 $rest =~ s/\s*$//s;
2543 # Clean up the original statement.
2544 if ($args) {
2545 substr($dstat, 0, length($dcond), '');
2546 } else {
2547 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2549 $dstat =~ s/$;//g;
2550 $dstat =~ s/\\\n.//g;
2551 $dstat =~ s/^\s*//s;
2552 $dstat =~ s/\s*$//s;
2554 # Flatten any parentheses and braces
2555 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2556 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2557 $dstat =~ s/\[[^\{\}]*\]/1/)
2561 my $exceptions = qr{
2562 $Declare|
2563 module_param_named|
2564 MODULE_PARAM_DESC|
2565 DECLARE_PER_CPU|
2566 DEFINE_PER_CPU|
2567 __typeof__\(|
2568 union|
2569 struct|
2570 \.$Ident\s*=\s*|
2571 ^\"|\"$
2573 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2574 if ($rest ne '' && $rest ne ',') {
2575 if ($rest !~ /while\s*\(/ &&
2576 $dstat !~ /$exceptions/)
2578 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2581 } elsif ($ctx !~ /;/) {
2582 if ($dstat ne '' &&
2583 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2584 $dstat !~ /$exceptions/ &&
2585 $dstat !~ /^\.$Ident\s*=/ &&
2586 $dstat =~ /$Operators/)
2588 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2593 # check for missing bracing around if etc
2594 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2595 $line !~ /\#\s*if/) {
2596 my $allowed = 0;
2598 # Check the pre-context.
2599 if ($line =~ /(\}.*?)$/) {
2600 my $pre = $1;
2602 if ($line !~ /else/) {
2603 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2604 if $dbg_adv_apw;
2605 $allowed = 1;
2608 my ($level, $endln, @chunks) =
2609 ctx_statement_full($linenr, $realcnt, 1);
2610 if ($dbg_adv_apw) {
2611 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2612 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2613 if $#chunks >= 1;
2615 if ($#chunks >= 0 && $level == 0) {
2616 my $seen = 0;
2617 my $herectx = $here . "\n";
2618 my $ln = $linenr - 1;
2619 for my $chunk (@chunks) {
2620 my ($cond, $block) = @{$chunk};
2622 # If the condition carries leading newlines, then count those as offsets.
2623 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2624 my $offset = statement_rawlines($whitespace) - 1;
2626 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2628 # We have looked at and allowed this specific line.
2629 $suppress_ifbraces{$ln + $offset} = 1;
2631 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2632 $ln += statement_rawlines($block) - 1;
2634 substr($block, 0, length($cond), '');
2636 my $spaced_block = $block;
2637 $spaced_block =~ s/\n\+/ /g;
2639 $seen++ if ($spaced_block =~ /^\s*\{/);
2641 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2642 if $dbg_adv_apw;
2643 if (statement_lines($cond) > 1) {
2644 print "APW: ALLOWED: cond<$cond>\n"
2645 if $dbg_adv_apw;
2646 $allowed = 1;
2648 if ($block =~/\b(?:if|for|while)\b/) {
2649 print "APW: ALLOWED: block<$block>\n"
2650 if $dbg_adv_apw;
2651 $allowed = 1;
2653 if (statement_block_size($block) > 1) {
2654 print "APW: ALLOWED: lines block<$block>\n"
2655 if $dbg_adv_apw;
2656 $allowed = 1;
2659 if ($seen != ($#chunks + 1) && !$allowed) {
2660 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2664 if (!defined $suppress_ifbraces{$linenr - 1} &&
2665 $line =~ /\b(if|while|for|else)\b/ &&
2666 $line !~ /\#\s*if/ &&
2667 $line !~ /\#\s*else/) {
2668 my $allowed = 0;
2670 # Check the pre-context.
2671 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2672 my $pre = $1;
2674 if ($line !~ /else/) {
2675 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2676 if $dbg_adv_apw;
2677 $allowed = 1;
2681 my ($level, $endln, @chunks) =
2682 ctx_statement_full($linenr, $realcnt, $-[0]);
2684 # Check the condition.
2685 my ($cond, $block) = @{$chunks[0]};
2686 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2687 if $dbg_adv_checking;
2688 if (defined $cond) {
2689 substr($block, 0, length($cond), '');
2691 if (statement_lines($cond) > 1) {
2692 print "APW: ALLOWED: cond<$cond>\n"
2693 if $dbg_adv_apw;
2694 $allowed = 1;
2696 if ($block =~/\b(?:if|for|while)\b/) {
2697 print "APW: ALLOWED: block<$block>\n"
2698 if $dbg_adv_apw;
2699 $allowed = 1;
2701 if (statement_block_size($block) > 1) {
2702 print "APW: ALLOWED: lines block<$block>\n"
2703 if $dbg_adv_apw;
2704 $allowed = 1;
2706 # Check the post-context.
2707 if (defined $chunks[1]) {
2708 my ($cond, $block) = @{$chunks[1]};
2709 if (defined $cond) {
2710 substr($block, 0, length($cond), '');
2712 if ($block =~ /^\s*\{/) {
2713 print "APW: ALLOWED: chunk-1 block<$block>\n"
2714 if $dbg_adv_apw;
2715 $allowed = 1;
2718 print "DCS: level=$level block<$block> allowed=$allowed\n"
2719 if $dbg_adv_dcs;
2720 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2721 my $herectx = $here . "\n";;
2722 my $cnt = statement_rawlines($block);
2724 for (my $n = 0; $n < $cnt; $n++) {
2725 $herectx .= raw_line($linenr, $n) . "\n";;
2728 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2732 # no volatiles please
2733 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2734 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
2735 $line !~ /sig_atomic_t/ &&
2736 !ctx_has_comment($first_line, $linenr)) {
2737 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
2738 ERROR($msg);
2741 # warn about #if 0
2742 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2743 ERROR("if this code is redundant consider removing it\n" .
2744 $herecurr);
2747 # check for needless g_free() checks
2748 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2749 my $expr = $1;
2750 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2751 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2755 # warn about #ifdefs in C files
2756 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2757 # print "#ifdef in C files should be avoided\n";
2758 # print "$herecurr";
2759 # $clean = 0;
2762 # warn about spacing in #ifdefs
2763 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2764 ERROR("exactly one space required after that #$1\n" . $herecurr);
2766 # check for memory barriers without a comment.
2767 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2768 if (!ctx_has_comment($first_line, $linenr)) {
2769 ERROR("memory barrier without comment\n" . $herecurr);
2772 # check of hardware specific defines
2773 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2774 # where they might be necessary.
2775 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2776 WARN("architecture specific defines should be avoided\n" . $herecurr);
2779 # Check that the storage class is at the beginning of a declaration
2780 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2781 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2784 # check the location of the inline attribute, that it is between
2785 # storage class and type.
2786 if ($line =~ /\b$Type\s+$Inline\b/ ||
2787 $line =~ /\b$Inline\s+$Storage\b/) {
2788 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2791 # check for sizeof(&)
2792 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2793 ERROR("sizeof(& should be avoided\n" . $herecurr);
2796 # check for new externs in .c files.
2797 if ($realfile =~ /\.c$/ && defined $stat &&
2798 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2800 my $function_name = $1;
2801 my $paren_space = $2;
2803 my $s = $stat;
2804 if (defined $cond) {
2805 substr($s, 0, length($cond), '');
2807 if ($s =~ /^\s*;/ &&
2808 $function_name ne 'uninitialized_var')
2810 ERROR("externs should be avoided in .c files\n" . $herecurr);
2813 if ($paren_space =~ /\n/) {
2814 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2817 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2818 $stat =~ /^.\s*extern\s+/)
2820 ERROR("externs should be avoided in .c files\n" . $herecurr);
2823 # check for pointless casting of g_malloc return
2824 if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2825 if ($2 == 'm') {
2826 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2827 } else {
2828 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2832 # check for gcc specific __FUNCTION__
2833 if ($line =~ /__FUNCTION__/) {
2834 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
2837 # recommend g_path_get_* over g_strdup(basename/dirname(...))
2838 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
2839 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
2842 # recommend qemu_strto* over strto* for numeric conversions
2843 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2844 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2846 # recommend sigaction over signal for portability, when establishing a handler
2847 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2848 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2850 # check for module_init(), use category-specific init macros explicitly please
2851 if ($line =~ /^module_init\s*\(/) {
2852 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2854 # check for various ops structs, ensure they are const.
2855 my $struct_ops = qr{AIOCBInfo|
2856 BdrvActionOps|
2857 BlockDevOps|
2858 BlockJobDriver|
2859 DisplayChangeListenerOps|
2860 GraphicHwOps|
2861 IDEDMAOps|
2862 KVMCapabilityInfo|
2863 MemoryRegionIOMMUOps|
2864 MemoryRegionOps|
2865 MemoryRegionPortio|
2866 QEMUFileOps|
2867 SCSIBusInfo|
2868 SCSIReqOps|
2869 Spice[A-Z][a-zA-Z0-9]*Interface|
2870 USBDesc[A-Z][a-zA-Z0-9]*|
2871 VhostOps|
2872 VMStateDescription|
2873 VMStateInfo}x;
2874 if ($line !~ /\bconst\b/ &&
2875 $line =~ /\b($struct_ops)\b.*=/) {
2876 ERROR("initializer for struct $1 should normally be const\n" .
2877 $herecurr);
2880 # check for %L{u,d,i} in strings
2881 my $string;
2882 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2883 $string = substr($rawline, $-[1], $+[1] - $-[1]);
2884 $string =~ s/%%/__/g;
2885 if ($string =~ /(?<!%)%L[udi]/) {
2886 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2887 last;
2891 # QEMU specific tests
2892 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2893 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2896 # Qemu error function tests
2898 # Find newlines in error messages
2899 my $qemu_error_funcs = qr{error_setg|
2900 error_setg_errno|
2901 error_setg_win32|
2902 error_setg_file_open|
2903 error_set|
2904 error_prepend|
2905 warn_reportf_err|
2906 error_reportf_err|
2907 error_vreport|
2908 warn_vreport|
2909 info_vreport|
2910 error_report|
2911 warn_report|
2912 info_report|
2913 g_test_message}x;
2915 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2916 ERROR("Error messages should not contain newlines\n" . $herecurr);
2919 # Continue checking for error messages that contains newlines. This
2920 # check handles cases where string literals are spread over multiple lines.
2921 # Example:
2922 # error_report("Error msg line #1"
2923 # "Error msg line #2\n");
2924 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2925 my $continued_str_literal = qr{\+\s*\".*\"};
2927 if ($rawline =~ /$quoted_newline_regex/) {
2928 # Backtrack to first line that does not contain only a quoted literal
2929 # and assume that it is the start of the statement.
2930 my $i = $linenr - 2;
2932 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2933 $i--;
2936 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2937 ERROR("Error messages should not contain newlines\n" . $herecurr);
2941 # check for non-portable libc calls that have portable alternatives in QEMU
2942 if ($line =~ /\bffs\(/) {
2943 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2945 if ($line =~ /\bffsl\(/) {
2946 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2948 if ($line =~ /\bffsll\(/) {
2949 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2951 if ($line =~ /\bbzero\(/) {
2952 ERROR("use memset() instead of bzero()\n" . $herecurr);
2954 if ($line =~ /\bgetpagesize\(\)/) {
2955 ERROR("use qemu_real_host_page_size instead of getpagesize()\n" . $herecurr);
2957 if ($line =~ /\bsysconf\(_SC_PAGESIZE\)/) {
2958 ERROR("use qemu_real_host_page_size instead of sysconf(_SC_PAGESIZE)\n" . $herecurr);
2960 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2961 g_assert_cmpint|
2962 g_assert_cmpuint|
2963 g_assert_cmphex|
2964 g_assert_cmpfloat|
2965 g_assert_true|
2966 g_assert_false|
2967 g_assert_nonnull|
2968 g_assert_null|
2969 g_assert_no_error|
2970 g_assert_error|
2971 g_test_assert_expected_messages|
2972 g_test_trap_assert_passed|
2973 g_test_trap_assert_stdout|
2974 g_test_trap_assert_stdout_unmatched|
2975 g_test_trap_assert_stderr|
2976 g_test_trap_assert_stderr_unmatched}x;
2977 if ($realfile !~ /^tests\// &&
2978 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2979 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
2983 if ($is_patch && $chk_signoff && $signoff == 0) {
2984 ERROR("Missing Signed-off-by: line(s)\n");
2987 # If we have no input at all, then there is nothing to report on
2988 # so just keep quiet.
2989 if ($#rawlines == -1) {
2990 return 1;
2993 # In mailback mode only produce a report in the negative, for
2994 # things that appear to be patches.
2995 if ($mailback && ($clean == 1 || !$is_patch)) {
2996 return 1;
2999 # This is not a patch, and we are are in 'no-patch' mode so
3000 # just keep quiet.
3001 if (!$chk_patch && !$is_patch) {
3002 return 1;
3005 if (!$is_patch) {
3006 ERROR("Does not appear to be a unified-diff format patch\n");
3009 print report_dump();
3010 if ($summary && !($clean == 1 && $quiet == 1)) {
3011 print "$filename " if ($summary_file);
3012 print "total: $cnt_error errors, $cnt_warn warnings, " .
3013 "$cnt_lines lines checked\n";
3014 print "\n" if ($quiet == 0);
3017 if ($quiet == 0) {
3018 # If there were whitespace errors which cleanpatch can fix
3019 # then suggest that.
3020 # if ($rpt_cleaners) {
3021 # print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
3022 # print " scripts/cleanfile\n\n";
3026 if ($clean == 1 && $quiet == 0) {
3027 print "$vname has no obvious style problems and is ready for submission.\n"
3029 if ($clean == 0 && $quiet == 0) {
3030 print "$vname has style problems, please review. If any of these errors\n";
3031 print "are false positives report them to the maintainer, see\n";
3032 print "CHECKPATCH in MAINTAINERS.\n";
3035 return ($no_warnings ? $clean : $cnt_error == 0);