]> git.proxmox.com Git - mirror_qemu.git/blob - scripts/checkpatch.pl
Merge remote-tracking branch 'remotes/iwj/tags/for-upstream.depriv-2' into staging
[mirror_qemu.git] / scripts / checkpatch.pl
1 #!/usr/bin/env perl
2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
7
8 use strict;
9 use warnings;
10
11 my $P = $0;
12 $P =~ s@.*/@@g;
13
14 our $SrcFile = qr{\.(?:h|c|cpp|s|S|pl|py|sh)$};
15
16 my $V = '0.31';
17
18 use Getopt::Long qw(:config no_auto_abbrev);
19
20 my $quiet = 0;
21 my $tree = 1;
22 my $chk_signoff = 1;
23 my $chk_patch = undef;
24 my $chk_branch = undef;
25 my $tst_only;
26 my $emacs = 0;
27 my $terse = 0;
28 my $file = undef;
29 my $no_warnings = 0;
30 my $summary = 1;
31 my $mailback = 0;
32 my $summary_file = 0;
33 my $root;
34 my %debug;
35 my $help = 0;
36
37 sub help {
38 my ($exitcode) = @_;
39
40 print << "EOM";
41 Usage:
42
43 $P [OPTION]... [FILE]...
44 $P [OPTION]... [GIT-REV-LIST]
45
46 Version: $V
47
48 Options:
49 -q, --quiet quiet
50 --no-tree run without a kernel tree
51 --no-signoff do not check for 'Signed-off-by' line
52 --patch treat FILE as patchfile
53 --branch treat args as GIT revision list
54 --emacs emacs compile window format
55 --terse one line per report
56 -f, --file treat FILE as regular source file
57 --strict fail if only warnings are found
58 --root=PATH PATH to the kernel tree root
59 --no-summary suppress the per-file summary
60 --mailback only produce a report in case of warnings/errors
61 --summary-file include the filename in summary
62 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
63 'values', 'possible', 'type', and 'attr' (default
64 is all off)
65 --test-only=WORD report only warnings/errors containing WORD
66 literally
67 -h, --help, --version display this help and exit
68
69 When FILE is - read standard input.
70 EOM
71
72 exit($exitcode);
73 }
74
75 GetOptions(
76 'q|quiet+' => \$quiet,
77 'tree!' => \$tree,
78 'signoff!' => \$chk_signoff,
79 'patch!' => \$chk_patch,
80 'branch!' => \$chk_branch,
81 'emacs!' => \$emacs,
82 'terse!' => \$terse,
83 'f|file!' => \$file,
84 'strict!' => \$no_warnings,
85 'root=s' => \$root,
86 'summary!' => \$summary,
87 'mailback!' => \$mailback,
88 'summary-file!' => \$summary_file,
89
90 'debug=s' => \%debug,
91 'test-only=s' => \$tst_only,
92 'h|help' => \$help,
93 'version' => \$help
94 ) or help(1);
95
96 help(0) if ($help);
97
98 my $exit = 0;
99
100 if ($#ARGV < 0) {
101 print "$P: no input files\n";
102 exit(1);
103 }
104
105 if (!defined $chk_branch && !defined $chk_patch && !defined $file) {
106 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
107 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
108 $chk_patch = $chk_branch || $file ? 0 : 1;
109 } elsif (!defined $chk_branch && !defined $chk_patch) {
110 if ($file) {
111 $chk_branch = $chk_patch = 0;
112 } else {
113 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
114 $chk_patch = $chk_branch ? 0 : 1;
115 }
116 } elsif (!defined $chk_branch && !defined $file) {
117 if ($chk_patch) {
118 $chk_branch = $file = 0;
119 } else {
120 $chk_branch = $ARGV[0] =~ /.\.\./ ? 1 : 0;
121 $file = $chk_branch ? 0 : 1;
122 }
123 } elsif (!defined $chk_patch && !defined $file) {
124 if ($chk_branch) {
125 $chk_patch = $file = 0;
126 } else {
127 $file = $ARGV[0] =~ /$SrcFile/ ? 1 : 0;
128 $chk_patch = $file ? 0 : 1;
129 }
130 } elsif (!defined $chk_branch) {
131 $chk_branch = $chk_patch || $file ? 0 : 1;
132 } elsif (!defined $chk_patch) {
133 $chk_patch = $chk_branch || $file ? 0 : 1;
134 } elsif (!defined $file) {
135 $file = $chk_patch || $chk_branch ? 0 : 1;
136 }
137
138 if (($chk_patch && $chk_branch) ||
139 ($chk_patch && $file) ||
140 ($chk_branch && $file)) {
141 die "Only one of --file, --branch, --patch is permitted\n";
142 }
143 if (!$chk_patch && !$chk_branch && !$file) {
144 die "One of --file, --branch, --patch is required\n";
145 }
146
147 my $dbg_values = 0;
148 my $dbg_possible = 0;
149 my $dbg_type = 0;
150 my $dbg_attr = 0;
151 my $dbg_adv_dcs = 0;
152 my $dbg_adv_checking = 0;
153 my $dbg_adv_apw = 0;
154 for my $key (keys %debug) {
155 ## no critic
156 eval "\${dbg_$key} = '$debug{$key}';";
157 die "$@" if ($@);
158 }
159
160 my $rpt_cleaners = 0;
161
162 if ($terse) {
163 $emacs = 1;
164 $quiet++;
165 }
166
167 if ($tree) {
168 if (defined $root) {
169 if (!top_of_kernel_tree($root)) {
170 die "$P: $root: --root does not point at a valid tree\n";
171 }
172 } else {
173 if (top_of_kernel_tree('.')) {
174 $root = '.';
175 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
176 top_of_kernel_tree($1)) {
177 $root = $1;
178 }
179 }
180
181 if (!defined $root) {
182 print "Must be run from the top-level dir. of a kernel tree\n";
183 exit(2);
184 }
185 }
186
187 my $emitted_corrupt = 0;
188
189 our $Ident = qr{
190 [A-Za-z_][A-Za-z\d_]*
191 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
192 }x;
193 our $Storage = qr{extern|static|asmlinkage};
194 our $Sparse = qr{
195 __force
196 }x;
197
198 # Notes to $Attribute:
199 our $Attribute = qr{
200 const|
201 volatile|
202 QEMU_NORETURN|
203 QEMU_WARN_UNUSED_RESULT|
204 QEMU_SENTINEL|
205 QEMU_ARTIFICIAL|
206 QEMU_PACKED|
207 GCC_FMT_ATTR
208 }x;
209 our $Modifier;
210 our $Inline = qr{inline};
211 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
212 our $Lval = qr{$Ident(?:$Member)*};
213
214 our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
215 our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
216 our $Compare = qr{<=|>=|==|!=|<|>};
217 our $Operators = qr{
218 <=|>=|==|!=|
219 =>|->|<<|>>|<|>|!|~|
220 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
221 }x;
222
223 our $NonptrType;
224 our $Type;
225 our $Declare;
226
227 our $UTF8 = qr {
228 [\x09\x0A\x0D\x20-\x7E] # ASCII
229 | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
230 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
231 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
232 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
233 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
234 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
235 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
236 }x;
237
238 # There are still some false positives, but this catches most
239 # common cases.
240 our $typeTypedefs = qr{(?x:
241 [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]* # camelcase
242 | [A-Z][A-Z\d_]*AIOCB # all uppercase
243 | [A-Z][A-Z\d_]*CPU # all uppercase
244 | QEMUBH # all uppercase
245 )};
246
247 our @typeList = (
248 qr{void},
249 qr{(?:unsigned\s+)?char},
250 qr{(?:unsigned\s+)?short},
251 qr{(?:unsigned\s+)?int},
252 qr{(?:unsigned\s+)?long},
253 qr{(?:unsigned\s+)?long\s+int},
254 qr{(?:unsigned\s+)?long\s+long},
255 qr{(?:unsigned\s+)?long\s+long\s+int},
256 qr{unsigned},
257 qr{float},
258 qr{double},
259 qr{bool},
260 qr{struct\s+$Ident},
261 qr{union\s+$Ident},
262 qr{enum\s+$Ident},
263 qr{${Ident}_t},
264 qr{${Ident}_handler},
265 qr{${Ident}_handler_fn},
266 qr{target_(?:u)?long},
267 qr{hwaddr},
268 qr{xml${Ident}},
269 qr{xendevicemodel_handle},
270 );
271
272 # This can be modified by sub possible. Since it can be empty, be careful
273 # about regexes that always match, because they can cause infinite loops.
274 our @modifierList = (
275 );
276
277 sub build_types {
278 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
279 if (@modifierList > 0) {
280 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
281 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
282 } else {
283 $Modifier = qr{(?:$Attribute|$Sparse)};
284 }
285 $NonptrType = qr{
286 (?:$Modifier\s+|const\s+)*
287 (?:
288 (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
289 (?:$typeTypedefs\b)|
290 (?:${all}\b)
291 )
292 (?:\s+$Modifier|\s+const)*
293 }x;
294 $Type = qr{
295 $NonptrType
296 (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
297 (?:\s+$Inline|\s+$Modifier)*
298 }x;
299 $Declare = qr{(?:$Storage\s+)?$Type};
300 }
301 build_types();
302
303 $chk_signoff = 0 if ($file);
304
305 my @rawlines = ();
306 my @lines = ();
307 my $vname;
308 if ($chk_branch) {
309 my @patches;
310 my $HASH;
311 open($HASH, "-|", "git", "log", "--format=%H", $ARGV[0]) ||
312 die "$P: git log --format=%H $ARGV[0] failed - $!\n";
313
314 while (<$HASH>) {
315 chomp;
316 push @patches, $_;
317 }
318
319 close $HASH;
320
321 die "$P: no revisions returned for revlist '$chk_branch'\n"
322 unless @patches;
323
324 for my $hash (@patches) {
325 my $FILE;
326 open($FILE, '-|', "git", "show", $hash) ||
327 die "$P: git show $hash - $!\n";
328 $vname = $hash;
329 while (<$FILE>) {
330 chomp;
331 push(@rawlines, $_);
332 }
333 close($FILE);
334 if (!process($hash)) {
335 $exit = 1;
336 }
337 @rawlines = ();
338 @lines = ();
339 }
340 } else {
341 for my $filename (@ARGV) {
342 my $FILE;
343 if ($file) {
344 open($FILE, '-|', "diff -u /dev/null $filename") ||
345 die "$P: $filename: diff failed - $!\n";
346 } elsif ($filename eq '-') {
347 open($FILE, '<&STDIN');
348 } else {
349 open($FILE, '<', "$filename") ||
350 die "$P: $filename: open failed - $!\n";
351 }
352 if ($filename eq '-') {
353 $vname = 'Your patch';
354 } else {
355 $vname = $filename;
356 }
357 while (<$FILE>) {
358 chomp;
359 push(@rawlines, $_);
360 }
361 close($FILE);
362 if (!process($filename)) {
363 $exit = 1;
364 }
365 @rawlines = ();
366 @lines = ();
367 }
368 }
369
370 exit($exit);
371
372 sub top_of_kernel_tree {
373 my ($root) = @_;
374
375 my @tree_check = (
376 "COPYING", "MAINTAINERS", "Makefile",
377 "README", "docs", "VERSION",
378 "vl.c"
379 );
380
381 foreach my $check (@tree_check) {
382 if (! -e $root . '/' . $check) {
383 return 0;
384 }
385 }
386 return 1;
387 }
388
389 sub expand_tabs {
390 my ($str) = @_;
391
392 my $res = '';
393 my $n = 0;
394 for my $c (split(//, $str)) {
395 if ($c eq "\t") {
396 $res .= ' ';
397 $n++;
398 for (; ($n % 8) != 0; $n++) {
399 $res .= ' ';
400 }
401 next;
402 }
403 $res .= $c;
404 $n++;
405 }
406
407 return $res;
408 }
409 sub copy_spacing {
410 (my $res = shift) =~ tr/\t/ /c;
411 return $res;
412 }
413
414 sub line_stats {
415 my ($line) = @_;
416
417 # Drop the diff line leader and expand tabs
418 $line =~ s/^.//;
419 $line = expand_tabs($line);
420
421 # Pick the indent from the front of the line.
422 my ($white) = ($line =~ /^(\s*)/);
423
424 return (length($line), length($white));
425 }
426
427 my $sanitise_quote = '';
428
429 sub sanitise_line_reset {
430 my ($in_comment) = @_;
431
432 if ($in_comment) {
433 $sanitise_quote = '*/';
434 } else {
435 $sanitise_quote = '';
436 }
437 }
438 sub sanitise_line {
439 my ($line) = @_;
440
441 my $res = '';
442 my $l = '';
443
444 my $qlen = 0;
445 my $off = 0;
446 my $c;
447
448 # Always copy over the diff marker.
449 $res = substr($line, 0, 1);
450
451 for ($off = 1; $off < length($line); $off++) {
452 $c = substr($line, $off, 1);
453
454 # Comments we are wacking completely including the begin
455 # and end, all to $;.
456 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
457 $sanitise_quote = '*/';
458
459 substr($res, $off, 2, "$;$;");
460 $off++;
461 next;
462 }
463 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
464 $sanitise_quote = '';
465 substr($res, $off, 2, "$;$;");
466 $off++;
467 next;
468 }
469 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
470 $sanitise_quote = '//';
471
472 substr($res, $off, 2, $sanitise_quote);
473 $off++;
474 next;
475 }
476
477 # A \ in a string means ignore the next character.
478 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
479 $c eq "\\") {
480 substr($res, $off, 2, 'XX');
481 $off++;
482 next;
483 }
484 # Regular quotes.
485 if ($c eq "'" || $c eq '"') {
486 if ($sanitise_quote eq '') {
487 $sanitise_quote = $c;
488
489 substr($res, $off, 1, $c);
490 next;
491 } elsif ($sanitise_quote eq $c) {
492 $sanitise_quote = '';
493 }
494 }
495
496 #print "c<$c> SQ<$sanitise_quote>\n";
497 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
498 substr($res, $off, 1, $;);
499 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
500 substr($res, $off, 1, $;);
501 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
502 substr($res, $off, 1, 'X');
503 } else {
504 substr($res, $off, 1, $c);
505 }
506 }
507
508 if ($sanitise_quote eq '//') {
509 $sanitise_quote = '';
510 }
511
512 # The pathname on a #include may be surrounded by '<' and '>'.
513 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
514 my $clean = 'X' x length($1);
515 $res =~ s@\<.*\>@<$clean>@;
516
517 # The whole of a #error is a string.
518 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
519 my $clean = 'X' x length($1);
520 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
521 }
522
523 return $res;
524 }
525
526 sub ctx_statement_block {
527 my ($linenr, $remain, $off) = @_;
528 my $line = $linenr - 1;
529 my $blk = '';
530 my $soff = $off;
531 my $coff = $off - 1;
532 my $coff_set = 0;
533
534 my $loff = 0;
535
536 my $type = '';
537 my $level = 0;
538 my @stack = ();
539 my $p;
540 my $c;
541 my $len = 0;
542
543 my $remainder;
544 while (1) {
545 @stack = (['', 0]) if ($#stack == -1);
546
547 #warn "CSB: blk<$blk> remain<$remain>\n";
548 # If we are about to drop off the end, pull in more
549 # context.
550 if ($off >= $len) {
551 for (; $remain > 0; $line++) {
552 last if (!defined $lines[$line]);
553 next if ($lines[$line] =~ /^-/);
554 $remain--;
555 $loff = $len;
556 $blk .= $lines[$line] . "\n";
557 $len = length($blk);
558 $line++;
559 last;
560 }
561 # Bail if there is no further context.
562 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
563 if ($off >= $len) {
564 last;
565 }
566 }
567 $p = $c;
568 $c = substr($blk, $off, 1);
569 $remainder = substr($blk, $off);
570
571 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
572
573 # Handle nested #if/#else.
574 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
575 push(@stack, [ $type, $level ]);
576 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
577 ($type, $level) = @{$stack[$#stack - 1]};
578 } elsif ($remainder =~ /^#\s*endif\b/) {
579 ($type, $level) = @{pop(@stack)};
580 }
581
582 # Statement ends at the ';' or a close '}' at the
583 # outermost level.
584 if ($level == 0 && $c eq ';') {
585 last;
586 }
587
588 # An else is really a conditional as long as its not else if
589 if ($level == 0 && $coff_set == 0 &&
590 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
591 $remainder =~ /^(else)(?:\s|{)/ &&
592 $remainder !~ /^else\s+if\b/) {
593 $coff = $off + length($1) - 1;
594 $coff_set = 1;
595 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
596 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
597 }
598
599 if (($type eq '' || $type eq '(') && $c eq '(') {
600 $level++;
601 $type = '(';
602 }
603 if ($type eq '(' && $c eq ')') {
604 $level--;
605 $type = ($level != 0)? '(' : '';
606
607 if ($level == 0 && $coff < $soff) {
608 $coff = $off;
609 $coff_set = 1;
610 #warn "CSB: mark coff<$coff>\n";
611 }
612 }
613 if (($type eq '' || $type eq '{') && $c eq '{') {
614 $level++;
615 $type = '{';
616 }
617 if ($type eq '{' && $c eq '}') {
618 $level--;
619 $type = ($level != 0)? '{' : '';
620
621 if ($level == 0) {
622 if (substr($blk, $off + 1, 1) eq ';') {
623 $off++;
624 }
625 last;
626 }
627 }
628 $off++;
629 }
630 # We are truly at the end, so shuffle to the next line.
631 if ($off == $len) {
632 $loff = $len + 1;
633 $line++;
634 $remain--;
635 }
636
637 my $statement = substr($blk, $soff, $off - $soff + 1);
638 my $condition = substr($blk, $soff, $coff - $soff + 1);
639
640 #warn "STATEMENT<$statement>\n";
641 #warn "CONDITION<$condition>\n";
642
643 #print "coff<$coff> soff<$off> loff<$loff>\n";
644
645 return ($statement, $condition,
646 $line, $remain + 1, $off - $loff + 1, $level);
647 }
648
649 sub statement_lines {
650 my ($stmt) = @_;
651
652 # Strip the diff line prefixes and rip blank lines at start and end.
653 $stmt =~ s/(^|\n)./$1/g;
654 $stmt =~ s/^\s*//;
655 $stmt =~ s/\s*$//;
656
657 my @stmt_lines = ($stmt =~ /\n/g);
658
659 return $#stmt_lines + 2;
660 }
661
662 sub statement_rawlines {
663 my ($stmt) = @_;
664
665 my @stmt_lines = ($stmt =~ /\n/g);
666
667 return $#stmt_lines + 2;
668 }
669
670 sub statement_block_size {
671 my ($stmt) = @_;
672
673 $stmt =~ s/(^|\n)./$1/g;
674 $stmt =~ s/^\s*\{//;
675 $stmt =~ s/}\s*$//;
676 $stmt =~ s/^\s*//;
677 $stmt =~ s/\s*$//;
678
679 my @stmt_lines = ($stmt =~ /\n/g);
680 my @stmt_statements = ($stmt =~ /;/g);
681
682 my $stmt_lines = $#stmt_lines + 2;
683 my $stmt_statements = $#stmt_statements + 1;
684
685 if ($stmt_lines > $stmt_statements) {
686 return $stmt_lines;
687 } else {
688 return $stmt_statements;
689 }
690 }
691
692 sub ctx_statement_full {
693 my ($linenr, $remain, $off) = @_;
694 my ($statement, $condition, $level);
695
696 my (@chunks);
697
698 # Grab the first conditional/block pair.
699 ($statement, $condition, $linenr, $remain, $off, $level) =
700 ctx_statement_block($linenr, $remain, $off);
701 #print "F: c<$condition> s<$statement> remain<$remain>\n";
702 push(@chunks, [ $condition, $statement ]);
703 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
704 return ($level, $linenr, @chunks);
705 }
706
707 # Pull in the following conditional/block pairs and see if they
708 # could continue the statement.
709 for (;;) {
710 ($statement, $condition, $linenr, $remain, $off, $level) =
711 ctx_statement_block($linenr, $remain, $off);
712 #print "C: c<$condition> s<$statement> remain<$remain>\n";
713 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
714 #print "C: push\n";
715 push(@chunks, [ $condition, $statement ]);
716 }
717
718 return ($level, $linenr, @chunks);
719 }
720
721 sub ctx_block_get {
722 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
723 my $line;
724 my $start = $linenr - 1;
725 my $blk = '';
726 my @o;
727 my @c;
728 my @res = ();
729
730 my $level = 0;
731 my @stack = ($level);
732 for ($line = $start; $remain > 0; $line++) {
733 next if ($rawlines[$line] =~ /^-/);
734 $remain--;
735
736 $blk .= $rawlines[$line];
737
738 # Handle nested #if/#else.
739 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
740 push(@stack, $level);
741 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
742 $level = $stack[$#stack - 1];
743 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
744 $level = pop(@stack);
745 }
746
747 foreach my $c (split(//, $lines[$line])) {
748 ##print "C<$c>L<$level><$open$close>O<$off>\n";
749 if ($off > 0) {
750 $off--;
751 next;
752 }
753
754 if ($c eq $close && $level > 0) {
755 $level--;
756 last if ($level == 0);
757 } elsif ($c eq $open) {
758 $level++;
759 }
760 }
761
762 if (!$outer || $level <= 1) {
763 push(@res, $rawlines[$line]);
764 }
765
766 last if ($level == 0);
767 }
768
769 return ($level, @res);
770 }
771 sub ctx_block_outer {
772 my ($linenr, $remain) = @_;
773
774 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
775 return @r;
776 }
777 sub ctx_block {
778 my ($linenr, $remain) = @_;
779
780 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
781 return @r;
782 }
783 sub ctx_statement {
784 my ($linenr, $remain, $off) = @_;
785
786 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
787 return @r;
788 }
789 sub ctx_block_level {
790 my ($linenr, $remain) = @_;
791
792 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
793 }
794 sub ctx_statement_level {
795 my ($linenr, $remain, $off) = @_;
796
797 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
798 }
799
800 sub ctx_locate_comment {
801 my ($first_line, $end_line) = @_;
802
803 # Catch a comment on the end of the line itself.
804 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
805 return $current_comment if (defined $current_comment);
806
807 # Look through the context and try and figure out if there is a
808 # comment.
809 my $in_comment = 0;
810 $current_comment = '';
811 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
812 my $line = $rawlines[$linenr - 1];
813 #warn " $line\n";
814 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
815 $in_comment = 1;
816 }
817 if ($line =~ m@/\*@) {
818 $in_comment = 1;
819 }
820 if (!$in_comment && $current_comment ne '') {
821 $current_comment = '';
822 }
823 $current_comment .= $line . "\n" if ($in_comment);
824 if ($line =~ m@\*/@) {
825 $in_comment = 0;
826 }
827 }
828
829 chomp($current_comment);
830 return($current_comment);
831 }
832 sub ctx_has_comment {
833 my ($first_line, $end_line) = @_;
834 my $cmt = ctx_locate_comment($first_line, $end_line);
835
836 ##print "LINE: $rawlines[$end_line - 1 ]\n";
837 ##print "CMMT: $cmt\n";
838
839 return ($cmt ne '');
840 }
841
842 sub raw_line {
843 my ($linenr, $cnt) = @_;
844
845 my $offset = $linenr - 1;
846 $cnt++;
847
848 my $line;
849 while ($cnt) {
850 $line = $rawlines[$offset++];
851 next if (defined($line) && $line =~ /^-/);
852 $cnt--;
853 }
854
855 return $line;
856 }
857
858 sub cat_vet {
859 my ($vet) = @_;
860 my ($res, $coded);
861
862 $res = '';
863 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
864 $res .= $1;
865 if ($2 ne '') {
866 $coded = sprintf("^%c", unpack('C', $2) + 64);
867 $res .= $coded;
868 }
869 }
870 $res =~ s/$/\$/;
871
872 return $res;
873 }
874
875 my $av_preprocessor = 0;
876 my $av_pending;
877 my @av_paren_type;
878 my $av_pend_colon;
879
880 sub annotate_reset {
881 $av_preprocessor = 0;
882 $av_pending = '_';
883 @av_paren_type = ('E');
884 $av_pend_colon = 'O';
885 }
886
887 sub annotate_values {
888 my ($stream, $type) = @_;
889
890 my $res;
891 my $var = '_' x length($stream);
892 my $cur = $stream;
893
894 print "$stream\n" if ($dbg_values > 1);
895
896 while (length($cur)) {
897 @av_paren_type = ('E') if ($#av_paren_type < 0);
898 print " <" . join('', @av_paren_type) .
899 "> <$type> <$av_pending>" if ($dbg_values > 1);
900 if ($cur =~ /^(\s+)/o) {
901 print "WS($1)\n" if ($dbg_values > 1);
902 if ($1 =~ /\n/ && $av_preprocessor) {
903 $type = pop(@av_paren_type);
904 $av_preprocessor = 0;
905 }
906
907 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
908 print "CAST($1)\n" if ($dbg_values > 1);
909 push(@av_paren_type, $type);
910 $type = 'C';
911
912 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
913 print "DECLARE($1)\n" if ($dbg_values > 1);
914 $type = 'T';
915
916 } elsif ($cur =~ /^($Modifier)\s*/) {
917 print "MODIFIER($1)\n" if ($dbg_values > 1);
918 $type = 'T';
919
920 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
921 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
922 $av_preprocessor = 1;
923 push(@av_paren_type, $type);
924 if ($2 ne '') {
925 $av_pending = 'N';
926 }
927 $type = 'E';
928
929 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
930 print "UNDEF($1)\n" if ($dbg_values > 1);
931 $av_preprocessor = 1;
932 push(@av_paren_type, $type);
933
934 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
935 print "PRE_START($1)\n" if ($dbg_values > 1);
936 $av_preprocessor = 1;
937
938 push(@av_paren_type, $type);
939 push(@av_paren_type, $type);
940 $type = 'E';
941
942 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
943 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
944 $av_preprocessor = 1;
945
946 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
947
948 $type = 'E';
949
950 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
951 print "PRE_END($1)\n" if ($dbg_values > 1);
952
953 $av_preprocessor = 1;
954
955 # Assume all arms of the conditional end as this
956 # one does, and continue as if the #endif was not here.
957 pop(@av_paren_type);
958 push(@av_paren_type, $type);
959 $type = 'E';
960
961 } elsif ($cur =~ /^(\\\n)/o) {
962 print "PRECONT($1)\n" if ($dbg_values > 1);
963
964 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
965 print "ATTR($1)\n" if ($dbg_values > 1);
966 $av_pending = $type;
967 $type = 'N';
968
969 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
970 print "SIZEOF($1)\n" if ($dbg_values > 1);
971 if (defined $2) {
972 $av_pending = 'V';
973 }
974 $type = 'N';
975
976 } elsif ($cur =~ /^(if|while|for)\b/o) {
977 print "COND($1)\n" if ($dbg_values > 1);
978 $av_pending = 'E';
979 $type = 'N';
980
981 } elsif ($cur =~/^(case)/o) {
982 print "CASE($1)\n" if ($dbg_values > 1);
983 $av_pend_colon = 'C';
984 $type = 'N';
985
986 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
987 print "KEYWORD($1)\n" if ($dbg_values > 1);
988 $type = 'N';
989
990 } elsif ($cur =~ /^(\()/o) {
991 print "PAREN('$1')\n" if ($dbg_values > 1);
992 push(@av_paren_type, $av_pending);
993 $av_pending = '_';
994 $type = 'N';
995
996 } elsif ($cur =~ /^(\))/o) {
997 my $new_type = pop(@av_paren_type);
998 if ($new_type ne '_') {
999 $type = $new_type;
1000 print "PAREN('$1') -> $type\n"
1001 if ($dbg_values > 1);
1002 } else {
1003 print "PAREN('$1')\n" if ($dbg_values > 1);
1004 }
1005
1006 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1007 print "FUNC($1)\n" if ($dbg_values > 1);
1008 $type = 'V';
1009 $av_pending = 'V';
1010
1011 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1012 if (defined $2 && $type eq 'C' || $type eq 'T') {
1013 $av_pend_colon = 'B';
1014 } elsif ($type eq 'E') {
1015 $av_pend_colon = 'L';
1016 }
1017 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1018 $type = 'V';
1019
1020 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1021 print "IDENT($1)\n" if ($dbg_values > 1);
1022 $type = 'V';
1023
1024 } elsif ($cur =~ /^($Assignment)/o) {
1025 print "ASSIGN($1)\n" if ($dbg_values > 1);
1026 $type = 'N';
1027
1028 } elsif ($cur =~/^(;|{|})/) {
1029 print "END($1)\n" if ($dbg_values > 1);
1030 $type = 'E';
1031 $av_pend_colon = 'O';
1032
1033 } elsif ($cur =~/^(,)/) {
1034 print "COMMA($1)\n" if ($dbg_values > 1);
1035 $type = 'C';
1036
1037 } elsif ($cur =~ /^(\?)/o) {
1038 print "QUESTION($1)\n" if ($dbg_values > 1);
1039 $type = 'N';
1040
1041 } elsif ($cur =~ /^(:)/o) {
1042 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1043
1044 substr($var, length($res), 1, $av_pend_colon);
1045 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1046 $type = 'E';
1047 } else {
1048 $type = 'N';
1049 }
1050 $av_pend_colon = 'O';
1051
1052 } elsif ($cur =~ /^(\[)/o) {
1053 print "CLOSE($1)\n" if ($dbg_values > 1);
1054 $type = 'N';
1055
1056 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1057 my $variant;
1058
1059 print "OPV($1)\n" if ($dbg_values > 1);
1060 if ($type eq 'V') {
1061 $variant = 'B';
1062 } else {
1063 $variant = 'U';
1064 }
1065
1066 substr($var, length($res), 1, $variant);
1067 $type = 'N';
1068
1069 } elsif ($cur =~ /^($Operators)/o) {
1070 print "OP($1)\n" if ($dbg_values > 1);
1071 if ($1 ne '++' && $1 ne '--') {
1072 $type = 'N';
1073 }
1074
1075 } elsif ($cur =~ /(^.)/o) {
1076 print "C($1)\n" if ($dbg_values > 1);
1077 }
1078 if (defined $1) {
1079 $cur = substr($cur, length($1));
1080 $res .= $type x length($1);
1081 }
1082 }
1083
1084 return ($res, $var);
1085 }
1086
1087 sub possible {
1088 my ($possible, $line) = @_;
1089 my $notPermitted = qr{(?:
1090 ^(?:
1091 $Modifier|
1092 $Storage|
1093 $Type|
1094 DEFINE_\S+
1095 )$|
1096 ^(?:
1097 goto|
1098 return|
1099 case|
1100 else|
1101 asm|__asm__|
1102 do|
1103 \#|
1104 \#\#
1105 )(?:\s|$)|
1106 ^(?:typedef|struct|enum)\b
1107 )}x;
1108 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1109 if ($possible !~ $notPermitted) {
1110 # Check for modifiers.
1111 $possible =~ s/\s*$Storage\s*//g;
1112 $possible =~ s/\s*$Sparse\s*//g;
1113 if ($possible =~ /^\s*$/) {
1114
1115 } elsif ($possible =~ /\s/) {
1116 $possible =~ s/\s*$Type\s*//g;
1117 for my $modifier (split(' ', $possible)) {
1118 if ($modifier !~ $notPermitted) {
1119 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1120 push(@modifierList, $modifier);
1121 }
1122 }
1123
1124 } else {
1125 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1126 push(@typeList, $possible);
1127 }
1128 build_types();
1129 } else {
1130 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1131 }
1132 }
1133
1134 my $prefix = '';
1135
1136 sub report {
1137 if (defined $tst_only && $_[0] !~ /\Q$tst_only\E/) {
1138 return 0;
1139 }
1140 my $line = $prefix . $_[0];
1141
1142 $line = (split('\n', $line))[0] . "\n" if ($terse);
1143
1144 push(our @report, $line);
1145
1146 return 1;
1147 }
1148 sub report_dump {
1149 our @report;
1150 }
1151 sub ERROR {
1152 if (report("ERROR: $_[0]\n")) {
1153 our $clean = 0;
1154 our $cnt_error++;
1155 }
1156 }
1157 sub WARN {
1158 if (report("WARNING: $_[0]\n")) {
1159 our $clean = 0;
1160 our $cnt_warn++;
1161 }
1162 }
1163
1164 sub process {
1165 my $filename = shift;
1166
1167 my $linenr=0;
1168 my $prevline="";
1169 my $prevrawline="";
1170 my $stashline="";
1171 my $stashrawline="";
1172
1173 my $length;
1174 my $indent;
1175 my $previndent=0;
1176 my $stashindent=0;
1177
1178 our $clean = 1;
1179 my $signoff = 0;
1180 my $is_patch = 0;
1181
1182 our @report = ();
1183 our $cnt_lines = 0;
1184 our $cnt_error = 0;
1185 our $cnt_warn = 0;
1186 our $cnt_chk = 0;
1187
1188 # Trace the real file/line as we go.
1189 my $realfile = '';
1190 my $realline = 0;
1191 my $realcnt = 0;
1192 my $here = '';
1193 my $in_comment = 0;
1194 my $comment_edge = 0;
1195 my $first_line = 0;
1196 my $p1_prefix = '';
1197
1198 my $prev_values = 'E';
1199
1200 # suppression flags
1201 my %suppress_ifbraces;
1202 my %suppress_whiletrailers;
1203 my %suppress_export;
1204
1205 # Pre-scan the patch sanitizing the lines.
1206
1207 sanitise_line_reset();
1208 my $line;
1209 foreach my $rawline (@rawlines) {
1210 $linenr++;
1211 $line = $rawline;
1212
1213 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1214 $realline=$1-1;
1215 if (defined $2) {
1216 $realcnt=$3+1;
1217 } else {
1218 $realcnt=1+1;
1219 }
1220 $in_comment = 0;
1221
1222 # Guestimate if this is a continuing comment. Run
1223 # the context looking for a comment "edge". If this
1224 # edge is a close comment then we must be in a comment
1225 # at context start.
1226 my $edge;
1227 my $cnt = $realcnt;
1228 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1229 next if (defined $rawlines[$ln - 1] &&
1230 $rawlines[$ln - 1] =~ /^-/);
1231 $cnt--;
1232 #print "RAW<$rawlines[$ln - 1]>\n";
1233 last if (!defined $rawlines[$ln - 1]);
1234 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1235 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1236 ($edge) = $1;
1237 last;
1238 }
1239 }
1240 if (defined $edge && $edge eq '*/') {
1241 $in_comment = 1;
1242 }
1243
1244 # Guestimate if this is a continuing comment. If this
1245 # is the start of a diff block and this line starts
1246 # ' *' then it is very likely a comment.
1247 if (!defined $edge &&
1248 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1249 {
1250 $in_comment = 1;
1251 }
1252
1253 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1254 sanitise_line_reset($in_comment);
1255
1256 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1257 # Standardise the strings and chars within the input to
1258 # simplify matching -- only bother with positive lines.
1259 $line = sanitise_line($rawline);
1260 }
1261 push(@lines, $line);
1262
1263 if ($realcnt > 1) {
1264 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1265 } else {
1266 $realcnt = 0;
1267 }
1268
1269 #print "==>$rawline\n";
1270 #print "-->$line\n";
1271 }
1272
1273 $prefix = '';
1274
1275 $realcnt = 0;
1276 $linenr = 0;
1277 foreach my $line (@lines) {
1278 $linenr++;
1279
1280 my $rawline = $rawlines[$linenr - 1];
1281
1282 #extract the line range in the file after the patch is applied
1283 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1284 $is_patch = 1;
1285 $first_line = $linenr + 1;
1286 $realline=$1-1;
1287 if (defined $2) {
1288 $realcnt=$3+1;
1289 } else {
1290 $realcnt=1+1;
1291 }
1292 annotate_reset();
1293 $prev_values = 'E';
1294
1295 %suppress_ifbraces = ();
1296 %suppress_whiletrailers = ();
1297 %suppress_export = ();
1298 next;
1299
1300 # track the line number as we move through the hunk, note that
1301 # new versions of GNU diff omit the leading space on completely
1302 # blank context lines so we need to count that too.
1303 } elsif ($line =~ /^( |\+|$)/) {
1304 $realline++;
1305 $realcnt-- if ($realcnt != 0);
1306
1307 # Measure the line length and indent.
1308 ($length, $indent) = line_stats($rawline);
1309
1310 # Track the previous line.
1311 ($prevline, $stashline) = ($stashline, $line);
1312 ($previndent, $stashindent) = ($stashindent, $indent);
1313 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1314
1315 #warn "line<$line>\n";
1316
1317 } elsif ($realcnt == 1) {
1318 $realcnt--;
1319 }
1320
1321 my $hunk_line = ($realcnt != 0);
1322
1323 #make up the handle for any error we report on this line
1324 $prefix = "$filename:$realline: " if ($emacs && $file);
1325 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1326
1327 $here = "#$linenr: " if (!$file);
1328 $here = "#$realline: " if ($file);
1329
1330 # extract the filename as it passes
1331 if ($line =~ /^diff --git.*?(\S+)$/) {
1332 $realfile = $1;
1333 $realfile =~ s@^([^/]*)/@@;
1334
1335 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1336 $realfile = $1;
1337 $realfile =~ s@^([^/]*)/@@;
1338
1339 $p1_prefix = $1;
1340 if (!$file && $tree && $p1_prefix ne '' &&
1341 -e "$root/$p1_prefix") {
1342 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1343 }
1344
1345 next;
1346 }
1347
1348 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1349
1350 my $hereline = "$here\n$rawline\n";
1351 my $herecurr = "$here\n$rawline\n";
1352 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1353
1354 $cnt_lines++ if ($realcnt != 0);
1355
1356 # Check for incorrect file permissions
1357 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1358 my $permhere = $here . "FILE: $realfile\n";
1359 if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1360 ERROR("do not set execute permissions for source files\n" . $permhere);
1361 }
1362 }
1363
1364 # Accept git diff extended headers as valid patches
1365 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1366 $is_patch = 1;
1367 }
1368
1369 #check the patch for a signoff:
1370 if ($line =~ /^\s*signed-off-by:/i) {
1371 # This is a signoff, if ugly, so do not double report.
1372 $signoff++;
1373 if (!($line =~ /^\s*Signed-off-by:/)) {
1374 ERROR("The correct form is \"Signed-off-by\"\n" .
1375 $herecurr);
1376 }
1377 if ($line =~ /^\s*signed-off-by:\S/i) {
1378 ERROR("space required after Signed-off-by:\n" .
1379 $herecurr);
1380 }
1381 }
1382
1383 # Check for wrappage within a valid hunk of the file
1384 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1385 ERROR("patch seems to be corrupt (line wrapped?)\n" .
1386 $herecurr) if (!$emitted_corrupt++);
1387 }
1388
1389 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1390 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1391 $rawline !~ m/^$UTF8*$/) {
1392 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1393
1394 my $blank = copy_spacing($rawline);
1395 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1396 my $hereptr = "$hereline$ptr\n";
1397
1398 ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1399 }
1400
1401 # ignore non-hunk lines and lines being removed
1402 next if (!$hunk_line || $line =~ /^-/);
1403
1404 # ignore files that are being periodically imported from Linux
1405 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1406
1407 #trailing whitespace
1408 if ($line =~ /^\+.*\015/) {
1409 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1410 ERROR("DOS line endings\n" . $herevet);
1411
1412 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1413 $realfile =~ /^docs\/.+\.md/) {
1414 if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1415 # TODO: properly check we're in a code block
1416 # (surrounding text is 4-column aligned)
1417 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1418 ERROR("code blocks in documentation should have " .
1419 "empty lines with exactly 4 columns of " .
1420 "whitespace\n" . $herevet);
1421 }
1422 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1423 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1424 ERROR("trailing whitespace\n" . $herevet);
1425 $rpt_cleaners = 1;
1426 }
1427
1428 # checks for trace-events files
1429 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1430 if ($rawline =~ /%[-+ 0]*#/) {
1431 ERROR("Don't use '#' flag of printf format ('%#') in " .
1432 "trace-events, use '0x' prefix instead\n" . $herecurr);
1433 } else {
1434 my $hex =
1435 qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1436
1437 # don't consider groups splitted by [.:/ ], like 2A.20:12ab
1438 my $tmpline = $rawline;
1439 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1440
1441 if ($tmpline =~ /(?<!0x)$hex/) {
1442 ERROR("Hex numbers must be prefixed with '0x'\n" .
1443 $herecurr);
1444 }
1445 }
1446 }
1447
1448 # check we are in a valid source file if not then ignore this hunk
1449 next if ($realfile !~ /$SrcFile/);
1450
1451 #90 column limit; exempt URLs, if no other words on line
1452 if ($line =~ /^\+/ &&
1453 !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1454 !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1455 $length > 80)
1456 {
1457 if ($length > 90) {
1458 ERROR("line over 90 characters\n" . $herecurr);
1459 } else {
1460 WARN("line over 80 characters\n" . $herecurr);
1461 }
1462 }
1463
1464 # check for spaces before a quoted newline
1465 if ($rawline =~ /^.*\".*\s\\n/) {
1466 ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1467 }
1468
1469 # check for adding lines without a newline.
1470 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1471 ERROR("adding a line without newline at end of file\n" . $herecurr);
1472 }
1473
1474 # check for RCS/CVS revision markers
1475 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1476 ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1477 }
1478
1479 # tabs are only allowed in assembly source code, and in
1480 # some scripts we imported from other projects.
1481 next if ($realfile =~ /\.(s|S)$/);
1482 next if ($realfile =~ /(checkpatch|get_maintainer|texi2pod)\.pl$/);
1483
1484 if ($rawline =~ /^\+.*\t/) {
1485 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1486 ERROR("code indent should never use tabs\n" . $herevet);
1487 $rpt_cleaners = 1;
1488 }
1489
1490 # check we are in a valid C source file if not then ignore this hunk
1491 next if ($realfile !~ /\.(h|c|cpp)$/);
1492
1493 # Check for potential 'bare' types
1494 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1495 $realline_next);
1496 if ($realcnt && $line =~ /.\s*\S/) {
1497 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1498 ctx_statement_block($linenr, $realcnt, 0);
1499 $stat =~ s/\n./\n /g;
1500 $cond =~ s/\n./\n /g;
1501
1502 # Find the real next line.
1503 $realline_next = $line_nr_next;
1504 if (defined $realline_next &&
1505 (!defined $lines[$realline_next - 1] ||
1506 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1507 $realline_next++;
1508 }
1509
1510 my $s = $stat;
1511 $s =~ s/{.*$//s;
1512
1513 # Ignore goto labels.
1514 if ($s =~ /$Ident:\*$/s) {
1515
1516 # Ignore functions being called
1517 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1518
1519 } elsif ($s =~ /^.\s*else\b/s) {
1520
1521 # declarations always start with types
1522 } 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) {
1523 my $type = $1;
1524 $type =~ s/\s+/ /g;
1525 possible($type, "A:" . $s);
1526
1527 # definitions in global scope can only start with types
1528 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1529 possible($1, "B:" . $s);
1530 }
1531
1532 # any (foo ... *) is a pointer cast, and foo is a type
1533 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1534 possible($1, "C:" . $s);
1535 }
1536
1537 # Check for any sort of function declaration.
1538 # int foo(something bar, other baz);
1539 # void (*store_gdt)(x86_descr_ptr *);
1540 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1541 my ($name_len) = length($1);
1542
1543 my $ctx = $s;
1544 substr($ctx, 0, $name_len + 1, '');
1545 $ctx =~ s/\)[^\)]*$//;
1546
1547 for my $arg (split(/\s*,\s*/, $ctx)) {
1548 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1549
1550 possible($1, "D:" . $s);
1551 }
1552 }
1553 }
1554
1555 }
1556
1557 #
1558 # Checks which may be anchored in the context.
1559 #
1560
1561 # Check for switch () and associated case and default
1562 # statements should be at the same indent.
1563 if ($line=~/\bswitch\s*\(.*\)/) {
1564 my $err = '';
1565 my $sep = '';
1566 my @ctx = ctx_block_outer($linenr, $realcnt);
1567 shift(@ctx);
1568 for my $ctx (@ctx) {
1569 my ($clen, $cindent) = line_stats($ctx);
1570 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1571 $indent != $cindent) {
1572 $err .= "$sep$ctx\n";
1573 $sep = '';
1574 } else {
1575 $sep = "[...]\n";
1576 }
1577 }
1578 if ($err ne '') {
1579 ERROR("switch and case should be at the same indent\n$hereline$err");
1580 }
1581 }
1582
1583 # if/while/etc brace do not go on next line, unless defining a do while loop,
1584 # or if that brace on the next line is for something else
1585 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1586 my $pre_ctx = "$1$2";
1587
1588 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1589 my $ctx_cnt = $realcnt - $#ctx - 1;
1590 my $ctx = join("\n", @ctx);
1591
1592 my $ctx_ln = $linenr;
1593 my $ctx_skip = $realcnt;
1594
1595 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1596 defined $lines[$ctx_ln - 1] &&
1597 $lines[$ctx_ln - 1] =~ /^-/)) {
1598 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1599 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1600 $ctx_ln++;
1601 }
1602
1603 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1604 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1605
1606 # The length of the "previous line" is checked against 80 because it
1607 # includes the + at the beginning of the line (if the actual line has
1608 # 79 or 80 characters, it is no longer possible to add a space and an
1609 # opening brace there)
1610 if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1611 defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1612 defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1613 ERROR("that open brace { should be on the previous line\n" .
1614 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1615 }
1616 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1617 $ctx =~ /\)\s*\;\s*$/ &&
1618 defined $lines[$ctx_ln - 1])
1619 {
1620 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1621 if ($nindent > $indent) {
1622 ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1623 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1624 }
1625 }
1626 }
1627
1628 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1629 if ($line =~ /while\s*\((0|false)\);/) {
1630 ERROR("suspicious ; after while (0)\n" . $herecurr);
1631 }
1632
1633 # Check relative indent for conditionals and blocks.
1634 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1635 my ($s, $c) = ($stat, $cond);
1636
1637 substr($s, 0, length($c), '');
1638
1639 # Make sure we remove the line prefixes as we have
1640 # none on the first line, and are going to readd them
1641 # where necessary.
1642 $s =~ s/\n./\n/gs;
1643
1644 # Find out how long the conditional actually is.
1645 my @newlines = ($c =~ /\n/gs);
1646 my $cond_lines = 1 + $#newlines;
1647
1648 # We want to check the first line inside the block
1649 # starting at the end of the conditional, so remove:
1650 # 1) any blank line termination
1651 # 2) any opening brace { on end of the line
1652 # 3) any do (...) {
1653 my $continuation = 0;
1654 my $check = 0;
1655 $s =~ s/^.*\bdo\b//;
1656 $s =~ s/^\s*\{//;
1657 if ($s =~ s/^\s*\\//) {
1658 $continuation = 1;
1659 }
1660 if ($s =~ s/^\s*?\n//) {
1661 $check = 1;
1662 $cond_lines++;
1663 }
1664
1665 # Also ignore a loop construct at the end of a
1666 # preprocessor statement.
1667 if (($prevline =~ /^.\s*#\s*define\s/ ||
1668 $prevline =~ /\\\s*$/) && $continuation == 0) {
1669 $check = 0;
1670 }
1671
1672 my $cond_ptr = -1;
1673 $continuation = 0;
1674 while ($cond_ptr != $cond_lines) {
1675 $cond_ptr = $cond_lines;
1676
1677 # If we see an #else/#elif then the code
1678 # is not linear.
1679 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1680 $check = 0;
1681 }
1682
1683 # Ignore:
1684 # 1) blank lines, they should be at 0,
1685 # 2) preprocessor lines, and
1686 # 3) labels.
1687 if ($continuation ||
1688 $s =~ /^\s*?\n/ ||
1689 $s =~ /^\s*#\s*?/ ||
1690 $s =~ /^\s*$Ident\s*:/) {
1691 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1692 if ($s =~ s/^.*?\n//) {
1693 $cond_lines++;
1694 }
1695 }
1696 }
1697
1698 my (undef, $sindent) = line_stats("+" . $s);
1699 my $stat_real = raw_line($linenr, $cond_lines);
1700
1701 # Check if either of these lines are modified, else
1702 # this is not this patch's fault.
1703 if (!defined($stat_real) ||
1704 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1705 $check = 0;
1706 }
1707 if (defined($stat_real) && $cond_lines > 1) {
1708 $stat_real = "[...]\n$stat_real";
1709 }
1710
1711 #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";
1712
1713 if ($check && (($sindent % 4) != 0 ||
1714 ($sindent <= $indent && $s ne ''))) {
1715 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1716 }
1717 }
1718
1719 # Track the 'values' across context and added lines.
1720 my $opline = $line; $opline =~ s/^./ /;
1721 my ($curr_values, $curr_vars) =
1722 annotate_values($opline . "\n", $prev_values);
1723 $curr_values = $prev_values . $curr_values;
1724 if ($dbg_values) {
1725 my $outline = $opline; $outline =~ s/\t/ /g;
1726 print "$linenr > .$outline\n";
1727 print "$linenr > $curr_values\n";
1728 print "$linenr > $curr_vars\n";
1729 }
1730 $prev_values = substr($curr_values, -1);
1731
1732 #ignore lines not being added
1733 if ($line=~/^[^\+]/) {next;}
1734
1735 # TEST: allow direct testing of the type matcher.
1736 if ($dbg_type) {
1737 if ($line =~ /^.\s*$Declare\s*$/) {
1738 ERROR("TEST: is type\n" . $herecurr);
1739 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1740 ERROR("TEST: is not type ($1 is)\n". $herecurr);
1741 }
1742 next;
1743 }
1744 # TEST: allow direct testing of the attribute matcher.
1745 if ($dbg_attr) {
1746 if ($line =~ /^.\s*$Modifier\s*$/) {
1747 ERROR("TEST: is attr\n" . $herecurr);
1748 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1749 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1750 }
1751 next;
1752 }
1753
1754 # check for initialisation to aggregates open brace on the next line
1755 if ($line =~ /^.\s*\{/ &&
1756 $prevline =~ /(?:^|[^=])=\s*$/) {
1757 ERROR("that open brace { should be on the previous line\n" . $hereprev);
1758 }
1759
1760 #
1761 # Checks which are anchored on the added line.
1762 #
1763
1764 # check for malformed paths in #include statements (uses RAW line)
1765 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1766 my $path = $1;
1767 if ($path =~ m{//}) {
1768 ERROR("malformed #include filename\n" .
1769 $herecurr);
1770 }
1771 }
1772
1773 # no C99 // comments
1774 if ($line =~ m{//}) {
1775 ERROR("do not use C99 // comments\n" . $herecurr);
1776 }
1777 # Remove C99 comments.
1778 $line =~ s@//.*@@;
1779 $opline =~ s@//.*@@;
1780
1781 # check for global initialisers.
1782 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
1783 ERROR("do not initialise globals to 0 or NULL\n" .
1784 $herecurr);
1785 }
1786 # check for static initialisers.
1787 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
1788 ERROR("do not initialise statics to 0 or NULL\n" .
1789 $herecurr);
1790 }
1791
1792 # * goes on variable not on type
1793 # (char*[ const])
1794 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1795 my ($from, $to) = ($1, $1);
1796
1797 # Should start with a space.
1798 $to =~ s/^(\S)/ $1/;
1799 # Should not end with a space.
1800 $to =~ s/\s+$//;
1801 # '*'s should not have spaces between.
1802 while ($to =~ s/\*\s+\*/\*\*/) {
1803 }
1804
1805 #print "from<$from> to<$to>\n";
1806 if ($from ne $to) {
1807 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr);
1808 }
1809 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1810 my ($from, $to, $ident) = ($1, $1, $2);
1811
1812 # Should start with a space.
1813 $to =~ s/^(\S)/ $1/;
1814 # Should not end with a space.
1815 $to =~ s/\s+$//;
1816 # '*'s should not have spaces between.
1817 while ($to =~ s/\*\s+\*/\*\*/) {
1818 }
1819 # Modifiers should have spaces.
1820 $to =~ s/(\b$Modifier$)/$1 /;
1821
1822 #print "from<$from> to<$to> ident<$ident>\n";
1823 if ($from ne $to && $ident !~ /^$Modifier$/) {
1824 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr);
1825 }
1826 }
1827
1828 # function brace can't be on same line, except for #defines of do while,
1829 # or if closed on same line
1830 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
1831 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
1832 ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
1833 }
1834
1835 # open braces for enum, union and struct go on the same line.
1836 if ($line =~ /^.\s*\{/ &&
1837 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
1838 ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
1839 }
1840
1841 # missing space after union, struct or enum definition
1842 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
1843 ERROR("missing space after $1 definition\n" . $herecurr);
1844 }
1845
1846 # check for spacing round square brackets; allowed:
1847 # 1. with a type on the left -- int [] a;
1848 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
1849 # 3. inside a curly brace -- = { [0...10] = 5 }
1850 # 4. after a comma -- [1] = 5, [2] = 6
1851 # 5. in a macro definition -- #define abc(x) [x] = y
1852 while ($line =~ /(.*?\s)\[/g) {
1853 my ($where, $prefix) = ($-[1], $1);
1854 if ($prefix !~ /$Type\s+$/ &&
1855 ($where != 0 || $prefix !~ /^.\s+$/) &&
1856 $prefix !~ /{\s+$/ &&
1857 $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
1858 $prefix !~ /,\s+$/) {
1859 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
1860 }
1861 }
1862
1863 # check for spaces between functions and their parentheses.
1864 while ($line =~ /($Ident)\s+\(/g) {
1865 my $name = $1;
1866 my $ctx_before = substr($line, 0, $-[1]);
1867 my $ctx = "$ctx_before$name";
1868
1869 # Ignore those directives where spaces _are_ permitted.
1870 if ($name =~ /^(?:
1871 if|for|while|switch|return|case|
1872 volatile|__volatile__|coroutine_fn|
1873 __attribute__|format|__extension__|
1874 asm|__asm__)$/x)
1875 {
1876
1877 # Ignore 'catch (...)' in C++
1878 } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
1879
1880 # cpp #define statements have non-optional spaces, ie
1881 # if there is a space between the name and the open
1882 # parenthesis it is simply not a parameter group.
1883 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
1884
1885 # cpp #elif statement condition may start with a (
1886 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
1887
1888 # If this whole things ends with a type its most
1889 # likely a typedef for a function.
1890 } elsif ($ctx =~ /$Type$/) {
1891
1892 } else {
1893 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
1894 }
1895 }
1896 # Check operator spacing.
1897 if (!($line=~/\#\s*include/)) {
1898 my $ops = qr{
1899 <<=|>>=|<=|>=|==|!=|
1900 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
1901 =>|->|<<|>>|<|>|=|!|~|
1902 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
1903 \?|::|:
1904 }x;
1905 my @elements = split(/($ops|;)/, $opline);
1906 my $off = 0;
1907
1908 my $blank = copy_spacing($opline);
1909
1910 for (my $n = 0; $n < $#elements; $n += 2) {
1911 $off += length($elements[$n]);
1912
1913 # Pick up the preceding and succeeding characters.
1914 my $ca = substr($opline, 0, $off);
1915 my $cc = '';
1916 if (length($opline) >= ($off + length($elements[$n + 1]))) {
1917 $cc = substr($opline, $off + length($elements[$n + 1]));
1918 }
1919 my $cb = "$ca$;$cc";
1920
1921 my $a = '';
1922 $a = 'V' if ($elements[$n] ne '');
1923 $a = 'W' if ($elements[$n] =~ /\s$/);
1924 $a = 'C' if ($elements[$n] =~ /$;$/);
1925 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
1926 $a = 'O' if ($elements[$n] eq '');
1927 $a = 'E' if ($ca =~ /^\s*$/);
1928
1929 my $op = $elements[$n + 1];
1930
1931 my $c = '';
1932 if (defined $elements[$n + 2]) {
1933 $c = 'V' if ($elements[$n + 2] ne '');
1934 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
1935 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
1936 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
1937 $c = 'O' if ($elements[$n + 2] eq '');
1938 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
1939 } else {
1940 $c = 'E';
1941 }
1942
1943 my $ctx = "${a}x${c}";
1944
1945 my $at = "(ctx:$ctx)";
1946
1947 my $ptr = substr($blank, 0, $off) . "^";
1948 my $hereptr = "$hereline$ptr\n";
1949
1950 # Pull out the value of this operator.
1951 my $op_type = substr($curr_values, $off + 1, 1);
1952
1953 # Get the full operator variant.
1954 my $opv = $op . substr($curr_vars, $off, 1);
1955
1956 # Ignore operators passed as parameters.
1957 if ($op_type ne 'V' &&
1958 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
1959
1960 # # Ignore comments
1961 # } elsif ($op =~ /^$;+$/) {
1962
1963 # ; should have either the end of line or a space or \ after it
1964 } elsif ($op eq ';') {
1965 if ($ctx !~ /.x[WEBC]/ &&
1966 $cc !~ /^\\/ && $cc !~ /^;/) {
1967 ERROR("space required after that '$op' $at\n" . $hereptr);
1968 }
1969
1970 # // is a comment
1971 } elsif ($op eq '//') {
1972
1973 # Ignore : used in class declaration in C++
1974 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
1975 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
1976
1977 # No spaces for:
1978 # ->
1979 # : when part of a bitfield
1980 } elsif ($op eq '->' || $opv eq ':B') {
1981 if ($ctx =~ /Wx.|.xW/) {
1982 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
1983 }
1984
1985 # , must have a space on the right.
1986 # not required when having a single },{ on one line
1987 } elsif ($op eq ',') {
1988 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
1989 ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
1990 ERROR("space required after that '$op' $at\n" . $hereptr);
1991 }
1992
1993 # '*' as part of a type definition -- reported already.
1994 } elsif ($opv eq '*_') {
1995 #warn "'*' is part of type\n";
1996
1997 # unary operators should have a space before and
1998 # none after. May be left adjacent to another
1999 # unary operator, or a cast
2000 } elsif ($op eq '!' || $op eq '~' ||
2001 $opv eq '*U' || $opv eq '-U' ||
2002 $opv eq '&U' || $opv eq '&&U') {
2003 if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2004 # '~' used as a name of Destructor
2005
2006 } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2007 ERROR("space required before that '$op' $at\n" . $hereptr);
2008 }
2009 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2010 # A unary '*' may be const
2011
2012 } elsif ($ctx =~ /.xW/) {
2013 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2014 }
2015
2016 # unary ++ and unary -- are allowed no space on one side.
2017 } elsif ($op eq '++' or $op eq '--') {
2018 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2019 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2020 }
2021 if ($ctx =~ /Wx[BE]/ ||
2022 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2023 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2024 }
2025 if ($ctx =~ /ExW/) {
2026 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2027 }
2028
2029 # A colon needs no spaces before when it is
2030 # terminating a case value or a label.
2031 } elsif ($opv eq ':C' || $opv eq ':L') {
2032 if ($ctx =~ /Wx./) {
2033 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2034 }
2035
2036 # All the others need spaces both sides.
2037 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2038 my $ok = 0;
2039
2040 if ($realfile =~ /\.cpp|\.h$/) {
2041 # Ignore template arguments <...> in C++
2042 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2043 $ok = 1;
2044 }
2045
2046 # Ignore :: in C++
2047 if ($op eq '::') {
2048 $ok = 1;
2049 }
2050 }
2051
2052 # Ignore email addresses <foo@bar>
2053 if (($op eq '<' &&
2054 $cc =~ /^\S+\@\S+>/) ||
2055 ($op eq '>' &&
2056 $ca =~ /<\S+\@\S+$/))
2057 {
2058 $ok = 1;
2059 }
2060
2061 # Ignore ?:
2062 if (($opv eq ':O' && $ca =~ /\?$/) ||
2063 ($op eq '?' && $cc =~ /^:/)) {
2064 $ok = 1;
2065 }
2066
2067 if ($ok == 0) {
2068 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2069 }
2070 }
2071 $off += length($elements[$n + 1]);
2072 }
2073 }
2074
2075 #need space before brace following if, while, etc
2076 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2077 $line =~ /do\{/) {
2078 ERROR("space required before the open brace '{'\n" . $herecurr);
2079 }
2080
2081 # closing brace should have a space following it when it has anything
2082 # on the line
2083 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2084 ERROR("space required after that close brace '}'\n" . $herecurr);
2085 }
2086
2087 # check spacing on square brackets
2088 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2089 ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2090 }
2091 if ($line =~ /\s\]/) {
2092 ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2093 }
2094
2095 # check spacing on parentheses
2096 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2097 $line !~ /for\s*\(\s+;/) {
2098 ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2099 }
2100 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2101 $line !~ /for\s*\(.*;\s+\)/ &&
2102 $line !~ /:\s+\)/) {
2103 ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2104 }
2105
2106 # Return is not a function.
2107 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2108 my $spacing = $1;
2109 my $value = $2;
2110
2111 # Flatten any parentheses
2112 $value =~ s/\(/ \(/g;
2113 $value =~ s/\)/\) /g;
2114 while ($value =~ s/\[[^\{\}]*\]/1/ ||
2115 $value !~ /(?:$Ident|-?$Constant)\s*
2116 $Compare\s*
2117 (?:$Ident|-?$Constant)/x &&
2118 $value =~ s/\([^\(\)]*\)/1/) {
2119 }
2120 #print "value<$value>\n";
2121 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2122 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2123
2124 } elsif ($spacing !~ /\s+/) {
2125 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2126 }
2127 }
2128 # Return of what appears to be an errno should normally be -'ve
2129 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2130 my $name = $1;
2131 if ($name ne 'EOF' && $name ne 'ERROR') {
2132 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2133 }
2134 }
2135
2136 # Need a space before open parenthesis after if, while etc
2137 if ($line=~/\b(if|while|for|switch)\(/) {
2138 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2139 }
2140
2141 # Check for illegal assignment in if conditional -- and check for trailing
2142 # statements after the conditional.
2143 if ($line =~ /do\s*(?!{)/) {
2144 my ($stat_next) = ctx_statement_block($line_nr_next,
2145 $remain_next, $off_next);
2146 $stat_next =~ s/\n./\n /g;
2147 ##print "stat<$stat> stat_next<$stat_next>\n";
2148
2149 if ($stat_next =~ /^\s*while\b/) {
2150 # If the statement carries leading newlines,
2151 # then count those as offsets.
2152 my ($whitespace) =
2153 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2154 my $offset =
2155 statement_rawlines($whitespace) - 1;
2156
2157 $suppress_whiletrailers{$line_nr_next +
2158 $offset} = 1;
2159 }
2160 }
2161 if (!defined $suppress_whiletrailers{$linenr} &&
2162 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2163 my ($s, $c) = ($stat, $cond);
2164
2165 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2166 ERROR("do not use assignment in if condition\n" . $herecurr);
2167 }
2168
2169 # Find out what is on the end of the line after the
2170 # conditional.
2171 substr($s, 0, length($c), '');
2172 $s =~ s/\n.*//g;
2173 $s =~ s/$;//g; # Remove any comments
2174 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2175 $c !~ /}\s*while\s*/)
2176 {
2177 # Find out how long the conditional actually is.
2178 my @newlines = ($c =~ /\n/gs);
2179 my $cond_lines = 1 + $#newlines;
2180 my $stat_real = '';
2181
2182 $stat_real = raw_line($linenr, $cond_lines)
2183 . "\n" if ($cond_lines);
2184 if (defined($stat_real) && $cond_lines > 1) {
2185 $stat_real = "[...]\n$stat_real";
2186 }
2187
2188 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2189 }
2190 }
2191
2192 # Check for bitwise tests written as boolean
2193 if ($line =~ /
2194 (?:
2195 (?:\[|\(|\&\&|\|\|)
2196 \s*0[xX][0-9]+\s*
2197 (?:\&\&|\|\|)
2198 |
2199 (?:\&\&|\|\|)
2200 \s*0[xX][0-9]+\s*
2201 (?:\&\&|\|\||\)|\])
2202 )/x)
2203 {
2204 ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2205 }
2206
2207 # if and else should not have general statements after it
2208 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2209 my $s = $1;
2210 $s =~ s/$;//g; # Remove any comments
2211 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2212 ERROR("trailing statements should be on next line\n" . $herecurr);
2213 }
2214 }
2215 # if should not continue a brace
2216 if ($line =~ /}\s*if\b/) {
2217 ERROR("trailing statements should be on next line\n" .
2218 $herecurr);
2219 }
2220 # case and default should not have general statements after them
2221 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2222 $line !~ /\G(?:
2223 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2224 \s*return\s+
2225 )/xg)
2226 {
2227 ERROR("trailing statements should be on next line\n" . $herecurr);
2228 }
2229
2230 # Check for }<nl>else {, these must be at the same
2231 # indent level to be relevant to each other.
2232 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2233 $previndent == $indent) {
2234 ERROR("else should follow close brace '}'\n" . $hereprev);
2235 }
2236
2237 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2238 $previndent == $indent) {
2239 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2240
2241 # Find out what is on the end of the line after the
2242 # conditional.
2243 substr($s, 0, length($c), '');
2244 $s =~ s/\n.*//g;
2245
2246 if ($s =~ /^\s*;/) {
2247 ERROR("while should follow close brace '}'\n" . $hereprev);
2248 }
2249 }
2250
2251 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2252 # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2253 # print "No studly caps, use _\n";
2254 # print "$herecurr";
2255 # $clean = 0;
2256 # }
2257
2258 #no spaces allowed after \ in define
2259 if ($line=~/\#\s*define.*\\\s$/) {
2260 ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2261 }
2262
2263 # multi-statement macros should be enclosed in a do while loop, grab the
2264 # first statement and ensure its the whole macro if its not enclosed
2265 # in a known good container
2266 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2267 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2268 my $ln = $linenr;
2269 my $cnt = $realcnt;
2270 my ($off, $dstat, $dcond, $rest);
2271 my $ctx = '';
2272
2273 my $args = defined($1);
2274
2275 # Find the end of the macro and limit our statement
2276 # search to that.
2277 while ($cnt > 0 && defined $lines[$ln - 1] &&
2278 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2279 {
2280 $ctx .= $rawlines[$ln - 1] . "\n";
2281 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2282 $ln++;
2283 }
2284 $ctx .= $rawlines[$ln - 1];
2285
2286 ($dstat, $dcond, $ln, $cnt, $off) =
2287 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2288 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2289 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2290
2291 # Extract the remainder of the define (if any) and
2292 # rip off surrounding spaces, and trailing \'s.
2293 $rest = '';
2294 while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2295 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2296 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2297 $rest .= substr($lines[$ln - 1], $off) . "\n";
2298 $cnt--;
2299 }
2300 $ln++;
2301 $off = 0;
2302 }
2303 $rest =~ s/\\\n.//g;
2304 $rest =~ s/^\s*//s;
2305 $rest =~ s/\s*$//s;
2306
2307 # Clean up the original statement.
2308 if ($args) {
2309 substr($dstat, 0, length($dcond), '');
2310 } else {
2311 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2312 }
2313 $dstat =~ s/$;//g;
2314 $dstat =~ s/\\\n.//g;
2315 $dstat =~ s/^\s*//s;
2316 $dstat =~ s/\s*$//s;
2317
2318 # Flatten any parentheses and braces
2319 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2320 $dstat =~ s/\{[^\{\}]*\}/1/ ||
2321 $dstat =~ s/\[[^\{\}]*\]/1/)
2322 {
2323 }
2324
2325 my $exceptions = qr{
2326 $Declare|
2327 module_param_named|
2328 MODULE_PARAM_DESC|
2329 DECLARE_PER_CPU|
2330 DEFINE_PER_CPU|
2331 __typeof__\(|
2332 union|
2333 struct|
2334 \.$Ident\s*=\s*|
2335 ^\"|\"$
2336 }x;
2337 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2338 if ($rest ne '' && $rest ne ',') {
2339 if ($rest !~ /while\s*\(/ &&
2340 $dstat !~ /$exceptions/)
2341 {
2342 ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2343 }
2344
2345 } elsif ($ctx !~ /;/) {
2346 if ($dstat ne '' &&
2347 $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2348 $dstat !~ /$exceptions/ &&
2349 $dstat !~ /^\.$Ident\s*=/ &&
2350 $dstat =~ /$Operators/)
2351 {
2352 ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2353 }
2354 }
2355 }
2356
2357 # check for missing bracing around if etc
2358 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2359 $line !~ /\#\s*if/) {
2360 my $allowed = 0;
2361
2362 # Check the pre-context.
2363 if ($line =~ /(\}.*?)$/) {
2364 my $pre = $1;
2365
2366 if ($line !~ /else/) {
2367 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2368 if $dbg_adv_apw;
2369 $allowed = 1;
2370 }
2371 }
2372 my ($level, $endln, @chunks) =
2373 ctx_statement_full($linenr, $realcnt, 1);
2374 if ($dbg_adv_apw) {
2375 print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2376 print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2377 if $#chunks >= 1;
2378 }
2379 if ($#chunks >= 0 && $level == 0) {
2380 my $seen = 0;
2381 my $herectx = $here . "\n";
2382 my $ln = $linenr - 1;
2383 for my $chunk (@chunks) {
2384 my ($cond, $block) = @{$chunk};
2385
2386 # If the condition carries leading newlines, then count those as offsets.
2387 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2388 my $offset = statement_rawlines($whitespace) - 1;
2389
2390 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2391
2392 # We have looked at and allowed this specific line.
2393 $suppress_ifbraces{$ln + $offset} = 1;
2394
2395 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2396 $ln += statement_rawlines($block) - 1;
2397
2398 substr($block, 0, length($cond), '');
2399
2400 my $spaced_block = $block;
2401 $spaced_block =~ s/\n\+/ /g;
2402
2403 $seen++ if ($spaced_block =~ /^\s*\{/);
2404
2405 print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2406 if $dbg_adv_apw;
2407 if (statement_lines($cond) > 1) {
2408 print "APW: ALLOWED: cond<$cond>\n"
2409 if $dbg_adv_apw;
2410 $allowed = 1;
2411 }
2412 if ($block =~/\b(?:if|for|while)\b/) {
2413 print "APW: ALLOWED: block<$block>\n"
2414 if $dbg_adv_apw;
2415 $allowed = 1;
2416 }
2417 if (statement_block_size($block) > 1) {
2418 print "APW: ALLOWED: lines block<$block>\n"
2419 if $dbg_adv_apw;
2420 $allowed = 1;
2421 }
2422 }
2423 if ($seen != ($#chunks + 1) && !$allowed) {
2424 ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2425 }
2426 }
2427 }
2428 if (!defined $suppress_ifbraces{$linenr - 1} &&
2429 $line =~ /\b(if|while|for|else)\b/ &&
2430 $line !~ /\#\s*if/ &&
2431 $line !~ /\#\s*else/) {
2432 my $allowed = 0;
2433
2434 # Check the pre-context.
2435 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2436 my $pre = $1;
2437
2438 if ($line !~ /else/) {
2439 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2440 if $dbg_adv_apw;
2441 $allowed = 1;
2442 }
2443 }
2444
2445 my ($level, $endln, @chunks) =
2446 ctx_statement_full($linenr, $realcnt, $-[0]);
2447
2448 # Check the condition.
2449 my ($cond, $block) = @{$chunks[0]};
2450 print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2451 if $dbg_adv_checking;
2452 if (defined $cond) {
2453 substr($block, 0, length($cond), '');
2454 }
2455 if (statement_lines($cond) > 1) {
2456 print "APW: ALLOWED: cond<$cond>\n"
2457 if $dbg_adv_apw;
2458 $allowed = 1;
2459 }
2460 if ($block =~/\b(?:if|for|while)\b/) {
2461 print "APW: ALLOWED: block<$block>\n"
2462 if $dbg_adv_apw;
2463 $allowed = 1;
2464 }
2465 if (statement_block_size($block) > 1) {
2466 print "APW: ALLOWED: lines block<$block>\n"
2467 if $dbg_adv_apw;
2468 $allowed = 1;
2469 }
2470 # Check the post-context.
2471 if (defined $chunks[1]) {
2472 my ($cond, $block) = @{$chunks[1]};
2473 if (defined $cond) {
2474 substr($block, 0, length($cond), '');
2475 }
2476 if ($block =~ /^\s*\{/) {
2477 print "APW: ALLOWED: chunk-1 block<$block>\n"
2478 if $dbg_adv_apw;
2479 $allowed = 1;
2480 }
2481 }
2482 print "DCS: level=$level block<$block> allowed=$allowed\n"
2483 if $dbg_adv_dcs;
2484 if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2485 my $herectx = $here . "\n";;
2486 my $cnt = statement_rawlines($block);
2487
2488 for (my $n = 0; $n < $cnt; $n++) {
2489 $herectx .= raw_line($linenr, $n) . "\n";;
2490 }
2491
2492 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2493 }
2494 }
2495
2496 # no volatiles please
2497 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2498 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
2499 $line !~ /sig_atomic_t/ &&
2500 !ctx_has_comment($first_line, $linenr)) {
2501 my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
2502 ERROR($msg);
2503 }
2504
2505 # warn about #if 0
2506 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2507 ERROR("if this code is redundant consider removing it\n" .
2508 $herecurr);
2509 }
2510
2511 # check for needless g_free() checks
2512 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2513 my $expr = $1;
2514 if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2515 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2516 }
2517 }
2518
2519 # warn about #ifdefs in C files
2520 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2521 # print "#ifdef in C files should be avoided\n";
2522 # print "$herecurr";
2523 # $clean = 0;
2524 # }
2525
2526 # warn about spacing in #ifdefs
2527 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2528 ERROR("exactly one space required after that #$1\n" . $herecurr);
2529 }
2530 # check for memory barriers without a comment.
2531 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2532 if (!ctx_has_comment($first_line, $linenr)) {
2533 ERROR("memory barrier without comment\n" . $herecurr);
2534 }
2535 }
2536 # check of hardware specific defines
2537 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2538 # where they might be necessary.
2539 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2540 WARN("architecture specific defines should be avoided\n" . $herecurr);
2541 }
2542
2543 # Check that the storage class is at the beginning of a declaration
2544 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2545 ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2546 }
2547
2548 # check the location of the inline attribute, that it is between
2549 # storage class and type.
2550 if ($line =~ /\b$Type\s+$Inline\b/ ||
2551 $line =~ /\b$Inline\s+$Storage\b/) {
2552 ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2553 }
2554
2555 # check for sizeof(&)
2556 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2557 ERROR("sizeof(& should be avoided\n" . $herecurr);
2558 }
2559
2560 # check for new externs in .c files.
2561 if ($realfile =~ /\.c$/ && defined $stat &&
2562 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2563 {
2564 my $function_name = $1;
2565 my $paren_space = $2;
2566
2567 my $s = $stat;
2568 if (defined $cond) {
2569 substr($s, 0, length($cond), '');
2570 }
2571 if ($s =~ /^\s*;/ &&
2572 $function_name ne 'uninitialized_var')
2573 {
2574 ERROR("externs should be avoided in .c files\n" . $herecurr);
2575 }
2576
2577 if ($paren_space =~ /\n/) {
2578 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2579 }
2580
2581 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2582 $stat =~ /^.\s*extern\s+/)
2583 {
2584 ERROR("externs should be avoided in .c files\n" . $herecurr);
2585 }
2586
2587 # check for pointless casting of g_malloc return
2588 if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2589 if ($2 == 'm') {
2590 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2591 } else {
2592 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2593 }
2594 }
2595
2596 # check for gcc specific __FUNCTION__
2597 if ($line =~ /__FUNCTION__/) {
2598 ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr);
2599 }
2600
2601 # recommend g_path_get_* over g_strdup(basename/dirname(...))
2602 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
2603 WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
2604 }
2605
2606 # recommend qemu_strto* over strto* for numeric conversions
2607 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2608 ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2609 }
2610 # recommend sigaction over signal for portability, when establishing a handler
2611 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2612 ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2613 }
2614 # check for module_init(), use category-specific init macros explicitly please
2615 if ($line =~ /^module_init\s*\(/) {
2616 ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2617 }
2618 # check for various ops structs, ensure they are const.
2619 my $struct_ops = qr{AIOCBInfo|
2620 BdrvActionOps|
2621 BlockDevOps|
2622 BlockJobDriver|
2623 DisplayChangeListenerOps|
2624 GraphicHwOps|
2625 IDEDMAOps|
2626 KVMCapabilityInfo|
2627 MemoryRegionIOMMUOps|
2628 MemoryRegionOps|
2629 MemoryRegionPortio|
2630 QEMUFileOps|
2631 SCSIBusInfo|
2632 SCSIReqOps|
2633 Spice[A-Z][a-zA-Z0-9]*Interface|
2634 USBDesc[A-Z][a-zA-Z0-9]*|
2635 VhostOps|
2636 VMStateDescription|
2637 VMStateInfo}x;
2638 if ($line !~ /\bconst\b/ &&
2639 $line =~ /\b($struct_ops)\b.*=/) {
2640 ERROR("initializer for struct $1 should normally be const\n" .
2641 $herecurr);
2642 }
2643
2644 # check for %L{u,d,i} in strings
2645 my $string;
2646 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2647 $string = substr($rawline, $-[1], $+[1] - $-[1]);
2648 $string =~ s/%%/__/g;
2649 if ($string =~ /(?<!%)%L[udi]/) {
2650 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2651 last;
2652 }
2653 }
2654
2655 # QEMU specific tests
2656 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2657 ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2658 }
2659
2660 # Qemu error function tests
2661
2662 # Find newlines in error messages
2663 my $qemu_error_funcs = qr{error_setg|
2664 error_setg_errno|
2665 error_setg_win32|
2666 error_setg_file_open|
2667 error_set|
2668 error_prepend|
2669 warn_reportf_err|
2670 error_reportf_err|
2671 error_vreport|
2672 warn_vreport|
2673 info_vreport|
2674 error_report|
2675 warn_report|
2676 info_report}x;
2677
2678 if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2679 ERROR("Error messages should not contain newlines\n" . $herecurr);
2680 }
2681
2682 # Continue checking for error messages that contains newlines. This
2683 # check handles cases where string literals are spread over multiple lines.
2684 # Example:
2685 # error_report("Error msg line #1"
2686 # "Error msg line #2\n");
2687 my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2688 my $continued_str_literal = qr{\+\s*\".*\"};
2689
2690 if ($rawline =~ /$quoted_newline_regex/) {
2691 # Backtrack to first line that does not contain only a quoted literal
2692 # and assume that it is the start of the statement.
2693 my $i = $linenr - 2;
2694
2695 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2696 $i--;
2697 }
2698
2699 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2700 ERROR("Error messages should not contain newlines\n" . $herecurr);
2701 }
2702 }
2703
2704 # check for non-portable libc calls that have portable alternatives in QEMU
2705 if ($line =~ /\bffs\(/) {
2706 ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2707 }
2708 if ($line =~ /\bffsl\(/) {
2709 ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2710 }
2711 if ($line =~ /\bffsll\(/) {
2712 ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2713 }
2714 if ($line =~ /\bbzero\(/) {
2715 ERROR("use memset() instead of bzero()\n" . $herecurr);
2716 }
2717 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2718 g_assert_cmpint|
2719 g_assert_cmpuint|
2720 g_assert_cmphex|
2721 g_assert_cmpfloat|
2722 g_assert_true|
2723 g_assert_false|
2724 g_assert_nonnull|
2725 g_assert_null|
2726 g_assert_no_error|
2727 g_assert_error|
2728 g_test_assert_expected_messages|
2729 g_test_trap_assert_passed|
2730 g_test_trap_assert_stdout|
2731 g_test_trap_assert_stdout_unmatched|
2732 g_test_trap_assert_stderr|
2733 g_test_trap_assert_stderr_unmatched}x;
2734 if ($realfile !~ /^tests\// &&
2735 $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2736 ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
2737 }
2738 }
2739
2740 # If we have no input at all, then there is nothing to report on
2741 # so just keep quiet.
2742 if ($#rawlines == -1) {
2743 exit(0);
2744 }
2745
2746 # In mailback mode only produce a report in the negative, for
2747 # things that appear to be patches.
2748 if ($mailback && ($clean == 1 || !$is_patch)) {
2749 exit(0);
2750 }
2751
2752 # This is not a patch, and we are are in 'no-patch' mode so
2753 # just keep quiet.
2754 if (!$chk_patch && !$is_patch) {
2755 exit(0);
2756 }
2757
2758 if (!$is_patch) {
2759 ERROR("Does not appear to be a unified-diff format patch\n");
2760 }
2761 if ($is_patch && $chk_signoff && $signoff == 0) {
2762 ERROR("Missing Signed-off-by: line(s)\n");
2763 }
2764
2765 print report_dump();
2766 if ($summary && !($clean == 1 && $quiet == 1)) {
2767 print "$filename " if ($summary_file);
2768 print "total: $cnt_error errors, $cnt_warn warnings, " .
2769 "$cnt_lines lines checked\n";
2770 print "\n" if ($quiet == 0);
2771 }
2772
2773 if ($quiet == 0) {
2774 # If there were whitespace errors which cleanpatch can fix
2775 # then suggest that.
2776 # if ($rpt_cleaners) {
2777 # print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2778 # print " scripts/cleanfile\n\n";
2779 # }
2780 }
2781
2782 if ($clean == 1 && $quiet == 0) {
2783 print "$vname has no obvious style problems and is ready for submission.\n"
2784 }
2785 if ($clean == 0 && $quiet == 0) {
2786 print "$vname has style problems, please review. If any of these errors\n";
2787 print "are false positives report them to the maintainer, see\n";
2788 print "CHECKPATCH in MAINTAINERS.\n";
2789 }
2790
2791 return ($no_warnings ? $clean : $cnt_error == 0);
2792 }