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