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