checkpatch.pl 182 KB
Newer Older
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 7 8
# Licensed under the terms of the GNU GPL License version 2

use strict;
9
use POSIX;
10 11
use File::Basename;
use Cwd 'abs_path';
12
use Term::ANSIColor qw(:constants);
13 14

my $P = $0;
15
my $D = dirname(abs_path($P));
16

17
my $V = '0.32';
18 19 20 21 22 23 24

use Getopt::Long qw(:config no_auto_abbrev);

my $quiet = 0;
my $tree = 1;
my $chk_signoff = 1;
my $chk_patch = 1;
25
my $tst_only;
26
my $emacs = 0;
27
my $terse = 0;
28
my $showfile = 0;
29
my $file = 0;
30
my $git = 0;
31
my %git_commits = ();
32
my $check = 0;
33
my $check_orig = 0;
34 35
my $summary = 1;
my $mailback = 0;
36
my $summary_file = 0;
37
my $show_types = 0;
38
my $list_types = 0;
39
my $fix = 0;
40
my $fix_inplace = 0;
41
my $root;
42
my %debug;
43
my %camelcase = ();
44 45 46
my %use_type = ();
my @use = ();
my %ignore_type = ();
47
my @ignore = ();
48
my $help = 0;
49
my $configuration_file = ".checkpatch.conf";
50
my $max_line_length = 80;
51 52
my $ignore_perl_version = 0;
my $minimum_perl_version = 5.10.0;
53
my $min_conf_desc_length = 4;
54
my $spelling_file = "$D/spelling.txt";
55
my $codespell = 0;
56
my $codespellfile = "/usr/share/codespell/dictionary.txt";
57
my $conststructsfile = "$D/const_structs.checkpatch";
58
my $color = 1;
59
my $allow_c99_comments = 1;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

sub help {
	my ($exitcode) = @_;

	print << "EOM";
Usage: $P [OPTION]... [FILE]...
Version: $V

Options:
  -q, --quiet                quiet
  --no-tree                  run without a kernel tree
  --no-signoff               do not check for 'Signed-off-by' line
  --patch                    treat FILE as patchfile (default)
  --emacs                    emacs compile window format
  --terse                    one line per report
75
  --showfile                 emit diffed file position, not input file position
76 77 78 79 80 81 82 83 84 85
  -g, --git                  treat FILE as a single commit or git revision range
                             single git commit with:
                               <rev>
                               <rev>^
                               <rev>~n
                             multiple git commits with:
                               <rev1>..<rev2>
                               <rev1>...<rev2>
                               <rev>-<count>
                             git merges are ignored
86 87
  -f, --file                 treat FILE as regular source file
  --subjective, --strict     enable more subjective tests
88
  --list-types               list the possible message types
89
  --types TYPE(,TYPE2...)    show only these comma separated message types
90
  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
91
  --show-types               show the specific message type in the output
92
  --max-line-length=n        set the maximum line length, if exceeded, warn
93
  --min-conf-desc-length=n   set the min description length, if shorter, warn
94 95 96 97 98 99 100 101 102
  --root=PATH                PATH to the kernel tree root
  --no-summary               suppress the per-file summary
  --mailback                 only produce a report in case of warnings/errors
  --summary-file             include the filename in summary
  --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
                             'values', 'possible', 'type', and 'attr' (default
                             is all off)
  --test-only=WORD           report only warnings/errors containing WORD
                             literally
103 104 105 106 107
  --fix                      EXPERIMENTAL - may create horrible results
                             If correctable single-line errors exist, create
                             "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
                             with potential errors corrected to the preferred
                             checkpatch style
108 109 110
  --fix-inplace              EXPERIMENTAL - may create horrible results
                             Is the same as --fix, but overwrites the input
                             file.  It's your fault if there's no backup or git
111 112
  --ignore-perl-version      override checking of perl version.  expect
                             runtime errors.
113
  --codespell                Use the codespell dictionary for spelling/typos
114
                             (default:/usr/share/codespell/dictionary.txt)
115
  --codespellfile            Use this codespell dictionary
116
  --color                    Use colors when output is STDOUT (default: on)
117 118 119 120 121 122 123 124
  -h, --help, --version      display this help and exit

When FILE is - read standard input.
EOM

	exit($exitcode);
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
sub uniq {
	my %seen;
	return grep { !$seen{$_}++ } @_;
}

sub list_types {
	my ($exitcode) = @_;

	my $count = 0;

	local $/ = undef;

	open(my $script, '<', abs_path($P)) or
	    die "$P: Can't read '$P' $!\n";

	my $text = <$script>;
	close($script);

	my @types = ();
	for ($text =~ /\b(?:(?:CHK|WARN|ERROR)\s*\(\s*"([^"]+)")/g) {
		push (@types, $_);
	}
	@types = sort(uniq(@types));
	print("#\tMessage type\n\n");
	foreach my $type (@types) {
		print(++$count . "\t" . $type . "\n");
	}

	exit($exitcode);
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
my $conf = which_conf($configuration_file);
if (-f $conf) {
	my @conf_args;
	open(my $conffile, '<', "$conf")
	    or warn "$P: Can't find a readable $configuration_file file $!\n";

	while (<$conffile>) {
		my $line = $_;

		$line =~ s/\s*\n?$//g;
		$line =~ s/^\s*//g;
		$line =~ s/\s+/ /g;

		next if ($line =~ m/^\s*#/);
		next if ($line =~ m/^\s*$/);

		my @words = split(" ", $line);
		foreach my $word (@words) {
			last if ($word =~ m/^#/);
			push (@conf_args, $word);
		}
	}
	close($conffile);
	unshift(@ARGV, @conf_args) if @conf_args;
}

182
GetOptions(
183
	'q|quiet+'	=> \$quiet,
184 185 186
	'tree!'		=> \$tree,
	'signoff!'	=> \$chk_signoff,
	'patch!'	=> \$chk_patch,
187
	'emacs!'	=> \$emacs,
188
	'terse!'	=> \$terse,
189
	'showfile!'	=> \$showfile,
190
	'f|file!'	=> \$file,
191
	'g|git!'	=> \$git,
192 193
	'subjective!'	=> \$check,
	'strict!'	=> \$check,
194
	'ignore=s'	=> \@ignore,
195
	'types=s'	=> \@use,
196
	'show-types!'	=> \$show_types,
197
	'list-types!'	=> \$list_types,
198
	'max-line-length=i' => \$max_line_length,
199
	'min-conf-desc-length=i' => \$min_conf_desc_length,
200
	'root=s'	=> \$root,
201 202
	'summary!'	=> \$summary,
	'mailback!'	=> \$mailback,
203
	'summary-file!'	=> \$summary_file,
204
	'fix!'		=> \$fix,
205
	'fix-inplace!'	=> \$fix_inplace,
206
	'ignore-perl-version!' => \$ignore_perl_version,
207
	'debug=s'	=> \%debug,
208
	'test-only=s'	=> \$tst_only,
209 210
	'codespell!'	=> \$codespell,
	'codespellfile=s'	=> \$codespellfile,
211
	'color!'	=> \$color,
212 213 214 215 216
	'h|help'	=> \$help,
	'version'	=> \$help
) or help(1);

help(0) if ($help);
217

218 219
list_types(0) if ($list_types);

220
$fix = 1 if ($fix_inplace);
221
$check_orig = $check;
222

223 224
my $exit = 0;

225 226 227 228 229 230 231
if ($^V && $^V lt $minimum_perl_version) {
	printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
	if (!$ignore_perl_version) {
		exit(1);
	}
}

232
#if no filenames are given, push '-' to read patch from stdin
233
if ($#ARGV < 0) {
234
	push(@ARGV, '-');
235 236
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
sub hash_save_array_words {
	my ($hashRef, $arrayRef) = @_;

	my @array = split(/,/, join(',', @$arrayRef));
	foreach my $word (@array) {
		$word =~ s/\s*\n?$//g;
		$word =~ s/^\s*//g;
		$word =~ s/\s+/ /g;
		$word =~ tr/[a-z]/[A-Z]/;

		next if ($word =~ m/^\s*#/);
		next if ($word =~ m/^\s*$/);

		$hashRef->{$word}++;
	}
}
253

254 255
sub hash_show_words {
	my ($hashRef, $prefix) = @_;
256

257
	if (keys %$hashRef) {
258
		print "\nNOTE: $prefix message types:";
259
		foreach my $word (sort keys %$hashRef) {
260 261
			print " $word";
		}
262
		print "\n";
263
	}
264 265
}

266 267 268
hash_save_array_words(\%ignore_type, \@ignore);
hash_save_array_words(\%use_type, \@use);

269 270
my $dbg_values = 0;
my $dbg_possible = 0;
271
my $dbg_type = 0;
272
my $dbg_attr = 0;
273
for my $key (keys %debug) {
274 275 276
	## no critic
	eval "\${dbg_$key} = '$debug{$key}';";
	die "$@" if ($@);
277 278
}

279 280
my $rpt_cleaners = 0;

281 282 283 284 285
if ($terse) {
	$emacs = 1;
	$quiet++;
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
if ($tree) {
	if (defined $root) {
		if (!top_of_kernel_tree($root)) {
			die "$P: $root: --root does not point at a valid tree\n";
		}
	} else {
		if (top_of_kernel_tree('.')) {
			$root = '.';
		} elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
						top_of_kernel_tree($1)) {
			$root = $1;
		}
	}

	if (!defined $root) {
		print "Must be run from the top-level dir. of a kernel tree\n";
		exit(2);
	}
304 305
}

306 307
my $emitted_corrupt = 0;

308 309 310 311
our $Ident	= qr{
			[A-Za-z_][A-Za-z\d_]*
			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
		}x;
312 313 314 315 316 317 318 319
our $Storage	= qr{extern|static|asmlinkage};
our $Sparse	= qr{
			__user|
			__kernel|
			__force|
			__iomem|
			__must_check|
			__init_refok|
320
			__kprobes|
321
			__ref|
322 323
			__rcu|
			__private
324
		}x;
325 326 327 328 329
our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
330

331 332
# Notes to $Attribute:
# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
333 334
our $Attribute	= qr{
			const|
335 336 337
			__percpu|
			__nocast|
			__safe|
338
			__bitwise|
339 340 341 342 343 344 345 346
			__packed__|
			__packed2__|
			__naked|
			__maybe_unused|
			__always_unused|
			__noreturn|
			__used|
			__cold|
347
			__pure|
348 349
			__noclone|
			__deprecated|
350 351
			__read_mostly|
			__kprobes|
352
			$InitAttribute|
353 354
			____cacheline_aligned|
			____cacheline_aligned_in_smp|
355 356
			____cacheline_internodealigned_in_smp|
			__weak
357
		  }x;
358
our $Modifier;
359
our $Inline	= qr{inline|__always_inline|noinline|__inline|__inline__};
360 361 362
our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
our $Lval	= qr{$Ident(?:$Member)*};

363 364 365 366
our $Int_type	= qr{(?i)llu|ull|ll|lu|ul|l|u};
our $Binary	= qr{(?i)0b[01]+$Int_type?};
our $Hex	= qr{(?i)0x[0-9a-f]+$Int_type?};
our $Int	= qr{[0-9]+$Int_type?};
367
our $Octal	= qr{0[0-7]+$Int_type?};
368
our $String	= qr{"[X\t]*"};
369 370 371
our $Float_hex	= qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
our $Float_dec	= qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
our $Float_int	= qr{(?i)[0-9]+e-?[0-9]+[fl]?};
372
our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
373
our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
374
our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
375
our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
376
our $Arithmetic = qr{\+|-|\*|\/|%};
377 378 379
our $Operators	= qr{
			<=|>=|==|!=|
			=>|->|<<|>>|<|>|!|~|
380
			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
381 382
		  }x;

383 384
our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;

385
our $BasicType;
386
our $NonptrType;
387
our $NonptrTypeMisordered;
388
our $NonptrTypeWithAttr;
389
our $Type;
390
our $TypeMisordered;
391
our $Declare;
392
our $DeclareMisordered;
393

394 395
our $NON_ASCII_UTF8	= qr{
	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
396 397 398 399 400 401 402 403
	|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
	|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
	|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
	| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
	|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
}x;

404 405 406 407 408
our $UTF8	= qr{
	[\x09\x0A\x0D\x20-\x7E]              # ASCII
	| $NON_ASCII_UTF8
}x;

409
our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
410 411 412 413
our $typeOtherOSTypedefs = qr{(?x:
	u_(?:char|short|int|long) |          # bsd
	u(?:nchar|short|int|long)            # sysv
)};
414
our $typeKernelTypedefs = qr{(?x:
415
	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
416 417
	atomic_t
)};
418 419 420 421 422
our $typeTypedefs = qr{(?x:
	$typeC99Typedefs\b|
	$typeOtherOSTypedefs\b|
	$typeKernelTypedefs\b
)};
423

424 425
our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};

426
our $logFunctions = qr{(?x:
427
	printk(?:_ratelimited|_once|)|
428
	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
429
	WARN(?:_RATELIMIT|_ONCE|)|
430
	panic|
431 432
	MODULE_[A-Z_]+|
	seq_vprintf|seq_printf|seq_puts
433 434
)};

435 436 437 438 439 440
our $signature_tags = qr{(?xi:
	Signed-off-by:|
	Acked-by:|
	Tested-by:|
	Reviewed-by:|
	Reported-by:|
441
	Suggested-by:|
442 443 444 445
	To:|
	Cc:
)};

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
our @typeListMisordered = (
	qr{char\s+(?:un)?signed},
	qr{int\s+(?:(?:un)?signed\s+)?short\s},
	qr{int\s+short(?:\s+(?:un)?signed)},
	qr{short\s+int(?:\s+(?:un)?signed)},
	qr{(?:un)?signed\s+int\s+short},
	qr{short\s+(?:un)?signed},
	qr{long\s+int\s+(?:un)?signed},
	qr{int\s+long\s+(?:un)?signed},
	qr{long\s+(?:un)?signed\s+int},
	qr{int\s+(?:un)?signed\s+long},
	qr{int\s+(?:un)?signed},
	qr{int\s+long\s+long\s+(?:un)?signed},
	qr{long\s+long\s+int\s+(?:un)?signed},
	qr{long\s+long\s+(?:un)?signed\s+int},
	qr{long\s+long\s+(?:un)?signed},
	qr{long\s+(?:un)?signed},
);

465 466
our @typeList = (
	qr{void},
467 468 469 470 471 472 473 474 475
	qr{(?:(?:un)?signed\s+)?char},
	qr{(?:(?:un)?signed\s+)?short\s+int},
	qr{(?:(?:un)?signed\s+)?short},
	qr{(?:(?:un)?signed\s+)?int},
	qr{(?:(?:un)?signed\s+)?long\s+int},
	qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
	qr{(?:(?:un)?signed\s+)?long\s+long},
	qr{(?:(?:un)?signed\s+)?long},
	qr{(?:un)?signed},
476 477 478 479 480 481 482 483 484
	qr{float},
	qr{double},
	qr{bool},
	qr{struct\s+$Ident},
	qr{union\s+$Ident},
	qr{enum\s+$Ident},
	qr{${Ident}_t},
	qr{${Ident}_handler},
	qr{${Ident}_handler_fn},
485
	@typeListMisordered,
486
);
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

our $C90_int_types = qr{(?x:
	long\s+long\s+int\s+(?:un)?signed|
	long\s+long\s+(?:un)?signed\s+int|
	long\s+long\s+(?:un)?signed|
	(?:(?:un)?signed\s+)?long\s+long\s+int|
	(?:(?:un)?signed\s+)?long\s+long|
	int\s+long\s+long\s+(?:un)?signed|
	int\s+(?:(?:un)?signed\s+)?long\s+long|

	long\s+int\s+(?:un)?signed|
	long\s+(?:un)?signed\s+int|
	long\s+(?:un)?signed|
	(?:(?:un)?signed\s+)?long\s+int|
	(?:(?:un)?signed\s+)?long|
	int\s+long\s+(?:un)?signed|
	int\s+(?:(?:un)?signed\s+)?long|

	int\s+(?:un)?signed|
	(?:(?:un)?signed\s+)?int
)};

509
our @typeListFile = ();
510 511 512 513 514 515
our @typeListWithAttr = (
	@typeList,
	qr{struct\s+$InitAttribute\s+$Ident},
	qr{union\s+$InitAttribute\s+$Ident},
);

516 517 518
our @modifierList = (
	qr{fastcall},
);
519
our @modifierListFile = ();
520

521 522 523 524 525 526
our @mode_permission_funcs = (
	["module_param", 3],
	["module_param_(?:array|named|string)", 4],
	["module_param_array_named", 5],
	["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
	["proc_create(?:_data|)", 2],
527 528 529 530 531
	["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
	["IIO_DEV_ATTR_[A-Z_]+", 1],
	["SENSOR_(?:DEVICE_|)ATTR_2", 2],
	["SENSOR_TEMPLATE(?:_2|)", 3],
	["__ATTR", 2],
532 533
);

534 535 536 537 538 539 540
#Create a search pattern for all these functions to speed up a loop below
our $mode_perms_search = "";
foreach my $entry (@mode_permission_funcs) {
	$mode_perms_search .= '|' if ($mode_perms_search ne "");
	$mode_perms_search .= $entry->[0];
}

541 542 543 544 545 546 547 548
our $mode_perms_world_writable = qr{
	S_IWUGO		|
	S_IWOTH		|
	S_IRWXUGO	|
	S_IALLUGO	|
	0[0-7][0-7][2367]
}x;

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
our %mode_permission_string_types = (
	"S_IRWXU" => 0700,
	"S_IRUSR" => 0400,
	"S_IWUSR" => 0200,
	"S_IXUSR" => 0100,
	"S_IRWXG" => 0070,
	"S_IRGRP" => 0040,
	"S_IWGRP" => 0020,
	"S_IXGRP" => 0010,
	"S_IRWXO" => 0007,
	"S_IROTH" => 0004,
	"S_IWOTH" => 0002,
	"S_IXOTH" => 0001,
	"S_IRWXUGO" => 0777,
	"S_IRUGO" => 0444,
	"S_IWUGO" => 0222,
	"S_IXUGO" => 0111,
);

#Create a search pattern for all these strings to speed up a loop below
our $mode_perms_string_search = "";
foreach my $entry (keys %mode_permission_string_types) {
	$mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
	$mode_perms_string_search .= $entry;
}

575 576
our $allowed_asm_includes = qr{(?x:
	irq|
577 578 579
	memory|
	time|
	reboot
580 581 582
)};
# memory.h: ARM has a custom one

583 584 585 586
# Load common spelling mistakes and build regular expression list.
my $misspellings;
my %spelling_fix;

587 588 589
if (open(my $spelling, '<', $spelling_file)) {
	while (<$spelling>) {
		my $line = $_;
590

591 592
		$line =~ s/\s*\n?$//g;
		$line =~ s/^\s*//g;
593

594 595 596 597
		next if ($line =~ m/^\s*#/);
		next if ($line =~ m/^\s*$/);

		my ($suspect, $fix) = split(/\|\|/, $line);
598

599 600 601 602 603
		$spelling_fix{$suspect} = $fix;
	}
	close($spelling);
} else {
	warn "No typos will be found - file '$spelling_file': $!\n";
604 605
}

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
if ($codespell) {
	if (open(my $spelling, '<', $codespellfile)) {
		while (<$spelling>) {
			my $line = $_;

			$line =~ s/\s*\n?$//g;
			$line =~ s/^\s*//g;

			next if ($line =~ m/^\s*#/);
			next if ($line =~ m/^\s*$/);
			next if ($line =~ m/, disabled/i);

			$line =~ s/,.*$//;

			my ($suspect, $fix) = split(/->/, $line);

			$spelling_fix{$suspect} = $fix;
		}
		close($spelling);
	} else {
		warn "No codespell typos will be found - file '$codespellfile': $!\n";
	}
}

$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
my $const_structs = "";
if (open(my $conststructs, '<', $conststructsfile)) {
	while (<$conststructs>) {
		my $line = $_;

		$line =~ s/\s*\n?$//g;
		$line =~ s/^\s*//g;

		next if ($line =~ m/^\s*#/);
		next if ($line =~ m/^\s*$/);
		if ($line =~ /\s/) {
			print("$conststructsfile: '$line' invalid - ignored\n");
			next;
		}

		$const_structs .= '|' if ($const_structs ne "");
		$const_structs .= $line;
	}
	close($conststructsfile);
} else {
	warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
}

655
sub build_types {
656 657
	my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
	my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
658
	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
659
	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
660
	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
661 662 663 664
	$BasicType	= qr{
				(?:$typeTypedefs\b)|
				(?:${all}\b)
		}x;
665
	$NonptrType	= qr{
666
			(?:$Modifier\s+|const\s+)*
667
			(?:
668
				(?:typeof|__typeof__)\s*\([^\)]*\)|
669
				(?:$typeTypedefs\b)|
670
				(?:${all}\b)
671
			)
672
			(?:\s+$Modifier|\s+const)*
673
		  }x;
674 675 676 677 678 679 680
	$NonptrTypeMisordered	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:${Misordered}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
681 682 683 684 685 686 687 688 689
	$NonptrTypeWithAttr	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:typeof|__typeof__)\s*\([^\)]*\)|
				(?:$typeTypedefs\b)|
				(?:${allWithAttr}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
690
	$Type	= qr{
691
			$NonptrType
692
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
693
			(?:\s+$Inline|\s+$Modifier)*
694
		  }x;
695 696 697 698 699
	$TypeMisordered	= qr{
			$NonptrTypeMisordered
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
			(?:\s+$Inline|\s+$Modifier)*
		  }x;
700
	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
701
	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
702 703
}
build_types();
704

705
our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
706 707 708 709 710 711

# Using $balanced_parens, $LvalOrFunc, or $FuncArg
# requires at least perl version v5.10.0
# Any use must be runtime checked with $^V

our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
712
our $LvalOrFunc	= qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
713
our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
714

715
our $declaration_macros = qr{(?x:
716
	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
717 718 719 720
	(?:$Storage\s+)?LIST_HEAD\s*\(|
	(?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
)};

721 722 723
sub deparenthesize {
	my ($string) = @_;
	return "" if (!defined($string));
724 725 726 727 728 729

	while ($string =~ /^\s*\(.*\)\s*$/) {
		$string =~ s@^\s*\(\s*@@;
		$string =~ s@\s*\)\s*$@@;
	}

730
	$string =~ s@\s+@ @g;
731

732 733 734
	return $string;
}

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
sub seed_camelcase_file {
	my ($file) = @_;

	return if (!(-f $file));

	local $/;

	open(my $include_file, '<', "$file")
	    or warn "$P: Can't read '$file' $!\n";
	my $text = <$include_file>;
	close($include_file);

	my @lines = split('\n', $text);

	foreach my $line (@lines) {
		next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
		if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
			$camelcase{$1} = 1;
753 754 755
		} elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
			$camelcase{$1} = 1;
		} elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
756 757 758 759 760
			$camelcase{$1} = 1;
		}
	}
}

761 762 763
sub is_maintained_obsolete {
	my ($filename) = @_;

764
	return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
765

766
	my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
767 768 769 770

	return $status =~ /obsolete/i;
}

771 772 773 774 775
my $camelcase_seeded = 0;
sub seed_camelcase_includes {
	return if ($camelcase_seeded);

	my $files;
776 777 778 779
	my $camelcase_cache = "";
	my @include_files = ();

	$camelcase_seeded = 1;
780

781
	if (-e ".git") {
782 783
		my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
		chomp $git_last_include_commit;
784
		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
785
	} else {
786
		my $last_mod_date = 0;
787
		$files = `find $root/include -name "*.h"`;
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
		@include_files = split('\n', $files);
		foreach my $file (@include_files) {
			my $date = POSIX::strftime("%Y%m%d%H%M",
						   localtime((stat $file)[9]));
			$last_mod_date = $date if ($last_mod_date < $date);
		}
		$camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
	}

	if ($camelcase_cache ne "" && -f $camelcase_cache) {
		open(my $camelcase_file, '<', "$camelcase_cache")
		    or warn "$P: Can't read '$camelcase_cache' $!\n";
		while (<$camelcase_file>) {
			chomp;
			$camelcase{$_} = 1;
		}
		close($camelcase_file);

		return;
807
	}
808

809
	if (-e ".git") {
810 811 812 813
		$files = `git ls-files "include/*.h"`;
		@include_files = split('\n', $files);
	}

814 815 816
	foreach my $file (@include_files) {
		seed_camelcase_file($file);
	}
817

818
	if ($camelcase_cache ne "") {
819
		unlink glob ".checkpatch-camelcase.*";
820 821
		open(my $camelcase_file, '>', "$camelcase_cache")
		    or warn "$P: Can't write '$camelcase_cache' $!\n";
822 823 824 825 826
		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
			print $camelcase_file ("$_\n");
		}
		close($camelcase_file);
	}
827 828
}

829 830 831 832 833 834 835 836 837
sub git_commit_info {
	my ($commit, $id, $desc) = @_;

	return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));

	my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
	$output =~ s/^\s*//gm;
	my @lines = split("\n", $output);

838 839
	return ($id, $desc) if ($#lines < 0);

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
	if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
# Maybe one day convert this block of bash into something that returns
# all matching commit ids, but it's very slow...
#
#		echo "checking commits $1..."
#		git rev-list --remotes | grep -i "^$1" |
#		while read line ; do
#		    git log --format='%H %s' -1 $line |
#		    echo "commit $(cut -c 1-12,41-)"
#		done
	} elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
	} else {
		$id = substr($lines[0], 0, 12);
		$desc = substr($lines[0], 41);
	}

	return ($id, $desc);
}

859 860
$chk_signoff = 0 if ($file);

861
my @rawlines = ();
862
my @lines = ();
863
my @fixed = ();
864 865
my @fixed_inserted = ();
my @fixed_deleted = ();
866 867
my $fixlinenr = -1;

868 869 870 871 872 873
# If input is git commits, extract all commits from the commit expressions.
# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
die "$P: No git repository found\n" if ($git && !-e ".git");

if ($git) {
	my @commits = ();
874
	foreach my $commit_expr (@ARGV) {
875
		my $git_range;
876 877
		if ($commit_expr =~ m/^(.*)-(\d+)$/) {
			$git_range = "-$2 $1";
878 879 880
		} elsif ($commit_expr =~ m/\.\./) {
			$git_range = "$commit_expr";
		} else {
881 882 883 884
			$git_range = "-1 $commit_expr";
		}
		my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
		foreach my $line (split(/\n/, $lines)) {
885 886
			$line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
			next if (!defined($1) || !defined($2));
887 888 889 890
			my $sha1 = $1;
			my $subject = $2;
			unshift(@commits, $sha1);
			$git_commits{$sha1} = $subject;
891 892 893 894 895 896
		}
	}
	die "$P: no git commits after extraction!\n" if (@commits == 0);
	@ARGV = @commits;
}

897
my $vname;
898
for my $filename (@ARGV) {
899
	my $FILE;
900 901 902 903
	if ($git) {
		open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
			die "$P: $filename: git format-patch failed - $!\n";
	} elsif ($file) {
904
		open($FILE, '-|', "diff -u /dev/null $filename") ||
905
			die "$P: $filename: diff failed - $!\n";
906 907
	} elsif ($filename eq '-') {
		open($FILE, '<&STDIN');
908
	} else {
909
		open($FILE, '<', "$filename") ||
910
			die "$P: $filename: open failed - $!\n";
911
	}
912 913
	if ($filename eq '-') {
		$vname = 'Your patch';
914
	} elsif ($git) {
915
		$vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
916 917 918
	} else {
		$vname = $filename;
	}
919
	while (<$FILE>) {
920 921 922
		chomp;
		push(@rawlines, $_);
	}
923
	close($FILE);
924 925 926 927 928 929 930

	if ($#ARGV > 0 && $quiet == 0) {
		print '-' x length($vname) . "\n";
		print "$vname\n";
		print '-' x length($vname) . "\n";
	}

931
	if (!process($filename)) {
932 933 934
		$exit = 1;
	}
	@rawlines = ();
935
	@lines = ();
936
	@fixed = ();
937 938
	@fixed_inserted = ();
	@fixed_deleted = ();
939
	$fixlinenr = -1;
940 941 942
	@modifierListFile = ();
	@typeListFile = ();
	build_types();
943 944
}

945
if (!$quiet) {
946 947 948
	hash_show_words(\%use_type, "Used");
	hash_show_words(\%ignore_type, "Ignored");

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
	if ($^V lt 5.10.0) {
		print << "EOM"

NOTE: perl $^V is not modern enough to detect all possible issues.
      An upgrade to at least perl v5.10.0 is suggested.
EOM
	}
	if ($exit) {
		print << "EOM"

NOTE: If any of the errors are false positives, please report
      them to the maintainer, see CHECKPATCH in MAINTAINERS.
EOM
	}
}

965 966 967
exit($exit);

sub top_of_kernel_tree {
968 969 970 971 972 973 974 975 976 977 978 979
	my ($root) = @_;

	my @tree_check = (
		"COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
		"README", "Documentation", "arch", "include", "drivers",
		"fs", "init", "ipc", "kernel", "lib", "scripts",
	);

	foreach my $check (@tree_check) {
		if (! -e $root . '/' . $check) {
			return 0;
		}
980
	}
981
	return 1;
982
}
983

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
sub parse_email {
	my ($formatted_email) = @_;

	my $name = "";
	my $address = "";
	my $comment = "";

	if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
		$name = $1;
		$address = $2;
		$comment = $3 if defined $3;
	} elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
		$address = $1;
		$comment = $2 if defined $2;
	} elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
		$address = $1;
		$comment = $2 if defined $2;
		$formatted_email =~ s/$address.*$//;
		$name = $formatted_email;
1003
		$name = trim($name);
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
		$name =~ s/^\"|\"$//g;
		# If there's a name left after stripping spaces and
		# leading quotes, and the address doesn't have both
		# leading and trailing angle brackets, the address
		# is invalid. ie:
		#   "joe smith joe@smith.com" bad
		#   "joe smith <joe@smith.com" bad
		if ($name ne "" && $address !~ /^<[^>]+>$/) {
			$name = "";
			$address = "";
			$comment = "";
		}
	}

1018
	$name = trim($name);
1019
	$name =~ s/^\"|\"$//g;
1020
	$address = trim($address);
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	$address =~ s/^\<|\>$//g;

	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
		$name = "\"$name\"";
	}

	return ($name, $address, $comment);
}

sub format_email {
	my ($name, $address) = @_;

	my $formatted_email;

1036
	$name = trim($name);
1037
	$name =~ s/^\"|\"$//g;
1038
	$address = trim($address);
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
		$name = "\"$name\"";
	}

	if ("$name" eq "") {
		$formatted_email = "$address";
	} else {
		$formatted_email = "$name <$address>";
	}

	return $formatted_email;
}

1054
sub which {
1055
	my ($bin) = @_;
1056

1057 1058 1059 1060
	foreach my $path (split(/:/, $ENV{PATH})) {
		if (-e "$path/$bin") {
			return "$path/$bin";
		}
1061 1062
	}

1063
	return "";
1064 1065
}

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
sub which_conf {
	my ($conf) = @_;

	foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
		if (-e "$path/$conf") {
			return "$path/$conf";
		}
	}

	return "";
}

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
sub expand_tabs {
	my ($str) = @_;

	my $res = '';
	my $n = 0;
	for my $c (split(//, $str)) {
		if ($c eq "\t") {
			$res .= ' ';
			$n++;
			for (; ($n % 8) != 0; $n++) {
				$res .= ' ';
			}
			next;
		}
		$res .= $c;
		$n++;
	}

	return $res;
}
1098
sub copy_spacing {
1099
	(my $res = shift) =~ tr/\t/ /c;
1100 1101
	return $res;
}
1102

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
sub line_stats {
	my ($line) = @_;

	# Drop the diff line leader and expand tabs
	$line =~ s/^.//;
	$line = expand_tabs($line);

	# Pick the indent from the front of the line.
	my ($white) = ($line =~ /^(\s*)/);

	return (length($line), length($white));
}

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
my $sanitise_quote = '';

sub sanitise_line_reset {
	my ($in_comment) = @_;

	if ($in_comment) {
		$sanitise_quote = '*/';
	} else {
		$sanitise_quote = '';
	}
}
1127 1128 1129 1130 1131 1132
sub sanitise_line {
	my ($line) = @_;

	my $res = '';
	my $l = '';

1133
	my $qlen = 0;
1134 1135
	my $off = 0;
	my $c;
1136

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	# Always copy over the diff marker.
	$res = substr($line, 0, 1);

	for ($off = 1; $off < length($line); $off++) {
		$c = substr($line, $off, 1);

		# Comments we are wacking completly including the begin
		# and end, all to $;.
		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
			$sanitise_quote = '*/';

			substr($res, $off, 2, "$;$;");
			$off++;
			next;
1151
		}
1152
		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1153 1154 1155 1156
			$sanitise_quote = '';
			substr($res, $off, 2, "$;$;");
			$off++;
			next;
1157
		}
1158 1159 1160 1161 1162 1163 1164
		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
			$sanitise_quote = '//';

			substr($res, $off, 2, $sanitise_quote);
			$off++;
			next;
		}
1165 1166 1167 1168 1169 1170 1171

		# A \ in a string means ignore the next character.
		if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
		    $c eq "\\") {
			substr($res, $off, 2, 'XX');
			$off++;
			next;
1172
		}
1173 1174 1175 1176
		# Regular quotes.
		if ($c eq "'" || $c eq '"') {
			if ($sanitise_quote eq '') {
				$sanitise_quote = $c;
1177

1178 1179 1180 1181 1182 1183
				substr($res, $off, 1, $c);
				next;
			} elsif ($sanitise_quote eq $c) {
				$sanitise_quote = '';
			}
		}
1184

1185
		#print "c<$c> SQ<$sanitise_quote>\n";
1186 1187
		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
			substr($res, $off, 1, $;);
1188 1189
		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
			substr($res, $off, 1, $;);
1190 1191 1192 1193 1194
		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
			substr($res, $off, 1, 'X');
		} else {
			substr($res, $off, 1, $c);
		}
1195 1196
	}

1197 1198 1199 1200
	if ($sanitise_quote eq '//') {
		$sanitise_quote = '';
	}

1201
	# The pathname on a #include may be surrounded by '<' and '>'.
1202
	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1203 1204 1205 1206
		my $clean = 'X' x length($1);
		$res =~ s@\<.*\>@<$clean>@;

	# The whole of a #error is a string.
1207
	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1208
		my $clean = 'X' x length($1);
1209
		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1210 1211
	}

1212 1213 1214 1215 1216
	if ($allow_c99_comments && $res =~ m@(//.*$)@) {
		my $match = $1;
		$res =~ s/\Q$match\E/"$;" x length($match)/e;
	}

1217 1218 1219
	return $res;
}

1220 1221 1222
sub get_quoted_string {
	my ($line, $rawline) = @_;

1223
	return "" if ($line !~ m/($String)/g);
1224 1225 1226
	return substr($rawline, $-[0], $+[0] - $-[0]);
}

1227 1228 1229 1230 1231 1232
sub ctx_statement_block {
	my ($linenr, $remain, $off) = @_;
	my $line = $linenr - 1;
	my $blk = '';
	my $soff = $off;
	my $coff = $off - 1;
1233
	my $coff_set = 0;
1234

1235 1236
	my $loff = 0;

1237 1238
	my $type = '';
	my $level = 0;
1239
	my @stack = ();
1240
	my $p;
1241 1242
	my $c;
	my $len = 0;
1243 1244

	my $remainder;
1245
	while (1) {
1246 1247
		@stack = (['', 0]) if ($#stack == -1);

1248
		#warn "CSB: blk<$blk> remain<$remain>\n";
1249 1250 1251 1252
		# If we are about to drop off the end, pull in more
		# context.
		if ($off >= $len) {
			for (; $remain > 0; $line++) {
1253
				last if (!defined $lines[$line]);
1254
				next if ($lines[$line] =~ /^-/);
1255
				$remain--;
1256
				$loff = $len;