checkpatch.pl 170 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 30
my $file = 0;
my $check = 0;
31
my $check_orig = 0;
32 33
my $summary = 1;
my $mailback = 0;
34
my $summary_file = 0;
35
my $show_types = 0;
36
my $fix = 0;
37
my $fix_inplace = 0;
38
my $root;
39
my %debug;
40
my %camelcase = ();
41 42 43
my %use_type = ();
my @use = ();
my %ignore_type = ();
44
my @ignore = ();
45
my $help = 0;
46
my $configuration_file = ".checkpatch.conf";
47
my $max_line_length = 80;
48 49
my $ignore_perl_version = 0;
my $minimum_perl_version = 5.10.0;
50
my $min_conf_desc_length = 4;
51
my $spelling_file = "$D/spelling.txt";
52
my $codespell = 0;
53
my $codespellfile = "/usr/share/codespell/dictionary.txt";
54
my $color = 1;
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

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

When FILE is - read standard input.
EOM

	exit($exitcode);
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
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;
}

135
GetOptions(
136
	'q|quiet+'	=> \$quiet,
137 138 139
	'tree!'		=> \$tree,
	'signoff!'	=> \$chk_signoff,
	'patch!'	=> \$chk_patch,
140
	'emacs!'	=> \$emacs,
141
	'terse!'	=> \$terse,
142
	'showfile!'	=> \$showfile,
143
	'f|file!'	=> \$file,
144 145
	'subjective!'	=> \$check,
	'strict!'	=> \$check,
146
	'ignore=s'	=> \@ignore,
147
	'types=s'	=> \@use,
148
	'show-types!'	=> \$show_types,
149
	'max-line-length=i' => \$max_line_length,
150
	'min-conf-desc-length=i' => \$min_conf_desc_length,
151
	'root=s'	=> \$root,
152 153
	'summary!'	=> \$summary,
	'mailback!'	=> \$mailback,
154
	'summary-file!'	=> \$summary_file,
155
	'fix!'		=> \$fix,
156
	'fix-inplace!'	=> \$fix_inplace,
157
	'ignore-perl-version!' => \$ignore_perl_version,
158
	'debug=s'	=> \%debug,
159
	'test-only=s'	=> \$tst_only,
160 161
	'codespell!'	=> \$codespell,
	'codespellfile=s'	=> \$codespellfile,
162
	'color!'	=> \$color,
163 164 165 166 167
	'h|help'	=> \$help,
	'version'	=> \$help
) or help(1);

help(0) if ($help);
168

169
$fix = 1 if ($fix_inplace);
170
$check_orig = $check;
171

172 173
my $exit = 0;

174 175 176 177 178 179 180
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);
	}
}

181
if ($#ARGV < 0) {
182
	print "$P: no input files\n";
183 184 185
	exit(1);
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
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}++;
	}
}
202

203 204
sub hash_show_words {
	my ($hashRef, $prefix) = @_;
205

206
	if (keys %$hashRef) {
207
		print "\nNOTE: $prefix message types:";
208
		foreach my $word (sort keys %$hashRef) {
209 210
			print " $word";
		}
211
		print "\n";
212
	}
213 214
}

215 216 217
hash_save_array_words(\%ignore_type, \@ignore);
hash_save_array_words(\%use_type, \@use);

218 219
my $dbg_values = 0;
my $dbg_possible = 0;
220
my $dbg_type = 0;
221
my $dbg_attr = 0;
222
for my $key (keys %debug) {
223 224 225
	## no critic
	eval "\${dbg_$key} = '$debug{$key}';";
	die "$@" if ($@);
226 227
}

228 229
my $rpt_cleaners = 0;

230 231 232 233 234
if ($terse) {
	$emacs = 1;
	$quiet++;
}

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

255 256
my $emitted_corrupt = 0;

257 258 259 260
our $Ident	= qr{
			[A-Za-z_][A-Za-z\d_]*
			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
		}x;
261 262 263 264 265 266
our $Storage	= qr{extern|static|asmlinkage};
our $Sparse	= qr{
			__user|
			__kernel|
			__force|
			__iomem|
267
			__pmem|
268 269
			__must_check|
			__init_refok|
270
			__kprobes|
271 272
			__ref|
			__rcu
273
		}x;
274 275 276 277 278
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};
279

280 281
# Notes to $Attribute:
# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
282 283
our $Attribute	= qr{
			const|
284 285 286 287 288 289 290 291 292 293 294 295
			__percpu|
			__nocast|
			__safe|
			__bitwise__|
			__packed__|
			__packed2__|
			__naked|
			__maybe_unused|
			__always_unused|
			__noreturn|
			__used|
			__cold|
296
			__pure|
297 298
			__noclone|
			__deprecated|
299 300
			__read_mostly|
			__kprobes|
301
			$InitAttribute|
302 303
			____cacheline_aligned|
			____cacheline_aligned_in_smp|
304 305
			____cacheline_internodealigned_in_smp|
			__weak
306
		  }x;
307
our $Modifier;
308
our $Inline	= qr{inline|__always_inline|noinline|__inline|__inline__};
309 310 311
our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
our $Lval	= qr{$Ident(?:$Member)*};

312 313 314 315
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?};
316
our $Octal	= qr{0[0-7]+$Int_type?};
317
our $String	= qr{"[X\t]*"};
318 319 320
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]?};
321
our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
322
our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
323
our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
324
our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
325
our $Arithmetic = qr{\+|-|\*|\/|%};
326 327 328
our $Operators	= qr{
			<=|>=|==|!=|
			=>|->|<<|>>|<|>|!|~|
329
			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
330 331
		  }x;

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

334
our $BasicType;
335
our $NonptrType;
336
our $NonptrTypeMisordered;
337
our $NonptrTypeWithAttr;
338
our $Type;
339
our $TypeMisordered;
340
our $Declare;
341
our $DeclareMisordered;
342

343 344
our $NON_ASCII_UTF8	= qr{
	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
345 346 347 348 349 350 351 352
	|  \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;

353 354 355 356 357
our $UTF8	= qr{
	[\x09\x0A\x0D\x20-\x7E]              # ASCII
	| $NON_ASCII_UTF8
}x;

358
our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
359 360 361 362
our $typeOtherOSTypedefs = qr{(?x:
	u_(?:char|short|int|long) |          # bsd
	u(?:nchar|short|int|long)            # sysv
)};
363
our $typeKernelTypedefs = qr{(?x:
364
	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
365 366
	atomic_t
)};
367 368 369 370 371
our $typeTypedefs = qr{(?x:
	$typeC99Typedefs\b|
	$typeOtherOSTypedefs\b|
	$typeKernelTypedefs\b
)};
372

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

375
our $logFunctions = qr{(?x:
376
	printk(?:_ratelimited|_once|)|
377
	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
378
	WARN(?:_RATELIMIT|_ONCE|)|
379
	panic|
380 381
	MODULE_[A-Z_]+|
	seq_vprintf|seq_printf|seq_puts
382 383
)};

384 385 386 387 388 389
our $signature_tags = qr{(?xi:
	Signed-off-by:|
	Acked-by:|
	Tested-by:|
	Reviewed-by:|
	Reported-by:|
390
	Suggested-by:|
391 392 393 394
	To:|
	Cc:
)};

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
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},
);

414 415
our @typeList = (
	qr{void},
416 417 418 419 420 421 422 423 424
	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},
425 426 427 428 429 430 431 432 433
	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},
434
	@typeListMisordered,
435
);
436
our @typeListFile = ();
437 438 439 440 441 442
our @typeListWithAttr = (
	@typeList,
	qr{struct\s+$InitAttribute\s+$Ident},
	qr{union\s+$InitAttribute\s+$Ident},
);

443 444 445
our @modifierList = (
	qr{fastcall},
);
446
our @modifierListFile = ();
447

448 449 450 451 452 453 454 455 456
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],
);

457 458 459 460 461 462 463
#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];
}

464 465 466 467 468 469 470 471
our $mode_perms_world_writable = qr{
	S_IWUGO		|
	S_IWOTH		|
	S_IRWXUGO	|
	S_IALLUGO	|
	0[0-7][0-7][2367]
}x;

472 473
our $allowed_asm_includes = qr{(?x:
	irq|
474 475 476
	memory|
	time|
	reboot
477 478 479
)};
# memory.h: ARM has a custom one

480 481 482 483
# Load common spelling mistakes and build regular expression list.
my $misspellings;
my %spelling_fix;

484 485 486
if (open(my $spelling, '<', $spelling_file)) {
	while (<$spelling>) {
		my $line = $_;
487

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

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

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

496 497 498 499 500
		$spelling_fix{$suspect} = $fix;
	}
	close($spelling);
} else {
	warn "No typos will be found - file '$spelling_file': $!\n";
501 502
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
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;

529
sub build_types {
530 531
	my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
	my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
532
	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
533
	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
534
	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
535 536 537 538
	$BasicType	= qr{
				(?:$typeTypedefs\b)|
				(?:${all}\b)
		}x;
539
	$NonptrType	= qr{
540
			(?:$Modifier\s+|const\s+)*
541
			(?:
542
				(?:typeof|__typeof__)\s*\([^\)]*\)|
543
				(?:$typeTypedefs\b)|
544
				(?:${all}\b)
545
			)
546
			(?:\s+$Modifier|\s+const)*
547
		  }x;
548 549 550 551 552 553 554
	$NonptrTypeMisordered	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:${Misordered}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
555 556 557 558 559 560 561 562 563
	$NonptrTypeWithAttr	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:typeof|__typeof__)\s*\([^\)]*\)|
				(?:$typeTypedefs\b)|
				(?:${allWithAttr}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
564
	$Type	= qr{
565
			$NonptrType
566
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
567
			(?:\s+$Inline|\s+$Modifier)*
568
		  }x;
569 570 571 572 573
	$TypeMisordered	= qr{
			$NonptrTypeMisordered
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
			(?:\s+$Inline|\s+$Modifier)*
		  }x;
574
	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
575
	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
576 577
}
build_types();
578

579
our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
580 581 582 583 584 585

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

589
our $declaration_macros = qr{(?x:
590
	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
591 592 593 594
	(?:$Storage\s+)?LIST_HEAD\s*\(|
	(?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
)};

595 596 597
sub deparenthesize {
	my ($string) = @_;
	return "" if (!defined($string));
598 599 600 601 602 603

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

604
	$string =~ s@\s+@ @g;
605

606 607 608
	return $string;
}

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
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;
627 628 629
		} 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*[;\{]/) {
630 631 632 633 634 635 636 637 638 639
			$camelcase{$1} = 1;
		}
	}
}

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

	my $files;
640 641 642 643
	my $camelcase_cache = "";
	my @include_files = ();

	$camelcase_seeded = 1;
644

645
	if (-e ".git") {
646 647
		my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
		chomp $git_last_include_commit;
648
		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
649
	} else {
650
		my $last_mod_date = 0;
651
		$files = `find $root/include -name "*.h"`;
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
		@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;
671
	}
672

673
	if (-e ".git") {
674 675 676 677
		$files = `git ls-files "include/*.h"`;
		@include_files = split('\n', $files);
	}

678 679 680
	foreach my $file (@include_files) {
		seed_camelcase_file($file);
	}
681

682
	if ($camelcase_cache ne "") {
683
		unlink glob ".checkpatch-camelcase.*";
684 685
		open(my $camelcase_file, '>', "$camelcase_cache")
		    or warn "$P: Can't write '$camelcase_cache' $!\n";
686 687 688 689 690
		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
			print $camelcase_file ("$_\n");
		}
		close($camelcase_file);
	}
691 692
}

693 694 695 696 697 698 699 700 701
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);

702 703
	return ($id, $desc) if ($#lines < 0);

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
	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);
}

723 724
$chk_signoff = 0 if ($file);

725
my @rawlines = ();
726
my @lines = ();
727
my @fixed = ();
728 729
my @fixed_inserted = ();
my @fixed_deleted = ();
730 731
my $fixlinenr = -1;

732
my $vname;
733
for my $filename (@ARGV) {
734
	my $FILE;
735
	if ($file) {
736
		open($FILE, '-|', "diff -u /dev/null $filename") ||
737
			die "$P: $filename: diff failed - $!\n";
738 739
	} elsif ($filename eq '-') {
		open($FILE, '<&STDIN');
740
	} else {
741
		open($FILE, '<', "$filename") ||
742
			die "$P: $filename: open failed - $!\n";
743
	}
744 745 746 747 748
	if ($filename eq '-') {
		$vname = 'Your patch';
	} else {
		$vname = $filename;
	}
749
	while (<$FILE>) {
750 751 752
		chomp;
		push(@rawlines, $_);
	}
753
	close($FILE);
754 755 756 757 758 759 760

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

761
	if (!process($filename)) {
762 763 764
		$exit = 1;
	}
	@rawlines = ();
765
	@lines = ();
766
	@fixed = ();
767 768
	@fixed_inserted = ();
	@fixed_deleted = ();
769
	$fixlinenr = -1;
770 771 772
	@modifierListFile = ();
	@typeListFile = ();
	build_types();
773 774
}

775
if (!$quiet) {
776 777 778
	hash_show_words(\%use_type, "Used");
	hash_show_words(\%ignore_type, "Ignored");

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

795 796 797
exit($exit);

sub top_of_kernel_tree {
798 799 800 801 802 803 804 805 806 807 808 809
	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;
		}
810
	}
811
	return 1;
812
}
813

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
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;
833
		$name = trim($name);
834 835 836 837 838 839 840 841 842 843 844 845 846 847
		$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 = "";
		}
	}

848
	$name = trim($name);
849
	$name =~ s/^\"|\"$//g;
850
	$address = trim($address);
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	$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;

866
	$name = trim($name);
867
	$name =~ s/^\"|\"$//g;
868
	$address = trim($address);
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883

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

884
sub which {
885
	my ($bin) = @_;
886

887 888 889 890
	foreach my $path (split(/:/, $ENV{PATH})) {
		if (-e "$path/$bin") {
			return "$path/$bin";
		}
891 892
	}

893
	return "";
894 895
}

896 897 898 899 900 901 902 903 904 905 906 907
sub which_conf {
	my ($conf) = @_;

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

	return "";
}

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
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;
}
928
sub copy_spacing {
929
	(my $res = shift) =~ tr/\t/ /c;
930 931
	return $res;
}
932

933 934 935 936 937 938 939 940 941 942 943 944 945
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));
}

946 947 948 949 950 951 952 953 954 955 956
my $sanitise_quote = '';

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

	if ($in_comment) {
		$sanitise_quote = '*/';
	} else {
		$sanitise_quote = '';
	}
}
957 958 959 960 961 962
sub sanitise_line {
	my ($line) = @_;

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

963
	my $qlen = 0;
964 965
	my $off = 0;
	my $c;
966

967 968 969 970 971 972 973 974 975 976 977 978 979 980
	# 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;
981
		}
982
		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
983 984 985 986
			$sanitise_quote = '';
			substr($res, $off, 2, "$;$;");
			$off++;
			next;
987
		}
988 989 990 991 992 993 994
		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
			$sanitise_quote = '//';

			substr($res, $off, 2, $sanitise_quote);
			$off++;
			next;
		}
995 996 997 998 999 1000 1001

		# 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;
1002
		}
1003 1004 1005 1006
		# Regular quotes.
		if ($c eq "'" || $c eq '"') {
			if ($sanitise_quote eq '') {
				$sanitise_quote = $c;
1007

1008 1009 1010 1011 1012 1013
				substr($res, $off, 1, $c);
				next;
			} elsif ($sanitise_quote eq $c) {
				$sanitise_quote = '';
			}
		}
1014

1015
		#print "c<$c> SQ<$sanitise_quote>\n";
1016 1017
		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
			substr($res, $off, 1, $;);
1018 1019
		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
			substr($res, $off, 1, $;);
1020 1021 1022 1023 1024
		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
			substr($res, $off, 1, 'X');
		} else {
			substr($res, $off, 1, $c);
		}
1025 1026
	}

1027 1028 1029 1030
	if ($sanitise_quote eq '//') {
		$sanitise_quote = '';
	}

1031
	# The pathname on a #include may be surrounded by '<' and '>'.
1032
	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1033 1034 1035 1036
		my $clean = 'X' x length($1);
		$res =~ s@\<.*\>@<$clean>@;

	# The whole of a #error is a string.
1037
	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1038
		my $clean = 'X' x length($1);
1039
		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1040 1041
	}

1042 1043 1044
	return $res;
}

1045 1046 1047
sub get_quoted_string {
	my ($line, $rawline) = @_;

1048
	return "" if ($line !~ m/($String)/g);
1049 1050 1051
	return substr($rawline, $-[0], $+[0] - $-[0]);
}

1052 1053 1054 1055 1056 1057
sub ctx_statement_block {
	my ($linenr, $remain, $off) = @_;
	my $line = $linenr - 1;
	my $blk = '';
	my $soff = $off;
	my $coff = $off - 1;
1058
	my $coff_set = 0;
1059

1060 1061
	my $loff = 0;

1062 1063
	my $type = '';
	my $level = 0;
1064
	my @stack = ();
1065
	my $p;
1066 1067
	my $c;
	my $len = 0;
1068 1069

	my $remainder;
1070
	while (1) {
1071 1072
		@stack = (['', 0]) if ($#stack == -1);

1073
		#warn "CSB: blk<$blk> remain<$remain>\n";
1074 1075 1076 1077
		# If we are about to drop off the end, pull in more
		# context.
		if ($off >= $len) {
			for (; $remain > 0; $line++) {
1078
				last if (!defined $lines[$line]);
1079
				next if ($lines[$line] =~ /^-/);
1080
				$remain--;
1081
				$loff = $len;