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