xref: /openbmc/qemu/scripts/checkpatch.pl (revision 2e1d70b9e03ca3f1c6185b54010bc9e47e0a0d0c)
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;
1436				$tmpline =~ s/($hex[.:\/ ])+$hex//g;
1437
1438				if ($tmpline =~ /(?<!0x)$hex/) {
1439					ERROR("Hex numbers must be prefixed with '0x'\n" .
1440					      $herecurr);
1441				}
1442			}
1443		}
1444
1445# check we are in a valid source file if not then ignore this hunk
1446		next if ($realfile !~ /\.(h|c|cpp|s|S|pl|py|sh)$/);
1447
1448#90 column limit
1449		if ($line =~ /^\+/ &&
1450		    !($line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1451		    $length > 80)
1452		{
1453			if ($length > 90) {
1454				ERROR("line over 90 characters\n" . $herecurr);
1455			} else {
1456				WARN("line over 80 characters\n" . $herecurr);
1457			}
1458		}
1459
1460# check for spaces before a quoted newline
1461		if ($rawline =~ /^.*\".*\s\\n/) {
1462			ERROR("unnecessary whitespace before a quoted newline\n" . $herecurr);
1463		}
1464
1465# check for adding lines without a newline.
1466		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1467			ERROR("adding a line without newline at end of file\n" . $herecurr);
1468		}
1469
1470# check for RCS/CVS revision markers
1471		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|\b)/) {
1472			ERROR("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1473		}
1474
1475# tabs are only allowed in assembly source code, and in
1476# some scripts we imported from other projects.
1477		next if ($realfile =~ /\.(s|S)$/);
1478		next if ($realfile =~ /(checkpatch|get_maintainer|texi2pod)\.pl$/);
1479
1480		if ($rawline =~ /^\+.*\t/) {
1481			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1482			ERROR("code indent should never use tabs\n" . $herevet);
1483			$rpt_cleaners = 1;
1484		}
1485
1486# check we are in a valid C source file if not then ignore this hunk
1487		next if ($realfile !~ /\.(h|c|cpp)$/);
1488
1489# Check for potential 'bare' types
1490		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1491		    $realline_next);
1492		if ($realcnt && $line =~ /.\s*\S/) {
1493			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1494				ctx_statement_block($linenr, $realcnt, 0);
1495			$stat =~ s/\n./\n /g;
1496			$cond =~ s/\n./\n /g;
1497
1498			# Find the real next line.
1499			$realline_next = $line_nr_next;
1500			if (defined $realline_next &&
1501			    (!defined $lines[$realline_next - 1] ||
1502			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1503				$realline_next++;
1504			}
1505
1506			my $s = $stat;
1507			$s =~ s/{.*$//s;
1508
1509			# Ignore goto labels.
1510			if ($s =~ /$Ident:\*$/s) {
1511
1512			# Ignore functions being called
1513			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1514
1515			} elsif ($s =~ /^.\s*else\b/s) {
1516
1517			# declarations always start with types
1518			} 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) {
1519				my $type = $1;
1520				$type =~ s/\s+/ /g;
1521				possible($type, "A:" . $s);
1522
1523			# definitions in global scope can only start with types
1524			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1525				possible($1, "B:" . $s);
1526			}
1527
1528			# any (foo ... *) is a pointer cast, and foo is a type
1529			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1530				possible($1, "C:" . $s);
1531			}
1532
1533			# Check for any sort of function declaration.
1534			# int foo(something bar, other baz);
1535			# void (*store_gdt)(x86_descr_ptr *);
1536			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1537				my ($name_len) = length($1);
1538
1539				my $ctx = $s;
1540				substr($ctx, 0, $name_len + 1, '');
1541				$ctx =~ s/\)[^\)]*$//;
1542
1543				for my $arg (split(/\s*,\s*/, $ctx)) {
1544					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1545
1546						possible($1, "D:" . $s);
1547					}
1548				}
1549			}
1550
1551		}
1552
1553#
1554# Checks which may be anchored in the context.
1555#
1556
1557# Check for switch () and associated case and default
1558# statements should be at the same indent.
1559		if ($line=~/\bswitch\s*\(.*\)/) {
1560			my $err = '';
1561			my $sep = '';
1562			my @ctx = ctx_block_outer($linenr, $realcnt);
1563			shift(@ctx);
1564			for my $ctx (@ctx) {
1565				my ($clen, $cindent) = line_stats($ctx);
1566				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1567							$indent != $cindent) {
1568					$err .= "$sep$ctx\n";
1569					$sep = '';
1570				} else {
1571					$sep = "[...]\n";
1572				}
1573			}
1574			if ($err ne '') {
1575				ERROR("switch and case should be at the same indent\n$hereline$err");
1576			}
1577		}
1578
1579# if/while/etc brace do not go on next line, unless defining a do while loop,
1580# or if that brace on the next line is for something else
1581		if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1582			my $pre_ctx = "$1$2";
1583
1584			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1585			my $ctx_cnt = $realcnt - $#ctx - 1;
1586			my $ctx = join("\n", @ctx);
1587
1588			my $ctx_ln = $linenr;
1589			my $ctx_skip = $realcnt;
1590
1591			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1592					defined $lines[$ctx_ln - 1] &&
1593					$lines[$ctx_ln - 1] =~ /^-/)) {
1594				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1595				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1596				$ctx_ln++;
1597			}
1598
1599			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1600			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1601
1602			# The length of the "previous line" is checked against 80 because it
1603			# includes the + at the beginning of the line (if the actual line has
1604			# 79 or 80 characters, it is no longer possible to add a space and an
1605			# opening brace there)
1606			if ($#ctx == 0 && $ctx !~ /{\s*/ &&
1607			    defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*\{/ &&
1608			    defined($lines[$ctx_ln - 2]) && length($lines[$ctx_ln - 2]) < 80) {
1609				ERROR("that open brace { should be on the previous line\n" .
1610					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1611			}
1612			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1613			    $ctx =~ /\)\s*\;\s*$/ &&
1614			    defined $lines[$ctx_ln - 1])
1615			{
1616				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1617				if ($nindent > $indent) {
1618					ERROR("trailing semicolon indicates no statements, indent implies otherwise\n" .
1619						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1620				}
1621			}
1622		}
1623
1624# Check relative indent for conditionals and blocks.
1625		if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1626			my ($s, $c) = ($stat, $cond);
1627
1628			substr($s, 0, length($c), '');
1629
1630			# Make sure we remove the line prefixes as we have
1631			# none on the first line, and are going to readd them
1632			# where necessary.
1633			$s =~ s/\n./\n/gs;
1634
1635			# Find out how long the conditional actually is.
1636			my @newlines = ($c =~ /\n/gs);
1637			my $cond_lines = 1 + $#newlines;
1638
1639			# We want to check the first line inside the block
1640			# starting at the end of the conditional, so remove:
1641			#  1) any blank line termination
1642			#  2) any opening brace { on end of the line
1643			#  3) any do (...) {
1644			my $continuation = 0;
1645			my $check = 0;
1646			$s =~ s/^.*\bdo\b//;
1647			$s =~ s/^\s*\{//;
1648			if ($s =~ s/^\s*\\//) {
1649				$continuation = 1;
1650			}
1651			if ($s =~ s/^\s*?\n//) {
1652				$check = 1;
1653				$cond_lines++;
1654			}
1655
1656			# Also ignore a loop construct at the end of a
1657			# preprocessor statement.
1658			if (($prevline =~ /^.\s*#\s*define\s/ ||
1659			    $prevline =~ /\\\s*$/) && $continuation == 0) {
1660				$check = 0;
1661			}
1662
1663			my $cond_ptr = -1;
1664			$continuation = 0;
1665			while ($cond_ptr != $cond_lines) {
1666				$cond_ptr = $cond_lines;
1667
1668				# If we see an #else/#elif then the code
1669				# is not linear.
1670				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1671					$check = 0;
1672				}
1673
1674				# Ignore:
1675				#  1) blank lines, they should be at 0,
1676				#  2) preprocessor lines, and
1677				#  3) labels.
1678				if ($continuation ||
1679				    $s =~ /^\s*?\n/ ||
1680				    $s =~ /^\s*#\s*?/ ||
1681				    $s =~ /^\s*$Ident\s*:/) {
1682					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1683					if ($s =~ s/^.*?\n//) {
1684						$cond_lines++;
1685					}
1686				}
1687			}
1688
1689			my (undef, $sindent) = line_stats("+" . $s);
1690			my $stat_real = raw_line($linenr, $cond_lines);
1691
1692			# Check if either of these lines are modified, else
1693			# this is not this patch's fault.
1694			if (!defined($stat_real) ||
1695			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1696				$check = 0;
1697			}
1698			if (defined($stat_real) && $cond_lines > 1) {
1699				$stat_real = "[...]\n$stat_real";
1700			}
1701
1702			#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";
1703
1704			if ($check && (($sindent % 4) != 0 ||
1705			    ($sindent <= $indent && $s ne ''))) {
1706				ERROR("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1707			}
1708		}
1709
1710		# Track the 'values' across context and added lines.
1711		my $opline = $line; $opline =~ s/^./ /;
1712		my ($curr_values, $curr_vars) =
1713				annotate_values($opline . "\n", $prev_values);
1714		$curr_values = $prev_values . $curr_values;
1715		if ($dbg_values) {
1716			my $outline = $opline; $outline =~ s/\t/ /g;
1717			print "$linenr > .$outline\n";
1718			print "$linenr > $curr_values\n";
1719			print "$linenr >  $curr_vars\n";
1720		}
1721		$prev_values = substr($curr_values, -1);
1722
1723#ignore lines not being added
1724		if ($line=~/^[^\+]/) {next;}
1725
1726# TEST: allow direct testing of the type matcher.
1727		if ($dbg_type) {
1728			if ($line =~ /^.\s*$Declare\s*$/) {
1729				ERROR("TEST: is type\n" . $herecurr);
1730			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1731				ERROR("TEST: is not type ($1 is)\n". $herecurr);
1732			}
1733			next;
1734		}
1735# TEST: allow direct testing of the attribute matcher.
1736		if ($dbg_attr) {
1737			if ($line =~ /^.\s*$Modifier\s*$/) {
1738				ERROR("TEST: is attr\n" . $herecurr);
1739			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1740				ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1741			}
1742			next;
1743		}
1744
1745# check for initialisation to aggregates open brace on the next line
1746		if ($line =~ /^.\s*\{/ &&
1747		    $prevline =~ /(?:^|[^=])=\s*$/) {
1748			ERROR("that open brace { should be on the previous line\n" . $hereprev);
1749		}
1750
1751#
1752# Checks which are anchored on the added line.
1753#
1754
1755# check for malformed paths in #include statements (uses RAW line)
1756		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1757			my $path = $1;
1758			if ($path =~ m{//}) {
1759				ERROR("malformed #include filename\n" .
1760					$herecurr);
1761			}
1762		}
1763
1764# no C99 // comments
1765		if ($line =~ m{//}) {
1766			ERROR("do not use C99 // comments\n" . $herecurr);
1767		}
1768		# Remove C99 comments.
1769		$line =~ s@//.*@@;
1770		$opline =~ s@//.*@@;
1771
1772# check for global initialisers.
1773		if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
1774			ERROR("do not initialise globals to 0 or NULL\n" .
1775				$herecurr);
1776		}
1777# check for static initialisers.
1778		if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
1779			ERROR("do not initialise statics to 0 or NULL\n" .
1780				$herecurr);
1781		}
1782
1783# * goes on variable not on type
1784		# (char*[ const])
1785		if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1786			my ($from, $to) = ($1, $1);
1787
1788			# Should start with a space.
1789			$to =~ s/^(\S)/ $1/;
1790			# Should not end with a space.
1791			$to =~ s/\s+$//;
1792			# '*'s should not have spaces between.
1793			while ($to =~ s/\*\s+\*/\*\*/) {
1794			}
1795
1796			#print "from<$from> to<$to>\n";
1797			if ($from ne $to) {
1798				ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr);
1799			}
1800		} elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1801			my ($from, $to, $ident) = ($1, $1, $2);
1802
1803			# Should start with a space.
1804			$to =~ s/^(\S)/ $1/;
1805			# Should not end with a space.
1806			$to =~ s/\s+$//;
1807			# '*'s should not have spaces between.
1808			while ($to =~ s/\*\s+\*/\*\*/) {
1809			}
1810			# Modifiers should have spaces.
1811			$to =~ s/(\b$Modifier$)/$1 /;
1812
1813			#print "from<$from> to<$to> ident<$ident>\n";
1814			if ($from ne $to && $ident !~ /^$Modifier$/) {
1815				ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr);
1816			}
1817		}
1818
1819# function brace can't be on same line, except for #defines of do while,
1820# or if closed on same line
1821		if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
1822		    !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
1823			ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
1824		}
1825
1826# open braces for enum, union and struct go on the same line.
1827		if ($line =~ /^.\s*\{/ &&
1828		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
1829			ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
1830		}
1831
1832# missing space after union, struct or enum definition
1833		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
1834		    ERROR("missing space after $1 definition\n" . $herecurr);
1835		}
1836
1837# check for spacing round square brackets; allowed:
1838#  1. with a type on the left -- int [] a;
1839#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
1840#  3. inside a curly brace -- = { [0...10] = 5 }
1841#  4. after a comma -- [1] = 5, [2] = 6
1842#  5. in a macro definition -- #define abc(x) [x] = y
1843		while ($line =~ /(.*?\s)\[/g) {
1844			my ($where, $prefix) = ($-[1], $1);
1845			if ($prefix !~ /$Type\s+$/ &&
1846			    ($where != 0 || $prefix !~ /^.\s+$/) &&
1847			    $prefix !~ /{\s+$/ &&
1848			    $prefix !~ /\#\s*define[^(]*\([^)]*\)\s+$/ &&
1849			    $prefix !~ /,\s+$/) {
1850				ERROR("space prohibited before open square bracket '['\n" . $herecurr);
1851			}
1852		}
1853
1854# check for spaces between functions and their parentheses.
1855		while ($line =~ /($Ident)\s+\(/g) {
1856			my $name = $1;
1857			my $ctx_before = substr($line, 0, $-[1]);
1858			my $ctx = "$ctx_before$name";
1859
1860			# Ignore those directives where spaces _are_ permitted.
1861			if ($name =~ /^(?:
1862				if|for|while|switch|return|case|
1863				volatile|__volatile__|coroutine_fn|
1864				__attribute__|format|__extension__|
1865				asm|__asm__)$/x)
1866			{
1867
1868			# Ignore 'catch (...)' in C++
1869			} elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
1870
1871			# cpp #define statements have non-optional spaces, ie
1872			# if there is a space between the name and the open
1873			# parenthesis it is simply not a parameter group.
1874			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
1875
1876			# cpp #elif statement condition may start with a (
1877			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
1878
1879			# If this whole things ends with a type its most
1880			# likely a typedef for a function.
1881			} elsif ($ctx =~ /$Type$/) {
1882
1883			} else {
1884				ERROR("space prohibited between function name and open parenthesis '('\n" . $herecurr);
1885			}
1886		}
1887# Check operator spacing.
1888		if (!($line=~/\#\s*include/)) {
1889			my $ops = qr{
1890				<<=|>>=|<=|>=|==|!=|
1891				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
1892				=>|->|<<|>>|<|>|=|!|~|
1893				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
1894				\?|::|:
1895			}x;
1896			my @elements = split(/($ops|;)/, $opline);
1897			my $off = 0;
1898
1899			my $blank = copy_spacing($opline);
1900
1901			for (my $n = 0; $n < $#elements; $n += 2) {
1902				$off += length($elements[$n]);
1903
1904				# Pick up the preceding and succeeding characters.
1905				my $ca = substr($opline, 0, $off);
1906				my $cc = '';
1907				if (length($opline) >= ($off + length($elements[$n + 1]))) {
1908					$cc = substr($opline, $off + length($elements[$n + 1]));
1909				}
1910				my $cb = "$ca$;$cc";
1911
1912				my $a = '';
1913				$a = 'V' if ($elements[$n] ne '');
1914				$a = 'W' if ($elements[$n] =~ /\s$/);
1915				$a = 'C' if ($elements[$n] =~ /$;$/);
1916				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
1917				$a = 'O' if ($elements[$n] eq '');
1918				$a = 'E' if ($ca =~ /^\s*$/);
1919
1920				my $op = $elements[$n + 1];
1921
1922				my $c = '';
1923				if (defined $elements[$n + 2]) {
1924					$c = 'V' if ($elements[$n + 2] ne '');
1925					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
1926					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
1927					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
1928					$c = 'O' if ($elements[$n + 2] eq '');
1929					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
1930				} else {
1931					$c = 'E';
1932				}
1933
1934				my $ctx = "${a}x${c}";
1935
1936				my $at = "(ctx:$ctx)";
1937
1938				my $ptr = substr($blank, 0, $off) . "^";
1939				my $hereptr = "$hereline$ptr\n";
1940
1941				# Pull out the value of this operator.
1942				my $op_type = substr($curr_values, $off + 1, 1);
1943
1944				# Get the full operator variant.
1945				my $opv = $op . substr($curr_vars, $off, 1);
1946
1947				# Ignore operators passed as parameters.
1948				if ($op_type ne 'V' &&
1949				    $ca =~ /\s$/ && $cc =~ /^\s*,/) {
1950
1951#				# Ignore comments
1952#				} elsif ($op =~ /^$;+$/) {
1953
1954				# ; should have either the end of line or a space or \ after it
1955				} elsif ($op eq ';') {
1956					if ($ctx !~ /.x[WEBC]/ &&
1957					    $cc !~ /^\\/ && $cc !~ /^;/) {
1958						ERROR("space required after that '$op' $at\n" . $hereptr);
1959					}
1960
1961				# // is a comment
1962				} elsif ($op eq '//') {
1963
1964				# Ignore : used in class declaration in C++
1965				} elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
1966						 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
1967
1968				# No spaces for:
1969				#   ->
1970				#   :   when part of a bitfield
1971				} elsif ($op eq '->' || $opv eq ':B') {
1972					if ($ctx =~ /Wx.|.xW/) {
1973						ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
1974					}
1975
1976				# , must have a space on the right.
1977                                # not required when having a single },{ on one line
1978				} elsif ($op eq ',') {
1979					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
1980                                            ($elements[$n] . $elements[$n + 2]) !~ " *}\\{") {
1981						ERROR("space required after that '$op' $at\n" . $hereptr);
1982					}
1983
1984				# '*' as part of a type definition -- reported already.
1985				} elsif ($opv eq '*_') {
1986					#warn "'*' is part of type\n";
1987
1988				# unary operators should have a space before and
1989				# none after.  May be left adjacent to another
1990				# unary operator, or a cast
1991				} elsif ($op eq '!' || $op eq '~' ||
1992					 $opv eq '*U' || $opv eq '-U' ||
1993					 $opv eq '&U' || $opv eq '&&U') {
1994					if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
1995						# '~' used as a name of Destructor
1996
1997					} elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
1998						ERROR("space required before that '$op' $at\n" . $hereptr);
1999					}
2000					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2001						# A unary '*' may be const
2002
2003					} elsif ($ctx =~ /.xW/) {
2004						ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2005					}
2006
2007				# unary ++ and unary -- are allowed no space on one side.
2008				} elsif ($op eq '++' or $op eq '--') {
2009					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2010						ERROR("space required one side of that '$op' $at\n" . $hereptr);
2011					}
2012					if ($ctx =~ /Wx[BE]/ ||
2013					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2014						ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2015					}
2016					if ($ctx =~ /ExW/) {
2017						ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2018					}
2019
2020				# A colon needs no spaces before when it is
2021				# terminating a case value or a label.
2022				} elsif ($opv eq ':C' || $opv eq ':L') {
2023					if ($ctx =~ /Wx./) {
2024						ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2025					}
2026
2027				# All the others need spaces both sides.
2028				} elsif ($ctx !~ /[EWC]x[CWE]/) {
2029					my $ok = 0;
2030
2031					if ($realfile =~ /\.cpp|\.h$/) {
2032						# Ignore template arguments <...> in C++
2033						if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2034							$ok = 1;
2035						}
2036
2037						# Ignore :: in C++
2038						if ($op eq '::') {
2039							$ok = 1;
2040						}
2041					}
2042
2043					# Ignore email addresses <foo@bar>
2044					if (($op eq '<' &&
2045					     $cc =~ /^\S+\@\S+>/) ||
2046					    ($op eq '>' &&
2047					     $ca =~ /<\S+\@\S+$/))
2048					{
2049						$ok = 1;
2050					}
2051
2052					# Ignore ?:
2053					if (($opv eq ':O' && $ca =~ /\?$/) ||
2054					    ($op eq '?' && $cc =~ /^:/)) {
2055						$ok = 1;
2056					}
2057
2058					if ($ok == 0) {
2059						ERROR("spaces required around that '$op' $at\n" . $hereptr);
2060					}
2061				}
2062				$off += length($elements[$n + 1]);
2063			}
2064		}
2065
2066#need space before brace following if, while, etc
2067		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
2068		    $line =~ /do\{/) {
2069			ERROR("space required before the open brace '{'\n" . $herecurr);
2070		}
2071
2072# closing brace should have a space following it when it has anything
2073# on the line
2074		if ($line =~ /}(?!(?:,|;|\)))\S/) {
2075			ERROR("space required after that close brace '}'\n" . $herecurr);
2076		}
2077
2078# check spacing on square brackets
2079		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2080			ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2081		}
2082		if ($line =~ /\s\]/) {
2083			ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2084		}
2085
2086# check spacing on parentheses
2087		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2088		    $line !~ /for\s*\(\s+;/) {
2089			ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2090		}
2091		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2092		    $line !~ /for\s*\(.*;\s+\)/ &&
2093		    $line !~ /:\s+\)/) {
2094			ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2095		}
2096
2097# Return is not a function.
2098		if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2099			my $spacing = $1;
2100			my $value = $2;
2101
2102			# Flatten any parentheses
2103			$value =~ s/\(/ \(/g;
2104			$value =~ s/\)/\) /g;
2105			while ($value =~ s/\[[^\{\}]*\]/1/ ||
2106			       $value !~ /(?:$Ident|-?$Constant)\s*
2107					     $Compare\s*
2108					     (?:$Ident|-?$Constant)/x &&
2109			       $value =~ s/\([^\(\)]*\)/1/) {
2110			}
2111#print "value<$value>\n";
2112			if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2113				ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2114
2115			} elsif ($spacing !~ /\s+/) {
2116				ERROR("space required before the open parenthesis '('\n" . $herecurr);
2117			}
2118		}
2119# Return of what appears to be an errno should normally be -'ve
2120		if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2121			my $name = $1;
2122			if ($name ne 'EOF' && $name ne 'ERROR') {
2123				ERROR("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2124			}
2125		}
2126
2127# Need a space before open parenthesis after if, while etc
2128		if ($line=~/\b(if|while|for|switch)\(/) {
2129			ERROR("space required before the open parenthesis '('\n" . $herecurr);
2130		}
2131
2132# Check for illegal assignment in if conditional -- and check for trailing
2133# statements after the conditional.
2134		if ($line =~ /do\s*(?!{)/) {
2135			my ($stat_next) = ctx_statement_block($line_nr_next,
2136						$remain_next, $off_next);
2137			$stat_next =~ s/\n./\n /g;
2138			##print "stat<$stat> stat_next<$stat_next>\n";
2139
2140			if ($stat_next =~ /^\s*while\b/) {
2141				# If the statement carries leading newlines,
2142				# then count those as offsets.
2143				my ($whitespace) =
2144					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2145				my $offset =
2146					statement_rawlines($whitespace) - 1;
2147
2148				$suppress_whiletrailers{$line_nr_next +
2149								$offset} = 1;
2150			}
2151		}
2152		if (!defined $suppress_whiletrailers{$linenr} &&
2153		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2154			my ($s, $c) = ($stat, $cond);
2155
2156			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2157				ERROR("do not use assignment in if condition\n" . $herecurr);
2158			}
2159
2160			# Find out what is on the end of the line after the
2161			# conditional.
2162			substr($s, 0, length($c), '');
2163			$s =~ s/\n.*//g;
2164			$s =~ s/$;//g; 	# Remove any comments
2165			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2166			    $c !~ /}\s*while\s*/)
2167			{
2168				# Find out how long the conditional actually is.
2169				my @newlines = ($c =~ /\n/gs);
2170				my $cond_lines = 1 + $#newlines;
2171				my $stat_real = '';
2172
2173				$stat_real = raw_line($linenr, $cond_lines)
2174							. "\n" if ($cond_lines);
2175				if (defined($stat_real) && $cond_lines > 1) {
2176					$stat_real = "[...]\n$stat_real";
2177				}
2178
2179				ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2180			}
2181		}
2182
2183# Check for bitwise tests written as boolean
2184		if ($line =~ /
2185			(?:
2186				(?:\[|\(|\&\&|\|\|)
2187				\s*0[xX][0-9]+\s*
2188				(?:\&\&|\|\|)
2189			|
2190				(?:\&\&|\|\|)
2191				\s*0[xX][0-9]+\s*
2192				(?:\&\&|\|\||\)|\])
2193			)/x)
2194		{
2195			ERROR("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2196		}
2197
2198# if and else should not have general statements after it
2199		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2200			my $s = $1;
2201			$s =~ s/$;//g; 	# Remove any comments
2202			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2203				ERROR("trailing statements should be on next line\n" . $herecurr);
2204			}
2205		}
2206# if should not continue a brace
2207		if ($line =~ /}\s*if\b/) {
2208			ERROR("trailing statements should be on next line\n" .
2209				$herecurr);
2210		}
2211# case and default should not have general statements after them
2212		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2213		    $line !~ /\G(?:
2214			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2215			\s*return\s+
2216		    )/xg)
2217		{
2218			ERROR("trailing statements should be on next line\n" . $herecurr);
2219		}
2220
2221		# Check for }<nl>else {, these must be at the same
2222		# indent level to be relevant to each other.
2223		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2224						$previndent == $indent) {
2225			ERROR("else should follow close brace '}'\n" . $hereprev);
2226		}
2227
2228		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2229						$previndent == $indent) {
2230			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2231
2232			# Find out what is on the end of the line after the
2233			# conditional.
2234			substr($s, 0, length($c), '');
2235			$s =~ s/\n.*//g;
2236
2237			if ($s =~ /^\s*;/) {
2238				ERROR("while should follow close brace '}'\n" . $hereprev);
2239			}
2240		}
2241
2242#studly caps, commented out until figure out how to distinguish between use of existing and adding new
2243#		if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2244#		    print "No studly caps, use _\n";
2245#		    print "$herecurr";
2246#		    $clean = 0;
2247#		}
2248
2249#no spaces allowed after \ in define
2250		if ($line=~/\#\s*define.*\\\s$/) {
2251			ERROR("Whitespace after \\ makes next lines useless\n" . $herecurr);
2252		}
2253
2254# multi-statement macros should be enclosed in a do while loop, grab the
2255# first statement and ensure its the whole macro if its not enclosed
2256# in a known good container
2257		if ($realfile !~ m@/vmlinux.lds.h$@ &&
2258		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2259			my $ln = $linenr;
2260			my $cnt = $realcnt;
2261			my ($off, $dstat, $dcond, $rest);
2262			my $ctx = '';
2263
2264			my $args = defined($1);
2265
2266			# Find the end of the macro and limit our statement
2267			# search to that.
2268			while ($cnt > 0 && defined $lines[$ln - 1] &&
2269				$lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2270			{
2271				$ctx .= $rawlines[$ln - 1] . "\n";
2272				$cnt-- if ($lines[$ln - 1] !~ /^-/);
2273				$ln++;
2274			}
2275			$ctx .= $rawlines[$ln - 1];
2276
2277			($dstat, $dcond, $ln, $cnt, $off) =
2278				ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2279			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2280			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2281
2282			# Extract the remainder of the define (if any) and
2283			# rip off surrounding spaces, and trailing \'s.
2284			$rest = '';
2285			while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2286				#print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2287				if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2288					$rest .= substr($lines[$ln - 1], $off) . "\n";
2289					$cnt--;
2290				}
2291				$ln++;
2292				$off = 0;
2293			}
2294			$rest =~ s/\\\n.//g;
2295			$rest =~ s/^\s*//s;
2296			$rest =~ s/\s*$//s;
2297
2298			# Clean up the original statement.
2299			if ($args) {
2300				substr($dstat, 0, length($dcond), '');
2301			} else {
2302				$dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2303			}
2304			$dstat =~ s/$;//g;
2305			$dstat =~ s/\\\n.//g;
2306			$dstat =~ s/^\s*//s;
2307			$dstat =~ s/\s*$//s;
2308
2309			# Flatten any parentheses and braces
2310			while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2311			       $dstat =~ s/\{[^\{\}]*\}/1/ ||
2312			       $dstat =~ s/\[[^\{\}]*\]/1/)
2313			{
2314			}
2315
2316			my $exceptions = qr{
2317				$Declare|
2318				module_param_named|
2319				MODULE_PARAM_DESC|
2320				DECLARE_PER_CPU|
2321				DEFINE_PER_CPU|
2322				__typeof__\(|
2323				union|
2324				struct|
2325				\.$Ident\s*=\s*|
2326				^\"|\"$
2327			}x;
2328			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2329			if ($rest ne '' && $rest ne ',') {
2330				if ($rest !~ /while\s*\(/ &&
2331				    $dstat !~ /$exceptions/)
2332				{
2333					ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2334				}
2335
2336			} elsif ($ctx !~ /;/) {
2337				if ($dstat ne '' &&
2338				    $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2339				    $dstat !~ /$exceptions/ &&
2340				    $dstat !~ /^\.$Ident\s*=/ &&
2341				    $dstat =~ /$Operators/)
2342				{
2343					ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2344				}
2345			}
2346		}
2347
2348# check for missing bracing round if etc
2349		if ($line =~ /(^.*)\bif\b/ && $line !~ /\#\s*if/) {
2350			my ($level, $endln, @chunks) =
2351				ctx_statement_full($linenr, $realcnt, 1);
2352                        if ($dbg_adv_apw) {
2353                            print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2354                            print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2355                                if $#chunks >= 1;
2356                        }
2357			if ($#chunks >= 0 && $level == 0) {
2358				my $allowed = 0;
2359				my $seen = 0;
2360				my $herectx = $here . "\n";
2361				my $ln = $linenr - 1;
2362				for my $chunk (@chunks) {
2363					my ($cond, $block) = @{$chunk};
2364
2365					# If the condition carries leading newlines, then count those as offsets.
2366					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2367					my $offset = statement_rawlines($whitespace) - 1;
2368
2369					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2370
2371					# We have looked at and allowed this specific line.
2372					$suppress_ifbraces{$ln + $offset} = 1;
2373
2374					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2375					$ln += statement_rawlines($block) - 1;
2376
2377					substr($block, 0, length($cond), '');
2378
2379					my $spaced_block = $block;
2380					$spaced_block =~ s/\n\+/ /g;
2381
2382					$seen++ if ($spaced_block =~ /^\s*\{/);
2383
2384                                        print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2385                                            if $dbg_adv_apw;
2386					if (statement_lines($cond) > 1) {
2387                                            print "APW: ALLOWED: cond<$cond>\n"
2388                                                if $dbg_adv_apw;
2389                                            $allowed = 1;
2390					}
2391					if ($block =~/\b(?:if|for|while)\b/) {
2392                                            print "APW: ALLOWED: block<$block>\n"
2393                                                if $dbg_adv_apw;
2394                                            $allowed = 1;
2395					}
2396					if (statement_block_size($block) > 1) {
2397                                            print "APW: ALLOWED: lines block<$block>\n"
2398                                                if $dbg_adv_apw;
2399                                            $allowed = 1;
2400					}
2401				}
2402				if ($seen != ($#chunks + 1)) {
2403					ERROR("braces {} are necessary for all arms of this statement\n" . $herectx);
2404				}
2405			}
2406		}
2407		if (!defined $suppress_ifbraces{$linenr - 1} &&
2408					$line =~ /\b(if|while|for|else)\b/ &&
2409					$line !~ /\#\s*if/ &&
2410					$line !~ /\#\s*else/) {
2411			my $allowed = 0;
2412
2413                        # Check the pre-context.
2414                        if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2415                            my $pre = $1;
2416
2417                            if ($line !~ /else/) {
2418                                print "APW: ALLOWED: pre<$pre> line<$line>\n"
2419                                    if $dbg_adv_apw;
2420                                $allowed = 1;
2421                            }
2422                        }
2423
2424			my ($level, $endln, @chunks) =
2425				ctx_statement_full($linenr, $realcnt, $-[0]);
2426
2427			# Check the condition.
2428			my ($cond, $block) = @{$chunks[0]};
2429                        print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2430                            if $dbg_adv_checking;
2431			if (defined $cond) {
2432				substr($block, 0, length($cond), '');
2433			}
2434			if (statement_lines($cond) > 1) {
2435                            print "APW: ALLOWED: cond<$cond>\n"
2436                                if $dbg_adv_apw;
2437                            $allowed = 1;
2438			}
2439			if ($block =~/\b(?:if|for|while)\b/) {
2440                            print "APW: ALLOWED: block<$block>\n"
2441                                if $dbg_adv_apw;
2442                            $allowed = 1;
2443			}
2444			if (statement_block_size($block) > 1) {
2445                            print "APW: ALLOWED: lines block<$block>\n"
2446                                if $dbg_adv_apw;
2447                            $allowed = 1;
2448			}
2449			# Check the post-context.
2450			if (defined $chunks[1]) {
2451				my ($cond, $block) = @{$chunks[1]};
2452				if (defined $cond) {
2453					substr($block, 0, length($cond), '');
2454				}
2455				if ($block =~ /^\s*\{/) {
2456                                    print "APW: ALLOWED: chunk-1 block<$block>\n"
2457                                        if $dbg_adv_apw;
2458                                    $allowed = 1;
2459				}
2460			}
2461                        print "DCS: level=$level block<$block> allowed=$allowed\n"
2462                            if $dbg_adv_dcs;
2463			if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2464				my $herectx = $here . "\n";;
2465				my $cnt = statement_rawlines($block);
2466
2467				for (my $n = 0; $n < $cnt; $n++) {
2468					$herectx .= raw_line($linenr, $n) . "\n";;
2469				}
2470
2471				ERROR("braces {} are necessary even for single statement blocks\n" . $herectx);
2472			}
2473		}
2474
2475# no volatiles please
2476		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2477		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
2478			ERROR("Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
2479		}
2480
2481# warn about #if 0
2482		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2483			ERROR("if this code is redundant consider removing it\n" .
2484				$herecurr);
2485		}
2486
2487# check for needless g_free() checks
2488		if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2489			my $expr = $1;
2490			if ($line =~ /\bg_free\(\Q$expr\E\);/) {
2491				ERROR("g_free(NULL) is safe this check is probably not required\n" . $hereprev);
2492			}
2493		}
2494
2495# warn about #ifdefs in C files
2496#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2497#			print "#ifdef in C files should be avoided\n";
2498#			print "$herecurr";
2499#			$clean = 0;
2500#		}
2501
2502# warn about spacing in #ifdefs
2503		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2504			ERROR("exactly one space required after that #$1\n" . $herecurr);
2505		}
2506# check for memory barriers without a comment.
2507		if ($line =~ /\b(smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2508			if (!ctx_has_comment($first_line, $linenr)) {
2509				ERROR("memory barrier without comment\n" . $herecurr);
2510			}
2511		}
2512# check of hardware specific defines
2513# we have e.g. CONFIG_LINUX and CONFIG_WIN32 for common cases
2514# where they might be necessary.
2515		if ($line =~ m@^.\s*\#\s*if.*\b__@) {
2516			WARN("architecture specific defines should be avoided\n" .  $herecurr);
2517		}
2518
2519# Check that the storage class is at the beginning of a declaration
2520		if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2521			ERROR("storage class should be at the beginning of the declaration\n" . $herecurr)
2522		}
2523
2524# check the location of the inline attribute, that it is between
2525# storage class and type.
2526		if ($line =~ /\b$Type\s+$Inline\b/ ||
2527		    $line =~ /\b$Inline\s+$Storage\b/) {
2528			ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2529		}
2530
2531# check for sizeof(&)
2532		if ($line =~ /\bsizeof\s*\(\s*\&/) {
2533			ERROR("sizeof(& should be avoided\n" . $herecurr);
2534		}
2535
2536# check for new externs in .c files.
2537		if ($realfile =~ /\.c$/ && defined $stat &&
2538		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2539		{
2540			my $function_name = $1;
2541			my $paren_space = $2;
2542
2543			my $s = $stat;
2544			if (defined $cond) {
2545				substr($s, 0, length($cond), '');
2546			}
2547			if ($s =~ /^\s*;/ &&
2548			    $function_name ne 'uninitialized_var')
2549			{
2550				ERROR("externs should be avoided in .c files\n" .  $herecurr);
2551			}
2552
2553			if ($paren_space =~ /\n/) {
2554				ERROR("arguments for function declarations should follow identifier\n" . $herecurr);
2555			}
2556
2557		} elsif ($realfile =~ /\.c$/ && defined $stat &&
2558		    $stat =~ /^.\s*extern\s+/)
2559		{
2560			ERROR("externs should be avoided in .c files\n" .  $herecurr);
2561		}
2562
2563# check for pointless casting of g_malloc return
2564		if ($line =~ /\*\s*\)\s*g_(try)?(m|re)alloc(0?)(_n)?\b/) {
2565			if ($2 == 'm') {
2566				ERROR("unnecessary cast may hide bugs, use g_$1new$3 instead\n" . $herecurr);
2567			} else {
2568				ERROR("unnecessary cast may hide bugs, use g_$1renew$3 instead\n" . $herecurr);
2569			}
2570		}
2571
2572# check for gcc specific __FUNCTION__
2573		if ($line =~ /__FUNCTION__/) {
2574			ERROR("__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr);
2575		}
2576
2577# recommend qemu_strto* over strto* for numeric conversions
2578		if ($line =~ /\b(strto[^kd].*?)\s*\(/) {
2579			ERROR("consider using qemu_$1 in preference to $1\n" . $herecurr);
2580		}
2581# recommend sigaction over signal for portability, when establishing a handler
2582		if ($line =~ /\bsignal\s*\(/ && !($line =~ /SIG_(?:IGN|DFL)/)) {
2583			ERROR("use sigaction to establish signal handlers; signal is not portable\n" . $herecurr);
2584		}
2585# check for module_init(), use category-specific init macros explicitly please
2586		if ($line =~ /^module_init\s*\(/) {
2587			ERROR("please use block_init(), type_init() etc. instead of module_init()\n" . $herecurr);
2588		}
2589# check for various ops structs, ensure they are const.
2590		my $struct_ops = qr{AIOCBInfo|
2591				BdrvActionOps|
2592				BlockDevOps|
2593				BlockJobDriver|
2594				DisplayChangeListenerOps|
2595				GraphicHwOps|
2596				IDEDMAOps|
2597				KVMCapabilityInfo|
2598				MemoryRegionIOMMUOps|
2599				MemoryRegionOps|
2600				MemoryRegionPortio|
2601				QEMUFileOps|
2602				SCSIBusInfo|
2603				SCSIReqOps|
2604				Spice[A-Z][a-zA-Z0-9]*Interface|
2605				TPMDriverOps|
2606				USBDesc[A-Z][a-zA-Z0-9]*|
2607				VhostOps|
2608				VMStateDescription|
2609				VMStateInfo}x;
2610		if ($line !~ /\bconst\b/ &&
2611		    $line =~ /\b($struct_ops)\b.*=/) {
2612			ERROR("initializer for struct $1 should normally be const\n" .
2613				$herecurr);
2614		}
2615
2616# check for %L{u,d,i} in strings
2617		my $string;
2618		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2619			$string = substr($rawline, $-[1], $+[1] - $-[1]);
2620			$string =~ s/%%/__/g;
2621			if ($string =~ /(?<!%)%L[udi]/) {
2622				ERROR("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2623				last;
2624			}
2625		}
2626
2627# QEMU specific tests
2628		if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2629			ERROR("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2630		}
2631
2632# Qemu error function tests
2633
2634	# Find newlines in error messages
2635	my $qemu_error_funcs = qr{error_setg|
2636				error_setg_errno|
2637				error_setg_win32|
2638				error_setg_file_open|
2639				error_set|
2640				error_prepend|
2641				warn_reportf_err|
2642				error_reportf_err|
2643				error_vreport|
2644				warn_vreport|
2645				info_vreport|
2646				error_report|
2647				warn_report|
2648				info_report}x;
2649
2650	if ($rawline =~ /\b(?:$qemu_error_funcs)\s*\(.*\".*\\n/) {
2651		ERROR("Error messages should not contain newlines\n" . $herecurr);
2652	}
2653
2654	# Continue checking for error messages that contains newlines. This
2655	# check handles cases where string literals are spread over multiple lines.
2656	# Example:
2657	# error_report("Error msg line #1"
2658	#              "Error msg line #2\n");
2659	my $quoted_newline_regex = qr{\+\s*\".*\\n.*\"};
2660	my $continued_str_literal = qr{\+\s*\".*\"};
2661
2662	if ($rawline =~ /$quoted_newline_regex/) {
2663		# Backtrack to first line that does not contain only a quoted literal
2664		# and assume that it is the start of the statement.
2665		my $i = $linenr - 2;
2666
2667		while (($i >= 0) & $rawlines[$i] =~ /$continued_str_literal/) {
2668			$i--;
2669		}
2670
2671		if ($rawlines[$i] =~ /\b(?:$qemu_error_funcs)\s*\(/) {
2672			ERROR("Error messages should not contain newlines\n" . $herecurr);
2673		}
2674	}
2675
2676# check for non-portable libc calls that have portable alternatives in QEMU
2677		if ($line =~ /\bffs\(/) {
2678			ERROR("use ctz32() instead of ffs()\n" . $herecurr);
2679		}
2680		if ($line =~ /\bffsl\(/) {
2681			ERROR("use ctz32() or ctz64() instead of ffsl()\n" . $herecurr);
2682		}
2683		if ($line =~ /\bffsll\(/) {
2684			ERROR("use ctz64() instead of ffsll()\n" . $herecurr);
2685		}
2686		if ($line =~ /\bbzero\(/) {
2687			ERROR("use memset() instead of bzero()\n" . $herecurr);
2688		}
2689		my $non_exit_glib_asserts = qr{g_assert_cmpstr|
2690						g_assert_cmpint|
2691						g_assert_cmpuint|
2692						g_assert_cmphex|
2693						g_assert_cmpfloat|
2694						g_assert_true|
2695						g_assert_false|
2696						g_assert_nonnull|
2697						g_assert_null|
2698						g_assert_no_error|
2699						g_assert_error|
2700						g_test_assert_expected_messages|
2701						g_test_trap_assert_passed|
2702						g_test_trap_assert_stdout|
2703						g_test_trap_assert_stdout_unmatched|
2704						g_test_trap_assert_stderr|
2705						g_test_trap_assert_stderr_unmatched}x;
2706		if ($realfile !~ /^tests\// &&
2707			$line =~ /\b(?:$non_exit_glib_asserts)\(/) {
2708			ERROR("Use g_assert or g_assert_not_reached\n". $herecurr);
2709		}
2710	}
2711
2712	# If we have no input at all, then there is nothing to report on
2713	# so just keep quiet.
2714	if ($#rawlines == -1) {
2715		exit(0);
2716	}
2717
2718	# In mailback mode only produce a report in the negative, for
2719	# things that appear to be patches.
2720	if ($mailback && ($clean == 1 || !$is_patch)) {
2721		exit(0);
2722	}
2723
2724	# This is not a patch, and we are are in 'no-patch' mode so
2725	# just keep quiet.
2726	if (!$chk_patch && !$is_patch) {
2727		exit(0);
2728	}
2729
2730	if (!$is_patch) {
2731		ERROR("Does not appear to be a unified-diff format patch\n");
2732	}
2733	if ($is_patch && $chk_signoff && $signoff == 0) {
2734		ERROR("Missing Signed-off-by: line(s)\n");
2735	}
2736
2737	print report_dump();
2738	if ($summary && !($clean == 1 && $quiet == 1)) {
2739		print "$filename " if ($summary_file);
2740		print "total: $cnt_error errors, $cnt_warn warnings, " .
2741			"$cnt_lines lines checked\n";
2742		print "\n" if ($quiet == 0);
2743	}
2744
2745	if ($quiet == 0) {
2746		# If there were whitespace errors which cleanpatch can fix
2747		# then suggest that.
2748#		if ($rpt_cleaners) {
2749#			print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2750#			print "      scripts/cleanfile\n\n";
2751#		}
2752	}
2753
2754	if ($clean == 1 && $quiet == 0) {
2755		print "$vname has no obvious style problems and is ready for submission.\n"
2756	}
2757	if ($clean == 0 && $quiet == 0) {
2758		print "$vname has style problems, please review.  If any of these errors\n";
2759		print "are false positives report them to the maintainer, see\n";
2760		print "CHECKPATCH in MAINTAINERS.\n";
2761	}
2762
2763	return ($no_warnings ? $clean : $cnt_error == 0);
2764}
2765