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