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