xref: /openbmc/u-boot/scripts/checkpatch.pl (revision eb5ba3ae)
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;
9use POSIX;
10use File::Basename;
11use Cwd 'abs_path';
12
13my $P = $0;
14$P =~ s@.*/@@g;
15my $D = dirname(abs_path($P));
16
17my $V = '0.32';
18
19use Getopt::Long qw(:config no_auto_abbrev);
20
21my $quiet = 0;
22my $tree = 1;
23my $chk_signoff = 1;
24my $chk_patch = 1;
25my $tst_only;
26my $emacs = 0;
27my $terse = 0;
28my $file = 0;
29my $check = 0;
30my $summary = 1;
31my $mailback = 0;
32my $summary_file = 0;
33my $show_types = 0;
34my $fix = 0;
35my $fix_inplace = 0;
36my $root;
37my %debug;
38my %camelcase = ();
39my %use_type = ();
40my @use = ();
41my %ignore_type = ();
42my @ignore = ();
43my $help = 0;
44my $configuration_file = ".checkpatch.conf";
45my $max_line_length = 80;
46my $ignore_perl_version = 0;
47my $minimum_perl_version = 5.10.0;
48my $spelling_file = "$D/spelling.txt";
49my $codespell = 0;
50my $codespellfile = "/usr/share/codespell/dictionary.txt";
51
52sub help {
53	my ($exitcode) = @_;
54
55	print << "EOM";
56Usage: $P [OPTION]... [FILE]...
57Version: $V
58
59Options:
60  -q, --quiet                quiet
61  --no-tree                  run without a kernel tree
62  --no-signoff               do not check for 'Signed-off-by' line
63  --patch                    treat FILE as patchfile (default)
64  --emacs                    emacs compile window format
65  --terse                    one line per report
66  -f, --file                 treat FILE as regular source file
67  --subjective, --strict     enable more subjective tests
68  --types TYPE(,TYPE2...)    show only these comma separated message types
69  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
70  --max-line-length=n        set the maximum line length, if exceeded, warn
71  --show-types               show the message "types" in the output
72  --root=PATH                PATH to the kernel tree root
73  --no-summary               suppress the per-file summary
74  --mailback                 only produce a report in case of warnings/errors
75  --summary-file             include the filename in summary
76  --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
77                             'values', 'possible', 'type', and 'attr' (default
78                             is all off)
79  --test-only=WORD           report only warnings/errors containing WORD
80                             literally
81  --fix                      EXPERIMENTAL - may create horrible results
82                             If correctable single-line errors exist, create
83                             "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84                             with potential errors corrected to the preferred
85                             checkpatch style
86  --fix-inplace              EXPERIMENTAL - may create horrible results
87                             Is the same as --fix, but overwrites the input
88                             file.  It's your fault if there's no backup or git
89  --ignore-perl-version      override checking of perl version.  expect
90                             runtime errors.
91  --codespell                Use the codespell dictionary for spelling/typos
92                             (default:/usr/local/share/codespell/dictionary.txt)
93  --codespellfile            Use this codespell dictionary
94  -h, --help, --version      display this help and exit
95
96When FILE is - read standard input.
97EOM
98
99	exit($exitcode);
100}
101
102my $conf = which_conf($configuration_file);
103if (-f $conf) {
104	my @conf_args;
105	open(my $conffile, '<', "$conf")
106	    or warn "$P: Can't find a readable $configuration_file file $!\n";
107
108	while (<$conffile>) {
109		my $line = $_;
110
111		$line =~ s/\s*\n?$//g;
112		$line =~ s/^\s*//g;
113		$line =~ s/\s+/ /g;
114
115		next if ($line =~ m/^\s*#/);
116		next if ($line =~ m/^\s*$/);
117
118		my @words = split(" ", $line);
119		foreach my $word (@words) {
120			last if ($word =~ m/^#/);
121			push (@conf_args, $word);
122		}
123	}
124	close($conffile);
125	unshift(@ARGV, @conf_args) if @conf_args;
126}
127
128GetOptions(
129	'q|quiet+'	=> \$quiet,
130	'tree!'		=> \$tree,
131	'signoff!'	=> \$chk_signoff,
132	'patch!'	=> \$chk_patch,
133	'emacs!'	=> \$emacs,
134	'terse!'	=> \$terse,
135	'f|file!'	=> \$file,
136	'subjective!'	=> \$check,
137	'strict!'	=> \$check,
138	'ignore=s'	=> \@ignore,
139	'types=s'	=> \@use,
140	'show-types!'	=> \$show_types,
141	'max-line-length=i' => \$max_line_length,
142	'root=s'	=> \$root,
143	'summary!'	=> \$summary,
144	'mailback!'	=> \$mailback,
145	'summary-file!'	=> \$summary_file,
146	'fix!'		=> \$fix,
147	'fix-inplace!'	=> \$fix_inplace,
148	'ignore-perl-version!' => \$ignore_perl_version,
149	'debug=s'	=> \%debug,
150	'test-only=s'	=> \$tst_only,
151	'codespell!'    => \$codespell,
152	'codespellfile=s' => \$codespellfile,
153	'h|help'	=> \$help,
154	'version'	=> \$help
155) or help(1);
156
157help(0) if ($help);
158
159$fix = 1 if ($fix_inplace);
160
161my $exit = 0;
162
163if ($^V && $^V lt $minimum_perl_version) {
164	printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
165	if (!$ignore_perl_version) {
166		exit(1);
167	}
168}
169
170if ($#ARGV < 0) {
171	print "$P: no input files\n";
172	exit(1);
173}
174
175sub hash_save_array_words {
176	my ($hashRef, $arrayRef) = @_;
177
178	my @array = split(/,/, join(',', @$arrayRef));
179	foreach my $word (@array) {
180		$word =~ s/\s*\n?$//g;
181		$word =~ s/^\s*//g;
182		$word =~ s/\s+/ /g;
183		$word =~ tr/[a-z]/[A-Z]/;
184
185		next if ($word =~ m/^\s*#/);
186		next if ($word =~ m/^\s*$/);
187
188		$hashRef->{$word}++;
189	}
190}
191
192sub hash_show_words {
193	my ($hashRef, $prefix) = @_;
194
195	if ($quiet == 0 && keys %$hashRef) {
196		print "NOTE: $prefix message types:";
197		foreach my $word (sort keys %$hashRef) {
198			print " $word";
199		}
200		print "\n\n";
201	}
202}
203
204hash_save_array_words(\%ignore_type, \@ignore);
205hash_save_array_words(\%use_type, \@use);
206
207my $dbg_values = 0;
208my $dbg_possible = 0;
209my $dbg_type = 0;
210my $dbg_attr = 0;
211for my $key (keys %debug) {
212	## no critic
213	eval "\${dbg_$key} = '$debug{$key}';";
214	die "$@" if ($@);
215}
216
217my $rpt_cleaners = 0;
218
219if ($terse) {
220	$emacs = 1;
221	$quiet++;
222}
223
224if ($tree) {
225	if (defined $root) {
226		if (!top_of_kernel_tree($root)) {
227			die "$P: $root: --root does not point at a valid tree\n";
228		}
229	} else {
230		if (top_of_kernel_tree('.')) {
231			$root = '.';
232		} elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
233						top_of_kernel_tree($1)) {
234			$root = $1;
235		}
236	}
237
238	if (!defined $root) {
239		print "Must be run from the top-level dir. of a kernel tree\n";
240		exit(2);
241	}
242}
243
244my $emitted_corrupt = 0;
245
246our $Ident	= qr{
247			[A-Za-z_][A-Za-z\d_]*
248			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
249		}x;
250our $Storage	= qr{extern|static|asmlinkage};
251our $Sparse	= qr{
252			__user|
253			__kernel|
254			__force|
255			__iomem|
256			__must_check|
257			__init_refok|
258			__kprobes|
259			__ref|
260			__rcu
261		}x;
262our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
263our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
264our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
265our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
266our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
267
268# Notes to $Attribute:
269# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
270our $Attribute	= qr{
271			const|
272			__percpu|
273			__nocast|
274			__safe|
275			__bitwise__|
276			__packed__|
277			__packed2__|
278			__naked|
279			__maybe_unused|
280			__always_unused|
281			__noreturn|
282			__used|
283			__cold|
284			__noclone|
285			__deprecated|
286			__read_mostly|
287			__kprobes|
288			$InitAttribute|
289			____cacheline_aligned|
290			____cacheline_aligned_in_smp|
291			____cacheline_internodealigned_in_smp|
292			__weak
293		  }x;
294our $Modifier;
295our $Inline	= qr{inline|__always_inline|noinline};
296our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
297our $Lval	= qr{$Ident(?:$Member)*};
298
299our $Int_type	= qr{(?i)llu|ull|ll|lu|ul|l|u};
300our $Binary	= qr{(?i)0b[01]+$Int_type?};
301our $Hex	= qr{(?i)0x[0-9a-f]+$Int_type?};
302our $Int	= qr{[0-9]+$Int_type?};
303our $Float_hex	= qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
304our $Float_dec	= qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
305our $Float_int	= qr{(?i)[0-9]+e-?[0-9]+[fl]?};
306our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
307our $Constant	= qr{$Float|$Binary|$Hex|$Int};
308our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
309our $Compare    = qr{<=|>=|==|!=|<|>};
310our $Arithmetic = qr{\+|-|\*|\/|%};
311our $Operators	= qr{
312			<=|>=|==|!=|
313			=>|->|<<|>>|<|>|!|~|
314			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
315		  }x;
316
317our $NonptrType;
318our $NonptrTypeWithAttr;
319our $Type;
320our $Declare;
321
322our $NON_ASCII_UTF8	= qr{
323	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
324	|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
325	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
326	|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
327	|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
328	| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
329	|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
330}x;
331
332our $UTF8	= qr{
333	[\x09\x0A\x0D\x20-\x7E]              # ASCII
334	| $NON_ASCII_UTF8
335}x;
336
337our $typeTypedefs = qr{(?x:
338	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
339	atomic_t
340)};
341
342our $logFunctions = qr{(?x:
343	printk(?:_ratelimited|_once|)|
344	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
345	WARN(?:_RATELIMIT|_ONCE|)|
346	panic|
347	debug|
348	printf|
349	puts|
350	MODULE_[A-Z_]+|
351	seq_vprintf|seq_printf|seq_puts
352)};
353
354our $signature_tags = qr{(?xi:
355	Signed-off-by:|
356	Acked-by:|
357	Tested-by:|
358	Reviewed-by:|
359	Reported-by:|
360	Suggested-by:|
361	To:|
362	Cc:
363)};
364
365our @typeList = (
366	qr{void},
367	qr{(?:unsigned\s+)?char},
368	qr{(?:unsigned\s+)?short},
369	qr{(?:unsigned\s+)?int},
370	qr{(?:unsigned\s+)?long},
371	qr{(?:unsigned\s+)?long\s+int},
372	qr{(?:unsigned\s+)?long\s+long},
373	qr{(?:unsigned\s+)?long\s+long\s+int},
374	qr{unsigned},
375	qr{float},
376	qr{double},
377	qr{bool},
378	qr{struct\s+$Ident},
379	qr{union\s+$Ident},
380	qr{enum\s+$Ident},
381	qr{${Ident}_t},
382	qr{${Ident}_handler},
383	qr{${Ident}_handler_fn},
384);
385our @typeListWithAttr = (
386	@typeList,
387	qr{struct\s+$InitAttribute\s+$Ident},
388	qr{union\s+$InitAttribute\s+$Ident},
389);
390
391our @modifierList = (
392	qr{fastcall},
393);
394
395our $allowed_asm_includes = qr{(?x:
396	irq|
397	memory
398)};
399# memory.h: ARM has a custom one
400
401# Load common spelling mistakes and build regular expression list.
402my $misspellings;
403my %spelling_fix;
404
405if (open(my $spelling, '<', $spelling_file)) {
406	while (<$spelling>) {
407		my $line = $_;
408
409		$line =~ s/\s*\n?$//g;
410		$line =~ s/^\s*//g;
411
412		next if ($line =~ m/^\s*#/);
413		next if ($line =~ m/^\s*$/);
414
415		my ($suspect, $fix) = split(/\|\|/, $line);
416
417		$spelling_fix{$suspect} = $fix;
418	}
419	close($spelling);
420} else {
421	warn "No typos will be found - file '$spelling_file': $!\n";
422}
423
424if ($codespell) {
425	if (open(my $spelling, '<', $codespellfile)) {
426		while (<$spelling>) {
427			my $line = $_;
428
429			$line =~ s/\s*\n?$//g;
430			$line =~ s/^\s*//g;
431
432			next if ($line =~ m/^\s*#/);
433			next if ($line =~ m/^\s*$/);
434			next if ($line =~ m/, disabled/i);
435
436			$line =~ s/,.*$//;
437
438			my ($suspect, $fix) = split(/->/, $line);
439
440			$spelling_fix{$suspect} = $fix;
441		}
442		close($spelling);
443	} else {
444		warn "No codespell typos will be found - file '$codespellfile': $!\n";
445	}
446}
447
448$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
449
450
451sub build_types {
452	my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
453	my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
454	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
455	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
456	$NonptrType	= qr{
457			(?:$Modifier\s+|const\s+)*
458			(?:
459				(?:typeof|__typeof__)\s*\([^\)]*\)|
460				(?:$typeTypedefs\b)|
461				(?:${all}\b)
462			)
463			(?:\s+$Modifier|\s+const)*
464		  }x;
465	$NonptrTypeWithAttr	= qr{
466			(?:$Modifier\s+|const\s+)*
467			(?:
468				(?:typeof|__typeof__)\s*\([^\)]*\)|
469				(?:$typeTypedefs\b)|
470				(?:${allWithAttr}\b)
471			)
472			(?:\s+$Modifier|\s+const)*
473		  }x;
474	$Type	= qr{
475			$NonptrType
476			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*|\[\])+|(?:\s*\[\s*\])+)?
477			(?:\s+$Inline|\s+$Modifier)*
478		  }x;
479	$Declare	= qr{(?:$Storage\s+)?$Type};
480}
481build_types();
482
483our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
484
485# Using $balanced_parens, $LvalOrFunc, or $FuncArg
486# requires at least perl version v5.10.0
487# Any use must be runtime checked with $^V
488
489our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
490our $LvalOrFunc	= qr{($Lval)\s*($balanced_parens{0,1})\s*};
491our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
492
493sub deparenthesize {
494	my ($string) = @_;
495	return "" if (!defined($string));
496	$string =~ s@^\s*\(\s*@@g;
497	$string =~ s@\s*\)\s*$@@g;
498	$string =~ s@\s+@ @g;
499	return $string;
500}
501
502sub seed_camelcase_file {
503	my ($file) = @_;
504
505	return if (!(-f $file));
506
507	local $/;
508
509	open(my $include_file, '<', "$file")
510	    or warn "$P: Can't read '$file' $!\n";
511	my $text = <$include_file>;
512	close($include_file);
513
514	my @lines = split('\n', $text);
515
516	foreach my $line (@lines) {
517		next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
518		if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
519			$camelcase{$1} = 1;
520		} elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
521			$camelcase{$1} = 1;
522		} elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
523			$camelcase{$1} = 1;
524		}
525	}
526}
527
528my $camelcase_seeded = 0;
529sub seed_camelcase_includes {
530	return if ($camelcase_seeded);
531
532	my $files;
533	my $camelcase_cache = "";
534	my @include_files = ();
535
536	$camelcase_seeded = 1;
537
538	if (-e ".git") {
539		my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
540		chomp $git_last_include_commit;
541		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
542	} else {
543		my $last_mod_date = 0;
544		$files = `find $root/include -name "*.h"`;
545		@include_files = split('\n', $files);
546		foreach my $file (@include_files) {
547			my $date = POSIX::strftime("%Y%m%d%H%M",
548						   localtime((stat $file)[9]));
549			$last_mod_date = $date if ($last_mod_date < $date);
550		}
551		$camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
552	}
553
554	if ($camelcase_cache ne "" && -f $camelcase_cache) {
555		open(my $camelcase_file, '<', "$camelcase_cache")
556		    or warn "$P: Can't read '$camelcase_cache' $!\n";
557		while (<$camelcase_file>) {
558			chomp;
559			$camelcase{$_} = 1;
560		}
561		close($camelcase_file);
562
563		return;
564	}
565
566	if (-e ".git") {
567		$files = `git ls-files "include/*.h"`;
568		@include_files = split('\n', $files);
569	}
570
571	foreach my $file (@include_files) {
572		seed_camelcase_file($file);
573	}
574
575	if ($camelcase_cache ne "") {
576		unlink glob ".checkpatch-camelcase.*";
577		open(my $camelcase_file, '>', "$camelcase_cache")
578		    or warn "$P: Can't write '$camelcase_cache' $!\n";
579		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
580			print $camelcase_file ("$_\n");
581		}
582		close($camelcase_file);
583	}
584}
585
586$chk_signoff = 0 if ($file);
587
588my @rawlines = ();
589my @lines = ();
590my @fixed = ();
591my $vname;
592my $fixlinenr = -1;
593
594for my $filename (@ARGV) {
595	my $FILE;
596	if ($file) {
597		open($FILE, '-|', "diff -u /dev/null $filename") ||
598			die "$P: $filename: diff failed - $!\n";
599	} elsif ($filename eq '-') {
600		open($FILE, '<&STDIN');
601	} else {
602		open($FILE, '<', "$filename") ||
603			die "$P: $filename: open failed - $!\n";
604	}
605	if ($filename eq '-') {
606		$vname = 'Your patch';
607	} else {
608		$vname = $filename;
609	}
610	while (<$FILE>) {
611		chomp;
612		push(@rawlines, $_);
613	}
614	close($FILE);
615	if (!process($filename)) {
616		$exit = 1;
617	}
618	@rawlines = ();
619	@lines = ();
620	@fixed = ();
621}
622
623exit($exit);
624
625sub top_of_kernel_tree {
626	my ($root) = @_;
627
628	my @tree_check = (
629		"COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
630		"README", "Documentation", "arch", "include", "drivers",
631		"fs", "init", "ipc", "kernel", "lib", "scripts",
632	);
633
634	foreach my $check (@tree_check) {
635		if (! -e $root . '/' . $check) {
636			return 0;
637		}
638	}
639	return 1;
640}
641
642sub parse_email {
643	my ($formatted_email) = @_;
644
645	my $name = "";
646	my $address = "";
647	my $comment = "";
648
649	if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
650		$name = $1;
651		$address = $2;
652		$comment = $3 if defined $3;
653	} elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
654		$address = $1;
655		$comment = $2 if defined $2;
656	} elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
657		$address = $1;
658		$comment = $2 if defined $2;
659		$formatted_email =~ s/$address.*$//;
660		$name = $formatted_email;
661		$name = trim($name);
662		$name =~ s/^\"|\"$//g;
663		# If there's a name left after stripping spaces and
664		# leading quotes, and the address doesn't have both
665		# leading and trailing angle brackets, the address
666		# is invalid. ie:
667		#   "joe smith joe@smith.com" bad
668		#   "joe smith <joe@smith.com" bad
669		if ($name ne "" && $address !~ /^<[^>]+>$/) {
670			$name = "";
671			$address = "";
672			$comment = "";
673		}
674	}
675
676	$name = trim($name);
677	$name =~ s/^\"|\"$//g;
678	$address = trim($address);
679	$address =~ s/^\<|\>$//g;
680
681	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
682		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
683		$name = "\"$name\"";
684	}
685
686	return ($name, $address, $comment);
687}
688
689sub format_email {
690	my ($name, $address) = @_;
691
692	my $formatted_email;
693
694	$name = trim($name);
695	$name =~ s/^\"|\"$//g;
696	$address = trim($address);
697
698	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
699		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
700		$name = "\"$name\"";
701	}
702
703	if ("$name" eq "") {
704		$formatted_email = "$address";
705	} else {
706		$formatted_email = "$name <$address>";
707	}
708
709	return $formatted_email;
710}
711
712sub which_conf {
713	my ($conf) = @_;
714
715	foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
716		if (-e "$path/$conf") {
717			return "$path/$conf";
718		}
719	}
720
721	return "";
722}
723
724sub expand_tabs {
725	my ($str) = @_;
726
727	my $res = '';
728	my $n = 0;
729	for my $c (split(//, $str)) {
730		if ($c eq "\t") {
731			$res .= ' ';
732			$n++;
733			for (; ($n % 8) != 0; $n++) {
734				$res .= ' ';
735			}
736			next;
737		}
738		$res .= $c;
739		$n++;
740	}
741
742	return $res;
743}
744sub copy_spacing {
745	(my $res = shift) =~ tr/\t/ /c;
746	return $res;
747}
748
749sub line_stats {
750	my ($line) = @_;
751
752	# Drop the diff line leader and expand tabs
753	$line =~ s/^.//;
754	$line = expand_tabs($line);
755
756	# Pick the indent from the front of the line.
757	my ($white) = ($line =~ /^(\s*)/);
758
759	return (length($line), length($white));
760}
761
762my $sanitise_quote = '';
763
764sub sanitise_line_reset {
765	my ($in_comment) = @_;
766
767	if ($in_comment) {
768		$sanitise_quote = '*/';
769	} else {
770		$sanitise_quote = '';
771	}
772}
773sub sanitise_line {
774	my ($line) = @_;
775
776	my $res = '';
777	my $l = '';
778
779	my $qlen = 0;
780	my $off = 0;
781	my $c;
782
783	# Always copy over the diff marker.
784	$res = substr($line, 0, 1);
785
786	for ($off = 1; $off < length($line); $off++) {
787		$c = substr($line, $off, 1);
788
789		# Comments we are wacking completly including the begin
790		# and end, all to $;.
791		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
792			$sanitise_quote = '*/';
793
794			substr($res, $off, 2, "$;$;");
795			$off++;
796			next;
797		}
798		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
799			$sanitise_quote = '';
800			substr($res, $off, 2, "$;$;");
801			$off++;
802			next;
803		}
804		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
805			$sanitise_quote = '//';
806
807			substr($res, $off, 2, $sanitise_quote);
808			$off++;
809			next;
810		}
811
812		# A \ in a string means ignore the next character.
813		if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
814		    $c eq "\\") {
815			substr($res, $off, 2, 'XX');
816			$off++;
817			next;
818		}
819		# Regular quotes.
820		if ($c eq "'" || $c eq '"') {
821			if ($sanitise_quote eq '') {
822				$sanitise_quote = $c;
823
824				substr($res, $off, 1, $c);
825				next;
826			} elsif ($sanitise_quote eq $c) {
827				$sanitise_quote = '';
828			}
829		}
830
831		#print "c<$c> SQ<$sanitise_quote>\n";
832		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
833			substr($res, $off, 1, $;);
834		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
835			substr($res, $off, 1, $;);
836		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
837			substr($res, $off, 1, 'X');
838		} else {
839			substr($res, $off, 1, $c);
840		}
841	}
842
843	if ($sanitise_quote eq '//') {
844		$sanitise_quote = '';
845	}
846
847	# The pathname on a #include may be surrounded by '<' and '>'.
848	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
849		my $clean = 'X' x length($1);
850		$res =~ s@\<.*\>@<$clean>@;
851
852	# The whole of a #error is a string.
853	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
854		my $clean = 'X' x length($1);
855		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
856	}
857
858	return $res;
859}
860
861sub get_quoted_string {
862	my ($line, $rawline) = @_;
863
864	return "" if ($line !~ m/(\"[X]+\")/g);
865	return substr($rawline, $-[0], $+[0] - $-[0]);
866}
867
868sub ctx_statement_block {
869	my ($linenr, $remain, $off) = @_;
870	my $line = $linenr - 1;
871	my $blk = '';
872	my $soff = $off;
873	my $coff = $off - 1;
874	my $coff_set = 0;
875
876	my $loff = 0;
877
878	my $type = '';
879	my $level = 0;
880	my @stack = ();
881	my $p;
882	my $c;
883	my $len = 0;
884
885	my $remainder;
886	while (1) {
887		@stack = (['', 0]) if ($#stack == -1);
888
889		#warn "CSB: blk<$blk> remain<$remain>\n";
890		# If we are about to drop off the end, pull in more
891		# context.
892		if ($off >= $len) {
893			for (; $remain > 0; $line++) {
894				last if (!defined $lines[$line]);
895				next if ($lines[$line] =~ /^-/);
896				$remain--;
897				$loff = $len;
898				$blk .= $lines[$line] . "\n";
899				$len = length($blk);
900				$line++;
901				last;
902			}
903			# Bail if there is no further context.
904			#warn "CSB: blk<$blk> off<$off> len<$len>\n";
905			if ($off >= $len) {
906				last;
907			}
908			if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
909				$level++;
910				$type = '#';
911			}
912		}
913		$p = $c;
914		$c = substr($blk, $off, 1);
915		$remainder = substr($blk, $off);
916
917		#warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
918
919		# Handle nested #if/#else.
920		if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
921			push(@stack, [ $type, $level ]);
922		} elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
923			($type, $level) = @{$stack[$#stack - 1]};
924		} elsif ($remainder =~ /^#\s*endif\b/) {
925			($type, $level) = @{pop(@stack)};
926		}
927
928		# Statement ends at the ';' or a close '}' at the
929		# outermost level.
930		if ($level == 0 && $c eq ';') {
931			last;
932		}
933
934		# An else is really a conditional as long as its not else if
935		if ($level == 0 && $coff_set == 0 &&
936				(!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
937				$remainder =~ /^(else)(?:\s|{)/ &&
938				$remainder !~ /^else\s+if\b/) {
939			$coff = $off + length($1) - 1;
940			$coff_set = 1;
941			#warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
942			#warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
943		}
944
945		if (($type eq '' || $type eq '(') && $c eq '(') {
946			$level++;
947			$type = '(';
948		}
949		if ($type eq '(' && $c eq ')') {
950			$level--;
951			$type = ($level != 0)? '(' : '';
952
953			if ($level == 0 && $coff < $soff) {
954				$coff = $off;
955				$coff_set = 1;
956				#warn "CSB: mark coff<$coff>\n";
957			}
958		}
959		if (($type eq '' || $type eq '{') && $c eq '{') {
960			$level++;
961			$type = '{';
962		}
963		if ($type eq '{' && $c eq '}') {
964			$level--;
965			$type = ($level != 0)? '{' : '';
966
967			if ($level == 0) {
968				if (substr($blk, $off + 1, 1) eq ';') {
969					$off++;
970				}
971				last;
972			}
973		}
974		# Preprocessor commands end at the newline unless escaped.
975		if ($type eq '#' && $c eq "\n" && $p ne "\\") {
976			$level--;
977			$type = '';
978			$off++;
979			last;
980		}
981		$off++;
982	}
983	# We are truly at the end, so shuffle to the next line.
984	if ($off == $len) {
985		$loff = $len + 1;
986		$line++;
987		$remain--;
988	}
989
990	my $statement = substr($blk, $soff, $off - $soff + 1);
991	my $condition = substr($blk, $soff, $coff - $soff + 1);
992
993	#warn "STATEMENT<$statement>\n";
994	#warn "CONDITION<$condition>\n";
995
996	#print "coff<$coff> soff<$off> loff<$loff>\n";
997
998	return ($statement, $condition,
999			$line, $remain + 1, $off - $loff + 1, $level);
1000}
1001
1002sub statement_lines {
1003	my ($stmt) = @_;
1004
1005	# Strip the diff line prefixes and rip blank lines at start and end.
1006	$stmt =~ s/(^|\n)./$1/g;
1007	$stmt =~ s/^\s*//;
1008	$stmt =~ s/\s*$//;
1009
1010	my @stmt_lines = ($stmt =~ /\n/g);
1011
1012	return $#stmt_lines + 2;
1013}
1014
1015sub statement_rawlines {
1016	my ($stmt) = @_;
1017
1018	my @stmt_lines = ($stmt =~ /\n/g);
1019
1020	return $#stmt_lines + 2;
1021}
1022
1023sub statement_block_size {
1024	my ($stmt) = @_;
1025
1026	$stmt =~ s/(^|\n)./$1/g;
1027	$stmt =~ s/^\s*{//;
1028	$stmt =~ s/}\s*$//;
1029	$stmt =~ s/^\s*//;
1030	$stmt =~ s/\s*$//;
1031
1032	my @stmt_lines = ($stmt =~ /\n/g);
1033	my @stmt_statements = ($stmt =~ /;/g);
1034
1035	my $stmt_lines = $#stmt_lines + 2;
1036	my $stmt_statements = $#stmt_statements + 1;
1037
1038	if ($stmt_lines > $stmt_statements) {
1039		return $stmt_lines;
1040	} else {
1041		return $stmt_statements;
1042	}
1043}
1044
1045sub ctx_statement_full {
1046	my ($linenr, $remain, $off) = @_;
1047	my ($statement, $condition, $level);
1048
1049	my (@chunks);
1050
1051	# Grab the first conditional/block pair.
1052	($statement, $condition, $linenr, $remain, $off, $level) =
1053				ctx_statement_block($linenr, $remain, $off);
1054	#print "F: c<$condition> s<$statement> remain<$remain>\n";
1055	push(@chunks, [ $condition, $statement ]);
1056	if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1057		return ($level, $linenr, @chunks);
1058	}
1059
1060	# Pull in the following conditional/block pairs and see if they
1061	# could continue the statement.
1062	for (;;) {
1063		($statement, $condition, $linenr, $remain, $off, $level) =
1064				ctx_statement_block($linenr, $remain, $off);
1065		#print "C: c<$condition> s<$statement> remain<$remain>\n";
1066		last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1067		#print "C: push\n";
1068		push(@chunks, [ $condition, $statement ]);
1069	}
1070
1071	return ($level, $linenr, @chunks);
1072}
1073
1074sub ctx_block_get {
1075	my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1076	my $line;
1077	my $start = $linenr - 1;
1078	my $blk = '';
1079	my @o;
1080	my @c;
1081	my @res = ();
1082
1083	my $level = 0;
1084	my @stack = ($level);
1085	for ($line = $start; $remain > 0; $line++) {
1086		next if ($rawlines[$line] =~ /^-/);
1087		$remain--;
1088
1089		$blk .= $rawlines[$line];
1090
1091		# Handle nested #if/#else.
1092		if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1093			push(@stack, $level);
1094		} elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1095			$level = $stack[$#stack - 1];
1096		} elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1097			$level = pop(@stack);
1098		}
1099
1100		foreach my $c (split(//, $lines[$line])) {
1101			##print "C<$c>L<$level><$open$close>O<$off>\n";
1102			if ($off > 0) {
1103				$off--;
1104				next;
1105			}
1106
1107			if ($c eq $close && $level > 0) {
1108				$level--;
1109				last if ($level == 0);
1110			} elsif ($c eq $open) {
1111				$level++;
1112			}
1113		}
1114
1115		if (!$outer || $level <= 1) {
1116			push(@res, $rawlines[$line]);
1117		}
1118
1119		last if ($level == 0);
1120	}
1121
1122	return ($level, @res);
1123}
1124sub ctx_block_outer {
1125	my ($linenr, $remain) = @_;
1126
1127	my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1128	return @r;
1129}
1130sub ctx_block {
1131	my ($linenr, $remain) = @_;
1132
1133	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1134	return @r;
1135}
1136sub ctx_statement {
1137	my ($linenr, $remain, $off) = @_;
1138
1139	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1140	return @r;
1141}
1142sub ctx_block_level {
1143	my ($linenr, $remain) = @_;
1144
1145	return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1146}
1147sub ctx_statement_level {
1148	my ($linenr, $remain, $off) = @_;
1149
1150	return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1151}
1152
1153sub ctx_locate_comment {
1154	my ($first_line, $end_line) = @_;
1155
1156	# Catch a comment on the end of the line itself.
1157	my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1158	return $current_comment if (defined $current_comment);
1159
1160	# Look through the context and try and figure out if there is a
1161	# comment.
1162	my $in_comment = 0;
1163	$current_comment = '';
1164	for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1165		my $line = $rawlines[$linenr - 1];
1166		#warn "           $line\n";
1167		if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1168			$in_comment = 1;
1169		}
1170		if ($line =~ m@/\*@) {
1171			$in_comment = 1;
1172		}
1173		if (!$in_comment && $current_comment ne '') {
1174			$current_comment = '';
1175		}
1176		$current_comment .= $line . "\n" if ($in_comment);
1177		if ($line =~ m@\*/@) {
1178			$in_comment = 0;
1179		}
1180	}
1181
1182	chomp($current_comment);
1183	return($current_comment);
1184}
1185sub ctx_has_comment {
1186	my ($first_line, $end_line) = @_;
1187	my $cmt = ctx_locate_comment($first_line, $end_line);
1188
1189	##print "LINE: $rawlines[$end_line - 1 ]\n";
1190	##print "CMMT: $cmt\n";
1191
1192	return ($cmt ne '');
1193}
1194
1195sub raw_line {
1196	my ($linenr, $cnt) = @_;
1197
1198	my $offset = $linenr - 1;
1199	$cnt++;
1200
1201	my $line;
1202	while ($cnt) {
1203		$line = $rawlines[$offset++];
1204		next if (defined($line) && $line =~ /^-/);
1205		$cnt--;
1206	}
1207
1208	return $line;
1209}
1210
1211sub cat_vet {
1212	my ($vet) = @_;
1213	my ($res, $coded);
1214
1215	$res = '';
1216	while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1217		$res .= $1;
1218		if ($2 ne '') {
1219			$coded = sprintf("^%c", unpack('C', $2) + 64);
1220			$res .= $coded;
1221		}
1222	}
1223	$res =~ s/$/\$/;
1224
1225	return $res;
1226}
1227
1228my $av_preprocessor = 0;
1229my $av_pending;
1230my @av_paren_type;
1231my $av_pend_colon;
1232
1233sub annotate_reset {
1234	$av_preprocessor = 0;
1235	$av_pending = '_';
1236	@av_paren_type = ('E');
1237	$av_pend_colon = 'O';
1238}
1239
1240sub annotate_values {
1241	my ($stream, $type) = @_;
1242
1243	my $res;
1244	my $var = '_' x length($stream);
1245	my $cur = $stream;
1246
1247	print "$stream\n" if ($dbg_values > 1);
1248
1249	while (length($cur)) {
1250		@av_paren_type = ('E') if ($#av_paren_type < 0);
1251		print " <" . join('', @av_paren_type) .
1252				"> <$type> <$av_pending>" if ($dbg_values > 1);
1253		if ($cur =~ /^(\s+)/o) {
1254			print "WS($1)\n" if ($dbg_values > 1);
1255			if ($1 =~ /\n/ && $av_preprocessor) {
1256				$type = pop(@av_paren_type);
1257				$av_preprocessor = 0;
1258			}
1259
1260		} elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1261			print "CAST($1)\n" if ($dbg_values > 1);
1262			push(@av_paren_type, $type);
1263			$type = 'c';
1264
1265		} elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1266			print "DECLARE($1)\n" if ($dbg_values > 1);
1267			$type = 'T';
1268
1269		} elsif ($cur =~ /^($Modifier)\s*/) {
1270			print "MODIFIER($1)\n" if ($dbg_values > 1);
1271			$type = 'T';
1272
1273		} elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1274			print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1275			$av_preprocessor = 1;
1276			push(@av_paren_type, $type);
1277			if ($2 ne '') {
1278				$av_pending = 'N';
1279			}
1280			$type = 'E';
1281
1282		} elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1283			print "UNDEF($1)\n" if ($dbg_values > 1);
1284			$av_preprocessor = 1;
1285			push(@av_paren_type, $type);
1286
1287		} elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1288			print "PRE_START($1)\n" if ($dbg_values > 1);
1289			$av_preprocessor = 1;
1290
1291			push(@av_paren_type, $type);
1292			push(@av_paren_type, $type);
1293			$type = 'E';
1294
1295		} elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1296			print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1297			$av_preprocessor = 1;
1298
1299			push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1300
1301			$type = 'E';
1302
1303		} elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1304			print "PRE_END($1)\n" if ($dbg_values > 1);
1305
1306			$av_preprocessor = 1;
1307
1308			# Assume all arms of the conditional end as this
1309			# one does, and continue as if the #endif was not here.
1310			pop(@av_paren_type);
1311			push(@av_paren_type, $type);
1312			$type = 'E';
1313
1314		} elsif ($cur =~ /^(\\\n)/o) {
1315			print "PRECONT($1)\n" if ($dbg_values > 1);
1316
1317		} elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1318			print "ATTR($1)\n" if ($dbg_values > 1);
1319			$av_pending = $type;
1320			$type = 'N';
1321
1322		} elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1323			print "SIZEOF($1)\n" if ($dbg_values > 1);
1324			if (defined $2) {
1325				$av_pending = 'V';
1326			}
1327			$type = 'N';
1328
1329		} elsif ($cur =~ /^(if|while|for)\b/o) {
1330			print "COND($1)\n" if ($dbg_values > 1);
1331			$av_pending = 'E';
1332			$type = 'N';
1333
1334		} elsif ($cur =~/^(case)/o) {
1335			print "CASE($1)\n" if ($dbg_values > 1);
1336			$av_pend_colon = 'C';
1337			$type = 'N';
1338
1339		} elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1340			print "KEYWORD($1)\n" if ($dbg_values > 1);
1341			$type = 'N';
1342
1343		} elsif ($cur =~ /^(\()/o) {
1344			print "PAREN('$1')\n" if ($dbg_values > 1);
1345			push(@av_paren_type, $av_pending);
1346			$av_pending = '_';
1347			$type = 'N';
1348
1349		} elsif ($cur =~ /^(\))/o) {
1350			my $new_type = pop(@av_paren_type);
1351			if ($new_type ne '_') {
1352				$type = $new_type;
1353				print "PAREN('$1') -> $type\n"
1354							if ($dbg_values > 1);
1355			} else {
1356				print "PAREN('$1')\n" if ($dbg_values > 1);
1357			}
1358
1359		} elsif ($cur =~ /^($Ident)\s*\(/o) {
1360			print "FUNC($1)\n" if ($dbg_values > 1);
1361			$type = 'V';
1362			$av_pending = 'V';
1363
1364		} elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1365			if (defined $2 && $type eq 'C' || $type eq 'T') {
1366				$av_pend_colon = 'B';
1367			} elsif ($type eq 'E') {
1368				$av_pend_colon = 'L';
1369			}
1370			print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1371			$type = 'V';
1372
1373		} elsif ($cur =~ /^($Ident|$Constant)/o) {
1374			print "IDENT($1)\n" if ($dbg_values > 1);
1375			$type = 'V';
1376
1377		} elsif ($cur =~ /^($Assignment)/o) {
1378			print "ASSIGN($1)\n" if ($dbg_values > 1);
1379			$type = 'N';
1380
1381		} elsif ($cur =~/^(;|{|})/) {
1382			print "END($1)\n" if ($dbg_values > 1);
1383			$type = 'E';
1384			$av_pend_colon = 'O';
1385
1386		} elsif ($cur =~/^(,)/) {
1387			print "COMMA($1)\n" if ($dbg_values > 1);
1388			$type = 'C';
1389
1390		} elsif ($cur =~ /^(\?)/o) {
1391			print "QUESTION($1)\n" if ($dbg_values > 1);
1392			$type = 'N';
1393
1394		} elsif ($cur =~ /^(:)/o) {
1395			print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1396
1397			substr($var, length($res), 1, $av_pend_colon);
1398			if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1399				$type = 'E';
1400			} else {
1401				$type = 'N';
1402			}
1403			$av_pend_colon = 'O';
1404
1405		} elsif ($cur =~ /^(\[)/o) {
1406			print "CLOSE($1)\n" if ($dbg_values > 1);
1407			$type = 'N';
1408
1409		} elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1410			my $variant;
1411
1412			print "OPV($1)\n" if ($dbg_values > 1);
1413			if ($type eq 'V') {
1414				$variant = 'B';
1415			} else {
1416				$variant = 'U';
1417			}
1418
1419			substr($var, length($res), 1, $variant);
1420			$type = 'N';
1421
1422		} elsif ($cur =~ /^($Operators)/o) {
1423			print "OP($1)\n" if ($dbg_values > 1);
1424			if ($1 ne '++' && $1 ne '--') {
1425				$type = 'N';
1426			}
1427
1428		} elsif ($cur =~ /(^.)/o) {
1429			print "C($1)\n" if ($dbg_values > 1);
1430		}
1431		if (defined $1) {
1432			$cur = substr($cur, length($1));
1433			$res .= $type x length($1);
1434		}
1435	}
1436
1437	return ($res, $var);
1438}
1439
1440sub possible {
1441	my ($possible, $line) = @_;
1442	my $notPermitted = qr{(?:
1443		^(?:
1444			$Modifier|
1445			$Storage|
1446			$Type|
1447			DEFINE_\S+
1448		)$|
1449		^(?:
1450			goto|
1451			return|
1452			case|
1453			else|
1454			asm|__asm__|
1455			do|
1456			\#|
1457			\#\#|
1458		)(?:\s|$)|
1459		^(?:typedef|struct|enum)\b
1460	    )}x;
1461	warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1462	if ($possible !~ $notPermitted) {
1463		# Check for modifiers.
1464		$possible =~ s/\s*$Storage\s*//g;
1465		$possible =~ s/\s*$Sparse\s*//g;
1466		if ($possible =~ /^\s*$/) {
1467
1468		} elsif ($possible =~ /\s/) {
1469			$possible =~ s/\s*$Type\s*//g;
1470			for my $modifier (split(' ', $possible)) {
1471				if ($modifier !~ $notPermitted) {
1472					warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1473					push(@modifierList, $modifier);
1474				}
1475			}
1476
1477		} else {
1478			warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1479			push(@typeList, $possible);
1480		}
1481		build_types();
1482	} else {
1483		warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1484	}
1485}
1486
1487my $prefix = '';
1488
1489sub show_type {
1490	return defined $use_type{$_[0]} if (scalar keys %use_type > 0);
1491
1492	return !defined $ignore_type{$_[0]};
1493}
1494
1495sub report {
1496	if (!show_type($_[1]) ||
1497	    (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1498		return 0;
1499	}
1500	my $line;
1501	if ($show_types) {
1502		$line = "$prefix$_[0]:$_[1]: $_[2]\n";
1503	} else {
1504		$line = "$prefix$_[0]: $_[2]\n";
1505	}
1506	$line = (split('\n', $line))[0] . "\n" if ($terse);
1507
1508	push(our @report, $line);
1509
1510	return 1;
1511}
1512sub report_dump {
1513	our @report;
1514}
1515
1516sub ERROR {
1517	if (report("ERROR", $_[0], $_[1])) {
1518		our $clean = 0;
1519		our $cnt_error++;
1520		return 1;
1521	}
1522	return 0;
1523}
1524sub WARN {
1525	if (report("WARNING", $_[0], $_[1])) {
1526		our $clean = 0;
1527		our $cnt_warn++;
1528		return 1;
1529	}
1530	return 0;
1531}
1532sub CHK {
1533	if ($check && report("CHECK", $_[0], $_[1])) {
1534		our $clean = 0;
1535		our $cnt_chk++;
1536		return 1;
1537	}
1538	return 0;
1539}
1540
1541sub check_absolute_file {
1542	my ($absolute, $herecurr) = @_;
1543	my $file = $absolute;
1544
1545	##print "absolute<$absolute>\n";
1546
1547	# See if any suffix of this path is a path within the tree.
1548	while ($file =~ s@^[^/]*/@@) {
1549		if (-f "$root/$file") {
1550			##print "file<$file>\n";
1551			last;
1552		}
1553	}
1554	if (! -f _)  {
1555		return 0;
1556	}
1557
1558	# It is, so see if the prefix is acceptable.
1559	my $prefix = $absolute;
1560	substr($prefix, -length($file)) = '';
1561
1562	##print "prefix<$prefix>\n";
1563	if ($prefix ne ".../") {
1564		WARN("USE_RELATIVE_PATH",
1565		     "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1566	}
1567}
1568
1569sub trim {
1570	my ($string) = @_;
1571
1572	$string =~ s/^\s+|\s+$//g;
1573
1574	return $string;
1575}
1576
1577sub ltrim {
1578	my ($string) = @_;
1579
1580	$string =~ s/^\s+//;
1581
1582	return $string;
1583}
1584
1585sub rtrim {
1586	my ($string) = @_;
1587
1588	$string =~ s/\s+$//;
1589
1590	return $string;
1591}
1592
1593sub string_find_replace {
1594	my ($string, $find, $replace) = @_;
1595
1596	$string =~ s/$find/$replace/g;
1597
1598	return $string;
1599}
1600
1601sub tabify {
1602	my ($leading) = @_;
1603
1604	my $source_indent = 8;
1605	my $max_spaces_before_tab = $source_indent - 1;
1606	my $spaces_to_tab = " " x $source_indent;
1607
1608	#convert leading spaces to tabs
1609	1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1610	#Remove spaces before a tab
1611	1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1612
1613	return "$leading";
1614}
1615
1616sub pos_last_openparen {
1617	my ($line) = @_;
1618
1619	my $pos = 0;
1620
1621	my $opens = $line =~ tr/\(/\(/;
1622	my $closes = $line =~ tr/\)/\)/;
1623
1624	my $last_openparen = 0;
1625
1626	if (($opens == 0) || ($closes >= $opens)) {
1627		return -1;
1628	}
1629
1630	my $len = length($line);
1631
1632	for ($pos = 0; $pos < $len; $pos++) {
1633		my $string = substr($line, $pos);
1634		if ($string =~ /^($FuncArg|$balanced_parens)/) {
1635			$pos += length($1) - 1;
1636		} elsif (substr($line, $pos, 1) eq '(') {
1637			$last_openparen = $pos;
1638		} elsif (index($string, '(') == -1) {
1639			last;
1640		}
1641	}
1642
1643	return $last_openparen + 1;
1644}
1645
1646sub process {
1647	my $filename = shift;
1648
1649	my $linenr=0;
1650	my $prevline="";
1651	my $prevrawline="";
1652	my $stashline="";
1653	my $stashrawline="";
1654
1655	my $length;
1656	my $indent;
1657	my $previndent=0;
1658	my $stashindent=0;
1659
1660	our $clean = 1;
1661	my $signoff = 0;
1662	my $is_patch = 0;
1663
1664	my $in_header_lines = 1;
1665	my $in_commit_log = 0;		#Scanning lines before patch
1666
1667	my $non_utf8_charset = 0;
1668
1669	our @report = ();
1670	our $cnt_lines = 0;
1671	our $cnt_error = 0;
1672	our $cnt_warn = 0;
1673	our $cnt_chk = 0;
1674
1675	# Trace the real file/line as we go.
1676	my $realfile = '';
1677	my $realline = 0;
1678	my $realcnt = 0;
1679	my $here = '';
1680	my $in_comment = 0;
1681	my $comment_edge = 0;
1682	my $first_line = 0;
1683	my $p1_prefix = '';
1684
1685	my $prev_values = 'E';
1686
1687	# suppression flags
1688	my %suppress_ifbraces;
1689	my %suppress_whiletrailers;
1690	my %suppress_export;
1691	my $suppress_statement = 0;
1692
1693	my %signatures = ();
1694
1695	# Pre-scan the patch sanitizing the lines.
1696	# Pre-scan the patch looking for any __setup documentation.
1697	#
1698	my @setup_docs = ();
1699	my $setup_docs = 0;
1700
1701	my $camelcase_file_seeded = 0;
1702
1703	sanitise_line_reset();
1704	my $line;
1705	foreach my $rawline (@rawlines) {
1706		$linenr++;
1707		$line = $rawline;
1708
1709		push(@fixed, $rawline) if ($fix);
1710
1711		if ($rawline=~/^\+\+\+\s+(\S+)/) {
1712			$setup_docs = 0;
1713			if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1714				$setup_docs = 1;
1715			}
1716			#next;
1717		}
1718		if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1719			$realline=$1-1;
1720			if (defined $2) {
1721				$realcnt=$3+1;
1722			} else {
1723				$realcnt=1+1;
1724			}
1725			$in_comment = 0;
1726
1727			# Guestimate if this is a continuing comment.  Run
1728			# the context looking for a comment "edge".  If this
1729			# edge is a close comment then we must be in a comment
1730			# at context start.
1731			my $edge;
1732			my $cnt = $realcnt;
1733			for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1734				next if (defined $rawlines[$ln - 1] &&
1735					 $rawlines[$ln - 1] =~ /^-/);
1736				$cnt--;
1737				#print "RAW<$rawlines[$ln - 1]>\n";
1738				last if (!defined $rawlines[$ln - 1]);
1739				if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1740				    $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1741					($edge) = $1;
1742					last;
1743				}
1744			}
1745			if (defined $edge && $edge eq '*/') {
1746				$in_comment = 1;
1747			}
1748
1749			# Guestimate if this is a continuing comment.  If this
1750			# is the start of a diff block and this line starts
1751			# ' *' then it is very likely a comment.
1752			if (!defined $edge &&
1753			    $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1754			{
1755				$in_comment = 1;
1756			}
1757
1758			##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1759			sanitise_line_reset($in_comment);
1760
1761		} elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1762			# Standardise the strings and chars within the input to
1763			# simplify matching -- only bother with positive lines.
1764			$line = sanitise_line($rawline);
1765		}
1766		push(@lines, $line);
1767
1768		if ($realcnt > 1) {
1769			$realcnt-- if ($line =~ /^(?:\+| |$)/);
1770		} else {
1771			$realcnt = 0;
1772		}
1773
1774		#print "==>$rawline\n";
1775		#print "-->$line\n";
1776
1777		if ($setup_docs && $line =~ /^\+/) {
1778			push(@setup_docs, $line);
1779		}
1780	}
1781
1782	$prefix = '';
1783
1784	$realcnt = 0;
1785	$linenr = 0;
1786	foreach my $line (@lines) {
1787		$linenr++;
1788		my $sline = $line;	#copy of $line
1789		$sline =~ s/$;/ /g;	#with comments as spaces
1790
1791		my $rawline = $rawlines[$linenr - 1];
1792
1793#extract the line range in the file after the patch is applied
1794		if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1795			$is_patch = 1;
1796			$first_line = $linenr + 1;
1797			$realline=$1-1;
1798			if (defined $2) {
1799				$realcnt=$3+1;
1800			} else {
1801				$realcnt=1+1;
1802			}
1803			annotate_reset();
1804			$prev_values = 'E';
1805
1806			%suppress_ifbraces = ();
1807			%suppress_whiletrailers = ();
1808			%suppress_export = ();
1809			$suppress_statement = 0;
1810			next;
1811
1812# track the line number as we move through the hunk, note that
1813# new versions of GNU diff omit the leading space on completely
1814# blank context lines so we need to count that too.
1815		} elsif ($line =~ /^( |\+|$)/) {
1816			$realline++;
1817			$realcnt-- if ($realcnt != 0);
1818
1819			# Measure the line length and indent.
1820			($length, $indent) = line_stats($rawline);
1821
1822			# Track the previous line.
1823			($prevline, $stashline) = ($stashline, $line);
1824			($previndent, $stashindent) = ($stashindent, $indent);
1825			($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1826
1827			#warn "line<$line>\n";
1828
1829		} elsif ($realcnt == 1) {
1830			$realcnt--;
1831		}
1832
1833		my $hunk_line = ($realcnt != 0);
1834
1835#make up the handle for any error we report on this line
1836		$prefix = "$filename:$realline: " if ($emacs && $file);
1837		$prefix = "$filename:$linenr: " if ($emacs && !$file);
1838
1839		$here = "#$linenr: " if (!$file);
1840		$here = "#$realline: " if ($file);
1841
1842		# extract the filename as it passes
1843		if ($line =~ /^diff --git.*?(\S+)$/) {
1844			$realfile = $1;
1845			$realfile =~ s@^([^/]*)/@@ if (!$file);
1846			$in_commit_log = 0;
1847		} elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1848			$realfile = $1;
1849			$realfile =~ s@^([^/]*)/@@ if (!$file);
1850			$in_commit_log = 0;
1851
1852			$p1_prefix = $1;
1853			if (!$file && $tree && $p1_prefix ne '' &&
1854			    -e "$root/$p1_prefix") {
1855				WARN("PATCH_PREFIX",
1856				     "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1857			}
1858
1859			if ($realfile =~ m@^include/asm/@) {
1860				ERROR("MODIFIED_INCLUDE_ASM",
1861				      "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1862			}
1863			next;
1864		}
1865
1866		$here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1867
1868		my $hereline = "$here\n$rawline\n";
1869		my $herecurr = "$here\n$rawline\n";
1870		my $hereprev = "$here\n$prevrawline\n$rawline\n";
1871
1872		$cnt_lines++ if ($realcnt != 0);
1873
1874# Check for incorrect file permissions
1875		if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1876			my $permhere = $here . "FILE: $realfile\n";
1877			if ($realfile !~ m@scripts/@ &&
1878			    $realfile !~ /\.(py|pl|awk|sh)$/) {
1879				ERROR("EXECUTE_PERMISSIONS",
1880				      "do not set execute permissions for source files\n" . $permhere);
1881			}
1882		}
1883
1884# Check the patch for a signoff:
1885		if ($line =~ /^\s*signed-off-by:/i) {
1886			$signoff++;
1887			$in_commit_log = 0;
1888		}
1889
1890# Check signature styles
1891		if (!$in_header_lines &&
1892		    $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
1893			my $space_before = $1;
1894			my $sign_off = $2;
1895			my $space_after = $3;
1896			my $email = $4;
1897			my $ucfirst_sign_off = ucfirst(lc($sign_off));
1898
1899			if ($sign_off !~ /$signature_tags/) {
1900				WARN("BAD_SIGN_OFF",
1901				     "Non-standard signature: $sign_off\n" . $herecurr);
1902			}
1903			if (defined $space_before && $space_before ne "") {
1904				if (WARN("BAD_SIGN_OFF",
1905					 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
1906				    $fix) {
1907					$fixed[$linenr - 1] =
1908					    "$ucfirst_sign_off $email";
1909				}
1910			}
1911			if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1912				if (WARN("BAD_SIGN_OFF",
1913					 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
1914				    $fix) {
1915					$fixed[$linenr - 1] =
1916					    "$ucfirst_sign_off $email";
1917				}
1918
1919			}
1920			if (!defined $space_after || $space_after ne " ") {
1921				if (WARN("BAD_SIGN_OFF",
1922					 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
1923				    $fix) {
1924					$fixed[$linenr - 1] =
1925					    "$ucfirst_sign_off $email";
1926				}
1927			}
1928
1929			my ($email_name, $email_address, $comment) = parse_email($email);
1930			my $suggested_email = format_email(($email_name, $email_address));
1931			if ($suggested_email eq "") {
1932				ERROR("BAD_SIGN_OFF",
1933				      "Unrecognized email address: '$email'\n" . $herecurr);
1934			} else {
1935				my $dequoted = $suggested_email;
1936				$dequoted =~ s/^"//;
1937				$dequoted =~ s/" </ </;
1938				# Don't force email to have quotes
1939				# Allow just an angle bracketed address
1940				if ("$dequoted$comment" ne $email &&
1941				    "<$email_address>$comment" ne $email &&
1942				    "$suggested_email$comment" ne $email) {
1943					WARN("BAD_SIGN_OFF",
1944					     "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1945				}
1946			}
1947
1948# Check for duplicate signatures
1949			my $sig_nospace = $line;
1950			$sig_nospace =~ s/\s//g;
1951			$sig_nospace = lc($sig_nospace);
1952			if (defined $signatures{$sig_nospace}) {
1953				WARN("BAD_SIGN_OFF",
1954				     "Duplicate signature\n" . $herecurr);
1955			} else {
1956				$signatures{$sig_nospace} = 1;
1957			}
1958		}
1959
1960# Check for wrappage within a valid hunk of the file
1961		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1962			ERROR("CORRUPTED_PATCH",
1963			      "patch seems to be corrupt (line wrapped?)\n" .
1964				$herecurr) if (!$emitted_corrupt++);
1965		}
1966
1967# Check for absolute kernel paths.
1968		if ($tree) {
1969			while ($line =~ m{(?:^|\s)(/\S*)}g) {
1970				my $file = $1;
1971
1972				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1973				    check_absolute_file($1, $herecurr)) {
1974					#
1975				} else {
1976					check_absolute_file($file, $herecurr);
1977				}
1978			}
1979		}
1980
1981# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1982		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1983		    $rawline !~ m/^$UTF8*$/) {
1984			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1985
1986			my $blank = copy_spacing($rawline);
1987			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1988			my $hereptr = "$hereline$ptr\n";
1989
1990			CHK("INVALID_UTF8",
1991			    "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1992		}
1993
1994# Check if it's the start of a commit log
1995# (not a header line and we haven't seen the patch filename)
1996		if ($in_header_lines && $realfile =~ /^$/ &&
1997		    $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1998			$in_header_lines = 0;
1999			$in_commit_log = 1;
2000		}
2001
2002# Check if there is UTF-8 in a commit log when a mail header has explicitly
2003# declined it, i.e defined some charset where it is missing.
2004		if ($in_header_lines &&
2005		    $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2006		    $1 !~ /utf-8/i) {
2007			$non_utf8_charset = 1;
2008		}
2009
2010		if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2011		    $rawline =~ /$NON_ASCII_UTF8/) {
2012			WARN("UTF8_BEFORE_PATCH",
2013			    "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2014		}
2015
2016# Check for various typo / spelling mistakes
2017		if (defined($misspellings) &&
2018		    ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2019			while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2020				my $typo = $1;
2021				my $typo_fix = $spelling_fix{lc($typo)};
2022				$typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2023				$typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2024				my $msg_type = \&WARN;
2025				$msg_type = \&CHK if ($file);
2026				if (&{$msg_type}("TYPO_SPELLING",
2027						 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2028				    $fix) {
2029					$fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2030				}
2031			}
2032		}
2033
2034# ignore non-hunk lines and lines being removed
2035		next if (!$hunk_line || $line =~ /^-/);
2036
2037#trailing whitespace
2038		if ($line =~ /^\+.*\015/) {
2039			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2040			if (ERROR("DOS_LINE_ENDINGS",
2041				  "DOS line endings\n" . $herevet) &&
2042			    $fix) {
2043				$fixed[$linenr - 1] =~ s/[\s\015]+$//;
2044			}
2045		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2046			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2047			if (ERROR("TRAILING_WHITESPACE",
2048				  "trailing whitespace\n" . $herevet) &&
2049			    $fix) {
2050				$fixed[$linenr - 1] =~ s/\s+$//;
2051			}
2052
2053			$rpt_cleaners = 1;
2054		}
2055
2056# Check for FSF mailing addresses.
2057		if ($rawline =~ /\bwrite to the Free/i ||
2058		    $rawline =~ /\b59\s+Temple\s+Pl/i ||
2059		    $rawline =~ /\b51\s+Franklin\s+St/i) {
2060			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2061			my $msg_type = \&ERROR;
2062			$msg_type = \&CHK if ($file);
2063			&{$msg_type}("FSF_MAILING_ADDRESS",
2064				     "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
2065		}
2066
2067# check for Kconfig help text having a real description
2068# Only applies when adding the entry originally, after that we do not have
2069# sufficient context to determine whether it is indeed long enough.
2070		if ($realfile =~ /Kconfig/ &&
2071		    $line =~ /.\s*config\s+/) {
2072			my $length = 0;
2073			my $cnt = $realcnt;
2074			my $ln = $linenr + 1;
2075			my $f;
2076			my $is_start = 0;
2077			my $is_end = 0;
2078			for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2079				$f = $lines[$ln - 1];
2080				$cnt-- if ($lines[$ln - 1] !~ /^-/);
2081				$is_end = $lines[$ln - 1] =~ /^\+/;
2082
2083				next if ($f =~ /^-/);
2084
2085				if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
2086					$is_start = 1;
2087				} elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
2088					$length = -1;
2089				}
2090
2091				$f =~ s/^.//;
2092				$f =~ s/#.*//;
2093				$f =~ s/^\s+//;
2094				next if ($f =~ /^$/);
2095				if ($f =~ /^\s*config\s/) {
2096					$is_end = 1;
2097					last;
2098				}
2099				$length++;
2100			}
2101			WARN("CONFIG_DESCRIPTION",
2102			     "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
2103			#print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2104		}
2105
2106# discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2107		if ($realfile =~ /Kconfig/ &&
2108		    $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2109			WARN("CONFIG_EXPERIMENTAL",
2110			     "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2111		}
2112
2113		if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2114		    ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2115			my $flag = $1;
2116			my $replacement = {
2117				'EXTRA_AFLAGS' =>   'asflags-y',
2118				'EXTRA_CFLAGS' =>   'ccflags-y',
2119				'EXTRA_CPPFLAGS' => 'cppflags-y',
2120				'EXTRA_LDFLAGS' =>  'ldflags-y',
2121			};
2122
2123			WARN("DEPRECATED_VARIABLE",
2124			     "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2125		}
2126
2127# check for DT compatible documentation
2128		if (defined $root && $realfile =~ /\.dts/ &&
2129		    $rawline =~ /^\+\s*compatible\s*=/) {
2130			my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2131
2132			foreach my $compat (@compats) {
2133				my $compat2 = $compat;
2134				my $dt_path =  $root . "/Documentation/devicetree/bindings/";
2135				$compat2 =~ s/\,[a-z]*\-/\,<\.\*>\-/;
2136				`grep -Erq "$compat|$compat2" $dt_path`;
2137				if ( $? >> 8 ) {
2138					WARN("UNDOCUMENTED_DT_STRING",
2139					     "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2140				}
2141
2142				my $vendor = $compat;
2143				my $vendor_path = $dt_path . "vendor-prefixes.txt";
2144				next if (! -f $vendor_path);
2145				$vendor =~ s/^([a-zA-Z0-9]+)\,.*/$1/;
2146				`grep -Eq "$vendor" $vendor_path`;
2147				if ( $? >> 8 ) {
2148					WARN("UNDOCUMENTED_DT_STRING",
2149					     "DT compatible string vendor \"$vendor\" appears un-documented -- check $vendor_path\n" . $herecurr);
2150				}
2151			}
2152		}
2153
2154# check we are in a valid source file if not then ignore this hunk
2155		next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
2156
2157#line length limit
2158		if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2159		    $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2160		    !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2161		    $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2162		    $length > $max_line_length)
2163		{
2164			WARN("LONG_LINE",
2165			     "line over $max_line_length characters\n" . $herecurr);
2166		}
2167
2168# Check for user-visible strings broken across lines, which breaks the ability
2169# to grep for the string.  Make exceptions when the previous string ends in a
2170# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
2171# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
2172		if ($line =~ /^\+\s*"/ &&
2173		    $prevline =~ /"\s*$/ &&
2174		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
2175			WARN("SPLIT_STRING",
2176			     "quoted string split across lines\n" . $hereprev);
2177		}
2178
2179# check for spaces before a quoted newline
2180		if ($rawline =~ /^.*\".*\s\\n/) {
2181			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2182				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2183			    $fix) {
2184				$fixed[$linenr - 1] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2185			}
2186
2187		}
2188
2189# check for adding lines without a newline.
2190		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2191			WARN("MISSING_EOF_NEWLINE",
2192			     "adding a line without newline at end of file\n" . $herecurr);
2193		}
2194
2195# Blackfin: use hi/lo macros
2196		if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2197			if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2198				my $herevet = "$here\n" . cat_vet($line) . "\n";
2199				ERROR("LO_MACRO",
2200				      "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2201			}
2202			if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2203				my $herevet = "$here\n" . cat_vet($line) . "\n";
2204				ERROR("HI_MACRO",
2205				      "use the HI() macro, not (... >> 16)\n" . $herevet);
2206			}
2207		}
2208
2209# check we are in a valid source file C or perl if not then ignore this hunk
2210		next if ($realfile !~ /\.(h|c|pl)$/);
2211
2212# at the beginning of a line any tabs must come first and anything
2213# more than 8 must use tabs.
2214		if ($rawline =~ /^\+\s* \t\s*\S/ ||
2215		    $rawline =~ /^\+\s*        \s*/) {
2216			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2217			$rpt_cleaners = 1;
2218			if (ERROR("CODE_INDENT",
2219				  "code indent should use tabs where possible\n" . $herevet) &&
2220			    $fix) {
2221				$fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2222			}
2223		}
2224
2225# check for space before tabs.
2226		if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2227			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2228			if (WARN("SPACE_BEFORE_TAB",
2229				"please, no space before tabs\n" . $herevet) &&
2230			    $fix) {
2231				while ($fixed[$linenr - 1] =~
2232					   s/(^\+.*) {8,8}\t/$1\t\t/) {}
2233				while ($fixed[$linenr - 1] =~
2234					   s/(^\+.*) +\t/$1\t/) {}
2235			}
2236		}
2237
2238# check for && or || at the start of a line
2239		if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2240			CHK("LOGICAL_CONTINUATIONS",
2241			    "Logical continuations should be on the previous line\n" . $hereprev);
2242		}
2243
2244# check multi-line statement indentation matches previous line
2245		if ($^V && $^V ge 5.10.0 &&
2246		    $prevline =~ /^\+(\t*)(if \(|$Ident\().*(\&\&|\|\||,)\s*$/) {
2247			$prevline =~ /^\+(\t*)(.*)$/;
2248			my $oldindent = $1;
2249			my $rest = $2;
2250
2251			my $pos = pos_last_openparen($rest);
2252			if ($pos >= 0) {
2253				$line =~ /^(\+| )([ \t]*)/;
2254				my $newindent = $2;
2255
2256				my $goodtabindent = $oldindent .
2257					"\t" x ($pos / 8) .
2258					" "  x ($pos % 8);
2259				my $goodspaceindent = $oldindent . " "  x $pos;
2260
2261				if ($newindent ne $goodtabindent &&
2262				    $newindent ne $goodspaceindent) {
2263
2264					if (CHK("PARENTHESIS_ALIGNMENT",
2265						"Alignment should match open parenthesis\n" . $hereprev) &&
2266					    $fix && $line =~ /^\+/) {
2267						$fixed[$linenr - 1] =~
2268						    s/^\+[ \t]*/\+$goodtabindent/;
2269					}
2270				}
2271			}
2272		}
2273
2274		if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) {
2275			if (CHK("SPACING",
2276				"No space is necessary after a cast\n" . $hereprev) &&
2277			    $fix) {
2278				$fixed[$linenr - 1] =~
2279				    s/^(\+.*\*[ \t]*\))[ \t]+/$1/;
2280			}
2281		}
2282
2283		if ($realfile =~ m@^(drivers/net/|net/)@ &&
2284		    $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2285		    $rawline =~ /^\+[ \t]*\*/) {
2286			WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2287			     "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2288		}
2289
2290		if ($realfile =~ m@^(drivers/net/|net/)@ &&
2291		    $prevrawline =~ /^\+[ \t]*\/\*/ &&		#starting /*
2292		    $prevrawline !~ /\*\/[ \t]*$/ &&		#no trailing */
2293		    $rawline =~ /^\+/ &&			#line is new
2294		    $rawline !~ /^\+[ \t]*\*/) {		#no leading *
2295			WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2296			     "networking block comments start with * on subsequent lines\n" . $hereprev);
2297		}
2298
2299		if ($realfile =~ m@^(drivers/net/|net/)@ &&
2300		    $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&	#trailing */
2301		    $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&	#inline /*...*/
2302		    $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&	#trailing **/
2303		    $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {	#non blank */
2304			WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2305			     "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2306		}
2307
2308# check for spaces at the beginning of a line.
2309# Exceptions:
2310#  1) within comments
2311#  2) indented preprocessor commands
2312#  3) hanging labels
2313		if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
2314			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2315			if (WARN("LEADING_SPACE",
2316				 "please, no spaces at the start of a line\n" . $herevet) &&
2317			    $fix) {
2318				$fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2319			}
2320		}
2321
2322# check we are in a valid C source file if not then ignore this hunk
2323		next if ($realfile !~ /\.(h|c)$/);
2324
2325# discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2326		if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2327			WARN("CONFIG_EXPERIMENTAL",
2328			     "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2329		}
2330
2331# check for RCS/CVS revision markers
2332		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2333			WARN("CVS_KEYWORD",
2334			     "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2335		}
2336
2337# Blackfin: don't use __builtin_bfin_[cs]sync
2338		if ($line =~ /__builtin_bfin_csync/) {
2339			my $herevet = "$here\n" . cat_vet($line) . "\n";
2340			ERROR("CSYNC",
2341			      "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2342		}
2343		if ($line =~ /__builtin_bfin_ssync/) {
2344			my $herevet = "$here\n" . cat_vet($line) . "\n";
2345			ERROR("SSYNC",
2346			      "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2347		}
2348
2349# check for old HOTPLUG __dev<foo> section markings
2350		if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2351			WARN("HOTPLUG_SECTION",
2352			     "Using $1 is unnecessary\n" . $herecurr);
2353		}
2354
2355# Check for potential 'bare' types
2356		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2357		    $realline_next);
2358#print "LINE<$line>\n";
2359		if ($linenr >= $suppress_statement &&
2360		    $realcnt && $sline =~ /.\s*\S/) {
2361			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2362				ctx_statement_block($linenr, $realcnt, 0);
2363			$stat =~ s/\n./\n /g;
2364			$cond =~ s/\n./\n /g;
2365
2366#print "linenr<$linenr> <$stat>\n";
2367			# If this statement has no statement boundaries within
2368			# it there is no point in retrying a statement scan
2369			# until we hit end of it.
2370			my $frag = $stat; $frag =~ s/;+\s*$//;
2371			if ($frag !~ /(?:{|;)/) {
2372#print "skip<$line_nr_next>\n";
2373				$suppress_statement = $line_nr_next;
2374			}
2375
2376			# Find the real next line.
2377			$realline_next = $line_nr_next;
2378			if (defined $realline_next &&
2379			    (!defined $lines[$realline_next - 1] ||
2380			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2381				$realline_next++;
2382			}
2383
2384			my $s = $stat;
2385			$s =~ s/{.*$//s;
2386
2387			# Ignore goto labels.
2388			if ($s =~ /$Ident:\*$/s) {
2389
2390			# Ignore functions being called
2391			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2392
2393			} elsif ($s =~ /^.\s*else\b/s) {
2394
2395			# declarations always start with types
2396			} 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) {
2397				my $type = $1;
2398				$type =~ s/\s+/ /g;
2399				possible($type, "A:" . $s);
2400
2401			# definitions in global scope can only start with types
2402			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2403				possible($1, "B:" . $s);
2404			}
2405
2406			# any (foo ... *) is a pointer cast, and foo is a type
2407			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2408				possible($1, "C:" . $s);
2409			}
2410
2411			# Check for any sort of function declaration.
2412			# int foo(something bar, other baz);
2413			# void (*store_gdt)(x86_descr_ptr *);
2414			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2415				my ($name_len) = length($1);
2416
2417				my $ctx = $s;
2418				substr($ctx, 0, $name_len + 1, '');
2419				$ctx =~ s/\)[^\)]*$//;
2420
2421				for my $arg (split(/\s*,\s*/, $ctx)) {
2422					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2423
2424						possible($1, "D:" . $s);
2425					}
2426				}
2427			}
2428
2429		}
2430
2431#
2432# Checks which may be anchored in the context.
2433#
2434
2435# Check for switch () and associated case and default
2436# statements should be at the same indent.
2437		if ($line=~/\bswitch\s*\(.*\)/) {
2438			my $err = '';
2439			my $sep = '';
2440			my @ctx = ctx_block_outer($linenr, $realcnt);
2441			shift(@ctx);
2442			for my $ctx (@ctx) {
2443				my ($clen, $cindent) = line_stats($ctx);
2444				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2445							$indent != $cindent) {
2446					$err .= "$sep$ctx\n";
2447					$sep = '';
2448				} else {
2449					$sep = "[...]\n";
2450				}
2451			}
2452			if ($err ne '') {
2453				ERROR("SWITCH_CASE_INDENT_LEVEL",
2454				      "switch and case should be at the same indent\n$hereline$err");
2455			}
2456		}
2457
2458# if/while/etc brace do not go on next line, unless defining a do while loop,
2459# or if that brace on the next line is for something else
2460		if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2461			my $pre_ctx = "$1$2";
2462
2463			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2464
2465			if ($line =~ /^\+\t{6,}/) {
2466				WARN("DEEP_INDENTATION",
2467				     "Too many leading tabs - consider code refactoring\n" . $herecurr);
2468			}
2469
2470			my $ctx_cnt = $realcnt - $#ctx - 1;
2471			my $ctx = join("\n", @ctx);
2472
2473			my $ctx_ln = $linenr;
2474			my $ctx_skip = $realcnt;
2475
2476			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2477					defined $lines[$ctx_ln - 1] &&
2478					$lines[$ctx_ln - 1] =~ /^-/)) {
2479				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2480				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2481				$ctx_ln++;
2482			}
2483
2484			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2485			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2486
2487			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2488				ERROR("OPEN_BRACE",
2489				      "that open brace { should be on the previous line\n" .
2490					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2491			}
2492			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2493			    $ctx =~ /\)\s*\;\s*$/ &&
2494			    defined $lines[$ctx_ln - 1])
2495			{
2496				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2497				if ($nindent > $indent) {
2498					WARN("TRAILING_SEMICOLON",
2499					     "trailing semicolon indicates no statements, indent implies otherwise\n" .
2500						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2501				}
2502			}
2503		}
2504
2505# Check relative indent for conditionals and blocks.
2506		if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2507			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2508				ctx_statement_block($linenr, $realcnt, 0)
2509					if (!defined $stat);
2510			my ($s, $c) = ($stat, $cond);
2511
2512			substr($s, 0, length($c), '');
2513
2514			# Make sure we remove the line prefixes as we have
2515			# none on the first line, and are going to readd them
2516			# where necessary.
2517			$s =~ s/\n./\n/gs;
2518
2519			# Find out how long the conditional actually is.
2520			my @newlines = ($c =~ /\n/gs);
2521			my $cond_lines = 1 + $#newlines;
2522
2523			# We want to check the first line inside the block
2524			# starting at the end of the conditional, so remove:
2525			#  1) any blank line termination
2526			#  2) any opening brace { on end of the line
2527			#  3) any do (...) {
2528			my $continuation = 0;
2529			my $check = 0;
2530			$s =~ s/^.*\bdo\b//;
2531			$s =~ s/^\s*{//;
2532			if ($s =~ s/^\s*\\//) {
2533				$continuation = 1;
2534			}
2535			if ($s =~ s/^\s*?\n//) {
2536				$check = 1;
2537				$cond_lines++;
2538			}
2539
2540			# Also ignore a loop construct at the end of a
2541			# preprocessor statement.
2542			if (($prevline =~ /^.\s*#\s*define\s/ ||
2543			    $prevline =~ /\\\s*$/) && $continuation == 0) {
2544				$check = 0;
2545			}
2546
2547			my $cond_ptr = -1;
2548			$continuation = 0;
2549			while ($cond_ptr != $cond_lines) {
2550				$cond_ptr = $cond_lines;
2551
2552				# If we see an #else/#elif then the code
2553				# is not linear.
2554				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2555					$check = 0;
2556				}
2557
2558				# Ignore:
2559				#  1) blank lines, they should be at 0,
2560				#  2) preprocessor lines, and
2561				#  3) labels.
2562				if ($continuation ||
2563				    $s =~ /^\s*?\n/ ||
2564				    $s =~ /^\s*#\s*?/ ||
2565				    $s =~ /^\s*$Ident\s*:/) {
2566					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2567					if ($s =~ s/^.*?\n//) {
2568						$cond_lines++;
2569					}
2570				}
2571			}
2572
2573			my (undef, $sindent) = line_stats("+" . $s);
2574			my $stat_real = raw_line($linenr, $cond_lines);
2575
2576			# Check if either of these lines are modified, else
2577			# this is not this patch's fault.
2578			if (!defined($stat_real) ||
2579			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2580				$check = 0;
2581			}
2582			if (defined($stat_real) && $cond_lines > 1) {
2583				$stat_real = "[...]\n$stat_real";
2584			}
2585
2586			#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";
2587
2588			if ($check && (($sindent % 8) != 0 ||
2589			    ($sindent <= $indent && $s ne ''))) {
2590				WARN("SUSPECT_CODE_INDENT",
2591				     "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2592			}
2593		}
2594
2595		# Track the 'values' across context and added lines.
2596		my $opline = $line; $opline =~ s/^./ /;
2597		my ($curr_values, $curr_vars) =
2598				annotate_values($opline . "\n", $prev_values);
2599		$curr_values = $prev_values . $curr_values;
2600		if ($dbg_values) {
2601			my $outline = $opline; $outline =~ s/\t/ /g;
2602			print "$linenr > .$outline\n";
2603			print "$linenr > $curr_values\n";
2604			print "$linenr >  $curr_vars\n";
2605		}
2606		$prev_values = substr($curr_values, -1);
2607
2608#ignore lines not being added
2609		next if ($line =~ /^[^\+]/);
2610
2611# TEST: allow direct testing of the type matcher.
2612		if ($dbg_type) {
2613			if ($line =~ /^.\s*$Declare\s*$/) {
2614				ERROR("TEST_TYPE",
2615				      "TEST: is type\n" . $herecurr);
2616			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2617				ERROR("TEST_NOT_TYPE",
2618				      "TEST: is not type ($1 is)\n". $herecurr);
2619			}
2620			next;
2621		}
2622# TEST: allow direct testing of the attribute matcher.
2623		if ($dbg_attr) {
2624			if ($line =~ /^.\s*$Modifier\s*$/) {
2625				ERROR("TEST_ATTR",
2626				      "TEST: is attr\n" . $herecurr);
2627			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2628				ERROR("TEST_NOT_ATTR",
2629				      "TEST: is not attr ($1 is)\n". $herecurr);
2630			}
2631			next;
2632		}
2633
2634# check for initialisation to aggregates open brace on the next line
2635		if ($line =~ /^.\s*{/ &&
2636		    $prevline =~ /(?:^|[^=])=\s*$/) {
2637			ERROR("OPEN_BRACE",
2638			      "that open brace { should be on the previous line\n" . $hereprev);
2639		}
2640
2641#
2642# Checks which are anchored on the added line.
2643#
2644
2645# check for malformed paths in #include statements (uses RAW line)
2646		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2647			my $path = $1;
2648			if ($path =~ m{//}) {
2649				ERROR("MALFORMED_INCLUDE",
2650				      "malformed #include filename\n" . $herecurr);
2651			}
2652			if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2653				ERROR("UAPI_INCLUDE",
2654				      "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2655			}
2656		}
2657
2658# no C99 // comments
2659		if ($line =~ m{//}) {
2660			if (ERROR("C99_COMMENTS",
2661				  "do not use C99 // comments\n" . $herecurr) &&
2662			    $fix) {
2663				my $line = $fixed[$linenr - 1];
2664				if ($line =~ /\/\/(.*)$/) {
2665					my $comment = trim($1);
2666					$fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@;
2667				}
2668			}
2669		}
2670		# Remove C99 comments.
2671		$line =~ s@//.*@@;
2672		$opline =~ s@//.*@@;
2673
2674# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2675# the whole statement.
2676#print "APW <$lines[$realline_next - 1]>\n";
2677		if (defined $realline_next &&
2678		    exists $lines[$realline_next - 1] &&
2679		    !defined $suppress_export{$realline_next} &&
2680		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2681		     $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2682			# Handle definitions which produce identifiers with
2683			# a prefix:
2684			#   XXX(foo);
2685			#   EXPORT_SYMBOL(something_foo);
2686			my $name = $1;
2687			if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2688			    $name =~ /^${Ident}_$2/) {
2689#print "FOO C name<$name>\n";
2690				$suppress_export{$realline_next} = 1;
2691
2692			} elsif ($stat !~ /(?:
2693				\n.}\s*$|
2694				^.DEFINE_$Ident\(\Q$name\E\)|
2695				^.DECLARE_$Ident\(\Q$name\E\)|
2696				^.LIST_HEAD\(\Q$name\E\)|
2697				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2698				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2699			    )/x) {
2700#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2701				$suppress_export{$realline_next} = 2;
2702			} else {
2703				$suppress_export{$realline_next} = 1;
2704			}
2705		}
2706		if (!defined $suppress_export{$linenr} &&
2707		    $prevline =~ /^.\s*$/ &&
2708		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2709		     $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2710#print "FOO B <$lines[$linenr - 1]>\n";
2711			$suppress_export{$linenr} = 2;
2712		}
2713		if (defined $suppress_export{$linenr} &&
2714		    $suppress_export{$linenr} == 2) {
2715			WARN("EXPORT_SYMBOL",
2716			     "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2717		}
2718
2719# check for global initialisers.
2720		if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
2721			if (ERROR("GLOBAL_INITIALISERS",
2722				  "do not initialise globals to 0 or NULL\n" .
2723				      $herecurr) &&
2724			    $fix) {
2725				$fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
2726			}
2727		}
2728# check for static initialisers.
2729		if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2730			if (ERROR("INITIALISED_STATIC",
2731				  "do not initialise statics to 0 or NULL\n" .
2732				      $herecurr) &&
2733			    $fix) {
2734				$fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
2735			}
2736		}
2737
2738# check for static const char * arrays.
2739		if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2740			WARN("STATIC_CONST_CHAR_ARRAY",
2741			     "static const char * array should probably be static const char * const\n" .
2742				$herecurr);
2743               }
2744
2745# check for static char foo[] = "bar" declarations.
2746		if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2747			WARN("STATIC_CONST_CHAR_ARRAY",
2748			     "static char array declaration should probably be static const char\n" .
2749				$herecurr);
2750               }
2751
2752# check for function declarations without arguments like "int foo()"
2753		if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
2754			if (ERROR("FUNCTION_WITHOUT_ARGS",
2755				  "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
2756			    $fix) {
2757				$fixed[$linenr - 1] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
2758			}
2759		}
2760
2761# check for uses of DEFINE_PCI_DEVICE_TABLE
2762		if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
2763			if (WARN("DEFINE_PCI_DEVICE_TABLE",
2764				 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
2765			    $fix) {
2766				$fixed[$linenr - 1] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
2767			}
2768		}
2769
2770# check for new typedefs, only function parameters and sparse annotations
2771# make sense.
2772		if ($line =~ /\btypedef\s/ &&
2773		    $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2774		    $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2775		    $line !~ /\b$typeTypedefs\b/ &&
2776		    $line !~ /\b__bitwise(?:__|)\b/) {
2777			WARN("NEW_TYPEDEFS",
2778			     "do not add new typedefs\n" . $herecurr);
2779		}
2780
2781# * goes on variable not on type
2782		# (char*[ const])
2783		while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2784			#print "AA<$1>\n";
2785			my ($ident, $from, $to) = ($1, $2, $2);
2786
2787			# Should start with a space.
2788			$to =~ s/^(\S)/ $1/;
2789			# Should not end with a space.
2790			$to =~ s/\s+$//;
2791			# '*'s should not have spaces between.
2792			while ($to =~ s/\*\s+\*/\*\*/) {
2793			}
2794
2795##			print "1: from<$from> to<$to> ident<$ident>\n";
2796			if ($from ne $to) {
2797				if (ERROR("POINTER_LOCATION",
2798					  "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
2799				    $fix) {
2800					my $sub_from = $ident;
2801					my $sub_to = $ident;
2802					$sub_to =~ s/\Q$from\E/$to/;
2803					$fixed[$linenr - 1] =~
2804					    s@\Q$sub_from\E@$sub_to@;
2805				}
2806			}
2807		}
2808		while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2809			#print "BB<$1>\n";
2810			my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
2811
2812			# Should start with a space.
2813			$to =~ s/^(\S)/ $1/;
2814			# Should not end with a space.
2815			$to =~ s/\s+$//;
2816			# '*'s should not have spaces between.
2817			while ($to =~ s/\*\s+\*/\*\*/) {
2818			}
2819			# Modifiers should have spaces.
2820			$to =~ s/(\b$Modifier$)/$1 /;
2821
2822##			print "2: from<$from> to<$to> ident<$ident>\n";
2823			if ($from ne $to && $ident !~ /^$Modifier$/) {
2824				if (ERROR("POINTER_LOCATION",
2825					  "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
2826				    $fix) {
2827
2828					my $sub_from = $match;
2829					my $sub_to = $match;
2830					$sub_to =~ s/\Q$from\E/$to/;
2831					$fixed[$linenr - 1] =~
2832					    s@\Q$sub_from\E@$sub_to@;
2833				}
2834			}
2835		}
2836
2837# # no BUG() or BUG_ON()
2838# 		if ($line =~ /\b(BUG|BUG_ON)\b/) {
2839# 			print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2840# 			print "$herecurr";
2841# 			$clean = 0;
2842# 		}
2843
2844		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2845			WARN("LINUX_VERSION_CODE",
2846			     "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2847		}
2848
2849# check for uses of printk_ratelimit
2850		if ($line =~ /\bprintk_ratelimit\s*\(/) {
2851			WARN("PRINTK_RATELIMITED",
2852"Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2853		}
2854
2855# printk should use KERN_* levels.  Note that follow on printk's on the
2856# same line do not need a level, so we use the current block context
2857# to try and find and validate the current printk.  In summary the current
2858# printk includes all preceding printk's which have no newline on the end.
2859# we assume the first bad printk is the one to report.
2860		if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2861			my $ok = 0;
2862			for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2863				#print "CHECK<$lines[$ln - 1]\n";
2864				# we have a preceding printk if it ends
2865				# with "\n" ignore it, else it is to blame
2866				if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2867					if ($rawlines[$ln - 1] !~ m{\\n"}) {
2868						$ok = 1;
2869					}
2870					last;
2871				}
2872			}
2873			if ($ok == 0) {
2874				WARN("PRINTK_WITHOUT_KERN_LEVEL",
2875				     "printk() should include KERN_ facility level\n" . $herecurr);
2876			}
2877		}
2878
2879		if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
2880			my $orig = $1;
2881			my $level = lc($orig);
2882			$level = "warn" if ($level eq "warning");
2883			my $level2 = $level;
2884			$level2 = "dbg" if ($level eq "debug");
2885			WARN("PREFER_PR_LEVEL",
2886			     "Prefer netdev_$level2(netdev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
2887		}
2888
2889		if ($line =~ /\bpr_warning\s*\(/) {
2890			if (WARN("PREFER_PR_LEVEL",
2891				 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
2892			    $fix) {
2893				$fixed[$linenr - 1] =~
2894				    s/\bpr_warning\b/pr_warn/;
2895			}
2896		}
2897
2898		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
2899			my $orig = $1;
2900			my $level = lc($orig);
2901			$level = "warn" if ($level eq "warning");
2902			$level = "dbg" if ($level eq "debug");
2903			WARN("PREFER_DEV_LEVEL",
2904			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
2905		}
2906
2907# function brace can't be on same line, except for #defines of do while,
2908# or if closed on same line
2909		if (($line=~/$Type\s*$Ident\(.*\).*\s\{/) and
2910		    !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
2911			ERROR("OPEN_BRACE",
2912			      "open brace '{' following function declarations go on the next line\n" . $herecurr);
2913		}
2914
2915# open braces for enum, union and struct go on the same line.
2916		if ($line =~ /^.\s*{/ &&
2917		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2918			ERROR("OPEN_BRACE",
2919			      "open brace '{' following $1 go on the same line\n" . $hereprev);
2920		}
2921
2922# missing space after union, struct or enum definition
2923		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
2924			if (WARN("SPACING",
2925				 "missing space after $1 definition\n" . $herecurr) &&
2926			    $fix) {
2927				$fixed[$linenr - 1] =~
2928				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
2929			}
2930		}
2931
2932# Function pointer declarations
2933# check spacing between type, funcptr, and args
2934# canonical declaration is "type (*funcptr)(args...)"
2935#
2936# the $Declare variable will capture all spaces after the type
2937# so check it for trailing missing spaces or multiple spaces
2938		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)$Ident(\s*)\)(\s*)\(/) {
2939			my $declare = $1;
2940			my $pre_pointer_space = $2;
2941			my $post_pointer_space = $3;
2942			my $funcname = $4;
2943			my $post_funcname_space = $5;
2944			my $pre_args_space = $6;
2945
2946			if ($declare !~ /\s$/) {
2947				WARN("SPACING",
2948				     "missing space after return type\n" . $herecurr);
2949			}
2950
2951# unnecessary space "type  (*funcptr)(args...)"
2952			elsif ($declare =~ /\s{2,}$/) {
2953				WARN("SPACING",
2954				     "Multiple spaces after return type\n" . $herecurr);
2955			}
2956
2957# unnecessary space "type ( *funcptr)(args...)"
2958			if (defined $pre_pointer_space &&
2959			    $pre_pointer_space =~ /^\s/) {
2960				WARN("SPACING",
2961				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
2962			}
2963
2964# unnecessary space "type (* funcptr)(args...)"
2965			if (defined $post_pointer_space &&
2966			    $post_pointer_space =~ /^\s/) {
2967				WARN("SPACING",
2968				     "Unnecessary space before function pointer name\n" . $herecurr);
2969			}
2970
2971# unnecessary space "type (*funcptr )(args...)"
2972			if (defined $post_funcname_space &&
2973			    $post_funcname_space =~ /^\s/) {
2974				WARN("SPACING",
2975				     "Unnecessary space after function pointer name\n" . $herecurr);
2976			}
2977
2978# unnecessary space "type (*funcptr) (args...)"
2979			if (defined $pre_args_space &&
2980			    $pre_args_space =~ /^\s/) {
2981				WARN("SPACING",
2982				     "Unnecessary space before function pointer arguments\n" . $herecurr);
2983			}
2984
2985			if (show_type("SPACING") && $fix) {
2986				$fixed[$linenr - 1] =~
2987				    s/^(.\s*$Declare)\(\s*\*\s*($Ident)\s*\)\s*\(/rtrim($1) . " " . "\(\*$2\)\("/ex;
2988			}
2989		}
2990
2991# check for spacing round square brackets; allowed:
2992#  1. with a type on the left -- int [] a;
2993#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2994#  3. inside a curly brace -- = { [0...10] = 5 }
2995		while ($line =~ /(.*?\s)\[/g) {
2996			my ($where, $prefix) = ($-[1], $1);
2997			if ($prefix !~ /$Type\s+$/ &&
2998			    ($where != 0 || $prefix !~ /^.\s+$/) &&
2999			    $prefix !~ /[{,]\s+$/) {
3000				if (ERROR("BRACKET_SPACE",
3001					  "space prohibited before open square bracket '['\n" . $herecurr) &&
3002				    $fix) {
3003				    $fixed[$linenr - 1] =~
3004					s/^(\+.*?)\s+\[/$1\[/;
3005				}
3006			}
3007		}
3008
3009# check for spaces between functions and their parentheses.
3010		while ($line =~ /($Ident)\s+\(/g) {
3011			my $name = $1;
3012			my $ctx_before = substr($line, 0, $-[1]);
3013			my $ctx = "$ctx_before$name";
3014
3015			# Ignore those directives where spaces _are_ permitted.
3016			if ($name =~ /^(?:
3017				if|for|while|switch|return|case|
3018				volatile|__volatile__|
3019				__attribute__|format|__extension__|
3020				asm|__asm__)$/x)
3021			{
3022			# cpp #define statements have non-optional spaces, ie
3023			# if there is a space between the name and the open
3024			# parenthesis it is simply not a parameter group.
3025			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3026
3027			# cpp #elif statement condition may start with a (
3028			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3029
3030			# If this whole things ends with a type its most
3031			# likely a typedef for a function.
3032			} elsif ($ctx =~ /$Type$/) {
3033
3034			} else {
3035				if (WARN("SPACING",
3036					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3037					     $fix) {
3038					$fixed[$linenr - 1] =~
3039					    s/\b$name\s+\(/$name\(/;
3040				}
3041			}
3042		}
3043
3044# Check operator spacing.
3045		if (!($line=~/\#\s*include/)) {
3046			my $fixed_line = "";
3047			my $line_fixed = 0;
3048
3049			my $ops = qr{
3050				<<=|>>=|<=|>=|==|!=|
3051				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3052				=>|->|<<|>>|<|>|=|!|~|
3053				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3054				\?:|\?|:
3055			}x;
3056			my @elements = split(/($ops|;)/, $opline);
3057
3058##			print("element count: <" . $#elements . ">\n");
3059##			foreach my $el (@elements) {
3060##				print("el: <$el>\n");
3061##			}
3062
3063			my @fix_elements = ();
3064			my $off = 0;
3065
3066			foreach my $el (@elements) {
3067				push(@fix_elements, substr($rawline, $off, length($el)));
3068				$off += length($el);
3069			}
3070
3071			$off = 0;
3072
3073			my $blank = copy_spacing($opline);
3074			my $last_after = -1;
3075
3076			for (my $n = 0; $n < $#elements; $n += 2) {
3077
3078				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3079
3080##				print("n: <$n> good: <$good>\n");
3081
3082				$off += length($elements[$n]);
3083
3084				# Pick up the preceding and succeeding characters.
3085				my $ca = substr($opline, 0, $off);
3086				my $cc = '';
3087				if (length($opline) >= ($off + length($elements[$n + 1]))) {
3088					$cc = substr($opline, $off + length($elements[$n + 1]));
3089				}
3090				my $cb = "$ca$;$cc";
3091
3092				my $a = '';
3093				$a = 'V' if ($elements[$n] ne '');
3094				$a = 'W' if ($elements[$n] =~ /\s$/);
3095				$a = 'C' if ($elements[$n] =~ /$;$/);
3096				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3097				$a = 'O' if ($elements[$n] eq '');
3098				$a = 'E' if ($ca =~ /^\s*$/);
3099
3100				my $op = $elements[$n + 1];
3101
3102				my $c = '';
3103				if (defined $elements[$n + 2]) {
3104					$c = 'V' if ($elements[$n + 2] ne '');
3105					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
3106					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
3107					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3108					$c = 'O' if ($elements[$n + 2] eq '');
3109					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3110				} else {
3111					$c = 'E';
3112				}
3113
3114				my $ctx = "${a}x${c}";
3115
3116				my $at = "(ctx:$ctx)";
3117
3118				my $ptr = substr($blank, 0, $off) . "^";
3119				my $hereptr = "$hereline$ptr\n";
3120
3121				# Pull out the value of this operator.
3122				my $op_type = substr($curr_values, $off + 1, 1);
3123
3124				# Get the full operator variant.
3125				my $opv = $op . substr($curr_vars, $off, 1);
3126
3127				# Ignore operators passed as parameters.
3128				if ($op_type ne 'V' &&
3129				    $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3130
3131#				# Ignore comments
3132#				} elsif ($op =~ /^$;+$/) {
3133
3134				# ; should have either the end of line or a space or \ after it
3135				} elsif ($op eq ';') {
3136					if ($ctx !~ /.x[WEBC]/ &&
3137					    $cc !~ /^\\/ && $cc !~ /^;/) {
3138						if (ERROR("SPACING",
3139							  "space required after that '$op' $at\n" . $hereptr)) {
3140							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3141							$line_fixed = 1;
3142						}
3143					}
3144
3145				# // is a comment
3146				} elsif ($op eq '//') {
3147
3148				# No spaces for:
3149				#   ->
3150				#   :   when part of a bitfield
3151				} elsif ($op eq '->' || $opv eq ':B') {
3152					if ($ctx =~ /Wx.|.xW/) {
3153						if (ERROR("SPACING",
3154							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3155							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3156							if (defined $fix_elements[$n + 2]) {
3157								$fix_elements[$n + 2] =~ s/^\s+//;
3158							}
3159							$line_fixed = 1;
3160						}
3161					}
3162
3163				# , must have a space on the right.
3164				} elsif ($op eq ',') {
3165					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3166						if (ERROR("SPACING",
3167							  "space required after that '$op' $at\n" . $hereptr)) {
3168							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3169							$line_fixed = 1;
3170							$last_after = $n;
3171						}
3172					}
3173
3174				# '*' as part of a type definition -- reported already.
3175				} elsif ($opv eq '*_') {
3176					#warn "'*' is part of type\n";
3177
3178				# unary operators should have a space before and
3179				# none after.  May be left adjacent to another
3180				# unary operator, or a cast
3181				} elsif ($op eq '!' || $op eq '~' ||
3182					 $opv eq '*U' || $opv eq '-U' ||
3183					 $opv eq '&U' || $opv eq '&&U') {
3184					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3185						if (ERROR("SPACING",
3186							  "space required before that '$op' $at\n" . $hereptr)) {
3187							if ($n != $last_after + 2) {
3188								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3189								$line_fixed = 1;
3190							}
3191						}
3192					}
3193					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3194						# A unary '*' may be const
3195
3196					} elsif ($ctx =~ /.xW/) {
3197						if (ERROR("SPACING",
3198							  "space prohibited after that '$op' $at\n" . $hereptr)) {
3199							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3200							if (defined $fix_elements[$n + 2]) {
3201								$fix_elements[$n + 2] =~ s/^\s+//;
3202							}
3203							$line_fixed = 1;
3204						}
3205					}
3206
3207				# unary ++ and unary -- are allowed no space on one side.
3208				} elsif ($op eq '++' or $op eq '--') {
3209					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3210						if (ERROR("SPACING",
3211							  "space required one side of that '$op' $at\n" . $hereptr)) {
3212							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3213							$line_fixed = 1;
3214						}
3215					}
3216					if ($ctx =~ /Wx[BE]/ ||
3217					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3218						if (ERROR("SPACING",
3219							  "space prohibited before that '$op' $at\n" . $hereptr)) {
3220							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3221							$line_fixed = 1;
3222						}
3223					}
3224					if ($ctx =~ /ExW/) {
3225						if (ERROR("SPACING",
3226							  "space prohibited after that '$op' $at\n" . $hereptr)) {
3227							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3228							if (defined $fix_elements[$n + 2]) {
3229								$fix_elements[$n + 2] =~ s/^\s+//;
3230							}
3231							$line_fixed = 1;
3232						}
3233					}
3234
3235				# << and >> may either have or not have spaces both sides
3236				} elsif ($op eq '<<' or $op eq '>>' or
3237					 $op eq '&' or $op eq '^' or $op eq '|' or
3238					 $op eq '+' or $op eq '-' or
3239					 $op eq '*' or $op eq '/' or
3240					 $op eq '%')
3241				{
3242					if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3243						if (ERROR("SPACING",
3244							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
3245							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3246							if (defined $fix_elements[$n + 2]) {
3247								$fix_elements[$n + 2] =~ s/^\s+//;
3248							}
3249							$line_fixed = 1;
3250						}
3251					}
3252
3253				# A colon needs no spaces before when it is
3254				# terminating a case value or a label.
3255				} elsif ($opv eq ':C' || $opv eq ':L') {
3256					if ($ctx =~ /Wx./) {
3257						if (ERROR("SPACING",
3258							  "space prohibited before that '$op' $at\n" . $hereptr)) {
3259							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3260							$line_fixed = 1;
3261						}
3262					}
3263
3264				# All the others need spaces both sides.
3265				} elsif ($ctx !~ /[EWC]x[CWE]/) {
3266					my $ok = 0;
3267
3268					# Ignore email addresses <foo@bar>
3269					if (($op eq '<' &&
3270					     $cc =~ /^\S+\@\S+>/) ||
3271					    ($op eq '>' &&
3272					     $ca =~ /<\S+\@\S+$/))
3273					{
3274					    	$ok = 1;
3275					}
3276
3277					# messages are ERROR, but ?: are CHK
3278					if ($ok == 0) {
3279						my $msg_type = \&ERROR;
3280						$msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3281
3282						if (&{$msg_type}("SPACING",
3283								 "spaces required around that '$op' $at\n" . $hereptr)) {
3284							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3285							if (defined $fix_elements[$n + 2]) {
3286								$fix_elements[$n + 2] =~ s/^\s+//;
3287							}
3288							$line_fixed = 1;
3289						}
3290					}
3291				}
3292				$off += length($elements[$n + 1]);
3293
3294##				print("n: <$n> GOOD: <$good>\n");
3295
3296				$fixed_line = $fixed_line . $good;
3297			}
3298
3299			if (($#elements % 2) == 0) {
3300				$fixed_line = $fixed_line . $fix_elements[$#elements];
3301			}
3302
3303			if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) {
3304				$fixed[$linenr - 1] = $fixed_line;
3305			}
3306
3307
3308		}
3309
3310# check for whitespace before a non-naked semicolon
3311		if ($line =~ /^\+.*\S\s+;\s*$/) {
3312			if (WARN("SPACING",
3313				 "space prohibited before semicolon\n" . $herecurr) &&
3314			    $fix) {
3315				1 while $fixed[$linenr - 1] =~
3316				    s/^(\+.*\S)\s+;/$1;/;
3317			}
3318		}
3319
3320# check for multiple assignments
3321		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3322			CHK("MULTIPLE_ASSIGNMENTS",
3323			    "multiple assignments should be avoided\n" . $herecurr);
3324		}
3325
3326## # check for multiple declarations, allowing for a function declaration
3327## # continuation.
3328## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3329## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3330##
3331## 			# Remove any bracketed sections to ensure we do not
3332## 			# falsly report the parameters of functions.
3333## 			my $ln = $line;
3334## 			while ($ln =~ s/\([^\(\)]*\)//g) {
3335## 			}
3336## 			if ($ln =~ /,/) {
3337## 				WARN("MULTIPLE_DECLARATION",
3338##				     "declaring multiple variables together should be avoided\n" . $herecurr);
3339## 			}
3340## 		}
3341
3342#need space before brace following if, while, etc
3343		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\){/) ||
3344		    $line =~ /do\{/) {
3345			if (ERROR("SPACING",
3346				  "space required before the open brace '{'\n" . $herecurr) &&
3347			    $fix) {
3348				$fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/;
3349			}
3350		}
3351
3352## # check for blank lines before declarations
3353##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3354##		    $prevrawline =~ /^.\s*$/) {
3355##			WARN("SPACING",
3356##			     "No blank lines before declarations\n" . $hereprev);
3357##		}
3358##
3359
3360# closing brace should have a space following it when it has anything
3361# on the line
3362		if ($line =~ /}(?!(?:,|;|\)))\S/) {
3363			if (ERROR("SPACING",
3364				  "space required after that close brace '}'\n" . $herecurr) &&
3365			    $fix) {
3366				$fixed[$linenr - 1] =~
3367				    s/}((?!(?:,|;|\)))\S)/} $1/;
3368			}
3369		}
3370
3371# check spacing on square brackets
3372		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3373			if (ERROR("SPACING",
3374				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
3375			    $fix) {
3376				$fixed[$linenr - 1] =~
3377				    s/\[\s+/\[/;
3378			}
3379		}
3380		if ($line =~ /\s\]/) {
3381			if (ERROR("SPACING",
3382				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3383			    $fix) {
3384				$fixed[$linenr - 1] =~
3385				    s/\s+\]/\]/;
3386			}
3387		}
3388
3389# check spacing on parentheses
3390		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3391		    $line !~ /for\s*\(\s+;/) {
3392			if (ERROR("SPACING",
3393				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3394			    $fix) {
3395				$fixed[$linenr - 1] =~
3396				    s/\(\s+/\(/;
3397			}
3398		}
3399		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3400		    $line !~ /for\s*\(.*;\s+\)/ &&
3401		    $line !~ /:\s+\)/) {
3402			if (ERROR("SPACING",
3403				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3404			    $fix) {
3405				$fixed[$linenr - 1] =~
3406				    s/\s+\)/\)/;
3407			}
3408		}
3409
3410#goto labels aren't indented, allow a single space however
3411		if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3412		   !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3413			if (WARN("INDENTED_LABEL",
3414				 "labels should not be indented\n" . $herecurr) &&
3415			    $fix) {
3416				$fixed[$linenr - 1] =~
3417				    s/^(.)\s+/$1/;
3418			}
3419		}
3420
3421# Return is not a function.
3422		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3423			my $spacing = $1;
3424			if ($^V && $^V ge 5.10.0 &&
3425			    $stat =~ /^.\s*return\s*$balanced_parens\s*;\s*$/) {
3426				ERROR("RETURN_PARENTHESES",
3427				      "return is not a function, parentheses are not required\n" . $herecurr);
3428
3429			} elsif ($spacing !~ /\s+/) {
3430				ERROR("SPACING",
3431				      "space required before the open parenthesis '('\n" . $herecurr);
3432			}
3433		}
3434
3435# if statements using unnecessary parentheses - ie: if ((foo == bar))
3436		if ($^V && $^V ge 5.10.0 &&
3437		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
3438			my $openparens = $1;
3439			my $count = $openparens =~ tr@\(@\(@;
3440			my $msg = "";
3441			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3442				my $comp = $4;	#Not $1 because of $LvalOrFunc
3443				$msg = " - maybe == should be = ?" if ($comp eq "==");
3444				WARN("UNNECESSARY_PARENTHESES",
3445				     "Unnecessary parentheses$msg\n" . $herecurr);
3446			}
3447		}
3448
3449# Return of what appears to be an errno should normally be -'ve
3450		if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3451			my $name = $1;
3452			if ($name ne 'EOF' && $name ne 'ERROR') {
3453				WARN("USE_NEGATIVE_ERRNO",
3454				     "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3455			}
3456		}
3457
3458# Need a space before open parenthesis after if, while etc
3459		if ($line =~ /\b(if|while|for|switch)\(/) {
3460			if (ERROR("SPACING",
3461				  "space required before the open parenthesis '('\n" . $herecurr) &&
3462			    $fix) {
3463				$fixed[$linenr - 1] =~
3464				    s/\b(if|while|for|switch)\(/$1 \(/;
3465			}
3466		}
3467
3468# Check for illegal assignment in if conditional -- and check for trailing
3469# statements after the conditional.
3470		if ($line =~ /do\s*(?!{)/) {
3471			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3472				ctx_statement_block($linenr, $realcnt, 0)
3473					if (!defined $stat);
3474			my ($stat_next) = ctx_statement_block($line_nr_next,
3475						$remain_next, $off_next);
3476			$stat_next =~ s/\n./\n /g;
3477			##print "stat<$stat> stat_next<$stat_next>\n";
3478
3479			if ($stat_next =~ /^\s*while\b/) {
3480				# If the statement carries leading newlines,
3481				# then count those as offsets.
3482				my ($whitespace) =
3483					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3484				my $offset =
3485					statement_rawlines($whitespace) - 1;
3486
3487				$suppress_whiletrailers{$line_nr_next +
3488								$offset} = 1;
3489			}
3490		}
3491		if (!defined $suppress_whiletrailers{$linenr} &&
3492		    defined($stat) && defined($cond) &&
3493		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3494			my ($s, $c) = ($stat, $cond);
3495
3496			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3497				ERROR("ASSIGN_IN_IF",
3498				      "do not use assignment in if condition\n" . $herecurr);
3499			}
3500
3501			# Find out what is on the end of the line after the
3502			# conditional.
3503			substr($s, 0, length($c), '');
3504			$s =~ s/\n.*//g;
3505			$s =~ s/$;//g; 	# Remove any comments
3506			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3507			    $c !~ /}\s*while\s*/)
3508			{
3509				# Find out how long the conditional actually is.
3510				my @newlines = ($c =~ /\n/gs);
3511				my $cond_lines = 1 + $#newlines;
3512				my $stat_real = '';
3513
3514				$stat_real = raw_line($linenr, $cond_lines)
3515							. "\n" if ($cond_lines);
3516				if (defined($stat_real) && $cond_lines > 1) {
3517					$stat_real = "[...]\n$stat_real";
3518				}
3519
3520				ERROR("TRAILING_STATEMENTS",
3521				      "trailing statements should be on next line\n" . $herecurr . $stat_real);
3522			}
3523		}
3524
3525# Check for bitwise tests written as boolean
3526		if ($line =~ /
3527			(?:
3528				(?:\[|\(|\&\&|\|\|)
3529				\s*0[xX][0-9]+\s*
3530				(?:\&\&|\|\|)
3531			|
3532				(?:\&\&|\|\|)
3533				\s*0[xX][0-9]+\s*
3534				(?:\&\&|\|\||\)|\])
3535			)/x)
3536		{
3537			WARN("HEXADECIMAL_BOOLEAN_TEST",
3538			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3539		}
3540
3541# if and else should not have general statements after it
3542		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3543			my $s = $1;
3544			$s =~ s/$;//g; 	# Remove any comments
3545			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3546				ERROR("TRAILING_STATEMENTS",
3547				      "trailing statements should be on next line\n" . $herecurr);
3548			}
3549		}
3550# if should not continue a brace
3551		if ($line =~ /}\s*if\b/) {
3552			ERROR("TRAILING_STATEMENTS",
3553			      "trailing statements should be on next line\n" .
3554				$herecurr);
3555		}
3556# case and default should not have general statements after them
3557		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
3558		    $line !~ /\G(?:
3559			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
3560			\s*return\s+
3561		    )/xg)
3562		{
3563			ERROR("TRAILING_STATEMENTS",
3564			      "trailing statements should be on next line\n" . $herecurr);
3565		}
3566
3567		# Check for }<nl>else {, these must be at the same
3568		# indent level to be relevant to each other.
3569		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
3570						$previndent == $indent) {
3571			ERROR("ELSE_AFTER_BRACE",
3572			      "else should follow close brace '}'\n" . $hereprev);
3573		}
3574
3575		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
3576						$previndent == $indent) {
3577			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
3578
3579			# Find out what is on the end of the line after the
3580			# conditional.
3581			substr($s, 0, length($c), '');
3582			$s =~ s/\n.*//g;
3583
3584			if ($s =~ /^\s*;/) {
3585				ERROR("WHILE_AFTER_BRACE",
3586				      "while should follow close brace '}'\n" . $hereprev);
3587			}
3588		}
3589
3590#Specific variable tests
3591		while ($line =~ m{($Constant|$Lval)}g) {
3592			my $var = $1;
3593
3594#gcc binary extension
3595			if ($var =~ /^$Binary$/) {
3596				if (WARN("GCC_BINARY_CONSTANT",
3597					 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
3598				    $fix) {
3599					my $hexval = sprintf("0x%x", oct($var));
3600					$fixed[$linenr - 1] =~
3601					    s/\b$var\b/$hexval/;
3602				}
3603			}
3604
3605#CamelCase
3606			if ($var !~ /^$Constant$/ &&
3607			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
3608#Ignore Page<foo> variants
3609			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
3610#Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
3611			    $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) {
3612				while ($var =~ m{($Ident)}g) {
3613					my $word = $1;
3614					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
3615					if ($check) {
3616						seed_camelcase_includes();
3617						if (!$file && !$camelcase_file_seeded) {
3618							seed_camelcase_file($realfile);
3619							$camelcase_file_seeded = 1;
3620						}
3621					}
3622					if (!defined $camelcase{$word}) {
3623						$camelcase{$word} = 1;
3624						CHK("CAMELCASE",
3625						    "Avoid CamelCase: <$word>\n" . $herecurr);
3626					}
3627				}
3628			}
3629		}
3630
3631#no spaces allowed after \ in define
3632		if ($line =~ /\#\s*define.*\\\s+$/) {
3633			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
3634				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
3635			    $fix) {
3636				$fixed[$linenr - 1] =~ s/\s+$//;
3637			}
3638		}
3639
3640#warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
3641		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
3642			my $file = "$1.h";
3643			my $checkfile = "include/linux/$file";
3644			if (-f "$root/$checkfile" &&
3645			    $realfile ne $checkfile &&
3646			    $1 !~ /$allowed_asm_includes/)
3647			{
3648				if ($realfile =~ m{^arch/}) {
3649					CHK("ARCH_INCLUDE_LINUX",
3650					    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3651				} else {
3652					WARN("INCLUDE_LINUX",
3653					     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3654				}
3655			}
3656		}
3657
3658# multi-statement macros should be enclosed in a do while loop, grab the
3659# first statement and ensure its the whole macro if its not enclosed
3660# in a known good container
3661		if ($realfile !~ m@/vmlinux.lds.h$@ &&
3662		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
3663			my $ln = $linenr;
3664			my $cnt = $realcnt;
3665			my ($off, $dstat, $dcond, $rest);
3666			my $ctx = '';
3667			($dstat, $dcond, $ln, $cnt, $off) =
3668				ctx_statement_block($linenr, $realcnt, 0);
3669			$ctx = $dstat;
3670			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
3671			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
3672
3673			$dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
3674			$dstat =~ s/$;//g;
3675			$dstat =~ s/\\\n.//g;
3676			$dstat =~ s/^\s*//s;
3677			$dstat =~ s/\s*$//s;
3678
3679			# Flatten any parentheses and braces
3680			while ($dstat =~ s/\([^\(\)]*\)/1/ ||
3681			       $dstat =~ s/\{[^\{\}]*\}/1/ ||
3682			       $dstat =~ s/\[[^\[\]]*\]/1/)
3683			{
3684			}
3685
3686			# Flatten any obvious string concatentation.
3687			while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
3688			       $dstat =~ s/$Ident\s*("X*")/$1/)
3689			{
3690			}
3691
3692			my $exceptions = qr{
3693				$Declare|
3694				module_param_named|
3695				MODULE_PARM_DESC|
3696				DECLARE_PER_CPU|
3697				DEFINE_PER_CPU|
3698				__typeof__\(|
3699				union|
3700				struct|
3701				\.$Ident\s*=\s*|
3702				^\"|\"$
3703			}x;
3704			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
3705			if ($dstat ne '' &&
3706			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
3707			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
3708			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
3709			    $dstat !~ /^'X'$/ &&					# character constants
3710			    $dstat !~ /$exceptions/ &&
3711			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
3712			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
3713			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
3714			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
3715			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
3716			    $dstat !~ /^do\s*{/ &&					# do {...
3717			    $dstat !~ /^\(\{/ &&						# ({...
3718			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
3719			{
3720				$ctx =~ s/\n*$//;
3721				my $herectx = $here . "\n";
3722				my $cnt = statement_rawlines($ctx);
3723
3724				for (my $n = 0; $n < $cnt; $n++) {
3725					$herectx .= raw_line($linenr, $n) . "\n";
3726				}
3727
3728				if ($dstat =~ /;/) {
3729					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
3730					      "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
3731				} else {
3732					ERROR("COMPLEX_MACRO",
3733					      "Macros with complex values should be enclosed in parenthesis\n" . "$herectx");
3734				}
3735			}
3736
3737# check for line continuations outside of #defines, preprocessor #, and asm
3738
3739		} else {
3740			if ($prevline !~ /^..*\\$/ &&
3741			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
3742			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
3743			    $line =~ /^\+.*\\$/) {
3744				WARN("LINE_CONTINUATIONS",
3745				     "Avoid unnecessary line continuations\n" . $herecurr);
3746			}
3747		}
3748
3749# do {} while (0) macro tests:
3750# single-statement macros do not need to be enclosed in do while (0) loop,
3751# macro should not end with a semicolon
3752		if ($^V && $^V ge 5.10.0 &&
3753		    $realfile !~ m@/vmlinux.lds.h$@ &&
3754		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
3755			my $ln = $linenr;
3756			my $cnt = $realcnt;
3757			my ($off, $dstat, $dcond, $rest);
3758			my $ctx = '';
3759			($dstat, $dcond, $ln, $cnt, $off) =
3760				ctx_statement_block($linenr, $realcnt, 0);
3761			$ctx = $dstat;
3762
3763			$dstat =~ s/\\\n.//g;
3764
3765			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
3766				my $stmts = $2;
3767				my $semis = $3;
3768
3769				$ctx =~ s/\n*$//;
3770				my $cnt = statement_rawlines($ctx);
3771				my $herectx = $here . "\n";
3772
3773				for (my $n = 0; $n < $cnt; $n++) {
3774					$herectx .= raw_line($linenr, $n) . "\n";
3775				}
3776
3777				if (($stmts =~ tr/;/;/) == 1 &&
3778				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
3779					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
3780					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
3781				}
3782				if (defined $semis && $semis ne "") {
3783					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
3784					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
3785				}
3786			}
3787		}
3788
3789# make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
3790# all assignments may have only one of the following with an assignment:
3791#	.
3792#	ALIGN(...)
3793#	VMLINUX_SYMBOL(...)
3794		if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
3795			WARN("MISSING_VMLINUX_SYMBOL",
3796			     "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
3797		}
3798
3799# check for redundant bracing round if etc
3800		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
3801			my ($level, $endln, @chunks) =
3802				ctx_statement_full($linenr, $realcnt, 1);
3803			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
3804			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
3805			if ($#chunks > 0 && $level == 0) {
3806				my @allowed = ();
3807				my $allow = 0;
3808				my $seen = 0;
3809				my $herectx = $here . "\n";
3810				my $ln = $linenr - 1;
3811				for my $chunk (@chunks) {
3812					my ($cond, $block) = @{$chunk};
3813
3814					# If the condition carries leading newlines, then count those as offsets.
3815					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
3816					my $offset = statement_rawlines($whitespace) - 1;
3817
3818					$allowed[$allow] = 0;
3819					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
3820
3821					# We have looked at and allowed this specific line.
3822					$suppress_ifbraces{$ln + $offset} = 1;
3823
3824					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3825					$ln += statement_rawlines($block) - 1;
3826
3827					substr($block, 0, length($cond), '');
3828
3829					$seen++ if ($block =~ /^\s*{/);
3830
3831					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
3832					if (statement_lines($cond) > 1) {
3833						#print "APW: ALLOWED: cond<$cond>\n";
3834						$allowed[$allow] = 1;
3835					}
3836					if ($block =~/\b(?:if|for|while)\b/) {
3837						#print "APW: ALLOWED: block<$block>\n";
3838						$allowed[$allow] = 1;
3839					}
3840					if (statement_block_size($block) > 1) {
3841						#print "APW: ALLOWED: lines block<$block>\n";
3842						$allowed[$allow] = 1;
3843					}
3844					$allow++;
3845				}
3846				if ($seen) {
3847					my $sum_allowed = 0;
3848					foreach (@allowed) {
3849						$sum_allowed += $_;
3850					}
3851					if ($sum_allowed == 0) {
3852						WARN("BRACES",
3853						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
3854					} elsif ($sum_allowed != $allow &&
3855						 $seen != $allow) {
3856						CHK("BRACES",
3857						    "braces {} should be used on all arms of this statement\n" . $herectx);
3858					}
3859				}
3860			}
3861		}
3862		if (!defined $suppress_ifbraces{$linenr - 1} &&
3863					$line =~ /\b(if|while|for|else)\b/) {
3864			my $allowed = 0;
3865
3866			# Check the pre-context.
3867			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3868				#print "APW: ALLOWED: pre<$1>\n";
3869				$allowed = 1;
3870			}
3871
3872			my ($level, $endln, @chunks) =
3873				ctx_statement_full($linenr, $realcnt, $-[0]);
3874
3875			# Check the condition.
3876			my ($cond, $block) = @{$chunks[0]};
3877			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
3878			if (defined $cond) {
3879				substr($block, 0, length($cond), '');
3880			}
3881			if (statement_lines($cond) > 1) {
3882				#print "APW: ALLOWED: cond<$cond>\n";
3883				$allowed = 1;
3884			}
3885			if ($block =~/\b(?:if|for|while)\b/) {
3886				#print "APW: ALLOWED: block<$block>\n";
3887				$allowed = 1;
3888			}
3889			if (statement_block_size($block) > 1) {
3890				#print "APW: ALLOWED: lines block<$block>\n";
3891				$allowed = 1;
3892			}
3893			# Check the post-context.
3894			if (defined $chunks[1]) {
3895				my ($cond, $block) = @{$chunks[1]};
3896				if (defined $cond) {
3897					substr($block, 0, length($cond), '');
3898				}
3899				if ($block =~ /^\s*\{/) {
3900					#print "APW: ALLOWED: chunk-1 block<$block>\n";
3901					$allowed = 1;
3902				}
3903			}
3904			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
3905				my $herectx = $here . "\n";
3906				my $cnt = statement_rawlines($block);
3907
3908				for (my $n = 0; $n < $cnt; $n++) {
3909					$herectx .= raw_line($linenr, $n) . "\n";
3910				}
3911
3912				WARN("BRACES",
3913				     "braces {} are not necessary for single statement blocks\n" . $herectx);
3914			}
3915		}
3916
3917# check for unnecessary blank lines around braces
3918		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
3919			CHK("BRACES",
3920			    "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
3921		}
3922		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
3923			CHK("BRACES",
3924			    "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
3925		}
3926
3927# no volatiles please
3928		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3929		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
3930			WARN("VOLATILE",
3931			     "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
3932		}
3933
3934# warn about #if 0
3935		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3936			CHK("REDUNDANT_CODE",
3937			    "if this code is redundant consider removing it\n" .
3938				$herecurr);
3939		}
3940
3941# check for needless "if (<foo>) fn(<foo>)" uses
3942		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
3943			my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
3944			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
3945				WARN('NEEDLESS_IF',
3946				     "$1(NULL) is safe this check is probably not required\n" . $hereprev);
3947			}
3948		}
3949
3950# check for bad placement of section $InitAttribute (e.g.: __initdata)
3951		if ($line =~ /(\b$InitAttribute\b)/) {
3952			my $attr = $1;
3953			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
3954				my $ptr = $1;
3955				my $var = $2;
3956				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
3957				      ERROR("MISPLACED_INIT",
3958					    "$attr should be placed after $var\n" . $herecurr)) ||
3959				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
3960				      WARN("MISPLACED_INIT",
3961					   "$attr should be placed after $var\n" . $herecurr))) &&
3962				    $fix) {
3963					$fixed[$linenr - 1] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
3964				}
3965			}
3966		}
3967
3968# check for $InitAttributeData (ie: __initdata) with const
3969		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
3970			my $attr = $1;
3971			$attr =~ /($InitAttributePrefix)(.*)/;
3972			my $attr_prefix = $1;
3973			my $attr_type = $2;
3974			if (ERROR("INIT_ATTRIBUTE",
3975				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
3976			    $fix) {
3977				$fixed[$linenr - 1] =~
3978				    s/$InitAttributeData/${attr_prefix}initconst/;
3979			}
3980		}
3981
3982# check for $InitAttributeConst (ie: __initconst) without const
3983		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
3984			my $attr = $1;
3985			if (ERROR("INIT_ATTRIBUTE",
3986				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
3987			    $fix) {
3988				my $lead = $fixed[$linenr - 1] =~
3989				    /(^\+\s*(?:static\s+))/;
3990				$lead = rtrim($1);
3991				$lead = "$lead " if ($lead !~ /^\+$/);
3992				$lead = "${lead}const ";
3993				$fixed[$linenr - 1] =~ s/(^\+\s*(?:static\s+))/$lead/;
3994			}
3995		}
3996
3997# prefer usleep_range over udelay
3998		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
3999			# ignore udelay's < 10, however
4000			if (! ($1 < 10) ) {
4001				CHK("USLEEP_RANGE",
4002				    "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
4003			}
4004		}
4005
4006# warn about unexpectedly long msleep's
4007		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4008			if ($1 < 20) {
4009				WARN("MSLEEP",
4010				     "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
4011			}
4012		}
4013
4014# check for comparisons of jiffies
4015		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4016			WARN("JIFFIES_COMPARISON",
4017			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4018		}
4019
4020# check for comparisons of get_jiffies_64()
4021		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4022			WARN("JIFFIES_COMPARISON",
4023			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4024		}
4025
4026# warn about #ifdefs in C files
4027#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4028#			print "#ifdef in C files should be avoided\n";
4029#			print "$herecurr";
4030#			$clean = 0;
4031#		}
4032
4033# warn about spacing in #ifdefs
4034		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4035			if (ERROR("SPACING",
4036				  "exactly one space required after that #$1\n" . $herecurr) &&
4037			    $fix) {
4038				$fixed[$linenr - 1] =~
4039				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4040			}
4041
4042		}
4043
4044# check for spinlock_t definitions without a comment.
4045		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4046		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4047			my $which = $1;
4048			if (!ctx_has_comment($first_line, $linenr)) {
4049				CHK("UNCOMMENTED_DEFINITION",
4050				    "$1 definition without comment\n" . $herecurr);
4051			}
4052		}
4053# check for memory barriers without a comment.
4054		if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4055			if (!ctx_has_comment($first_line, $linenr)) {
4056				WARN("MEMORY_BARRIER",
4057				     "memory barrier without comment\n" . $herecurr);
4058			}
4059		}
4060# check of hardware specific defines
4061		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4062			CHK("ARCH_DEFINES",
4063			    "architecture specific defines should be avoided\n" .  $herecurr);
4064		}
4065
4066# Check that the storage class is at the beginning of a declaration
4067		if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4068			WARN("STORAGE_CLASS",
4069			     "storage class should be at the beginning of the declaration\n" . $herecurr)
4070		}
4071
4072# check the location of the inline attribute, that it is between
4073# storage class and type.
4074		if ($line =~ /\b$Type\s+$Inline\b/ ||
4075		    $line =~ /\b$Inline\s+$Storage\b/) {
4076			ERROR("INLINE_LOCATION",
4077			      "inline keyword should sit between storage class and type\n" . $herecurr);
4078		}
4079
4080# Check for __inline__ and __inline, prefer inline
4081		if ($realfile !~ m@\binclude/uapi/@ &&
4082		    $line =~ /\b(__inline__|__inline)\b/) {
4083			if (WARN("INLINE",
4084				 "plain inline is preferred over $1\n" . $herecurr) &&
4085			    $fix) {
4086				$fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/;
4087
4088			}
4089		}
4090
4091# Check for __attribute__ packed, prefer __packed
4092		if ($realfile !~ m@\binclude/uapi/@ &&
4093		    $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4094			WARN("PREFER_PACKED",
4095			     "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4096		}
4097# Check for new packed members, warn to use care
4098		if ($line =~ /\b(__attribute__\s*\(\s*\(.*\bpacked|__packed)\b/) {
4099			WARN("NEW_PACKED",
4100			     "Adding new packed members is to be done with care\n" . $herecurr);
4101		}
4102
4103# Check for __attribute__ aligned, prefer __aligned
4104		if ($realfile !~ m@\binclude/uapi/@ &&
4105		    $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4106			WARN("PREFER_ALIGNED",
4107			     "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4108		}
4109
4110# Check for __attribute__ format(printf, prefer __printf
4111		if ($realfile !~ m@\binclude/uapi/@ &&
4112		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4113			if (WARN("PREFER_PRINTF",
4114				 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4115			    $fix) {
4116				$fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4117
4118			}
4119		}
4120
4121# Check for __attribute__ format(scanf, prefer __scanf
4122		if ($realfile !~ m@\binclude/uapi/@ &&
4123		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4124			if (WARN("PREFER_SCANF",
4125				 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4126			    $fix) {
4127				$fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4128			}
4129		}
4130
4131# check for sizeof(&)
4132		if ($line =~ /\bsizeof\s*\(\s*\&/) {
4133			WARN("SIZEOF_ADDRESS",
4134			     "sizeof(& should be avoided\n" . $herecurr);
4135		}
4136
4137# check for sizeof without parenthesis
4138		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4139			if (WARN("SIZEOF_PARENTHESIS",
4140				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4141			    $fix) {
4142				$fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4143			}
4144		}
4145
4146# check for line continuations in quoted strings with odd counts of "
4147		if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4148			WARN("LINE_CONTINUATIONS",
4149			     "Avoid line continuations in quoted strings\n" . $herecurr);
4150		}
4151
4152# check for struct spinlock declarations
4153		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4154			WARN("USE_SPINLOCK_T",
4155			     "struct spinlock should be spinlock_t\n" . $herecurr);
4156		}
4157
4158# check for seq_printf uses that could be seq_puts
4159		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4160			my $fmt = get_quoted_string($line, $rawline);
4161			if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4162				if (WARN("PREFER_SEQ_PUTS",
4163					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4164				    $fix) {
4165					$fixed[$linenr - 1] =~ s/\bseq_printf\b/seq_puts/;
4166				}
4167			}
4168		}
4169
4170# Check for misused memsets
4171		if ($^V && $^V ge 5.10.0 &&
4172		    defined $stat &&
4173		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4174
4175			my $ms_addr = $2;
4176			my $ms_val = $7;
4177			my $ms_size = $12;
4178
4179			if ($ms_size =~ /^(0x|)0$/i) {
4180				ERROR("MEMSET",
4181				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4182			} elsif ($ms_size =~ /^(0x|)1$/i) {
4183				WARN("MEMSET",
4184				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4185			}
4186		}
4187
4188# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4189		if ($^V && $^V ge 5.10.0 &&
4190		    $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4191			if (WARN("PREFER_ETHER_ADDR_COPY",
4192				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4193			    $fix) {
4194				$fixed[$linenr - 1] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4195			}
4196		}
4197
4198# typecasts on min/max could be min_t/max_t
4199		if ($^V && $^V ge 5.10.0 &&
4200		    defined $stat &&
4201		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4202			if (defined $2 || defined $7) {
4203				my $call = $1;
4204				my $cast1 = deparenthesize($2);
4205				my $arg1 = $3;
4206				my $cast2 = deparenthesize($7);
4207				my $arg2 = $8;
4208				my $cast;
4209
4210				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4211					$cast = "$cast1 or $cast2";
4212				} elsif ($cast1 ne "") {
4213					$cast = $cast1;
4214				} else {
4215					$cast = $cast2;
4216				}
4217				WARN("MINMAX",
4218				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4219			}
4220		}
4221
4222# check usleep_range arguments
4223		if ($^V && $^V ge 5.10.0 &&
4224		    defined $stat &&
4225		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4226			my $min = $1;
4227			my $max = $7;
4228			if ($min eq $max) {
4229				WARN("USLEEP_RANGE",
4230				     "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4231			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4232				 $min > $max) {
4233				WARN("USLEEP_RANGE",
4234				     "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4235			}
4236		}
4237
4238# check for naked sscanf
4239		if ($^V && $^V ge 5.10.0 &&
4240		    defined $stat &&
4241		    $stat =~ /\bsscanf\b/ &&
4242		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4243		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4244		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4245			my $lc = $stat =~ tr@\n@@;
4246			$lc = $lc + $linenr;
4247			my $stat_real = raw_line($linenr, 0);
4248		        for (my $count = $linenr + 1; $count <= $lc; $count++) {
4249				$stat_real = $stat_real . "\n" . raw_line($count, 0);
4250			}
4251			WARN("NAKED_SSCANF",
4252			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4253		}
4254
4255# check for new externs in .h files.
4256		if ($realfile =~ /\.h$/ &&
4257		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4258			if (CHK("AVOID_EXTERNS",
4259				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
4260			    $fix) {
4261				$fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4262			}
4263		}
4264
4265# check for new externs in .c files.
4266		if ($realfile =~ /\.c$/ && defined $stat &&
4267		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4268		{
4269			my $function_name = $1;
4270			my $paren_space = $2;
4271
4272			my $s = $stat;
4273			if (defined $cond) {
4274				substr($s, 0, length($cond), '');
4275			}
4276			if ($s =~ /^\s*;/ &&
4277			    $function_name ne 'uninitialized_var')
4278			{
4279				WARN("AVOID_EXTERNS",
4280				     "externs should be avoided in .c files\n" .  $herecurr);
4281			}
4282
4283			if ($paren_space =~ /\n/) {
4284				WARN("FUNCTION_ARGUMENTS",
4285				     "arguments for function declarations should follow identifier\n" . $herecurr);
4286			}
4287
4288		} elsif ($realfile =~ /\.c$/ && defined $stat &&
4289		    $stat =~ /^.\s*extern\s+/)
4290		{
4291			WARN("AVOID_EXTERNS",
4292			     "externs should be avoided in .c files\n" .  $herecurr);
4293		}
4294
4295# checks for new __setup's
4296		if ($rawline =~ /\b__setup\("([^"]*)"/) {
4297			my $name = $1;
4298
4299			if (!grep(/$name/, @setup_docs)) {
4300				CHK("UNDOCUMENTED_SETUP",
4301				    "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4302			}
4303		}
4304
4305# check for pointless casting of kmalloc return
4306		if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4307			WARN("UNNECESSARY_CASTS",
4308			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4309		}
4310
4311# alloc style
4312# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4313		if ($^V && $^V ge 5.10.0 &&
4314		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4315			CHK("ALLOC_SIZEOF_STRUCT",
4316			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4317		}
4318
4319# check for krealloc arg reuse
4320		if ($^V && $^V ge 5.10.0 &&
4321		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
4322			WARN("KREALLOC_ARG_REUSE",
4323			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
4324		}
4325
4326# check for alloc argument mismatch
4327		if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
4328			WARN("ALLOC_ARRAY_ARGS",
4329			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
4330		}
4331
4332# check for GFP_NOWAIT use
4333		if ($line =~ /\b__GFP_NOFAIL\b/) {
4334			WARN("__GFP_NOFAIL",
4335			     "Use of __GFP_NOFAIL is deprecated, no new users should be added\n" . $herecurr);
4336		}
4337
4338# check for multiple semicolons
4339		if ($line =~ /;\s*;\s*$/) {
4340			if (WARN("ONE_SEMICOLON",
4341				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
4342			    $fix) {
4343				$fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g;
4344			}
4345		}
4346
4347# check for case / default statements not preceded by break/fallthrough/switch
4348		if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
4349			my $has_break = 0;
4350			my $has_statement = 0;
4351			my $count = 0;
4352			my $prevline = $linenr;
4353			while ($prevline > 1 && $count < 3 && !$has_break) {
4354				$prevline--;
4355				my $rline = $rawlines[$prevline - 1];
4356				my $fline = $lines[$prevline - 1];
4357				last if ($fline =~ /^\@\@/);
4358				next if ($fline =~ /^\-/);
4359				next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
4360				$has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
4361				next if ($fline =~ /^.[\s$;]*$/);
4362				$has_statement = 1;
4363				$count++;
4364				$has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
4365			}
4366			if (!$has_break && $has_statement) {
4367				WARN("MISSING_BREAK",
4368				     "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
4369			}
4370		}
4371
4372# check for switch/default statements without a break;
4373		if ($^V && $^V ge 5.10.0 &&
4374		    defined $stat &&
4375		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
4376			my $ctx = '';
4377			my $herectx = $here . "\n";
4378			my $cnt = statement_rawlines($stat);
4379			for (my $n = 0; $n < $cnt; $n++) {
4380				$herectx .= raw_line($linenr, $n) . "\n";
4381			}
4382			WARN("DEFAULT_NO_BREAK",
4383			     "switch default: should use break\n" . $herectx);
4384		}
4385
4386# check for gcc specific __FUNCTION__
4387		if ($line =~ /\b__FUNCTION__\b/) {
4388			if (WARN("USE_FUNC",
4389				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
4390			    $fix) {
4391				$fixed[$linenr - 1] =~ s/\b__FUNCTION__\b/__func__/g;
4392			}
4393		}
4394
4395# check for use of yield()
4396		if ($line =~ /\byield\s*\(\s*\)/) {
4397			WARN("YIELD",
4398			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
4399		}
4400
4401# check for comparisons against true and false
4402		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
4403			my $lead = $1;
4404			my $arg = $2;
4405			my $test = $3;
4406			my $otype = $4;
4407			my $trail = $5;
4408			my $op = "!";
4409
4410			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
4411
4412			my $type = lc($otype);
4413			if ($type =~ /^(?:true|false)$/) {
4414				if (("$test" eq "==" && "$type" eq "true") ||
4415				    ("$test" eq "!=" && "$type" eq "false")) {
4416					$op = "";
4417				}
4418
4419				CHK("BOOL_COMPARISON",
4420				    "Using comparison to $otype is error prone\n" . $herecurr);
4421
4422## maybe suggesting a correct construct would better
4423##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
4424
4425			}
4426		}
4427
4428# check for semaphores initialized locked
4429		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
4430			WARN("CONSIDER_COMPLETION",
4431			     "consider using a completion\n" . $herecurr);
4432		}
4433
4434# recommend kstrto* over simple_strto* and strict_strto*
4435		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
4436			WARN("CONSIDER_KSTRTO",
4437			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
4438		}
4439
4440# check for __initcall(), use device_initcall() explicitly please
4441		if ($line =~ /^.\s*__initcall\s*\(/) {
4442			WARN("USE_DEVICE_INITCALL",
4443			     "please use device_initcall() instead of __initcall()\n" . $herecurr);
4444		}
4445
4446# check for various ops structs, ensure they are const.
4447		my $struct_ops = qr{acpi_dock_ops|
4448				address_space_operations|
4449				backlight_ops|
4450				block_device_operations|
4451				dentry_operations|
4452				dev_pm_ops|
4453				dma_map_ops|
4454				extent_io_ops|
4455				file_lock_operations|
4456				file_operations|
4457				hv_ops|
4458				ide_dma_ops|
4459				intel_dvo_dev_ops|
4460				item_operations|
4461				iwl_ops|
4462				kgdb_arch|
4463				kgdb_io|
4464				kset_uevent_ops|
4465				lock_manager_operations|
4466				microcode_ops|
4467				mtrr_ops|
4468				neigh_ops|
4469				nlmsvc_binding|
4470				pci_raw_ops|
4471				pipe_buf_operations|
4472				platform_hibernation_ops|
4473				platform_suspend_ops|
4474				proto_ops|
4475				rpc_pipe_ops|
4476				seq_operations|
4477				snd_ac97_build_ops|
4478				soc_pcmcia_socket_ops|
4479				stacktrace_ops|
4480				sysfs_ops|
4481				tty_operations|
4482				usb_mon_operations|
4483				wd_ops}x;
4484		if ($line !~ /\bconst\b/ &&
4485		    $line =~ /\bstruct\s+($struct_ops)\b/) {
4486			WARN("CONST_STRUCT",
4487			     "struct $1 should normally be const\n" .
4488				$herecurr);
4489		}
4490
4491# use of NR_CPUS is usually wrong
4492# ignore definitions of NR_CPUS and usage to define arrays as likely right
4493		if ($line =~ /\bNR_CPUS\b/ &&
4494		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
4495		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
4496		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
4497		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
4498		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
4499		{
4500			WARN("NR_CPUS",
4501			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
4502		}
4503
4504# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
4505		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
4506			ERROR("DEFINE_ARCH_HAS",
4507			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
4508		}
4509
4510# check for %L{u,d,i} in strings
4511		my $string;
4512		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4513			$string = substr($rawline, $-[1], $+[1] - $-[1]);
4514			$string =~ s/%%/__/g;
4515			if ($string =~ /(?<!%)%L[udi]/) {
4516				WARN("PRINTF_L",
4517				     "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4518				last;
4519			}
4520		}
4521
4522# whine mightly about in_atomic
4523		if ($line =~ /\bin_atomic\s*\(/) {
4524			if ($realfile =~ m@^drivers/@) {
4525				ERROR("IN_ATOMIC",
4526				      "do not use in_atomic in drivers\n" . $herecurr);
4527			} elsif ($realfile !~ m@^kernel/@) {
4528				WARN("IN_ATOMIC",
4529				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
4530			}
4531		}
4532
4533# check for lockdep_set_novalidate_class
4534		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
4535		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
4536			if ($realfile !~ m@^kernel/lockdep@ &&
4537			    $realfile !~ m@^include/linux/lockdep@ &&
4538			    $realfile !~ m@^drivers/base/core@) {
4539				ERROR("LOCKDEP",
4540				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
4541			}
4542		}
4543
4544		if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
4545		    $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
4546			WARN("EXPORTED_WORLD_WRITABLE",
4547			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
4548		}
4549	}
4550
4551	# If we have no input at all, then there is nothing to report on
4552	# so just keep quiet.
4553	if ($#rawlines == -1) {
4554		exit(0);
4555	}
4556
4557	# In mailback mode only produce a report in the negative, for
4558	# things that appear to be patches.
4559	if ($mailback && ($clean == 1 || !$is_patch)) {
4560		exit(0);
4561	}
4562
4563	# This is not a patch, and we are are in 'no-patch' mode so
4564	# just keep quiet.
4565	if (!$chk_patch && !$is_patch) {
4566		exit(0);
4567	}
4568
4569	if (!$is_patch) {
4570		ERROR("NOT_UNIFIED_DIFF",
4571		      "Does not appear to be a unified-diff format patch\n");
4572	}
4573	if ($is_patch && $chk_signoff && $signoff == 0) {
4574		ERROR("MISSING_SIGN_OFF",
4575		      "Missing Signed-off-by: line(s)\n");
4576	}
4577
4578	print report_dump();
4579	if ($summary && !($clean == 1 && $quiet == 1)) {
4580		print "$filename " if ($summary_file);
4581		print "total: $cnt_error errors, $cnt_warn warnings, " .
4582			(($check)? "$cnt_chk checks, " : "") .
4583			"$cnt_lines lines checked\n";
4584		print "\n" if ($quiet == 0);
4585	}
4586
4587	if ($quiet == 0) {
4588
4589		if ($^V lt 5.10.0) {
4590			print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
4591			print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
4592		}
4593
4594		# If there were whitespace errors which cleanpatch can fix
4595		# then suggest that.
4596		if ($rpt_cleaners) {
4597			print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
4598			print "      scripts/cleanfile\n\n";
4599			$rpt_cleaners = 0;
4600		}
4601	}
4602
4603	hash_show_words(\%use_type, "Used");
4604	hash_show_words(\%ignore_type, "Ignored");
4605
4606	if ($clean == 0 && $fix && "@rawlines" ne "@fixed") {
4607		my $newfile = $filename;
4608		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
4609		my $linecount = 0;
4610		my $f;
4611
4612		open($f, '>', $newfile)
4613		    or die "$P: Can't open $newfile for write\n";
4614		foreach my $fixed_line (@fixed) {
4615			$linecount++;
4616			if ($file) {
4617				if ($linecount > 3) {
4618					$fixed_line =~ s/^\+//;
4619					print $f $fixed_line. "\n";
4620				}
4621			} else {
4622				print $f $fixed_line . "\n";
4623			}
4624		}
4625		close($f);
4626
4627		if (!$quiet) {
4628			print << "EOM";
4629Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
4630
4631Do _NOT_ trust the results written to this file.
4632Do _NOT_ submit these changes without inspecting them for correctness.
4633
4634This EXPERIMENTAL file is simply a convenience to help rewrite patches.
4635No warranties, expressed or implied...
4636
4637EOM
4638		}
4639	}
4640
4641	if ($clean == 1 && $quiet == 0) {
4642		print "$vname has no obvious style problems and is ready for submission.\n"
4643	}
4644	if ($clean == 0 && $quiet == 0) {
4645		print << "EOM";
4646$vname has style problems, please review.
4647
4648If any of these errors are false positives, please report
4649them to the maintainer, see CHECKPATCH in MAINTAINERS.
4650EOM
4651	}
4652
4653	return $clean;
4654}
4655