xref: /linux/scripts/checkpatch.pl (revision 44a2db43eb715b54618bf01520cc5d46376cdbe2)
1#!/usr/bin/perl -w
2# (c) 2001, Dave Jones. <davej@codemonkey.org.uk> (the file handling bit)
3# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4# (c) 2007, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite, etc)
5# Licensed under the terms of the GNU GPL License version 2
6
7use strict;
8
9my $P = $0;
10$P =~ s@.*/@@g;
11
12my $V = '0.10';
13
14use Getopt::Long qw(:config no_auto_abbrev);
15
16my $quiet = 0;
17my $tree = 1;
18my $chk_signoff = 1;
19my $chk_patch = 1;
20my $tst_type = 0;
21GetOptions(
22	'q|quiet'	=> \$quiet,
23	'tree!'		=> \$tree,
24	'signoff!'	=> \$chk_signoff,
25	'patch!'	=> \$chk_patch,
26	'test-type!'	=> \$tst_type,
27) or exit;
28
29my $exit = 0;
30
31if ($#ARGV < 0) {
32	print "usage: $P [options] patchfile\n";
33	print "version: $V\n";
34	print "options: -q           => quiet\n";
35	print "         --no-tree    => run without a kernel tree\n";
36	exit(1);
37}
38
39if ($tree && !top_of_kernel_tree()) {
40	print "Must be run from the top-level dir. of a kernel tree\n";
41	exit(2);
42}
43
44my @dep_includes = ();
45my @dep_functions = ();
46my $removal = 'Documentation/feature-removal-schedule.txt';
47if ($tree && -f $removal) {
48	open(REMOVE, "<$removal") || die "$P: $removal: open failed - $!\n";
49	while (<REMOVE>) {
50		if (/^Check:\s+(.*\S)/) {
51			for my $entry (split(/[, ]+/, $1)) {
52				if ($entry =~ m@include/(.*)@) {
53					push(@dep_includes, $1);
54
55				} elsif ($entry !~ m@/@) {
56					push(@dep_functions, $entry);
57				}
58			}
59		}
60	}
61}
62
63my @rawlines = ();
64while (<>) {
65	chomp;
66	push(@rawlines, $_);
67	if (eof(ARGV)) {
68		if (!process($ARGV, @rawlines)) {
69			$exit = 1;
70		}
71		@rawlines = ();
72	}
73}
74
75exit($exit);
76
77sub top_of_kernel_tree {
78	if ((-f "COPYING") && (-f "CREDITS") && (-f "Kbuild") &&
79	    (-f "MAINTAINERS") && (-f "Makefile") && (-f "README") &&
80	    (-d "Documentation") && (-d "arch") && (-d "include") &&
81	    (-d "drivers") && (-d "fs") && (-d "init") && (-d "ipc") &&
82	    (-d "kernel") && (-d "lib") && (-d "scripts")) {
83		return 1;
84	}
85	return 0;
86}
87
88sub expand_tabs {
89	my ($str) = @_;
90
91	my $res = '';
92	my $n = 0;
93	for my $c (split(//, $str)) {
94		if ($c eq "\t") {
95			$res .= ' ';
96			$n++;
97			for (; ($n % 8) != 0; $n++) {
98				$res .= ' ';
99			}
100			next;
101		}
102		$res .= $c;
103		$n++;
104	}
105
106	return $res;
107}
108
109sub line_stats {
110	my ($line) = @_;
111
112	# Drop the diff line leader and expand tabs
113	$line =~ s/^.//;
114	$line = expand_tabs($line);
115
116	# Pick the indent from the front of the line.
117	my ($white) = ($line =~ /^(\s*)/);
118
119	return (length($line), length($white));
120}
121
122sub sanitise_line {
123	my ($line) = @_;
124
125	my $res = '';
126	my $l = '';
127
128	my $quote = '';
129
130	foreach my $c (split(//, $line)) {
131		if ($l ne "\\" && ($c eq "'" || $c eq '"')) {
132			if ($quote eq '') {
133				$quote = $c;
134				$res .= $c;
135				$l = $c;
136				next;
137			} elsif ($quote eq $c) {
138				$quote = '';
139			}
140		}
141		if ($quote && $c ne "\t") {
142			$res .= "X";
143		} else {
144			$res .= $c;
145		}
146
147		$l = $c;
148	}
149
150	return $res;
151}
152
153sub ctx_block_get {
154	my ($linenr, $remain, $outer, $open, $close, $off) = @_;
155	my $line;
156	my $start = $linenr - 1;
157	my $blk = '';
158	my @o;
159	my @c;
160	my @res = ();
161
162	my $level = 0;
163	for ($line = $start; $remain > 0; $line++) {
164		next if ($rawlines[$line] =~ /^-/);
165		$remain--;
166
167		$blk .= $rawlines[$line];
168		foreach my $c (split(//, $rawlines[$line])) {
169			##print "C<$c>L<$level><$open$close>O<$off>\n";
170			if ($off > 0) {
171				$off--;
172				next;
173			}
174
175			if ($c eq $close && $level > 0) {
176				$level--;
177				last if ($level == 0);
178			} elsif ($c eq $open) {
179				$level++;
180			}
181		}
182
183		if (!$outer || $level <= 1) {
184			push(@res, $rawlines[$line]);
185		}
186
187		last if ($level == 0);
188	}
189
190	return ($level, @res);
191}
192sub ctx_block_outer {
193	my ($linenr, $remain) = @_;
194
195	my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
196	return @r;
197}
198sub ctx_block {
199	my ($linenr, $remain) = @_;
200
201	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
202	return @r;
203}
204sub ctx_statement {
205	my ($linenr, $remain, $off) = @_;
206
207	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
208	return @r;
209}
210sub ctx_block_level {
211	my ($linenr, $remain) = @_;
212
213	return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
214}
215sub ctx_statement_level {
216	my ($linenr, $remain, $off) = @_;
217
218	return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
219}
220
221sub ctx_locate_comment {
222	my ($first_line, $end_line) = @_;
223
224	# Catch a comment on the end of the line itself.
225	my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*$@);
226	return $current_comment if (defined $current_comment);
227
228	# Look through the context and try and figure out if there is a
229	# comment.
230	my $in_comment = 0;
231	$current_comment = '';
232	for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
233		my $line = $rawlines[$linenr - 1];
234		#warn "           $line\n";
235		if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
236			$in_comment = 1;
237		}
238		if ($line =~ m@/\*@) {
239			$in_comment = 1;
240		}
241		if (!$in_comment && $current_comment ne '') {
242			$current_comment = '';
243		}
244		$current_comment .= $line . "\n" if ($in_comment);
245		if ($line =~ m@\*/@) {
246			$in_comment = 0;
247		}
248	}
249
250	chomp($current_comment);
251	return($current_comment);
252}
253sub ctx_has_comment {
254	my ($first_line, $end_line) = @_;
255	my $cmt = ctx_locate_comment($first_line, $end_line);
256
257	##print "LINE: $rawlines[$end_line - 1 ]\n";
258	##print "CMMT: $cmt\n";
259
260	return ($cmt ne '');
261}
262
263sub ctx_expr_before {
264	my ($line) = @_;
265
266	##print "CHECK<$line>\n";
267
268	my $pos = length($line) - 1;
269	my $count = 0;
270	my $c;
271
272	for (; $pos >= 0; $pos--) {
273		$c = substr($line, $pos, 1);
274		##print "CHECK: c<$c> count<$count>\n";
275		if ($c eq ')') {
276			$count++;
277		} elsif ($c eq '(') {
278			last if (--$count == 0);
279		}
280	}
281
282	##print "CHECK: result<" . substr($line, 0, $pos) . ">\n";
283
284	return substr($line, 0, $pos);
285}
286
287sub cat_vet {
288	my ($vet) = @_;
289	my ($res, $coded);
290
291	$res = '';
292	while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]])/g) {
293		$coded = sprintf("^%c", unpack('C', $2) + 64);
294		$res .= $1 . $coded;
295	}
296	$res =~ s/$/\$/;
297
298	return $res;
299}
300
301my @report = ();
302sub report {
303	push(@report, $_[0]);
304}
305sub report_dump {
306	@report;
307}
308sub ERROR {
309	report("ERROR: $_[0]\n");
310	our $clean = 0;
311}
312sub WARN {
313	report("WARNING: $_[0]\n");
314	our $clean = 0;
315}
316sub CHK {
317	report("CHECK: $_[0]\n");
318	our $clean = 0;
319}
320
321sub process {
322	my $filename = shift;
323	my @lines = @_;
324
325	my $linenr=0;
326	my $prevline="";
327	my $stashline="";
328
329	my $length;
330	my $indent;
331	my $previndent=0;
332	my $stashindent=0;
333
334	our $clean = 1;
335	my $signoff = 0;
336	my $is_patch = 0;
337
338	# Trace the real file/line as we go.
339	my $realfile = '';
340	my $realline = 0;
341	my $realcnt = 0;
342	my $here = '';
343	my $in_comment = 0;
344	my $first_line = 0;
345
346	my $Ident	= qr{[A-Za-z\d_]+};
347	my $Storage	= qr{extern|static|asmlinkage};
348	my $Sparse	= qr{
349				__user|
350				__kernel|
351				__force|
352				__iomem|
353				__must_check|
354				__init_refok|
355				fastcall
356			}x;
357	my $Inline	= qr{inline|__always_inline|noinline};
358	my $NonptrType	= qr{
359				\b
360				(?:const\s+)?
361				(?:unsigned\s+)?
362				(?:
363					void|
364					char|
365					short|
366					int|
367					long|
368					unsigned|
369					float|
370					double|
371					bool|
372					long\s+int|
373					long\s+long|
374					long\s+long\s+int|
375					u8|u16|u32|u64|
376					s8|s16|s32|s64|
377					struct\s+$Ident|
378					union\s+$Ident|
379					enum\s+$Ident|
380					${Ident}_t
381				)
382				(?:\s+$Sparse)*
383				\b
384			  }x;
385	my $Type	= qr{
386				\b$NonptrType\b
387				(?:\s*\*+\s*const|\s*\*+|(?:\s*\[\s*\])+)?
388				(?:\s+$Sparse)*
389			  }x;
390	my $Declare	= qr{(?:$Storage\s+)?$Type};
391	my $Attribute	= qr{
392				const|
393				__read_mostly|
394				__(?:mem|cpu|dev|)(?:initdata|init)
395			  }x;
396	my $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
397	my $Lval	= qr{$Ident(?:$Member)*};
398
399	# Possible bare types.
400	my @bare = ();
401	my $Bare = $NonptrType;
402
403	# Pre-scan the patch looking for any __setup documentation.
404	my @setup_docs = ();
405	my $setup_docs = 0;
406	foreach my $line (@lines) {
407		if ($line=~/^\+\+\+\s+(\S+)/) {
408			$setup_docs = 0;
409			if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
410				$setup_docs = 1;
411			}
412			next;
413		}
414
415		if ($setup_docs && $line =~ /^\+/) {
416			push(@setup_docs, $line);
417		}
418	}
419
420	foreach my $line (@lines) {
421		$linenr++;
422
423		my $rawline = $line;
424
425#extract the filename as it passes
426		if ($line=~/^\+\+\+\s+(\S+)/) {
427			$realfile=$1;
428			$realfile =~ s@^[^/]*/@@;
429			$in_comment = 0;
430			next;
431		}
432#extract the line range in the file after the patch is applied
433		if ($line=~/^\@\@ -\d+,\d+ \+(\d+)(,(\d+))? \@\@/) {
434			$is_patch = 1;
435			$first_line = $linenr + 1;
436			$in_comment = 0;
437			$realline=$1-1;
438			if (defined $2) {
439				$realcnt=$3+1;
440			} else {
441				$realcnt=1+1;
442			}
443			next;
444		}
445
446# track the line number as we move through the hunk, note that
447# new versions of GNU diff omit the leading space on completely
448# blank context lines so we need to count that too.
449		if ($line =~ /^( |\+|$)/) {
450			$realline++;
451			$realcnt-- if ($realcnt != 0);
452
453			# track any sort of multi-line comment.  Obviously if
454			# the added text or context do not include the whole
455			# comment we will not see it. Such is life.
456			#
457			# Guestimate if this is a continuing comment.  If this
458			# is the start of a diff block and this line starts
459			# ' *' then it is very likely a comment.
460			if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
461				$in_comment = 1;
462			}
463			if ($line =~ m@/\*@) {
464				$in_comment = 1;
465			}
466			if ($line =~ m@\*/@) {
467				$in_comment = 0;
468			}
469
470			# Measure the line length and indent.
471			($length, $indent) = line_stats($line);
472
473			# Track the previous line.
474			($prevline, $stashline) = ($stashline, $line);
475			($previndent, $stashindent) = ($stashindent, $indent);
476		} elsif ($realcnt == 1) {
477			$realcnt--;
478		}
479
480#make up the handle for any error we report on this line
481		$here = "#$linenr: ";
482		$here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
483
484		my $hereline = "$here\n$line\n";
485		my $herecurr = "$here\n$line\n";
486		my $hereprev = "$here\n$prevline\n$line\n";
487
488#check the patch for a signoff:
489		if ($line =~ /^\s*signed-off-by:/i) {
490			# This is a signoff, if ugly, so do not double report.
491			$signoff++;
492			if (!($line =~ /^\s*Signed-off-by:/)) {
493				WARN("Signed-off-by: is the preferred form\n" .
494					$herecurr);
495			}
496			if ($line =~ /^\s*signed-off-by:\S/i) {
497				WARN("need space after Signed-off-by:\n" .
498					$herecurr);
499			}
500		}
501
502# Check for wrappage within a valid hunk of the file
503		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |$)}) {
504			ERROR("patch seems to be corrupt (line wrapped?)\n" .
505				$herecurr);
506		}
507
508# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
509		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
510		     !($line =~ m/^(
511				[\x09\x0A\x0D\x20-\x7E]              # ASCII
512				| [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
513				|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
514				| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
515				|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
516				|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
517				| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
518				|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
519				)*$/x )) {
520			ERROR("Invalid UTF-8\n" . $herecurr);
521		}
522
523#ignore lines being removed
524		if ($line=~/^-/) {next;}
525
526# check we are in a valid source file if not then ignore this hunk
527		next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
528
529#trailing whitespace
530		if ($line =~ /^\+.*\015/) {
531			my $herevet = "$here\n" . cat_vet($line) . "\n";
532			ERROR("DOS line endings\n" . $herevet);
533
534		} elsif ($line =~ /^\+.*\S\s+$/ || $line =~ /^\+\s+$/) {
535			my $herevet = "$here\n" . cat_vet($line) . "\n";
536			ERROR("trailing whitespace\n" . $herevet);
537		}
538#80 column limit
539		if ($line =~ /^\+/ && !($prevline=~/\/\*\*/) && $length > 80) {
540			WARN("line over 80 characters\n" . $herecurr);
541		}
542
543# check we are in a valid source file *.[hc] if not then ignore this hunk
544		next if ($realfile !~ /\.[hc]$/);
545
546# at the beginning of a line any tabs must come first and anything
547# more than 8 must use tabs.
548		if ($line=~/^\+\s* \t\s*\S/ or $line=~/^\+\s*        \s*/) {
549			my $herevet = "$here\n" . cat_vet($line) . "\n";
550			ERROR("use tabs not spaces\n" . $herevet);
551		}
552
553# Remove comments from the line before processing.
554		my $comment_edge = ($line =~ s@/\*.*\*/@@g) +
555				   ($line =~ s@/\*.*@@) +
556				   ($line =~ s@^(.).*\*/@$1@);
557
558# The rest of our checks refer specifically to C style
559# only apply those _outside_ comments.  Only skip
560# lines in the middle of comments.
561		next if (!$comment_edge && $in_comment);
562
563# Standardise the strings and chars within the input to simplify matching.
564		$line = sanitise_line($line);
565
566# Check for potential 'bare' types
567		if ($realcnt &&
568		    $line !~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?$Type\b/ &&
569		    $line !~ /$Ident:\s*$/ &&
570		    $line !~ /^.\s*$Ident\s*\(/ &&
571		    ($line =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?($Ident)\b/ ||
572		     $line =~ /^.\s*(?:$Storage\s+)?($Ident)\b\s*\**\s*$Ident\s*(?:;|=)/)) {
573			my $possible = $1;
574			if ($possible !~ /^(?:$Storage|$Type|DEFINE_\S+)$/ &&
575			    $possible ne 'goto' && $possible ne 'return' &&
576			    $possible ne 'struct' && $possible ne 'enum' &&
577			    $possible ne 'case' && $possible ne 'else' &&
578			    $possible ne 'typedef') {
579				#print "POSSIBLE<$possible>\n";
580				push(@bare, $possible);
581				my $bare = join("|", @bare);
582				$Bare	= qr{
583						\b(?:$bare)\b
584						(?:\s*\*+\s*const|\s*\*+|(?:\s*\[\s*\])+)?
585						(?:\s+$Sparse)*
586					  }x;
587			}
588		}
589
590#
591# Checks which may be anchored in the context.
592#
593
594# Check for switch () and associated case and default
595# statements should be at the same indent.
596		if ($line=~/\bswitch\s*\(.*\)/) {
597			my $err = '';
598			my $sep = '';
599			my @ctx = ctx_block_outer($linenr, $realcnt);
600			shift(@ctx);
601			for my $ctx (@ctx) {
602				my ($clen, $cindent) = line_stats($ctx);
603				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
604							$indent != $cindent) {
605					$err .= "$sep$ctx\n";
606					$sep = '';
607				} else {
608					$sep = "[...]\n";
609				}
610			}
611			if ($err ne '') {
612				ERROR("switch and case should be at the same indent\n$hereline$err");
613			}
614		}
615
616# if/while/etc brace do not go on next line, unless defining a do while loop,
617# or if that brace on the next line is for something else
618		if ($line =~ /\b(?:(if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.#/) {
619			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
620			my $ctx_ln = $linenr + $#ctx + 1;
621			my $ctx_cnt = $realcnt - $#ctx - 1;
622			my $ctx = join("\n", @ctx);
623
624			# Skip over any removed lines in the context following statement.
625			while ($ctx_cnt > 0 && $lines[$ctx_ln - 1] =~ /^-/) {
626				$ctx_ln++;
627				$ctx_cnt--;
628			}
629			##warn "line<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>";
630
631			if ($ctx !~ /{\s*/ && $ctx_cnt > 0 && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
632				ERROR("That open brace { should be on the previous line\n" .
633					"$here\n$ctx\n$lines[$ctx_ln - 1]");
634			}
635			if ($level == 0 && $ctx =~ /\)\s*\;\s*$/ && defined $lines[$ctx_ln - 1]) {
636				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
637				if ($nindent > $indent) {
638					WARN("Trailing semicolon indicates no statements, indent implies otherwise\n" .
639						"$here\n$ctx\n$lines[$ctx_ln - 1]");
640				}
641			}
642		}
643
644#ignore lines not being added
645		if ($line=~/^[^\+]/) {next;}
646
647# TEST: allow direct testing of the type matcher.
648		if ($tst_type && $line =~ /^.$Declare$/) {
649			ERROR("TEST: is type $Declare\n" . $herecurr);
650			next;
651		}
652
653# check for initialisation to aggregates open brace on the next line
654		if ($prevline =~ /$Declare\s*$Ident\s*=\s*$/ &&
655		    $line =~ /^.\s*{/) {
656			ERROR("That open brace { should be on the previous line\n" . $hereprev);
657		}
658
659#
660# Checks which are anchored on the added line.
661#
662
663# check for malformed paths in #include statements (uses RAW line)
664		if ($rawline =~ m{^.#\s*include\s+[<"](.*)[">]}) {
665			my $path = $1;
666			if ($path =~ m{//}) {
667				ERROR("malformed #include filename\n" .
668					$herecurr);
669			}
670			# Sanitise this special form of string.
671			$path = 'X' x length($path);
672			$line =~ s{\<.*\>}{<$path>};
673		}
674
675# no C99 // comments
676		if ($line =~ m{//}) {
677			ERROR("do not use C99 // comments\n" . $herecurr);
678		}
679		# Remove C99 comments.
680		$line =~ s@//.*@@;
681
682#EXPORT_SYMBOL should immediately follow its function closing }.
683		if (($line =~ /EXPORT_SYMBOL.*\((.*)\)/) ||
684		    ($line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
685			my $name = $1;
686			if (($prevline !~ /^}/) &&
687			   ($prevline !~ /^\+}/) &&
688			   ($prevline !~ /^ }/) &&
689			   ($prevline !~ /\b\Q$name\E(?:\s+$Attribute)?\s*(?:;|=)/)) {
690				WARN("EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
691			}
692		}
693
694# check for external initialisers.
695		if ($line =~ /^.$Type\s*$Ident\s*=\s*(0|NULL);/) {
696			ERROR("do not initialise externals to 0 or NULL\n" .
697				$herecurr);
698		}
699# check for static initialisers.
700		if ($line =~ /\s*static\s.*=\s*(0|NULL);/) {
701			ERROR("do not initialise statics to 0 or NULL\n" .
702				$herecurr);
703		}
704
705# check for new typedefs, only function parameters and sparse annotations
706# make sense.
707		if ($line =~ /\btypedef\s/ &&
708		    $line !~ /\btypedef\s+$Type\s+\(\s*\*?$Ident\s*\)\s*\(/ &&
709		    $line !~ /\b__bitwise(?:__|)\b/) {
710			WARN("do not add new typedefs\n" . $herecurr);
711		}
712
713# * goes on variable not on type
714		if ($line =~ m{\($NonptrType(\*+)(?:\s+const)?\)}) {
715			ERROR("\"(foo$1)\" should be \"(foo $1)\"\n" .
716				$herecurr);
717
718		} elsif ($line =~ m{\($NonptrType\s+(\*+)(?!\s+const)\s+\)}) {
719			ERROR("\"(foo $1 )\" should be \"(foo $1)\"\n" .
720				$herecurr);
721
722		} elsif ($line =~ m{$NonptrType(\*+)(?:\s+(?:$Attribute|$Sparse))?\s+[A-Za-z\d_]+}) {
723			ERROR("\"foo$1 bar\" should be \"foo $1bar\"\n" .
724				$herecurr);
725
726		} elsif ($line =~ m{$NonptrType\s+(\*+)(?!\s+(?:$Attribute|$Sparse))\s+[A-Za-z\d_]+}) {
727			ERROR("\"foo $1 bar\" should be \"foo $1bar\"\n" .
728				$herecurr);
729		}
730
731# # no BUG() or BUG_ON()
732# 		if ($line =~ /\b(BUG|BUG_ON)\b/) {
733# 			print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
734# 			print "$herecurr";
735# 			$clean = 0;
736# 		}
737
738# printk should use KERN_* levels.  Note that follow on printk's on the
739# same line do not need a level, so we use the current block context
740# to try and find and validate the current printk.  In summary the current
741# printk includes all preceeding printk's which have no newline on the end.
742# we assume the first bad printk is the one to report.
743		if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
744			my $ok = 0;
745			for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
746				#print "CHECK<$lines[$ln - 1]\n";
747				# we have a preceeding printk if it ends
748				# with "\n" ignore it, else it is to blame
749				if ($lines[$ln - 1] =~ m{\bprintk\(}) {
750					if ($rawlines[$ln - 1] !~ m{\\n"}) {
751						$ok = 1;
752					}
753					last;
754				}
755			}
756			if ($ok == 0) {
757				WARN("printk() should include KERN_ facility level\n" . $herecurr);
758			}
759		}
760
761# function brace can't be on same line, except for #defines of do while,
762# or if closed on same line
763		if (($line=~/$Type\s*[A-Za-z\d_]+\(.*\).* {/) and
764		    !($line=~/\#define.*do\s{/) and !($line=~/}/)) {
765			ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
766		}
767
768# check for spaces between functions and their parentheses.
769		if ($line =~ /($Ident)\s+\(/ &&
770		    $1 !~ /^(?:if|for|while|switch|return|volatile|__volatile__|__attribute__|format|__extension__|Copyright)$/ &&
771		    $line !~ /$Type\s+\(/ && $line !~ /^.\#\s*define\b/) {
772			WARN("no space between function name and open parenthesis '('\n" . $herecurr);
773		}
774# Check operator spacing.
775		# Note we expand the line with the leading + as the real
776		# line will be displayed with the leading + and the tabs
777		# will therefore also expand that way.
778		my $opline = $line;
779		$opline = expand_tabs($opline);
780		$opline =~ s/^./ /;
781		if (!($line=~/\#\s*include/)) {
782			my $ops = qr{
783				<<=|>>=|<=|>=|==|!=|
784				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
785				=>|->|<<|>>|<|>|=|!|~|
786				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/
787			}x;
788			my @elements = split(/($ops|;)/, $opline);
789			my $off = 0;
790			for (my $n = 0; $n < $#elements; $n += 2) {
791				$off += length($elements[$n]);
792
793				my $a = '';
794				$a = 'V' if ($elements[$n] ne '');
795				$a = 'W' if ($elements[$n] =~ /\s$/);
796				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
797				$a = 'O' if ($elements[$n] eq '');
798				$a = 'E' if ($elements[$n] eq '' && $n == 0);
799
800				my $op = $elements[$n + 1];
801
802				my $c = '';
803				if (defined $elements[$n + 2]) {
804					$c = 'V' if ($elements[$n + 2] ne '');
805					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
806					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
807					$c = 'O' if ($elements[$n + 2] eq '');
808					$c = 'E' if ($elements[$n + 2] =~ /\s*\\$/);
809				} else {
810					$c = 'E';
811				}
812
813				# Pick up the preceeding and succeeding characters.
814				my $ca = substr($opline, 0, $off);
815				my $cc = '';
816				if (length($opline) >= ($off + length($elements[$n + 1]))) {
817					$cc = substr($opline, $off + length($elements[$n + 1]));
818				}
819				my $cb = "$ca$;$cc";
820
821				my $ctx = "${a}x${c}";
822
823				my $at = "(ctx:$ctx)";
824
825				my $ptr = (" " x $off) . "^";
826				my $hereptr = "$hereline$ptr\n";
827
828				# Classify operators into binary, unary, or
829				# definitions (* only) where they have more
830				# than one mode.
831				my $unary_ctx = $prevline . $ca;
832				$unary_ctx =~ s/^./ /;
833				my $is_unary = 0;
834				my $Unary = qr{
835					(?:
836						^|;|,|$ops|\(|\?|:|
837						\(\s*$Type\s*\)|
838						$Type|
839						return|case|else|
840						\{|\}|
841						\[|
842						^.\#\s*define\s+$Ident\s*(?:\([^\)]*\))?|
843						^.\#\s*else|
844						^.\#\s*endif|
845						^.\#\s*(?:if|ifndef|ifdef)\b.*
846					)\s*(?:|\\)\s*$
847				}x;
848				my $UnaryFalse = qr{
849					sizeof\s*\(\s*$Type\s*\)\s*$
850				}x;
851				my $UnaryDefine = qr{
852					 (?:$Type|$Bare)\s*|
853					 (?:$Type|$Bare).*,\s*\**
854				}x;
855				if ($op eq '-' || $op eq '&' || $op eq '*') {
856					# An operator is binary if the left hand
857					# side is a value.  Pick out the known
858					# non-values.
859					if ($unary_ctx =~ /$Unary$/s &&
860					    $unary_ctx !~ /$UnaryFalse$/s) {
861						$is_unary = 1;
862
863					# Special handling for ')' check if this
864					# brace represents a conditional, if so
865					# we are unary.
866					} elsif ($unary_ctx =~ /\)\s*$/) {
867						my $before = ctx_expr_before($unary_ctx);
868						if ($before =~ /(?:for|if|while)\s*$/) {
869							$is_unary = 1;
870						}
871					}
872
873					# Check for type definition for of '*'.
874					if ($op eq '*' && $unary_ctx =~ /$UnaryDefine$/) {
875						$is_unary = 2;
876					}
877				}
878
879				#if ($op eq '-' || $op eq '&' || $op eq '*') {
880				#	print "UNARY: <$is_unary $a:$op:$c> <$ca:$op:$cc> <$unary_ctx>\n";
881				#}
882
883				# ; should have either the end of line or a space or \ after it
884				if ($op eq ';') {
885					if ($ctx !~ /.x[WEB]/ && $cc !~ /^\\/ &&
886					    $cc !~ /^;/) {
887						ERROR("need space after that '$op' $at\n" . $hereptr);
888					}
889
890				# // is a comment
891				} elsif ($op eq '//') {
892
893				# -> should have no spaces
894				} elsif ($op eq '->') {
895					if ($ctx =~ /Wx.|.xW/) {
896						ERROR("no spaces around that '$op' $at\n" . $hereptr);
897					}
898
899				# , must have a space on the right.
900				} elsif ($op eq ',') {
901					if ($ctx !~ /.xW|.xE/ && $cc !~ /^}/) {
902						ERROR("need space after that '$op' $at\n" . $hereptr);
903					}
904
905				# '*' as part of a type definition -- reported already.
906				} elsif ($op eq '*' && $is_unary == 2) {
907					#warn "'*' is part of type\n";
908
909				# unary operators should have a space before and
910				# none after.  May be left adjacent to another
911				# unary operator, or a cast
912				} elsif ($op eq '!' || $op eq '~' ||
913				         ($is_unary && ($op eq '*' || $op eq '-' || $op eq '&'))) {
914					if ($ctx !~ /[WEB]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
915						ERROR("need space before that '$op' $at\n" . $hereptr);
916					}
917					if ($ctx =~ /.xW/) {
918						ERROR("no space after that '$op' $at\n" . $hereptr);
919					}
920
921				# unary ++ and unary -- are allowed no space on one side.
922				} elsif ($op eq '++' or $op eq '--') {
923					if ($ctx !~ /[WOB]x[^W]/ && $ctx !~ /[^W]x[WOBE]/) {
924						ERROR("need space one side of that '$op' $at\n" . $hereptr);
925					}
926					if ($ctx =~ /Wx./ && $cc =~ /^;/) {
927						ERROR("no space before that '$op' $at\n" . $hereptr);
928					}
929
930				# << and >> may either have or not have spaces both sides
931				} elsif ($op eq '<<' or $op eq '>>' or
932					 $op eq '&' or $op eq '^' or $op eq '|' or
933					 $op eq '+' or $op eq '-' or
934					 $op eq '*' or $op eq '/')
935				{
936					if ($ctx !~ /VxV|WxW|VxE|WxE|VxO/) {
937						ERROR("need consistent spacing around '$op' $at\n" .
938							$hereptr);
939					}
940
941				# All the others need spaces both sides.
942				} elsif ($ctx !~ /[EW]x[WE]/) {
943					# Ignore email addresses <foo@bar>
944					if (!($op eq '<' && $cb =~ /$;\S+\@\S+>/) &&
945					    !($op eq '>' && $cb =~ /<\S+\@\S+$;/)) {
946						ERROR("need spaces around that '$op' $at\n" . $hereptr);
947					}
948				}
949				$off += length($elements[$n + 1]);
950			}
951		}
952
953# check for multiple assignments
954		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
955			WARN("multiple assignments should be avoided\n" . $herecurr);
956		}
957
958## # check for multiple declarations, allowing for a function declaration
959## # continuation.
960## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
961## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
962##
963## 			# Remove any bracketed sections to ensure we do not
964## 			# falsly report the parameters of functions.
965## 			my $ln = $line;
966## 			while ($ln =~ s/\([^\(\)]*\)//g) {
967## 			}
968## 			if ($ln =~ /,/) {
969## 				WARN("declaring multiple variables together should be avoided\n" . $herecurr);
970## 			}
971## 		}
972
973#need space before brace following if, while, etc
974		if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
975		    $line =~ /do{/) {
976			ERROR("need a space before the open brace '{'\n" . $herecurr);
977		}
978
979# closing brace should have a space following it when it has anything
980# on the line
981		if ($line =~ /}(?!(?:,|;|\)))\S/) {
982			ERROR("need a space after that close brace '}'\n" . $herecurr);
983		}
984
985# check spacing on square brackets
986		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
987			ERROR("no space after that open square bracket '['\n" . $herecurr);
988		}
989		if ($line =~ /\s\]/) {
990			ERROR("no space before that close square bracket ']'\n" . $herecurr);
991		}
992
993# check spacing on paretheses
994		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
995		    $line !~ /for\s*\(\s+;/) {
996			ERROR("no space after that open parenthesis '('\n" . $herecurr);
997		}
998		if ($line =~ /\s\)/ && $line !~ /^.\s*\)/ &&
999		    $line !~ /for\s*\(.*;\s+\)/) {
1000			ERROR("no space before that close parenthesis ')'\n" . $herecurr);
1001		}
1002
1003#goto labels aren't indented, allow a single space however
1004		if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
1005		   !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
1006			WARN("labels should not be indented\n" . $herecurr);
1007		}
1008
1009# Need a space before open parenthesis after if, while etc
1010		if ($line=~/\b(if|while|for|switch)\(/) {
1011			ERROR("need a space before the open parenthesis '('\n" . $herecurr);
1012		}
1013
1014# Check for illegal assignment in if conditional.
1015		if ($line=~/\bif\s*\(.*[^<>!=]=[^=].*\)/) {
1016			#next if ($line=~/\".*\Q$op\E.*\"/ or $line=~/\'\Q$op\E\'/);
1017			ERROR("do not use assignment in if condition\n" . $herecurr);
1018		}
1019
1020		# Check for }<nl>else {, these must be at the same
1021		# indent level to be relevant to each other.
1022		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
1023						$previndent == $indent) {
1024			ERROR("else should follow close brace '}'\n" . $hereprev);
1025		}
1026
1027#studly caps, commented out until figure out how to distinguish between use of existing and adding new
1028#		if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
1029#		    print "No studly caps, use _\n";
1030#		    print "$herecurr";
1031#		    $clean = 0;
1032#		}
1033
1034#no spaces allowed after \ in define
1035		if ($line=~/\#define.*\\\s$/) {
1036			WARN("Whitepspace after \\ makes next lines useless\n" . $herecurr);
1037		}
1038
1039#warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
1040		if ($tree && $rawline =~ m{^.\#\s*include\s*\<asm\/(.*)\.h\>}) {
1041			my $checkfile = "include/linux/$1.h";
1042			if (-f $checkfile) {
1043				CHK("Use #include <linux/$1.h> instead of <asm/$1.h>\n" .
1044					$herecurr);
1045			}
1046		}
1047
1048# if and else should not have general statements after it
1049		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/ &&
1050		    $1 !~ /^\s*(?:\sif|{|\\|$)/) {
1051			ERROR("trailing statements should be on next line\n" . $herecurr);
1052		}
1053
1054# multi-statement macros should be enclosed in a do while loop, grab the
1055# first statement and ensure its the whole macro if its not enclosed
1056# in a known goot container
1057		if ($prevline =~ /\#define.*\\/ &&
1058		   $prevline !~/(?:do\s+{|\(\{|\{)/ &&
1059		   $line !~ /(?:do\s+{|\(\{|\{)/ &&
1060		   $line !~ /^.\s*$Declare\s/) {
1061			# Grab the first statement, if that is the entire macro
1062			# its ok.  This may start either on the #define line
1063			# or the one below.
1064			my $ln = $linenr;
1065			my $cnt = $realcnt;
1066			my $off = 0;
1067
1068			# If the macro starts on the define line start
1069			# grabbing the statement after the identifier
1070			$prevline =~ m{^(.#\s*define\s*$Ident(?:\([^\)]*\))?\s*)(.*)\\\s*$};
1071			##print "1<$1> 2<$2>\n";
1072			if (defined $2 && $2 ne '') {
1073				$off = length($1);
1074				$ln--;
1075				$cnt++;
1076			}
1077			my @ctx = ctx_statement($ln, $cnt, $off);
1078			my $ctx_ln = $ln + $#ctx + 1;
1079			my $ctx = join("\n", @ctx);
1080
1081			# Pull in any empty extension lines.
1082			while ($ctx =~ /\\$/ &&
1083			       $lines[$ctx_ln - 1] =~ /^.\s*(?:\\)?$/) {
1084				$ctx .= $lines[$ctx_ln - 1];
1085				$ctx_ln++;
1086			}
1087
1088			if ($ctx =~ /\\$/) {
1089				if ($ctx =~ /;/) {
1090					ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
1091				} else {
1092					ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
1093				}
1094			}
1095		}
1096
1097# check for redundant bracing round if etc
1098		if ($line =~ /\b(if|while|for|else)\b/) {
1099			# Locate the end of the opening statement.
1100			my @control = ctx_statement($linenr, $realcnt, 0);
1101			my $nr = $linenr + (scalar(@control) - 1);
1102			my $cnt = $realcnt - (scalar(@control) - 1);
1103
1104			my $off = $realcnt - $cnt;
1105			#print "$off: line<$line>end<" . $lines[$nr - 1] . ">\n";
1106
1107			# If this is is a braced statement group check it
1108			if ($lines[$nr - 1] =~ /{\s*$/) {
1109				my ($lvl, @block) = ctx_block_level($nr, $cnt);
1110
1111				my $stmt = join(' ', @block);
1112				$stmt =~ s/(^[^{]*){//;
1113				my $before = $1;
1114				$stmt =~ s/}([^}]*$)//;
1115				my $after = $1;
1116
1117				#print "block<" . join(' ', @block) . "><" . scalar(@block) . ">\n";
1118				#print "stmt<$stmt>\n\n";
1119
1120				# Count the ;'s if there is fewer than two
1121				# then there can only be one statement,
1122				# if there is a brace inside we cannot
1123				# trivially detect if its one statement.
1124				# Also nested if's often require braces to
1125				# disambiguate the else binding so shhh there.
1126				my @semi = ($stmt =~ /;/g);
1127				push(@semi, "/**/") if ($stmt =~ m@/\*@);
1128				##print "semi<" . scalar(@semi) . ">\n";
1129				if ($lvl == 0 && scalar(@semi) < 2 &&
1130				    $stmt !~ /{/ && $stmt !~ /\bif\b/ &&
1131				    $before !~ /}/ && $after !~ /{/) {
1132				    	my $herectx = "$here\n" . join("\n", @control, @block[1 .. $#block]) . "\n";
1133				    	shift(@block);
1134					WARN("braces {} are not necessary for single statement blocks\n" . $herectx);
1135				}
1136			}
1137		}
1138
1139# don't include deprecated include files (uses RAW line)
1140		for my $inc (@dep_includes) {
1141			if ($rawline =~ m@\#\s*include\s*\<$inc>@) {
1142				ERROR("Don't use <$inc>: see Documentation/feature-removal-schedule.txt\n" . $herecurr);
1143			}
1144		}
1145
1146# don't use deprecated functions
1147		for my $func (@dep_functions) {
1148			if ($line =~ /\b$func\b/) {
1149				ERROR("Don't use $func(): see Documentation/feature-removal-schedule.txt\n" . $herecurr);
1150			}
1151		}
1152
1153# no volatiles please
1154		if ($line =~ /\bvolatile\b/ && $line !~ /\basm\s+volatile\b/) {
1155			WARN("Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
1156		}
1157
1158# SPIN_LOCK_UNLOCKED & RW_LOCK_UNLOCKED are deprecated
1159		if ($line =~ /\b(SPIN_LOCK_UNLOCKED|RW_LOCK_UNLOCKED)/) {
1160			ERROR("Use of $1 is deprecated: see Documentation/spinlocks.txt\n" . $herecurr);
1161		}
1162
1163# warn about #if 0
1164		if ($line =~ /^.#\s*if\s+0\b/) {
1165			CHK("if this code is redundant consider removing it\n" .
1166				$herecurr);
1167		}
1168
1169# check for needless kfree() checks
1170		if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
1171			my $expr = $1;
1172			if ($line =~ /\bkfree\(\Q$expr\E\);/) {
1173				WARN("kfree(NULL) is safe this check is probabally not required\n" . $hereprev);
1174			}
1175		}
1176
1177# warn about #ifdefs in C files
1178#		if ($line =~ /^.#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
1179#			print "#ifdef in C files should be avoided\n";
1180#			print "$herecurr";
1181#			$clean = 0;
1182#		}
1183
1184# warn about spacing in #ifdefs
1185		if ($line =~ /^.#\s*(ifdef|ifndef|elif)\s\s+/) {
1186			ERROR("exactly one space required after that #$1\n" . $herecurr);
1187		}
1188
1189# check for spinlock_t definitions without a comment.
1190		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/) {
1191			my $which = $1;
1192			if (!ctx_has_comment($first_line, $linenr)) {
1193				CHK("$1 definition without comment\n" . $herecurr);
1194			}
1195		}
1196# check for memory barriers without a comment.
1197		if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
1198			if (!ctx_has_comment($first_line, $linenr)) {
1199				CHK("memory barrier without comment\n" . $herecurr);
1200			}
1201		}
1202# check of hardware specific defines
1203		if ($line =~ m@^.#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
1204			CHK("architecture specific defines should be avoided\n" .  $herecurr);
1205		}
1206
1207# check the location of the inline attribute, that it is between
1208# storage class and type.
1209		if ($line =~ /\b$Type\s+$Inline\b/ ||
1210		    $line =~ /\b$Inline\s+$Storage\b/) {
1211			ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
1212		}
1213
1214# check for new externs in .c files.
1215		if ($line =~ /^.\s*extern\s/ && ($realfile =~ /\.c$/)) {
1216			WARN("externs should be avoided in .c files\n" .  $herecurr);
1217		}
1218
1219# checks for new __setup's
1220		if ($rawline =~ /\b__setup\("([^"]*)"/) {
1221			my $name = $1;
1222
1223			if (!grep(/$name/, @setup_docs)) {
1224				CHK("__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
1225			}
1226		}
1227
1228# check for pointless casting of kmalloc return
1229		if ($line =~ /\*\s*\)\s*k[czm]alloc\b/) {
1230			WARN("unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
1231		}
1232	}
1233
1234	if ($chk_patch && !$is_patch) {
1235		ERROR("Does not appear to be a unified-diff format patch\n");
1236	}
1237	if ($is_patch && $chk_signoff && $signoff == 0) {
1238		ERROR("Missing Signed-off-by: line(s)\n");
1239	}
1240
1241	if ($clean == 0 && ($chk_patch || $is_patch)) {
1242		print report_dump();
1243	}
1244	if ($clean == 1 && $quiet == 0) {
1245		print "Your patch has no obvious style problems and is ready for submission.\n"
1246	}
1247	if ($clean == 0 && $quiet == 0) {
1248		print "Your patch has style problems, please review.  If any of these errors\n";
1249		print "are false positives report them to the maintainer, see\n";
1250		print "CHECKPATCH in MAINTAINERS.\n";
1251	}
1252	return $clean;
1253}
1254