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