All new accounts created on Gitlab now require administrator approval. If you invite any collaborators, please let Flux staff know so they can approve the accounts.

checkpatch.pl 177 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)
Andy Whitcroft's avatar
Andy Whitcroft committed
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 $color = 1;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

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
73
  --showfile                 emit diffed file position, not input file position
74 75 76 77 78 79 80 81 82 83
  -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
84 85
  -f, --file                 treat FILE as regular source file
  --subjective, --strict     enable more subjective tests
86
  --list-types               list the possible message types
87
  --types TYPE(,TYPE2...)    show only these comma separated message types
88
  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
89
  --show-types               show the specific message type in the output
90
  --max-line-length=n        set the maximum line length, if exceeded, warn
91
  --min-conf-desc-length=n   set the min description length, if shorter, warn
92 93 94 95 96 97 98 99 100
  --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
101 102 103 104 105
  --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
106 107 108
  --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
109 110
  --ignore-perl-version      override checking of perl version.  expect
                             runtime errors.
111
  --codespell                Use the codespell dictionary for spelling/typos
112
                             (default:/usr/share/codespell/dictionary.txt)
113
  --codespellfile            Use this codespell dictionary
114
  --color                    Use colors when output is STDOUT (default: on)
115 116 117 118 119 120 121 122
  -h, --help, --version      display this help and exit

When FILE is - read standard input.
EOM

	exit($exitcode);
}

123 124 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
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);
}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
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;
}

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

help(0) if ($help);
215

216 217
list_types(0) if ($list_types);

218
$fix = 1 if ($fix_inplace);
219
$check_orig = $check;
220

221 222
my $exit = 0;

223 224 225 226 227 228 229
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);
	}
}

230
if ($#ARGV < 0) {
231
	print "$P: no input files\n";
232 233 234
	exit(1);
}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
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}++;
	}
}
251

252 253
sub hash_show_words {
	my ($hashRef, $prefix) = @_;
254

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

264 265 266
hash_save_array_words(\%ignore_type, \@ignore);
hash_save_array_words(\%use_type, \@use);

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

277 278
my $rpt_cleaners = 0;

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

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
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);
	}
302 303
}

304 305
my $emitted_corrupt = 0;

306 307 308 309
our $Ident	= qr{
			[A-Za-z_][A-Za-z\d_]*
			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
		}x;
310 311 312 313 314 315
our $Storage	= qr{extern|static|asmlinkage};
our $Sparse	= qr{
			__user|
			__kernel|
			__force|
			__iomem|
316
			__pmem|
317 318
			__must_check|
			__init_refok|
319
			__kprobes|
320
			__ref|
321 322
			__rcu|
			__private
323
		}x;
324 325 326 327 328
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};
329

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

362 363 364 365
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?};
366
our $Octal	= qr{0[0-7]+$Int_type?};
367
our $String	= qr{"[X\t]*"};
368 369 370
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]?};
371
our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
372
our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
373
our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
374
our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
375
our $Arithmetic = qr{\+|-|\*|\/|%};
376 377 378
our $Operators	= qr{
			<=|>=|==|!=|
			=>|->|<<|>>|<|>|!|~|
379
			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
380 381
		  }x;

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

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

393 394
our $NON_ASCII_UTF8	= qr{
	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
395 396 397 398 399 400 401 402
	|  \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;

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

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

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

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

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

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
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},
);

464 465
our @typeList = (
	qr{void},
466 467 468 469 470 471 472 473 474
	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},
475 476 477 478 479 480 481 482 483
	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},
484
	@typeListMisordered,
485
);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

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
)};

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

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

520 521 522 523 524 525 526 527 528
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],
	["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
);

529 530 531 532 533 534 535
#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];
}

536 537 538 539 540 541 542 543
our $mode_perms_world_writable = qr{
	S_IWUGO		|
	S_IWOTH		|
	S_IRWXUGO	|
	S_IALLUGO	|
	0[0-7][0-7][2367]
}x;

544 545
our $allowed_asm_includes = qr{(?x:
	irq|
546 547 548
	memory|
	time|
	reboot
549 550 551
)};
# memory.h: ARM has a custom one

552 553 554 555
# Load common spelling mistakes and build regular expression list.
my $misspellings;
my %spelling_fix;

556 557 558
if (open(my $spelling, '<', $spelling_file)) {
	while (<$spelling>) {
		my $line = $_;
559

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

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

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

568 569 570 571 572
		$spelling_fix{$suspect} = $fix;
	}
	close($spelling);
} else {
	warn "No typos will be found - file '$spelling_file': $!\n";
573 574
}

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
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;

601
sub build_types {
602 603
	my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
	my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
604
	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
605
	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
606
	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
607 608 609 610
	$BasicType	= qr{
				(?:$typeTypedefs\b)|
				(?:${all}\b)
		}x;
611
	$NonptrType	= qr{
612
			(?:$Modifier\s+|const\s+)*
613
			(?:
614
				(?:typeof|__typeof__)\s*\([^\)]*\)|
615
				(?:$typeTypedefs\b)|
616
				(?:${all}\b)
617
			)
618
			(?:\s+$Modifier|\s+const)*
619
		  }x;
620 621 622 623 624 625 626
	$NonptrTypeMisordered	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:${Misordered}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
627 628 629 630 631 632 633 634 635
	$NonptrTypeWithAttr	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:typeof|__typeof__)\s*\([^\)]*\)|
				(?:$typeTypedefs\b)|
				(?:${allWithAttr}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
636
	$Type	= qr{
637
			$NonptrType
638
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
639
			(?:\s+$Inline|\s+$Modifier)*
640
		  }x;
641 642 643 644 645
	$TypeMisordered	= qr{
			$NonptrTypeMisordered
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
			(?:\s+$Inline|\s+$Modifier)*
		  }x;
646
	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
647
	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
648 649
}
build_types();
650

651
our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
652 653 654 655 656 657

# 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))*\))/;
658
our $LvalOrFunc	= qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
659
our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
660

661
our $declaration_macros = qr{(?x:
662
	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
663 664 665 666
	(?:$Storage\s+)?LIST_HEAD\s*\(|
	(?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
)};

667 668 669
sub deparenthesize {
	my ($string) = @_;
	return "" if (!defined($string));
670 671 672 673 674 675

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

676
	$string =~ s@\s+@ @g;
677

678 679 680
	return $string;
}

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
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;
699 700 701
		} 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*[;\{]/) {
702 703 704 705 706 707 708 709 710 711
			$camelcase{$1} = 1;
		}
	}
}

my $camelcase_seeded = 0;
sub seed_camelcase_includes {
	return if ($camelcase_seeded);

	my $files;
712 713 714 715
	my $camelcase_cache = "";
	my @include_files = ();

	$camelcase_seeded = 1;
716

717
	if (-e ".git") {
718 719
		my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
		chomp $git_last_include_commit;
720
		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
721
	} else {
722
		my $last_mod_date = 0;
723
		$files = `find $root/include -name "*.h"`;
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
		@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;
743
	}
744

745
	if (-e ".git") {
746 747 748 749
		$files = `git ls-files "include/*.h"`;
		@include_files = split('\n', $files);
	}

750 751 752
	foreach my $file (@include_files) {
		seed_camelcase_file($file);
	}
753

754
	if ($camelcase_cache ne "") {
755
		unlink glob ".checkpatch-camelcase.*";
756 757
		open(my $camelcase_file, '>', "$camelcase_cache")
		    or warn "$P: Can't write '$camelcase_cache' $!\n";
758 759 760 761 762
		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
			print $camelcase_file ("$_\n");
		}
		close($camelcase_file);
	}
763 764
}

765 766 767 768 769 770 771 772 773
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);

774 775
	return ($id, $desc) if ($#lines < 0);

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
	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);
}

795 796
$chk_signoff = 0 if ($file);

797
my @rawlines = ();
798
my @lines = ();
799
my @fixed = ();
800 801
my @fixed_inserted = ();
my @fixed_deleted = ();
802 803
my $fixlinenr = -1;

804 805 806 807 808 809
# 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 = ();
810
	foreach my $commit_expr (@ARGV) {
811
		my $git_range;
812 813
		if ($commit_expr =~ m/^(.*)-(\d+)$/) {
			$git_range = "-$2 $1";
814 815 816
		} elsif ($commit_expr =~ m/\.\./) {
			$git_range = "$commit_expr";
		} else {
817 818 819 820
			$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)) {
821 822
			$line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
			next if (!defined($1) || !defined($2));
823 824 825 826
			my $sha1 = $1;
			my $subject = $2;
			unshift(@commits, $sha1);
			$git_commits{$sha1} = $subject;
827 828 829 830 831 832
		}
	}
	die "$P: no git commits after extraction!\n" if (@commits == 0);
	@ARGV = @commits;
}

833
my $vname;
834
for my $filename (@ARGV) {
835
	my $FILE;
836 837 838 839
	if ($git) {
		open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
			die "$P: $filename: git format-patch failed - $!\n";
	} elsif ($file) {
840
		open($FILE, '-|', "diff -u /dev/null $filename") ||
841
			die "$P: $filename: diff failed - $!\n";
842 843
	} elsif ($filename eq '-') {
		open($FILE, '<&STDIN');
844
	} else {
845
		open($FILE, '<', "$filename") ||
846
			die "$P: $filename: open failed - $!\n";
847
	}
848 849
	if ($filename eq '-') {
		$vname = 'Your patch';
850
	} elsif ($git) {
851
		$vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
852 853 854
	} else {
		$vname = $filename;
	}
855
	while (<$FILE>) {
856 857 858
		chomp;
		push(@rawlines, $_);
	}
859
	close($FILE);
860 861 862 863 864 865 866

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

867
	if (!process($filename)) {
868 869 870
		$exit = 1;
	}
	@rawlines = ();
871
	@lines = ();
872
	@fixed = ();
873 874
	@fixed_inserted = ();
	@fixed_deleted = ();
875
	$fixlinenr = -1;
876 877 878
	@modifierListFile = ();
	@typeListFile = ();
	build_types();
879 880
}

881
if (!$quiet) {
882 883 884
	hash_show_words(\%use_type, "Used");
	hash_show_words(\%ignore_type, "Ignored");

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
	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
	}
}

901 902 903
exit($exit);

sub top_of_kernel_tree {
904 905 906 907 908 909 910 911 912 913 914 915
	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;
		}
916
	}
917
	return 1;
918
}
919

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
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;
939
		$name = trim($name);
940 941 942 943 944 945 946 947 948 949 950 951 952 953
		$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 = "";
		}
	}

954
	$name = trim($name);
955
	$name =~ s/^\"|\"$//g;
956
	$address = trim($address);
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
	$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;

972
	$name = trim($name);
973
	$name =~ s/^\"|\"$//g;
974
	$address = trim($address);
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

	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;
}

990
sub which {
991
	my ($bin) = @_;
992

993 994 995 996
	foreach my $path (split(/:/, $ENV{PATH})) {
		if (-e "$path/$bin") {
			return "$path/$bin";
		}
997 998
	}

999
	return "";
1000 1001
}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
sub which_conf {
	my ($conf) = @_;

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

	return "";
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
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;
}
1034
sub copy_spacing {
1035
	(my $res = shift) =~ tr/\t/ /c;
1036 1037
	return $res;
}
1038

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
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));
}

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
my $sanitise_quote = '';

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

	if ($in_comment) {
		$sanitise_quote = '*/';
	} else {
		$sanitise_quote = '';
	}
}
1063 1064 1065 1066 1067 1068
sub sanitise_line {
	my ($line) = @_;

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

1069
	my $qlen = 0;
1070 1071
	my $off = 0;
	my $c;
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
	# 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;
1087
		}
1088
		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1089 1090 1091 1092
			$sanitise_quote = '';
			substr($res, $off, 2, "$;$;");
			$off++;
			next;
1093
		}
1094 1095 1096 1097 1098 1099 1100
		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
			$sanitise_quote = '//';

			substr($res, $off, 2, $sanitise_quote);
			$off++;
			next;
		}
1101 1102 1103