checkpatch.pl 155 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
13

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

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

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

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

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
  -f, --file                 treat FILE as regular source file
  --subjective, --strict     enable more subjective tests
67
  --types TYPE(,TYPE2...)    show only these comma separated message types
68
  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
69
  --max-line-length=n        set the maximum line length, if exceeded, warn
70
  --min-conf-desc-length=n   set the min description length, if shorter, warn
71
  --show-types               show the message "types" in the output
72
73
74
75
76
77
78
79
80
  --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
81
82
83
84
85
  --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
86
87
88
  --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
89
90
  --ignore-perl-version      override checking of perl version.  expect
                             runtime errors.
91
92
93
94
95
96
97
98
  -h, --help, --version      display this help and exit

When FILE is - read standard input.
EOM

	exit($exitcode);
}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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;
}

125
GetOptions(
126
	'q|quiet+'	=> \$quiet,
127
128
129
	'tree!'		=> \$tree,
	'signoff!'	=> \$chk_signoff,
	'patch!'	=> \$chk_patch,
130
	'emacs!'	=> \$emacs,
131
	'terse!'	=> \$terse,
132
	'f|file!'	=> \$file,
133
134
	'subjective!'	=> \$check,
	'strict!'	=> \$check,
135
	'ignore=s'	=> \@ignore,
136
	'types=s'	=> \@use,
137
	'show-types!'	=> \$show_types,
138
	'max-line-length=i' => \$max_line_length,
139
	'min-conf-desc-length=i' => \$min_conf_desc_length,
140
	'root=s'	=> \$root,
141
142
	'summary!'	=> \$summary,
	'mailback!'	=> \$mailback,
143
	'summary-file!'	=> \$summary_file,
144
	'fix!'		=> \$fix,
145
	'fix-inplace!'	=> \$fix_inplace,
146
	'ignore-perl-version!' => \$ignore_perl_version,
147
	'debug=s'	=> \%debug,
148
	'test-only=s'	=> \$tst_only,
149
150
151
152
153
	'h|help'	=> \$help,
	'version'	=> \$help
) or help(1);

help(0) if ($help);
154

155
$fix = 1 if ($fix_inplace);
156
$check_orig = $check;
157

158
159
my $exit = 0;

160
161
162
163
164
165
166
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);
	}
}

167
if ($#ARGV < 0) {
168
	print "$P: no input files\n";
169
170
171
	exit(1);
}

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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}++;
	}
}
188

189
190
sub hash_show_words {
	my ($hashRef, $prefix) = @_;
191

192
	if ($quiet == 0 && keys %$hashRef) {
193
		print "NOTE: $prefix message types:";
194
		foreach my $word (sort keys %$hashRef) {
195
196
197
198
			print " $word";
		}
		print "\n\n";
	}
199
200
}

201
202
203
hash_save_array_words(\%ignore_type, \@ignore);
hash_save_array_words(\%use_type, \@use);

204
205
my $dbg_values = 0;
my $dbg_possible = 0;
206
my $dbg_type = 0;
207
my $dbg_attr = 0;
208
for my $key (keys %debug) {
209
210
211
	## no critic
	eval "\${dbg_$key} = '$debug{$key}';";
	die "$@" if ($@);
212
213
}

214
215
my $rpt_cleaners = 0;

216
217
218
219
220
if ($terse) {
	$emacs = 1;
	$quiet++;
}

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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);
	}
239
240
}

241
242
my $emitted_corrupt = 0;

243
244
245
246
our $Ident	= qr{
			[A-Za-z_][A-Za-z\d_]*
			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
		}x;
247
248
249
250
251
252
253
254
our $Storage	= qr{extern|static|asmlinkage};
our $Sparse	= qr{
			__user|
			__kernel|
			__force|
			__iomem|
			__must_check|
			__init_refok|
255
			__kprobes|
256
257
			__ref|
			__rcu
258
		}x;
259
260
261
262
263
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};
264

265
266
# Notes to $Attribute:
# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
267
268
our $Attribute	= qr{
			const|
269
270
271
272
273
274
275
276
277
278
279
280
			__percpu|
			__nocast|
			__safe|
			__bitwise__|
			__packed__|
			__packed2__|
			__naked|
			__maybe_unused|
			__always_unused|
			__noreturn|
			__used|
			__cold|
281
			__pure|
282
283
			__noclone|
			__deprecated|
284
285
			__read_mostly|
			__kprobes|
286
			$InitAttribute|
287
288
			____cacheline_aligned|
			____cacheline_aligned_in_smp|
289
290
			____cacheline_internodealigned_in_smp|
			__weak
291
		  }x;
292
our $Modifier;
293
our $Inline	= qr{inline|__always_inline|noinline|__inline|__inline__};
294
295
296
our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
our $Lval	= qr{$Ident(?:$Member)*};

297
298
299
300
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?};
301
our $Octal	= qr{0[0-7]+$Int_type?};
302
our $String	= qr{"[X\t]*"};
303
304
305
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]?};
306
our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
307
our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
308
our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
309
our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
310
our $Arithmetic = qr{\+|-|\*|\/|%};
311
312
313
our $Operators	= qr{
			<=|>=|==|!=|
			=>|->|<<|>>|<|>|!|~|
314
			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
315
316
		  }x;

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

319
our $NonptrType;
320
our $NonptrTypeMisordered;
321
our $NonptrTypeWithAttr;
322
our $Type;
323
our $TypeMisordered;
324
our $Declare;
325
our $DeclareMisordered;
326

327
328
our $NON_ASCII_UTF8	= qr{
	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
329
330
331
332
333
334
335
336
	|  \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;

337
338
339
340
341
our $UTF8	= qr{
	[\x09\x0A\x0D\x20-\x7E]              # ASCII
	| $NON_ASCII_UTF8
}x;

342
343
344
345
346
our $typeOtherOSTypedefs = qr{(?x:
	u_(?:char|short|int|long) |          # bsd
	u(?:nchar|short|int|long)            # sysv
)};

347
our $typeTypedefs = qr{(?x:
348
	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
349
350
351
	atomic_t
)};

352
our $logFunctions = qr{(?x:
353
	printk(?:_ratelimited|_once|)|
354
	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
355
	WARN(?:_RATELIMIT|_ONCE|)|
356
	panic|
357
358
	MODULE_[A-Z_]+|
	seq_vprintf|seq_printf|seq_puts
359
360
)};

361
362
363
364
365
366
our $signature_tags = qr{(?xi:
	Signed-off-by:|
	Acked-by:|
	Tested-by:|
	Reviewed-by:|
	Reported-by:|
367
	Suggested-by:|
368
369
370
371
	To:|
	Cc:
)};

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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},
);

391
392
our @typeList = (
	qr{void},
393
394
395
396
397
398
399
400
401
	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},
402
403
404
405
406
407
408
409
410
	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},
411
	@typeListMisordered,
412
);
413
414
415
416
417
418
our @typeListWithAttr = (
	@typeList,
	qr{struct\s+$InitAttribute\s+$Ident},
	qr{union\s+$InitAttribute\s+$Ident},
);

419
420
421
our @modifierList = (
	qr{fastcall},
);
422

423
424
425
426
427
428
429
430
431
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],
);

432
433
434
435
436
437
438
#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];
}

439
440
our $allowed_asm_includes = qr{(?x:
	irq|
441
442
443
	memory|
	time|
	reboot
444
445
446
)};
# memory.h: ARM has a custom one

447
448
449
450
# Load common spelling mistakes and build regular expression list.
my $misspellings;
my %spelling_fix;

451
452
453
454
if (open(my $spelling, '<', $spelling_file)) {
	my @spelling_list;
	while (<$spelling>) {
		my $line = $_;
455

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

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

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

464
465
466
467
468
469
470
		push(@spelling_list, $suspect);
		$spelling_fix{$suspect} = $fix;
	}
	close($spelling);
	$misspellings = join("|", @spelling_list);
} else {
	warn "No typos will be found - file '$spelling_file': $!\n";
471
472
}

473
sub build_types {
474
475
	my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
	my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
476
	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
477
	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
478
	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
479
	$NonptrType	= qr{
480
			(?:$Modifier\s+|const\s+)*
481
			(?:
482
				(?:typeof|__typeof__)\s*\([^\)]*\)|
483
				(?:$typeOtherOSTypedefs\b)|
484
				(?:$typeTypedefs\b)|
485
				(?:${all}\b)
486
			)
487
			(?:\s+$Modifier|\s+const)*
488
		  }x;
489
490
491
492
493
494
495
	$NonptrTypeMisordered	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:${Misordered}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
496
497
498
499
500
	$NonptrTypeWithAttr	= qr{
			(?:$Modifier\s+|const\s+)*
			(?:
				(?:typeof|__typeof__)\s*\([^\)]*\)|
				(?:$typeTypedefs\b)|
501
				(?:$typeOtherOSTypedefs\b)|
502
503
504
505
				(?:${allWithAttr}\b)
			)
			(?:\s+$Modifier|\s+const)*
		  }x;
506
	$Type	= qr{
507
			$NonptrType
508
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
509
			(?:\s+$Inline|\s+$Modifier)*
510
		  }x;
511
512
513
514
515
	$TypeMisordered	= qr{
			$NonptrTypeMisordered
			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
			(?:\s+$Inline|\s+$Modifier)*
		  }x;
516
	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
517
	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
518
519
}
build_types();
520

521
our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
522
523
524
525
526
527

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

531
532
533
534
535
536
our $declaration_macros = qr{(?x:
	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
	(?:$Storage\s+)?LIST_HEAD\s*\(|
	(?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
)};

537
538
539
sub deparenthesize {
	my ($string) = @_;
	return "" if (!defined($string));
540
541
542
543
544
545

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

546
	$string =~ s@\s+@ @g;
547

548
549
550
	return $string;
}

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
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;
569
570
571
		} 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*[;\{]/) {
572
573
574
575
576
577
578
579
580
581
			$camelcase{$1} = 1;
		}
	}
}

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

	my $files;
582
583
584
585
	my $camelcase_cache = "";
	my @include_files = ();

	$camelcase_seeded = 1;
586

587
	if (-e ".git") {
588
589
		my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
		chomp $git_last_include_commit;
590
		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
591
	} else {
592
		my $last_mod_date = 0;
593
		$files = `find $root/include -name "*.h"`;
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
		@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;
613
	}
614

615
	if (-e ".git") {
616
617
618
619
		$files = `git ls-files "include/*.h"`;
		@include_files = split('\n', $files);
	}

620
621
622
	foreach my $file (@include_files) {
		seed_camelcase_file($file);
	}
623

624
	if ($camelcase_cache ne "") {
625
		unlink glob ".checkpatch-camelcase.*";
626
627
		open(my $camelcase_file, '>', "$camelcase_cache")
		    or warn "$P: Can't write '$camelcase_cache' $!\n";
628
629
630
631
632
		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
			print $camelcase_file ("$_\n");
		}
		close($camelcase_file);
	}
633
634
}

635
636
637
638
639
640
641
642
643
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);

644
645
	return ($id, $desc) if ($#lines < 0);

646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
	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);
}

665
666
$chk_signoff = 0 if ($file);

667
my @rawlines = ();
668
my @lines = ();
669
my @fixed = ();
670
671
my @fixed_inserted = ();
my @fixed_deleted = ();
672
673
my $fixlinenr = -1;

674
my $vname;
675
for my $filename (@ARGV) {
676
	my $FILE;
677
	if ($file) {
678
		open($FILE, '-|', "diff -u /dev/null $filename") ||
679
			die "$P: $filename: diff failed - $!\n";
680
681
	} elsif ($filename eq '-') {
		open($FILE, '<&STDIN');
682
	} else {
683
		open($FILE, '<', "$filename") ||
684
			die "$P: $filename: open failed - $!\n";
685
	}
686
687
688
689
690
	if ($filename eq '-') {
		$vname = 'Your patch';
	} else {
		$vname = $filename;
	}
691
	while (<$FILE>) {
692
693
694
		chomp;
		push(@rawlines, $_);
	}
695
	close($FILE);
696
	if (!process($filename)) {
697
698
699
		$exit = 1;
	}
	@rawlines = ();
700
	@lines = ();
701
	@fixed = ();
702
703
	@fixed_inserted = ();
	@fixed_deleted = ();
704
	$fixlinenr = -1;
705
706
707
708
709
}

exit($exit);

sub top_of_kernel_tree {
710
711
712
713
714
715
716
717
718
719
720
721
	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;
		}
722
	}
723
	return 1;
724
}
725

726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
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;
745
		$name = trim($name);
746
747
748
749
750
751
752
753
754
755
756
757
758
759
		$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 = "";
		}
	}

760
	$name = trim($name);
761
	$name =~ s/^\"|\"$//g;
762
	$address = trim($address);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
	$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;

778
	$name = trim($name);
779
	$name =~ s/^\"|\"$//g;
780
	$address = trim($address);
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795

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

796
sub which {
797
	my ($bin) = @_;
798

799
800
801
802
	foreach my $path (split(/:/, $ENV{PATH})) {
		if (-e "$path/$bin") {
			return "$path/$bin";
		}
803
804
	}

805
	return "";
806
807
}

808
809
810
811
812
813
814
815
816
817
818
819
sub which_conf {
	my ($conf) = @_;

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

	return "";
}

820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
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;
}
840
sub copy_spacing {
841
	(my $res = shift) =~ tr/\t/ /c;
842
843
	return $res;
}
844

845
846
847
848
849
850
851
852
853
854
855
856
857
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));
}

858
859
860
861
862
863
864
865
866
867
868
my $sanitise_quote = '';

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

	if ($in_comment) {
		$sanitise_quote = '*/';
	} else {
		$sanitise_quote = '';
	}
}
869
870
871
872
873
874
sub sanitise_line {
	my ($line) = @_;

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

875
	my $qlen = 0;
876
877
	my $off = 0;
	my $c;
878

879
880
881
882
883
884
885
886
887
888
889
890
891
892
	# 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;
893
		}
894
		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
895
896
897
898
			$sanitise_quote = '';
			substr($res, $off, 2, "$;$;");
			$off++;
			next;
899
		}
900
901
902
903
904
905
906
		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
			$sanitise_quote = '//';

			substr($res, $off, 2, $sanitise_quote);
			$off++;
			next;
		}
907
908
909
910
911
912
913

		# 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;
914
		}
915
916
917
918
		# Regular quotes.
		if ($c eq "'" || $c eq '"') {
			if ($sanitise_quote eq '') {
				$sanitise_quote = $c;
919

920
921
922
923
924
925
				substr($res, $off, 1, $c);
				next;
			} elsif ($sanitise_quote eq $c) {
				$sanitise_quote = '';
			}
		}
926

927
		#print "c<$c> SQ<$sanitise_quote>\n";
928
929
		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
			substr($res, $off, 1, $;);
930
931
		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
			substr($res, $off, 1, $;);
932
933
934
935
936
		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
			substr($res, $off, 1, 'X');
		} else {
			substr($res, $off, 1, $c);
		}
937
938
	}

939
940
941
942
	if ($sanitise_quote eq '//') {
		$sanitise_quote = '';
	}

943
	# The pathname on a #include may be surrounded by '<' and '>'.
944
	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
945
946
947
948
		my $clean = 'X' x length($1);
		$res =~ s@\<.*\>@<$clean>@;

	# The whole of a #error is a string.
949
	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
950
		my $clean = 'X' x length($1);
951
		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
952
953
	}

954
955
956
	return $res;
}

957
958
959
sub get_quoted_string {
	my ($line, $rawline) = @_;

960
	return "" if ($line !~ m/(\"[X\t]+\")/g);
961
962
963
	return substr($rawline, $-[0], $+[0] - $-[0]);
}

964
965
966
967
968
969
sub ctx_statement_block {
	my ($linenr, $remain, $off) = @_;
	my $line = $linenr - 1;
	my $blk = '';
	my $soff = $off;
	my $coff = $off - 1;
970
	my $coff_set = 0;
971

972
973
	my $loff = 0;

974
975
	my $type = '';
	my $level = 0;
976
	my @stack = ();
977
	my $p;
978
979
	my $c;
	my $len = 0;
980
981

	my $remainder;
982
	while (1) {
983
984
		@stack = (['', 0]) if ($#stack == -1);

985
		#warn "CSB: blk<$blk> remain<$remain>\n";
986
987
988
989
		# If we are about to drop off the end, pull in more
		# context.
		if ($off >= $len) {
			for (; $remain > 0; $line++) {
990
				last if (!defined $lines[$line]);
991
				next if ($lines[$line] =~ /^-/);
992
				$remain--;
993
				$loff = $len;
994
				$blk .= $lines[$line] . "\n";
995
996
997
998
999
1000
				$len = length($blk);
				$line++;
				last;
			}
			# Bail if there is no further context.
			#warn "CSB: blk<$blk> off<$off> len<$len>\n";
For faster browsing, not all history is shown. View entire blame