target/arm: Reset btype for direct branches
[qemu/ar7.git] / scripts / checkpatch.pl
blob88682cb0a9f324e0f56a00037d394fb548b59566
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;
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 kernel 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 kernel 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 kernel 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 # There are still some false positives, but this catches most
266 # common cases.
267 our $typeTypedefs = qr{(?x:
268 (?![KMGTPE]iB) # IEC binary prefix (do not match)
269 [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]* # camelcase
270 | [A-Z][A-Z\d_]*AIOCB # all uppercase
271 | [A-Z][A-Z\d_]*CPU # all uppercase
272 | QEMUBH # all uppercase
275 our @typeList = (
276 qr{void},
277 qr{(?:unsigned\s+)?char},
278 qr{(?:unsigned\s+)?short},
279 qr{(?:unsigned\s+)?int},
280 qr{(?:unsigned\s+)?long},
281 qr{(?:unsigned\s+)?long\s+int},
282 qr{(?:unsigned\s+)?long\s+long},
283 qr{(?:unsigned\s+)?long\s+long\s+int},
284 qr{unsigned},
285 qr{float},
286 qr{double},
287 qr{bool},
288 qr{struct\s+$Ident},
289 qr{union\s+$Ident},
290 qr{enum\s+$Ident},
291 qr{${Ident}_t},
292 qr{${Ident}_handler},
293 qr{${Ident}_handler_fn},
294 qr{target_(?:u)?long},
295 qr{hwaddr},
296 # external libraries
297 qr{xml${Ident}},
298 qr{xen\w+_handle},
299 # Glib definitions
300 qr{gchar},
301 qr{gshort},
302 qr{glong},
303 qr{gint},
304 qr{gboolean},
305 qr{guchar},
306 qr{gushort},
307 qr{gulong},
308 qr{guint},
309 qr{gfloat},
310 qr{gdouble},
311 qr{gpointer},
312 qr{gconstpointer},
313 qr{gint8},
314 qr{guint8},
315 qr{gint16},
316 qr{guint16},
317 qr{gint32},
318 qr{guint32},
319 qr{gint64},
320 qr{guint64},
321 qr{gsize},
322 qr{gssize},
323 qr{goffset},
324 qr{gintptr},
325 qr{guintptr},
328 # This can be modified by sub possible. Since it can be empty, be careful
329 # about regexes that always match, because they can cause infinite loops.
330 our @modifierList = (
333 sub build_types {
334 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
335 if (@modifierList > 0) {
336 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
337 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
338 } else {
339 $Modifier = qr{(?:$Attribute|$Sparse)};
341 $NonptrType = qr{
342 (?:$Modifier\s+|const\s+)*
344 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
345 (?:$typeTypedefs\b)|
346 (?:${all}\b)
348 (?:\s+$Modifier|\s+const)*
350 $Type = qr{
351 $NonptrType
352 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
353 (?:\s+$Inline|\s+$Modifier)*
355 $Declare = qr{(?:$Storage\s+)?$Type};
357 build_types();
359 $chk_signoff = 0 if ($file);
361 my @rawlines = ();
362 my @lines = ();
363 my $vname;
364 if ($chk_branch) {
365 my @patches;
366 my %git_commits = ();
367 my $HASH;
368 open($HASH, "-|", "git", "log", "--reverse", "--no-merges", "--format=%H %s", $ARGV[0]) ||
369 die "$P: git log --reverse --no-merges --format='%H %s' $ARGV[0] failed - $!\n";
371 for my $line (<$HASH>) {
372 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
373 next if (!defined($1) || !defined($2));
374 my $sha1 = $1;
375 my $subject = $2;
376 push(@patches, $sha1);
377 $git_commits{$sha1} = $subject;
380 close $HASH;
382 die "$P: no revisions returned for revlist '$chk_branch'\n"
383 unless @patches;
385 my $i = 1;
386 my $num_patches = @patches;
387 for my $hash (@patches) {
388 my $FILE;
389 open($FILE, '-|', "git", "show", $hash) ||
390 die "$P: git show $hash - $!\n";
391 while (<$FILE>) {
392 chomp;
393 push(@rawlines, $_);
395 close($FILE);
396 $vname = substr($hash, 0, 12) . ' (' . $git_commits{$hash} . ')';
397 if ($num_patches > 1 && $quiet == 0) {
398 my $prefix = "$i/$num_patches";
399 $prefix = BLUE . BOLD . $prefix . RESET if $color;
400 print "$prefix Checking commit $vname\n";
401 $vname = "Patch $i/$num_patches";
402 } else {
403 $vname = "Commit " . $vname;
405 if (!process($hash)) {
406 $exit = 1;
407 print "\n" if ($num_patches > 1 && $quiet == 0);
409 @rawlines = ();
410 @lines = ();
411 $i++;
413 } else {
414 for my $filename (@ARGV) {
415 my $FILE;
416 if ($file) {
417 open($FILE, '-|', "diff -u /dev/null $filename") ||
418 die "$P: $filename: diff failed - $!\n";
419 } elsif ($filename eq '-') {
420 open($FILE, '<&STDIN');
421 } else {
422 open($FILE, '<', "$filename") ||
423 die "$P: $filename: open failed - $!\n";
425 if ($filename eq '-') {
426 $vname = 'Your patch';
427 } else {
428 $vname = $filename;
430 print "Checking $filename...\n" if @ARGV > 1 && $quiet == 0;
431 while (<$FILE>) {
432 chomp;
433 push(@rawlines, $_);
435 close($FILE);
436 if (!process($filename)) {
437 $exit = 1;
439 @rawlines = ();
440 @lines = ();
444 exit($exit);
446 sub top_of_kernel_tree {
447 my ($root) = @_;
449 my @tree_check = (
450 "COPYING", "MAINTAINERS", "Makefile",
451 "README", "docs", "VERSION",
452 "vl.c"
455 foreach my $check (@tree_check) {
456 if (! -e $root . '/' . $check) {
457 return 0;
460 return 1;
463 sub expand_tabs {
464 my ($str) = @_;
466 my $res = '';
467 my $n = 0;
468 for my $c (split(//, $str)) {
469 if ($c eq "\t") {
470 $res .= ' ';
471 $n++;
472 for (; ($n % 8) != 0; $n++) {
473 $res .= ' ';
475 next;
477 $res .= $c;
478 $n++;
481 return $res;
483 sub copy_spacing {
484 (my $res = shift) =~ tr/\t/ /c;
485 return $res;
488 sub line_stats {
489 my ($line) = @_;
491 # Drop the diff line leader and expand tabs
492 $line =~ s/^.//;
493 $line = expand_tabs($line);
495 # Pick the indent from the front of the line.
496 my ($white) = ($line =~ /^(\s*)/);
498 return (length($line), length($white));
501 my $sanitise_quote = '';
503 sub sanitise_line_reset {
504 my ($in_comment) = @_;
506 if ($in_comment) {
507 $sanitise_quote = '*/';
508 } else {
509 $sanitise_quote = '';
512 sub sanitise_line {
513 my ($line) = @_;
515 my $res = '';
516 my $l = '';
518 my $qlen = 0;
519 my $off = 0;
520 my $c;
522 # Always copy over the diff marker.
523 $res = substr($line, 0, 1);
525 for ($off = 1; $off < length($line); $off++) {
526 $c = substr($line, $off, 1);
528 # Comments we are wacking completely including the begin
529 # and end, all to $;.
530 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
531 $sanitise_quote = '*/';
533 substr($res, $off, 2, "$;$;");
534 $off++;
535 next;
537 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
538 $sanitise_quote = '';
539 substr($res, $off, 2, "$;$;");
540 $off++;
541 next;
543 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
544 $sanitise_quote = '//';
546 substr($res, $off, 2, $sanitise_quote);
547 $off++;
548 next;
551 # A \ in a string means ignore the next character.
552 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
553 $c eq "\\") {
554 substr($res, $off, 2, 'XX');
555 $off++;
556 next;
558 # Regular quotes.
559 if ($c eq "'" || $c eq '"') {
560 if ($sanitise_quote eq '') {
561 $sanitise_quote = $c;
563 substr($res, $off, 1, $c);
564 next;
565 } elsif ($sanitise_quote eq $c) {
566 $sanitise_quote = '';
570 #print "c<$c> SQ<$sanitise_quote>\n";
571 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
572 substr($res, $off, 1, $;);
573 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
574 substr($res, $off, 1, $;);
575 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
576 substr($res, $off, 1, 'X');
577 } else {
578 substr($res, $off, 1, $c);
582 if ($sanitise_quote eq '//') {
583 $sanitise_quote = '';
586 # The pathname on a #include may be surrounded by '<' and '>'.
587 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
588 my $clean = 'X' x length($1);
589 $res =~ s@\<.*\>@<$clean>@;
591 # The whole of a #error is a string.
592 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
593 my $clean = 'X' x length($1);
594 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
597 return $res;
600 sub ctx_statement_block {
601 my ($linenr, $remain, $off) = @_;
602 my $line = $linenr - 1;
603 my $blk = '';
604 my $soff = $off;
605 my $coff = $off - 1;
606 my $coff_set = 0;
608 my $loff = 0;
610 my $type = '';
611 my $level = 0;
612 my @stack = ();
613 my $p;
614 my $c;
615 my $len = 0;
617 my $remainder;
618 while (1) {
619 @stack = (['', 0]) if ($#stack == -1);
621 #warn "CSB: blk<$blk> remain<$remain>\n";
622 # If we are about to drop off the end, pull in more
623 # context.
624 if ($off >= $len) {
625 for (; $remain > 0; $line++) {
626 last if (!defined $lines[$line]);
627 next if ($lines[$line] =~ /^-/);
628 $remain--;
629 $loff = $len;
630 $blk .= $lines[$line] . "\n";
631 $len = length($blk);
632 $line++;
633 last;
635 # Bail if there is no further context.
636 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
637 if ($off >= $len) {
638 last;
641 $p = $c;
642 $c = substr($blk, $off, 1);
643 $remainder = substr($blk, $off);
645 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
647 # Handle nested #if/#else.
648 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
649 push(@stack, [ $type, $level ]);
650 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
651 ($type, $level) = @{$stack[$#stack - 1]};
652 } elsif ($remainder =~ /^#\s*endif\b/) {
653 ($type, $level) = @{pop(@stack)};
656 # Statement ends at the ';' or a close '}' at the
657 # outermost level.
658 if ($level == 0 && $c eq ';') {
659 last;
662 # An else is really a conditional as long as its not else if
663 if ($level == 0 && $coff_set == 0 &&
664 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
665 $remainder =~ /^(else)(?:\s|{)/ &&
666 $remainder !~ /^else\s+if\b/) {
667 $coff = $off + length($1) - 1;
668 $coff_set = 1;
669 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
670 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
673 if (($type eq '' || $type eq '(') && $c eq '(') {
674 $level++;
675 $type = '(';
677 if ($type eq '(' && $c eq ')') {
678 $level--;
679 $type = ($level != 0)? '(' : '';
681 if ($level == 0 && $coff < $soff) {
682 $coff = $off;
683 $coff_set = 1;
684 #warn "CSB: mark coff<$coff>\n";
687 if (($type eq '' || $type eq '{') && $c eq '{') {
688 $level++;
689 $type = '{';
691 if ($type eq '{' && $c eq '}') {
692 $level--;
693 $type = ($level != 0)? '{' : '';
695 if ($level == 0) {
696 if (substr($blk, $off + 1, 1) eq ';') {
697 $off++;
699 last;
702 $off++;
704 # We are truly at the end, so shuffle to the next line.
705 if ($off == $len) {
706 $loff = $len + 1;
707 $line++;
708 $remain--;
711 my $statement = substr($blk, $soff, $off - $soff + 1);
712 my $condition = substr($blk, $soff, $coff - $soff + 1);
714 #warn "STATEMENT<$statement>\n";
715 #warn "CONDITION<$condition>\n";
717 #print "coff<$coff> soff<$off> loff<$loff>\n";
719 return ($statement, $condition,
720 $line, $remain + 1, $off - $loff + 1, $level);
723 sub statement_lines {
724 my ($stmt) = @_;
726 # Strip the diff line prefixes and rip blank lines at start and end.
727 $stmt =~ s/(^|\n)./$1/g;
728 $stmt =~ s/^\s*//;
729 $stmt =~ s/\s*$//;
731 my @stmt_lines = ($stmt =~ /\n/g);
733 return $#stmt_lines + 2;
736 sub statement_rawlines {
737 my ($stmt) = @_;
739 my @stmt_lines = ($stmt =~ /\n/g);
741 return $#stmt_lines + 2;
744 sub statement_block_size {
745 my ($stmt) = @_;
747 $stmt =~ s/(^|\n)./$1/g;
748 $stmt =~ s/^\s*\{//;
749 $stmt =~ s/}\s*$//;
750 $stmt =~ s/^\s*//;
751 $stmt =~ s/\s*$//;
753 my @stmt_lines = ($stmt =~ /\n/g);
754 my @stmt_statements = ($stmt =~ /;/g);
756 my $stmt_lines = $#stmt_lines + 2;
757 my $stmt_statements = $#stmt_statements + 1;
759 if ($stmt_lines > $stmt_statements) {
760 return $stmt_lines;
761 } else {
762 return $stmt_statements;
766 sub ctx_statement_full {
767 my ($linenr, $remain, $off) = @_;
768 my ($statement, $condition, $level);
770 my (@chunks);
772 # Grab the first conditional/block pair.
773 ($statement, $condition, $linenr, $remain, $off, $level) =
774 ctx_statement_block($linenr, $remain, $off);
775 #print "F: c<$condition> s<$statement> remain<$remain>\n";
776 push(@chunks, [ $condition, $statement ]);
777 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
778 return ($level, $linenr, @chunks);
781 # Pull in the following conditional/block pairs and see if they
782 # could continue the statement.
783 for (;;) {
784 ($statement, $condition, $linenr, $remain, $off, $level) =
785 ctx_statement_block($linenr, $remain, $off);
786 #print "C: c<$condition> s<$statement> remain<$remain>\n";
787 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
788 #print "C: push\n";
789 push(@chunks, [ $condition, $statement ]);
792 return ($level, $linenr, @chunks);
795 sub ctx_block_get {
796 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
797 my $line;
798 my $start = $linenr - 1;
799 my $blk = '';
800 my @o;
801 my @c;
802 my @res = ();
804 my $level = 0;
805 my @stack = ($level);
806 for ($line = $start; $remain > 0; $line++) {
807 next if ($rawlines[$line] =~ /^-/);
808 $remain--;
810 $blk .= $rawlines[$line];
812 # Handle nested #if/#else.
813 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
814 push(@stack, $level);
815 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
816 $level = $stack[$#stack - 1];
817 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
818 $level = pop(@stack);
821 foreach my $c (split(//, $lines[$line])) {
822 ##print "C<$c>L<$level><$open$close>O<$off>\n";
823 if ($off > 0) {
824 $off--;
825 next;
828 if ($c eq $close && $level > 0) {
829 $level--;
830 last if ($level == 0);
831 } elsif ($c eq $open) {
832 $level++;
836 if (!$outer || $level <= 1) {
837 push(@res, $rawlines[$line]);
840 last if ($level == 0);
843 return ($level, @res);
845 sub ctx_block_outer {
846 my ($linenr, $remain) = @_;
848 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
849 return @r;
851 sub ctx_block {
852 my ($linenr, $remain) = @_;
854 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
855 return @r;
857 sub ctx_statement {
858 my ($linenr, $remain, $off) = @_;
860 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
861 return @r;
863 sub ctx_block_level {
864 my ($linenr, $remain) = @_;
866 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
868 sub ctx_statement_level {
869 my ($linenr, $remain, $off) = @_;
871 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
874 sub ctx_locate_comment {
875 my ($first_line, $end_line) = @_;
877 # Catch a comment on the end of the line itself.
878 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
879 return $current_comment if (defined $current_comment);
881 # Look through the context and try and figure out if there is a
882 # comment.
883 my $in_comment = 0;
884 $current_comment = '';
885 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
886 my $line = $rawlines[$linenr - 1];
887 #warn " $line\n";
888 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
889 $in_comment = 1;
891 if ($line =~ m@/\*@) {
892 $in_comment = 1;
894 if (!$in_comment && $current_comment ne '') {
895 $current_comment = '';
897 $current_comment .= $line . "\n" if ($in_comment);
898 if ($line =~ m@\*/@) {
899 $in_comment = 0;
903 chomp($current_comment);
904 return($current_comment);
906 sub ctx_has_comment {
907 my ($first_line, $end_line) = @_;
908 my $cmt = ctx_locate_comment($first_line, $end_line);
910 ##print "LINE: $rawlines[$end_line - 1 ]\n";
911 ##print "CMMT: $cmt\n";
913 return ($cmt ne '');
916 sub raw_line {
917 my ($linenr, $cnt) = @_;
919 my $offset = $linenr - 1;
920 $cnt++;
922 my $line;
923 while ($cnt) {
924 $line = $rawlines[$offset++];
925 next if (defined($line) && $line =~ /^-/);
926 $cnt--;
929 return $line;
932 sub cat_vet {
933 my ($vet) = @_;
934 my ($res, $coded);
936 $res = '';
937 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
938 $res .= $1;
939 if ($2 ne '') {
940 $coded = sprintf("^%c", unpack('C', $2) + 64);
941 $res .= $coded;
944 $res =~ s/$/\$/;
946 return $res;
949 my $av_preprocessor = 0;
950 my $av_pending;
951 my @av_paren_type;
952 my $av_pend_colon;
954 sub annotate_reset {
955 $av_preprocessor = 0;
956 $av_pending = '_';
957 @av_paren_type = ('E');
958 $av_pend_colon = 'O';
961 sub annotate_values {
962 my ($stream, $type) = @_;
964 my $res;
965 my $var = '_' x length($stream);
966 my $cur = $stream;
968 print "$stream\n" if ($dbg_values > 1);
970 while (length($cur)) {
971 @av_paren_type = ('E') if ($#av_paren_type < 0);
972 print " <" . join('', @av_paren_type) .
973 "> <$type> <$av_pending>" if ($dbg_values > 1);
974 if ($cur =~ /^(\s+)/o) {
975 print "WS($1)\n" if ($dbg_values > 1);
976 if ($1 =~ /\n/ && $av_preprocessor) {
977 $type = pop(@av_paren_type);
978 $av_preprocessor = 0;
981 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
982 print "CAST($1)\n" if ($dbg_values > 1);
983 push(@av_paren_type, $type);
984 $type = 'C';
986 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
987 print "DECLARE($1)\n" if ($dbg_values > 1);
988 $type = 'T';
990 } elsif ($cur =~ /^($Modifier)\s*/) {
991 print "MODIFIER($1)\n" if ($dbg_values > 1);
992 $type = 'T';
994 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
995 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
996 $av_preprocessor = 1;
997 push(@av_paren_type, $type);
998 if ($2 ne '') {
999 $av_pending = 'N';
1001 $type = 'E';
1003 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1004 print "UNDEF($1)\n" if ($dbg_values > 1);
1005 $av_preprocessor = 1;
1006 push(@av_paren_type, $type);
1008 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1009 print "PRE_START($1)\n" if ($dbg_values > 1);
1010 $av_preprocessor = 1;
1012 push(@av_paren_type, $type);
1013 push(@av_paren_type, $type);
1014 $type = 'E';
1016 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1017 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1018 $av_preprocessor = 1;
1020 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1022 $type = 'E';
1024 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1025 print "PRE_END($1)\n" if ($dbg_values > 1);
1027 $av_preprocessor = 1;
1029 # Assume all arms of the conditional end as this
1030 # one does, and continue as if the #endif was not here.
1031 pop(@av_paren_type);
1032 push(@av_paren_type, $type);
1033 $type = 'E';
1035 } elsif ($cur =~ /^(\\\n)/o) {
1036 print "PRECONT($1)\n" if ($dbg_values > 1);
1038 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1039 print "ATTR($1)\n" if ($dbg_values > 1);
1040 $av_pending = $type;
1041 $type = 'N';
1043 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1044 print "SIZEOF($1)\n" if ($dbg_values > 1);
1045 if (defined $2) {
1046 $av_pending = 'V';
1048 $type = 'N';
1050 } elsif ($cur =~ /^(if|while|for)\b/o) {
1051 print "COND($1)\n" if ($dbg_values > 1);
1052 $av_pending = 'E';
1053 $type = 'N';
1055 } elsif ($cur =~/^(case)/o) {
1056 print "CASE($1)\n" if ($dbg_values > 1);
1057 $av_pend_colon = 'C';
1058 $type = 'N';
1060 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1061 print "KEYWORD($1)\n" if ($dbg_values > 1);
1062 $type = 'N';
1064 } elsif ($cur =~ /^(\()/o) {
1065 print "PAREN('$1')\n" if ($dbg_values > 1);
1066 push(@av_paren_type, $av_pending);
1067 $av_pending = '_';
1068 $type = 'N';
1070 } elsif ($cur =~ /^(\))/o) {
1071 my $new_type = pop(@av_paren_type);
1072 if ($new_type ne '_') {
1073 $type = $new_type;
1074 print "PAREN('$1') -> $type\n"
1075 if ($dbg_values > 1);
1076 } else {
1077 print "PAREN('$1')\n" if ($dbg_values > 1);
1080 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1081 print "FUNC($1)\n" if ($dbg_values > 1);
1082 $type = 'V';
1083 $av_pending = 'V';
1085 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1086 if (defined $2 && $type eq 'C' || $type eq 'T') {
1087 $av_pend_colon = 'B';
1088 } elsif ($type eq 'E') {
1089 $av_pend_colon = 'L';
1091 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1092 $type = 'V';
1094 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1095 print "IDENT($1)\n" if ($dbg_values > 1);
1096 $type = 'V';
1098 } elsif ($cur =~ /^($Assignment)/o) {
1099 print "ASSIGN($1)\n" if ($dbg_values > 1);
1100 $type = 'N';
1102 } elsif ($cur =~/^(;|{|})/) {
1103 print "END($1)\n" if ($dbg_values > 1);
1104 $type = 'E';
1105 $av_pend_colon = 'O';
1107 } elsif ($cur =~/^(,)/) {
1108 print "COMMA($1)\n" if ($dbg_values > 1);
1109 $type = 'C';
1111 } elsif ($cur =~ /^(\?)/o) {
1112 print "QUESTION($1)\n" if ($dbg_values > 1);
1113 $type = 'N';
1115 } elsif ($cur =~ /^(:)/o) {
1116 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1118 substr($var, length($res), 1, $av_pend_colon);
1119 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1120 $type = 'E';
1121 } else {
1122 $type = 'N';
1124 $av_pend_colon = 'O';
1126 } elsif ($cur =~ /^(\[)/o) {
1127 print "CLOSE($1)\n" if ($dbg_values > 1);
1128 $type = 'N';
1130 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1131 my $variant;
1133 print "OPV($1)\n" if ($dbg_values > 1);
1134 if ($type eq 'V') {
1135 $variant = 'B';
1136 } else {
1137 $variant = 'U';
1140 substr($var, length($res), 1, $variant);
1141 $type = 'N';
1143 } elsif ($cur =~ /^($Operators)/o) {
1144 print "OP($1)\n" if ($dbg_values > 1);
1145 if ($1 ne '++' && $1 ne '--') {
1146 $type = 'N';
1149 } elsif ($cur =~ /(^.)/o) {
1150 print "C($1)\n" if ($dbg_values > 1);
1152 if (defined $1) {
1153 $cur = substr($cur, length($1));
1154 $res .= $type x length($1);
1158 return ($res, $var);
1161 sub possible {
1162 my ($possible, $line) = @_;
1163 my $notPermitted = qr{(?:
1164 ^(?:
1165 $Modifier|
1166 $Storage|
1167 $Type|
1168 DEFINE_\S+
1170 ^(?:
1171 goto|
1172 return|
1173 case|
1174 else|
1175 asm|__asm__|
1177 )(?:\s|$)|
1178 ^(?:typedef|struct|enum)\b|
1180 )}x;
1181 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1182 if ($possible !~ $notPermitted) {
1183 # Check for modifiers.
1184 $possible =~ s/\s*$Storage\s*//g;
1185 $possible =~ s/\s*$Sparse\s*//g;
1186 if ($possible =~ /^\s*$/) {
1188 } elsif ($possible =~ /\s/) {
1189 $possible =~ s/\s*(?:$Type|\#\#)\s*//g;
1190 for my $modifier (split(' ', $possible)) {
1191 if ($modifier !~ $notPermitted) {
1192 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1193 push(@modifierList, $modifier);
1197 } else {
1198 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1199 push(@typeList, $possible);
1201 build_types();
1202 } else {
1203 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1207 my $prefix = '';
1209 sub report {
1210 my ($level, $msg) = @_;
1211 if (defined $tst_only && $msg !~ /\Q$tst_only\E/) {
1212 return 0;
1215 my $output = '';
1216 $output .= BOLD if $color;
1217 $output .= $prefix;
1218 $output .= RED if $color && $level eq 'ERROR';
1219 $output .= MAGENTA if $color && $level eq 'WARNING';
1220 $output .= $level . ':';
1221 $output .= RESET if $color;
1222 $output .= ' ' . $msg . "\n";
1224 $output = (split('\n', $output))[0] . "\n" if ($terse);
1226 push(our @report, $output);
1228 return 1;
1230 sub report_dump {
1231 our @report;
1233 sub ERROR {
1234 if (report("ERROR", $_[0])) {
1235 our $clean = 0;
1236 our $cnt_error++;
1239 sub WARN {
1240 if (report("WARNING", $_[0])) {
1241 our $clean = 0;
1242 our $cnt_warn++;
1246 sub process {
1247 my $filename = shift;
1249 my $linenr=0;
1250 my $prevline="";
1251 my $prevrawline="";
1252 my $stashline="";
1253 my $stashrawline="";
1255 my $length;
1256 my $indent;
1257 my $previndent=0;
1258 my $stashindent=0;
1260 our $clean = 1;
1261 my $signoff = 0;
1262 my $is_patch = 0;
1264 my $in_header_lines = $file ? 0 : 1;
1265 my $in_commit_log = 0; #Scanning lines before patch
1266 my $reported_maintainer_file = 0;
1267 my $non_utf8_charset = 0;
1269 our @report = ();
1270 our $cnt_lines = 0;
1271 our $cnt_error = 0;
1272 our $cnt_warn = 0;
1273 our $cnt_chk = 0;
1275 # Trace the real file/line as we go.
1276 my $realfile = '';
1277 my $realline = 0;
1278 my $realcnt = 0;
1279 my $here = '';
1280 my $in_comment = 0;
1281 my $comment_edge = 0;
1282 my $first_line = 0;
1283 my $p1_prefix = '';
1285 my $prev_values = 'E';
1287 # suppression flags
1288 my %suppress_ifbraces;
1289 my %suppress_whiletrailers;
1290 my %suppress_export;
1292 # Pre-scan the patch sanitizing the lines.
1294 sanitise_line_reset();
1295 my $line;
1296 foreach my $rawline (@rawlines) {
1297 $linenr++;
1298 $line = $rawline;
1300 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1301 $realline=$1-1;
1302 if (defined $2) {
1303 $realcnt=$3+1;
1304 } else {
1305 $realcnt=1+1;
1307 $in_comment = 0;
1309 # Guestimate if this is a continuing comment. Run
1310 # the context looking for a comment "edge". If this
1311 # edge is a close comment then we must be in a comment
1312 # at context start.
1313 my $edge;
1314 my $cnt = $realcnt;
1315 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1316 next if (defined $rawlines[$ln - 1] &&
1317 $rawlines[$ln - 1] =~ /^-/);
1318 $cnt--;
1319 #print "RAW<$rawlines[$ln - 1]>\n";
1320 last if (!defined $rawlines[$ln - 1]);
1321 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1322 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1323 ($edge) = $1;
1324 last;
1327 if (defined $edge && $edge eq '*/') {
1328 $in_comment = 1;
1331 # Guestimate if this is a continuing comment. If this
1332 # is the start of a diff block and this line starts
1333 # ' *' then it is very likely a comment.
1334 if (!defined $edge &&
1335 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1337 $in_comment = 1;
1340 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1341 sanitise_line_reset($in_comment);
1343 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1344 # Standardise the strings and chars within the input to
1345 # simplify matching -- only bother with positive lines.
1346 $line = sanitise_line($rawline);
1348 push(@lines, $line);
1350 if ($realcnt > 1) {
1351 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1352 } else {
1353 $realcnt = 0;
1356 #print "==>$rawline\n";
1357 #print "-->$line\n";
1360 $prefix = '';
1362 $realcnt = 0;
1363 $linenr = 0;
1364 foreach my $line (@lines) {
1365 $linenr++;
1367 my $rawline = $rawlines[$linenr - 1];
1369 #extract the line range in the file after the patch is applied
1370 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1371 $is_patch = 1;
1372 $first_line = $linenr + 1;
1373 $realline=$1-1;
1374 if (defined $2) {
1375 $realcnt=$3+1;
1376 } else {
1377 $realcnt=1+1;
1379 annotate_reset();
1380 $prev_values = 'E';
1382 %suppress_ifbraces = ();
1383 %suppress_whiletrailers = ();
1384 %suppress_export = ();
1385 next;
1387 # track the line number as we move through the hunk, note that
1388 # new versions of GNU diff omit the leading space on completely
1389 # blank context lines so we need to count that too.
1390 } elsif ($line =~ /^( |\+|$)/) {
1391 $realline++;
1392 $realcnt-- if ($realcnt != 0);
1394 # Measure the line length and indent.
1395 ($length, $indent) = line_stats($rawline);
1397 # Track the previous line.
1398 ($prevline, $stashline) = ($stashline, $line);
1399 ($previndent, $stashindent) = ($stashindent, $indent);
1400 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1402 #warn "line<$line>\n";
1404 } elsif ($realcnt == 1) {
1405 $realcnt--;
1408 my $hunk_line = ($realcnt != 0);
1410 #make up the handle for any error we report on this line
1411 $prefix = "$filename:$realline: " if ($emacs && $file);
1412 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1414 $here = "#$linenr: " if (!$file);
1415 $here = "#$realline: " if ($file);
1417 # extract the filename as it passes
1418 if ($line =~ /^diff --git.*?(\S+)$/) {
1419 $realfile = $1;
1420 $realfile =~ s@^([^/]*)/@@ if (!$file);
1421 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1422 $realfile = $1;
1423 $realfile =~ s@^([^/]*)/@@ if (!$file);
1425 $p1_prefix = $1;
1426 if (!$file && $tree && $p1_prefix ne '' &&
1427 -e "$root/$p1_prefix") {
1428 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1431 next;
1434 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1436 my $hereline = "$here\n$rawline\n";
1437 my $herecurr = "$here\n$rawline\n";
1438 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1440 $cnt_lines++ if ($realcnt != 0);
1442 # Check for incorrect file permissions
1443 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1444 my $permhere = $here . "FILE: $realfile\n";
1445 if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1446 ERROR("do not set execute permissions for source files\n" . $permhere);
1450 # Accept git diff extended headers as valid patches
1451 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1452 $is_patch = 1;
1455 if ($line =~ /^Author: .*via Qemu-devel.*<qemu-devel\@nongnu.org>/) {
1456 ERROR("Author email address is mangled by the mailing list\n" . $herecurr);
1459 #check the patch for a signoff:
1460 if ($line =~ /^\s*signed-off-by:/i) {
1461 # This is a signoff, if ugly, so do not double report.
1462 $signoff++;
1463 $in_commit_log = 0;
1465 if (!($line =~ /^\s*Signed-off-by:/)) {
1466 ERROR("The correct form is \"Signed-off-by\"\n" .
1467 $herecurr);
1469 if ($line =~ /^\s*signed-off-by:\S/i) {
1470 ERROR("space required after Signed-off-by:\n" .
1471 $herecurr);
1475 # Check if MAINTAINERS is being updated. If so, there's probably no need to
1476 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
1477 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
1478 $reported_maintainer_file = 1;
1481 # Check for added, moved or deleted files
1482 if (!$reported_maintainer_file && !$in_commit_log &&
1483 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
1484 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
1485 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
1486 (defined($1) || defined($2))))) {
1487 $reported_maintainer_file = 1;
1488 WARN("added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
1491 # Check for wrappage within a valid hunk of the file
1492 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1493 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1494 $herecurr) if (!$emitted_corrupt++);
1497 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1498 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1499 $rawline !~ m/^$UTF8*$/) {
1500 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1502 my $blank = copy_spacing($rawline);
1503 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1504 my $hereptr = "$hereline$ptr\n";
1506 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1509 # Check if it's the start of a commit log
1510 # (not a header line and we haven't seen the patch filename)
1511 if ($in_header_lines && $realfile =~ /^$/ &&
1512 !($rawline =~ /^\s+\S/ ||
1513 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1514 $in_header_lines = 0;
1515 $in_commit_log = 1;
1518 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1519 # declined it, i.e defined some charset where it is missing.
1520 if ($in_header_lines &&
1521 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1522 $1 !~ /utf-8/i) {
1523 $non_utf8_charset = 1;
1526 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1527 $rawline =~ /$NON_ASCII_UTF8/) {
1528 WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1531 # ignore non-hunk lines and lines being removed
1532 next if (!$hunk_line || $line =~ /^-/);
1534 # ignore files that are being periodically imported from Linux
1535 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1537 #trailing whitespace
1538 if ($line =~ /^\+.*\015/) {
1539 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1540 ERROR("DOS line endings\n" . $herevet);
1542 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1543 $realfile =~ /^docs\/.+\.md/) {
1544 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1545 # TODO: properly check we're in a code block
1546 # (surrounding text is 4-column aligned)
1547 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1548 ERROR("code blocks in documentation should have " .
1549 "empty lines with exactly 4 columns of " .
1550 "whitespace\n" . $herevet);
1552 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1553 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1554 ERROR("trailing whitespace\n" . $herevet);
1555 $rpt_cleaners = 1;
1558 # checks for trace-events files
1559 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1560 if ($rawline =~ /%[-+ 0]*#/) {
1561 ERROR("Don't use '#' flag of printf format ('%#') in " .
1562 "trace-events, use '0x' prefix instead\n" . $herecurr);
1563 } else {
1564 my $hex =
1565 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1567 # don't consider groups splitted by [.:/ ], like 2A.20:12ab
1568 my $tmpline = $rawline;
1569 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1571 if ($tmpline =~ /(?<!0x)$hex/) {
1572 ERROR("Hex numbers must be prefixed with '0x'\n" .
1573 $herecurr);
1578 # check we are in a valid source file if not then ignore this hunk
1579 next if ($realfile !~ /$SrcFile/);
1581 #90 column limit; exempt URLs, if no other words on line
1582 if ($line =~ /^\+/ &&
1583 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1584 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1585 $length > 80)
1587 if ($length > 90) {
1588 ERROR("line over 90 characters\n" . $herecurr);
1589 } else {
1590 WARN("line over 80 characters\n" . $herecurr);
1594 # check for spaces before a quoted newline
1595 if ($rawline =~ /^.*\".*\s\\n/) {
1596 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1599 # check for adding lines without a newline.
1600 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1601 ERROR("adding a line without newline at end of file\n" . $herecurr);
1604 # check for RCS/CVS revision markers
1605 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1606 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1609 # tabs are only allowed in assembly source code, and in
1610 # some scripts we imported from other projects.
1611 next if ($realfile =~ /\.(s|S)$/);
1612 next if ($realfile =~ /(checkpatch|get_maintainer|texi2pod)\.pl$/);
1614 if ($rawline =~ /^\+.*\t/) {
1615 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1616 ERROR("code indent should never use tabs\n" . $herevet);
1617 $rpt_cleaners = 1;
1620 # check we are in a valid C source file if not then ignore this hunk
1621 next if ($realfile !~ /\.(h|c|cpp)$/);
1623 # Block comment styles
1625 # Block comments use /* on a line of its own
1626 if ($rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
1627 $rawline =~ m@^\+.*/\*\*?+[ \t]*[^ \t]@) { # /* or /** non-blank
1628 WARN("Block comments use a leading /* on a separate line\n" . $herecurr);
1631 # Block comments use * on subsequent lines
1632 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1633 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
1634 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
1635 $rawline =~ /^\+/ && #line is new
1636 $rawline !~ /^\+[ \t]*\*/) { #no leading *
1637 WARN("Block comments use * on subsequent lines\n" . $hereprev);
1640 # Block comments use */ on trailing lines
1641 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
1642 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
1643 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
1644 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
1645 WARN("Block comments use a trailing */ on a separate line\n" . $herecurr);
1648 # Block comment * alignment
1649 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
1650 $line =~ /^\+[ \t]*$;/ && #leading comment
1651 $rawline =~ /^\+[ \t]*\*/ && #leading *
1652 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
1653 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
1654 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
1655 my $oldindent;
1656 $prevrawline =~ m@^\+([ \t]*/?)\*@;
1657 if (defined($1)) {
1658 $oldindent = expand_tabs($1);
1659 } else {
1660 $prevrawline =~ m@^\+(.*/?)\*@;
1661 $oldindent = expand_tabs($1);
1663 $rawline =~ m@^\+([ \t]*)\*@;
1664 my $newindent = $1;
1665 $newindent = expand_tabs($newindent);
1666 if (length($oldindent) ne length($newindent)) {
1667 WARN("Block comments should align the * on each line\n" . $hereprev);
1671 # Check for potential 'bare' types
1672 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1673 $realline_next);
1674 if ($realcnt && $line =~ /.\s*\S/) {
1675 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1676 ctx_statement_block($linenr, $realcnt, 0);
1677 $stat =~ s/\n./\n /g;
1678 $cond =~ s/\n./\n /g;
1680 # Find the real next line.
1681 $realline_next = $line_nr_next;
1682 if (defined $realline_next &&
1683 (!defined $lines[$realline_next - 1] ||
1684 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1685 $realline_next++;
1688 my $s = $stat;
1689 $s =~ s/{.*$//s;
1691 # Ignore goto labels.
1692 if ($s =~ /$Ident:\*$/s) {
1694 # Ignore functions being called
1695 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1697 } elsif ($s =~ /^.\s*else\b/s) {
1699 # declarations always start with types
1700 } 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) {
1701 my $type = $1;
1702 $type =~ s/\s+/ /g;
1703 possible($type, "A:" . $s);
1705 # definitions in global scope can only start with types
1706 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1707 possible($1, "B:" . $s);
1710 # any (foo ... *) is a pointer cast, and foo is a type
1711 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1712 possible($1, "C:" . $s);
1715 # Check for any sort of function declaration.
1716 # int foo(something bar, other baz);
1717 # void (*store_gdt)(x86_descr_ptr *);
1718 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1719 my ($name_len) = length($1);
1721 my $ctx = $s;
1722 substr($ctx, 0, $name_len + 1, '');
1723 $ctx =~ s/\)[^\)]*$//;
1725 for my $arg (split(/\s*,\s*/, $ctx)) {
1726 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1728 possible($1, "D:" . $s);
1736 # Checks which may be anchored in the context.
1739 # Check for switch () and associated case and default
1740 # statements should be at the same indent.
1741 if ($line=~/\bswitch\s*\(.*\)/) {
1742 my $err = '';
1743 my $sep = '';
1744 my @ctx = ctx_block_outer($linenr, $realcnt);
1745 shift(@ctx);
1746 for my $ctx (@ctx) {
1747 my ($clen, $cindent) = line_stats($ctx);
1748 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1749 $indent != $cindent) {
1750 $err .= "$sep$ctx\n";
1751 $sep = '';
1752 } else {
1753 $sep = "[...]\n";
1756 if ($err ne '') {
1757 ERROR("switch and case should be at the same indent\n$hereline$err");
1761 # if/while/etc brace do not go on next line, unless defining a do while loop,
1762 # or if that brace on the next line is for something else
1763 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1764 my $pre_ctx = "$1$2";
1766 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1767 my $ctx_cnt = $realcnt - $#ctx - 1;
1768 my $ctx = join("\n", @ctx);
1770 my $ctx_ln = $linenr;
1771 my $ctx_skip = $realcnt;
1773 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1774 defined $lines[$ctx_ln - 1] &&
1775 $lines[$ctx_ln - 1] =~ /^-/)) {
1776 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1777 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1778 $ctx_ln++;
1781 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1782 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1784 # The length of the "previous line" is checked against 80 because it
1785 # includes the + at the beginning of the line (if the actual line has
1786 # 79 or 80 characters, it is no longer possible to add a space and an
1787 # opening brace there)
1788 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1789 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1790 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1791 ERROR("that open brace { should be on the previous line\n" .
1792 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1794 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1795 $ctx =~ /\)\s*\;\s*$/ &&
1796 defined $lines[$ctx_ln - 1])
1798 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1799 if ($nindent > $indent) {
1800 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1801 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1806 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1807 if ($line =~ /while\s*\((0|false)\);/) {
1808 ERROR("suspicious ; after while (0)\n" . $herecurr);
1811 # Check relative indent for conditionals and blocks.
1812 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1813 my ($s, $c) = ($stat, $cond);
1815 substr($s, 0, length($c), '');
1817 # Make sure we remove the line prefixes as we have
1818 # none on the first line, and are going to readd them
1819 # where necessary.
1820 $s =~ s/\n./\n/gs;
1822 # Find out how long the conditional actually is.
1823 my @newlines = ($c =~ /\n/gs);
1824 my $cond_lines = 1 + $#newlines;
1826 # We want to check the first line inside the block
1827 # starting at the end of the conditional, so remove:
1828 # 1) any blank line termination
1829 # 2) any opening brace { on end of the line
1830 # 3) any do (...) {
1831 my $continuation = 0;
1832 my $check = 0;
1833 $s =~ s/^.*\bdo\b//;
1834 $s =~ s/^\s*\{//;
1835 if ($s =~ s/^\s*\\//) {
1836 $continuation = 1;
1838 if ($s =~ s/^\s*?\n//) {
1839 $check = 1;
1840 $cond_lines++;
1843 # Also ignore a loop construct at the end of a
1844 # preprocessor statement.
1845 if (($prevline =~ /^.\s*#\s*define\s/ ||
1846 $prevline =~ /\\\s*$/) && $continuation == 0) {
1847 $check = 0;
1850 my $cond_ptr = -1;
1851 $continuation = 0;
1852 while ($cond_ptr != $cond_lines) {
1853 $cond_ptr = $cond_lines;
1855 # If we see an #else/#elif then the code
1856 # is not linear.
1857 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1858 $check = 0;
1861 # Ignore:
1862 # 1) blank lines, they should be at 0,
1863 # 2) preprocessor lines, and
1864 # 3) labels.
1865 if ($continuation ||
1866 $s =~ /^\s*?\n/ ||
1867 $s =~ /^\s*#\s*?/ ||
1868 $s =~ /^\s*$Ident\s*:/) {
1869 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1870 if ($s =~ s/^.*?\n//) {
1871 $cond_lines++;
1876 my (undef, $sindent) = line_stats("+" . $s);
1877 my $stat_real = raw_line($linenr, $cond_lines);
1879 # Check if either of these lines are modified, else
1880 # this is not this patch's fault.
1881 if (!defined($stat_real) ||
1882 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1883 $check = 0;
1885 if (defined($stat_real) && $cond_lines > 1) {
1886 $stat_real = "[...]\n$stat_real";
1889 #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";
1891 if ($check && (($sindent % 4) != 0 ||
1892 ($sindent <= $indent && $s ne ''))) {
1893 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1897 # Track the 'values' across context and added lines.
1898 my $opline = $line; $opline =~ s/^./ /;
1899 my ($curr_values, $curr_vars) =
1900 annotate_values($opline . "\n", $prev_values);
1901 $curr_values = $prev_values . $curr_values;
1902 if ($dbg_values) {
1903 my $outline = $opline; $outline =~ s/\t/ /g;
1904 print "$linenr > .$outline\n";
1905 print "$linenr > $curr_values\n";
1906 print "$linenr > $curr_vars\n";
1908 $prev_values = substr($curr_values, -1);
1910 #ignore lines not being added
1911 if ($line=~/^[^\+]/) {next;}
1913 # TEST: allow direct testing of the type matcher.
1914 if ($dbg_type) {
1915 if ($line =~ /^.\s*$Declare\s*$/) {
1916 ERROR("TEST: is type\n" . $herecurr);
1917 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1918 ERROR("TEST: is not type ($1 is)\n". $herecurr);
1920 next;
1922 # TEST: allow direct testing of the attribute matcher.
1923 if ($dbg_attr) {
1924 if ($line =~ /^.\s*$Modifier\s*$/) {
1925 ERROR("TEST: is attr\n" . $herecurr);
1926 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1927 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1929 next;
1932 # check for initialisation to aggregates open brace on the next line
1933 if ($line =~ /^.\s*\{/ &&
1934 $prevline =~ /(?:^|[^=])=\s*$/) {
1935 ERROR("that open brace { should be on the previous line\n" . $hereprev);
1939 # Checks which are anchored on the added line.
1942 # check for malformed paths in #include statements (uses RAW line)
1943 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1944 my $path = $1;
1945 if ($path =~ m{//}) {
1946 ERROR("malformed #include filename\n" .
1947 $herecurr);
1951 # no C99 // comments
1952 if ($line =~ m{//}) {
1953 ERROR("do not use C99 // comments\n" . $herecurr);
1955 # Remove C99 comments.
1956 $line =~ s@//.*@@;
1957 $opline =~ s@//.*@@;
1959 # check for global initialisers.
1960 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
1961 ERROR("do not initialise globals to 0 or NULL\n" .
1962 $herecurr);
1964 # check for static initialisers.
1965 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
1966 ERROR("do not initialise statics to 0 or NULL\n" .
1967 $herecurr);
1970 # * goes on variable not on type
1971 # (char*[ const])
1972 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1973 my ($from, $to) = ($1, $1);
1975 # Should start with a space.
1976 $to =~ s/^(\S)/ $1/;
1977 # Should not end with a space.
1978 $to =~ s/\s+$//;
1979 # '*'s should not have spaces between.
1980 while ($to =~ s/\*\s+\*/\*\*/) {
1983 #print "from<$from> to<$to>\n";
1984 if ($from ne $to) {
1985 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
1987 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1988 my ($from, $to, $ident) = ($1, $1, $2);
1990 # Should start with a space.
1991 $to =~ s/^(\S)/ $1/;
1992 # Should not end with a space.
1993 $to =~ s/\s+$//;
1994 # '*'s should not have spaces between.
1995 while ($to =~ s/\*\s+\*/\*\*/) {
1997 # Modifiers should have spaces.
1998 $to =~ s/(\b$Modifier$)/$1 /;
2000 #print "from<$from> to<$to> ident<$ident>\n";
2001 if ($from ne $to && $ident !~ /^$Modifier$/) {
2002 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
2006 # function brace can't be on same line, except for #defines of do while,
2007 # or if closed on same line
2008 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2009 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
2010 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
2013 # open braces for enum, union and struct go on the same line.
2014 if ($line =~ /^.\s*\{/ &&
2015 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2016 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
2019 # missing space after union, struct or enum definition
2020 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
2021 ERROR("missing space after $1 definition\n" . $herecurr);
2024 # check for spacing round square brackets; allowed:
2025 # 1. with a type on the left -- int [] a;
2026 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2027 # 3. inside a curly brace -- = { [0...10] = 5 }
2028 # 4. after a comma -- [1] = 5, [2] = 6
2029 # 5. in a macro definition -- #define abc(x) [x] = y
2030 while ($line =~ /(.*?\s)\[/g) {
2031 my ($where, $prefix) = ($-[1], $1);
2032 if ($prefix !~ /$Type\s+$/ &&
2033 ($where != 0 || $prefix !~ /^.\s+$/) &&
2034 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
2035 $prefix !~ /[,{:]\s+$/) {
2036 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
2040 # check for spaces between functions and their parentheses.
2041 while ($line =~ /($Ident)\s+\(/g) {
2042 my $name = $1;
2043 my $ctx_before = substr($line, 0, $-[1]);
2044 my $ctx = "$ctx_before$name";
2046 # Ignore those directives where spaces _are_ permitted.
2047 if ($name =~ /^(?:
2048 if|for|while|switch|return|case|
2049 volatile|__volatile__|coroutine_fn|
2050 __attribute__|format|__extension__|
2051 asm|__asm__)$/x)
2054 # Ignore 'catch (...)' in C++
2055 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
2057 # cpp #define statements have non-optional spaces, ie
2058 # if there is a space between the name and the open
2059 # parenthesis it is simply not a parameter group.
2060 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2062 # cpp #elif statement condition may start with a (
2063 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2065 # If this whole things ends with a type its most
2066 # likely a typedef for a function.
2067 } elsif ($ctx =~ /$Type$/) {
2069 } else {
2070 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
2073 # Check operator spacing.
2074 if (!($line=~/\#\s*include/)) {
2075 my $ops = qr{
2076 <<=|>>=|<=|>=|==|!=|
2077 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2078 =>|->|<<|>>|<|>|=|!|~|
2079 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2080 \?|::|:
2082 my @elements = split(/($ops|;)/, $opline);
2083 my $off = 0;
2085 my $blank = copy_spacing($opline);
2087 for (my $n = 0; $n < $#elements; $n += 2) {
2088 $off += length($elements[$n]);
2090 # Pick up the preceding and succeeding characters.
2091 my $ca = substr($opline, 0, $off);
2092 my $cc = '';
2093 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2094 $cc = substr($opline, $off + length($elements[$n + 1]));
2096 my $cb = "$ca$;$cc";
2098 my $a = '';
2099 $a = 'V' if ($elements[$n] ne '');
2100 $a = 'W' if ($elements[$n] =~ /\s$/);
2101 $a = 'C' if ($elements[$n] =~ /$;$/);
2102 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2103 $a = 'O' if ($elements[$n] eq '');
2104 $a = 'E' if ($ca =~ /^\s*$/);
2106 my $op = $elements[$n + 1];
2108 my $c = '';
2109 if (defined $elements[$n + 2]) {
2110 $c = 'V' if ($elements[$n + 2] ne '');
2111 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2112 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2113 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2114 $c = 'O' if ($elements[$n + 2] eq '');
2115 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2116 } else {
2117 $c = 'E';
2120 my $ctx = "${a}x${c}";
2122 my $at = "(ctx:$ctx)";
2124 my $ptr = substr($blank, 0, $off) . "^";
2125 my $hereptr = "$hereline$ptr\n";
2127 # Pull out the value of this operator.
2128 my $op_type = substr($curr_values, $off + 1, 1);
2130 # Get the full operator variant.
2131 my $opv = $op . substr($curr_vars, $off, 1);
2133 # Ignore operators passed as parameters.
2134 if ($op_type ne 'V' &&
2135 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2137 # # Ignore comments
2138 # } elsif ($op =~ /^$;+$/) {
2140 # ; should have either the end of line or a space or \ after it
2141 } elsif ($op eq ';') {
2142 if ($ctx !~ /.x[WEBC]/ &&
2143 $cc !~ /^\\/ && $cc !~ /^;/) {
2144 ERROR("space required after that '$op' $at\n" . $hereptr);
2147 # // is a comment
2148 } elsif ($op eq '//') {
2150 # Ignore : used in class declaration in C++
2151 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2152 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2154 # No spaces for:
2155 # ->
2156 # : when part of a bitfield
2157 } elsif ($op eq '->' || $opv eq ':B') {
2158 if ($ctx =~ /Wx.|.xW/) {
2159 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2162 # , must have a space on the right.
2163 # not required when having a single },{ on one line
2164 } elsif ($op eq ',') {
2165 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2166 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2167 ERROR("space required after that '$op' $at\n" . $hereptr);
2170 # '*' as part of a type definition -- reported already.
2171 } elsif ($opv eq '*_') {
2172 #warn "'*' is part of type\n";
2174 # unary operators should have a space before and
2175 # none after. May be left adjacent to another
2176 # unary operator, or a cast
2177 } elsif ($op eq '!' || $op eq '~' ||
2178 $opv eq '*U' || $opv eq '-U' ||
2179 $opv eq '&U' || $opv eq '&&U') {
2180 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2181 # '~' used as a name of Destructor
2183 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2184 ERROR("space required before that '$op' $at\n" . $hereptr);
2186 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2187 # A unary '*' may be const
2189 } elsif ($ctx =~ /.xW/) {
2190 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2193 # unary ++ and unary -- are allowed no space on one side.
2194 } elsif ($op eq '++' or $op eq '--') {
2195 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2196 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2198 if ($ctx =~ /Wx[BE]/ ||
2199 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2200 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2202 if ($ctx =~ /ExW/) {
2203 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2206 # A colon needs no spaces before when it is
2207 # terminating a case value or a label.
2208 } elsif ($opv eq ':C' || $opv eq ':L') {
2209 if ($ctx =~ /Wx./) {
2210 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2213 # All the others need spaces both sides.
2214 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2215 my $ok = 0;
2217 if ($realfile =~ /\.cpp|\.h$/) {
2218 # Ignore template arguments <...> in C++
2219 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2220 $ok = 1;
2223 # Ignore :: in C++
2224 if ($op eq '::') {
2225 $ok = 1;
2229 # Ignore email addresses <foo@bar>
2230 if (($op eq '<' &&
2231 $cc =~ /^\S+\@\S+>/) ||
2232 ($op eq '>' &&
2233 $ca =~ /<\S+\@\S+$/))
2235 $ok = 1;
2238 # Ignore ?:
2239 if (($opv eq ':O' && $ca =~ /\?$/) ||
2240 ($op eq '?' && $cc =~ /^:/)) {
2241 $ok = 1;
2244 if ($ok == 0) {
2245 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2248 $off += length($elements[$n + 1]);
2252 #need space before brace following if, while, etc
2253 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2254 $line =~ /do\{/) {
2255 ERROR("space required before the open brace '{'\n" . $herecurr);
2258 # closing brace should have a space following it when it has anything
2259 # on the line
2260 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2261 ERROR("space required after that close brace '}'\n" . $herecurr);
2264 # check spacing on square brackets
2265 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2266 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2268 if ($line =~ /\s\]/) {
2269 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2272 # check spacing on parentheses
2273 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2274 $line !~ /for\s*\(\s+;/) {
2275 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2277 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2278 $line !~ /for\s*\(.*;\s+\)/ &&
2279 $line !~ /:\s+\)/) {
2280 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2283 # Return is not a function.
2284 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2285 my $spacing = $1;
2286 my $value = $2;
2288 # Flatten any parentheses
2289 $value =~ s/\(/ \(/g;
2290 $value =~ s/\)/\) /g;
2291 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2292 $value !~ /(?:$Ident|-?$Constant)\s*
2293 $Compare\s*
2294 (?:$Ident|-?$Constant)/x &&
2295 $value =~ s/\([^\(\)]*\)/1/) {
2297 #print "value<$value>\n";
2298 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2299 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2301 } elsif ($spacing !~ /\s+/) {
2302 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2305 # Return of what appears to be an errno should normally be -'ve
2306 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2307 my $name = $1;
2308 if ($name ne 'EOF' && $name ne 'ERROR') {
2309 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2313 if ($line =~ /^.\s*(Q(?:S?LIST|SIMPLEQ|TAILQ)_HEAD)\s*\(\s*[^,]/ &&
2314 $line !~ /^.typedef/) {
2315 ERROR("named $1 should be typedefed separately\n" . $herecurr);
2318 # Need a space before open parenthesis after if, while etc
2319 if ($line=~/\b(if|while|for|switch)\(/) {
2320 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2323 # Check for illegal assignment in if conditional -- and check for trailing
2324 # statements after the conditional.
2325 if ($line =~ /do\s*(?!{)/) {
2326 my ($stat_next) = ctx_statement_block($line_nr_next,
2327 $remain_next, $off_next);
2328 $stat_next =~ s/\n./\n /g;
2329 ##print "stat<$stat> stat_next<$stat_next>\n";
2331 if ($stat_next =~ /^\s*while\b/) {
2332 # If the statement carries leading newlines,
2333 # then count those as offsets.
2334 my ($whitespace) =
2335 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2336 my $offset =
2337 statement_rawlines($whitespace) - 1;
2339 $suppress_whiletrailers{$line_nr_next +
2340 $offset} = 1;
2343 if (!defined $suppress_whiletrailers{$linenr} &&
2344 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2345 my ($s, $c) = ($stat, $cond);
2347 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2348 ERROR("do not use assignment in if condition\n" . $herecurr);
2351 # Find out what is on the end of the line after the
2352 # conditional.
2353 substr($s, 0, length($c), '');
2354 $s =~ s/\n.*//g;
2355 $s =~ s/$;//g; # Remove any comments
2356 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2357 $c !~ /}\s*while\s*/)
2359 # Find out how long the conditional actually is.
2360 my @newlines = ($c =~ /\n/gs);
2361 my $cond_lines = 1 + $#newlines;
2362 my $stat_real = '';
2364 $stat_real = raw_line($linenr, $cond_lines)
2365 . "\n" if ($cond_lines);
2366 if (defined($stat_real) && $cond_lines > 1) {
2367 $stat_real = "[...]\n$stat_real";
2370 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2374 # Check for bitwise tests written as boolean
2375 if ($line =~ /
2377 (?:\[|\(|\&\&|\|\|)
2378 \s*0[xX][0-9]+\s*
2379 (?:\&\&|\|\|)
2381 (?:\&\&|\|\|)
2382 \s*0[xX][0-9]+\s*
2383 (?:\&\&|\|\||\)|\])
2384 )/x)
2386 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2389 # if and else should not have general statements after it
2390 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2391 my $s = $1;
2392 $s =~ s/$;//g; # Remove any comments
2393 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2394 ERROR("trailing statements should be on next line\n" . $herecurr);
2397 # if should not continue a brace
2398 if ($line =~ /}\s*if\b/) {
2399 ERROR("trailing statements should be on next line\n" .
2400 $herecurr);
2402 # case and default should not have general statements after them
2403 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2404 $line !~ /\G(?:
2405 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2406 \s*return\s+
2407 )/xg)
2409 ERROR("trailing statements should be on next line\n" . $herecurr);
2412 # Check for }<nl>else {, these must be at the same
2413 # indent level to be relevant to each other.
2414 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2415 $previndent == $indent) {
2416 ERROR("else should follow close brace '}'\n" . $hereprev);
2419 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2420 $previndent == $indent) {
2421 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2423 # Find out what is on the end of the line after the
2424 # conditional.
2425 substr($s, 0, length($c), '');
2426 $s =~ s/\n.*//g;
2428 if ($s =~ /^\s*;/) {
2429 ERROR("while should follow close brace '}'\n" . $hereprev);
2433 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2434 # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2435 # print "No studly caps, use _\n";
2436 # print "$herecurr";
2437 # $clean = 0;
2440 #no spaces allowed after \ in define
2441 if ($line=~/\#\s*define.*\\\s$/) {
2442 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2445 # multi-statement macros should be enclosed in a do while loop, grab the
2446 # first statement and ensure its the whole macro if its not enclosed
2447 # in a known good container
2448 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2449 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2450 my $ln = $linenr;
2451 my $cnt = $realcnt;
2452 my ($off, $dstat, $dcond, $rest);
2453 my $ctx = '';
2455 my $args = defined($1);
2457 # Find the end of the macro and limit our statement
2458 # search to that.
2459 while ($cnt > 0 && defined $lines[$ln - 1] &&
2460 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2462 $ctx .= $rawlines[$ln - 1] . "\n";
2463 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2464 $ln++;
2466 $ctx .= $rawlines[$ln - 1];
2468 ($dstat, $dcond, $ln, $cnt, $off) =
2469 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2470 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2471 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2473 # Extract the remainder of the define (if any) and
2474 # rip off surrounding spaces, and trailing \'s.
2475 $rest = '';
2476 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2477 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2478 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2479 $rest .= substr($lines[$ln - 1], $off) . "\n";
2480 $cnt--;
2482 $ln++;
2483 $off = 0;
2485 $rest =~ s/\\\n.//g;
2486 $rest =~ s/^\s*//s;
2487 $rest =~ s/\s*$//s;
2489 # Clean up the original statement.
2490 if ($args) {
2491 substr($dstat, 0, length($dcond), '');
2492 } else {
2493 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2495 $dstat =~ s/$;//g;
2496 $dstat =~ s/\\\n.//g;
2497 $dstat =~ s/^\s*//s;
2498 $dstat =~ s/\s*$//s;
2500 # Flatten any parentheses and braces
2501 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2502 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2503 $dstat =~ s/\[[^\{\}]*\]/1/)
2507 my $exceptions = qr{
2508 $Declare|
2509 module_param_named|
2510 MODULE_PARAM_DESC|
2511 DECLARE_PER_CPU|
2512 DEFINE_PER_CPU|
2513 __typeof__\(|
2514 union|
2515 struct|
2516 \.$Ident\s*=\s*|
2517 ^\"|\"$
2519 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2520 if ($rest ne '' && $rest ne ',') {
2521 if ($rest !~ /while\s*\(/ &&
2522 $dstat !~ /$exceptions/)
2524 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2527 } elsif ($ctx !~ /;/) {
2528 if ($dstat ne '' &&
2529 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2530 $dstat !~ /$exceptions/ &&
2531 $dstat !~ /^\.$Ident\s*=/ &&
2532 $dstat =~ /$Operators/)
2534 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2539 # check for missing bracing around if etc
2540 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2541 $line !~ /\#\s*if/) {
2542 my $allowed = 0;
2544 # Check the pre-context.
2545 if ($line =~ /(\}.*?)$/) {
2546 my $pre = $1;
2548 if ($line !~ /else/) {
2549 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2550 if $dbg_adv_apw;
2551 $allowed = 1;
2554 my ($level, $endln, @chunks) =
2555 ctx_statement_full($linenr, $realcnt, 1);
2556 if ($dbg_adv_apw) {
2557 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2558 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2559 if $#chunks >= 1;
2561 if ($#chunks >= 0 && $level == 0) {
2562 my $seen = 0;
2563 my $herectx = $here . "\n";
2564 my $ln = $linenr - 1;
2565 for my $chunk (@chunks) {
2566 my ($cond, $block) = @{$chunk};
2568 # If the condition carries leading newlines, then count those as offsets.
2569 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2570 my $offset = statement_rawlines($whitespace) - 1;
2572 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2574 # We have looked at and allowed this specific line.
2575 $suppress_ifbraces{$ln + $offset} = 1;
2577 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2578 $ln += statement_rawlines($block) - 1;
2580 substr($block, 0, length($cond), '');
2582 my $spaced_block = $block;
2583 $spaced_block =~ s/\n\+/ /g;
2585 $seen++ if ($spaced_block =~ /^\s*\{/);
2587 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2588 if $dbg_adv_apw;
2589 if (statement_lines($cond) > 1) {
2590 print "APW: ALLOWED: cond<$cond>\n"
2591 if $dbg_adv_apw;
2592 $allowed = 1;
2594 if ($block =~/\b(?:if|for|while)\b/) {
2595 print "APW: ALLOWED: block<$block>\n"
2596 if $dbg_adv_apw;
2597 $allowed = 1;
2599 if (statement_block_size($block) > 1) {
2600 print "APW: ALLOWED: lines block<$block>\n"
2601 if $dbg_adv_apw;
2602 $allowed = 1;
2605 if ($seen != ($#chunks + 1) && !$allowed) {
2606 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2610 if (!defined $suppress_ifbraces{$linenr - 1} &&
2611 $line =~ /\b(if|while|for|else)\b/ &&
2612 $line !~ /\#\s*if/ &&
2613 $line !~ /\#\s*else/) {
2614 my $allowed = 0;
2616 # Check the pre-context.
2617 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2618 my $pre = $1;
2620 if ($line !~ /else/) {
2621 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2622 if $dbg_adv_apw;
2623 $allowed = 1;
2627 my ($level, $endln, @chunks) =
2628 ctx_statement_full($linenr, $realcnt, $-[0]);
2630 # Check the condition.
2631 my ($cond, $block) = @{$chunks[0]};
2632 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2633 if $dbg_adv_checking;
2634 if (defined $cond) {
2635 substr($block, 0, length($cond), '');
2637 if (statement_lines($cond) > 1) {
2638 print "APW: ALLOWED: cond<$cond>\n"
2639 if $dbg_adv_apw;
2640 $allowed = 1;
2642 if ($block =~/\b(?:if|for|while)\b/) {
2643 print "APW: ALLOWED: block<$block>\n"
2644 if $dbg_adv_apw;
2645 $allowed = 1;
2647 if (statement_block_size($block) > 1) {
2648 print "APW: ALLOWED: lines block<$block>\n"
2649 if $dbg_adv_apw;
2650 $allowed = 1;
2652 # Check the post-context.
2653 if (defined $chunks[1]) {
2654 my ($cond, $block) = @{$chunks[1]};
2655 if (defined $cond) {
2656 substr($block, 0, length($cond), '');
2658 if ($block =~ /^\s*\{/) {
2659 print "APW: ALLOWED: chunk-1 block<$block>\n"
2660 if $dbg_adv_apw;
2661 $allowed = 1;
2664 print "DCS: level=$level block<$block> allowed=$allowed\n"
2665 if $dbg_adv_dcs;
2666 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2667 my $herectx = $here . "\n";;
2668 my $cnt = statement_rawlines($block);
2670 for (my $n = 0; $n < $cnt; $n++) {
2671 $herectx .= raw_line($linenr, $n) . "\n";;
2674 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2678 # no volatiles please
2679 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2680 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
2681 $line !~ /sig_atomic_t/ &&
2682 !ctx_has_comment($first_line, $linenr)) {
2683 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
2684 ERROR($msg);
2687 # warn about #if 0
2688 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2689 ERROR("if this code is redundant consider removing it\n" .
2690 $herecurr);
2693 # check for needless g_free() checks
2694 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2695 my $expr = $1;
2696 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2697 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2701 # warn about #ifdefs in C files
2702 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2703 # print "#ifdef in C files should be avoided\n";
2704 # print "$herecurr";
2705 # $clean = 0;
2708 # warn about spacing in #ifdefs
2709 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2710 ERROR("exactly one space required after that #$1\n" . $herecurr);
2712 # check for memory barriers without a comment.
2713 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2714 if (!ctx_has_comment($first_line, $linenr)) {
2715 ERROR("memory barrier without comment\n" . $herecurr);
2718 # check of hardware specific defines
2719 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2720 # where they might be necessary.
2721 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2722 WARN("architecture specific defines should be avoided\n" . $herecurr);
2725 # Check that the storage class is at the beginning of a declaration
2726 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2727 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2730 # check the location of the inline attribute, that it is between
2731 # storage class and type.
2732 if ($line =~ /\b$Type\s+$Inline\b/ ||
2733 $line =~ /\b$Inline\s+$Storage\b/) {
2734 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2737 # check for sizeof(&)
2738 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2739 ERROR("sizeof(& should be avoided\n" . $herecurr);
2742 # check for new externs in .c files.
2743 if ($realfile =~ /\.c$/ && defined $stat &&
2744 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2746 my $function_name = $1;
2747 my $paren_space = $2;
2749 my $s = $stat;
2750 if (defined $cond) {
2751 substr($s, 0, length($cond), '');
2753 if ($s =~ /^\s*;/ &&
2754 $function_name ne 'uninitialized_var')
2756 ERROR("externs should be avoided in .c files\n" . $herecurr);
2759 if ($paren_space =~ /\n/) {
2760 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2763 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2764 $stat =~ /^.\s*extern\s+/)
2766 ERROR("externs should be avoided in .c files\n" . $herecurr);
2769 # check for pointless casting of g_malloc return
2770 if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2771 if ($2 == 'm') {
2772 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2773 } else {
2774 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2778 # check for gcc specific __FUNCTION__
2779 if ($line =~ /__FUNCTION__/) {
2780 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
2783 # recommend g_path_get_* over g_strdup(basename/dirname(...))
2784 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
2785 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
2788 # recommend qemu_strto* over strto* for numeric conversions
2789 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2790 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2792 # recommend sigaction over signal for portability, when establishing a handler
2793 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2794 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2796 # check for module_init(), use category-specific init macros explicitly please
2797 if ($line =~ /^module_init\s*\(/) {
2798 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2800 # check for various ops structs, ensure they are const.
2801 my $struct_ops = qr{AIOCBInfo|
2802 BdrvActionOps|
2803 BlockDevOps|
2804 BlockJobDriver|
2805 DisplayChangeListenerOps|
2806 GraphicHwOps|
2807 IDEDMAOps|
2808 KVMCapabilityInfo|
2809 MemoryRegionIOMMUOps|
2810 MemoryRegionOps|
2811 MemoryRegionPortio|
2812 QEMUFileOps|
2813 SCSIBusInfo|
2814 SCSIReqOps|
2815 Spice[A-Z][a-zA-Z0-9]*Interface|
2816 USBDesc[A-Z][a-zA-Z0-9]*|
2817 VhostOps|
2818 VMStateDescription|
2819 VMStateInfo}x;
2820 if ($line !~ /\bconst\b/ &&
2821 $line =~ /\b($struct_ops)\b.*=/) {
2822 ERROR("initializer for struct $1 should normally be const\n" .
2823 $herecurr);
2826 # check for %L{u,d,i} in strings
2827 my $string;
2828 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2829 $string = substr($rawline, $-[1], $+[1] - $-[1]);
2830 $string =~ s/%%/__/g;
2831 if ($string =~ /(?<!%)%L[udi]/) {
2832 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2833 last;
2837 # QEMU specific tests
2838 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2839 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2842 # Qemu error function tests
2844 # Find newlines in error messages
2845 my $qemu_error_funcs = qr{error_setg|
2846 error_setg_errno|
2847 error_setg_win32|
2848 error_setg_file_open|
2849 error_set|
2850 error_prepend|
2851 warn_reportf_err|
2852 error_reportf_err|
2853 error_vreport|
2854 warn_vreport|
2855 info_vreport|
2856 error_report|
2857 warn_report|
2858 info_report|
2859 g_test_message}x;
2861 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2862 ERROR("Error messages should not contain newlines\n" . $herecurr);
2865 # Continue checking for error messages that contains newlines. This
2866 # check handles cases where string literals are spread over multiple lines.
2867 # Example:
2868 # error_report("Error msg line #1"
2869 # "Error msg line #2\n");
2870 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2871 my $continued_str_literal = qr{\+\s*\".*\"};
2873 if ($rawline =~ /$quoted_newline_regex/) {
2874 # Backtrack to first line that does not contain only a quoted literal
2875 # and assume that it is the start of the statement.
2876 my $i = $linenr - 2;
2878 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2879 $i--;
2882 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2883 ERROR("Error messages should not contain newlines\n" . $herecurr);
2887 # check for non-portable libc calls that have portable alternatives in QEMU
2888 if ($line =~ /\bffs\(/) {
2889 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2891 if ($line =~ /\bffsl\(/) {
2892 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2894 if ($line =~ /\bffsll\(/) {
2895 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2897 if ($line =~ /\bbzero\(/) {
2898 ERROR("use memset() instead of bzero()\n" . $herecurr);
2900 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2901 g_assert_cmpint|
2902 g_assert_cmpuint|
2903 g_assert_cmphex|
2904 g_assert_cmpfloat|
2905 g_assert_true|
2906 g_assert_false|
2907 g_assert_nonnull|
2908 g_assert_null|
2909 g_assert_no_error|
2910 g_assert_error|
2911 g_test_assert_expected_messages|
2912 g_test_trap_assert_passed|
2913 g_test_trap_assert_stdout|
2914 g_test_trap_assert_stdout_unmatched|
2915 g_test_trap_assert_stderr|
2916 g_test_trap_assert_stderr_unmatched}x;
2917 if ($realfile !~ /^tests\// &&
2918 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2919 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
2923 if ($is_patch && $chk_signoff && $signoff == 0) {
2924 ERROR("Missing Signed-off-by: line(s)\n");
2927 # If we have no input at all, then there is nothing to report on
2928 # so just keep quiet.
2929 if ($#rawlines == -1) {
2930 return 1;
2933 # In mailback mode only produce a report in the negative, for
2934 # things that appear to be patches.
2935 if ($mailback && ($clean == 1 || !$is_patch)) {
2936 return 1;
2939 # This is not a patch, and we are are in 'no-patch' mode so
2940 # just keep quiet.
2941 if (!$chk_patch && !$is_patch) {
2942 return 1;
2945 if (!$is_patch) {
2946 ERROR("Does not appear to be a unified-diff format patch\n");
2949 print report_dump();
2950 if ($summary && !($clean == 1 && $quiet == 1)) {
2951 print "$filename " if ($summary_file);
2952 print "total: $cnt_error errors, $cnt_warn warnings, " .
2953 "$cnt_lines lines checked\n";
2954 print "\n" if ($quiet == 0);
2957 if ($quiet == 0) {
2958 # If there were whitespace errors which cleanpatch can fix
2959 # then suggest that.
2960 # if ($rpt_cleaners) {
2961 # print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2962 # print " scripts/cleanfile\n\n";
2966 if ($clean == 1 && $quiet == 0) {
2967 print "$vname has no obvious style problems and is ready for submission.\n"
2969 if ($clean == 0 && $quiet == 0) {
2970 print "$vname has style problems, please review. If any of these errors\n";
2971 print "are false positives report them to the maintainer, see\n";
2972 print "CHECKPATCH in MAINTAINERS.\n";
2975 return ($no_warnings ? $clean : $cnt_error == 0);