tests: acpi: prepare for changing DSDT tables
[qemu/kevin.git] / scripts / checkpatch.pl
blobcb8eff233e0656e8d64344e2325467cb8671f114
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)(\.inc)?|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;
39 sub help {
40 my ($exitcode) = @_;
42 print << "EOM";
43 Usage:
45 $P [OPTION]... [FILE]...
46 $P [OPTION]... [GIT-REV-LIST]
48 Version: $V
50 Options:
51 -q, --quiet quiet
52 --no-tree run without a qemu tree
53 --no-signoff do not check for 'Signed-off-by' line
54 --patch treat FILE as patchfile
55 --branch treat args as GIT revision list
56 --emacs emacs compile window format
57 --terse one line per report
58 -f, --file treat FILE as regular source file
59 --strict fail if only warnings are found
60 --root=PATH PATH to the qemu tree root
61 --no-summary suppress the per-file summary
62 --mailback only produce a report in case of warnings/errors
63 --summary-file include the filename in summary
64 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
65 'values', 'possible', 'type', and 'attr' (default
66 is all off)
67 --test-only=WORD report only warnings/errors containing WORD
68 literally
69 --color[=WHEN] Use colors 'always', 'never', or only when output
70 is a terminal ('auto'). Default is 'auto'.
71 -h, --help, --version display this help and exit
73 When FILE is - read standard input.
74 EOM
76 exit($exitcode);
79 # Perl's Getopt::Long allows options to take optional arguments after a space.
80 # Prevent --color by itself from consuming other arguments
81 foreach (@ARGV) {
82 if ($_ eq "--color" || $_ eq "-color") {
83 $_ = "--color=$color";
87 GetOptions(
88 'q|quiet+' => \$quiet,
89 'tree!' => \$tree,
90 'signoff!' => \$chk_signoff,
91 'patch!' => \$chk_patch,
92 'branch!' => \$chk_branch,
93 'emacs!' => \$emacs,
94 'terse!' => \$terse,
95 'f|file!' => \$file,
96 'strict!' => \$no_warnings,
97 'root=s' => \$root,
98 'summary!' => \$summary,
99 'mailback!' => \$mailback,
100 'summary-file!' => \$summary_file,
102 'debug=s' => \%debug,
103 'test-only=s' => \$tst_only,
104 'color=s' => \$color,
105 'no-color' => sub { $color = 'never'; },
106 'h|help' => \$help,
107 'version' => \$help
108 ) or help(1);
110 help(0) if ($help);
112 my $exit = 0;
114 if ($#ARGV < 0) {
115 print "$P: no input files\n";
116 exit(1);
119 if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
120 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
121 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
122 $chk_patch = $chk_branch || $file ? 0 : 1;
123 } elsif (!defined $chk_branch && !defined $chk_patch) {
124 if ($file) {
125 $chk_branch = $chk_patch = 0;
126 } else {
127 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
128 $chk_patch = $chk_branch ? 0 : 1;
130 } elsif (!defined $chk_branch && !defined $file) {
131 if ($chk_patch) {
132 $chk_branch = $file = 0;
133 } else {
134 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
135 $file = $chk_branch ? 0 : 1;
137 } elsif (!defined $chk_patch && !defined $file) {
138 if ($chk_branch) {
139 $chk_patch = $file = 0;
140 } else {
141 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
142 $chk_patch = $file ? 0 : 1;
144 } elsif (!defined $chk_branch) {
145 $chk_branch = $chk_patch || $file ? 0 : 1;
146 } elsif (!defined $chk_patch) {
147 $chk_patch = $chk_branch || $file ? 0 : 1;
148 } elsif (!defined $file) {
149 $file = $chk_patch || $chk_branch ? 0 : 1;
152 if (($chk_patch && $chk_branch) ||
153 ($chk_patch && $file) ||
154 ($chk_branch && $file)) {
155 die "Only one of --file, --branch, --patch is permitted\n";
157 if (!$chk_patch && !$chk_branch && !$file) {
158 die "One of --file, --branch, --patch is required\n";
161 if ($color =~ /^always$/i) {
162 $color = 1;
163 } elsif ($color =~ /^never$/i) {
164 $color = 0;
165 } elsif ($color =~ /^auto$/i) {
166 $color = (-t STDOUT);
167 } else {
168 die "Invalid color mode: $color\n";
171 my $dbg_values = 0;
172 my $dbg_possible = 0;
173 my $dbg_type = 0;
174 my $dbg_attr = 0;
175 my $dbg_adv_dcs = 0;
176 my $dbg_adv_checking = 0;
177 my $dbg_adv_apw = 0;
178 for my $key (keys %debug) {
179 ## no critic
180 eval "\${dbg_$key} = '$debug{$key}';";
181 die "$@" if ($@);
184 my $rpt_cleaners = 0;
186 if ($terse) {
187 $emacs = 1;
188 $quiet++;
191 if ($tree) {
192 if (defined $root) {
193 if (!top_of_kernel_tree($root)) {
194 die "$P: $root: --root does not point at a valid tree\n";
196 } else {
197 if (top_of_kernel_tree('.')) {
198 $root = '.';
199 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
200 top_of_kernel_tree($1)) {
201 $root = $1;
205 if (!defined $root) {
206 print "Must be run from the top-level dir. of a qemu tree\n";
207 exit(2);
211 my $emitted_corrupt = 0;
213 our $Ident = qr{
214 [A-Za-z_][A-Za-z\d_]*
215 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
217 our $Storage = qr{extern|static|asmlinkage};
218 our $Sparse = qr{
219 __force
222 # Notes to $Attribute:
223 our $Attribute = qr{
224 const|
225 volatile|
226 QEMU_NORETURN|
227 QEMU_WARN_UNUSED_RESULT|
228 QEMU_SENTINEL|
229 QEMU_PACKED|
230 GCC_FMT_ATTR
232 our $Modifier;
233 our $Inline = qr{inline};
234 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
235 our $Lval = qr{$Ident(?:$Member)*};
237 our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
238 our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
239 our $Compare = qr{<=|>=|==|!=|<|>};
240 our $Operators = qr{
241 <=|>=|==|!=|
242 =>|->|<<|>>|<|>|!|~|
243 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
246 our $NonptrType;
247 our $Type;
248 our $Declare;
250 our $NON_ASCII_UTF8 = qr{
251 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
252 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
253 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
254 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
255 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
256 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
257 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
260 our $UTF8 = qr{
261 [\x09\x0A\x0D\x20-\x7E] # ASCII
262 | $NON_ASCII_UTF8
265 # some readers default to ISO-8859-1 when showing email source. detect
266 # when UTF-8 is incorrectly interpreted as ISO-8859-1 and reencoded back.
267 # False positives are possible but very unlikely.
268 our $UTF8_MOJIBAKE = qr{
269 \xC3[\x82-\x9F] \xC2[\x80-\xBF] # c2-df 80-bf
270 | \xC3\xA0 \xC2[\xA0-\xBF] \xC2[\x80-\xBF] # e0 a0-bf 80-bf
271 | \xC3[\xA1-\xAC\xAE\xAF] (?: \xC2[\x80-\xBF]){2} # e1-ec/ee/ef 80-bf 80-bf
272 | \xC3\xAD \xC2[\x80-\x9F] \xC2[\x80-\xBF] # ed 80-9f 80-bf
273 | \xC3\xB0 \xC2[\x90-\xBF] (?: \xC2[\x80-\xBF]){2} # f0 90-bf 80-bf 80-bf
274 | \xC3[\xB1-\xB3] (?: \xC2[\x80-\xBF]){3} # f1-f3 80-bf 80-bf 80-bf
275 | \xC3\xB4 \xC2[\x80-\x8F] (?: \xC2[\x80-\xBF]){2} # f4 80-b8 80-bf 80-bf
278 # There are still some false positives, but this catches most
279 # common cases.
280 our $typeTypedefs = qr{(?x:
281 (?![KMGTPE]iB) # IEC binary prefix (do not match)
282 [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]* # camelcase
283 | [A-Z][A-Z\d_]*AIOCB # all uppercase
284 | [A-Z][A-Z\d_]*CPU # all uppercase
285 | QEMUBH # all uppercase
288 our @typeList = (
289 qr{void},
290 qr{(?:unsigned\s+)?char},
291 qr{(?:unsigned\s+)?short},
292 qr{(?:unsigned\s+)?int},
293 qr{(?:unsigned\s+)?long},
294 qr{(?:unsigned\s+)?long\s+int},
295 qr{(?:unsigned\s+)?long\s+long},
296 qr{(?:unsigned\s+)?long\s+long\s+int},
297 qr{unsigned},
298 qr{float},
299 qr{double},
300 qr{bool},
301 qr{struct\s+$Ident},
302 qr{union\s+$Ident},
303 qr{enum\s+$Ident},
304 qr{${Ident}_t},
305 qr{${Ident}_handler},
306 qr{${Ident}_handler_fn},
307 qr{target_(?:u)?long},
308 qr{hwaddr},
309 # external libraries
310 qr{xml${Ident}},
311 qr{xen\w+_handle},
312 # Glib definitions
313 qr{gchar},
314 qr{gshort},
315 qr{glong},
316 qr{gint},
317 qr{gboolean},
318 qr{guchar},
319 qr{gushort},
320 qr{gulong},
321 qr{guint},
322 qr{gfloat},
323 qr{gdouble},
324 qr{gpointer},
325 qr{gconstpointer},
326 qr{gint8},
327 qr{guint8},
328 qr{gint16},
329 qr{guint16},
330 qr{gint32},
331 qr{guint32},
332 qr{gint64},
333 qr{guint64},
334 qr{gsize},
335 qr{gssize},
336 qr{goffset},
337 qr{gintptr},
338 qr{guintptr},
341 # This can be modified by sub possible. Since it can be empty, be careful
342 # about regexes that always match, because they can cause infinite loops.
343 our @modifierList = (
346 sub build_types {
347 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
348 if (@modifierList > 0) {
349 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
350 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
351 } else {
352 $Modifier = qr{(?:$Attribute|$Sparse)};
354 $NonptrType = qr{
355 (?:$Modifier\s+|const\s+)*
357 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
358 (?:$typeTypedefs\b)|
359 (?:${all}\b)
361 (?:\s+$Modifier|\s+const)*
363 $Type = qr{
364 $NonptrType
365 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
366 (?:\s+$Inline|\s+$Modifier)*
368 $Declare = qr{(?:$Storage\s+)?$Type};
370 build_types();
372 $chk_signoff = 0 if ($file);
374 my @rawlines = ();
375 my @lines = ();
376 my $vname;
377 if ($chk_branch) {
378 my @patches;
379 my %git_commits = ();
380 my $HASH;
381 open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--format=%H %s", $ARGV[0]) ||
382 die "$P: git log --reverse --no-merges --format='%H %s' $ARGV[0] failed - $!\n";
384 for my $line (<$HASH>) {
385 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
386 next if (!defined($1) || !defined($2));
387 my $sha1 = $1;
388 my $subject = $2;
389 push(@patches, $sha1);
390 $git_commits{$sha1} = $subject;
393 close $HASH;
395 die "$P: no revisions returned for revlist '$ARGV[0]'\n"
396 unless @patches;
398 my $i = 1;
399 my $num_patches = @patches;
400 for my $hash (@patches) {
401 my $FILE;
402 open($FILE, '-|', "git",
403 "-c", "diff.renamelimit=0",
404 "-c", "diff.renames=True",
405 "-c", "diff.algorithm=histogram",
406 "show",
407 "--patch-with-stat", $hash) ||
408 die "$P: git show $hash - $!\n";
409 while (<$FILE>) {
410 chomp;
411 push(@rawlines, $_);
413 close($FILE);
414 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
415 if ($num_patches > 1 && $quiet == 0) {
416 my $prefix = "$i/$num_patches";
417 $prefix = BLUE . BOLD . $prefix . RESET if $color;
418 print "$prefix Checking commit $vname\n";
419 $vname = "Patch $i/$num_patches";
420 } else {
421 $vname = "Commit " . $vname;
423 if (!process($hash)) {
424 $exit = 1;
425 print "\n" if ($num_patches > 1 && $quiet == 0);
427 @rawlines = ();
428 @lines = ();
429 $i++;
431 } else {
432 for my $filename (@ARGV) {
433 my $FILE;
434 if ($file) {
435 open($FILE, '-|', "diff -u /dev/null $filename") ||
436 die "$P: $filename: diff failed - $!\n";
437 } elsif ($filename eq '-') {
438 open($FILE, '<&STDIN');
439 } else {
440 open($FILE, '<', "$filename") ||
441 die "$P: $filename: open failed - $!\n";
443 if ($filename eq '-') {
444 $vname = 'Your patch';
445 } else {
446 $vname = $filename;
448 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
449 while (<$FILE>) {
450 chomp;
451 push(@rawlines, $_);
453 close($FILE);
454 if (!process($filename)) {
455 $exit = 1;
457 @rawlines = ();
458 @lines = ();
462 exit($exit);
464 sub top_of_kernel_tree {
465 my ($root) = @_;
467 my @tree_check = (
468 "COPYING", "MAINTAINERS", "Makefile",
469 "README.rst", "docs", "VERSION",
470 "linux-user", "softmmu"
473 foreach my $check (@tree_check) {
474 if (! -e $root . '/' . $check) {
475 return 0;
478 return 1;
481 sub expand_tabs {
482 my ($str) = @_;
484 my $res = '';
485 my $n = 0;
486 for my $c (split(//, $str)) {
487 if ($c eq "\t") {
488 $res .= ' ';
489 $n++;
490 for (; ($n % 8) != 0; $n++) {
491 $res .= ' ';
493 next;
495 $res .= $c;
496 $n++;
499 return $res;
501 sub copy_spacing {
502 (my $res = shift) =~ tr/\t/ /c;
503 return $res;
506 sub line_stats {
507 my ($line) = @_;
509 # Drop the diff line leader and expand tabs
510 $line =~ s/^.//;
511 $line = expand_tabs($line);
513 # Pick the indent from the front of the line.
514 my ($white) = ($line =~ /^(\s*)/);
516 return (length($line), length($white));
519 my $sanitise_quote = '';
521 sub sanitise_line_reset {
522 my ($in_comment) = @_;
524 if ($in_comment) {
525 $sanitise_quote = '*/';
526 } else {
527 $sanitise_quote = '';
530 sub sanitise_line {
531 my ($line) = @_;
533 my $res = '';
534 my $l = '';
536 my $qlen = 0;
537 my $off = 0;
538 my $c;
540 # Always copy over the diff marker.
541 $res = substr($line, 0, 1);
543 for ($off = 1; $off < length($line); $off++) {
544 $c = substr($line, $off, 1);
546 # Comments we are wacking completely including the begin
547 # and end, all to $;.
548 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
549 $sanitise_quote = '*/';
551 substr($res, $off, 2, "$;$;");
552 $off++;
553 next;
555 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
556 $sanitise_quote = '';
557 substr($res, $off, 2, "$;$;");
558 $off++;
559 next;
561 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
562 $sanitise_quote = '//';
564 substr($res, $off, 2, $sanitise_quote);
565 $off++;
566 next;
569 # A \ in a string means ignore the next character.
570 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
571 $c eq "\\") {
572 substr($res, $off, 2, 'XX');
573 $off++;
574 next;
576 # Regular quotes.
577 if ($c eq "'" || $c eq '"') {
578 if ($sanitise_quote eq '') {
579 $sanitise_quote = $c;
581 substr($res, $off, 1, $c);
582 next;
583 } elsif ($sanitise_quote eq $c) {
584 $sanitise_quote = '';
588 #print "c<$c> SQ<$sanitise_quote>\n";
589 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
590 substr($res, $off, 1, $;);
591 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
592 substr($res, $off, 1, $;);
593 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
594 substr($res, $off, 1, 'X');
595 } else {
596 substr($res, $off, 1, $c);
600 if ($sanitise_quote eq '//') {
601 $sanitise_quote = '';
604 # The pathname on a #include may be surrounded by '<' and '>'.
605 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
606 my $clean = 'X' x length($1);
607 $res =~ s@\<.*\>@<$clean>@;
609 # The whole of a #error is a string.
610 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
611 my $clean = 'X' x length($1);
612 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
615 return $res;
618 sub ctx_statement_block {
619 my ($linenr, $remain, $off) = @_;
620 my $line = $linenr - 1;
621 my $blk = '';
622 my $soff = $off;
623 my $coff = $off - 1;
624 my $coff_set = 0;
626 my $loff = 0;
628 my $type = '';
629 my $level = 0;
630 my @stack = ();
631 my $p;
632 my $c;
633 my $len = 0;
635 my $remainder;
636 while (1) {
637 @stack = (['', 0]) if ($#stack == -1);
639 #warn "CSB: blk<$blk> remain<$remain>\n";
640 # If we are about to drop off the end, pull in more
641 # context.
642 if ($off >= $len) {
643 for (; $remain > 0; $line++) {
644 last if (!defined $lines[$line]);
645 next if ($lines[$line] =~ /^-/);
646 $remain--;
647 $loff = $len;
648 $blk .= $lines[$line] . "\n";
649 $len = length($blk);
650 $line++;
651 last;
653 # Bail if there is no further context.
654 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
655 if ($off >= $len) {
656 last;
659 $p = $c;
660 $c = substr($blk, $off, 1);
661 $remainder = substr($blk, $off);
663 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
665 # Handle nested #if/#else.
666 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
667 push(@stack, [ $type, $level ]);
668 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
669 ($type, $level) = @{$stack[$#stack - 1]};
670 } elsif ($remainder =~ /^#\s*endif\b/) {
671 ($type, $level) = @{pop(@stack)};
674 # Statement ends at the ';' or a close '}' at the
675 # outermost level.
676 if ($level == 0 && $c eq ';') {
677 last;
680 # An else is really a conditional as long as its not else if
681 if ($level == 0 && $coff_set == 0 &&
682 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
683 $remainder =~ /^(else)(?:\s|{)/ &&
684 $remainder !~ /^else\s+if\b/) {
685 $coff = $off + length($1) - 1;
686 $coff_set = 1;
687 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
688 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
691 if (($type eq '' || $type eq '(') && $c eq '(') {
692 $level++;
693 $type = '(';
695 if ($type eq '(' && $c eq ')') {
696 $level--;
697 $type = ($level != 0)? '(' : '';
699 if ($level == 0 && $coff < $soff) {
700 $coff = $off;
701 $coff_set = 1;
702 #warn "CSB: mark coff<$coff>\n";
705 if (($type eq '' || $type eq '{') && $c eq '{') {
706 $level++;
707 $type = '{';
709 if ($type eq '{' && $c eq '}') {
710 $level--;
711 $type = ($level != 0)? '{' : '';
713 if ($level == 0) {
714 if (substr($blk, $off + 1, 1) eq ';') {
715 $off++;
717 last;
720 $off++;
722 # We are truly at the end, so shuffle to the next line.
723 if ($off == $len) {
724 $loff = $len + 1;
725 $line++;
726 $remain--;
729 my $statement = substr($blk, $soff, $off - $soff + 1);
730 my $condition = substr($blk, $soff, $coff - $soff + 1);
732 #warn "STATEMENT<$statement>\n";
733 #warn "CONDITION<$condition>\n";
735 #print "coff<$coff> soff<$off> loff<$loff>\n";
737 return ($statement, $condition,
738 $line, $remain + 1, $off - $loff + 1, $level);
741 sub statement_lines {
742 my ($stmt) = @_;
744 # Strip the diff line prefixes and rip blank lines at start and end.
745 $stmt =~ s/(^|\n)./$1/g;
746 $stmt =~ s/^\s*//;
747 $stmt =~ s/\s*$//;
749 my @stmt_lines = ($stmt =~ /\n/g);
751 return $#stmt_lines + 2;
754 sub statement_rawlines {
755 my ($stmt) = @_;
757 my @stmt_lines = ($stmt =~ /\n/g);
759 return $#stmt_lines + 2;
762 sub statement_block_size {
763 my ($stmt) = @_;
765 $stmt =~ s/(^|\n)./$1/g;
766 $stmt =~ s/^\s*\{//;
767 $stmt =~ s/}\s*$//;
768 $stmt =~ s/^\s*//;
769 $stmt =~ s/\s*$//;
771 my @stmt_lines = ($stmt =~ /\n/g);
772 my @stmt_statements = ($stmt =~ /;/g);
774 my $stmt_lines = $#stmt_lines + 2;
775 my $stmt_statements = $#stmt_statements + 1;
777 if ($stmt_lines > $stmt_statements) {
778 return $stmt_lines;
779 } else {
780 return $stmt_statements;
784 sub ctx_statement_full {
785 my ($linenr, $remain, $off) = @_;
786 my ($statement, $condition, $level);
788 my (@chunks);
790 # Grab the first conditional/block pair.
791 ($statement, $condition, $linenr, $remain, $off, $level) =
792 ctx_statement_block($linenr, $remain, $off);
793 #print "F: c<$condition> s<$statement> remain<$remain>\n";
794 push(@chunks, [ $condition, $statement ]);
795 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
796 return ($level, $linenr, @chunks);
799 # Pull in the following conditional/block pairs and see if they
800 # could continue the statement.
801 for (;;) {
802 ($statement, $condition, $linenr, $remain, $off, $level) =
803 ctx_statement_block($linenr, $remain, $off);
804 #print "C: c<$condition> s<$statement> remain<$remain>\n";
805 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
806 #print "C: push\n";
807 push(@chunks, [ $condition, $statement ]);
810 return ($level, $linenr, @chunks);
813 sub ctx_block_get {
814 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
815 my $line;
816 my $start = $linenr - 1;
817 my $blk = '';
818 my @o;
819 my @c;
820 my @res = ();
822 my $level = 0;
823 my @stack = ($level);
824 for ($line = $start; $remain > 0; $line++) {
825 next if ($rawlines[$line] =~ /^-/);
826 $remain--;
828 $blk .= $rawlines[$line];
830 # Handle nested #if/#else.
831 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
832 push(@stack, $level);
833 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
834 $level = $stack[$#stack - 1];
835 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
836 $level = pop(@stack);
839 foreach my $c (split(//, $lines[$line])) {
840 ##print "C<$c>L<$level><$open$close>O<$off>\n";
841 if ($off > 0) {
842 $off--;
843 next;
846 if ($c eq $close && $level > 0) {
847 $level--;
848 last if ($level == 0);
849 } elsif ($c eq $open) {
850 $level++;
854 if (!$outer || $level <= 1) {
855 push(@res, $rawlines[$line]);
858 last if ($level == 0);
861 return ($level, @res);
863 sub ctx_block_outer {
864 my ($linenr, $remain) = @_;
866 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
867 return @r;
869 sub ctx_block {
870 my ($linenr, $remain) = @_;
872 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
873 return @r;
875 sub ctx_statement {
876 my ($linenr, $remain, $off) = @_;
878 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
879 return @r;
881 sub ctx_block_level {
882 my ($linenr, $remain) = @_;
884 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
886 sub ctx_statement_level {
887 my ($linenr, $remain, $off) = @_;
889 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
892 sub ctx_locate_comment {
893 my ($first_line, $end_line) = @_;
895 # Catch a comment on the end of the line itself.
896 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
897 return $current_comment if (defined $current_comment);
899 # Look through the context and try and figure out if there is a
900 # comment.
901 my $in_comment = 0;
902 $current_comment = '';
903 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
904 my $line = $rawlines[$linenr - 1];
905 #warn " $line\n";
906 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
907 $in_comment = 1;
909 if ($line =~ m@/\*@) {
910 $in_comment = 1;
912 if (!$in_comment && $current_comment ne '') {
913 $current_comment = '';
915 $current_comment .= $line . "\n" if ($in_comment);
916 if ($line =~ m@\*/@) {
917 $in_comment = 0;
921 chomp($current_comment);
922 return($current_comment);
924 sub ctx_has_comment {
925 my ($first_line, $end_line) = @_;
926 my $cmt = ctx_locate_comment($first_line, $end_line);
928 ##print "LINE: $rawlines[$end_line - 1 ]\n";
929 ##print "CMMT: $cmt\n";
931 return ($cmt ne '');
934 sub raw_line {
935 my ($linenr, $cnt) = @_;
937 my $offset = $linenr - 1;
938 $cnt++;
940 my $line;
941 while ($cnt) {
942 $line = $rawlines[$offset++];
943 next if (defined($line) && $line =~ /^-/);
944 $cnt--;
947 return $line;
950 sub cat_vet {
951 my ($vet) = @_;
952 my ($res, $coded);
954 $res = '';
955 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
956 $res .= $1;
957 if ($2 ne '') {
958 $coded = sprintf("^%c", unpack('C', $2) + 64);
959 $res .= $coded;
962 $res =~ s/$/\$/;
964 return $res;
967 my $av_preprocessor = 0;
968 my $av_pending;
969 my @av_paren_type;
970 my $av_pend_colon;
972 sub annotate_reset {
973 $av_preprocessor = 0;
974 $av_pending = '_';
975 @av_paren_type = ('E');
976 $av_pend_colon = 'O';
979 sub annotate_values {
980 my ($stream, $type) = @_;
982 my $res;
983 my $var = '_' x length($stream);
984 my $cur = $stream;
986 print "$stream\n" if ($dbg_values > 1);
988 while (length($cur)) {
989 @av_paren_type = ('E') if ($#av_paren_type < 0);
990 print " <" . join('', @av_paren_type) .
991 "> <$type> <$av_pending>" if ($dbg_values > 1);
992 if ($cur =~ /^(\s+)/o) {
993 print "WS($1)\n" if ($dbg_values > 1);
994 if ($1 =~ /\n/ && $av_preprocessor) {
995 $type = pop(@av_paren_type);
996 $av_preprocessor = 0;
999 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1000 print "CAST($1)\n" if ($dbg_values > 1);
1001 push(@av_paren_type, $type);
1002 $type = 'C';
1004 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1005 print "DECLARE($1)\n" if ($dbg_values > 1);
1006 $type = 'T';
1008 } elsif ($cur =~ /^($Modifier)\s*/) {
1009 print "MODIFIER($1)\n" if ($dbg_values > 1);
1010 $type = 'T';
1012 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1013 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1014 $av_preprocessor = 1;
1015 push(@av_paren_type, $type);
1016 if ($2 ne '') {
1017 $av_pending = 'N';
1019 $type = 'E';
1021 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1022 print "UNDEF($1)\n" if ($dbg_values > 1);
1023 $av_preprocessor = 1;
1024 push(@av_paren_type, $type);
1026 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1027 print "PRE_START($1)\n" if ($dbg_values > 1);
1028 $av_preprocessor = 1;
1030 push(@av_paren_type, $type);
1031 push(@av_paren_type, $type);
1032 $type = 'E';
1034 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1035 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1036 $av_preprocessor = 1;
1038 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1040 $type = 'E';
1042 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1043 print "PRE_END($1)\n" if ($dbg_values > 1);
1045 $av_preprocessor = 1;
1047 # Assume all arms of the conditional end as this
1048 # one does, and continue as if the #endif was not here.
1049 pop(@av_paren_type);
1050 push(@av_paren_type, $type);
1051 $type = 'E';
1053 } elsif ($cur =~ /^(\\\n)/o) {
1054 print "PRECONT($1)\n" if ($dbg_values > 1);
1056 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1057 print "ATTR($1)\n" if ($dbg_values > 1);
1058 $av_pending = $type;
1059 $type = 'N';
1061 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1062 print "SIZEOF($1)\n" if ($dbg_values > 1);
1063 if (defined $2) {
1064 $av_pending = 'V';
1066 $type = 'N';
1068 } elsif ($cur =~ /^(if|while|for)\b/o) {
1069 print "COND($1)\n" if ($dbg_values > 1);
1070 $av_pending = 'E';
1071 $type = 'N';
1073 } elsif ($cur =~/^(case)/o) {
1074 print "CASE($1)\n" if ($dbg_values > 1);
1075 $av_pend_colon = 'C';
1076 $type = 'N';
1078 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1079 print "KEYWORD($1)\n" if ($dbg_values > 1);
1080 $type = 'N';
1082 } elsif ($cur =~ /^(\()/o) {
1083 print "PAREN('$1')\n" if ($dbg_values > 1);
1084 push(@av_paren_type, $av_pending);
1085 $av_pending = '_';
1086 $type = 'N';
1088 } elsif ($cur =~ /^(\))/o) {
1089 my $new_type = pop(@av_paren_type);
1090 if ($new_type ne '_') {
1091 $type = $new_type;
1092 print "PAREN('$1') -> $type\n"
1093 if ($dbg_values > 1);
1094 } else {
1095 print "PAREN('$1')\n" if ($dbg_values > 1);
1098 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1099 print "FUNC($1)\n" if ($dbg_values > 1);
1100 $type = 'V';
1101 $av_pending = 'V';
1103 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1104 if (defined $2 && $type eq 'C' || $type eq 'T') {
1105 $av_pend_colon = 'B';
1106 } elsif ($type eq 'E') {
1107 $av_pend_colon = 'L';
1109 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1110 $type = 'V';
1112 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1113 print "IDENT($1)\n" if ($dbg_values > 1);
1114 $type = 'V';
1116 } elsif ($cur =~ /^($Assignment)/o) {
1117 print "ASSIGN($1)\n" if ($dbg_values > 1);
1118 $type = 'N';
1120 } elsif ($cur =~/^(;|{|})/) {
1121 print "END($1)\n" if ($dbg_values > 1);
1122 $type = 'E';
1123 $av_pend_colon = 'O';
1125 } elsif ($cur =~/^(,)/) {
1126 print "COMMA($1)\n" if ($dbg_values > 1);
1127 $type = 'C';
1129 } elsif ($cur =~ /^(\?)/o) {
1130 print "QUESTION($1)\n" if ($dbg_values > 1);
1131 $type = 'N';
1133 } elsif ($cur =~ /^(:)/o) {
1134 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1136 substr($var, length($res), 1, $av_pend_colon);
1137 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1138 $type = 'E';
1139 } else {
1140 $type = 'N';
1142 $av_pend_colon = 'O';
1144 } elsif ($cur =~ /^(\[)/o) {
1145 print "CLOSE($1)\n" if ($dbg_values > 1);
1146 $type = 'N';
1148 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1149 my $variant;
1151 print "OPV($1)\n" if ($dbg_values > 1);
1152 if ($type eq 'V') {
1153 $variant = 'B';
1154 } else {
1155 $variant = 'U';
1158 substr($var, length($res), 1, $variant);
1159 $type = 'N';
1161 } elsif ($cur =~ /^($Operators)/o) {
1162 print "OP($1)\n" if ($dbg_values > 1);
1163 if ($1 ne '++' && $1 ne '--') {
1164 $type = 'N';
1167 } elsif ($cur =~ /(^.)/o) {
1168 print "C($1)\n" if ($dbg_values > 1);
1170 if (defined $1) {
1171 $cur = substr($cur, length($1));
1172 $res .= $type x length($1);
1176 return ($res, $var);
1179 sub possible {
1180 my ($possible, $line) = @_;
1181 my $notPermitted = qr{(?:
1182 ^(?:
1183 $Modifier|
1184 $Storage|
1185 $Type|
1186 DEFINE_\S+
1188 ^(?:
1189 goto|
1190 return|
1191 case|
1192 else|
1193 asm|__asm__|
1195 )(?:\s|$)|
1196 ^(?:typedef|struct|enum)\b|
1198 )}x;
1199 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1200 if ($possible !~ $notPermitted) {
1201 # Check for modifiers.
1202 $possible =~ s/\s*$Storage\s*//g;
1203 $possible =~ s/\s*$Sparse\s*//g;
1204 if ($possible =~ /^\s*$/) {
1206 } elsif ($possible =~ /\s/) {
1207 $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
1208 for my $modifier (split(' ', $possible)) {
1209 if ($modifier !~ $notPermitted) {
1210 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1211 push(@modifierList, $modifier);
1215 } else {
1216 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1217 push(@typeList, $possible);
1219 build_types();
1220 } else {
1221 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1225 my $prefix = '';
1227 sub report {
1228 my ($level, $msg) = @_;
1229 if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
1230 return 0;
1233 my $output = '';
1234 $output .= BOLD if $color;
1235 $output .= $prefix;
1236 $output .= RED if $color && $level eq 'ERROR';
1237 $output .= MAGENTA if $color && $level eq 'WARNING';
1238 $output .= $level . ':';
1239 $output .= RESET if $color;
1240 $output .= ' ' . $msg . "\n";
1242 $output = (split('\n', $output))[0] . "\n" if ($terse);
1244 push(our @report, $output);
1246 return 1;
1248 sub report_dump {
1249 our @report;
1251 sub ERROR {
1252 if (report("ERROR", $_[0])) {
1253 our $clean = 0;
1254 our $cnt_error++;
1257 sub WARN {
1258 if (report("WARNING", $_[0])) {
1259 our $clean = 0;
1260 our $cnt_warn++;
1264 # According to tests/qtest/bios-tables-test.c: do not
1265 # change expected file in the same commit with adding test
1266 sub checkfilename {
1267 my ($name, $acpi_testexpected, $acpi_nontestexpected) = @_;
1269 # Note: shell script that rebuilds the expected files is in the same
1270 # directory as files themselves.
1271 # Note: allowed diff list can be changed both when changing expected
1272 # files and when changing tests.
1273 if ($name =~ m#^tests/data/acpi/# and not $name =~ m#^\.sh$#) {
1274 $$acpi_testexpected = $name;
1275 } elsif ($name !~ m#^tests/qtest/bios-tables-test-allowed-diff.h$#) {
1276 $$acpi_nontestexpected = $name;
1278 if (defined $$acpi_testexpected and defined $$acpi_nontestexpected) {
1279 ERROR("Do not add expected files together with tests, " .
1280 "follow instructions in " .
1281 "tests/qtest/bios-tables-test.c: both " .
1282 $$acpi_testexpected . " and " .
1283 $$acpi_nontestexpected . " found\n");
1287 sub process {
1288 my $filename = shift;
1290 my $linenr=0;
1291 my $prevline="";
1292 my $prevrawline="";
1293 my $stashline="";
1294 my $stashrawline="";
1296 my $length;
1297 my $indent;
1298 my $previndent=0;
1299 my $stashindent=0;
1301 our $clean = 1;
1302 my $signoff = 0;
1303 my $is_patch = 0;
1305 my $in_header_lines = $file ? 0 : 1;
1306 my $in_commit_log = 0; #Scanning lines before patch
1307 my $reported_maintainer_file = 0;
1308 my $non_utf8_charset = 0;
1310 our @report = ();
1311 our $cnt_lines = 0;
1312 our $cnt_error = 0;
1313 our $cnt_warn = 0;
1314 our $cnt_chk = 0;
1316 # Trace the real file/line as we go.
1317 my $realfile = '';
1318 my $realline = 0;
1319 my $realcnt = 0;
1320 my $here = '';
1321 my $in_comment = 0;
1322 my $comment_edge = 0;
1323 my $first_line = 0;
1324 my $p1_prefix = '';
1326 my $prev_values = 'E';
1328 # suppression flags
1329 my %suppress_ifbraces;
1330 my %suppress_whiletrailers;
1331 my %suppress_export;
1333 my $acpi_testexpected;
1334 my $acpi_nontestexpected;
1336 # Pre-scan the patch sanitizing the lines.
1338 sanitise_line_reset();
1339 my $line;
1340 foreach my $rawline (@rawlines) {
1341 $linenr++;
1342 $line = $rawline;
1344 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1345 $realline=$1-1;
1346 if (defined $2) {
1347 $realcnt=$3+1;
1348 } else {
1349 $realcnt=1+1;
1351 $in_comment = 0;
1353 # Guestimate if this is a continuing comment. Run
1354 # the context looking for a comment "edge". If this
1355 # edge is a close comment then we must be in a comment
1356 # at context start.
1357 my $edge;
1358 my $cnt = $realcnt;
1359 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1360 next if (defined $rawlines[$ln - 1] &&
1361 $rawlines[$ln - 1] =~ /^-/);
1362 $cnt--;
1363 #print "RAW<$rawlines[$ln - 1]>\n";
1364 last if (!defined $rawlines[$ln - 1]);
1365 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1366 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1367 ($edge) = $1;
1368 last;
1371 if (defined $edge && $edge eq '*/') {
1372 $in_comment = 1;
1375 # Guestimate if this is a continuing comment. If this
1376 # is the start of a diff block and this line starts
1377 # ' *' then it is very likely a comment.
1378 if (!defined $edge &&
1379 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1381 $in_comment = 1;
1384 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1385 sanitise_line_reset($in_comment);
1387 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1388 # Standardise the strings and chars within the input to
1389 # simplify matching -- only bother with positive lines.
1390 $line = sanitise_line($rawline);
1392 push(@lines, $line);
1394 if ($realcnt > 1) {
1395 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1396 } else {
1397 $realcnt = 0;
1400 #print "==>$rawline\n";
1401 #print "-->$line\n";
1404 $prefix = '';
1406 $realcnt = 0;
1407 $linenr = 0;
1408 foreach my $line (@lines) {
1409 $linenr++;
1411 my $rawline = $rawlines[$linenr - 1];
1413 #extract the line range in the file after the patch is applied
1414 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1415 $is_patch = 1;
1416 $first_line = $linenr + 1;
1417 $realline=$1-1;
1418 if (defined $2) {
1419 $realcnt=$3+1;
1420 } else {
1421 $realcnt=1+1;
1423 annotate_reset();
1424 $prev_values = 'E';
1426 %suppress_ifbraces = ();
1427 %suppress_whiletrailers = ();
1428 %suppress_export = ();
1429 next;
1431 # track the line number as we move through the hunk, note that
1432 # new versions of GNU diff omit the leading space on completely
1433 # blank context lines so we need to count that too.
1434 } elsif ($line =~ /^( |\+|$)/) {
1435 $realline++;
1436 $realcnt-- if ($realcnt != 0);
1438 # Measure the line length and indent.
1439 ($length, $indent) = line_stats($rawline);
1441 # Track the previous line.
1442 ($prevline, $stashline) = ($stashline, $line);
1443 ($previndent, $stashindent) = ($stashindent, $indent);
1444 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1446 #warn "line<$line>\n";
1448 } elsif ($realcnt == 1) {
1449 $realcnt--;
1452 my $hunk_line = ($realcnt != 0);
1454 #make up the handle for any error we report on this line
1455 $prefix = "$filename:$realline: " if ($emacs && $file);
1456 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1458 $here = "#$linenr: " if (!$file);
1459 $here = "#$realline: " if ($file);
1461 # extract the filename as it passes
1462 if ($line =~ /^diff --git.*?(\S+)$/) {
1463 $realfile = $1;
1464 $realfile =~ s@^([^/]*)/@@ if (!$file);
1465 checkfilename($realfile, \$acpi_testexpected, \$acpi_nontestexpected);
1466 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1467 $realfile = $1;
1468 $realfile =~ s@^([^/]*)/@@ if (!$file);
1469 checkfilename($realfile, \$acpi_testexpected, \$acpi_nontestexpected);
1471 $p1_prefix = $1;
1472 if (!$file && $tree && $p1_prefix ne '' &&
1473 -e "$root/$p1_prefix") {
1474 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1477 next;
1480 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1482 my $hereline = "$here\n$rawline\n";
1483 my $herecurr = "$here\n$rawline\n";
1484 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1486 $cnt_lines++ if ($realcnt != 0);
1488 # Check for incorrect file permissions
1489 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1490 my $permhere = $here . "FILE: $realfile\n";
1491 if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1492 ERROR("do not set execute permissions for source files\n" . $permhere);
1496 # Only allow Python 3 interpreter
1497 if ($realline == 1 &&
1498 $line =~ /^\+#!\ *\/usr\/bin\/(?:env )?python$/) {
1499 ERROR("please use python3 interpreter\n" . $herecurr);
1502 # Accept git diff extended headers as valid patches
1503 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1504 $is_patch = 1;
1507 if ($line =~ /^(Author|From): .* via .*<qemu-devel\@nongnu.org>/) {
1508 ERROR("Author email address is mangled by the mailing list\n" . $herecurr);
1511 #check the patch for a signoff:
1512 if ($line =~ /^\s*signed-off-by:/i) {
1513 # This is a signoff, if ugly, so do not double report.
1514 $signoff++;
1515 $in_commit_log = 0;
1517 if (!($line =~ /^\s*Signed-off-by:/)) {
1518 ERROR("The correct form is \"Signed-off-by\"\n" .
1519 $herecurr);
1521 if ($line =~ /^\s*signed-off-by:\S/i) {
1522 ERROR("space required after Signed-off-by:\n" .
1523 $herecurr);
1527 # Check if MAINTAINERS is being updated. If so, there's probably no need to
1528 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
1529 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
1530 $reported_maintainer_file = 1;
1533 # Check for added, moved or deleted files
1534 if (!$reported_maintainer_file && !$in_commit_log &&
1535 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
1536 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
1537 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
1538 (defined($1) || defined($2)))) &&
1539 !(($realfile ne '') &&
1540 defined($acpi_testexpected) &&
1541 ($realfile eq $acpi_testexpected))) {
1542 $reported_maintainer_file = 1;
1543 WARN("added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
1546 # Check for wrappage within a valid hunk of the file
1547 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1548 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1549 $herecurr) if (!$emitted_corrupt++);
1552 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1553 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1554 $rawline !~ m/^$UTF8*$/) {
1555 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1557 my $blank = copy_spacing($rawline);
1558 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1559 my $hereptr = "$hereline$ptr\n";
1561 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1564 if ($rawline =~ m/$UTF8_MOJIBAKE/) {
1565 ERROR("Doubly-encoded UTF-8\n" . $herecurr);
1567 # Check if it's the start of a commit log
1568 # (not a header line and we haven't seen the patch filename)
1569 if ($in_header_lines && $realfile =~ /^$/ &&
1570 !($rawline =~ /^\s+\S/ ||
1571 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1572 $in_header_lines = 0;
1573 $in_commit_log = 1;
1576 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1577 # declined it, i.e defined some charset where it is missing.
1578 if ($in_header_lines &&
1579 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1580 $1 !~ /utf-8/i) {
1581 $non_utf8_charset = 1;
1584 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1585 $rawline =~ /$NON_ASCII_UTF8/) {
1586 WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1589 # ignore non-hunk lines and lines being removed
1590 next if (!$hunk_line || $line =~ /^-/);
1592 # ignore files that are being periodically imported from Linux
1593 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1595 #trailing whitespace
1596 if ($line =~ /^\+.*\015/) {
1597 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1598 ERROR("DOS line endings\n" . $herevet);
1600 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1601 $realfile =~ /^docs\/.+\.md/) {
1602 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1603 # TODO: properly check we're in a code block
1604 # (surrounding text is 4-column aligned)
1605 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1606 ERROR("code blocks in documentation should have " .
1607 "empty lines with exactly 4 columns of " .
1608 "whitespace\n" . $herevet);
1610 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1611 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1612 ERROR("trailing whitespace\n" . $herevet);
1613 $rpt_cleaners = 1;
1616 # checks for trace-events files
1617 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1618 if ($rawline =~ /%[-+ 0]*#/) {
1619 ERROR("Don't use '#' flag of printf format ('%#') in " .
1620 "trace-events, use '0x' prefix instead\n" . $herecurr);
1621 } else {
1622 my $hex =
1623 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1625 # don't consider groups splitted by [.:/ ], like 2A.20:12ab
1626 my $tmpline = $rawline;
1627 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1629 if ($tmpline =~ /(?<!0x)$hex/) {
1630 ERROR("Hex numbers must be prefixed with '0x'\n" .
1631 $herecurr);
1636 # check we are in a valid source file if not then ignore this hunk
1637 next if ($realfile !~ /$SrcFile/);
1639 #90 column limit; exempt URLs, if no other words on line
1640 if ($line =~ /^\+/ &&
1641 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1642 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1643 $length > 80)
1645 if ($length > 90) {
1646 ERROR("line over 90 characters\n" . $herecurr);
1647 } else {
1648 WARN("line over 80 characters\n" . $herecurr);
1652 # check for spaces before a quoted newline
1653 if ($rawline =~ /^.*\".*\s\\n/) {
1654 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1657 # check for adding lines without a newline.
1658 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1659 ERROR("adding a line without newline at end of file\n" . $herecurr);
1662 # check for RCS/CVS revision markers
1663 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1664 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1667 # tabs are only allowed in assembly source code, and in
1668 # some scripts we imported from other projects.
1669 next if ($realfile =~ /\.(s|S)$/);
1670 next if ($realfile =~ /(checkpatch|get_maintainer)\.pl$/);
1672 if ($rawline =~ /^\+.*\t/) {
1673 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1674 ERROR("code indent should never use tabs\n" . $herevet);
1675 $rpt_cleaners = 1;
1678 # check we are in a valid C source file if not then ignore this hunk
1679 next if ($realfile !~ /\.((h|c)(\.inc)?|cpp)$/);
1681 # Block comment styles
1683 # Block comments use /* on a line of its own
1684 if ($rawline !~ m@^\+.*/\*.*\*/[ \t)}]*$@ && #inline /*...*/
1685 $rawline =~ m@^\+.*/\*\*?+[ \t]*[^ \t]@) { # /* or /** non-blank
1686 WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
1689 # Block comments use * on subsequent lines
1690 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1691 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
1692 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
1693 $rawline =~ /^\+/ && #line is new
1694 $rawline !~ /^\+[ \t]*\*/) { #no leading *
1695 WARN("Block comments use * on subsequent lines\n" . $hereprev);
1698 # Block comments use */ on trailing lines
1699 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
1700 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
1701 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
1702 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
1703 WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
1706 # Block comment * alignment
1707 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1708 $line =~ /^\+[ \t]*$;/ && #leading comment
1709 $rawline =~ /^\+[ \t]*\*/ && #leading *
1710 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
1711 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
1712 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
1713 my $oldindent;
1714 $prevrawline =~ m@^\+([ \t]*/?)\*@;
1715 if (defined($1)) {
1716 $oldindent = expand_tabs($1);
1717 } else {
1718 $prevrawline =~ m@^\+(.*/?)\*@;
1719 $oldindent = expand_tabs($1);
1721 $rawline =~ m@^\+([ \t]*)\*@;
1722 my $newindent = $1;
1723 $newindent = expand_tabs($newindent);
1724 if (length($oldindent) ne length($newindent)) {
1725 WARN("Block comments should align the * on each line\n" . $hereprev);
1729 # Check for potential 'bare' types
1730 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1731 $realline_next);
1732 if ($realcnt && $line =~ /.\s*\S/) {
1733 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1734 ctx_statement_block($linenr, $realcnt, 0);
1735 $stat =~ s/\n./\n /g;
1736 $cond =~ s/\n./\n /g;
1738 # Find the real next line.
1739 $realline_next = $line_nr_next;
1740 if (defined $realline_next &&
1741 (!defined $lines[$realline_next - 1] ||
1742 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1743 $realline_next++;
1746 my $s = $stat;
1747 $s =~ s/{.*$//s;
1749 # Ignore goto labels.
1750 if ($s =~ /$Ident:\*$/s) {
1752 # Ignore functions being called
1753 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1755 } elsif ($s =~ /^.\s*else\b/s) {
1757 # declarations always start with types
1758 } 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) {
1759 my $type = $1;
1760 $type =~ s/\s+/ /g;
1761 possible($type, "A:" . $s);
1763 # definitions in global scope can only start with types
1764 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1765 possible($1, "B:" . $s);
1768 # any (foo ... *) is a pointer cast, and foo is a type
1769 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1770 possible($1, "C:" . $s);
1773 # Check for any sort of function declaration.
1774 # int foo(something bar, other baz);
1775 # void (*store_gdt)(x86_descr_ptr *);
1776 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1777 my ($name_len) = length($1);
1779 my $ctx = $s;
1780 substr($ctx, 0, $name_len + 1, '');
1781 $ctx =~ s/\)[^\)]*$//;
1783 for my $arg (split(/\s*,\s*/, $ctx)) {
1784 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1786 possible($1, "D:" . $s);
1794 # Checks which may be anchored in the context.
1797 # Check for switch () and associated case and default
1798 # statements should be at the same indent.
1799 if ($line=~/\bswitch\s*\(.*\)/) {
1800 my $err = '';
1801 my $sep = '';
1802 my @ctx = ctx_block_outer($linenr, $realcnt);
1803 shift(@ctx);
1804 for my $ctx (@ctx) {
1805 my ($clen, $cindent) = line_stats($ctx);
1806 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1807 $indent != $cindent) {
1808 $err .= "$sep$ctx\n";
1809 $sep = '';
1810 } else {
1811 $sep = "[...]\n";
1814 if ($err ne '') {
1815 ERROR("switch and case should be at the same indent\n$hereline$err");
1819 # if/while/etc brace do not go on next line, unless defining a do while loop,
1820 # or if that brace on the next line is for something else
1821 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1822 my $pre_ctx = "$1$2";
1824 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1825 my $ctx_cnt = $realcnt - $#ctx - 1;
1826 my $ctx = join("\n", @ctx);
1828 my $ctx_ln = $linenr;
1829 my $ctx_skip = $realcnt;
1831 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1832 defined $lines[$ctx_ln - 1] &&
1833 $lines[$ctx_ln - 1] =~ /^-/)) {
1834 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1835 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1836 $ctx_ln++;
1839 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1840 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1842 # The length of the "previous line" is checked against 80 because it
1843 # includes the + at the beginning of the line (if the actual line has
1844 # 79 or 80 characters, it is no longer possible to add a space and an
1845 # opening brace there)
1846 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1847 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1848 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1849 ERROR("that open brace { should be on the previous line\n" .
1850 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1852 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1853 $ctx =~ /\)\s*\;\s*$/ &&
1854 defined $lines[$ctx_ln - 1])
1856 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1857 if ($nindent > $indent) {
1858 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1859 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1864 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1865 if ($line =~ /while\s*\((0|false)\);/) {
1866 ERROR("suspicious ; after while (0)\n" . $herecurr);
1869 # Check superfluous trailing ';'
1870 if ($line =~ /;;$/) {
1871 ERROR("superfluous trailing semicolon\n" . $herecurr);
1874 # Check relative indent for conditionals and blocks.
1875 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1876 my ($s, $c) = ($stat, $cond);
1878 substr($s, 0, length($c), '');
1880 # Make sure we remove the line prefixes as we have
1881 # none on the first line, and are going to re-add them
1882 # where necessary.
1883 $s =~ s/\n./\n/gs;
1885 # Find out how long the conditional actually is.
1886 my @newlines = ($c =~ /\n/gs);
1887 my $cond_lines = 1 + $#newlines;
1889 # We want to check the first line inside the block
1890 # starting at the end of the conditional, so remove:
1891 # 1) any blank line termination
1892 # 2) any opening brace { on end of the line
1893 # 3) any do (...) {
1894 my $continuation = 0;
1895 my $check = 0;
1896 $s =~ s/^.*\bdo\b//;
1897 $s =~ s/^\s*\{//;
1898 if ($s =~ s/^\s*\\//) {
1899 $continuation = 1;
1901 if ($s =~ s/^\s*?\n//) {
1902 $check = 1;
1903 $cond_lines++;
1906 # Also ignore a loop construct at the end of a
1907 # preprocessor statement.
1908 if (($prevline =~ /^.\s*#\s*define\s/ ||
1909 $prevline =~ /\\\s*$/) && $continuation == 0) {
1910 $check = 0;
1913 my $cond_ptr = -1;
1914 $continuation = 0;
1915 while ($cond_ptr != $cond_lines) {
1916 $cond_ptr = $cond_lines;
1918 # If we see an #else/#elif then the code
1919 # is not linear.
1920 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1921 $check = 0;
1924 # Ignore:
1925 # 1) blank lines, they should be at 0,
1926 # 2) preprocessor lines, and
1927 # 3) labels.
1928 if ($continuation ||
1929 $s =~ /^\s*?\n/ ||
1930 $s =~ /^\s*#\s*?/ ||
1931 $s =~ /^\s*$Ident\s*:/) {
1932 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1933 if ($s =~ s/^.*?\n//) {
1934 $cond_lines++;
1939 my (undef, $sindent) = line_stats("+" . $s);
1940 my $stat_real = raw_line($linenr, $cond_lines);
1942 # Check if either of these lines are modified, else
1943 # this is not this patch's fault.
1944 if (!defined($stat_real) ||
1945 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1946 $check = 0;
1948 if (defined($stat_real) && $cond_lines > 1) {
1949 $stat_real = "[...]\n$stat_real";
1952 #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";
1954 if ($check && (($sindent % 4) != 0 ||
1955 ($sindent <= $indent && $s ne ''))) {
1956 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1960 # Track the 'values' across context and added lines.
1961 my $opline = $line; $opline =~ s/^./ /;
1962 my ($curr_values, $curr_vars) =
1963 annotate_values($opline . "\n", $prev_values);
1964 $curr_values = $prev_values . $curr_values;
1965 if ($dbg_values) {
1966 my $outline = $opline; $outline =~ s/\t/ /g;
1967 print "$linenr > .$outline\n";
1968 print "$linenr > $curr_values\n";
1969 print "$linenr > $curr_vars\n";
1971 $prev_values = substr($curr_values, -1);
1973 #ignore lines not being added
1974 if ($line=~/^[^\+]/) {next;}
1976 # TEST: allow direct testing of the type matcher.
1977 if ($dbg_type) {
1978 if ($line =~ /^.\s*$Declare\s*$/) {
1979 ERROR("TEST: is type\n" . $herecurr);
1980 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1981 ERROR("TEST: is not type ($1 is)\n". $herecurr);
1983 next;
1985 # TEST: allow direct testing of the attribute matcher.
1986 if ($dbg_attr) {
1987 if ($line =~ /^.\s*$Modifier\s*$/) {
1988 ERROR("TEST: is attr\n" . $herecurr);
1989 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1990 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1992 next;
1995 # check for initialisation to aggregates open brace on the next line
1996 if ($line =~ /^.\s*\{/ &&
1997 $prevline =~ /(?:^|[^=])=\s*$/) {
1998 ERROR("that open brace { should be on the previous line\n" . $hereprev);
2002 # Checks which are anchored on the added line.
2005 # check for malformed paths in #include statements (uses RAW line)
2006 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2007 my $path = $1;
2008 if ($path =~ m{//}) {
2009 ERROR("malformed #include filename\n" .
2010 $herecurr);
2014 # no C99 // comments
2015 if ($line =~ m{//} &&
2016 $rawline !~ m{// SPDX-License-Identifier: }) {
2017 ERROR("do not use C99 // comments\n" . $herecurr);
2019 # Remove C99 comments.
2020 $line =~ s@//.*@@;
2021 $opline =~ s@//.*@@;
2023 # check for global initialisers.
2024 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
2025 ERROR("do not initialise globals to 0 or NULL\n" .
2026 $herecurr);
2028 # check for static initialisers.
2029 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2030 ERROR("do not initialise statics to 0 or NULL\n" .
2031 $herecurr);
2034 # * goes on variable not on type
2035 # (char*[ const])
2036 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
2037 my ($from, $to) = ($1, $1);
2039 # Should start with a space.
2040 $to =~ s/^(\S)/ $1/;
2041 # Should not end with a space.
2042 $to =~ s/\s+$//;
2043 # '*'s should not have spaces between.
2044 while ($to =~ s/\*\s+\*/\*\*/) {
2047 #print "from<$from> to<$to>\n";
2048 if ($from ne $to) {
2049 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
2051 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
2052 my ($from, $to, $ident) = ($1, $1, $2);
2054 # Should start with a space.
2055 $to =~ s/^(\S)/ $1/;
2056 # Should not end with a space.
2057 $to =~ s/\s+$//;
2058 # '*'s should not have spaces between.
2059 while ($to =~ s/\*\s+\*/\*\*/) {
2061 # Modifiers should have spaces.
2062 $to =~ s/(\b$Modifier$)/$1 /;
2064 #print "from<$from> to<$to> ident<$ident>\n";
2065 if ($from ne $to && $ident !~ /^$Modifier$/) {
2066 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
2070 # function brace can't be on same line, except for #defines of do while,
2071 # or if closed on same line
2072 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2073 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
2074 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
2077 # open braces for enum, union and struct go on the same line.
2078 if ($line =~ /^.\s*\{/ &&
2079 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2080 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
2083 # missing space after union, struct or enum definition
2084 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
2085 ERROR("missing space after $1 definition\n" . $herecurr);
2088 # check for spacing round square brackets; allowed:
2089 # 1. with a type on the left -- int [] a;
2090 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2091 # 3. inside a curly brace -- = { [0...10] = 5 }
2092 # 4. after a comma -- [1] = 5, [2] = 6
2093 # 5. in a macro definition -- #define abc(x) [x] = y
2094 while ($line =~ /(.*?\s)\[/g) {
2095 my ($where, $prefix) = ($-[1], $1);
2096 if ($prefix !~ /$Type\s+$/ &&
2097 ($where != 0 || $prefix !~ /^.\s+$/) &&
2098 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
2099 $prefix !~ /[,{:]\s+$/) {
2100 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
2104 # check for spaces between functions and their parentheses.
2105 while ($line =~ /($Ident)\s+\(/g) {
2106 my $name = $1;
2107 my $ctx_before = substr($line, 0, $-[1]);
2108 my $ctx = "$ctx_before$name";
2110 # Ignore those directives where spaces _are_ permitted.
2111 if ($name =~ /^(?:
2112 if|for|while|switch|return|case|
2113 volatile|__volatile__|coroutine_fn|
2114 __attribute__|format|__extension__|
2115 asm|__asm__)$/x)
2118 # Ignore 'catch (...)' in C++
2119 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
2121 # cpp #define statements have non-optional spaces, ie
2122 # if there is a space between the name and the open
2123 # parenthesis it is simply not a parameter group.
2124 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2126 # cpp #elif statement condition may start with a (
2127 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2129 # If this whole things ends with a type its most
2130 # likely a typedef for a function.
2131 } elsif ($ctx =~ /$Type$/) {
2133 } else {
2134 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
2137 # Check operator spacing.
2138 if (!($line=~/\#\s*include/)) {
2139 my $ops = qr{
2140 <<=|>>=|<=|>=|==|!=|
2141 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2142 =>|->|<<|>>|<|>|=|!|~|
2143 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2144 \?|::|:
2146 my @elements = split(/($ops|;)/, $opline);
2147 my $off = 0;
2149 my $blank = copy_spacing($opline);
2151 for (my $n = 0; $n < $#elements; $n += 2) {
2152 $off += length($elements[$n]);
2154 # Pick up the preceding and succeeding characters.
2155 my $ca = substr($opline, 0, $off);
2156 my $cc = '';
2157 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2158 $cc = substr($opline, $off + length($elements[$n + 1]));
2160 my $cb = "$ca$;$cc";
2162 my $a = '';
2163 $a = 'V' if ($elements[$n] ne '');
2164 $a = 'W' if ($elements[$n] =~ /\s$/);
2165 $a = 'C' if ($elements[$n] =~ /$;$/);
2166 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2167 $a = 'O' if ($elements[$n] eq '');
2168 $a = 'E' if ($ca =~ /^\s*$/);
2170 my $op = $elements[$n + 1];
2172 my $c = '';
2173 if (defined $elements[$n + 2]) {
2174 $c = 'V' if ($elements[$n + 2] ne '');
2175 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2176 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2177 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2178 $c = 'O' if ($elements[$n + 2] eq '');
2179 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2180 } else {
2181 $c = 'E';
2184 my $ctx = "${a}x${c}";
2186 my $at = "(ctx:$ctx)";
2188 my $ptr = substr($blank, 0, $off) . "^";
2189 my $hereptr = "$hereline$ptr\n";
2191 # Pull out the value of this operator.
2192 my $op_type = substr($curr_values, $off + 1, 1);
2194 # Get the full operator variant.
2195 my $opv = $op . substr($curr_vars, $off, 1);
2197 # Ignore operators passed as parameters.
2198 if ($op_type ne 'V' &&
2199 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2201 # # Ignore comments
2202 # } elsif ($op =~ /^$;+$/) {
2204 # ; should have either the end of line or a space or \ after it
2205 } elsif ($op eq ';') {
2206 if ($ctx !~ /.x[WEBC]/ &&
2207 $cc !~ /^\\/ && $cc !~ /^;/) {
2208 ERROR("space required after that '$op' $at\n" . $hereptr);
2211 # // is a comment
2212 } elsif ($op eq '//') {
2214 # Ignore : used in class declaration in C++
2215 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2216 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2218 # No spaces for:
2219 # ->
2220 # : when part of a bitfield
2221 } elsif ($op eq '->' || $opv eq ':B') {
2222 if ($ctx =~ /Wx.|.xW/) {
2223 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2226 # , must have a space on the right.
2227 # not required when having a single },{ on one line
2228 } elsif ($op eq ',') {
2229 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2230 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2231 ERROR("space required after that '$op' $at\n" . $hereptr);
2234 # '*' as part of a type definition -- reported already.
2235 } elsif ($opv eq '*_') {
2236 #warn "'*' is part of type\n";
2238 # unary operators should have a space before and
2239 # none after. May be left adjacent to another
2240 # unary operator, or a cast
2241 } elsif ($op eq '!' || $op eq '~' ||
2242 $opv eq '*U' || $opv eq '-U' ||
2243 $opv eq '&U' || $opv eq '&&U') {
2244 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2245 # '~' used as a name of Destructor
2247 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2248 ERROR("space required before that '$op' $at\n" . $hereptr);
2250 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2251 # A unary '*' may be const
2253 } elsif ($ctx =~ /.xW/) {
2254 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2257 # unary ++ and unary -- are allowed no space on one side.
2258 } elsif ($op eq '++' or $op eq '--') {
2259 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2260 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2262 if ($ctx =~ /Wx[BE]/ ||
2263 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2264 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2266 if ($ctx =~ /ExW/) {
2267 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2270 # A colon needs no spaces before when it is
2271 # terminating a case value or a label.
2272 } elsif ($opv eq ':C' || $opv eq ':L') {
2273 if ($ctx =~ /Wx./) {
2274 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2277 # All the others need spaces both sides.
2278 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2279 my $ok = 0;
2281 if ($realfile =~ /\.cpp|\.h$/) {
2282 # Ignore template arguments <...> in C++
2283 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2284 $ok = 1;
2287 # Ignore :: in C++
2288 if ($op eq '::') {
2289 $ok = 1;
2293 # Ignore email addresses <foo@bar>
2294 if (($op eq '<' &&
2295 $cc =~ /^\S+\@\S+>/) ||
2296 ($op eq '>' &&
2297 $ca =~ /<\S+\@\S+$/))
2299 $ok = 1;
2302 # Ignore ?:
2303 if (($opv eq ':O' && $ca =~ /\?$/) ||
2304 ($op eq '?' && $cc =~ /^:/)) {
2305 $ok = 1;
2308 if ($ok == 0) {
2309 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2312 $off += length($elements[$n + 1]);
2316 #need space before brace following if, while, etc
2317 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2318 $line =~ /do\{/) {
2319 ERROR("space required before the open brace '{'\n" . $herecurr);
2322 # closing brace should have a space following it when it has anything
2323 # on the line
2324 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2325 ERROR("space required after that close brace '}'\n" . $herecurr);
2328 # check spacing on square brackets
2329 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2330 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2332 if ($line =~ /\s\]/) {
2333 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2336 # check spacing on parentheses
2337 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2338 $line !~ /for\s*\(\s+;/) {
2339 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2341 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2342 $line !~ /for\s*\(.*;\s+\)/ &&
2343 $line !~ /:\s+\)/) {
2344 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2347 # Return is not a function.
2348 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2349 my $spacing = $1;
2350 my $value = $2;
2352 # Flatten any parentheses
2353 $value =~ s/\(/ \(/g;
2354 $value =~ s/\)/\) /g;
2355 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2356 $value !~ /(?:$Ident|-?$Constant)\s*
2357 $Compare\s*
2358 (?:$Ident|-?$Constant)/x &&
2359 $value =~ s/\([^\(\)]*\)/1/) {
2361 #print "value<$value>\n";
2362 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/ &&
2363 $line =~ /;$/) {
2364 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2366 } elsif ($spacing !~ /\s+/) {
2367 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2370 # Return of what appears to be an errno should normally be -'ve
2371 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2372 my $name = $1;
2373 if ($name ne 'EOF' && $name ne 'ERROR') {
2374 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2378 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2379 $line !~ /^.typedef/) {
2380 ERROR("named $1 should be typedefed separately\n" . $herecurr);
2383 # Need a space before open parenthesis after if, while etc
2384 if ($line=~/\b(if|while|for|switch)\(/) {
2385 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2388 # Check for illegal assignment in if conditional -- and check for trailing
2389 # statements after the conditional.
2390 if ($line =~ /do\s*(?!{)/) {
2391 my ($stat_next) = ctx_statement_block($line_nr_next,
2392 $remain_next, $off_next);
2393 $stat_next =~ s/\n./\n /g;
2394 ##print "stat<$stat> stat_next<$stat_next>\n";
2396 if ($stat_next =~ /^\s*while\b/) {
2397 # If the statement carries leading newlines,
2398 # then count those as offsets.
2399 my ($whitespace) =
2400 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2401 my $offset =
2402 statement_rawlines($whitespace) - 1;
2404 $suppress_whiletrailers{$line_nr_next +
2405 $offset} = 1;
2408 if (!defined $suppress_whiletrailers{$linenr} &&
2409 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2410 my ($s, $c) = ($stat, $cond);
2412 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2413 ERROR("do not use assignment in if condition\n" . $herecurr);
2416 # Find out what is on the end of the line after the
2417 # conditional.
2418 substr($s, 0, length($c), '');
2419 $s =~ s/\n.*//g;
2420 $s =~ s/$;//g; # Remove any comments
2421 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2422 $c !~ /}\s*while\s*/)
2424 # Find out how long the conditional actually is.
2425 my @newlines = ($c =~ /\n/gs);
2426 my $cond_lines = 1 + $#newlines;
2427 my $stat_real = '';
2429 $stat_real = raw_line($linenr, $cond_lines)
2430 . "\n" if ($cond_lines);
2431 if (defined($stat_real) && $cond_lines > 1) {
2432 $stat_real = "[...]\n$stat_real";
2435 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2439 # Check for bitwise tests written as boolean
2440 if ($line =~ /
2442 (?:\[|\(|\&\&|\|\|)
2443 \s*0[xX][0-9]+\s*
2444 (?:\&\&|\|\|)
2446 (?:\&\&|\|\|)
2447 \s*0[xX][0-9]+\s*
2448 (?:\&\&|\|\||\)|\])
2449 )/x)
2451 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2454 # if and else should not have general statements after it
2455 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2456 my $s = $1;
2457 $s =~ s/$;//g; # Remove any comments
2458 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2459 ERROR("trailing statements should be on next line\n" . $herecurr);
2462 # if should not continue a brace
2463 if ($line =~ /}\s*if\b/) {
2464 ERROR("trailing statements should be on next line\n" .
2465 $herecurr);
2467 # case and default should not have general statements after them
2468 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2469 $line !~ /\G(?:
2470 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2471 \s*return\s+
2472 )/xg)
2474 ERROR("trailing statements should be on next line\n" . $herecurr);
2477 # Check for }<nl>else {, these must be at the same
2478 # indent level to be relevant to each other.
2479 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2480 $previndent == $indent) {
2481 ERROR("else should follow close brace '}'\n" . $hereprev);
2484 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2485 $previndent == $indent) {
2486 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2488 # Find out what is on the end of the line after the
2489 # conditional.
2490 substr($s, 0, length($c), '');
2491 $s =~ s/\n.*//g;
2493 if ($s =~ /^\s*;/) {
2494 ERROR("while should follow close brace '}'\n" . $hereprev);
2498 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2499 # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2500 # print "No studly caps, use _\n";
2501 # print "$herecurr";
2502 # $clean = 0;
2505 #no spaces allowed after \ in define
2506 if ($line=~/\#\s*define.*\\\s$/) {
2507 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2510 # multi-statement macros should be enclosed in a do while loop, grab the
2511 # first statement and ensure its the whole macro if its not enclosed
2512 # in a known good container
2513 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2514 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2515 my $ln = $linenr;
2516 my $cnt = $realcnt;
2517 my ($off, $dstat, $dcond, $rest);
2518 my $ctx = '';
2520 my $args = defined($1);
2522 # Find the end of the macro and limit our statement
2523 # search to that.
2524 while ($cnt > 0 && defined $lines[$ln - 1] &&
2525 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2527 $ctx .= $rawlines[$ln - 1] . "\n";
2528 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2529 $ln++;
2531 $ctx .= $rawlines[$ln - 1];
2533 ($dstat, $dcond, $ln, $cnt, $off) =
2534 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2535 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2536 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2538 # Extract the remainder of the define (if any) and
2539 # rip off surrounding spaces, and trailing \'s.
2540 $rest = '';
2541 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2542 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2543 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2544 $rest .= substr($lines[$ln - 1], $off) . "\n";
2545 $cnt--;
2547 $ln++;
2548 $off = 0;
2550 $rest =~ s/\\\n.//g;
2551 $rest =~ s/^\s*//s;
2552 $rest =~ s/\s*$//s;
2554 # Clean up the original statement.
2555 if ($args) {
2556 substr($dstat, 0, length($dcond), '');
2557 } else {
2558 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2560 $dstat =~ s/$;//g;
2561 $dstat =~ s/\\\n.//g;
2562 $dstat =~ s/^\s*//s;
2563 $dstat =~ s/\s*$//s;
2565 # Flatten any parentheses and braces
2566 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2567 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2568 $dstat =~ s/\[[^\{\}]*\]/1/)
2572 my $exceptions = qr{
2573 $Declare|
2574 module_param_named|
2575 MODULE_PARAM_DESC|
2576 DECLARE_PER_CPU|
2577 DEFINE_PER_CPU|
2578 __typeof__\(|
2579 union|
2580 struct|
2581 \.$Ident\s*=\s*|
2582 ^\"|\"$
2584 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2585 if ($rest ne '' && $rest ne ',') {
2586 if ($rest !~ /while\s*\(/ &&
2587 $dstat !~ /$exceptions/)
2589 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2592 } elsif ($ctx !~ /;/) {
2593 if ($dstat ne '' &&
2594 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2595 $dstat !~ /$exceptions/ &&
2596 $dstat !~ /^\.$Ident\s*=/ &&
2597 $dstat =~ /$Operators/)
2599 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2604 # check for missing bracing around if etc
2605 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2606 $line !~ /\#\s*if/) {
2607 my $allowed = 0;
2609 # Check the pre-context.
2610 if ($line =~ /(\}.*?)$/) {
2611 my $pre = $1;
2613 if ($line !~ /else/) {
2614 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2615 if $dbg_adv_apw;
2616 $allowed = 1;
2619 my ($level, $endln, @chunks) =
2620 ctx_statement_full($linenr, $realcnt, 1);
2621 if ($dbg_adv_apw) {
2622 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2623 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2624 if $#chunks >= 1;
2626 if ($#chunks >= 0 && $level == 0) {
2627 my $seen = 0;
2628 my $herectx = $here . "\n";
2629 my $ln = $linenr - 1;
2630 for my $chunk (@chunks) {
2631 my ($cond, $block) = @{$chunk};
2633 # If the condition carries leading newlines, then count those as offsets.
2634 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2635 my $offset = statement_rawlines($whitespace) - 1;
2637 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2639 # We have looked at and allowed this specific line.
2640 $suppress_ifbraces{$ln + $offset} = 1;
2642 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2643 $ln += statement_rawlines($block) - 1;
2645 substr($block, 0, length($cond), '');
2647 my $spaced_block = $block;
2648 $spaced_block =~ s/\n\+/ /g;
2650 $seen++ if ($spaced_block =~ /^\s*\{/);
2652 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2653 if $dbg_adv_apw;
2654 if (statement_lines($cond) > 1) {
2655 print "APW: ALLOWED: cond<$cond>\n"
2656 if $dbg_adv_apw;
2657 $allowed = 1;
2659 if ($block =~/\b(?:if|for|while)\b/) {
2660 print "APW: ALLOWED: block<$block>\n"
2661 if $dbg_adv_apw;
2662 $allowed = 1;
2664 if (statement_block_size($block) > 1) {
2665 print "APW: ALLOWED: lines block<$block>\n"
2666 if $dbg_adv_apw;
2667 $allowed = 1;
2670 if ($seen != ($#chunks + 1) && !$allowed) {
2671 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2675 if (!defined $suppress_ifbraces{$linenr - 1} &&
2676 $line =~ /\b(if|while|for|else)\b/ &&
2677 $line !~ /\#\s*if/ &&
2678 $line !~ /\#\s*else/) {
2679 my $allowed = 0;
2681 # Check the pre-context.
2682 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2683 my $pre = $1;
2685 if ($line !~ /else/) {
2686 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2687 if $dbg_adv_apw;
2688 $allowed = 1;
2692 my ($level, $endln, @chunks) =
2693 ctx_statement_full($linenr, $realcnt, $-[0]);
2695 # Check the condition.
2696 my ($cond, $block) = @{$chunks[0]};
2697 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2698 if $dbg_adv_checking;
2699 if (defined $cond) {
2700 substr($block, 0, length($cond), '');
2702 if (statement_lines($cond) > 1) {
2703 print "APW: ALLOWED: cond<$cond>\n"
2704 if $dbg_adv_apw;
2705 $allowed = 1;
2707 if ($block =~/\b(?:if|for|while)\b/) {
2708 print "APW: ALLOWED: block<$block>\n"
2709 if $dbg_adv_apw;
2710 $allowed = 1;
2712 if (statement_block_size($block) > 1) {
2713 print "APW: ALLOWED: lines block<$block>\n"
2714 if $dbg_adv_apw;
2715 $allowed = 1;
2717 # Check the post-context.
2718 if (defined $chunks[1]) {
2719 my ($cond, $block) = @{$chunks[1]};
2720 if (defined $cond) {
2721 substr($block, 0, length($cond), '');
2723 if ($block =~ /^\s*\{/) {
2724 print "APW: ALLOWED: chunk-1 block<$block>\n"
2725 if $dbg_adv_apw;
2726 $allowed = 1;
2729 print "DCS: level=$level block<$block> allowed=$allowed\n"
2730 if $dbg_adv_dcs;
2731 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2732 my $herectx = $here . "\n";;
2733 my $cnt = statement_rawlines($block);
2735 for (my $n = 0; $n < $cnt; $n++) {
2736 $herectx .= raw_line($linenr, $n) . "\n";;
2739 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2743 # no volatiles please
2744 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2745 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
2746 $line !~ /sig_atomic_t/ &&
2747 !ctx_has_comment($first_line, $linenr)) {
2748 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
2749 ERROR($msg);
2752 # warn about #if 0
2753 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2754 ERROR("if this code is redundant consider removing it\n" .
2755 $herecurr);
2758 # check for needless g_free() checks
2759 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2760 my $expr = $1;
2761 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2762 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2766 # warn about #ifdefs in C files
2767 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2768 # print "#ifdef in C files should be avoided\n";
2769 # print "$herecurr";
2770 # $clean = 0;
2773 # warn about spacing in #ifdefs
2774 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2775 ERROR("exactly one space required after that #$1\n" . $herecurr);
2777 # check for memory barriers without a comment.
2778 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2779 if (!ctx_has_comment($first_line, $linenr)) {
2780 ERROR("memory barrier without comment\n" . $herecurr);
2783 # check of hardware specific defines
2784 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2785 # where they might be necessary.
2786 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2787 WARN("architecture specific defines should be avoided\n" . $herecurr);
2790 # Check that the storage class is at the beginning of a declaration
2791 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2792 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2795 # check the location of the inline attribute, that it is between
2796 # storage class and type.
2797 if ($line =~ /\b$Type\s+$Inline\b/ ||
2798 $line =~ /\b$Inline\s+$Storage\b/) {
2799 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2802 # check for sizeof(&)
2803 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2804 ERROR("sizeof(& should be avoided\n" . $herecurr);
2807 # check for new externs in .c files.
2808 if ($realfile =~ /\.c$/ && defined $stat &&
2809 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2811 my $function_name = $1;
2812 my $paren_space = $2;
2814 my $s = $stat;
2815 if (defined $cond) {
2816 substr($s, 0, length($cond), '');
2818 if ($s =~ /^\s*;/ &&
2819 $function_name ne 'uninitialized_var')
2821 ERROR("externs should be avoided in .c files\n" . $herecurr);
2824 if ($paren_space =~ /\n/) {
2825 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2828 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2829 $stat =~ /^.\s*extern\s+/)
2831 ERROR("externs should be avoided in .c files\n" . $herecurr);
2834 # check for pointless casting of g_malloc return
2835 if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2836 if ($2 == 'm') {
2837 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2838 } else {
2839 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2843 # check for gcc specific __FUNCTION__
2844 if ($line =~ /__FUNCTION__/) {
2845 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
2848 # recommend g_path_get_* over g_strdup(basename/dirname(...))
2849 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
2850 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
2853 # recommend qemu_strto* over strto* for numeric conversions
2854 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2855 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2857 # recommend sigaction over signal for portability, when establishing a handler
2858 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2859 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2861 # check for module_init(), use category-specific init macros explicitly please
2862 if ($line =~ /^module_init\s*\(/) {
2863 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2865 # check for various ops structs, ensure they are const.
2866 my $struct_ops = qr{AIOCBInfo|
2867 BdrvActionOps|
2868 BlockDevOps|
2869 BlockJobDriver|
2870 DisplayChangeListenerOps|
2871 GraphicHwOps|
2872 IDEDMAOps|
2873 KVMCapabilityInfo|
2874 MemoryRegionIOMMUOps|
2875 MemoryRegionOps|
2876 MemoryRegionPortio|
2877 QEMUFileOps|
2878 SCSIBusInfo|
2879 SCSIReqOps|
2880 Spice[A-Z][a-zA-Z0-9]*Interface|
2881 USBDesc[A-Z][a-zA-Z0-9]*|
2882 VhostOps|
2883 VMStateDescription|
2884 VMStateInfo}x;
2885 if ($line !~ /\bconst\b/ &&
2886 $line =~ /\b($struct_ops)\b.*=/) {
2887 ERROR("initializer for struct $1 should normally be const\n" .
2888 $herecurr);
2891 # format strings checks
2892 my $string;
2893 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2894 $string = substr($rawline, $-[1], $+[1] - $-[1]);
2895 $string =~ s/%%/__/g;
2896 # check for %L{u,d,i} in strings
2897 if ($string =~ /(?<!%)%L[udi]/) {
2898 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2900 # check for %# or %0# in printf-style format strings
2901 if ($string =~ /(?<!%)%0?#/) {
2902 ERROR("Don't use '#' flag of printf format " .
2903 "('%#') in format strings, use '0x' " .
2904 "prefix instead\n" . $herecurr);
2908 # QEMU specific tests
2909 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2910 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2913 # Qemu error function tests
2915 # Find newlines in error messages
2916 my $qemu_error_funcs = qr{error_setg|
2917 error_setg_errno|
2918 error_setg_win32|
2919 error_setg_file_open|
2920 error_set|
2921 error_prepend|
2922 warn_reportf_err|
2923 error_reportf_err|
2924 error_vreport|
2925 warn_vreport|
2926 info_vreport|
2927 error_report|
2928 warn_report|
2929 info_report|
2930 g_test_message}x;
2932 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2933 ERROR("Error messages should not contain newlines\n" . $herecurr);
2936 # Continue checking for error messages that contains newlines. This
2937 # check handles cases where string literals are spread over multiple lines.
2938 # Example:
2939 # error_report("Error msg line #1"
2940 # "Error msg line #2\n");
2941 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2942 my $continued_str_literal = qr{\+\s*\".*\"};
2944 if ($rawline =~ /$quoted_newline_regex/) {
2945 # Backtrack to first line that does not contain only a quoted literal
2946 # and assume that it is the start of the statement.
2947 my $i = $linenr - 2;
2949 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2950 $i--;
2953 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2954 ERROR("Error messages should not contain newlines\n" . $herecurr);
2958 # check for non-portable libc calls that have portable alternatives in QEMU
2959 if ($line =~ /\bffs\(/) {
2960 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2962 if ($line =~ /\bffsl\(/) {
2963 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2965 if ($line =~ /\bffsll\(/) {
2966 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2968 if ($line =~ /\bbzero\(/) {
2969 ERROR("use memset() instead of bzero()\n" . $herecurr);
2971 if ($line =~ /\bgetpagesize\(\)/) {
2972 ERROR("use qemu_real_host_page_size instead of getpagesize()\n" . $herecurr);
2974 if ($line =~ /\bsysconf\(_SC_PAGESIZE\)/) {
2975 ERROR("use qemu_real_host_page_size instead of sysconf(_SC_PAGESIZE)\n" . $herecurr);
2977 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2978 g_assert_cmpint|
2979 g_assert_cmpuint|
2980 g_assert_cmphex|
2981 g_assert_cmpfloat|
2982 g_assert_true|
2983 g_assert_false|
2984 g_assert_nonnull|
2985 g_assert_null|
2986 g_assert_no_error|
2987 g_assert_error|
2988 g_test_assert_expected_messages|
2989 g_test_trap_assert_passed|
2990 g_test_trap_assert_stdout|
2991 g_test_trap_assert_stdout_unmatched|
2992 g_test_trap_assert_stderr|
2993 g_test_trap_assert_stderr_unmatched}x;
2994 if ($realfile !~ /^tests\// &&
2995 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2996 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
3000 if ($is_patch && $chk_signoff && $signoff == 0) {
3001 ERROR("Missing Signed-off-by: line(s)\n");
3004 # If we have no input at all, then there is nothing to report on
3005 # so just keep quiet.
3006 if ($#rawlines == -1) {
3007 return 1;
3010 # In mailback mode only produce a report in the negative, for
3011 # things that appear to be patches.
3012 if ($mailback && ($clean == 1 || !$is_patch)) {
3013 return 1;
3016 # This is not a patch, and we are are in 'no-patch' mode so
3017 # just keep quiet.
3018 if (!$chk_patch && !$is_patch) {
3019 return 1;
3022 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
3023 ERROR("Does not appear to be a unified-diff format patch\n");
3026 print report_dump();
3027 if ($summary && !($clean == 1 && $quiet == 1)) {
3028 print "$filename " if ($summary_file);
3029 print "total: $cnt_error errors, $cnt_warn warnings, " .
3030 "$cnt_lines lines checked\n";
3031 print "\n" if ($quiet == 0);
3034 if ($quiet == 0) {
3035 # If there were whitespace errors which cleanpatch can fix
3036 # then suggest that.
3037 # if ($rpt_cleaners) {
3038 # print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
3039 # print " scripts/cleanfile\n\n";
3043 if ($clean == 1 && $quiet == 0) {
3044 print "$vname has no obvious style problems and is ready for submission.\n"
3046 if ($clean == 0 && $quiet == 0) {
3047 print "$vname has style problems, please review. If any of these errors\n";
3048 print "are false positives report them to the maintainer, see\n";
3049 print "CHECKPATCH in MAINTAINERS.\n";
3052 return ($no_warnings ? $clean : $cnt_error == 0);