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