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