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