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