]> Git Repo - qemu.git/blob - scripts/checkpatch.pl
20d5b62586826af2864957bfe04007ece2ec772c
[qemu.git] / scripts / checkpatch.pl
1 #!/usr/bin/env perl
2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <[email protected]> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <[email protected]> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <[email protected]>
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 $NON_ASCII_UTF8     = qr{
228         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
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
237 our $UTF8       = qr{
238         [\x09\x0A\x0D\x20-\x7E]              # ASCII
239         | $NON_ASCII_UTF8
240 }x;
241
242 # There are still some false positives, but this catches most
243 # common cases.
244 our $typeTypedefs = qr{(?x:
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
249 )};
250
251 our @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},
270         qr{target_(?:u)?long},
271         qr{hwaddr},
272         qr{xml${Ident}},
273         qr{xendevicemodel_handle},
274 );
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.
278 our @modifierList = (
279 );
280
281 sub build_types {
282         my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
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         }
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 }
305 build_types();
306
307 $chk_signoff = 0 if ($file);
308
309 my @rawlines = ();
310 my @lines = ();
311 my $vname;
312 if ($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>) {
319                 chomp;
320                 push @patches, $_;
321         }
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 = ();
371         }
372 }
373
374 exit($exit);
375
376 sub top_of_kernel_tree {
377         my ($root) = @_;
378
379         my @tree_check = (
380                 "COPYING", "MAINTAINERS", "Makefile",
381                 "README", "docs", "VERSION",
382                 "vl.c"
383         );
384
385         foreach my $check (@tree_check) {
386                 if (! -e $root . '/' . $check) {
387                         return 0;
388                 }
389         }
390         return 1;
391 }
392
393 sub 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 }
413 sub copy_spacing {
414         (my $res = shift) =~ tr/\t/ /c;
415         return $res;
416 }
417
418 sub 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
431 my $sanitise_quote = '';
432
433 sub sanitise_line_reset {
434         my ($in_comment) = @_;
435
436         if ($in_comment) {
437                 $sanitise_quote = '*/';
438         } else {
439                 $sanitise_quote = '';
440         }
441 }
442 sub 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
458                 # Comments we are wacking completely including the begin
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
530 sub 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
653 sub 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
666 sub statement_rawlines {
667         my ($stmt) = @_;
668
669         my @stmt_lines = ($stmt =~ /\n/g);
670
671         return $#stmt_lines + 2;
672 }
673
674 sub statement_block_size {
675         my ($stmt) = @_;
676
677         $stmt =~ s/(^|\n)./$1/g;
678         $stmt =~ s/^\s*\{//;
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
696 sub 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
725 sub 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 }
775 sub ctx_block_outer {
776         my ($linenr, $remain) = @_;
777
778         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
779         return @r;
780 }
781 sub ctx_block {
782         my ($linenr, $remain) = @_;
783
784         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
785         return @r;
786 }
787 sub ctx_statement {
788         my ($linenr, $remain, $off) = @_;
789
790         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
791         return @r;
792 }
793 sub ctx_block_level {
794         my ($linenr, $remain) = @_;
795
796         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
797 }
798 sub ctx_statement_level {
799         my ($linenr, $remain, $off) = @_;
800
801         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
802 }
803
804 sub 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 }
836 sub 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
846 sub 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
862 sub 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
879 my $av_preprocessor = 0;
880 my $av_pending;
881 my @av_paren_type;
882 my $av_pend_colon;
883
884 sub annotate_reset {
885         $av_preprocessor = 0;
886         $av_pending = '_';
887         @av_paren_type = ('E');
888         $av_pend_colon = 'O';
889 }
890
891 sub 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
911                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
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
1091 sub 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__|
1106                         do|
1107                         \#|
1108                         \#\#
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
1138 my $prefix = '';
1139
1140 sub 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 }
1152 sub report_dump {
1153         our @report;
1154 }
1155 sub ERROR {
1156         if (report("ERROR: $_[0]\n")) {
1157                 our $clean = 0;
1158                 our $cnt_error++;
1159         }
1160 }
1161 sub WARN {
1162         if (report("WARNING: $_[0]\n")) {
1163                 our $clean = 0;
1164                 our $cnt_warn++;
1165         }
1166 }
1167
1168 sub 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
1186         my $in_header_lines = $file ? 0 : 1;
1187         my $in_commit_log = 0;          #Scanning lines before patch
1188
1189         my $non_utf8_charset = 0;
1190
1191         our @report = ();
1192         our $cnt_lines = 0;
1193         our $cnt_error = 0;
1194         our $cnt_warn = 0;
1195         our $cnt_chk = 0;
1196
1197         # Trace the real file/line as we go.
1198         my $realfile = '';
1199         my $realline = 0;
1200         my $realcnt = 0;
1201         my $here = '';
1202         my $in_comment = 0;
1203         my $comment_edge = 0;
1204         my $first_line = 0;
1205         my $p1_prefix = '';
1206
1207         my $prev_values = 'E';
1208
1209         # suppression flags
1210         my %suppress_ifbraces;
1211         my %suppress_whiletrailers;
1212         my %suppress_export;
1213
1214         # Pre-scan the patch sanitizing the lines.
1215
1216         sanitise_line_reset();
1217         my $line;
1218         foreach my $rawline (@rawlines) {
1219                 $linenr++;
1220                 $line = $rawline;
1221
1222                 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1223                         $realline=$1-1;
1224                         if (defined $2) {
1225                                 $realcnt=$3+1;
1226                         } else {
1227                                 $realcnt=1+1;
1228                         }
1229                         $in_comment = 0;
1230
1231                         # Guestimate if this is a continuing comment.  Run
1232                         # the context looking for a comment "edge".  If this
1233                         # edge is a close comment then we must be in a comment
1234                         # at context start.
1235                         my $edge;
1236                         my $cnt = $realcnt;
1237                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1238                                 next if (defined $rawlines[$ln - 1] &&
1239                                          $rawlines[$ln - 1] =~ /^-/);
1240                                 $cnt--;
1241                                 #print "RAW<$rawlines[$ln - 1]>\n";
1242                                 last if (!defined $rawlines[$ln - 1]);
1243                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1244                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1245                                         ($edge) = $1;
1246                                         last;
1247                                 }
1248                         }
1249                         if (defined $edge && $edge eq '*/') {
1250                                 $in_comment = 1;
1251                         }
1252
1253                         # Guestimate if this is a continuing comment.  If this
1254                         # is the start of a diff block and this line starts
1255                         # ' *' then it is very likely a comment.
1256                         if (!defined $edge &&
1257                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1258                         {
1259                                 $in_comment = 1;
1260                         }
1261
1262                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1263                         sanitise_line_reset($in_comment);
1264
1265                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1266                         # Standardise the strings and chars within the input to
1267                         # simplify matching -- only bother with positive lines.
1268                         $line = sanitise_line($rawline);
1269                 }
1270                 push(@lines, $line);
1271
1272                 if ($realcnt > 1) {
1273                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
1274                 } else {
1275                         $realcnt = 0;
1276                 }
1277
1278                 #print "==>$rawline\n";
1279                 #print "-->$line\n";
1280         }
1281
1282         $prefix = '';
1283
1284         $realcnt = 0;
1285         $linenr = 0;
1286         foreach my $line (@lines) {
1287                 $linenr++;
1288
1289                 my $rawline = $rawlines[$linenr - 1];
1290
1291 #extract the line range in the file after the patch is applied
1292                 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1293                         $is_patch = 1;
1294                         $first_line = $linenr + 1;
1295                         $realline=$1-1;
1296                         if (defined $2) {
1297                                 $realcnt=$3+1;
1298                         } else {
1299                                 $realcnt=1+1;
1300                         }
1301                         annotate_reset();
1302                         $prev_values = 'E';
1303
1304                         %suppress_ifbraces = ();
1305                         %suppress_whiletrailers = ();
1306                         %suppress_export = ();
1307                         next;
1308
1309 # track the line number as we move through the hunk, note that
1310 # new versions of GNU diff omit the leading space on completely
1311 # blank context lines so we need to count that too.
1312                 } elsif ($line =~ /^( |\+|$)/) {
1313                         $realline++;
1314                         $realcnt-- if ($realcnt != 0);
1315
1316                         # Measure the line length and indent.
1317                         ($length, $indent) = line_stats($rawline);
1318
1319                         # Track the previous line.
1320                         ($prevline, $stashline) = ($stashline, $line);
1321                         ($previndent, $stashindent) = ($stashindent, $indent);
1322                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1323
1324                         #warn "line<$line>\n";
1325
1326                 } elsif ($realcnt == 1) {
1327                         $realcnt--;
1328                 }
1329
1330                 my $hunk_line = ($realcnt != 0);
1331
1332 #make up the handle for any error we report on this line
1333                 $prefix = "$filename:$realline: " if ($emacs && $file);
1334                 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1335
1336                 $here = "#$linenr: " if (!$file);
1337                 $here = "#$realline: " if ($file);
1338
1339                 # extract the filename as it passes
1340                 if ($line =~ /^diff --git.*?(\S+)$/) {
1341                         $realfile = $1;
1342                         $realfile =~ s@^([^/]*)/@@;
1343                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1344                         $realfile = $1;
1345                         $realfile =~ s@^([^/]*)/@@;
1346
1347                         $p1_prefix = $1;
1348                         if (!$file && $tree && $p1_prefix ne '' &&
1349                             -e "$root/$p1_prefix") {
1350                                 WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1351                         }
1352
1353                         next;
1354                 }
1355
1356                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1357
1358                 my $hereline = "$here\n$rawline\n";
1359                 my $herecurr = "$here\n$rawline\n";
1360                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1361
1362                 $cnt_lines++ if ($realcnt != 0);
1363
1364 # Check for incorrect file permissions
1365                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1366                         my $permhere = $here . "FILE: $realfile\n";
1367                         if ($realfile =~ /(\bMakefile(?:\.objs)?|\.c|\.cc|\.cpp|\.h|\.mak|\.[sS])$/) {
1368                                 ERROR("do not set execute permissions for source files\n" . $permhere);
1369                         }
1370                 }
1371
1372 # Accept git diff extended headers as valid patches
1373                 if ($line =~ /^(?:rename|copy) (?:from|to) [\w\/\.\-]+\s*$/) {
1374                         $is_patch = 1;
1375                 }
1376
1377 #check the patch for a signoff:
1378                 if ($line =~ /^\s*signed-off-by:/i) {
1379                         # This is a signoff, if ugly, so do not double report.
1380                         $signoff++;
1381                         $in_commit_log = 0;
1382
1383                         if (!($line =~ /^\s*Signed-off-by:/)) {
1384                                 ERROR("The correct form is \"Signed-off-by\"\n" .
1385                                         $herecurr);
1386                         }
1387                         if ($line =~ /^\s*signed-off-by:\S/i) {
1388                                 ERROR("space required after Signed-off-by:\n" .
1389                                         $herecurr);
1390                         }
1391                 }
1392
1393 # Check for wrappage within a valid hunk of the file
1394                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1395                         ERROR("patch seems to be corrupt (line wrapped?)\n" .
1396                                 $herecurr) if (!$emitted_corrupt++);
1397                 }
1398
1399 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1400                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1401                     $rawline !~ m/^$UTF8*$/) {
1402                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1403
1404                         my $blank = copy_spacing($rawline);
1405                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1406                         my $hereptr = "$hereline$ptr\n";
1407
1408                         ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1409                 }
1410
1411 # Check if it's the start of a commit log
1412 # (not a header line and we haven't seen the patch filename)
1413                 if ($in_header_lines && $realfile =~ /^$/ &&
1414                     !($rawline =~ /^\s+\S/ ||
1415                       $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
1416                         $in_header_lines = 0;
1417                         $in_commit_log = 1;
1418                 }
1419
1420 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1421 # declined it, i.e defined some charset where it is missing.
1422                 if ($in_header_lines &&
1423                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1424                     $1 !~ /utf-8/i) {
1425                         $non_utf8_charset = 1;
1426                 }
1427
1428                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1429                     $rawline =~ /$NON_ASCII_UTF8/) {
1430                         WARN("8-bit UTF-8 used in possible commit log\n" . $herecurr);
1431                 }
1432
1433 # ignore non-hunk lines and lines being removed
1434                 next if (!$hunk_line || $line =~ /^-/);
1435
1436 # ignore files that are being periodically imported from Linux
1437                 next if ($realfile =~ /^(linux-headers|include\/standard-headers)\//);
1438
1439 #trailing whitespace
1440                 if ($line =~ /^\+.*\015/) {
1441                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1442                         ERROR("DOS line endings\n" . $herevet);
1443
1444                 } elsif ($realfile =~ /^docs\/.+\.txt/ ||
1445                          $realfile =~ /^docs\/.+\.md/) {
1446                     if ($rawline =~ /^\+\s+$/ && $rawline !~ /^\+ {4}$/) {
1447                         # TODO: properly check we're in a code block
1448                         #       (surrounding text is 4-column aligned)
1449                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1450                         ERROR("code blocks in documentation should have " .
1451                               "empty lines with exactly 4 columns of " .
1452                               "whitespace\n" . $herevet);
1453                     }
1454                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1455                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1456                         ERROR("trailing whitespace\n" . $herevet);
1457                         $rpt_cleaners = 1;
1458                 }
1459
1460 # checks for trace-events files
1461                 if ($realfile =~ /trace-events$/ && $line =~ /^\+/) {
1462                         if ($rawline =~ /%[-+ 0]*#/) {
1463                                 ERROR("Don't use '#' flag of printf format ('%#') in " .
1464                                       "trace-events, use '0x' prefix instead\n" . $herecurr);
1465                         } else {
1466                                 my $hex =
1467                                         qr/%[-+ *.0-9]*([hljztL]|ll|hh)?(x|X|"\s*PRI[xX][^"]*"?)/;
1468
1469                                 # don't consider groups splitted by [.:/ ], like 2A.20:12ab
1470                                 my $tmpline = $rawline;
1471                                 $tmpline =~ s/($hex[.:\/ ])+$hex//g;
1472
1473                                 if ($tmpline =~ /(?<!0x)$hex/) {
1474                                         ERROR("Hex numbers must be prefixed with '0x'\n" .
1475                                               $herecurr);
1476                                 }
1477                         }
1478                 }
1479
1480 # check we are in a valid source file if not then ignore this hunk
1481                 next if ($realfile !~ /$SrcFile/);
1482
1483 #90 column limit; exempt URLs, if no other words on line
1484                 if ($line =~ /^\+/ &&
1485                     !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1486                     !($rawline =~ /^[^[:alnum:]]*https?:\S*$/) &&
1487                     $length > 80)
1488                 {
1489                         if ($length > 90) {
1490                                 ERROR("line over 90 characters\n" . $herecurr);
1491                         } else {
1492                                 WARN("line over 80 characters\n" . $herecurr);
1493                         }
1494                 }
1495
1496 # check for spaces before a quoted newline
1497                 if ($rawline =~ /^.*\".*\s\\n/) {
1498                         ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1499                 }
1500
1501 # check for adding lines without a newline.
1502                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1503                         ERROR("adding a line without newline at end of file\n" . $herecurr);
1504                 }
1505
1506 # check for RCS/CVS revision markers
1507                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1508                         ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1509                 }
1510
1511 # tabs are only allowed in assembly source code, and in
1512 # some scripts we imported from other projects.
1513                 next if ($realfile =~ /\.(s|S)$/);
1514                 next if ($realfile =~ /(checkpatch|get_maintainer|texi2pod)\.pl$/);
1515
1516                 if ($rawline =~ /^\+.*\t/) {
1517                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1518                         ERROR("code indent should never use tabs\n" . $herevet);
1519                         $rpt_cleaners = 1;
1520                 }
1521
1522 # check we are in a valid C source file if not then ignore this hunk
1523                 next if ($realfile !~ /\.(h|c|cpp)$/);
1524
1525 # Check for potential 'bare' types
1526                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1527                     $realline_next);
1528                 if ($realcnt && $line =~ /.\s*\S/) {
1529                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1530                                 ctx_statement_block($linenr, $realcnt, 0);
1531                         $stat =~ s/\n./\n /g;
1532                         $cond =~ s/\n./\n /g;
1533
1534                         # Find the real next line.
1535                         $realline_next = $line_nr_next;
1536                         if (defined $realline_next &&
1537                             (!defined $lines[$realline_next - 1] ||
1538                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1539                                 $realline_next++;
1540                         }
1541
1542                         my $s = $stat;
1543                         $s =~ s/{.*$//s;
1544
1545                         # Ignore goto labels.
1546                         if ($s =~ /$Ident:\*$/s) {
1547
1548                         # Ignore functions being called
1549                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1550
1551                         } elsif ($s =~ /^.\s*else\b/s) {
1552
1553                         # declarations always start with types
1554                         } 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) {
1555                                 my $type = $1;
1556                                 $type =~ s/\s+/ /g;
1557                                 possible($type, "A:" . $s);
1558
1559                         # definitions in global scope can only start with types
1560                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1561                                 possible($1, "B:" . $s);
1562                         }
1563
1564                         # any (foo ... *) is a pointer cast, and foo is a type
1565                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1566                                 possible($1, "C:" . $s);
1567                         }
1568
1569                         # Check for any sort of function declaration.
1570                         # int foo(something bar, other baz);
1571                         # void (*store_gdt)(x86_descr_ptr *);
1572                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1573                                 my ($name_len) = length($1);
1574
1575                                 my $ctx = $s;
1576                                 substr($ctx, 0, $name_len + 1, '');
1577                                 $ctx =~ s/\)[^\)]*$//;
1578
1579                                 for my $arg (split(/\s*,\s*/, $ctx)) {
1580                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1581
1582                                                 possible($1, "D:" . $s);
1583                                         }
1584                                 }
1585                         }
1586
1587                 }
1588
1589 #
1590 # Checks which may be anchored in the context.
1591 #
1592
1593 # Check for switch () and associated case and default
1594 # statements should be at the same indent.
1595                 if ($line=~/\bswitch\s*\(.*\)/) {
1596                         my $err = '';
1597                         my $sep = '';
1598                         my @ctx = ctx_block_outer($linenr, $realcnt);
1599                         shift(@ctx);
1600                         for my $ctx (@ctx) {
1601                                 my ($clen, $cindent) = line_stats($ctx);
1602                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1603                                                         $indent != $cindent) {
1604                                         $err .= "$sep$ctx\n";
1605                                         $sep = '';
1606                                 } else {
1607                                         $sep = "[...]\n";
1608                                 }
1609                         }
1610                         if ($err ne '') {
1611                                 ERROR("switch and case should be at the same indent\n$hereline$err");
1612                         }
1613                 }
1614
1615 # if/while/etc brace do not go on next line, unless defining a do while loop,
1616 # or if that brace on the next line is for something else
1617                 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1618                         my $pre_ctx = "$1$2";
1619
1620                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1621                         my $ctx_cnt = $realcnt - $#ctx - 1;
1622                         my $ctx = join("\n", @ctx);
1623
1624                         my $ctx_ln = $linenr;
1625                         my $ctx_skip = $realcnt;
1626
1627                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1628                                         defined $lines[$ctx_ln - 1] &&
1629                                         $lines[$ctx_ln - 1] =~ /^-/)) {
1630                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1631                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1632                                 $ctx_ln++;
1633                         }
1634
1635                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1636                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1637
1638                         # The length of the "previous line" is checked against 80 because it
1639                         # includes the + at the beginning of the line (if the actual line has
1640                         # 79 or 80 characters, it is no longer possible to add a space and an
1641                         # opening brace there)
1642                         if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1643                             defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1644                             defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1645                                 ERROR("that open brace { should be on the previous line\n" .
1646                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1647                         }
1648                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1649                             $ctx =~ /\)\s*\;\s*$/ &&
1650                             defined $lines[$ctx_ln - 1])
1651                         {
1652                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1653                                 if ($nindent > $indent) {
1654                                         ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1655                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1656                                 }
1657                         }
1658                 }
1659
1660 # 'do ... while (0/false)' only makes sense in macros, without trailing ';'
1661                 if ($line =~ /while\s*\((0|false)\);/) {
1662                         ERROR("suspicious ; after while (0)\n" . $herecurr);
1663                 }
1664
1665 # Check relative indent for conditionals and blocks.
1666                 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1667                         my ($s, $c) = ($stat, $cond);
1668
1669                         substr($s, 0, length($c), '');
1670
1671                         # Make sure we remove the line prefixes as we have
1672                         # none on the first line, and are going to readd them
1673                         # where necessary.
1674                         $s =~ s/\n./\n/gs;
1675
1676                         # Find out how long the conditional actually is.
1677                         my @newlines = ($c =~ /\n/gs);
1678                         my $cond_lines = 1 + $#newlines;
1679
1680                         # We want to check the first line inside the block
1681                         # starting at the end of the conditional, so remove:
1682                         #  1) any blank line termination
1683                         #  2) any opening brace { on end of the line
1684                         #  3) any do (...) {
1685                         my $continuation = 0;
1686                         my $check = 0;
1687                         $s =~ s/^.*\bdo\b//;
1688                         $s =~ s/^\s*\{//;
1689                         if ($s =~ s/^\s*\\//) {
1690                                 $continuation = 1;
1691                         }
1692                         if ($s =~ s/^\s*?\n//) {
1693                                 $check = 1;
1694                                 $cond_lines++;
1695                         }
1696
1697                         # Also ignore a loop construct at the end of a
1698                         # preprocessor statement.
1699                         if (($prevline =~ /^.\s*#\s*define\s/ ||
1700                             $prevline =~ /\\\s*$/) && $continuation == 0) {
1701                                 $check = 0;
1702                         }
1703
1704                         my $cond_ptr = -1;
1705                         $continuation = 0;
1706                         while ($cond_ptr != $cond_lines) {
1707                                 $cond_ptr = $cond_lines;
1708
1709                                 # If we see an #else/#elif then the code
1710                                 # is not linear.
1711                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1712                                         $check = 0;
1713                                 }
1714
1715                                 # Ignore:
1716                                 #  1) blank lines, they should be at 0,
1717                                 #  2) preprocessor lines, and
1718                                 #  3) labels.
1719                                 if ($continuation ||
1720                                     $s =~ /^\s*?\n/ ||
1721                                     $s =~ /^\s*#\s*?/ ||
1722                                     $s =~ /^\s*$Ident\s*:/) {
1723                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1724                                         if ($s =~ s/^.*?\n//) {
1725                                                 $cond_lines++;
1726                                         }
1727                                 }
1728                         }
1729
1730                         my (undef, $sindent) = line_stats("+" . $s);
1731                         my $stat_real = raw_line($linenr, $cond_lines);
1732
1733                         # Check if either of these lines are modified, else
1734                         # this is not this patch's fault.
1735                         if (!defined($stat_real) ||
1736                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1737                                 $check = 0;
1738                         }
1739                         if (defined($stat_real) && $cond_lines > 1) {
1740                                 $stat_real = "[...]\n$stat_real";
1741                         }
1742
1743                         #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";
1744
1745                         if ($check && (($sindent % 4) != 0 ||
1746                             ($sindent <= $indent && $s ne ''))) {
1747                                 ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1748                         }
1749                 }
1750
1751                 # Track the 'values' across context and added lines.
1752                 my $opline = $line; $opline =~ s/^./ /;
1753                 my ($curr_values, $curr_vars) =
1754                                 annotate_values($opline . "\n", $prev_values);
1755                 $curr_values = $prev_values . $curr_values;
1756                 if ($dbg_values) {
1757                         my $outline = $opline; $outline =~ s/\t/ /g;
1758                         print "$linenr > .$outline\n";
1759                         print "$linenr > $curr_values\n";
1760                         print "$linenr >  $curr_vars\n";
1761                 }
1762                 $prev_values = substr($curr_values, -1);
1763
1764 #ignore lines not being added
1765                 if ($line=~/^[^\+]/) {next;}
1766
1767 # TEST: allow direct testing of the type matcher.
1768                 if ($dbg_type) {
1769                         if ($line =~ /^.\s*$Declare\s*$/) {
1770                                 ERROR("TEST: is type\n" . $herecurr);
1771                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1772                                 ERROR("TEST: is not type ($1 is)\n". $herecurr);
1773                         }
1774                         next;
1775                 }
1776 # TEST: allow direct testing of the attribute matcher.
1777                 if ($dbg_attr) {
1778                         if ($line =~ /^.\s*$Modifier\s*$/) {
1779                                 ERROR("TEST: is attr\n" . $herecurr);
1780                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1781                                 ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1782                         }
1783                         next;
1784                 }
1785
1786 # check for initialisation to aggregates open brace on the next line
1787                 if ($line =~ /^.\s*\{/ &&
1788                     $prevline =~ /(?:^|[^=])=\s*$/) {
1789                         ERROR("that open brace { should be on the previous line\n" . $hereprev);
1790                 }
1791
1792 #
1793 # Checks which are anchored on the added line.
1794 #
1795
1796 # check for malformed paths in #include statements (uses RAW line)
1797                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1798                         my $path = $1;
1799                         if ($path =~ m{//}) {
1800                                 ERROR("malformed #include filename\n" .
1801                                         $herecurr);
1802                         }
1803                 }
1804
1805 # no C99 // comments
1806                 if ($line =~ m{//}) {
1807                         ERROR("do not use C99 // comments\n" . $herecurr);
1808                 }
1809                 # Remove C99 comments.
1810                 $line =~ s@//.*@@;
1811                 $opline =~ s@//.*@@;
1812
1813 # check for global initialisers.
1814                 if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
1815                         ERROR("do not initialise globals to 0 or NULL\n" .
1816                                 $herecurr);
1817                 }
1818 # check for static initialisers.
1819                 if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
1820                         ERROR("do not initialise statics to 0 or NULL\n" .
1821                                 $herecurr);
1822                 }
1823
1824 # * goes on variable not on type
1825                 # (char*[ const])
1826                 if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1827                         my ($from, $to) = ($1, $1);
1828
1829                         # Should start with a space.
1830                         $to =~ s/^(\S)/ $1/;
1831                         # Should not end with a space.
1832                         $to =~ s/\s+$//;
1833                         # '*'s should not have spaces between.
1834                         while ($to =~ s/\*\s+\*/\*\*/) {
1835                         }
1836
1837                         #print "from<$from> to<$to>\n";
1838                         if ($from ne $to) {
1839                                 ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr);
1840                         }
1841                 } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1842                         my ($from, $to, $ident) = ($1, $1, $2);
1843
1844                         # Should start with a space.
1845                         $to =~ s/^(\S)/ $1/;
1846                         # Should not end with a space.
1847                         $to =~ s/\s+$//;
1848                         # '*'s should not have spaces between.
1849                         while ($to =~ s/\*\s+\*/\*\*/) {
1850                         }
1851                         # Modifiers should have spaces.
1852                         $to =~ s/(\b$Modifier$)/$1 /;
1853
1854                         #print "from<$from> to<$to> ident<$ident>\n";
1855                         if ($from ne $to && $ident !~ /^$Modifier$/) {
1856                                 ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr);
1857                         }
1858                 }
1859
1860 # function brace can't be on same line, except for #defines of do while,
1861 # or if closed on same line
1862                 if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
1863                     !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
1864                         ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
1865                 }
1866
1867 # open braces for enum, union and struct go on the same line.
1868                 if ($line =~ /^.\s*\{/ &&
1869                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
1870                         ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
1871                 }
1872
1873 # missing space after union, struct or enum definition
1874                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
1875                     ERROR("missing space after $1 definition\n" . $herecurr);
1876                 }
1877
1878 # check for spacing round square brackets; allowed:
1879 #  1. with a type on the left -- int [] a;
1880 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
1881 #  3. inside a curly brace -- = { [0...10] = 5 }
1882 #  4. after a comma -- [1] = 5, [2] = 6
1883 #  5. in a macro definition -- #define abc(x) [x] = y
1884                 while ($line =~ /(.*?\s)\[/g) {
1885                         my ($where, $prefix) = ($-[1], $1);
1886                         if ($prefix !~ /$Type\s+$/ &&
1887                             ($where != 0 || $prefix !~ /^.\s+$/) &&
1888                             $prefix !~ /{\s+$/ &&
1889                             $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
1890                             $prefix !~ /,\s+$/) {
1891                                 ERROR("space prohibited before open square bracket '['\n" . $herecurr);
1892                         }
1893                 }
1894
1895 # check for spaces between functions and their parentheses.
1896                 while ($line =~ /($Ident)\s+\(/g) {
1897                         my $name = $1;
1898                         my $ctx_before = substr($line, 0, $-[1]);
1899                         my $ctx = "$ctx_before$name";
1900
1901                         # Ignore those directives where spaces _are_ permitted.
1902                         if ($name =~ /^(?:
1903                                 if|for|while|switch|return|case|
1904                                 volatile|__volatile__|coroutine_fn|
1905                                 __attribute__|format|__extension__|
1906                                 asm|__asm__)$/x)
1907                         {
1908
1909                         # Ignore 'catch (...)' in C++
1910                         } elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
1911
1912                         # cpp #define statements have non-optional spaces, ie
1913                         # if there is a space between the name and the open
1914                         # parenthesis it is simply not a parameter group.
1915                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
1916
1917                         # cpp #elif statement condition may start with a (
1918                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
1919
1920                         # If this whole things ends with a type its most
1921                         # likely a typedef for a function.
1922                         } elsif ($ctx =~ /$Type$/) {
1923
1924                         } else {
1925                                 ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
1926                         }
1927                 }
1928 # Check operator spacing.
1929                 if (!($line=~/\#\s*include/)) {
1930                         my $ops = qr{
1931                                 <<=|>>=|<=|>=|==|!=|
1932                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
1933                                 =>|->|<<|>>|<|>|=|!|~|
1934                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
1935                                 \?|::|:
1936                         }x;
1937                         my @elements = split(/($ops|;)/, $opline);
1938                         my $off = 0;
1939
1940                         my $blank = copy_spacing($opline);
1941
1942                         for (my $n = 0; $n < $#elements; $n += 2) {
1943                                 $off += length($elements[$n]);
1944
1945                                 # Pick up the preceding and succeeding characters.
1946                                 my $ca = substr($opline, 0, $off);
1947                                 my $cc = '';
1948                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
1949                                         $cc = substr($opline, $off + length($elements[$n + 1]));
1950                                 }
1951                                 my $cb = "$ca$;$cc";
1952
1953                                 my $a = '';
1954                                 $a = 'V' if ($elements[$n] ne '');
1955                                 $a = 'W' if ($elements[$n] =~ /\s$/);
1956                                 $a = 'C' if ($elements[$n] =~ /$;$/);
1957                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
1958                                 $a = 'O' if ($elements[$n] eq '');
1959                                 $a = 'E' if ($ca =~ /^\s*$/);
1960
1961                                 my $op = $elements[$n + 1];
1962
1963                                 my $c = '';
1964                                 if (defined $elements[$n + 2]) {
1965                                         $c = 'V' if ($elements[$n + 2] ne '');
1966                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
1967                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
1968                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
1969                                         $c = 'O' if ($elements[$n + 2] eq '');
1970                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
1971                                 } else {
1972                                         $c = 'E';
1973                                 }
1974
1975                                 my $ctx = "${a}x${c}";
1976
1977                                 my $at = "(ctx:$ctx)";
1978
1979                                 my $ptr = substr($blank, 0, $off) . "^";
1980                                 my $hereptr = "$hereline$ptr\n";
1981
1982                                 # Pull out the value of this operator.
1983                                 my $op_type = substr($curr_values, $off + 1, 1);
1984
1985                                 # Get the full operator variant.
1986                                 my $opv = $op . substr($curr_vars, $off, 1);
1987
1988                                 # Ignore operators passed as parameters.
1989                                 if ($op_type ne 'V' &&
1990                                     $ca =~ /\s$/ && $cc =~ /^\s*,/) {
1991
1992 #                               # Ignore comments
1993 #                               } elsif ($op =~ /^$;+$/) {
1994
1995                                 # ; should have either the end of line or a space or \ after it
1996                                 } elsif ($op eq ';') {
1997                                         if ($ctx !~ /.x[WEBC]/ &&
1998                                             $cc !~ /^\\/ && $cc !~ /^;/) {
1999                                                 ERROR("space required after that '$op' $at\n" . $hereptr);
2000                                         }
2001
2002                                 # // is a comment
2003                                 } elsif ($op eq '//') {
2004
2005                                 # Ignore : used in class declaration in C++
2006                                 } elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2007                                                  $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2008
2009                                 # No spaces for:
2010                                 #   ->
2011                                 #   :   when part of a bitfield
2012                                 } elsif ($op eq '->' || $opv eq ':B') {
2013                                         if ($ctx =~ /Wx.|.xW/) {
2014                                                 ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2015                                         }
2016
2017                                 # , must have a space on the right.
2018                                 # not required when having a single },{ on one line
2019                                 } elsif ($op eq ',') {
2020                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2021                                             ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
2022                                                 ERROR("space required after that '$op' $at\n" . $hereptr);
2023                                         }
2024
2025                                 # '*' as part of a type definition -- reported already.
2026                                 } elsif ($opv eq '*_') {
2027                                         #warn "'*' is part of type\n";
2028
2029                                 # unary operators should have a space before and
2030                                 # none after.  May be left adjacent to another
2031                                 # unary operator, or a cast
2032                                 } elsif ($op eq '!' || $op eq '~' ||
2033                                          $opv eq '*U' || $opv eq '-U' ||
2034                                          $opv eq '&U' || $opv eq '&&U') {
2035                                         if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2036                                                 # '~' used as a name of Destructor
2037
2038                                         } elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2039                                                 ERROR("space required before that '$op' $at\n" . $hereptr);
2040                                         }
2041                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2042                                                 # A unary '*' may be const
2043
2044                                         } elsif ($ctx =~ /.xW/) {
2045                                                 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2046                                         }
2047
2048                                 # unary ++ and unary -- are allowed no space on one side.
2049                                 } elsif ($op eq '++' or $op eq '--') {
2050                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2051                                                 ERROR("space required one side of that '$op' $at\n" . $hereptr);
2052                                         }
2053                                         if ($ctx =~ /Wx[BE]/ ||
2054                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2055                                                 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2056                                         }
2057                                         if ($ctx =~ /ExW/) {
2058                                                 ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2059                                         }
2060
2061                                 # A colon needs no spaces before when it is
2062                                 # terminating a case value or a label.
2063                                 } elsif ($opv eq ':C' || $opv eq ':L') {
2064                                         if ($ctx =~ /Wx./) {
2065                                                 ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2066                                         }
2067
2068                                 # All the others need spaces both sides.
2069                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
2070                                         my $ok = 0;
2071
2072                                         if ($realfile =~ /\.cpp|\.h$/) {
2073                                                 # Ignore template arguments <...> in C++
2074                                                 if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2075                                                         $ok = 1;
2076                                                 }
2077
2078                                                 # Ignore :: in C++
2079                                                 if ($op eq '::') {
2080                                                         $ok = 1;
2081                                                 }
2082                                         }
2083
2084                                         # Ignore email addresses <foo@bar>
2085                                         if (($op eq '<' &&
2086                                              $cc =~ /^\S+\@\S+>/) ||
2087                                             ($op eq '>' &&
2088                                              $ca =~ /<\S+\@\S+$/))
2089                                         {
2090                                                 $ok = 1;
2091                                         }
2092
2093                                         # Ignore ?:
2094                                         if (($opv eq ':O' && $ca =~ /\?$/) ||
2095                                             ($op eq '?' && $cc =~ /^:/)) {
2096                                                 $ok = 1;
2097                                         }
2098
2099                                         if ($ok == 0) {
2100                                                 ERROR("spaces required around that '$op' $at\n" . $hereptr);
2101                                         }
2102                                 }
2103                                 $off += length($elements[$n + 1]);
2104                         }
2105                 }
2106
2107 #need space before brace following if, while, etc
2108                 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2109                     $line =~ /do\{/) {
2110                         ERROR("space required before the open brace '{'\n" . $herecurr);
2111                 }
2112
2113 # closing brace should have a space following it when it has anything
2114 # on the line
2115                 if ($line =~ /}(?!(?:,|;|\)))\S/) {
2116                         ERROR("space required after that close brace '}'\n" . $herecurr);
2117                 }
2118
2119 # check spacing on square brackets
2120                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2121                         ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2122                 }
2123                 if ($line =~ /\s\]/) {
2124                         ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2125                 }
2126
2127 # check spacing on parentheses
2128                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2129                     $line !~ /for\s*\(\s+;/) {
2130                         ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2131                 }
2132                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2133                     $line !~ /for\s*\(.*;\s+\)/ &&
2134                     $line !~ /:\s+\)/) {
2135                         ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2136                 }
2137
2138 # Return is not a function.
2139                 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2140                         my $spacing = $1;
2141                         my $value = $2;
2142
2143                         # Flatten any parentheses
2144                         $value =~ s/\(/ \(/g;
2145                         $value =~ s/\)/\) /g;
2146                         while ($value =~ s/\[[^\{\}]*\]/1/ ||
2147                                $value !~ /(?:$Ident|-?$Constant)\s*
2148                                              $Compare\s*
2149                                              (?:$Ident|-?$Constant)/x &&
2150                                $value =~ s/\([^\(\)]*\)/1/) {
2151                         }
2152 #print "value<$value>\n";
2153                         if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2154                                 ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2155
2156                         } elsif ($spacing !~ /\s+/) {
2157                                 ERROR("space required before the open parenthesis '('\n" . $herecurr);
2158                         }
2159                 }
2160 # Return of what appears to be an errno should normally be -'ve
2161                 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2162                         my $name = $1;
2163                         if ($name ne 'EOF' && $name ne 'ERROR') {
2164                                 ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2165                         }
2166                 }
2167
2168 # Need a space before open parenthesis after if, while etc
2169                 if ($line=~/\b(if|while|for|switch)\(/) {
2170                         ERROR("space required before the open parenthesis '('\n" . $herecurr);
2171                 }
2172
2173 # Check for illegal assignment in if conditional -- and check for trailing
2174 # statements after the conditional.
2175                 if ($line =~ /do\s*(?!{)/) {
2176                         my ($stat_next) = ctx_statement_block($line_nr_next,
2177                                                 $remain_next, $off_next);
2178                         $stat_next =~ s/\n./\n /g;
2179                         ##print "stat<$stat> stat_next<$stat_next>\n";
2180
2181                         if ($stat_next =~ /^\s*while\b/) {
2182                                 # If the statement carries leading newlines,
2183                                 # then count those as offsets.
2184                                 my ($whitespace) =
2185                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2186                                 my $offset =
2187                                         statement_rawlines($whitespace) - 1;
2188
2189                                 $suppress_whiletrailers{$line_nr_next +
2190                                                                 $offset} = 1;
2191                         }
2192                 }
2193                 if (!defined $suppress_whiletrailers{$linenr} &&
2194                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2195                         my ($s, $c) = ($stat, $cond);
2196
2197                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2198                                 ERROR("do not use assignment in if condition\n" . $herecurr);
2199                         }
2200
2201                         # Find out what is on the end of the line after the
2202                         # conditional.
2203                         substr($s, 0, length($c), '');
2204                         $s =~ s/\n.*//g;
2205                         $s =~ s/$;//g;  # Remove any comments
2206                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2207                             $c !~ /}\s*while\s*/)
2208                         {
2209                                 # Find out how long the conditional actually is.
2210                                 my @newlines = ($c =~ /\n/gs);
2211                                 my $cond_lines = 1 + $#newlines;
2212                                 my $stat_real = '';
2213
2214                                 $stat_real = raw_line($linenr, $cond_lines)
2215                                                         . "\n" if ($cond_lines);
2216                                 if (defined($stat_real) && $cond_lines > 1) {
2217                                         $stat_real = "[...]\n$stat_real";
2218                                 }
2219
2220                                 ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2221                         }
2222                 }
2223
2224 # Check for bitwise tests written as boolean
2225                 if ($line =~ /
2226                         (?:
2227                                 (?:\[|\(|\&\&|\|\|)
2228                                 \s*0[xX][0-9]+\s*
2229                                 (?:\&\&|\|\|)
2230                         |
2231                                 (?:\&\&|\|\|)
2232                                 \s*0[xX][0-9]+\s*
2233                                 (?:\&\&|\|\||\)|\])
2234                         )/x)
2235                 {
2236                         ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2237                 }
2238
2239 # if and else should not have general statements after it
2240                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2241                         my $s = $1;
2242                         $s =~ s/$;//g;  # Remove any comments
2243                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2244                                 ERROR("trailing statements should be on next line\n" . $herecurr);
2245                         }
2246                 }
2247 # if should not continue a brace
2248                 if ($line =~ /}\s*if\b/) {
2249                         ERROR("trailing statements should be on next line\n" .
2250                                 $herecurr);
2251                 }
2252 # case and default should not have general statements after them
2253                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2254                     $line !~ /\G(?:
2255                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2256                         \s*return\s+
2257                     )/xg)
2258                 {
2259                         ERROR("trailing statements should be on next line\n" . $herecurr);
2260                 }
2261
2262                 # Check for }<nl>else {, these must be at the same
2263                 # indent level to be relevant to each other.
2264                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2265                                                 $previndent == $indent) {
2266                         ERROR("else should follow close brace '}'\n" . $hereprev);
2267                 }
2268
2269                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2270                                                 $previndent == $indent) {
2271                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2272
2273                         # Find out what is on the end of the line after the
2274                         # conditional.
2275                         substr($s, 0, length($c), '');
2276                         $s =~ s/\n.*//g;
2277
2278                         if ($s =~ /^\s*;/) {
2279                                 ERROR("while should follow close brace '}'\n" . $hereprev);
2280                         }
2281                 }
2282
2283 #studly caps, commented out until figure out how to distinguish between use of existing and adding new
2284 #               if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2285 #                   print "No studly caps, use _\n";
2286 #                   print "$herecurr";
2287 #                   $clean = 0;
2288 #               }
2289
2290 #no spaces allowed after \ in define
2291                 if ($line=~/\#\s*define.*\\\s$/) {
2292                         ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2293                 }
2294
2295 # multi-statement macros should be enclosed in a do while loop, grab the
2296 # first statement and ensure its the whole macro if its not enclosed
2297 # in a known good container
2298                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
2299                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2300                         my $ln = $linenr;
2301                         my $cnt = $realcnt;
2302                         my ($off, $dstat, $dcond, $rest);
2303                         my $ctx = '';
2304
2305                         my $args = defined($1);
2306
2307                         # Find the end of the macro and limit our statement
2308                         # search to that.
2309                         while ($cnt > 0 && defined $lines[$ln - 1] &&
2310                                 $lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2311                         {
2312                                 $ctx .= $rawlines[$ln - 1] . "\n";
2313                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2314                                 $ln++;
2315                         }
2316                         $ctx .= $rawlines[$ln - 1];
2317
2318                         ($dstat, $dcond, $ln, $cnt, $off) =
2319                                 ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2320                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2321                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2322
2323                         # Extract the remainder of the define (if any) and
2324                         # rip off surrounding spaces, and trailing \'s.
2325                         $rest = '';
2326                         while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2327                                 #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2328                                 if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2329                                         $rest .= substr($lines[$ln - 1], $off) . "\n";
2330                                         $cnt--;
2331                                 }
2332                                 $ln++;
2333                                 $off = 0;
2334                         }
2335                         $rest =~ s/\\\n.//g;
2336                         $rest =~ s/^\s*//s;
2337                         $rest =~ s/\s*$//s;
2338
2339                         # Clean up the original statement.
2340                         if ($args) {
2341                                 substr($dstat, 0, length($dcond), '');
2342                         } else {
2343                                 $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2344                         }
2345                         $dstat =~ s/$;//g;
2346                         $dstat =~ s/\\\n.//g;
2347                         $dstat =~ s/^\s*//s;
2348                         $dstat =~ s/\s*$//s;
2349
2350                         # Flatten any parentheses and braces
2351                         while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2352                                $dstat =~ s/\{[^\{\}]*\}/1/ ||
2353                                $dstat =~ s/\[[^\{\}]*\]/1/)
2354                         {
2355                         }
2356
2357                         my $exceptions = qr{
2358                                 $Declare|
2359                                 module_param_named|
2360                                 MODULE_PARAM_DESC|
2361                                 DECLARE_PER_CPU|
2362                                 DEFINE_PER_CPU|
2363                                 __typeof__\(|
2364                                 union|
2365                                 struct|
2366                                 \.$Ident\s*=\s*|
2367                                 ^\"|\"$
2368                         }x;
2369                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2370                         if ($rest ne '' && $rest ne ',') {
2371                                 if ($rest !~ /while\s*\(/ &&
2372                                     $dstat !~ /$exceptions/)
2373                                 {
2374                                         ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2375                                 }
2376
2377                         } elsif ($ctx !~ /;/) {
2378                                 if ($dstat ne '' &&
2379                                     $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2380                                     $dstat !~ /$exceptions/ &&
2381                                     $dstat !~ /^\.$Ident\s*=/ &&
2382                                     $dstat =~ /$Operators/)
2383                                 {
2384                                         ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2385                                 }
2386                         }
2387                 }
2388
2389 # check for missing bracing around if etc
2390                 if ($line =~ /(^.*)\b(?:if|while|for)\b/ &&
2391                         $line !~ /\#\s*if/) {
2392                         my $allowed = 0;
2393
2394                         # Check the pre-context.
2395                         if ($line =~ /(\}.*?)$/) {
2396                                 my $pre = $1;
2397
2398                                 if ($line !~ /else/) {
2399                                         print "APW: ALLOWED: pre<$pre> line<$line>\n"
2400                                                 if $dbg_adv_apw;
2401                                         $allowed = 1;
2402                                 }
2403                         }
2404                         my ($level, $endln, @chunks) =
2405                                 ctx_statement_full($linenr, $realcnt, 1);
2406                         if ($dbg_adv_apw) {
2407                             print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2408                             print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2409                                 if $#chunks >= 1;
2410                         }
2411                         if ($#chunks >= 0 && $level == 0) {
2412                                 my $seen = 0;
2413                                 my $herectx = $here . "\n";
2414                                 my $ln = $linenr - 1;
2415                                 for my $chunk (@chunks) {
2416                                         my ($cond, $block) = @{$chunk};
2417
2418                                         # If the condition carries leading newlines, then count those as offsets.
2419                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2420                                         my $offset = statement_rawlines($whitespace) - 1;
2421
2422                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2423
2424                                         # We have looked at and allowed this specific line.
2425                                         $suppress_ifbraces{$ln + $offset} = 1;
2426
2427                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2428                                         $ln += statement_rawlines($block) - 1;
2429
2430                                         substr($block, 0, length($cond), '');
2431
2432                                         my $spaced_block = $block;
2433                                         $spaced_block =~ s/\n\+/ /g;
2434
2435                                         $seen++ if ($spaced_block =~ /^\s*\{/);
2436
2437                                         print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2438                                             if $dbg_adv_apw;
2439                                         if (statement_lines($cond) > 1) {
2440                                             print "APW: ALLOWED: cond<$cond>\n"
2441                                                 if $dbg_adv_apw;
2442                                             $allowed = 1;
2443                                         }
2444                                         if ($block =~/\b(?:if|for|while)\b/) {
2445                                             print "APW: ALLOWED: block<$block>\n"
2446                                                 if $dbg_adv_apw;
2447                                             $allowed = 1;
2448                                         }
2449                                         if (statement_block_size($block) > 1) {
2450                                             print "APW: ALLOWED: lines block<$block>\n"
2451                                                 if $dbg_adv_apw;
2452                                             $allowed = 1;
2453                                         }
2454                                 }
2455                                 if ($seen != ($#chunks + 1) && !$allowed) {
2456                                         ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2457                                 }
2458                         }
2459                 }
2460                 if (!defined $suppress_ifbraces{$linenr - 1} &&
2461                                         $line =~ /\b(if|while|for|else)\b/ &&
2462                                         $line !~ /\#\s*if/ &&
2463                                         $line !~ /\#\s*else/) {
2464                         my $allowed = 0;
2465
2466                         # Check the pre-context.
2467                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2468                             my $pre = $1;
2469
2470                             if ($line !~ /else/) {
2471                                 print "APW: ALLOWED: pre<$pre> line<$line>\n"
2472                                     if $dbg_adv_apw;
2473                                 $allowed = 1;
2474                             }
2475                         }
2476
2477                         my ($level, $endln, @chunks) =
2478                                 ctx_statement_full($linenr, $realcnt, $-[0]);
2479
2480                         # Check the condition.
2481                         my ($cond, $block) = @{$chunks[0]};
2482                         print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2483                             if $dbg_adv_checking;
2484                         if (defined $cond) {
2485                                 substr($block, 0, length($cond), '');
2486                         }
2487                         if (statement_lines($cond) > 1) {
2488                             print "APW: ALLOWED: cond<$cond>\n"
2489                                 if $dbg_adv_apw;
2490                             $allowed = 1;
2491                         }
2492                         if ($block =~/\b(?:if|for|while)\b/) {
2493                             print "APW: ALLOWED: block<$block>\n"
2494                                 if $dbg_adv_apw;
2495                             $allowed = 1;
2496                         }
2497                         if (statement_block_size($block) > 1) {
2498                             print "APW: ALLOWED: lines block<$block>\n"
2499                                 if $dbg_adv_apw;
2500                             $allowed = 1;
2501                         }
2502                         # Check the post-context.
2503                         if (defined $chunks[1]) {
2504                                 my ($cond, $block) = @{$chunks[1]};
2505                                 if (defined $cond) {
2506                                         substr($block, 0, length($cond), '');
2507                                 }
2508                                 if ($block =~ /^\s*\{/) {
2509                                     print "APW: ALLOWED: chunk-1 block<$block>\n"
2510                                         if $dbg_adv_apw;
2511                                     $allowed = 1;
2512                                 }
2513                         }
2514                         print "DCS: level=$level block<$block> allowed=$allowed\n"
2515                             if $dbg_adv_dcs;
2516                         if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2517                                 my $herectx = $here . "\n";;
2518                                 my $cnt = statement_rawlines($block);
2519
2520                                 for (my $n = 0; $n < $cnt; $n++) {
2521                                         $herectx .= raw_line($linenr, $n) . "\n";;
2522                                 }
2523
2524                                 ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2525                         }
2526                 }
2527
2528 # no volatiles please
2529                 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2530                 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/ &&
2531                     $line !~ /sig_atomic_t/ &&
2532                     !ctx_has_comment($first_line, $linenr)) {
2533                         my $msg = "Use of volatile is usually wrong, please add a comment\n" . $herecurr;
2534                         ERROR($msg);
2535                 }
2536
2537 # warn about #if 0
2538                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2539                         ERROR("if this code is redundant consider removing it\n" .
2540                                 $herecurr);
2541                 }
2542
2543 # check for needless g_free() checks
2544                 if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2545                         my $expr = $1;
2546                         if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2547                                 ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2548                         }
2549                 }
2550
2551 # warn about #ifdefs in C files
2552 #               if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2553 #                       print "#ifdef in C files should be avoided\n";
2554 #                       print "$herecurr";
2555 #                       $clean = 0;
2556 #               }
2557
2558 # warn about spacing in #ifdefs
2559                 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2560                         ERROR("exactly one space required after that #$1\n" . $herecurr);
2561                 }
2562 # check for memory barriers without a comment.
2563                 if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2564                         if (!ctx_has_comment($first_line, $linenr)) {
2565                                 ERROR("memory barrier without comment\n" . $herecurr);
2566                         }
2567                 }
2568 # check of hardware specific defines
2569 # we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2570 # where they might be necessary.
2571                 if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2572                         WARN("architecture specific defines should be avoided\n" .  $herecurr);
2573                 }
2574
2575 # Check that the storage class is at the beginning of a declaration
2576                 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2577                         ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2578                 }
2579
2580 # check the location of the inline attribute, that it is between
2581 # storage class and type.
2582                 if ($line =~ /\b$Type\s+$Inline\b/ ||
2583                     $line =~ /\b$Inline\s+$Storage\b/) {
2584                         ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2585                 }
2586
2587 # check for sizeof(&)
2588                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
2589                         ERROR("sizeof(& should be avoided\n" . $herecurr);
2590                 }
2591
2592 # check for new externs in .c files.
2593                 if ($realfile =~ /\.c$/ && defined $stat &&
2594                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2595                 {
2596                         my $function_name = $1;
2597                         my $paren_space = $2;
2598
2599                         my $s = $stat;
2600                         if (defined $cond) {
2601                                 substr($s, 0, length($cond), '');
2602                         }
2603                         if ($s =~ /^\s*;/ &&
2604                             $function_name ne 'uninitialized_var')
2605                         {
2606                                 ERROR("externs should be avoided in .c files\n" .  $herecurr);
2607                         }
2608
2609                         if ($paren_space =~ /\n/) {
2610                                 ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2611                         }
2612
2613                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
2614                     $stat =~ /^.\s*extern\s+/)
2615                 {
2616                         ERROR("externs should be avoided in .c files\n" .  $herecurr);
2617                 }
2618
2619 # check for pointless casting of g_malloc return
2620                 if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2621                         if ($2 == 'm') {
2622                                 ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2623                         } else {
2624                                 ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2625                         }
2626                 }
2627
2628 # check for gcc specific __FUNCTION__
2629                 if ($line =~ /__FUNCTION__/) {
2630                         ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr);
2631                 }
2632
2633 # recommend g_path_get_* over g_strdup(basename/dirname(...))
2634                 if ($line =~ /\bg_strdup\s*\(\s*(basename|dirname)\s*\(/) {
2635                         WARN("consider using g_path_get_$1() in preference to g_strdup($1())\n" . $herecurr);
2636                 }
2637
2638 # recommend qemu_strto* over strto* for numeric conversions
2639                 if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2640                         ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2641                 }
2642 # recommend sigaction over signal for portability, when establishing a handler
2643                 if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2644                         ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2645                 }
2646 # check for module_init(), use category-specific init macros explicitly please
2647                 if ($line =~ /^module_init\s*\(/) {
2648                         ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2649                 }
2650 # check for various ops structs, ensure they are const.
2651                 my $struct_ops = qr{AIOCBInfo|
2652                                 BdrvActionOps|
2653                                 BlockDevOps|
2654                                 BlockJobDriver|
2655                                 DisplayChangeListenerOps|
2656                                 GraphicHwOps|
2657                                 IDEDMAOps|
2658                                 KVMCapabilityInfo|
2659                                 MemoryRegionIOMMUOps|
2660                                 MemoryRegionOps|
2661                                 MemoryRegionPortio|
2662                                 QEMUFileOps|
2663                                 SCSIBusInfo|
2664                                 SCSIReqOps|
2665                                 Spice[A-Z][a-zA-Z0-9]*Interface|
2666                                 USBDesc[A-Z][a-zA-Z0-9]*|
2667                                 VhostOps|
2668                                 VMStateDescription|
2669                                 VMStateInfo}x;
2670                 if ($line !~ /\bconst\b/ &&
2671                     $line =~ /\b($struct_ops)\b.*=/) {
2672                         ERROR("initializer for struct $1 should normally be const\n" .
2673                                 $herecurr);
2674                 }
2675
2676 # check for %L{u,d,i} in strings
2677                 my $string;
2678                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2679                         $string = substr($rawline, $-[1], $+[1] - $-[1]);
2680                         $string =~ s/%%/__/g;
2681                         if ($string =~ /(?<!%)%L[udi]/) {
2682                                 ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2683                                 last;
2684                         }
2685                 }
2686
2687 # QEMU specific tests
2688                 if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2689                         ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2690                 }
2691
2692 # Qemu error function tests
2693
2694         # Find newlines in error messages
2695         my $qemu_error_funcs = qr{error_setg|
2696                                 error_setg_errno|
2697                                 error_setg_win32|
2698                                 error_setg_file_open|
2699                                 error_set|
2700                                 error_prepend|
2701                                 warn_reportf_err|
2702                                 error_reportf_err|
2703                                 error_vreport|
2704                                 warn_vreport|
2705                                 info_vreport|
2706                                 error_report|
2707                                 warn_report|
2708                                 info_report}x;
2709
2710         if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2711                 ERROR("Error messages should not contain newlines\n" . $herecurr);
2712         }
2713
2714         # Continue checking for error messages that contains newlines. This
2715         # check handles cases where string literals are spread over multiple lines.
2716         # Example:
2717         # error_report("Error msg line #1"
2718         #              "Error msg line #2\n");
2719         my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2720         my $continued_str_literal = qr{\+\s*\".*\"};
2721
2722         if ($rawline =~ /$quoted_newline_regex/) {
2723                 # Backtrack to first line that does not contain only a quoted literal
2724                 # and assume that it is the start of the statement.
2725                 my $i = $linenr - 2;
2726
2727                 while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2728                         $i--;
2729                 }
2730
2731                 if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2732                         ERROR("Error messages should not contain newlines\n" . $herecurr);
2733                 }
2734         }
2735
2736 # check for non-portable libc calls that have portable alternatives in QEMU
2737                 if ($line =~ /\bffs\(/) {
2738                         ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2739                 }
2740                 if ($line =~ /\bffsl\(/) {
2741                         ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2742                 }
2743                 if ($line =~ /\bffsll\(/) {
2744                         ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2745                 }
2746                 if ($line =~ /\bbzero\(/) {
2747                         ERROR("use memset() instead of bzero()\n" . $herecurr);
2748                 }
2749                 my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2750                                                 g_assert_cmpint|
2751                                                 g_assert_cmpuint|
2752                                                 g_assert_cmphex|
2753                                                 g_assert_cmpfloat|
2754                                                 g_assert_true|
2755                                                 g_assert_false|
2756                                                 g_assert_nonnull|
2757                                                 g_assert_null|
2758                                                 g_assert_no_error|
2759                                                 g_assert_error|
2760                                                 g_test_assert_expected_messages|
2761                                                 g_test_trap_assert_passed|
2762                                                 g_test_trap_assert_stdout|
2763                                                 g_test_trap_assert_stdout_unmatched|
2764                                                 g_test_trap_assert_stderr|
2765                                                 g_test_trap_assert_stderr_unmatched}x;
2766                 if ($realfile !~ /^tests\// &&
2767                         $line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2768                         ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
2769                 }
2770         }
2771
2772         # If we have no input at all, then there is nothing to report on
2773         # so just keep quiet.
2774         if ($#rawlines == -1) {
2775                 exit(0);
2776         }
2777
2778         # In mailback mode only produce a report in the negative, for
2779         # things that appear to be patches.
2780         if ($mailback && ($clean == 1 || !$is_patch)) {
2781                 exit(0);
2782         }
2783
2784         # This is not a patch, and we are are in 'no-patch' mode so
2785         # just keep quiet.
2786         if (!$chk_patch && !$is_patch) {
2787                 exit(0);
2788         }
2789
2790         if (!$is_patch) {
2791                 ERROR("Does not appear to be a unified-diff format patch\n");
2792         }
2793         if ($is_patch && $chk_signoff && $signoff == 0) {
2794                 ERROR("Missing Signed-off-by: line(s)\n");
2795         }
2796
2797         print report_dump();
2798         if ($summary && !($clean == 1 && $quiet == 1)) {
2799                 print "$filename " if ($summary_file);
2800                 print "total: $cnt_error errors, $cnt_warn warnings, " .
2801                         "$cnt_lines lines checked\n";
2802                 print "\n" if ($quiet == 0);
2803         }
2804
2805         if ($quiet == 0) {
2806                 # If there were whitespace errors which cleanpatch can fix
2807                 # then suggest that.
2808 #               if ($rpt_cleaners) {
2809 #                       print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2810 #                       print "      scripts/cleanfile\n\n";
2811 #               }
2812         }
2813
2814         if ($clean == 1 && $quiet == 0) {
2815                 print "$vname has no obvious style problems and is ready for submission.\n"
2816         }
2817         if ($clean == 0 && $quiet == 0) {
2818                 print "$vname has style problems, please review.  If any of these errors\n";
2819                 print "are false positives report them to the maintainer, see\n";
2820                 print "CHECKPATCH in MAINTAINERS.\n";
2821         }
2822
2823         return ($no_warnings ? $clean : $cnt_error == 0);
2824 }
This page took 0.201765 seconds and 2 git commands to generate.