blob: 9afa2324b585816655b367163b54255368c25b24 [file] [log] [blame]
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001#!/usr/bin/perl -w
2# (c) 2001, Dave Jones. (the file handling bit)
3# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6# Licensed under the terms of the GNU GPL License version 2
7
8use strict;
9use POSIX;
10use File::Basename;
11use Cwd 'abs_path';
Stefan Reinauerc6080c62016-07-29 16:01:40 -070012use Term::ANSIColor qw(:constants);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010013
14my $P = $0;
15my $D = dirname(abs_path($P));
16
17my $V = '0.32';
18
19use Getopt::Long qw(:config no_auto_abbrev);
20
21my $quiet = 0;
22my $tree = 1;
23my $chk_signoff = 1;
24my $chk_patch = 1;
25my $tst_only;
26my $emacs = 0;
27my $terse = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070028my $showfile = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010029my $file = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070030my $git = 0;
31my %git_commits = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010032my $check = 0;
33my $check_orig = 0;
34my $summary = 1;
35my $mailback = 0;
36my $summary_file = 0;
37my $show_types = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -070038my $list_types = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010039my $fix = 0;
40my $fix_inplace = 0;
41my $root;
42my %debug;
43my %camelcase = ();
44my %use_type = ();
45my @use = ();
46my %ignore_type = ();
47my @ignore = ();
Martin Rotha3cac872017-03-04 18:17:35 -070048my @exclude = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010049my $help = 0;
50my $configuration_file = ".checkpatch.conf";
51my $max_line_length = 80;
52my $ignore_perl_version = 0;
53my $minimum_perl_version = 5.10.0;
54my $min_conf_desc_length = 4;
55my $spelling_file = "$D/spelling.txt";
Stefan Reinauerc6080c62016-07-29 16:01:40 -070056my $codespell = 0;
57my $codespellfile = "/usr/share/codespell/dictionary.txt";
58my $color = 1;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010059
60sub help {
61 my ($exitcode) = @_;
62
63 print << "EOM";
64Usage: $P [OPTION]... [FILE]...
65Version: $V
66
67Options:
68 -q, --quiet quiet
Stefan Reinauerc6080c62016-07-29 16:01:40 -070069 --no-tree run without a kernel tree
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010070 --no-signoff do not check for 'Signed-off-by' line
71 --patch treat FILE as patchfile (default)
72 --emacs emacs compile window format
73 --terse one line per report
Stefan Reinauerc6080c62016-07-29 16:01:40 -070074 --showfile emit diffed file position, not input file position
75 -g, --git treat FILE as a single commit or git revision range
76 single git commit with:
77 <rev>
78 <rev>^
79 <rev>~n
80 multiple git commits with:
81 <rev1>..<rev2>
82 <rev1>...<rev2>
83 <rev>-<count>
84 git merges are ignored
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010085 -f, --file treat FILE as regular source file
86 --subjective, --strict enable more subjective tests
Stefan Reinauerc6080c62016-07-29 16:01:40 -070087 --list-types list the possible message types
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010088 --types TYPE(,TYPE2...) show only these comma separated message types
89 --ignore TYPE(,TYPE2...) ignore various comma separated message types
Martin Rotha3cac872017-03-04 18:17:35 -070090 --exclude DIR(,DIR22...) exclude directories
Stefan Reinauerc6080c62016-07-29 16:01:40 -070091 --show-types show the specific message type in the output
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010092 --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
Stefan Reinauerc6080c62016-07-29 16:01:40 -070094 --root=PATH PATH to the kernel tree root
Stefan Reinauer44d0fd92015-02-11 01:49:00 +010095 --no-summary suppress the per-file summary
96 --mailback only produce a report in case of warnings/errors
97 --summary-file include the filename in summary
98 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
99 'values', 'possible', 'type', and 'attr' (default
100 is all off)
101 --test-only=WORD report only warnings/errors containing WORD
102 literally
103 --fix EXPERIMENTAL - may create horrible results
104 If correctable single-line errors exist, create
105 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
106 with potential errors corrected to the preferred
107 checkpatch style
108 --fix-inplace EXPERIMENTAL - may create horrible results
109 Is the same as --fix, but overwrites the input
110 file. It's your fault if there's no backup or git
111 --ignore-perl-version override checking of perl version. expect
112 runtime errors.
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700113 --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)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100117 -h, --help, --version display this help and exit
118
119When FILE is - read standard input.
120EOM
121
122 exit($exitcode);
123}
124
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700125sub uniq {
126 my %seen;
127 return grep { !$seen{$_}++ } @_;
128}
129
130sub list_types {
131 my ($exitcode) = @_;
132
133 my $count = 0;
134
135 local $/ = undef;
136
137 open(my $script, '<', abs_path($P)) or
138 die "$P: Can't read '$P' $!\n";
139
140 my $text = <$script>;
141 close($script);
142
143 my @types = ();
144 for ($text =~ /\b(?:(?:CHK|WARN|ERROR)\s*\(\s*"([^"]+)")/g) {
145 push (@types, $_);
146 }
147 @types = sort(uniq(@types));
148 print("#\tMessage type\n\n");
149 foreach my $type (@types) {
150 print(++$count . "\t" . $type . "\n");
151 }
152
153 exit($exitcode);
154}
155
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100156my $conf = which_conf($configuration_file);
157if (-f $conf) {
158 my @conf_args;
159 open(my $conffile, '<', "$conf")
160 or warn "$P: Can't find a readable $configuration_file file $!\n";
161
162 while (<$conffile>) {
163 my $line = $_;
164
165 $line =~ s/\s*\n?$//g;
166 $line =~ s/^\s*//g;
167 $line =~ s/\s+/ /g;
168
169 next if ($line =~ m/^\s*#/);
170 next if ($line =~ m/^\s*$/);
171
172 my @words = split(" ", $line);
173 foreach my $word (@words) {
174 last if ($word =~ m/^#/);
175 push (@conf_args, $word);
176 }
177 }
178 close($conffile);
179 unshift(@ARGV, @conf_args) if @conf_args;
180}
181
182GetOptions(
183 'q|quiet+' => \$quiet,
184 'tree!' => \$tree,
185 'signoff!' => \$chk_signoff,
186 'patch!' => \$chk_patch,
187 'emacs!' => \$emacs,
188 'terse!' => \$terse,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700189 'showfile!' => \$showfile,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100190 'f|file!' => \$file,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700191 'g|git!' => \$git,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100192 'subjective!' => \$check,
193 'strict!' => \$check,
194 'ignore=s' => \@ignore,
Martin Rotha3cac872017-03-04 18:17:35 -0700195 'exclude=s' => \@exclude,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100196 'types=s' => \@use,
197 'show-types!' => \$show_types,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700198 'list-types!' => \$list_types,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100199 'max-line-length=i' => \$max_line_length,
200 'min-conf-desc-length=i' => \$min_conf_desc_length,
201 'root=s' => \$root,
202 'summary!' => \$summary,
203 'mailback!' => \$mailback,
204 'summary-file!' => \$summary_file,
205 'fix!' => \$fix,
206 'fix-inplace!' => \$fix_inplace,
207 'ignore-perl-version!' => \$ignore_perl_version,
208 'debug=s' => \%debug,
209 'test-only=s' => \$tst_only,
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700210 'codespell!' => \$codespell,
211 'codespellfile=s' => \$codespellfile,
212 'color!' => \$color,
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100213 'h|help' => \$help,
214 'version' => \$help
215) or help(1);
216
217help(0) if ($help);
218
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700219list_types(0) if ($list_types);
220
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100221$fix = 1 if ($fix_inplace);
222$check_orig = $check;
223
224my $exit = 0;
225
226if ($^V && $^V lt $minimum_perl_version) {
227 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
228 if (!$ignore_perl_version) {
229 exit(1);
230 }
231}
232
233if ($#ARGV < 0) {
234 print "$P: no input files\n";
235 exit(1);
236}
237
238sub hash_save_array_words {
239 my ($hashRef, $arrayRef) = @_;
240
241 my @array = split(/,/, join(',', @$arrayRef));
242 foreach my $word (@array) {
243 $word =~ s/\s*\n?$//g;
244 $word =~ s/^\s*//g;
245 $word =~ s/\s+/ /g;
246 $word =~ tr/[a-z]/[A-Z]/;
247
248 next if ($word =~ m/^\s*#/);
249 next if ($word =~ m/^\s*$/);
250
251 $hashRef->{$word}++;
252 }
253}
254
255sub hash_show_words {
256 my ($hashRef, $prefix) = @_;
257
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700258 if (keys %$hashRef) {
259 print "\nNOTE: $prefix message types:";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100260 foreach my $word (sort keys %$hashRef) {
261 print " $word";
262 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700263 print "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100264 }
265}
266
267hash_save_array_words(\%ignore_type, \@ignore);
268hash_save_array_words(\%use_type, \@use);
269
270my $dbg_values = 0;
271my $dbg_possible = 0;
272my $dbg_type = 0;
273my $dbg_attr = 0;
274for my $key (keys %debug) {
275 ## no critic
276 eval "\${dbg_$key} = '$debug{$key}';";
277 die "$@" if ($@);
278}
279
280my $rpt_cleaners = 0;
281
282if ($terse) {
283 $emacs = 1;
284 $quiet++;
285}
286
287if ($tree) {
288 if (defined $root) {
289 if (!top_of_kernel_tree($root)) {
290 die "$P: $root: --root does not point at a valid tree\n";
291 }
292 } else {
293 if (top_of_kernel_tree('.')) {
294 $root = '.';
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700295 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100296 top_of_kernel_tree($1)) {
297 $root = $1;
298 }
299 }
300
301 if (!defined $root) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700302 print "Must be run from the top-level dir. of a kernel tree\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100303 exit(2);
304 }
305}
306
307my $emitted_corrupt = 0;
308
309our $Ident = qr{
310 [A-Za-z_][A-Za-z\d_]*
311 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
312 }x;
313our $Storage = qr{extern|static|asmlinkage};
314our $Sparse = qr{
315 __user|
316 __kernel|
317 __force|
318 __iomem|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700319 __pmem|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100320 __must_check|
321 __init_refok|
322 __kprobes|
323 __ref|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700324 __rcu|
325 __private
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100326 }x;
327our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
328our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
329our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
330our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
331our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
332
333# Notes to $Attribute:
334# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
335our $Attribute = qr{
336 const|
337 __percpu|
338 __nocast|
339 __safe|
340 __bitwise__|
341 __packed__|
342 __packed2__|
343 __naked|
344 __maybe_unused|
345 __always_unused|
346 __noreturn|
347 __used|
348 __cold|
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700349 __pure|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100350 __noclone|
351 __deprecated|
352 __read_mostly|
353 __kprobes|
354 $InitAttribute|
355 ____cacheline_aligned|
356 ____cacheline_aligned_in_smp|
357 ____cacheline_internodealigned_in_smp|
358 __weak
359 }x;
360our $Modifier;
361our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
362our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
363our $Lval = qr{$Ident(?:$Member)*};
364
365our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
366our $Binary = qr{(?i)0b[01]+$Int_type?};
367our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
368our $Int = qr{[0-9]+$Int_type?};
369our $Octal = qr{0[0-7]+$Int_type?};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700370our $String = qr{"[X\t]*"};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100371our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
372our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
373our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
374our $Float = qr{$Float_hex|$Float_dec|$Float_int};
375our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
376our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
377our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
378our $Arithmetic = qr{\+|-|\*|\/|%};
379our $Operators = qr{
380 <=|>=|==|!=|
381 =>|->|<<|>>|<|>|!|~|
382 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
383 }x;
384
385our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
386
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700387our $BasicType;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100388our $NonptrType;
389our $NonptrTypeMisordered;
390our $NonptrTypeWithAttr;
391our $Type;
392our $TypeMisordered;
393our $Declare;
394our $DeclareMisordered;
395
396our $NON_ASCII_UTF8 = qr{
397 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
398 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
399 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
400 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
401 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
402 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
403 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
404}x;
405
406our $UTF8 = qr{
407 [\x09\x0A\x0D\x20-\x7E] # ASCII
408 | $NON_ASCII_UTF8
409}x;
410
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700411our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
412our $typeOtherOSTypedefs = qr{(?x:
413 u_(?:char|short|int|long) | # bsd
414 u(?:nchar|short|int|long) # sysv
415)};
416our $typeKernelTypedefs = qr{(?x:
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100417 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
418 atomic_t
419)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700420our $typeTypedefs = qr{(?x:
421 $typeC99Typedefs\b|
422 $typeOtherOSTypedefs\b|
423 $typeKernelTypedefs\b
424)};
425
426our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100427
428our $logFunctions = qr{(?x:
429 printk(?:_ratelimited|_once|)|
430 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
431 WARN(?:_RATELIMIT|_ONCE|)|
432 panic|
433 MODULE_[A-Z_]+|
434 seq_vprintf|seq_printf|seq_puts
435)};
436
437our $signature_tags = qr{(?xi:
438 Signed-off-by:|
439 Acked-by:|
440 Tested-by:|
441 Reviewed-by:|
442 Reported-by:|
443 Suggested-by:|
444 To:|
445 Cc:
446)};
447
448our @typeListMisordered = (
449 qr{char\s+(?:un)?signed},
450 qr{int\s+(?:(?:un)?signed\s+)?short\s},
451 qr{int\s+short(?:\s+(?:un)?signed)},
452 qr{short\s+int(?:\s+(?:un)?signed)},
453 qr{(?:un)?signed\s+int\s+short},
454 qr{short\s+(?:un)?signed},
455 qr{long\s+int\s+(?:un)?signed},
456 qr{int\s+long\s+(?:un)?signed},
457 qr{long\s+(?:un)?signed\s+int},
458 qr{int\s+(?:un)?signed\s+long},
459 qr{int\s+(?:un)?signed},
460 qr{int\s+long\s+long\s+(?:un)?signed},
461 qr{long\s+long\s+int\s+(?:un)?signed},
462 qr{long\s+long\s+(?:un)?signed\s+int},
463 qr{long\s+long\s+(?:un)?signed},
464 qr{long\s+(?:un)?signed},
465);
466
467our @typeList = (
468 qr{void},
469 qr{(?:(?:un)?signed\s+)?char},
470 qr{(?:(?:un)?signed\s+)?short\s+int},
471 qr{(?:(?:un)?signed\s+)?short},
472 qr{(?:(?:un)?signed\s+)?int},
473 qr{(?:(?:un)?signed\s+)?long\s+int},
474 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
475 qr{(?:(?:un)?signed\s+)?long\s+long},
476 qr{(?:(?:un)?signed\s+)?long},
477 qr{(?:un)?signed},
478 qr{float},
479 qr{double},
480 qr{bool},
481 qr{struct\s+$Ident},
482 qr{union\s+$Ident},
483 qr{enum\s+$Ident},
484 qr{${Ident}_t},
485 qr{${Ident}_handler},
486 qr{${Ident}_handler_fn},
487 @typeListMisordered,
488);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700489
490our $C90_int_types = qr{(?x:
491 long\s+long\s+int\s+(?:un)?signed|
492 long\s+long\s+(?:un)?signed\s+int|
493 long\s+long\s+(?:un)?signed|
494 (?:(?:un)?signed\s+)?long\s+long\s+int|
495 (?:(?:un)?signed\s+)?long\s+long|
496 int\s+long\s+long\s+(?:un)?signed|
497 int\s+(?:(?:un)?signed\s+)?long\s+long|
498
499 long\s+int\s+(?:un)?signed|
500 long\s+(?:un)?signed\s+int|
501 long\s+(?:un)?signed|
502 (?:(?:un)?signed\s+)?long\s+int|
503 (?:(?:un)?signed\s+)?long|
504 int\s+long\s+(?:un)?signed|
505 int\s+(?:(?:un)?signed\s+)?long|
506
507 int\s+(?:un)?signed|
508 (?:(?:un)?signed\s+)?int
509)};
510
511our @typeListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100512our @typeListWithAttr = (
513 @typeList,
514 qr{struct\s+$InitAttribute\s+$Ident},
515 qr{union\s+$InitAttribute\s+$Ident},
516);
517
518our @modifierList = (
519 qr{fastcall},
520);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700521our @modifierListFile = ();
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100522
523our @mode_permission_funcs = (
524 ["module_param", 3],
525 ["module_param_(?:array|named|string)", 4],
526 ["module_param_array_named", 5],
527 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
528 ["proc_create(?:_data|)", 2],
529 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
530);
531
532#Create a search pattern for all these functions to speed up a loop below
533our $mode_perms_search = "";
534foreach my $entry (@mode_permission_funcs) {
535 $mode_perms_search .= '|' if ($mode_perms_search ne "");
536 $mode_perms_search .= $entry->[0];
537}
538
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700539our $mode_perms_world_writable = qr{
540 S_IWUGO |
541 S_IWOTH |
542 S_IRWXUGO |
543 S_IALLUGO |
544 0[0-7][0-7][2367]
545}x;
546
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100547our $allowed_asm_includes = qr{(?x:
548 irq|
549 memory|
550 time|
551 reboot
552)};
553# memory.h: ARM has a custom one
554
555# Load common spelling mistakes and build regular expression list.
556my $misspellings;
557my %spelling_fix;
558
559if (open(my $spelling, '<', $spelling_file)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100560 while (<$spelling>) {
561 my $line = $_;
562
563 $line =~ s/\s*\n?$//g;
564 $line =~ s/^\s*//g;
565
566 next if ($line =~ m/^\s*#/);
567 next if ($line =~ m/^\s*$/);
568
569 my ($suspect, $fix) = split(/\|\|/, $line);
570
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100571 $spelling_fix{$suspect} = $fix;
572 }
573 close($spelling);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100574} else {
575 warn "No typos will be found - file '$spelling_file': $!\n";
576}
577
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700578if ($codespell) {
579 if (open(my $spelling, '<', $codespellfile)) {
580 while (<$spelling>) {
581 my $line = $_;
582
583 $line =~ s/\s*\n?$//g;
584 $line =~ s/^\s*//g;
585
586 next if ($line =~ m/^\s*#/);
587 next if ($line =~ m/^\s*$/);
588 next if ($line =~ m/, disabled/i);
589
590 $line =~ s/,.*$//;
591
592 my ($suspect, $fix) = split(/->/, $line);
593
594 $spelling_fix{$suspect} = $fix;
595 }
596 close($spelling);
597 } else {
598 warn "No codespell typos will be found - file '$codespellfile': $!\n";
599 }
600}
601
602$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
603
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100604sub build_types {
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700605 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
606 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100607 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
608 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
609 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700610 $BasicType = qr{
611 (?:$typeTypedefs\b)|
612 (?:${all}\b)
613 }x;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100614 $NonptrType = qr{
615 (?:$Modifier\s+|const\s+)*
616 (?:
617 (?:typeof|__typeof__)\s*\([^\)]*\)|
618 (?:$typeTypedefs\b)|
619 (?:${all}\b)
620 )
621 (?:\s+$Modifier|\s+const)*
622 }x;
623 $NonptrTypeMisordered = qr{
624 (?:$Modifier\s+|const\s+)*
625 (?:
626 (?:${Misordered}\b)
627 )
628 (?:\s+$Modifier|\s+const)*
629 }x;
630 $NonptrTypeWithAttr = qr{
631 (?:$Modifier\s+|const\s+)*
632 (?:
633 (?:typeof|__typeof__)\s*\([^\)]*\)|
634 (?:$typeTypedefs\b)|
635 (?:${allWithAttr}\b)
636 )
637 (?:\s+$Modifier|\s+const)*
638 }x;
639 $Type = qr{
640 $NonptrType
641 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
642 (?:\s+$Inline|\s+$Modifier)*
643 }x;
644 $TypeMisordered = qr{
645 $NonptrTypeMisordered
646 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
647 (?:\s+$Inline|\s+$Modifier)*
648 }x;
649 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
650 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
651}
652build_types();
653
654our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
655
656# Using $balanced_parens, $LvalOrFunc, or $FuncArg
657# requires at least perl version v5.10.0
658# Any use must be runtime checked with $^V
659
660our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
661our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700662our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100663
664our $declaration_macros = qr{(?x:
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700665 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100666 (?:$Storage\s+)?LIST_HEAD\s*\(|
667 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
668)};
669
670sub deparenthesize {
671 my ($string) = @_;
672 return "" if (!defined($string));
673
674 while ($string =~ /^\s*\(.*\)\s*$/) {
675 $string =~ s@^\s*\(\s*@@;
676 $string =~ s@\s*\)\s*$@@;
677 }
678
679 $string =~ s@\s+@ @g;
680
681 return $string;
682}
683
684sub seed_camelcase_file {
685 my ($file) = @_;
686
687 return if (!(-f $file));
688
689 local $/;
690
691 open(my $include_file, '<', "$file")
692 or warn "$P: Can't read '$file' $!\n";
693 my $text = <$include_file>;
694 close($include_file);
695
696 my @lines = split('\n', $text);
697
698 foreach my $line (@lines) {
699 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
700 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
701 $camelcase{$1} = 1;
702 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
703 $camelcase{$1} = 1;
704 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
705 $camelcase{$1} = 1;
706 }
707 }
708}
709
710my $camelcase_seeded = 0;
711sub seed_camelcase_includes {
712 return if ($camelcase_seeded);
713
714 my $files;
715 my $camelcase_cache = "";
716 my @include_files = ();
717
718 $camelcase_seeded = 1;
719
720 if (-e ".git") {
721 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
722 chomp $git_last_include_commit;
723 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
724 } else {
725 my $last_mod_date = 0;
726 $files = `find $root/include -name "*.h"`;
727 @include_files = split('\n', $files);
728 foreach my $file (@include_files) {
729 my $date = POSIX::strftime("%Y%m%d%H%M",
730 localtime((stat $file)[9]));
731 $last_mod_date = $date if ($last_mod_date < $date);
732 }
733 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
734 }
735
736 if ($camelcase_cache ne "" && -f $camelcase_cache) {
737 open(my $camelcase_file, '<', "$camelcase_cache")
738 or warn "$P: Can't read '$camelcase_cache' $!\n";
739 while (<$camelcase_file>) {
740 chomp;
741 $camelcase{$_} = 1;
742 }
743 close($camelcase_file);
744
745 return;
746 }
747
748 if (-e ".git") {
749 $files = `git ls-files "include/*.h"`;
750 @include_files = split('\n', $files);
751 }
752
753 foreach my $file (@include_files) {
754 seed_camelcase_file($file);
755 }
756
757 if ($camelcase_cache ne "") {
758 unlink glob ".checkpatch-camelcase.*";
759 open(my $camelcase_file, '>', "$camelcase_cache")
760 or warn "$P: Can't write '$camelcase_cache' $!\n";
761 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
762 print $camelcase_file ("$_\n");
763 }
764 close($camelcase_file);
765 }
766}
767
768sub git_commit_info {
769 my ($commit, $id, $desc) = @_;
770
771 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
772
773 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
774 $output =~ s/^\s*//gm;
775 my @lines = split("\n", $output);
776
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700777 return ($id, $desc) if ($#lines < 0);
778
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100779 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
780# Maybe one day convert this block of bash into something that returns
781# all matching commit ids, but it's very slow...
782#
783# echo "checking commits $1..."
784# git rev-list --remotes | grep -i "^$1" |
785# while read line ; do
786# git log --format='%H %s' -1 $line |
787# echo "commit $(cut -c 1-12,41-)"
788# done
789 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
790 } else {
791 $id = substr($lines[0], 0, 12);
792 $desc = substr($lines[0], 41);
793 }
794
795 return ($id, $desc);
796}
797
798$chk_signoff = 0 if ($file);
799
800my @rawlines = ();
801my @lines = ();
802my @fixed = ();
803my @fixed_inserted = ();
804my @fixed_deleted = ();
805my $fixlinenr = -1;
806
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700807# If input is git commits, extract all commits from the commit expressions.
808# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
809die "$P: No git repository found\n" if ($git && !-e ".git");
810
811if ($git) {
812 my @commits = ();
813 foreach my $commit_expr (@ARGV) {
814 my $git_range;
815 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
816 $git_range = "-$2 $1";
817 } elsif ($commit_expr =~ m/\.\./) {
818 $git_range = "$commit_expr";
819 } else {
820 $git_range = "-1 $commit_expr";
821 }
822 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
823 foreach my $line (split(/\n/, $lines)) {
824 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
825 next if (!defined($1) || !defined($2));
826 my $sha1 = $1;
827 my $subject = $2;
828 unshift(@commits, $sha1);
829 $git_commits{$sha1} = $subject;
830 }
831 }
832 die "$P: no git commits after extraction!\n" if (@commits == 0);
833 @ARGV = @commits;
834}
835
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100836my $vname;
837for my $filename (@ARGV) {
838 my $FILE;
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700839 if ($git) {
840 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
841 die "$P: $filename: git format-patch failed - $!\n";
842 } elsif ($file) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100843 open($FILE, '-|', "diff -u /dev/null $filename") ||
844 die "$P: $filename: diff failed - $!\n";
845 } elsif ($filename eq '-') {
846 open($FILE, '<&STDIN');
847 } else {
848 open($FILE, '<', "$filename") ||
849 die "$P: $filename: open failed - $!\n";
850 }
851 if ($filename eq '-') {
852 $vname = 'Your patch';
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700853 } elsif ($git) {
854 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100855 } else {
856 $vname = $filename;
857 }
858 while (<$FILE>) {
859 chomp;
860 push(@rawlines, $_);
861 }
862 close($FILE);
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700863
864 if ($#ARGV > 0 && $quiet == 0) {
865 print '-' x length($vname) . "\n";
866 print "$vname\n";
867 print '-' x length($vname) . "\n";
868 }
869
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100870 if (!process($filename)) {
871 $exit = 1;
872 }
873 @rawlines = ();
874 @lines = ();
875 @fixed = ();
876 @fixed_inserted = ();
877 @fixed_deleted = ();
878 $fixlinenr = -1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700879 @modifierListFile = ();
880 @typeListFile = ();
881 build_types();
882}
883
884if (!$quiet) {
885 hash_show_words(\%use_type, "Used");
886 hash_show_words(\%ignore_type, "Ignored");
887
888 if ($^V lt 5.10.0) {
889 print << "EOM"
890
891NOTE: perl $^V is not modern enough to detect all possible issues.
892 An upgrade to at least perl v5.10.0 is suggested.
893EOM
894 }
895 if ($exit) {
896 print << "EOM"
897
898NOTE: If any of the errors are false positives, please report
899 them to the maintainer, see CHECKPATCH in MAINTAINERS.
900EOM
901 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100902}
903
904exit($exit);
905
906sub top_of_kernel_tree {
907 my ($root) = @_;
908
909 my @tree_check = (
Stefan Reinauerc6080c62016-07-29 16:01:40 -0700910 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
911 "README", "Documentation", "arch", "include", "drivers",
912 "fs", "init", "ipc", "kernel", "lib", "scripts",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +0100913 );
914
915 foreach my $check (@tree_check) {
916 if (! -e $root . '/' . $check) {
917 return 0;
918 }
919 }
920 return 1;
921}
922
923sub parse_email {
924 my ($formatted_email) = @_;
925
926 my $name = "";
927 my $address = "";
928 my $comment = "";
929
930 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
931 $name = $1;
932 $address = $2;
933 $comment = $3 if defined $3;
934 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
935 $address = $1;
936 $comment = $2 if defined $2;
937 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
938 $address = $1;
939 $comment = $2 if defined $2;
940 $formatted_email =~ s/$address.*$//;
941 $name = $formatted_email;
942 $name = trim($name);
943 $name =~ s/^\"|\"$//g;
944 # If there's a name left after stripping spaces and
945 # leading quotes, and the address doesn't have both
946 # leading and trailing angle brackets, the address
947 # is invalid. ie:
948 # "joe smith joe@smith.com" bad
949 # "joe smith <joe@smith.com" bad
950 if ($name ne "" && $address !~ /^<[^>]+>$/) {
951 $name = "";
952 $address = "";
953 $comment = "";
954 }
955 }
956
957 $name = trim($name);
958 $name =~ s/^\"|\"$//g;
959 $address = trim($address);
960 $address =~ s/^\<|\>$//g;
961
962 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
963 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
964 $name = "\"$name\"";
965 }
966
967 return ($name, $address, $comment);
968}
969
970sub format_email {
971 my ($name, $address) = @_;
972
973 my $formatted_email;
974
975 $name = trim($name);
976 $name =~ s/^\"|\"$//g;
977 $address = trim($address);
978
979 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
980 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
981 $name = "\"$name\"";
982 }
983
984 if ("$name" eq "") {
985 $formatted_email = "$address";
986 } else {
987 $formatted_email = "$name <$address>";
988 }
989
990 return $formatted_email;
991}
992
993sub which {
994 my ($bin) = @_;
995
996 foreach my $path (split(/:/, $ENV{PATH})) {
997 if (-e "$path/$bin") {
998 return "$path/$bin";
999 }
1000 }
1001
1002 return "";
1003}
1004
1005sub which_conf {
1006 my ($conf) = @_;
1007
1008 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1009 if (-e "$path/$conf") {
1010 return "$path/$conf";
1011 }
1012 }
1013
1014 return "";
1015}
1016
1017sub expand_tabs {
1018 my ($str) = @_;
1019
1020 my $res = '';
1021 my $n = 0;
1022 for my $c (split(//, $str)) {
1023 if ($c eq "\t") {
1024 $res .= ' ';
1025 $n++;
1026 for (; ($n % 8) != 0; $n++) {
1027 $res .= ' ';
1028 }
1029 next;
1030 }
1031 $res .= $c;
1032 $n++;
1033 }
1034
1035 return $res;
1036}
1037sub copy_spacing {
1038 (my $res = shift) =~ tr/\t/ /c;
1039 return $res;
1040}
1041
1042sub line_stats {
1043 my ($line) = @_;
1044
1045 # Drop the diff line leader and expand tabs
1046 $line =~ s/^.//;
1047 $line = expand_tabs($line);
1048
1049 # Pick the indent from the front of the line.
1050 my ($white) = ($line =~ /^(\s*)/);
1051
1052 return (length($line), length($white));
1053}
1054
1055my $sanitise_quote = '';
1056
1057sub sanitise_line_reset {
1058 my ($in_comment) = @_;
1059
1060 if ($in_comment) {
1061 $sanitise_quote = '*/';
1062 } else {
1063 $sanitise_quote = '';
1064 }
1065}
1066sub sanitise_line {
1067 my ($line) = @_;
1068
1069 my $res = '';
1070 my $l = '';
1071
1072 my $qlen = 0;
1073 my $off = 0;
1074 my $c;
1075
1076 # Always copy over the diff marker.
1077 $res = substr($line, 0, 1);
1078
1079 for ($off = 1; $off < length($line); $off++) {
1080 $c = substr($line, $off, 1);
1081
1082 # Comments we are wacking completly including the begin
1083 # and end, all to $;.
1084 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1085 $sanitise_quote = '*/';
1086
1087 substr($res, $off, 2, "$;$;");
1088 $off++;
1089 next;
1090 }
1091 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1092 $sanitise_quote = '';
1093 substr($res, $off, 2, "$;$;");
1094 $off++;
1095 next;
1096 }
1097 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1098 $sanitise_quote = '//';
1099
1100 substr($res, $off, 2, $sanitise_quote);
1101 $off++;
1102 next;
1103 }
1104
1105 # A \ in a string means ignore the next character.
1106 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1107 $c eq "\\") {
1108 substr($res, $off, 2, 'XX');
1109 $off++;
1110 next;
1111 }
1112 # Regular quotes.
1113 if ($c eq "'" || $c eq '"') {
1114 if ($sanitise_quote eq '') {
1115 $sanitise_quote = $c;
1116
1117 substr($res, $off, 1, $c);
1118 next;
1119 } elsif ($sanitise_quote eq $c) {
1120 $sanitise_quote = '';
1121 }
1122 }
1123
1124 #print "c<$c> SQ<$sanitise_quote>\n";
1125 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1126 substr($res, $off, 1, $;);
1127 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1128 substr($res, $off, 1, $;);
1129 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1130 substr($res, $off, 1, 'X');
1131 } else {
1132 substr($res, $off, 1, $c);
1133 }
1134 }
1135
1136 if ($sanitise_quote eq '//') {
1137 $sanitise_quote = '';
1138 }
1139
1140 # The pathname on a #include may be surrounded by '<' and '>'.
1141 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1142 my $clean = 'X' x length($1);
1143 $res =~ s@\<.*\>@<$clean>@;
1144
1145 # The whole of a #error is a string.
1146 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1147 my $clean = 'X' x length($1);
1148 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1149 }
1150
1151 return $res;
1152}
1153
1154sub get_quoted_string {
1155 my ($line, $rawline) = @_;
1156
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001157 return "" if ($line !~ m/($String)/g);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001158 return substr($rawline, $-[0], $+[0] - $-[0]);
1159}
1160
1161sub ctx_statement_block {
1162 my ($linenr, $remain, $off) = @_;
1163 my $line = $linenr - 1;
1164 my $blk = '';
1165 my $soff = $off;
1166 my $coff = $off - 1;
1167 my $coff_set = 0;
1168
1169 my $loff = 0;
1170
1171 my $type = '';
1172 my $level = 0;
1173 my @stack = ();
1174 my $p;
1175 my $c;
1176 my $len = 0;
1177
1178 my $remainder;
1179 while (1) {
1180 @stack = (['', 0]) if ($#stack == -1);
1181
1182 #warn "CSB: blk<$blk> remain<$remain>\n";
1183 # If we are about to drop off the end, pull in more
1184 # context.
1185 if ($off >= $len) {
1186 for (; $remain > 0; $line++) {
1187 last if (!defined $lines[$line]);
1188 next if ($lines[$line] =~ /^-/);
1189 $remain--;
1190 $loff = $len;
1191 $blk .= $lines[$line] . "\n";
1192 $len = length($blk);
1193 $line++;
1194 last;
1195 }
1196 # Bail if there is no further context.
1197 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1198 if ($off >= $len) {
1199 last;
1200 }
1201 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1202 $level++;
1203 $type = '#';
1204 }
1205 }
1206 $p = $c;
1207 $c = substr($blk, $off, 1);
1208 $remainder = substr($blk, $off);
1209
1210 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1211
1212 # Handle nested #if/#else.
1213 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1214 push(@stack, [ $type, $level ]);
1215 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1216 ($type, $level) = @{$stack[$#stack - 1]};
1217 } elsif ($remainder =~ /^#\s*endif\b/) {
1218 ($type, $level) = @{pop(@stack)};
1219 }
1220
1221 # Statement ends at the ';' or a close '}' at the
1222 # outermost level.
1223 if ($level == 0 && $c eq ';') {
1224 last;
1225 }
1226
1227 # An else is really a conditional as long as its not else if
1228 if ($level == 0 && $coff_set == 0 &&
1229 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1230 $remainder =~ /^(else)(?:\s|{)/ &&
1231 $remainder !~ /^else\s+if\b/) {
1232 $coff = $off + length($1) - 1;
1233 $coff_set = 1;
1234 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1235 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1236 }
1237
1238 if (($type eq '' || $type eq '(') && $c eq '(') {
1239 $level++;
1240 $type = '(';
1241 }
1242 if ($type eq '(' && $c eq ')') {
1243 $level--;
1244 $type = ($level != 0)? '(' : '';
1245
1246 if ($level == 0 && $coff < $soff) {
1247 $coff = $off;
1248 $coff_set = 1;
1249 #warn "CSB: mark coff<$coff>\n";
1250 }
1251 }
1252 if (($type eq '' || $type eq '{') && $c eq '{') {
1253 $level++;
1254 $type = '{';
1255 }
1256 if ($type eq '{' && $c eq '}') {
1257 $level--;
1258 $type = ($level != 0)? '{' : '';
1259
1260 if ($level == 0) {
1261 if (substr($blk, $off + 1, 1) eq ';') {
1262 $off++;
1263 }
1264 last;
1265 }
1266 }
1267 # Preprocessor commands end at the newline unless escaped.
1268 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1269 $level--;
1270 $type = '';
1271 $off++;
1272 last;
1273 }
1274 $off++;
1275 }
1276 # We are truly at the end, so shuffle to the next line.
1277 if ($off == $len) {
1278 $loff = $len + 1;
1279 $line++;
1280 $remain--;
1281 }
1282
1283 my $statement = substr($blk, $soff, $off - $soff + 1);
1284 my $condition = substr($blk, $soff, $coff - $soff + 1);
1285
1286 #warn "STATEMENT<$statement>\n";
1287 #warn "CONDITION<$condition>\n";
1288
1289 #print "coff<$coff> soff<$off> loff<$loff>\n";
1290
1291 return ($statement, $condition,
1292 $line, $remain + 1, $off - $loff + 1, $level);
1293}
1294
1295sub statement_lines {
1296 my ($stmt) = @_;
1297
1298 # Strip the diff line prefixes and rip blank lines at start and end.
1299 $stmt =~ s/(^|\n)./$1/g;
1300 $stmt =~ s/^\s*//;
1301 $stmt =~ s/\s*$//;
1302
1303 my @stmt_lines = ($stmt =~ /\n/g);
1304
1305 return $#stmt_lines + 2;
1306}
1307
1308sub statement_rawlines {
1309 my ($stmt) = @_;
1310
1311 my @stmt_lines = ($stmt =~ /\n/g);
1312
1313 return $#stmt_lines + 2;
1314}
1315
1316sub statement_block_size {
1317 my ($stmt) = @_;
1318
1319 $stmt =~ s/(^|\n)./$1/g;
1320 $stmt =~ s/^\s*{//;
1321 $stmt =~ s/}\s*$//;
1322 $stmt =~ s/^\s*//;
1323 $stmt =~ s/\s*$//;
1324
1325 my @stmt_lines = ($stmt =~ /\n/g);
1326 my @stmt_statements = ($stmt =~ /;/g);
1327
1328 my $stmt_lines = $#stmt_lines + 2;
1329 my $stmt_statements = $#stmt_statements + 1;
1330
1331 if ($stmt_lines > $stmt_statements) {
1332 return $stmt_lines;
1333 } else {
1334 return $stmt_statements;
1335 }
1336}
1337
1338sub ctx_statement_full {
1339 my ($linenr, $remain, $off) = @_;
1340 my ($statement, $condition, $level);
1341
1342 my (@chunks);
1343
1344 # Grab the first conditional/block pair.
1345 ($statement, $condition, $linenr, $remain, $off, $level) =
1346 ctx_statement_block($linenr, $remain, $off);
1347 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1348 push(@chunks, [ $condition, $statement ]);
1349 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1350 return ($level, $linenr, @chunks);
1351 }
1352
1353 # Pull in the following conditional/block pairs and see if they
1354 # could continue the statement.
1355 for (;;) {
1356 ($statement, $condition, $linenr, $remain, $off, $level) =
1357 ctx_statement_block($linenr, $remain, $off);
1358 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1359 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1360 #print "C: push\n";
1361 push(@chunks, [ $condition, $statement ]);
1362 }
1363
1364 return ($level, $linenr, @chunks);
1365}
1366
1367sub ctx_block_get {
1368 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1369 my $line;
1370 my $start = $linenr - 1;
1371 my $blk = '';
1372 my @o;
1373 my @c;
1374 my @res = ();
1375
1376 my $level = 0;
1377 my @stack = ($level);
1378 for ($line = $start; $remain > 0; $line++) {
1379 next if ($rawlines[$line] =~ /^-/);
1380 $remain--;
1381
1382 $blk .= $rawlines[$line];
1383
1384 # Handle nested #if/#else.
1385 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1386 push(@stack, $level);
1387 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1388 $level = $stack[$#stack - 1];
1389 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1390 $level = pop(@stack);
1391 }
1392
1393 foreach my $c (split(//, $lines[$line])) {
1394 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1395 if ($off > 0) {
1396 $off--;
1397 next;
1398 }
1399
1400 if ($c eq $close && $level > 0) {
1401 $level--;
1402 last if ($level == 0);
1403 } elsif ($c eq $open) {
1404 $level++;
1405 }
1406 }
1407
1408 if (!$outer || $level <= 1) {
1409 push(@res, $rawlines[$line]);
1410 }
1411
1412 last if ($level == 0);
1413 }
1414
1415 return ($level, @res);
1416}
1417sub ctx_block_outer {
1418 my ($linenr, $remain) = @_;
1419
1420 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1421 return @r;
1422}
1423sub ctx_block {
1424 my ($linenr, $remain) = @_;
1425
1426 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1427 return @r;
1428}
1429sub ctx_statement {
1430 my ($linenr, $remain, $off) = @_;
1431
1432 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1433 return @r;
1434}
1435sub ctx_block_level {
1436 my ($linenr, $remain) = @_;
1437
1438 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1439}
1440sub ctx_statement_level {
1441 my ($linenr, $remain, $off) = @_;
1442
1443 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1444}
1445
1446sub ctx_locate_comment {
1447 my ($first_line, $end_line) = @_;
1448
1449 # Catch a comment on the end of the line itself.
1450 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1451 return $current_comment if (defined $current_comment);
1452
1453 # Look through the context and try and figure out if there is a
1454 # comment.
1455 my $in_comment = 0;
1456 $current_comment = '';
1457 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1458 my $line = $rawlines[$linenr - 1];
1459 #warn " $line\n";
1460 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1461 $in_comment = 1;
1462 }
1463 if ($line =~ m@/\*@) {
1464 $in_comment = 1;
1465 }
1466 if (!$in_comment && $current_comment ne '') {
1467 $current_comment = '';
1468 }
1469 $current_comment .= $line . "\n" if ($in_comment);
1470 if ($line =~ m@\*/@) {
1471 $in_comment = 0;
1472 }
1473 }
1474
1475 chomp($current_comment);
1476 return($current_comment);
1477}
1478sub ctx_has_comment {
1479 my ($first_line, $end_line) = @_;
1480 my $cmt = ctx_locate_comment($first_line, $end_line);
1481
1482 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1483 ##print "CMMT: $cmt\n";
1484
1485 return ($cmt ne '');
1486}
1487
1488sub raw_line {
1489 my ($linenr, $cnt) = @_;
1490
1491 my $offset = $linenr - 1;
1492 $cnt++;
1493
1494 my $line;
1495 while ($cnt) {
1496 $line = $rawlines[$offset++];
1497 next if (defined($line) && $line =~ /^-/);
1498 $cnt--;
1499 }
1500
Martin Roth96a48f12016-08-29 15:30:23 -06001501 # coreboot: This probably shouldn't happen, but it does.
1502 # Return a defined value so we don't get an error.
1503 if (defined $line) {
1504 return $line;
1505 } else {
1506 return "";
1507 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001508}
1509
1510sub cat_vet {
1511 my ($vet) = @_;
1512 my ($res, $coded);
1513
1514 $res = '';
1515 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1516 $res .= $1;
1517 if ($2 ne '') {
1518 $coded = sprintf("^%c", unpack('C', $2) + 64);
1519 $res .= $coded;
1520 }
1521 }
1522 $res =~ s/$/\$/;
1523
1524 return $res;
1525}
1526
1527my $av_preprocessor = 0;
1528my $av_pending;
1529my @av_paren_type;
1530my $av_pend_colon;
1531
1532sub annotate_reset {
1533 $av_preprocessor = 0;
1534 $av_pending = '_';
1535 @av_paren_type = ('E');
1536 $av_pend_colon = 'O';
1537}
1538
1539sub annotate_values {
1540 my ($stream, $type) = @_;
1541
1542 my $res;
1543 my $var = '_' x length($stream);
1544 my $cur = $stream;
1545
1546 print "$stream\n" if ($dbg_values > 1);
1547
1548 while (length($cur)) {
1549 @av_paren_type = ('E') if ($#av_paren_type < 0);
1550 print " <" . join('', @av_paren_type) .
1551 "> <$type> <$av_pending>" if ($dbg_values > 1);
1552 if ($cur =~ /^(\s+)/o) {
1553 print "WS($1)\n" if ($dbg_values > 1);
1554 if ($1 =~ /\n/ && $av_preprocessor) {
1555 $type = pop(@av_paren_type);
1556 $av_preprocessor = 0;
1557 }
1558
1559 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1560 print "CAST($1)\n" if ($dbg_values > 1);
1561 push(@av_paren_type, $type);
1562 $type = 'c';
1563
1564 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1565 print "DECLARE($1)\n" if ($dbg_values > 1);
1566 $type = 'T';
1567
1568 } elsif ($cur =~ /^($Modifier)\s*/) {
1569 print "MODIFIER($1)\n" if ($dbg_values > 1);
1570 $type = 'T';
1571
1572 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1573 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1574 $av_preprocessor = 1;
1575 push(@av_paren_type, $type);
1576 if ($2 ne '') {
1577 $av_pending = 'N';
1578 }
1579 $type = 'E';
1580
1581 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1582 print "UNDEF($1)\n" if ($dbg_values > 1);
1583 $av_preprocessor = 1;
1584 push(@av_paren_type, $type);
1585
1586 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1587 print "PRE_START($1)\n" if ($dbg_values > 1);
1588 $av_preprocessor = 1;
1589
1590 push(@av_paren_type, $type);
1591 push(@av_paren_type, $type);
1592 $type = 'E';
1593
1594 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1595 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1596 $av_preprocessor = 1;
1597
1598 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1599
1600 $type = 'E';
1601
1602 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1603 print "PRE_END($1)\n" if ($dbg_values > 1);
1604
1605 $av_preprocessor = 1;
1606
1607 # Assume all arms of the conditional end as this
1608 # one does, and continue as if the #endif was not here.
1609 pop(@av_paren_type);
1610 push(@av_paren_type, $type);
1611 $type = 'E';
1612
1613 } elsif ($cur =~ /^(\\\n)/o) {
1614 print "PRECONT($1)\n" if ($dbg_values > 1);
1615
1616 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1617 print "ATTR($1)\n" if ($dbg_values > 1);
1618 $av_pending = $type;
1619 $type = 'N';
1620
1621 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1622 print "SIZEOF($1)\n" if ($dbg_values > 1);
1623 if (defined $2) {
1624 $av_pending = 'V';
1625 }
1626 $type = 'N';
1627
1628 } elsif ($cur =~ /^(if|while|for)\b/o) {
1629 print "COND($1)\n" if ($dbg_values > 1);
1630 $av_pending = 'E';
1631 $type = 'N';
1632
1633 } elsif ($cur =~/^(case)/o) {
1634 print "CASE($1)\n" if ($dbg_values > 1);
1635 $av_pend_colon = 'C';
1636 $type = 'N';
1637
1638 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1639 print "KEYWORD($1)\n" if ($dbg_values > 1);
1640 $type = 'N';
1641
1642 } elsif ($cur =~ /^(\()/o) {
1643 print "PAREN('$1')\n" if ($dbg_values > 1);
1644 push(@av_paren_type, $av_pending);
1645 $av_pending = '_';
1646 $type = 'N';
1647
1648 } elsif ($cur =~ /^(\))/o) {
1649 my $new_type = pop(@av_paren_type);
1650 if ($new_type ne '_') {
1651 $type = $new_type;
1652 print "PAREN('$1') -> $type\n"
1653 if ($dbg_values > 1);
1654 } else {
1655 print "PAREN('$1')\n" if ($dbg_values > 1);
1656 }
1657
1658 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1659 print "FUNC($1)\n" if ($dbg_values > 1);
1660 $type = 'V';
1661 $av_pending = 'V';
1662
1663 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1664 if (defined $2 && $type eq 'C' || $type eq 'T') {
1665 $av_pend_colon = 'B';
1666 } elsif ($type eq 'E') {
1667 $av_pend_colon = 'L';
1668 }
1669 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1670 $type = 'V';
1671
1672 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1673 print "IDENT($1)\n" if ($dbg_values > 1);
1674 $type = 'V';
1675
1676 } elsif ($cur =~ /^($Assignment)/o) {
1677 print "ASSIGN($1)\n" if ($dbg_values > 1);
1678 $type = 'N';
1679
1680 } elsif ($cur =~/^(;|{|})/) {
1681 print "END($1)\n" if ($dbg_values > 1);
1682 $type = 'E';
1683 $av_pend_colon = 'O';
1684
1685 } elsif ($cur =~/^(,)/) {
1686 print "COMMA($1)\n" if ($dbg_values > 1);
1687 $type = 'C';
1688
1689 } elsif ($cur =~ /^(\?)/o) {
1690 print "QUESTION($1)\n" if ($dbg_values > 1);
1691 $type = 'N';
1692
1693 } elsif ($cur =~ /^(:)/o) {
1694 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1695
1696 substr($var, length($res), 1, $av_pend_colon);
1697 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1698 $type = 'E';
1699 } else {
1700 $type = 'N';
1701 }
1702 $av_pend_colon = 'O';
1703
1704 } elsif ($cur =~ /^(\[)/o) {
1705 print "CLOSE($1)\n" if ($dbg_values > 1);
1706 $type = 'N';
1707
1708 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1709 my $variant;
1710
1711 print "OPV($1)\n" if ($dbg_values > 1);
1712 if ($type eq 'V') {
1713 $variant = 'B';
1714 } else {
1715 $variant = 'U';
1716 }
1717
1718 substr($var, length($res), 1, $variant);
1719 $type = 'N';
1720
1721 } elsif ($cur =~ /^($Operators)/o) {
1722 print "OP($1)\n" if ($dbg_values > 1);
1723 if ($1 ne '++' && $1 ne '--') {
1724 $type = 'N';
1725 }
1726
1727 } elsif ($cur =~ /(^.)/o) {
1728 print "C($1)\n" if ($dbg_values > 1);
1729 }
1730 if (defined $1) {
1731 $cur = substr($cur, length($1));
1732 $res .= $type x length($1);
1733 }
1734 }
1735
1736 return ($res, $var);
1737}
1738
1739sub possible {
1740 my ($possible, $line) = @_;
1741 my $notPermitted = qr{(?:
1742 ^(?:
1743 $Modifier|
1744 $Storage|
1745 $Type|
1746 DEFINE_\S+
1747 )$|
1748 ^(?:
1749 goto|
1750 return|
1751 case|
1752 else|
1753 asm|__asm__|
1754 do|
1755 \#|
1756 \#\#|
1757 )(?:\s|$)|
1758 ^(?:typedef|struct|enum)\b
1759 )}x;
1760 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1761 if ($possible !~ $notPermitted) {
1762 # Check for modifiers.
1763 $possible =~ s/\s*$Storage\s*//g;
1764 $possible =~ s/\s*$Sparse\s*//g;
1765 if ($possible =~ /^\s*$/) {
1766
1767 } elsif ($possible =~ /\s/) {
1768 $possible =~ s/\s*$Type\s*//g;
1769 for my $modifier (split(' ', $possible)) {
1770 if ($modifier !~ $notPermitted) {
1771 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001772 push(@modifierListFile, $modifier);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001773 }
1774 }
1775
1776 } else {
1777 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001778 push(@typeListFile, $possible);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001779 }
1780 build_types();
1781 } else {
1782 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1783 }
1784}
1785
1786my $prefix = '';
1787
1788sub show_type {
1789 my ($type) = @_;
1790
1791 return defined $use_type{$type} if (scalar keys %use_type > 0);
1792
1793 return !defined $ignore_type{$type};
1794}
1795
1796sub report {
1797 my ($level, $type, $msg) = @_;
1798
1799 if (!show_type($type) ||
1800 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1801 return 0;
1802 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001803 my $output = '';
1804 if (-t STDOUT && $color) {
1805 if ($level eq 'ERROR') {
1806 $output .= RED;
1807 } elsif ($level eq 'WARNING') {
1808 $output .= YELLOW;
1809 } else {
1810 $output .= GREEN;
1811 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001812 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001813 $output .= $prefix . $level . ':';
1814 if ($show_types) {
1815 $output .= BLUE if (-t STDOUT && $color);
1816 $output .= "$type:";
1817 }
1818 $output .= RESET if (-t STDOUT && $color);
1819 $output .= ' ' . $msg . "\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001820
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001821 if ($showfile) {
1822 my @lines = split("\n", $output, -1);
1823 splice(@lines, 1, 1);
1824 $output = join("\n", @lines);
1825 }
1826 $output = (split('\n', $output))[0] . "\n" if ($terse);
1827
1828 push(our @report, $output);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001829
1830 return 1;
1831}
1832
1833sub report_dump {
1834 our @report;
1835}
1836
1837sub fixup_current_range {
1838 my ($lineRef, $offset, $length) = @_;
1839
1840 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1841 my $o = $1;
1842 my $l = $2;
1843 my $no = $o + $offset;
1844 my $nl = $l + $length;
1845 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1846 }
1847}
1848
1849sub fix_inserted_deleted_lines {
1850 my ($linesRef, $insertedRef, $deletedRef) = @_;
1851
1852 my $range_last_linenr = 0;
1853 my $delta_offset = 0;
1854
1855 my $old_linenr = 0;
1856 my $new_linenr = 0;
1857
1858 my $next_insert = 0;
1859 my $next_delete = 0;
1860
1861 my @lines = ();
1862
1863 my $inserted = @{$insertedRef}[$next_insert++];
1864 my $deleted = @{$deletedRef}[$next_delete++];
1865
1866 foreach my $old_line (@{$linesRef}) {
1867 my $save_line = 1;
1868 my $line = $old_line; #don't modify the array
Stefan Reinauerc6080c62016-07-29 16:01:40 -07001869 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01001870 $delta_offset = 0;
1871 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1872 $range_last_linenr = $new_linenr;
1873 fixup_current_range(\$line, $delta_offset, 0);
1874 }
1875
1876 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1877 $deleted = @{$deletedRef}[$next_delete++];
1878 $save_line = 0;
1879 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1880 }
1881
1882 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1883 push(@lines, ${$inserted}{'LINE'});
1884 $inserted = @{$insertedRef}[$next_insert++];
1885 $new_linenr++;
1886 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1887 }
1888
1889 if ($save_line) {
1890 push(@lines, $line);
1891 $new_linenr++;
1892 }
1893
1894 $old_linenr++;
1895 }
1896
1897 return @lines;
1898}
1899
1900sub fix_insert_line {
1901 my ($linenr, $line) = @_;
1902
1903 my $inserted = {
1904 LINENR => $linenr,
1905 LINE => $line,
1906 };
1907 push(@fixed_inserted, $inserted);
1908}
1909
1910sub fix_delete_line {
1911 my ($linenr, $line) = @_;
1912
1913 my $deleted = {
1914 LINENR => $linenr,
1915 LINE => $line,
1916 };
1917
1918 push(@fixed_deleted, $deleted);
1919}
1920
1921sub ERROR {
1922 my ($type, $msg) = @_;
1923
1924 if (report("ERROR", $type, $msg)) {
1925 our $clean = 0;
1926 our $cnt_error++;
1927 return 1;
1928 }
1929 return 0;
1930}
1931sub WARN {
1932 my ($type, $msg) = @_;
1933
1934 if (report("WARNING", $type, $msg)) {
1935 our $clean = 0;
1936 our $cnt_warn++;
1937 return 1;
1938 }
1939 return 0;
1940}
1941sub CHK {
1942 my ($type, $msg) = @_;
1943
1944 if ($check && report("CHECK", $type, $msg)) {
1945 our $clean = 0;
1946 our $cnt_chk++;
1947 return 1;
1948 }
1949 return 0;
1950}
1951
1952sub check_absolute_file {
1953 my ($absolute, $herecurr) = @_;
1954 my $file = $absolute;
1955
1956 ##print "absolute<$absolute>\n";
1957
1958 # See if any suffix of this path is a path within the tree.
1959 while ($file =~ s@^[^/]*/@@) {
1960 if (-f "$root/$file") {
1961 ##print "file<$file>\n";
1962 last;
1963 }
1964 }
1965 if (! -f _) {
1966 return 0;
1967 }
1968
1969 # It is, so see if the prefix is acceptable.
1970 my $prefix = $absolute;
1971 substr($prefix, -length($file)) = '';
1972
1973 ##print "prefix<$prefix>\n";
1974 if ($prefix ne ".../") {
1975 WARN("USE_RELATIVE_PATH",
1976 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1977 }
1978}
1979
1980sub trim {
1981 my ($string) = @_;
1982
1983 $string =~ s/^\s+|\s+$//g;
1984
1985 return $string;
1986}
1987
1988sub ltrim {
1989 my ($string) = @_;
1990
1991 $string =~ s/^\s+//;
1992
1993 return $string;
1994}
1995
1996sub rtrim {
1997 my ($string) = @_;
1998
1999 $string =~ s/\s+$//;
2000
2001 return $string;
2002}
2003
2004sub string_find_replace {
2005 my ($string, $find, $replace) = @_;
2006
2007 $string =~ s/$find/$replace/g;
2008
2009 return $string;
2010}
2011
2012sub tabify {
2013 my ($leading) = @_;
2014
2015 my $source_indent = 8;
2016 my $max_spaces_before_tab = $source_indent - 1;
2017 my $spaces_to_tab = " " x $source_indent;
2018
2019 #convert leading spaces to tabs
2020 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2021 #Remove spaces before a tab
2022 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2023
2024 return "$leading";
2025}
2026
2027sub pos_last_openparen {
2028 my ($line) = @_;
2029
2030 my $pos = 0;
2031
2032 my $opens = $line =~ tr/\(/\(/;
2033 my $closes = $line =~ tr/\)/\)/;
2034
2035 my $last_openparen = 0;
2036
2037 if (($opens == 0) || ($closes >= $opens)) {
2038 return -1;
2039 }
2040
2041 my $len = length($line);
2042
2043 for ($pos = 0; $pos < $len; $pos++) {
2044 my $string = substr($line, $pos);
2045 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2046 $pos += length($1) - 1;
2047 } elsif (substr($line, $pos, 1) eq '(') {
2048 $last_openparen = $pos;
2049 } elsif (index($string, '(') == -1) {
2050 last;
2051 }
2052 }
2053
2054 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2055}
2056
2057sub process {
2058 my $filename = shift;
2059
2060 my $linenr=0;
2061 my $prevline="";
2062 my $prevrawline="";
2063 my $stashline="";
2064 my $stashrawline="";
2065
2066 my $length;
2067 my $indent;
2068 my $previndent=0;
2069 my $stashindent=0;
2070
2071 our $clean = 1;
2072 my $signoff = 0;
2073 my $is_patch = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002074 my $in_header_lines = $file ? 0 : 1;
2075 my $in_commit_log = 0; #Scanning lines before patch
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002076 my $commit_log_possible_stack_dump = 0;
2077 my $commit_log_long_line = 0;
2078 my $commit_log_has_diff = 0;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002079 my $reported_maintainer_file = 0;
2080 my $non_utf8_charset = 0;
2081
2082 my $last_blank_line = 0;
2083 my $last_coalesced_string_linenr = -1;
2084
2085 our @report = ();
2086 our $cnt_lines = 0;
2087 our $cnt_error = 0;
2088 our $cnt_warn = 0;
2089 our $cnt_chk = 0;
2090
2091 # Trace the real file/line as we go.
2092 my $realfile = '';
2093 my $realline = 0;
2094 my $realcnt = 0;
2095 my $here = '';
2096 my $in_comment = 0;
2097 my $comment_edge = 0;
2098 my $first_line = 0;
2099 my $p1_prefix = '';
2100
2101 my $prev_values = 'E';
2102
2103 # suppression flags
2104 my %suppress_ifbraces;
2105 my %suppress_whiletrailers;
2106 my %suppress_export;
2107 my $suppress_statement = 0;
2108
2109 my %signatures = ();
2110
2111 # Pre-scan the patch sanitizing the lines.
2112 # Pre-scan the patch looking for any __setup documentation.
2113 #
2114 my @setup_docs = ();
2115 my $setup_docs = 0;
2116
2117 my $camelcase_file_seeded = 0;
2118
2119 sanitise_line_reset();
2120 my $line;
2121 foreach my $rawline (@rawlines) {
2122 $linenr++;
2123 $line = $rawline;
2124
2125 push(@fixed, $rawline) if ($fix);
2126
2127 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2128 $setup_docs = 0;
2129 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
2130 $setup_docs = 1;
2131 }
2132 #next;
2133 }
2134 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2135 $realline=$1-1;
2136 if (defined $2) {
2137 $realcnt=$3+1;
2138 } else {
2139 $realcnt=1+1;
2140 }
2141 $in_comment = 0;
2142
2143 # Guestimate if this is a continuing comment. Run
2144 # the context looking for a comment "edge". If this
2145 # edge is a close comment then we must be in a comment
2146 # at context start.
2147 my $edge;
2148 my $cnt = $realcnt;
2149 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2150 next if (defined $rawlines[$ln - 1] &&
2151 $rawlines[$ln - 1] =~ /^-/);
2152 $cnt--;
2153 #print "RAW<$rawlines[$ln - 1]>\n";
2154 last if (!defined $rawlines[$ln - 1]);
2155 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2156 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2157 ($edge) = $1;
2158 last;
2159 }
2160 }
2161 if (defined $edge && $edge eq '*/') {
2162 $in_comment = 1;
2163 }
2164
2165 # Guestimate if this is a continuing comment. If this
2166 # is the start of a diff block and this line starts
2167 # ' *' then it is very likely a comment.
2168 if (!defined $edge &&
2169 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2170 {
2171 $in_comment = 1;
2172 }
2173
2174 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2175 sanitise_line_reset($in_comment);
2176
2177 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2178 # Standardise the strings and chars within the input to
2179 # simplify matching -- only bother with positive lines.
2180 $line = sanitise_line($rawline);
2181 }
2182 push(@lines, $line);
2183
2184 if ($realcnt > 1) {
2185 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2186 } else {
2187 $realcnt = 0;
2188 }
2189
2190 #print "==>$rawline\n";
2191 #print "-->$line\n";
2192
2193 if ($setup_docs && $line =~ /^\+/) {
2194 push(@setup_docs, $line);
2195 }
2196 }
2197
2198 $prefix = '';
2199
2200 $realcnt = 0;
2201 $linenr = 0;
2202 $fixlinenr = -1;
2203 foreach my $line (@lines) {
2204 $linenr++;
2205 $fixlinenr++;
2206 my $sline = $line; #copy of $line
2207 $sline =~ s/$;/ /g; #with comments as spaces
2208
2209 my $rawline = $rawlines[$linenr - 1];
2210
2211#extract the line range in the file after the patch is applied
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002212 if (!$in_commit_log &&
2213 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002214 $is_patch = 1;
2215 $first_line = $linenr + 1;
2216 $realline=$1-1;
2217 if (defined $2) {
2218 $realcnt=$3+1;
2219 } else {
2220 $realcnt=1+1;
2221 }
2222 annotate_reset();
2223 $prev_values = 'E';
2224
2225 %suppress_ifbraces = ();
2226 %suppress_whiletrailers = ();
2227 %suppress_export = ();
2228 $suppress_statement = 0;
2229 next;
2230
2231# track the line number as we move through the hunk, note that
2232# new versions of GNU diff omit the leading space on completely
2233# blank context lines so we need to count that too.
2234 } elsif ($line =~ /^( |\+|$)/) {
2235 $realline++;
2236 $realcnt-- if ($realcnt != 0);
2237
2238 # Measure the line length and indent.
2239 ($length, $indent) = line_stats($rawline);
2240
2241 # Track the previous line.
2242 ($prevline, $stashline) = ($stashline, $line);
2243 ($previndent, $stashindent) = ($stashindent, $indent);
2244 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2245
2246 #warn "line<$line>\n";
2247
2248 } elsif ($realcnt == 1) {
2249 $realcnt--;
2250 }
2251
2252 my $hunk_line = ($realcnt != 0);
2253
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002254 $here = "#$linenr: " if (!$file);
2255 $here = "#$realline: " if ($file);
2256
2257 my $found_file = 0;
2258 # extract the filename as it passes
2259 if ($line =~ /^diff --git.*?(\S+)$/) {
2260 $realfile = $1;
2261 $realfile =~ s@^([^/]*)/@@ if (!$file);
2262 $in_commit_log = 0;
2263 $found_file = 1;
2264 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2265 $realfile = $1;
2266 $realfile =~ s@^([^/]*)/@@ if (!$file);
2267 $in_commit_log = 0;
2268
2269 $p1_prefix = $1;
2270 if (!$file && $tree && $p1_prefix ne '' &&
2271 -e "$root/$p1_prefix") {
2272 WARN("PATCH_PREFIX",
2273 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2274 }
2275
2276 if ($realfile =~ m@^include/asm/@) {
2277 ERROR("MODIFIED_INCLUDE_ASM",
2278 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2279 }
2280 $found_file = 1;
2281 }
2282
Martin Rotha3cac872017-03-04 18:17:35 -07002283 my $skipme = 0;
2284 foreach (@exclude) {
2285 if ($realfile =~ m@^(?:$_/)@) {
2286 $skipme = 1;
2287 }
2288 }
2289 if ($skipme) {
2290 next;
2291 }
2292
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002293#make up the handle for any error we report on this line
2294 if ($showfile) {
2295 $prefix = "$realfile:$realline: "
2296 } elsif ($emacs) {
2297 if ($file) {
2298 $prefix = "$filename:$realline: ";
2299 } else {
2300 $prefix = "$filename:$linenr: ";
2301 }
2302 }
2303
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002304 if ($found_file) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002305 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002306 $check = 1;
2307 } else {
2308 $check = $check_orig;
2309 }
2310 next;
2311 }
2312
2313 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2314
2315 my $hereline = "$here\n$rawline\n";
2316 my $herecurr = "$here\n$rawline\n";
2317 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2318
2319 $cnt_lines++ if ($realcnt != 0);
2320
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002321# Check if the commit log has what seems like a diff which can confuse patch
2322 if ($in_commit_log && !$commit_log_has_diff &&
2323 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2324 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2325 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2326 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2327 ERROR("DIFF_IN_COMMIT_MSG",
2328 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2329 $commit_log_has_diff = 1;
2330 }
2331
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002332# Check for incorrect file permissions
2333 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2334 my $permhere = $here . "FILE: $realfile\n";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002335 if ($realfile !~ m@scripts/@ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002336 $realfile !~ /\.(py|pl|awk|sh)$/) {
2337 ERROR("EXECUTE_PERMISSIONS",
2338 "do not set execute permissions for source files\n" . $permhere);
2339 }
2340 }
2341
2342# Check the patch for a signoff:
2343 if ($line =~ /^\s*signed-off-by:/i) {
2344 $signoff++;
2345 $in_commit_log = 0;
2346 }
2347
2348# Check if MAINTAINERS is being updated. If so, there's probably no need to
2349# emit the "does MAINTAINERS need updating?" message on file add/move/delete
2350 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2351 $reported_maintainer_file = 1;
2352 }
2353
2354# Check signature styles
2355 if (!$in_header_lines &&
2356 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2357 my $space_before = $1;
2358 my $sign_off = $2;
2359 my $space_after = $3;
2360 my $email = $4;
2361 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2362
2363 if ($sign_off !~ /$signature_tags/) {
2364 WARN("BAD_SIGN_OFF",
2365 "Non-standard signature: $sign_off\n" . $herecurr);
2366 }
2367 if (defined $space_before && $space_before ne "") {
2368 if (WARN("BAD_SIGN_OFF",
2369 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2370 $fix) {
2371 $fixed[$fixlinenr] =
2372 "$ucfirst_sign_off $email";
2373 }
2374 }
2375 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2376 if (WARN("BAD_SIGN_OFF",
2377 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2378 $fix) {
2379 $fixed[$fixlinenr] =
2380 "$ucfirst_sign_off $email";
2381 }
2382
2383 }
2384 if (!defined $space_after || $space_after ne " ") {
2385 if (WARN("BAD_SIGN_OFF",
2386 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2387 $fix) {
2388 $fixed[$fixlinenr] =
2389 "$ucfirst_sign_off $email";
2390 }
2391 }
2392
2393 my ($email_name, $email_address, $comment) = parse_email($email);
2394 my $suggested_email = format_email(($email_name, $email_address));
2395 if ($suggested_email eq "") {
2396 ERROR("BAD_SIGN_OFF",
2397 "Unrecognized email address: '$email'\n" . $herecurr);
2398 } else {
2399 my $dequoted = $suggested_email;
2400 $dequoted =~ s/^"//;
2401 $dequoted =~ s/" </ </;
2402 # Don't force email to have quotes
2403 # Allow just an angle bracketed address
2404 if ("$dequoted$comment" ne $email &&
2405 "<$email_address>$comment" ne $email &&
2406 "$suggested_email$comment" ne $email) {
2407 WARN("BAD_SIGN_OFF",
2408 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2409 }
2410 }
2411
2412# Check for duplicate signatures
2413 my $sig_nospace = $line;
2414 $sig_nospace =~ s/\s//g;
2415 $sig_nospace = lc($sig_nospace);
2416 if (defined $signatures{$sig_nospace}) {
2417 WARN("BAD_SIGN_OFF",
2418 "Duplicate signature\n" . $herecurr);
2419 } else {
2420 $signatures{$sig_nospace} = 1;
2421 }
2422 }
2423
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002424# Check email subject for common tools that don't need to be mentioned
2425 if ($in_header_lines &&
2426 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2427 WARN("EMAIL_SUBJECT",
2428 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2429 }
2430
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002431# Check for old stable address
2432 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2433 ERROR("STABLE_ADDRESS",
2434 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2435 }
2436
2437# Check for unwanted Gerrit info
2438 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2439 ERROR("GERRIT_CHANGE_ID",
2440 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2441 }
2442
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002443# Check if the commit log is in a possible stack dump
2444 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2445 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2446 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2447 # timestamp
2448 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2449 # stack dump address
2450 $commit_log_possible_stack_dump = 1;
2451 }
2452
2453# Check for line lengths > 75 in commit log, warn once
2454 if ($in_commit_log && !$commit_log_long_line &&
2455 length($line) > 75 &&
2456 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2457 # file delta changes
2458 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2459 # filename then :
2460 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2461 # A Fixes: or Link: line
2462 $commit_log_possible_stack_dump)) {
2463 WARN("COMMIT_LOG_LONG_LINE",
2464 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2465 $commit_log_long_line = 1;
2466 }
2467
2468# Reset possible stack dump if a blank line is found
2469 if ($in_commit_log && $commit_log_possible_stack_dump &&
2470 $line =~ /^\s*$/) {
2471 $commit_log_possible_stack_dump = 0;
2472 }
2473
2474# Check for git id commit length and improperly formed commit descriptions
2475 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2476 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2477 ($line =~ /\b[0-9a-f]{12,40}\b/i &&
2478 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2479 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2480 my $init_char = "c";
2481 my $orig_commit = "";
2482 my $short = 1;
2483 my $long = 0;
2484 my $case = 1;
2485 my $space = 1;
2486 my $hasdesc = 0;
2487 my $hasparens = 0;
2488 my $id = '0123456789ab';
2489 my $orig_desc = "commit description";
2490 my $description = "";
2491
2492 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2493 $init_char = $1;
2494 $orig_commit = lc($2);
2495 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2496 $orig_commit = lc($1);
2497 }
2498
2499 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2500 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2501 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2502 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2503 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2504 $orig_desc = $1;
2505 $hasparens = 1;
2506 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2507 defined $rawlines[$linenr] &&
2508 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2509 $orig_desc = $1;
2510 $hasparens = 1;
2511 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2512 defined $rawlines[$linenr] &&
2513 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2514 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2515 $orig_desc = $1;
2516 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2517 $orig_desc .= " " . $1;
2518 $hasparens = 1;
2519 }
2520
2521 ($id, $description) = git_commit_info($orig_commit,
2522 $id, $orig_desc);
2523
2524 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2525 ERROR("GIT_COMMIT_ID",
2526 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2527 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002528 }
2529
2530# Check for added, moved or deleted files
2531 if (!$reported_maintainer_file && !$in_commit_log &&
2532 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2533 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2534 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2535 (defined($1) || defined($2))))) {
2536 $reported_maintainer_file = 1;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002537 WARN("FILE_PATH_CHANGES",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002538 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2539 }
2540
2541# Check for wrappage within a valid hunk of the file
2542 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2543 ERROR("CORRUPTED_PATCH",
2544 "patch seems to be corrupt (line wrapped?)\n" .
2545 $herecurr) if (!$emitted_corrupt++);
2546 }
2547
2548# Check for absolute kernel paths.
2549 if ($tree) {
2550 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2551 my $file = $1;
2552
2553 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2554 check_absolute_file($1, $herecurr)) {
2555 #
2556 } else {
2557 check_absolute_file($file, $herecurr);
2558 }
2559 }
2560 }
2561
2562# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2563 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2564 $rawline !~ m/^$UTF8*$/) {
2565 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2566
2567 my $blank = copy_spacing($rawline);
2568 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2569 my $hereptr = "$hereline$ptr\n";
2570
2571 CHK("INVALID_UTF8",
2572 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2573 }
2574
2575# Check if it's the start of a commit log
2576# (not a header line and we haven't seen the patch filename)
2577 if ($in_header_lines && $realfile =~ /^$/ &&
2578 !($rawline =~ /^\s+\S/ ||
2579 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2580 $in_header_lines = 0;
2581 $in_commit_log = 1;
2582 }
2583
2584# Check if there is UTF-8 in a commit log when a mail header has explicitly
2585# declined it, i.e defined some charset where it is missing.
2586 if ($in_header_lines &&
2587 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2588 $1 !~ /utf-8/i) {
2589 $non_utf8_charset = 1;
2590 }
2591
2592 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2593 $rawline =~ /$NON_ASCII_UTF8/) {
2594 WARN("UTF8_BEFORE_PATCH",
2595 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2596 }
2597
2598# Check for various typo / spelling mistakes
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002599 if (defined($misspellings) &&
2600 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2601 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002602 my $typo = $1;
2603 my $typo_fix = $spelling_fix{lc($typo)};
2604 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2605 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2606 my $msg_type = \&WARN;
2607 $msg_type = \&CHK if ($file);
2608 if (&{$msg_type}("TYPO_SPELLING",
2609 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2610 $fix) {
2611 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2612 }
2613 }
2614 }
2615
2616# ignore non-hunk lines and lines being removed
2617 next if (!$hunk_line || $line =~ /^-/);
2618
2619#trailing whitespace
2620 if ($line =~ /^\+.*\015/) {
2621 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2622 if (ERROR("DOS_LINE_ENDINGS",
2623 "DOS line endings\n" . $herevet) &&
2624 $fix) {
2625 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2626 }
2627 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2628 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2629 if (ERROR("TRAILING_WHITESPACE",
2630 "trailing whitespace\n" . $herevet) &&
2631 $fix) {
2632 $fixed[$fixlinenr] =~ s/\s+$//;
2633 }
2634
2635 $rpt_cleaners = 1;
2636 }
2637
2638# Check for FSF mailing addresses.
2639 if ($rawline =~ /\bwrite to the Free/i ||
2640 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2641 $rawline =~ /\b51\s+Franklin\s+St/i) {
2642 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2643 my $msg_type = \&ERROR;
2644 $msg_type = \&CHK if ($file);
2645 &{$msg_type}("FSF_MAILING_ADDRESS",
2646 "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
2647 }
2648
2649# check for Kconfig help text having a real description
2650# Only applies when adding the entry originally, after that we do not have
2651# sufficient context to determine whether it is indeed long enough.
2652 if ($realfile =~ /Kconfig/ &&
2653 $line =~ /^\+\s*config\s+/) {
2654 my $length = 0;
2655 my $cnt = $realcnt;
2656 my $ln = $linenr + 1;
2657 my $f;
2658 my $is_start = 0;
2659 my $is_end = 0;
2660 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2661 $f = $lines[$ln - 1];
2662 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2663 $is_end = $lines[$ln - 1] =~ /^\+/;
2664
2665 next if ($f =~ /^-/);
2666 last if (!$file && $f =~ /^\@\@/);
2667
2668 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2669 $is_start = 1;
2670 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2671 $length = -1;
2672 }
2673
2674 $f =~ s/^.//;
2675 $f =~ s/#.*//;
2676 $f =~ s/^\s+//;
2677 next if ($f =~ /^$/);
2678 if ($f =~ /^\s*config\s/) {
2679 $is_end = 1;
2680 last;
2681 }
2682 $length++;
2683 }
2684 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2685 WARN("CONFIG_DESCRIPTION",
2686 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2687 }
2688 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2689 }
2690
2691# discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2692 if ($realfile =~ /Kconfig/ &&
2693 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2694 WARN("CONFIG_EXPERIMENTAL",
2695 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2696 }
2697
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002698# discourage the use of boolean for type definition attributes of Kconfig options
2699 if ($realfile =~ /Kconfig/ &&
2700 $line =~ /^\+\s*\bboolean\b/) {
2701 WARN("CONFIG_TYPE_BOOLEAN",
2702 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2703 }
2704
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002705 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2706 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2707 my $flag = $1;
2708 my $replacement = {
2709 'EXTRA_AFLAGS' => 'asflags-y',
2710 'EXTRA_CFLAGS' => 'ccflags-y',
2711 'EXTRA_CPPFLAGS' => 'cppflags-y',
2712 'EXTRA_LDFLAGS' => 'ldflags-y',
2713 };
2714
2715 WARN("DEPRECATED_VARIABLE",
2716 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2717 }
2718
2719# check for DT compatible documentation
2720 if (defined $root &&
2721 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2722 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2723
2724 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2725
2726 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2727 my $vp_file = $dt_path . "vendor-prefixes.txt";
2728
2729 foreach my $compat (@compats) {
2730 my $compat2 = $compat;
2731 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2732 my $compat3 = $compat;
2733 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2734 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2735 if ( $? >> 8 ) {
2736 WARN("UNDOCUMENTED_DT_STRING",
2737 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2738 }
2739
2740 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2741 my $vendor = $1;
2742 `grep -Eq "^$vendor\\b" $vp_file`;
2743 if ( $? >> 8 ) {
2744 WARN("UNDOCUMENTED_DT_STRING",
2745 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2746 }
2747 }
2748 }
2749
2750# check we are in a valid source file if not then ignore this hunk
2751 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2752
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002753# line length limit (with some exclusions)
2754#
2755# There are a few types of lines that may extend beyond $max_line_length:
2756# logging functions like pr_info that end in a string
2757# lines with a single string
2758# #defines that are a single string
2759#
2760# There are 3 different line length message types:
2761# LONG_LINE_COMMENT a comment starts before but extends beyond $max_linelength
2762# LONG_LINE_STRING a string starts before but extends beyond $max_line_length
2763# LONG_LINE all other lines longer than $max_line_length
2764#
2765# if LONG_LINE is ignored, the other 2 types are also ignored
2766#
2767
2768 if ($line =~ /^\+/ && $length > $max_line_length) {
2769 my $msg_type = "LONG_LINE";
2770
2771 # Check the allowed long line types first
2772
2773 # logging functions that end in a string that starts
2774 # before $max_line_length
2775 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2776 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2777 $msg_type = "";
2778
2779 # lines with only strings (w/ possible termination)
2780 # #defines with only strings
2781 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2782 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
2783 $msg_type = "";
2784
2785 # Otherwise set the alternate message types
2786
2787 # a comment starts before $max_line_length
2788 } elsif ($line =~ /($;[\s$;]*)$/ &&
2789 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2790 $msg_type = "LONG_LINE_COMMENT"
2791
2792 # a quoted string starts before $max_line_length
2793 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
2794 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2795 $msg_type = "LONG_LINE_STRING"
2796 }
2797
2798 if ($msg_type ne "" &&
2799 (show_type("LONG_LINE") || show_type($msg_type))) {
2800 WARN($msg_type,
2801 "line over $max_line_length characters\n" . $herecurr);
2802 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002803 }
2804
2805# check for adding lines without a newline.
2806 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2807 WARN("MISSING_EOF_NEWLINE",
2808 "adding a line without newline at end of file\n" . $herecurr);
2809 }
2810
2811# Blackfin: use hi/lo macros
2812 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2813 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2814 my $herevet = "$here\n" . cat_vet($line) . "\n";
2815 ERROR("LO_MACRO",
2816 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2817 }
2818 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2819 my $herevet = "$here\n" . cat_vet($line) . "\n";
2820 ERROR("HI_MACRO",
2821 "use the HI() macro, not (... >> 16)\n" . $herevet);
2822 }
2823 }
2824
2825# check we are in a valid source file C or perl if not then ignore this hunk
2826 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2827
2828# at the beginning of a line any tabs must come first and anything
2829# more than 8 must use tabs.
2830 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2831 $rawline =~ /^\+\s* \s*/) {
2832 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2833 $rpt_cleaners = 1;
2834 if (ERROR("CODE_INDENT",
2835 "code indent should use tabs where possible\n" . $herevet) &&
2836 $fix) {
2837 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2838 }
2839 }
2840
2841# check for space before tabs.
2842 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2843 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2844 if (WARN("SPACE_BEFORE_TAB",
2845 "please, no space before tabs\n" . $herevet) &&
2846 $fix) {
2847 while ($fixed[$fixlinenr] =~
2848 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2849 while ($fixed[$fixlinenr] =~
2850 s/(^\+.*) +\t/$1\t/) {}
2851 }
2852 }
2853
2854# check for && or || at the start of a line
2855 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2856 CHK("LOGICAL_CONTINUATIONS",
2857 "Logical continuations should be on the previous line\n" . $hereprev);
2858 }
2859
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002860# check indentation starts on a tab stop
2861 if ($^V && $^V ge 5.10.0 &&
2862 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$))/) {
2863 my $indent = length($1);
2864 if ($indent % 8) {
2865 if (WARN("TABSTOP",
2866 "Statements should start on a tabstop\n" . $herecurr) &&
2867 $fix) {
2868 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
2869 }
2870 }
2871 }
2872
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002873# check multi-line statement indentation matches previous line
2874 if ($^V && $^V ge 5.10.0 &&
2875 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2876 $prevline =~ /^\+(\t*)(.*)$/;
2877 my $oldindent = $1;
2878 my $rest = $2;
2879
2880 my $pos = pos_last_openparen($rest);
2881 if ($pos >= 0) {
2882 $line =~ /^(\+| )([ \t]*)/;
2883 my $newindent = $2;
2884
2885 my $goodtabindent = $oldindent .
2886 "\t" x ($pos / 8) .
2887 " " x ($pos % 8);
2888 my $goodspaceindent = $oldindent . " " x $pos;
2889
2890 if ($newindent ne $goodtabindent &&
2891 $newindent ne $goodspaceindent) {
2892
2893 if (CHK("PARENTHESIS_ALIGNMENT",
2894 "Alignment should match open parenthesis\n" . $hereprev) &&
2895 $fix && $line =~ /^\+/) {
2896 $fixed[$fixlinenr] =~
2897 s/^\+[ \t]*/\+$goodtabindent/;
2898 }
2899 }
2900 }
2901 }
2902
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002903# check for space after cast like "(int) foo" or "(struct foo) bar"
2904# avoid checking a few false positives:
2905# "sizeof(<type>)" or "__alignof__(<type>)"
2906# function pointer declarations like "(*foo)(int) = bar;"
2907# structure definitions like "(struct foo) { 0 };"
2908# multiline macros that define functions
2909# known attributes or the __attribute__ keyword
2910 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2911 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002912 if (CHK("SPACING",
2913 "No space is necessary after a cast\n" . $herecurr) &&
2914 $fix) {
2915 $fixed[$fixlinenr] =~
2916 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2917 }
2918 }
2919
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002920# Block comment styles
2921# Networking with an initial /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002922 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2923 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2924 $rawline =~ /^\+[ \t]*\*/ &&
2925 $realline > 2) {
2926 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2927 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2928 }
2929
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002930# Block comments use * on subsequent lines
2931 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2932 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002933 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2934 $rawline =~ /^\+/ && #line is new
2935 $rawline !~ /^\+[ \t]*\*/) { #no leading *
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002936 WARN("BLOCK_COMMENT_STYLE",
2937 "Block comments use * on subsequent lines\n" . $hereprev);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002938 }
2939
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002940# Block comments use */ on trailing lines
2941 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002942 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2943 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2944 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
Stefan Reinauerc6080c62016-07-29 16:01:40 -07002945 WARN("BLOCK_COMMENT_STYLE",
2946 "Block comments use a trailing */ on a separate line\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01002947 }
2948
2949# check for missing blank lines after struct/union declarations
2950# with exceptions for various attributes and macros
2951 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2952 $line =~ /^\+/ &&
2953 !($line =~ /^\+\s*$/ ||
2954 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2955 $line =~ /^\+\s*MODULE_/i ||
2956 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2957 $line =~ /^\+[a-z_]*init/ ||
2958 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2959 $line =~ /^\+\s*DECLARE/ ||
2960 $line =~ /^\+\s*__setup/)) {
2961 if (CHK("LINE_SPACING",
2962 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2963 $fix) {
2964 fix_insert_line($fixlinenr, "\+");
2965 }
2966 }
2967
2968# check for multiple consecutive blank lines
2969 if ($prevline =~ /^[\+ ]\s*$/ &&
2970 $line =~ /^\+\s*$/ &&
2971 $last_blank_line != ($linenr - 1)) {
2972 if (CHK("LINE_SPACING",
2973 "Please don't use multiple blank lines\n" . $hereprev) &&
2974 $fix) {
2975 fix_delete_line($fixlinenr, $rawline);
2976 }
2977
2978 $last_blank_line = $linenr;
2979 }
2980
2981# check for missing blank lines after declarations
2982 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2983 # actual declarations
2984 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2985 # function pointer declarations
2986 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2987 # foo bar; where foo is some local typedef or #define
2988 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2989 # known declaration macros
2990 $prevline =~ /^\+\s+$declaration_macros/) &&
2991 # for "else if" which can look like "$Ident $Ident"
2992 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2993 # other possible extensions of declaration lines
2994 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2995 # not starting a section or a macro "\" extended line
2996 $prevline =~ /(?:\{\s*|\\)$/) &&
2997 # looks like a declaration
2998 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2999 # function pointer declarations
3000 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3001 # foo bar; where foo is some local typedef or #define
3002 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3003 # known declaration macros
3004 $sline =~ /^\+\s+$declaration_macros/ ||
3005 # start of struct or union or enum
3006 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3007 # start or end of block or continuation of declaration
3008 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3009 # bitfield continuation
3010 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3011 # other possible extensions of declaration lines
3012 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3013 # indentation of previous and current line are the same
3014 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3015 if (WARN("LINE_SPACING",
3016 "Missing a blank line after declarations\n" . $hereprev) &&
3017 $fix) {
3018 fix_insert_line($fixlinenr, "\+");
3019 }
3020 }
3021
3022# check for spaces at the beginning of a line.
3023# Exceptions:
3024# 1) within comments
3025# 2) indented preprocessor commands
3026# 3) hanging labels
3027 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3028 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3029 if (WARN("LEADING_SPACE",
3030 "please, no spaces at the start of a line\n" . $herevet) &&
3031 $fix) {
3032 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3033 }
3034 }
3035
3036# check we are in a valid C source file if not then ignore this hunk
3037 next if ($realfile !~ /\.(h|c)$/);
3038
3039# check indentation of any line with a bare else
3040# (but not if it is a multiple line "if (foo) return bar; else return baz;")
3041# if the previous line is a break or return and is indented 1 tab more...
3042 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3043 my $tabs = length($1) + 1;
3044 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3045 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3046 defined $lines[$linenr] &&
3047 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3048 WARN("UNNECESSARY_ELSE",
3049 "else is not generally useful after a break or return\n" . $hereprev);
3050 }
3051 }
3052
3053# check indentation of a line with a break;
3054# if the previous line is a goto or return and is indented the same # of tabs
3055 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3056 my $tabs = $1;
3057 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3058 WARN("UNNECESSARY_BREAK",
3059 "break is not useful after a goto or return\n" . $hereprev);
3060 }
3061 }
3062
3063# discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
3064 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
3065 WARN("CONFIG_EXPERIMENTAL",
3066 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
3067 }
3068
3069# check for RCS/CVS revision markers
3070 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3071 WARN("CVS_KEYWORD",
3072 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3073 }
3074
3075# Blackfin: don't use __builtin_bfin_[cs]sync
3076 if ($line =~ /__builtin_bfin_csync/) {
3077 my $herevet = "$here\n" . cat_vet($line) . "\n";
3078 ERROR("CSYNC",
3079 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
3080 }
3081 if ($line =~ /__builtin_bfin_ssync/) {
3082 my $herevet = "$here\n" . cat_vet($line) . "\n";
3083 ERROR("SSYNC",
3084 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
3085 }
3086
3087# check for old HOTPLUG __dev<foo> section markings
3088 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3089 WARN("HOTPLUG_SECTION",
3090 "Using $1 is unnecessary\n" . $herecurr);
3091 }
3092
3093# Check for potential 'bare' types
3094 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3095 $realline_next);
3096#print "LINE<$line>\n";
3097 if ($linenr >= $suppress_statement &&
3098 $realcnt && $sline =~ /.\s*\S/) {
3099 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3100 ctx_statement_block($linenr, $realcnt, 0);
3101 $stat =~ s/\n./\n /g;
3102 $cond =~ s/\n./\n /g;
3103
3104#print "linenr<$linenr> <$stat>\n";
3105 # If this statement has no statement boundaries within
3106 # it there is no point in retrying a statement scan
3107 # until we hit end of it.
3108 my $frag = $stat; $frag =~ s/;+\s*$//;
3109 if ($frag !~ /(?:{|;)/) {
3110#print "skip<$line_nr_next>\n";
3111 $suppress_statement = $line_nr_next;
3112 }
3113
3114 # Find the real next line.
3115 $realline_next = $line_nr_next;
3116 if (defined $realline_next &&
3117 (!defined $lines[$realline_next - 1] ||
3118 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3119 $realline_next++;
3120 }
3121
3122 my $s = $stat;
3123 $s =~ s/{.*$//s;
3124
3125 # Ignore goto labels.
3126 if ($s =~ /$Ident:\*$/s) {
3127
3128 # Ignore functions being called
3129 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3130
3131 } elsif ($s =~ /^.\s*else\b/s) {
3132
3133 # declarations always start with types
3134 } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
3135 my $type = $1;
3136 $type =~ s/\s+/ /g;
3137 possible($type, "A:" . $s);
3138
3139 # definitions in global scope can only start with types
3140 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3141 possible($1, "B:" . $s);
3142 }
3143
3144 # any (foo ... *) is a pointer cast, and foo is a type
3145 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3146 possible($1, "C:" . $s);
3147 }
3148
3149 # Check for any sort of function declaration.
3150 # int foo(something bar, other baz);
3151 # void (*store_gdt)(x86_descr_ptr *);
3152 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3153 my ($name_len) = length($1);
3154
3155 my $ctx = $s;
3156 substr($ctx, 0, $name_len + 1, '');
3157 $ctx =~ s/\)[^\)]*$//;
3158
3159 for my $arg (split(/\s*,\s*/, $ctx)) {
3160 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3161
3162 possible($1, "D:" . $s);
3163 }
3164 }
3165 }
3166
3167 }
3168
3169#
3170# Checks which may be anchored in the context.
3171#
3172
3173# Check for switch () and associated case and default
3174# statements should be at the same indent.
3175 if ($line=~/\bswitch\s*\(.*\)/) {
3176 my $err = '';
3177 my $sep = '';
3178 my @ctx = ctx_block_outer($linenr, $realcnt);
3179 shift(@ctx);
3180 for my $ctx (@ctx) {
3181 my ($clen, $cindent) = line_stats($ctx);
3182 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3183 $indent != $cindent) {
3184 $err .= "$sep$ctx\n";
3185 $sep = '';
3186 } else {
3187 $sep = "[...]\n";
3188 }
3189 }
3190 if ($err ne '') {
3191 ERROR("SWITCH_CASE_INDENT_LEVEL",
3192 "switch and case should be at the same indent\n$hereline$err");
3193 }
3194 }
3195
3196# if/while/etc brace do not go on next line, unless defining a do while loop,
3197# or if that brace on the next line is for something else
3198 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3199 my $pre_ctx = "$1$2";
3200
3201 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3202
3203 if ($line =~ /^\+\t{6,}/) {
3204 WARN("DEEP_INDENTATION",
3205 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3206 }
3207
3208 my $ctx_cnt = $realcnt - $#ctx - 1;
3209 my $ctx = join("\n", @ctx);
3210
3211 my $ctx_ln = $linenr;
3212 my $ctx_skip = $realcnt;
3213
3214 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3215 defined $lines[$ctx_ln - 1] &&
3216 $lines[$ctx_ln - 1] =~ /^-/)) {
3217 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3218 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3219 $ctx_ln++;
3220 }
3221
3222 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3223 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3224
3225 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3226 ERROR("OPEN_BRACE",
3227 "that open brace { should be on the previous line\n" .
3228 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3229 }
3230 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3231 $ctx =~ /\)\s*\;\s*$/ &&
3232 defined $lines[$ctx_ln - 1])
3233 {
3234 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3235 if ($nindent > $indent) {
3236 WARN("TRAILING_SEMICOLON",
3237 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3238 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3239 }
3240 }
3241 }
3242
3243# Check relative indent for conditionals and blocks.
3244 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3245 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3246 ctx_statement_block($linenr, $realcnt, 0)
3247 if (!defined $stat);
3248 my ($s, $c) = ($stat, $cond);
3249
3250 substr($s, 0, length($c), '');
3251
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003252 # remove inline comments
3253 $s =~ s/$;/ /g;
3254 $c =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003255
3256 # Find out how long the conditional actually is.
3257 my @newlines = ($c =~ /\n/gs);
3258 my $cond_lines = 1 + $#newlines;
3259
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003260 # Make sure we remove the line prefixes as we have
3261 # none on the first line, and are going to readd them
3262 # where necessary.
3263 $s =~ s/\n./\n/gs;
3264 while ($s =~ /\n\s+\\\n/) {
3265 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3266 }
3267
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003268 # We want to check the first line inside the block
3269 # starting at the end of the conditional, so remove:
3270 # 1) any blank line termination
3271 # 2) any opening brace { on end of the line
3272 # 3) any do (...) {
3273 my $continuation = 0;
3274 my $check = 0;
3275 $s =~ s/^.*\bdo\b//;
3276 $s =~ s/^\s*{//;
3277 if ($s =~ s/^\s*\\//) {
3278 $continuation = 1;
3279 }
3280 if ($s =~ s/^\s*?\n//) {
3281 $check = 1;
3282 $cond_lines++;
3283 }
3284
3285 # Also ignore a loop construct at the end of a
3286 # preprocessor statement.
3287 if (($prevline =~ /^.\s*#\s*define\s/ ||
3288 $prevline =~ /\\\s*$/) && $continuation == 0) {
3289 $check = 0;
3290 }
3291
3292 my $cond_ptr = -1;
3293 $continuation = 0;
3294 while ($cond_ptr != $cond_lines) {
3295 $cond_ptr = $cond_lines;
3296
3297 # If we see an #else/#elif then the code
3298 # is not linear.
3299 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3300 $check = 0;
3301 }
3302
3303 # Ignore:
3304 # 1) blank lines, they should be at 0,
3305 # 2) preprocessor lines, and
3306 # 3) labels.
3307 if ($continuation ||
3308 $s =~ /^\s*?\n/ ||
3309 $s =~ /^\s*#\s*?/ ||
3310 $s =~ /^\s*$Ident\s*:/) {
3311 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3312 if ($s =~ s/^.*?\n//) {
3313 $cond_lines++;
3314 }
3315 }
3316 }
3317
3318 my (undef, $sindent) = line_stats("+" . $s);
3319 my $stat_real = raw_line($linenr, $cond_lines);
3320
3321 # Check if either of these lines are modified, else
3322 # this is not this patch's fault.
3323 if (!defined($stat_real) ||
3324 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3325 $check = 0;
3326 }
3327 if (defined($stat_real) && $cond_lines > 1) {
3328 $stat_real = "[...]\n$stat_real";
3329 }
3330
3331 #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
3332
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003333 if ($check && $s ne '' &&
3334 (($sindent % 8) != 0 ||
3335 ($sindent < $indent) ||
3336 ($sindent > $indent + 8))) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003337 WARN("SUSPECT_CODE_INDENT",
3338 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3339 }
3340 }
3341
3342 # Track the 'values' across context and added lines.
3343 my $opline = $line; $opline =~ s/^./ /;
3344 my ($curr_values, $curr_vars) =
3345 annotate_values($opline . "\n", $prev_values);
3346 $curr_values = $prev_values . $curr_values;
3347 if ($dbg_values) {
3348 my $outline = $opline; $outline =~ s/\t/ /g;
3349 print "$linenr > .$outline\n";
3350 print "$linenr > $curr_values\n";
3351 print "$linenr > $curr_vars\n";
3352 }
3353 $prev_values = substr($curr_values, -1);
3354
3355#ignore lines not being added
3356 next if ($line =~ /^[^\+]/);
3357
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003358# check for declarations of signed or unsigned without int
3359 while ($line =~ m{($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3360 my $type = $1;
3361 my $var = $2;
3362 $var = "" if (!defined $var);
3363 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3364 my $sign = $1;
3365 my $pointer = $2;
3366
3367 $pointer = "" if (!defined $pointer);
3368
3369 if (WARN("UNSPECIFIED_INT",
3370 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3371 $fix) {
3372 my $decl = trim($sign) . " int ";
3373 my $comp_pointer = $pointer;
3374 $comp_pointer =~ s/\s//g;
3375 $decl .= $comp_pointer;
3376 $decl = rtrim($decl) if ($var eq "");
3377 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3378 }
3379 }
3380 }
3381
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003382# TEST: allow direct testing of the type matcher.
3383 if ($dbg_type) {
3384 if ($line =~ /^.\s*$Declare\s*$/) {
3385 ERROR("TEST_TYPE",
3386 "TEST: is type\n" . $herecurr);
3387 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3388 ERROR("TEST_NOT_TYPE",
3389 "TEST: is not type ($1 is)\n". $herecurr);
3390 }
3391 next;
3392 }
3393# TEST: allow direct testing of the attribute matcher.
3394 if ($dbg_attr) {
3395 if ($line =~ /^.\s*$Modifier\s*$/) {
3396 ERROR("TEST_ATTR",
3397 "TEST: is attr\n" . $herecurr);
3398 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3399 ERROR("TEST_NOT_ATTR",
3400 "TEST: is not attr ($1 is)\n". $herecurr);
3401 }
3402 next;
3403 }
3404
3405# check for initialisation to aggregates open brace on the next line
3406 if ($line =~ /^.\s*{/ &&
3407 $prevline =~ /(?:^|[^=])=\s*$/) {
3408 if (ERROR("OPEN_BRACE",
3409 "that open brace { should be on the previous line\n" . $hereprev) &&
3410 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3411 fix_delete_line($fixlinenr - 1, $prevrawline);
3412 fix_delete_line($fixlinenr, $rawline);
3413 my $fixedline = $prevrawline;
3414 $fixedline =~ s/\s*=\s*$/ = {/;
3415 fix_insert_line($fixlinenr, $fixedline);
3416 $fixedline = $line;
3417 $fixedline =~ s/^(.\s*){\s*/$1/;
3418 fix_insert_line($fixlinenr, $fixedline);
3419 }
3420 }
3421
3422#
3423# Checks which are anchored on the added line.
3424#
3425
3426# check for malformed paths in #include statements (uses RAW line)
3427 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3428 my $path = $1;
3429 if ($path =~ m{//}) {
3430 ERROR("MALFORMED_INCLUDE",
3431 "malformed #include filename\n" . $herecurr);
3432 }
3433 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3434 ERROR("UAPI_INCLUDE",
3435 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3436 }
3437 }
3438
3439# no C99 // comments
3440 if ($line =~ m{//}) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003441 if (ERROR("C99_COMMENTS",
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003442 "do not use C99 // comments\n" . $herecurr) &&
3443 $fix) {
3444 my $line = $fixed[$fixlinenr];
3445 if ($line =~ /\/\/(.*)$/) {
3446 my $comment = trim($1);
3447 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3448 }
3449 }
3450 }
3451 # Remove C99 comments.
3452 $line =~ s@//.*@@;
3453 $opline =~ s@//.*@@;
3454
3455# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3456# the whole statement.
3457#print "APW <$lines[$realline_next - 1]>\n";
3458 if (defined $realline_next &&
3459 exists $lines[$realline_next - 1] &&
3460 !defined $suppress_export{$realline_next} &&
3461 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3462 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3463 # Handle definitions which produce identifiers with
3464 # a prefix:
3465 # XXX(foo);
3466 # EXPORT_SYMBOL(something_foo);
3467 my $name = $1;
3468 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3469 $name =~ /^${Ident}_$2/) {
3470#print "FOO C name<$name>\n";
3471 $suppress_export{$realline_next} = 1;
3472
3473 } elsif ($stat !~ /(?:
3474 \n.}\s*$|
3475 ^.DEFINE_$Ident\(\Q$name\E\)|
3476 ^.DECLARE_$Ident\(\Q$name\E\)|
3477 ^.LIST_HEAD\(\Q$name\E\)|
3478 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3479 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3480 )/x) {
3481#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3482 $suppress_export{$realline_next} = 2;
3483 } else {
3484 $suppress_export{$realline_next} = 1;
3485 }
3486 }
3487 if (!defined $suppress_export{$linenr} &&
3488 $prevline =~ /^.\s*$/ &&
3489 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3490 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3491#print "FOO B <$lines[$linenr - 1]>\n";
3492 $suppress_export{$linenr} = 2;
3493 }
3494 if (defined $suppress_export{$linenr} &&
3495 $suppress_export{$linenr} == 2) {
3496 WARN("EXPORT_SYMBOL",
3497 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3498 }
3499
3500# check for global initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003501 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003502 if (ERROR("GLOBAL_INITIALISERS",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003503 "do not initialise globals to $1\n" . $herecurr) &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003504 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003505 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003506 }
3507 }
3508# check for static initialisers.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003509 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003510 if (ERROR("INITIALISED_STATIC",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003511 "do not initialise statics to $1\n" .
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003512 $herecurr) &&
3513 $fix) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003514 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003515 }
3516 }
3517
3518# check for misordered declarations of char/short/int/long with signed/unsigned
3519 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3520 my $tmp = trim($1);
3521 WARN("MISORDERED_TYPE",
3522 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3523 }
3524
3525# check for static const char * arrays.
3526 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3527 WARN("STATIC_CONST_CHAR_ARRAY",
3528 "static const char * array should probably be static const char * const\n" .
3529 $herecurr);
3530 }
3531
3532# check for static char foo[] = "bar" declarations.
3533 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3534 WARN("STATIC_CONST_CHAR_ARRAY",
3535 "static char array declaration should probably be static const char\n" .
3536 $herecurr);
3537 }
3538
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003539# check for const <foo> const where <foo> is not a pointer or array type
3540 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3541 my $found = $1;
3542 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3543 WARN("CONST_CONST",
3544 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3545 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3546 WARN("CONST_CONST",
3547 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3548 }
3549 }
3550
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003551# check for non-global char *foo[] = {"bar", ...} declarations.
3552 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3553 WARN("STATIC_CONST_CHAR_ARRAY",
3554 "char * array declaration might be better as static const\n" .
3555 $herecurr);
3556 }
3557
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003558# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3559 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3560 my $array = $1;
3561 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3562 my $array_div = $1;
3563 if (WARN("ARRAY_SIZE",
3564 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3565 $fix) {
3566 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3567 }
3568 }
3569 }
3570
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003571# check for function declarations without arguments like "int foo()"
3572 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3573 if (ERROR("FUNCTION_WITHOUT_ARGS",
3574 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3575 $fix) {
3576 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3577 }
3578 }
3579
3580# check for uses of DEFINE_PCI_DEVICE_TABLE
3581 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3582 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3583 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3584 $fix) {
3585 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3586 }
3587 }
3588
3589# check for new typedefs, only function parameters and sparse annotations
3590# make sense.
3591 if ($line =~ /\btypedef\s/ &&
3592 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3593 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3594 $line !~ /\b$typeTypedefs\b/ &&
3595 $line !~ /\b__bitwise(?:__|)\b/) {
3596 WARN("NEW_TYPEDEFS",
3597 "do not add new typedefs\n" . $herecurr);
3598 }
3599
3600# * goes on variable not on type
3601 # (char*[ const])
3602 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3603 #print "AA<$1>\n";
3604 my ($ident, $from, $to) = ($1, $2, $2);
3605
3606 # Should start with a space.
3607 $to =~ s/^(\S)/ $1/;
3608 # Should not end with a space.
3609 $to =~ s/\s+$//;
3610 # '*'s should not have spaces between.
3611 while ($to =~ s/\*\s+\*/\*\*/) {
3612 }
3613
3614## print "1: from<$from> to<$to> ident<$ident>\n";
3615 if ($from ne $to) {
3616 if (ERROR("POINTER_LOCATION",
3617 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3618 $fix) {
3619 my $sub_from = $ident;
3620 my $sub_to = $ident;
3621 $sub_to =~ s/\Q$from\E/$to/;
3622 $fixed[$fixlinenr] =~
3623 s@\Q$sub_from\E@$sub_to@;
3624 }
3625 }
3626 }
3627 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3628 #print "BB<$1>\n";
3629 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3630
3631 # Should start with a space.
3632 $to =~ s/^(\S)/ $1/;
3633 # Should not end with a space.
3634 $to =~ s/\s+$//;
3635 # '*'s should not have spaces between.
3636 while ($to =~ s/\*\s+\*/\*\*/) {
3637 }
3638 # Modifiers should have spaces.
3639 $to =~ s/(\b$Modifier$)/$1 /;
3640
3641## print "2: from<$from> to<$to> ident<$ident>\n";
3642 if ($from ne $to && $ident !~ /^$Modifier$/) {
3643 if (ERROR("POINTER_LOCATION",
3644 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3645 $fix) {
3646
3647 my $sub_from = $match;
3648 my $sub_to = $match;
3649 $sub_to =~ s/\Q$from\E/$to/;
3650 $fixed[$fixlinenr] =~
3651 s@\Q$sub_from\E@$sub_to@;
3652 }
3653 }
3654 }
3655
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003656# avoid BUG() or BUG_ON()
3657 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3658 my $msg_type = \&WARN;
3659 $msg_type = \&CHK if ($file);
3660 &{$msg_type}("AVOID_BUG",
3661 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3662 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003663
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003664# avoid LINUX_VERSION_CODE
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003665 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3666 WARN("LINUX_VERSION_CODE",
3667 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3668 }
3669
3670# check for uses of printk_ratelimit
3671 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3672 WARN("PRINTK_RATELIMITED",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003673 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003674 }
3675
3676# printk should use KERN_* levels. Note that follow on printk's on the
3677# same line do not need a level, so we use the current block context
3678# to try and find and validate the current printk. In summary the current
3679# printk includes all preceding printk's which have no newline on the end.
3680# we assume the first bad printk is the one to report.
3681 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3682 my $ok = 0;
3683 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3684 #print "CHECK<$lines[$ln - 1]\n";
3685 # we have a preceding printk if it ends
3686 # with "\n" ignore it, else it is to blame
3687 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3688 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3689 $ok = 1;
3690 }
3691 last;
3692 }
3693 }
3694 if ($ok == 0) {
3695 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3696 "printk() should include KERN_ facility level\n" . $herecurr);
3697 }
3698 }
3699
3700 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3701 my $orig = $1;
3702 my $level = lc($orig);
3703 $level = "warn" if ($level eq "warning");
3704 my $level2 = $level;
3705 $level2 = "dbg" if ($level eq "debug");
3706 WARN("PREFER_PR_LEVEL",
3707 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3708 }
3709
3710 if ($line =~ /\bpr_warning\s*\(/) {
3711 if (WARN("PREFER_PR_LEVEL",
3712 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3713 $fix) {
3714 $fixed[$fixlinenr] =~
3715 s/\bpr_warning\b/pr_warn/;
3716 }
3717 }
3718
3719 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3720 my $orig = $1;
3721 my $level = lc($orig);
3722 $level = "warn" if ($level eq "warning");
3723 $level = "dbg" if ($level eq "debug");
3724 WARN("PREFER_DEV_LEVEL",
3725 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3726 }
3727
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003728# ENOSYS means "bad syscall nr" and nothing else. This will have a small
3729# number of false positives, but assembly files are not checked, so at
3730# least the arch entry code will not trigger this warning.
3731 if ($line =~ /\bENOSYS\b/) {
3732 WARN("ENOSYS",
3733 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
3734 }
3735
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003736# function brace can't be on same line, except for #defines of do while,
3737# or if closed on same line
3738 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
Martin Roth010905e2017-03-04 19:28:37 -07003739 ($line!~/struct.*__attribute__\(\(.*\)\)/) and
Alexander Couzensebef00f2016-04-11 00:52:01 +02003740 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003741 if (ERROR("OPEN_BRACE",
3742 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3743 $fix) {
3744 fix_delete_line($fixlinenr, $rawline);
3745 my $fixed_line = $rawline;
3746 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3747 my $line1 = $1;
3748 my $line2 = $2;
3749 fix_insert_line($fixlinenr, ltrim($line1));
3750 fix_insert_line($fixlinenr, "\+{");
3751 if ($line2 !~ /^\s*$/) {
3752 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3753 }
3754 }
3755 }
3756
3757# open braces for enum, union and struct go on the same line.
3758 if ($line =~ /^.\s*{/ &&
3759 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3760 if (ERROR("OPEN_BRACE",
3761 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3762 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3763 fix_delete_line($fixlinenr - 1, $prevrawline);
3764 fix_delete_line($fixlinenr, $rawline);
3765 my $fixedline = rtrim($prevrawline) . " {";
3766 fix_insert_line($fixlinenr, $fixedline);
3767 $fixedline = $rawline;
3768 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3769 if ($fixedline !~ /^\+\s*$/) {
3770 fix_insert_line($fixlinenr, $fixedline);
3771 }
3772 }
3773 }
3774
3775# missing space after union, struct or enum definition
3776 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3777 if (WARN("SPACING",
3778 "missing space after $1 definition\n" . $herecurr) &&
3779 $fix) {
3780 $fixed[$fixlinenr] =~
3781 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3782 }
3783 }
3784
3785# Function pointer declarations
3786# check spacing between type, funcptr, and args
3787# canonical declaration is "type (*funcptr)(args...)"
3788 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3789 my $declare = $1;
3790 my $pre_pointer_space = $2;
3791 my $post_pointer_space = $3;
3792 my $funcname = $4;
3793 my $post_funcname_space = $5;
3794 my $pre_args_space = $6;
3795
3796# the $Declare variable will capture all spaces after the type
3797# so check it for a missing trailing missing space but pointer return types
3798# don't need a space so don't warn for those.
3799 my $post_declare_space = "";
3800 if ($declare =~ /(\s+)$/) {
3801 $post_declare_space = $1;
3802 $declare = rtrim($declare);
3803 }
3804 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3805 WARN("SPACING",
3806 "missing space after return type\n" . $herecurr);
3807 $post_declare_space = " ";
3808 }
3809
3810# unnecessary space "type (*funcptr)(args...)"
3811# This test is not currently implemented because these declarations are
3812# equivalent to
3813# int foo(int bar, ...)
3814# and this is form shouldn't/doesn't generate a checkpatch warning.
3815#
3816# elsif ($declare =~ /\s{2,}$/) {
3817# WARN("SPACING",
3818# "Multiple spaces after return type\n" . $herecurr);
3819# }
3820
3821# unnecessary space "type ( *funcptr)(args...)"
3822 if (defined $pre_pointer_space &&
3823 $pre_pointer_space =~ /^\s/) {
3824 WARN("SPACING",
3825 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3826 }
3827
3828# unnecessary space "type (* funcptr)(args...)"
3829 if (defined $post_pointer_space &&
3830 $post_pointer_space =~ /^\s/) {
3831 WARN("SPACING",
3832 "Unnecessary space before function pointer name\n" . $herecurr);
3833 }
3834
3835# unnecessary space "type (*funcptr )(args...)"
3836 if (defined $post_funcname_space &&
3837 $post_funcname_space =~ /^\s/) {
3838 WARN("SPACING",
3839 "Unnecessary space after function pointer name\n" . $herecurr);
3840 }
3841
3842# unnecessary space "type (*funcptr) (args...)"
3843 if (defined $pre_args_space &&
3844 $pre_args_space =~ /^\s/) {
3845 WARN("SPACING",
3846 "Unnecessary space before function pointer arguments\n" . $herecurr);
3847 }
3848
3849 if (show_type("SPACING") && $fix) {
3850 $fixed[$fixlinenr] =~
3851 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3852 }
3853 }
3854
3855# check for spacing round square brackets; allowed:
3856# 1. with a type on the left -- int [] a;
3857# 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3858# 3. inside a curly brace -- = { [0...10] = 5 }
Martin Rothab9395f2016-08-29 10:39:30 -06003859# 4. in an extended asm instruction -- : [r0]"r"(r0)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003860 while ($line =~ /(.*?\s)\[/g) {
3861 my ($where, $prefix) = ($-[1], $1);
3862 if ($prefix !~ /$Type\s+$/ &&
3863 ($where != 0 || $prefix !~ /^.\s+$/) &&
Martin Rothab9395f2016-08-29 10:39:30 -06003864 $prefix !~ /[{,:]\s+$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003865 if (ERROR("BRACKET_SPACE",
3866 "space prohibited before open square bracket '['\n" . $herecurr) &&
3867 $fix) {
3868 $fixed[$fixlinenr] =~
3869 s/^(\+.*?)\s+\[/$1\[/;
3870 }
3871 }
3872 }
3873
3874# check for spaces between functions and their parentheses.
3875 while ($line =~ /($Ident)\s+\(/g) {
3876 my $name = $1;
3877 my $ctx_before = substr($line, 0, $-[1]);
3878 my $ctx = "$ctx_before$name";
3879
3880 # Ignore those directives where spaces _are_ permitted.
3881 if ($name =~ /^(?:
3882 if|for|while|switch|return|case|
3883 volatile|__volatile__|
3884 __attribute__|format|__extension__|
3885 asm|__asm__)$/x)
3886 {
3887 # cpp #define statements have non-optional spaces, ie
3888 # if there is a space between the name and the open
3889 # parenthesis it is simply not a parameter group.
3890 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3891
3892 # cpp #elif statement condition may start with a (
3893 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3894
3895 # If this whole things ends with a type its most
3896 # likely a typedef for a function.
3897 } elsif ($ctx =~ /$Type$/) {
3898
3899 } else {
3900 if (WARN("SPACING",
3901 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3902 $fix) {
3903 $fixed[$fixlinenr] =~
3904 s/\b$name\s+\(/$name\(/;
3905 }
3906 }
3907 }
3908
3909# Check operator spacing.
3910 if (!($line=~/\#\s*include/)) {
3911 my $fixed_line = "";
3912 my $line_fixed = 0;
3913
3914 my $ops = qr{
3915 <<=|>>=|<=|>=|==|!=|
3916 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3917 =>|->|<<|>>|<|>|=|!|~|
3918 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3919 \?:|\?|:
3920 }x;
3921 my @elements = split(/($ops|;)/, $opline);
3922
3923## print("element count: <" . $#elements . ">\n");
3924## foreach my $el (@elements) {
3925## print("el: <$el>\n");
3926## }
3927
3928 my @fix_elements = ();
3929 my $off = 0;
3930
3931 foreach my $el (@elements) {
3932 push(@fix_elements, substr($rawline, $off, length($el)));
3933 $off += length($el);
3934 }
3935
3936 $off = 0;
3937
3938 my $blank = copy_spacing($opline);
3939 my $last_after = -1;
3940
3941 for (my $n = 0; $n < $#elements; $n += 2) {
3942
3943 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3944
3945## print("n: <$n> good: <$good>\n");
3946
3947 $off += length($elements[$n]);
3948
3949 # Pick up the preceding and succeeding characters.
3950 my $ca = substr($opline, 0, $off);
3951 my $cc = '';
3952 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3953 $cc = substr($opline, $off + length($elements[$n + 1]));
3954 }
3955 my $cb = "$ca$;$cc";
3956
3957 my $a = '';
3958 $a = 'V' if ($elements[$n] ne '');
3959 $a = 'W' if ($elements[$n] =~ /\s$/);
3960 $a = 'C' if ($elements[$n] =~ /$;$/);
3961 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3962 $a = 'O' if ($elements[$n] eq '');
3963 $a = 'E' if ($ca =~ /^\s*$/);
3964
3965 my $op = $elements[$n + 1];
3966
3967 my $c = '';
3968 if (defined $elements[$n + 2]) {
3969 $c = 'V' if ($elements[$n + 2] ne '');
3970 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3971 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3972 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3973 $c = 'O' if ($elements[$n + 2] eq '');
3974 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3975 } else {
3976 $c = 'E';
3977 }
3978
3979 my $ctx = "${a}x${c}";
3980
3981 my $at = "(ctx:$ctx)";
3982
3983 my $ptr = substr($blank, 0, $off) . "^";
3984 my $hereptr = "$hereline$ptr\n";
3985
3986 # Pull out the value of this operator.
3987 my $op_type = substr($curr_values, $off + 1, 1);
3988
3989 # Get the full operator variant.
3990 my $opv = $op . substr($curr_vars, $off, 1);
3991
3992 # Ignore operators passed as parameters.
3993 if ($op_type ne 'V' &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07003994 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01003995
3996# # Ignore comments
3997# } elsif ($op =~ /^$;+$/) {
3998
3999 # ; should have either the end of line or a space or \ after it
4000 } elsif ($op eq ';') {
4001 if ($ctx !~ /.x[WEBC]/ &&
4002 $cc !~ /^\\/ && $cc !~ /^;/) {
4003 if (ERROR("SPACING",
4004 "space required after that '$op' $at\n" . $hereptr)) {
4005 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4006 $line_fixed = 1;
4007 }
4008 }
4009
4010 # // is a comment
4011 } elsif ($op eq '//') {
4012
4013 # : when part of a bitfield
4014 } elsif ($opv eq ':B') {
4015 # skip the bitfield test for now
4016
4017 # No spaces for:
4018 # ->
4019 } elsif ($op eq '->') {
4020 if ($ctx =~ /Wx.|.xW/) {
4021 if (ERROR("SPACING",
4022 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4023 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4024 if (defined $fix_elements[$n + 2]) {
4025 $fix_elements[$n + 2] =~ s/^\s+//;
4026 }
4027 $line_fixed = 1;
4028 }
4029 }
4030
4031 # , must not have a space before and must have a space on the right.
4032 } elsif ($op eq ',') {
4033 my $rtrim_before = 0;
4034 my $space_after = 0;
4035 if ($ctx =~ /Wx./) {
4036 if (ERROR("SPACING",
4037 "space prohibited before that '$op' $at\n" . $hereptr)) {
4038 $line_fixed = 1;
4039 $rtrim_before = 1;
4040 }
4041 }
4042 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4043 if (ERROR("SPACING",
4044 "space required after that '$op' $at\n" . $hereptr)) {
4045 $line_fixed = 1;
4046 $last_after = $n;
4047 $space_after = 1;
4048 }
4049 }
4050 if ($rtrim_before || $space_after) {
4051 if ($rtrim_before) {
4052 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4053 } else {
4054 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4055 }
4056 if ($space_after) {
4057 $good .= " ";
4058 }
4059 }
4060
4061 # '*' as part of a type definition -- reported already.
4062 } elsif ($opv eq '*_') {
4063 #warn "'*' is part of type\n";
4064
4065 # unary operators should have a space before and
4066 # none after. May be left adjacent to another
4067 # unary operator, or a cast
4068 } elsif ($op eq '!' || $op eq '~' ||
4069 $opv eq '*U' || $opv eq '-U' ||
4070 $opv eq '&U' || $opv eq '&&U') {
4071 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4072 if (ERROR("SPACING",
4073 "space required before that '$op' $at\n" . $hereptr)) {
4074 if ($n != $last_after + 2) {
4075 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4076 $line_fixed = 1;
4077 }
4078 }
4079 }
4080 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4081 # A unary '*' may be const
4082
4083 } elsif ($ctx =~ /.xW/) {
4084 if (ERROR("SPACING",
4085 "space prohibited after that '$op' $at\n" . $hereptr)) {
4086 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4087 if (defined $fix_elements[$n + 2]) {
4088 $fix_elements[$n + 2] =~ s/^\s+//;
4089 }
4090 $line_fixed = 1;
4091 }
4092 }
4093
4094 # unary ++ and unary -- are allowed no space on one side.
4095 } elsif ($op eq '++' or $op eq '--') {
4096 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4097 if (ERROR("SPACING",
4098 "space required one side of that '$op' $at\n" . $hereptr)) {
4099 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4100 $line_fixed = 1;
4101 }
4102 }
4103 if ($ctx =~ /Wx[BE]/ ||
4104 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4105 if (ERROR("SPACING",
4106 "space prohibited before that '$op' $at\n" . $hereptr)) {
4107 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4108 $line_fixed = 1;
4109 }
4110 }
4111 if ($ctx =~ /ExW/) {
4112 if (ERROR("SPACING",
4113 "space prohibited after that '$op' $at\n" . $hereptr)) {
4114 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4115 if (defined $fix_elements[$n + 2]) {
4116 $fix_elements[$n + 2] =~ s/^\s+//;
4117 }
4118 $line_fixed = 1;
4119 }
4120 }
4121
4122 # << and >> may either have or not have spaces both sides
4123 } elsif ($op eq '<<' or $op eq '>>' or
4124 $op eq '&' or $op eq '^' or $op eq '|' or
4125 $op eq '+' or $op eq '-' or
4126 $op eq '*' or $op eq '/' or
4127 $op eq '%')
4128 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004129 if ($check) {
4130 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4131 if (CHK("SPACING",
4132 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4133 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4134 $fix_elements[$n + 2] =~ s/^\s+//;
4135 $line_fixed = 1;
4136 }
4137 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4138 if (CHK("SPACING",
4139 "space preferred before that '$op' $at\n" . $hereptr)) {
4140 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4141 $line_fixed = 1;
4142 }
4143 }
4144 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004145 if (ERROR("SPACING",
4146 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4147 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4148 if (defined $fix_elements[$n + 2]) {
4149 $fix_elements[$n + 2] =~ s/^\s+//;
4150 }
4151 $line_fixed = 1;
4152 }
4153 }
4154
4155 # A colon needs no spaces before when it is
4156 # terminating a case value or a label.
4157 } elsif ($opv eq ':C' || $opv eq ':L') {
4158 if ($ctx =~ /Wx./) {
4159 if (ERROR("SPACING",
4160 "space prohibited before that '$op' $at\n" . $hereptr)) {
4161 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4162 $line_fixed = 1;
4163 }
4164 }
4165
4166 # All the others need spaces both sides.
4167 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4168 my $ok = 0;
4169
4170 # Ignore email addresses <foo@bar>
4171 if (($op eq '<' &&
4172 $cc =~ /^\S+\@\S+>/) ||
4173 ($op eq '>' &&
4174 $ca =~ /<\S+\@\S+$/))
4175 {
4176 $ok = 1;
4177 }
4178
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004179 # for asm volatile statements
4180 # ignore a colon with another
4181 # colon immediately before or after
4182 if (($op eq ':') &&
4183 ($ca =~ /:$/ || $cc =~ /^:/)) {
4184 $ok = 1;
4185 }
4186
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004187 # messages are ERROR, but ?: are CHK
4188 if ($ok == 0) {
4189 my $msg_type = \&ERROR;
4190 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4191
4192 if (&{$msg_type}("SPACING",
4193 "spaces required around that '$op' $at\n" . $hereptr)) {
4194 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4195 if (defined $fix_elements[$n + 2]) {
4196 $fix_elements[$n + 2] =~ s/^\s+//;
4197 }
4198 $line_fixed = 1;
4199 }
4200 }
4201 }
4202 $off += length($elements[$n + 1]);
4203
4204## print("n: <$n> GOOD: <$good>\n");
4205
4206 $fixed_line = $fixed_line . $good;
4207 }
4208
4209 if (($#elements % 2) == 0) {
4210 $fixed_line = $fixed_line . $fix_elements[$#elements];
4211 }
4212
4213 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4214 $fixed[$fixlinenr] = $fixed_line;
4215 }
4216
4217
4218 }
4219
4220# check for whitespace before a non-naked semicolon
4221 if ($line =~ /^\+.*\S\s+;\s*$/) {
4222 if (WARN("SPACING",
4223 "space prohibited before semicolon\n" . $herecurr) &&
4224 $fix) {
4225 1 while $fixed[$fixlinenr] =~
4226 s/^(\+.*\S)\s+;/$1;/;
4227 }
4228 }
4229
4230# check for multiple assignments
4231 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4232 CHK("MULTIPLE_ASSIGNMENTS",
4233 "multiple assignments should be avoided\n" . $herecurr);
4234 }
4235
4236## # check for multiple declarations, allowing for a function declaration
4237## # continuation.
4238## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4239## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4240##
4241## # Remove any bracketed sections to ensure we do not
4242## # falsly report the parameters of functions.
4243## my $ln = $line;
4244## while ($ln =~ s/\([^\(\)]*\)//g) {
4245## }
4246## if ($ln =~ /,/) {
4247## WARN("MULTIPLE_DECLARATION",
4248## "declaring multiple variables together should be avoided\n" . $herecurr);
4249## }
4250## }
4251
4252#need space before brace following if, while, etc
Alexander Couzensebef00f2016-04-11 00:52:01 +02004253 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4254 $line =~ /do\{/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004255 if (ERROR("SPACING",
4256 "space required before the open brace '{'\n" . $herecurr) &&
4257 $fix) {
4258 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
4259 }
4260 }
4261
4262## # check for blank lines before declarations
4263## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4264## $prevrawline =~ /^.\s*$/) {
4265## WARN("SPACING",
4266## "No blank lines before declarations\n" . $hereprev);
4267## }
4268##
4269
4270# closing brace should have a space following it when it has anything
4271# on the line
4272 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4273 if (ERROR("SPACING",
4274 "space required after that close brace '}'\n" . $herecurr) &&
4275 $fix) {
4276 $fixed[$fixlinenr] =~
4277 s/}((?!(?:,|;|\)))\S)/} $1/;
4278 }
4279 }
4280
4281# check spacing on square brackets
4282 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4283 if (ERROR("SPACING",
4284 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4285 $fix) {
4286 $fixed[$fixlinenr] =~
4287 s/\[\s+/\[/;
4288 }
4289 }
4290 if ($line =~ /\s\]/) {
4291 if (ERROR("SPACING",
4292 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4293 $fix) {
4294 $fixed[$fixlinenr] =~
4295 s/\s+\]/\]/;
4296 }
4297 }
4298
4299# check spacing on parentheses
4300 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4301 $line !~ /for\s*\(\s+;/) {
4302 if (ERROR("SPACING",
4303 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4304 $fix) {
4305 $fixed[$fixlinenr] =~
4306 s/\(\s+/\(/;
4307 }
4308 }
4309 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4310 $line !~ /for\s*\(.*;\s+\)/ &&
4311 $line !~ /:\s+\)/) {
4312 if (ERROR("SPACING",
4313 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4314 $fix) {
4315 $fixed[$fixlinenr] =~
4316 s/\s+\)/\)/;
4317 }
4318 }
4319
4320# check unnecessary parentheses around addressof/dereference single $Lvals
4321# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4322
4323 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4324 my $var = $1;
4325 if (CHK("UNNECESSARY_PARENTHESES",
4326 "Unnecessary parentheses around $var\n" . $herecurr) &&
4327 $fix) {
4328 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4329 }
4330 }
4331
4332# check for unnecessary parentheses around function pointer uses
4333# ie: (foo->bar)(); should be foo->bar();
4334# but not "if (foo->bar) (" to avoid some false positives
4335 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4336 my $var = $2;
4337 if (CHK("UNNECESSARY_PARENTHESES",
4338 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4339 $fix) {
4340 my $var2 = deparenthesize($var);
4341 $var2 =~ s/\s//g;
4342 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4343 }
4344 }
4345
4346#goto labels aren't indented, allow a single space however
4347 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4348 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4349 if (WARN("INDENTED_LABEL",
4350 "labels should not be indented\n" . $herecurr) &&
4351 $fix) {
4352 $fixed[$fixlinenr] =~
4353 s/^(.)\s+/$1/;
4354 }
4355 }
4356
4357# return is not a function
4358 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4359 my $spacing = $1;
4360 if ($^V && $^V ge 5.10.0 &&
4361 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4362 my $value = $1;
4363 $value = deparenthesize($value);
4364 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4365 ERROR("RETURN_PARENTHESES",
4366 "return is not a function, parentheses are not required\n" . $herecurr);
4367 }
4368 } elsif ($spacing !~ /\s+/) {
4369 ERROR("SPACING",
4370 "space required before the open parenthesis '('\n" . $herecurr);
4371 }
4372 }
4373
4374# unnecessary return in a void function
4375# at end-of-function, with the previous line a single leading tab, then return;
4376# and the line before that not a goto label target like "out:"
4377 if ($sline =~ /^[ \+]}\s*$/ &&
4378 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4379 $linenr >= 3 &&
4380 $lines[$linenr - 3] =~ /^[ +]/ &&
4381 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4382 WARN("RETURN_VOID",
4383 "void function return statements are not generally useful\n" . $hereprev);
4384 }
4385
4386# if statements using unnecessary parentheses - ie: if ((foo == bar))
4387 if ($^V && $^V ge 5.10.0 &&
4388 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4389 my $openparens = $1;
4390 my $count = $openparens =~ tr@\(@\(@;
4391 my $msg = "";
4392 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4393 my $comp = $4; #Not $1 because of $LvalOrFunc
4394 $msg = " - maybe == should be = ?" if ($comp eq "==");
4395 WARN("UNNECESSARY_PARENTHESES",
4396 "Unnecessary parentheses$msg\n" . $herecurr);
4397 }
4398 }
4399
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004400# comparisons with a constant or upper case identifier on the left
4401# avoid cases like "foo + BAR < baz"
4402# only fix matches surrounded by parentheses to avoid incorrect
4403# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4404 if ($^V && $^V ge 5.10.0 &&
4405 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4406 my $lead = $1;
4407 my $const = $2;
4408 my $comp = $3;
4409 my $to = $4;
4410 my $newcomp = $comp;
4411 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4412 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4413 WARN("CONSTANT_COMPARISON",
4414 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4415 $fix) {
4416 if ($comp eq "<") {
4417 $newcomp = ">";
4418 } elsif ($comp eq "<=") {
4419 $newcomp = ">=";
4420 } elsif ($comp eq ">") {
4421 $newcomp = "<";
4422 } elsif ($comp eq ">=") {
4423 $newcomp = "<=";
4424 }
4425 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4426 }
4427 }
4428
4429# Return of what appears to be an errno should normally be negative
4430 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004431 my $name = $1;
4432 if ($name ne 'EOF' && $name ne 'ERROR') {
4433 WARN("USE_NEGATIVE_ERRNO",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004434 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004435 }
4436 }
4437
4438# Need a space before open parenthesis after if, while etc
4439 if ($line =~ /\b(if|while|for|switch)\(/) {
4440 if (ERROR("SPACING",
4441 "space required before the open parenthesis '('\n" . $herecurr) &&
4442 $fix) {
4443 $fixed[$fixlinenr] =~
4444 s/\b(if|while|for|switch)\(/$1 \(/;
4445 }
4446 }
4447
4448# Check for illegal assignment in if conditional -- and check for trailing
4449# statements after the conditional.
4450 if ($line =~ /do\s*(?!{)/) {
4451 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4452 ctx_statement_block($linenr, $realcnt, 0)
4453 if (!defined $stat);
4454 my ($stat_next) = ctx_statement_block($line_nr_next,
4455 $remain_next, $off_next);
4456 $stat_next =~ s/\n./\n /g;
4457 ##print "stat<$stat> stat_next<$stat_next>\n";
4458
4459 if ($stat_next =~ /^\s*while\b/) {
4460 # If the statement carries leading newlines,
4461 # then count those as offsets.
4462 my ($whitespace) =
4463 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4464 my $offset =
4465 statement_rawlines($whitespace) - 1;
4466
4467 $suppress_whiletrailers{$line_nr_next +
4468 $offset} = 1;
4469 }
4470 }
4471 if (!defined $suppress_whiletrailers{$linenr} &&
4472 defined($stat) && defined($cond) &&
4473 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4474 my ($s, $c) = ($stat, $cond);
4475
4476 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4477 ERROR("ASSIGN_IN_IF",
4478 "do not use assignment in if condition\n" . $herecurr);
4479 }
4480
4481 # Find out what is on the end of the line after the
4482 # conditional.
4483 substr($s, 0, length($c), '');
4484 $s =~ s/\n.*//g;
4485 $s =~ s/$;//g; # Remove any comments
4486 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4487 $c !~ /}\s*while\s*/)
4488 {
4489 # Find out how long the conditional actually is.
4490 my @newlines = ($c =~ /\n/gs);
4491 my $cond_lines = 1 + $#newlines;
4492 my $stat_real = '';
4493
4494 $stat_real = raw_line($linenr, $cond_lines)
4495 . "\n" if ($cond_lines);
4496 if (defined($stat_real) && $cond_lines > 1) {
4497 $stat_real = "[...]\n$stat_real";
4498 }
4499
4500 ERROR("TRAILING_STATEMENTS",
4501 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4502 }
4503 }
4504
4505# Check for bitwise tests written as boolean
4506 if ($line =~ /
4507 (?:
4508 (?:\[|\(|\&\&|\|\|)
4509 \s*0[xX][0-9]+\s*
4510 (?:\&\&|\|\|)
4511 |
4512 (?:\&\&|\|\|)
4513 \s*0[xX][0-9]+\s*
4514 (?:\&\&|\|\||\)|\])
4515 )/x)
4516 {
4517 WARN("HEXADECIMAL_BOOLEAN_TEST",
4518 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4519 }
4520
4521# if and else should not have general statements after it
4522 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4523 my $s = $1;
4524 $s =~ s/$;//g; # Remove any comments
4525 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4526 ERROR("TRAILING_STATEMENTS",
4527 "trailing statements should be on next line\n" . $herecurr);
4528 }
4529 }
4530# if should not continue a brace
4531 if ($line =~ /}\s*if\b/) {
4532 ERROR("TRAILING_STATEMENTS",
4533 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4534 $herecurr);
4535 }
4536# case and default should not have general statements after them
4537 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4538 $line !~ /\G(?:
4539 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4540 \s*return\s+
4541 )/xg)
4542 {
4543 ERROR("TRAILING_STATEMENTS",
4544 "trailing statements should be on next line\n" . $herecurr);
4545 }
4546
4547 # Check for }<nl>else {, these must be at the same
4548 # indent level to be relevant to each other.
4549 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4550 $previndent == $indent) {
4551 if (ERROR("ELSE_AFTER_BRACE",
4552 "else should follow close brace '}'\n" . $hereprev) &&
4553 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4554 fix_delete_line($fixlinenr - 1, $prevrawline);
4555 fix_delete_line($fixlinenr, $rawline);
4556 my $fixedline = $prevrawline;
4557 $fixedline =~ s/}\s*$//;
4558 if ($fixedline !~ /^\+\s*$/) {
4559 fix_insert_line($fixlinenr, $fixedline);
4560 }
4561 $fixedline = $rawline;
4562 $fixedline =~ s/^(.\s*)else/$1} else/;
4563 fix_insert_line($fixlinenr, $fixedline);
4564 }
4565 }
4566
4567 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4568 $previndent == $indent) {
4569 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4570
4571 # Find out what is on the end of the line after the
4572 # conditional.
4573 substr($s, 0, length($c), '');
4574 $s =~ s/\n.*//g;
4575
4576 if ($s =~ /^\s*;/) {
4577 if (ERROR("WHILE_AFTER_BRACE",
4578 "while should follow close brace '}'\n" . $hereprev) &&
4579 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4580 fix_delete_line($fixlinenr - 1, $prevrawline);
4581 fix_delete_line($fixlinenr, $rawline);
4582 my $fixedline = $prevrawline;
4583 my $trailing = $rawline;
4584 $trailing =~ s/^\+//;
4585 $trailing = trim($trailing);
4586 $fixedline =~ s/}\s*$/} $trailing/;
4587 fix_insert_line($fixlinenr, $fixedline);
4588 }
4589 }
4590 }
4591
4592#Specific variable tests
4593 while ($line =~ m{($Constant|$Lval)}g) {
4594 my $var = $1;
4595
4596#gcc binary extension
4597 if ($var =~ /^$Binary$/) {
4598 if (WARN("GCC_BINARY_CONSTANT",
4599 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4600 $fix) {
4601 my $hexval = sprintf("0x%x", oct($var));
4602 $fixed[$fixlinenr] =~
4603 s/\b$var\b/$hexval/;
4604 }
4605 }
4606
4607#CamelCase
4608 if ($var !~ /^$Constant$/ &&
4609 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4610#Ignore Page<foo> variants
4611 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4612#Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4613 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4614#Ignore some three character SI units explicitly, like MiB and KHz
4615 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4616 while ($var =~ m{($Ident)}g) {
4617 my $word = $1;
4618 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4619 if ($check) {
4620 seed_camelcase_includes();
4621 if (!$file && !$camelcase_file_seeded) {
4622 seed_camelcase_file($realfile);
4623 $camelcase_file_seeded = 1;
4624 }
4625 }
4626 if (!defined $camelcase{$word}) {
4627 $camelcase{$word} = 1;
4628 CHK("CAMELCASE",
4629 "Avoid CamelCase: <$word>\n" . $herecurr);
4630 }
4631 }
4632 }
4633 }
4634
4635#no spaces allowed after \ in define
4636 if ($line =~ /\#\s*define.*\\\s+$/) {
4637 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4638 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4639 $fix) {
4640 $fixed[$fixlinenr] =~ s/\s+$//;
4641 }
4642 }
4643
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004644# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4645# itself <asm/foo.h> (uses RAW line)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004646 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4647 my $file = "$1.h";
4648 my $checkfile = "include/linux/$file";
4649 if (-f "$root/$checkfile" &&
4650 $realfile ne $checkfile &&
4651 $1 !~ /$allowed_asm_includes/)
4652 {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004653 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4654 if ($asminclude > 0) {
4655 if ($realfile =~ m{^arch/}) {
4656 CHK("ARCH_INCLUDE_LINUX",
4657 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4658 } else {
4659 WARN("INCLUDE_LINUX",
4660 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4661 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004662 }
4663 }
4664 }
4665
4666# multi-statement macros should be enclosed in a do while loop, grab the
4667# first statement and ensure its the whole macro if its not enclosed
4668# in a known good container
4669 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4670 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4671 my $ln = $linenr;
4672 my $cnt = $realcnt;
4673 my ($off, $dstat, $dcond, $rest);
4674 my $ctx = '';
4675 my $has_flow_statement = 0;
4676 my $has_arg_concat = 0;
4677 ($dstat, $dcond, $ln, $cnt, $off) =
4678 ctx_statement_block($linenr, $realcnt, 0);
4679 $ctx = $dstat;
4680 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4681 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4682
4683 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004684 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004685
4686 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4687 $dstat =~ s/$;//g;
4688 $dstat =~ s/\\\n.//g;
4689 $dstat =~ s/^\s*//s;
4690 $dstat =~ s/\s*$//s;
4691
4692 # Flatten any parentheses and braces
4693 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4694 $dstat =~ s/\{[^\{\}]*\}/1/ ||
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004695 $dstat =~ s/.\[[^\[\]]*\]/1/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004696 {
4697 }
4698
4699 # Flatten any obvious string concatentation.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004700 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
4701 $dstat =~ s/$Ident\s*($String)/$1/)
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004702 {
4703 }
4704
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004705 # Make asm volatile uses seem like a generic function
4706 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
4707
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004708 my $exceptions = qr{
4709 $Declare|
4710 module_param_named|
4711 MODULE_PARM_DESC|
4712 DECLARE_PER_CPU|
4713 DEFINE_PER_CPU|
4714 __typeof__\(|
4715 union|
4716 struct|
4717 \.$Ident\s*=\s*|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004718 ^\"|\"$|
4719 ^\[
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004720 }x;
4721 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4722 if ($dstat ne '' &&
4723 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4724 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4725 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4726 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4727 $dstat !~ /$exceptions/ &&
4728 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4729 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4730 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4731 $dstat !~ /^for\s*$Constant$/ && # for (...)
4732 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
Martin Rothab9395f2016-08-29 10:39:30 -06004733 $dstat !~ /^do\s*\{/ && # do {...
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004734 $dstat !~ /^\(\{/ && # ({...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004735 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4736 {
4737 $ctx =~ s/\n*$//;
4738 my $herectx = $here . "\n";
4739 my $cnt = statement_rawlines($ctx);
4740
4741 for (my $n = 0; $n < $cnt; $n++) {
4742 $herectx .= raw_line($linenr, $n) . "\n";
4743 }
4744
4745 if ($dstat =~ /;/) {
4746 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4747 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4748 } else {
4749 ERROR("COMPLEX_MACRO",
4750 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4751 }
4752 }
4753
4754# check for macros with flow control, but without ## concatenation
4755# ## concatenation is commonly a macro that defines a function so ignore those
4756 if ($has_flow_statement && !$has_arg_concat) {
4757 my $herectx = $here . "\n";
4758 my $cnt = statement_rawlines($ctx);
4759
4760 for (my $n = 0; $n < $cnt; $n++) {
4761 $herectx .= raw_line($linenr, $n) . "\n";
4762 }
4763 WARN("MACRO_WITH_FLOW_CONTROL",
4764 "Macros with flow control statements should be avoided\n" . "$herectx");
4765 }
4766
4767# check for line continuations outside of #defines, preprocessor #, and asm
4768
4769 } else {
4770 if ($prevline !~ /^..*\\$/ &&
4771 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4772 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4773 $line =~ /^\+.*\\$/) {
4774 WARN("LINE_CONTINUATIONS",
4775 "Avoid unnecessary line continuations\n" . $herecurr);
4776 }
4777 }
4778
4779# do {} while (0) macro tests:
4780# single-statement macros do not need to be enclosed in do while (0) loop,
4781# macro should not end with a semicolon
4782 if ($^V && $^V ge 5.10.0 &&
4783 $realfile !~ m@/vmlinux.lds.h$@ &&
4784 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4785 my $ln = $linenr;
4786 my $cnt = $realcnt;
4787 my ($off, $dstat, $dcond, $rest);
4788 my $ctx = '';
4789 ($dstat, $dcond, $ln, $cnt, $off) =
4790 ctx_statement_block($linenr, $realcnt, 0);
4791 $ctx = $dstat;
4792
4793 $dstat =~ s/\\\n.//g;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004794 $dstat =~ s/$;/ /g;
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004795
4796 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4797 my $stmts = $2;
4798 my $semis = $3;
4799
4800 $ctx =~ s/\n*$//;
4801 my $cnt = statement_rawlines($ctx);
4802 my $herectx = $here . "\n";
4803
4804 for (my $n = 0; $n < $cnt; $n++) {
4805 $herectx .= raw_line($linenr, $n) . "\n";
4806 }
4807
4808 if (($stmts =~ tr/;/;/) == 1 &&
4809 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4810 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4811 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4812 }
4813 if (defined $semis && $semis ne "") {
4814 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4815 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4816 }
4817 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4818 $ctx =~ s/\n*$//;
4819 my $cnt = statement_rawlines($ctx);
4820 my $herectx = $here . "\n";
4821
4822 for (my $n = 0; $n < $cnt; $n++) {
4823 $herectx .= raw_line($linenr, $n) . "\n";
4824 }
4825
4826 WARN("TRAILING_SEMICOLON",
4827 "macros should not use a trailing semicolon\n" . "$herectx");
4828 }
4829 }
4830
4831# make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4832# all assignments may have only one of the following with an assignment:
4833# .
4834# ALIGN(...)
4835# VMLINUX_SYMBOL(...)
4836 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4837 WARN("MISSING_VMLINUX_SYMBOL",
4838 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4839 }
4840
4841# check for redundant bracing round if etc
4842 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4843 my ($level, $endln, @chunks) =
4844 ctx_statement_full($linenr, $realcnt, 1);
4845 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4846 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4847 if ($#chunks > 0 && $level == 0) {
4848 my @allowed = ();
4849 my $allow = 0;
4850 my $seen = 0;
4851 my $herectx = $here . "\n";
4852 my $ln = $linenr - 1;
4853 for my $chunk (@chunks) {
4854 my ($cond, $block) = @{$chunk};
4855
4856 # If the condition carries leading newlines, then count those as offsets.
4857 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4858 my $offset = statement_rawlines($whitespace) - 1;
4859
4860 $allowed[$allow] = 0;
4861 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4862
4863 # We have looked at and allowed this specific line.
4864 $suppress_ifbraces{$ln + $offset} = 1;
4865
4866 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4867 $ln += statement_rawlines($block) - 1;
4868
4869 substr($block, 0, length($cond), '');
4870
4871 $seen++ if ($block =~ /^\s*{/);
4872
4873 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4874 if (statement_lines($cond) > 1) {
4875 #print "APW: ALLOWED: cond<$cond>\n";
4876 $allowed[$allow] = 1;
4877 }
4878 if ($block =~/\b(?:if|for|while)\b/) {
4879 #print "APW: ALLOWED: block<$block>\n";
4880 $allowed[$allow] = 1;
4881 }
4882 if (statement_block_size($block) > 1) {
4883 #print "APW: ALLOWED: lines block<$block>\n";
4884 $allowed[$allow] = 1;
4885 }
4886 $allow++;
4887 }
4888 if ($seen) {
4889 my $sum_allowed = 0;
4890 foreach (@allowed) {
4891 $sum_allowed += $_;
4892 }
4893 if ($sum_allowed == 0) {
4894 WARN("BRACES",
4895 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4896 } elsif ($sum_allowed != $allow &&
4897 $seen != $allow) {
4898 CHK("BRACES",
4899 "braces {} should be used on all arms of this statement\n" . $herectx);
4900 }
4901 }
4902 }
4903 }
4904 if (!defined $suppress_ifbraces{$linenr - 1} &&
4905 $line =~ /\b(if|while|for|else)\b/) {
4906 my $allowed = 0;
4907
4908 # Check the pre-context.
4909 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4910 #print "APW: ALLOWED: pre<$1>\n";
4911 $allowed = 1;
4912 }
4913
4914 my ($level, $endln, @chunks) =
4915 ctx_statement_full($linenr, $realcnt, $-[0]);
4916
4917 # Check the condition.
4918 my ($cond, $block) = @{$chunks[0]};
4919 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4920 if (defined $cond) {
4921 substr($block, 0, length($cond), '');
4922 }
4923 if (statement_lines($cond) > 1) {
4924 #print "APW: ALLOWED: cond<$cond>\n";
4925 $allowed = 1;
4926 }
4927 if ($block =~/\b(?:if|for|while)\b/) {
4928 #print "APW: ALLOWED: block<$block>\n";
4929 $allowed = 1;
4930 }
4931 if (statement_block_size($block) > 1) {
4932 #print "APW: ALLOWED: lines block<$block>\n";
4933 $allowed = 1;
4934 }
4935 # Check the post-context.
4936 if (defined $chunks[1]) {
4937 my ($cond, $block) = @{$chunks[1]};
4938 if (defined $cond) {
4939 substr($block, 0, length($cond), '');
4940 }
4941 if ($block =~ /^\s*\{/) {
4942 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4943 $allowed = 1;
4944 }
4945 }
4946 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4947 my $herectx = $here . "\n";
4948 my $cnt = statement_rawlines($block);
4949
4950 for (my $n = 0; $n < $cnt; $n++) {
4951 $herectx .= raw_line($linenr, $n) . "\n";
4952 }
4953
4954 WARN("BRACES",
4955 "braces {} are not necessary for single statement blocks\n" . $herectx);
4956 }
4957 }
4958
4959# check for unnecessary blank lines around braces
4960 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004961 if (CHK("BRACES",
4962 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4963 $fix && $prevrawline =~ /^\+/) {
4964 fix_delete_line($fixlinenr - 1, $prevrawline);
4965 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004966 }
4967 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004968 if (CHK("BRACES",
4969 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4970 $fix) {
4971 fix_delete_line($fixlinenr, $rawline);
4972 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004973 }
4974
4975# no volatiles please
4976 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4977 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4978 WARN("VOLATILE",
4979 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4980 }
4981
4982# Check for user-visible strings broken across lines, which breaks the ability
4983# to grep for the string. Make exceptions when the previous string ends in a
4984# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4985# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
Stefan Reinauerc6080c62016-07-29 16:01:40 -07004986 if ($line =~ /^\+\s*$String/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01004987 $prevline =~ /"\s*$/ &&
4988 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4989 if (WARN("SPLIT_STRING",
4990 "quoted string split across lines\n" . $hereprev) &&
4991 $fix &&
4992 $prevrawline =~ /^\+.*"\s*$/ &&
4993 $last_coalesced_string_linenr != $linenr - 1) {
4994 my $extracted_string = get_quoted_string($line, $rawline);
4995 my $comma_close = "";
4996 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4997 $comma_close = $1;
4998 }
4999
5000 fix_delete_line($fixlinenr - 1, $prevrawline);
5001 fix_delete_line($fixlinenr, $rawline);
5002 my $fixedline = $prevrawline;
5003 $fixedline =~ s/"\s*$//;
5004 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5005 fix_insert_line($fixlinenr - 1, $fixedline);
5006 $fixedline = $rawline;
5007 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5008 if ($fixedline !~ /\+\s*$/) {
5009 fix_insert_line($fixlinenr, $fixedline);
5010 }
5011 $last_coalesced_string_linenr = $linenr;
5012 }
5013 }
5014
5015# check for missing a space in a string concatenation
5016 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5017 WARN('MISSING_SPACE',
5018 "break quoted strings at a space character\n" . $hereprev);
5019 }
5020
5021# check for spaces before a quoted newline
5022 if ($rawline =~ /^.*\".*\s\\n/) {
5023 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5024 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5025 $fix) {
5026 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5027 }
5028
5029 }
5030
5031# concatenated string without spaces between elements
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005032 if ($line =~ /$String[A-Z_]/ || $line =~ /[A-Za-z0-9_]$String/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005033 CHK("CONCATENATED_STRING",
5034 "Concatenated strings should use spaces between elements\n" . $herecurr);
5035 }
5036
5037# uncoalesced string fragments
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005038 if ($line =~ /$String\s*"/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005039 WARN("STRING_FRAGMENTS",
5040 "Consecutive strings are generally better as a single string\n" . $herecurr);
5041 }
5042
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005043# check for %L{u,d,i} and 0x%[udi] in strings
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005044 my $string;
5045 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5046 $string = substr($rawline, $-[1], $+[1] - $-[1]);
5047 $string =~ s/%%/__/g;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005048 if ($string =~ /(?<!%)%[\*\d\.\$]*L[udi]/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005049 WARN("PRINTF_L",
5050 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
5051 last;
5052 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005053 if ($string =~ /0x%[\*\d\.\$\Llzth]*[udi]/) {
5054 ERROR("PRINTF_0xDECIMAL",
5055 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5056 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005057 }
5058
5059# check for line continuations in quoted strings with odd counts of "
5060 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
5061 WARN("LINE_CONTINUATIONS",
5062 "Avoid line continuations in quoted strings\n" . $herecurr);
5063 }
5064
5065# warn about #if 0
5066 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5067 CHK("REDUNDANT_CODE",
5068 "if this code is redundant consider removing it\n" .
5069 $herecurr);
5070 }
5071
5072# check for needless "if (<foo>) fn(<foo>)" uses
5073 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005074 my $tested = quotemeta($1);
5075 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5076 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5077 my $func = $1;
5078 if (WARN('NEEDLESS_IF',
5079 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5080 $fix) {
5081 my $do_fix = 1;
5082 my $leading_tabs = "";
5083 my $new_leading_tabs = "";
5084 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5085 $leading_tabs = $1;
5086 } else {
5087 $do_fix = 0;
5088 }
5089 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5090 $new_leading_tabs = $1;
5091 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5092 $do_fix = 0;
5093 }
5094 } else {
5095 $do_fix = 0;
5096 }
5097 if ($do_fix) {
5098 fix_delete_line($fixlinenr - 1, $prevrawline);
5099 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5100 }
5101 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005102 }
5103 }
5104
5105# check for unnecessary "Out of Memory" messages
5106 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5107 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5108 (defined $1 || defined $3) &&
5109 $linenr > 3) {
5110 my $testval = $2;
5111 my $testline = $lines[$linenr - 3];
5112
5113 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5114# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5115
5116 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
5117 WARN("OOM_MESSAGE",
5118 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5119 }
5120 }
5121
5122# check for logging functions with KERN_<LEVEL>
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005123 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005124 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5125 my $level = $1;
5126 if (WARN("UNNECESSARY_KERN_LEVEL",
5127 "Possible unnecessary $level\n" . $herecurr) &&
5128 $fix) {
5129 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5130 }
5131 }
5132
5133# check for mask then right shift without a parentheses
5134 if ($^V && $^V ge 5.10.0 &&
5135 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5136 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5137 WARN("MASK_THEN_SHIFT",
5138 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5139 }
5140
5141# check for pointer comparisons to NULL
5142 if ($^V && $^V ge 5.10.0) {
5143 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5144 my $val = $1;
5145 my $equal = "!";
5146 $equal = "" if ($4 eq "!=");
5147 if (CHK("COMPARISON_TO_NULL",
5148 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5149 $fix) {
5150 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5151 }
5152 }
5153 }
5154
5155# check for bad placement of section $InitAttribute (e.g.: __initdata)
5156 if ($line =~ /(\b$InitAttribute\b)/) {
5157 my $attr = $1;
5158 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5159 my $ptr = $1;
5160 my $var = $2;
5161 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5162 ERROR("MISPLACED_INIT",
5163 "$attr should be placed after $var\n" . $herecurr)) ||
5164 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5165 WARN("MISPLACED_INIT",
5166 "$attr should be placed after $var\n" . $herecurr))) &&
5167 $fix) {
5168 $fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
5169 }
5170 }
5171 }
5172
5173# check for $InitAttributeData (ie: __initdata) with const
5174 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5175 my $attr = $1;
5176 $attr =~ /($InitAttributePrefix)(.*)/;
5177 my $attr_prefix = $1;
5178 my $attr_type = $2;
5179 if (ERROR("INIT_ATTRIBUTE",
5180 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5181 $fix) {
5182 $fixed[$fixlinenr] =~
5183 s/$InitAttributeData/${attr_prefix}initconst/;
5184 }
5185 }
5186
5187# check for $InitAttributeConst (ie: __initconst) without const
5188 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5189 my $attr = $1;
5190 if (ERROR("INIT_ATTRIBUTE",
5191 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5192 $fix) {
5193 my $lead = $fixed[$fixlinenr] =~
5194 /(^\+\s*(?:static\s+))/;
5195 $lead = rtrim($1);
5196 $lead = "$lead " if ($lead !~ /^\+$/);
5197 $lead = "${lead}const ";
5198 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5199 }
5200 }
5201
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005202# check for __read_mostly with const non-pointer (should just be const)
5203 if ($line =~ /\b__read_mostly\b/ &&
5204 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5205 if (ERROR("CONST_READ_MOSTLY",
5206 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5207 $fix) {
5208 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5209 }
5210 }
5211
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005212# don't use __constant_<foo> functions outside of include/uapi/
5213 if ($realfile !~ m@^include/uapi/@ &&
5214 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5215 my $constant_func = $1;
5216 my $func = $constant_func;
5217 $func =~ s/^__constant_//;
5218 if (WARN("CONSTANT_CONVERSION",
5219 "$constant_func should be $func\n" . $herecurr) &&
5220 $fix) {
5221 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5222 }
5223 }
5224
5225# prefer usleep_range over udelay
5226 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5227 my $delay = $1;
5228 # ignore udelay's < 10, however
5229 if (! ($delay < 10) ) {
5230 CHK("USLEEP_RANGE",
5231 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5232 }
5233 if ($delay > 2000) {
5234 WARN("LONG_UDELAY",
5235 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5236 }
5237 }
5238
5239# warn about unexpectedly long msleep's
5240 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5241 if ($1 < 20) {
5242 WARN("MSLEEP",
5243 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5244 }
5245 }
5246
5247# check for comparisons of jiffies
5248 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5249 WARN("JIFFIES_COMPARISON",
5250 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5251 }
5252
5253# check for comparisons of get_jiffies_64()
5254 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5255 WARN("JIFFIES_COMPARISON",
5256 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5257 }
5258
5259# warn about #ifdefs in C files
5260# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5261# print "#ifdef in C files should be avoided\n";
5262# print "$herecurr";
5263# $clean = 0;
5264# }
5265
5266# warn about spacing in #ifdefs
5267 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5268 if (ERROR("SPACING",
5269 "exactly one space required after that #$1\n" . $herecurr) &&
5270 $fix) {
5271 $fixed[$fixlinenr] =~
5272 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5273 }
5274
5275 }
5276
5277# check for spinlock_t definitions without a comment.
5278 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5279 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5280 my $which = $1;
5281 if (!ctx_has_comment($first_line, $linenr)) {
5282 CHK("UNCOMMENTED_DEFINITION",
5283 "$1 definition without comment\n" . $herecurr);
5284 }
5285 }
5286# check for memory barriers without a comment.
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005287
5288 my $barriers = qr{
5289 mb|
5290 rmb|
5291 wmb|
5292 read_barrier_depends
5293 }x;
5294 my $barrier_stems = qr{
5295 mb__before_atomic|
5296 mb__after_atomic|
5297 store_release|
5298 load_acquire|
5299 store_mb|
5300 (?:$barriers)
5301 }x;
5302 my $all_barriers = qr{
5303 (?:$barriers)|
5304 smp_(?:$barrier_stems)|
5305 virt_(?:$barrier_stems)
5306 }x;
5307
5308 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005309 if (!ctx_has_comment($first_line, $linenr)) {
5310 WARN("MEMORY_BARRIER",
5311 "memory barrier without comment\n" . $herecurr);
5312 }
5313 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005314
5315 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5316
5317 if ($realfile !~ m@^include/asm-generic/@ &&
5318 $realfile !~ m@/barrier\.h$@ &&
5319 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5320 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5321 WARN("MEMORY_BARRIER",
5322 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5323 }
5324
5325# check for waitqueue_active without a comment.
5326 if ($line =~ /\bwaitqueue_active\s*\(/) {
5327 if (!ctx_has_comment($first_line, $linenr)) {
5328 WARN("WAITQUEUE_ACTIVE",
5329 "waitqueue_active without comment\n" . $herecurr);
5330 }
5331 }
5332
5333# Check for expedited grace periods that interrupt non-idle non-nohz
5334# online CPUs. These expedited can therefore degrade real-time response
5335# if used carelessly, and should be avoided where not absolutely
5336# needed. It is always OK to use synchronize_rcu_expedited() and
5337# synchronize_sched_expedited() at boot time (before real-time applications
5338# start) and in error situations where real-time response is compromised in
5339# any case. Note that synchronize_srcu_expedited() does -not- interrupt
5340# other CPUs, so don't warn on uses of synchronize_srcu_expedited().
5341# Of course, nothing comes for free, and srcu_read_lock() and
5342# srcu_read_unlock() do contain full memory barriers in payment for
5343# synchronize_srcu_expedited() non-interruption properties.
5344 if ($line =~ /\b(synchronize_rcu_expedited|synchronize_sched_expedited)\(/) {
5345 WARN("EXPEDITED_RCU_GRACE_PERIOD",
5346 "expedited RCU grace periods should be avoided where they can degrade real-time response\n" . $herecurr);
5347
5348 }
5349
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005350# check of hardware specific defines
5351 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5352 CHK("ARCH_DEFINES",
5353 "architecture specific defines should be avoided\n" . $herecurr);
5354 }
5355
5356# Check that the storage class is at the beginning of a declaration
Martin Roth57bfbb02016-08-29 15:32:10 -06005357# coreboot: skip complaint about our '#define asmlinkage' lines
5358 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/ && $line !~ /^.\s*#\s*define\s+$Storage\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005359 WARN("STORAGE_CLASS",
5360 "storage class should be at the beginning of the declaration\n" . $herecurr)
5361 }
5362
5363# check the location of the inline attribute, that it is between
5364# storage class and type.
5365 if ($line =~ /\b$Type\s+$Inline\b/ ||
5366 $line =~ /\b$Inline\s+$Storage\b/) {
5367 ERROR("INLINE_LOCATION",
5368 "inline keyword should sit between storage class and type\n" . $herecurr);
5369 }
5370
5371# Check for __inline__ and __inline, prefer inline
5372 if ($realfile !~ m@\binclude/uapi/@ &&
5373 $line =~ /\b(__inline__|__inline)\b/) {
5374 if (WARN("INLINE",
5375 "plain inline is preferred over $1\n" . $herecurr) &&
5376 $fix) {
5377 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5378
5379 }
5380 }
5381
5382# Check for __attribute__ packed, prefer __packed
5383 if ($realfile !~ m@\binclude/uapi/@ &&
5384 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5385 WARN("PREFER_PACKED",
5386 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5387 }
5388
5389# Check for __attribute__ aligned, prefer __aligned
5390 if ($realfile !~ m@\binclude/uapi/@ &&
5391 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5392 WARN("PREFER_ALIGNED",
5393 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5394 }
5395
5396# Check for __attribute__ format(printf, prefer __printf
5397 if ($realfile !~ m@\binclude/uapi/@ &&
5398 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5399 if (WARN("PREFER_PRINTF",
5400 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5401 $fix) {
5402 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5403
5404 }
5405 }
5406
5407# Check for __attribute__ format(scanf, prefer __scanf
5408 if ($realfile !~ m@\binclude/uapi/@ &&
5409 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5410 if (WARN("PREFER_SCANF",
5411 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5412 $fix) {
5413 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5414 }
5415 }
5416
5417# Check for __attribute__ weak, or __weak declarations (may have link issues)
5418 if ($^V && $^V ge 5.10.0 &&
5419 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5420 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5421 $line =~ /\b__weak\b/)) {
5422 ERROR("WEAK_DECLARATION",
5423 "Using weak declarations can have unintended link defects\n" . $herecurr);
5424 }
5425
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005426# check for c99 types like uint8_t used outside of uapi/
5427 if ($realfile !~ m@\binclude/uapi/@ &&
5428 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5429 my $type = $1;
5430 if ($type =~ /\b($typeC99Typedefs)\b/) {
5431 $type = $1;
5432 my $kernel_type = 'u';
5433 $kernel_type = 's' if ($type =~ /^_*[si]/);
5434 $type =~ /(\d+)/;
5435 $kernel_type .= $1;
5436 if (CHK("PREFER_KERNEL_TYPES",
5437 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5438 $fix) {
5439 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5440 }
5441 }
5442 }
5443
5444# check for cast of C90 native int or longer types constants
5445 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5446 my $cast = $1;
5447 my $const = $2;
5448 if (WARN("TYPECAST_INT_CONSTANT",
5449 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5450 $fix) {
5451 my $suffix = "";
5452 my $newconst = $const;
5453 $newconst =~ s/${Int_type}$//;
5454 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5455 if ($cast =~ /\blong\s+long\b/) {
5456 $suffix .= 'LL';
5457 } elsif ($cast =~ /\blong\b/) {
5458 $suffix .= 'L';
5459 }
5460 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5461 }
5462 }
5463
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005464# check for sizeof(&)
5465 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5466 WARN("SIZEOF_ADDRESS",
5467 "sizeof(& should be avoided\n" . $herecurr);
5468 }
5469
5470# check for sizeof without parenthesis
5471 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5472 if (WARN("SIZEOF_PARENTHESIS",
5473 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5474 $fix) {
5475 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5476 }
5477 }
5478
5479# check for struct spinlock declarations
5480 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5481 WARN("USE_SPINLOCK_T",
5482 "struct spinlock should be spinlock_t\n" . $herecurr);
5483 }
5484
5485# check for seq_printf uses that could be seq_puts
5486 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5487 my $fmt = get_quoted_string($line, $rawline);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005488 $fmt =~ s/%%//g;
5489 if ($fmt !~ /%/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005490 if (WARN("PREFER_SEQ_PUTS",
5491 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5492 $fix) {
5493 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5494 }
5495 }
5496 }
5497
5498# Check for misused memsets
5499 if ($^V && $^V ge 5.10.0 &&
5500 defined $stat &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005501 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005502
5503 my $ms_addr = $2;
5504 my $ms_val = $7;
5505 my $ms_size = $12;
5506
5507 if ($ms_size =~ /^(0x|)0$/i) {
5508 ERROR("MEMSET",
5509 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5510 } elsif ($ms_size =~ /^(0x|)1$/i) {
5511 WARN("MEMSET",
5512 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5513 }
5514 }
5515
5516# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5517 if ($^V && $^V ge 5.10.0 &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005518 defined $stat &&
5519 $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005520 if (WARN("PREFER_ETHER_ADDR_COPY",
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005521 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005522 $fix) {
5523 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5524 }
5525 }
5526
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005527# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5528 if ($^V && $^V ge 5.10.0 &&
5529 defined $stat &&
5530 $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5531 WARN("PREFER_ETHER_ADDR_EQUAL",
5532 "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5533 }
5534
5535# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5536# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5537 if ($^V && $^V ge 5.10.0 &&
5538 defined $stat &&
5539 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5540
5541 my $ms_val = $7;
5542
5543 if ($ms_val =~ /^(?:0x|)0+$/i) {
5544 if (WARN("PREFER_ETH_ZERO_ADDR",
5545 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5546 $fix) {
5547 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5548 }
5549 } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5550 if (WARN("PREFER_ETH_BROADCAST_ADDR",
5551 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
5552 $fix) {
5553 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
5554 }
5555 }
5556 }
5557
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005558# typecasts on min/max could be min_t/max_t
5559 if ($^V && $^V ge 5.10.0 &&
5560 defined $stat &&
5561 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5562 if (defined $2 || defined $7) {
5563 my $call = $1;
5564 my $cast1 = deparenthesize($2);
5565 my $arg1 = $3;
5566 my $cast2 = deparenthesize($7);
5567 my $arg2 = $8;
5568 my $cast;
5569
5570 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5571 $cast = "$cast1 or $cast2";
5572 } elsif ($cast1 ne "") {
5573 $cast = $cast1;
5574 } else {
5575 $cast = $cast2;
5576 }
5577 WARN("MINMAX",
5578 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5579 }
5580 }
5581
5582# check usleep_range arguments
5583 if ($^V && $^V ge 5.10.0 &&
5584 defined $stat &&
5585 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5586 my $min = $1;
5587 my $max = $7;
5588 if ($min eq $max) {
5589 WARN("USLEEP_RANGE",
5590 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5591 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5592 $min > $max) {
5593 WARN("USLEEP_RANGE",
5594 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5595 }
5596 }
5597
5598# check for naked sscanf
5599 if ($^V && $^V ge 5.10.0 &&
5600 defined $stat &&
5601 $line =~ /\bsscanf\b/ &&
5602 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5603 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5604 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5605 my $lc = $stat =~ tr@\n@@;
5606 $lc = $lc + $linenr;
5607 my $stat_real = raw_line($linenr, 0);
5608 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5609 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5610 }
5611 WARN("NAKED_SSCANF",
5612 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5613 }
5614
5615# check for simple sscanf that should be kstrto<foo>
5616 if ($^V && $^V ge 5.10.0 &&
5617 defined $stat &&
5618 $line =~ /\bsscanf\b/) {
5619 my $lc = $stat =~ tr@\n@@;
5620 $lc = $lc + $linenr;
5621 my $stat_real = raw_line($linenr, 0);
5622 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5623 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5624 }
5625 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5626 my $format = $6;
5627 my $count = $format =~ tr@%@%@;
5628 if ($count == 1 &&
5629 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5630 WARN("SSCANF_TO_KSTRTO",
5631 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5632 }
5633 }
5634 }
5635
5636# check for new externs in .h files.
5637 if ($realfile =~ /\.h$/ &&
5638 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5639 if (CHK("AVOID_EXTERNS",
5640 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5641 $fix) {
5642 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5643 }
5644 }
5645
5646# check for new externs in .c files.
5647 if ($realfile =~ /\.c$/ && defined $stat &&
5648 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5649 {
5650 my $function_name = $1;
5651 my $paren_space = $2;
5652
5653 my $s = $stat;
5654 if (defined $cond) {
5655 substr($s, 0, length($cond), '');
5656 }
5657 if ($s =~ /^\s*;/ &&
5658 $function_name ne 'uninitialized_var')
5659 {
5660 WARN("AVOID_EXTERNS",
5661 "externs should be avoided in .c files\n" . $herecurr);
5662 }
5663
5664 if ($paren_space =~ /\n/) {
5665 WARN("FUNCTION_ARGUMENTS",
5666 "arguments for function declarations should follow identifier\n" . $herecurr);
5667 }
5668
5669 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5670 $stat =~ /^.\s*extern\s+/)
5671 {
5672 WARN("AVOID_EXTERNS",
5673 "externs should be avoided in .c files\n" . $herecurr);
5674 }
5675
5676# checks for new __setup's
5677 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5678 my $name = $1;
5679
5680 if (!grep(/$name/, @setup_docs)) {
5681 CHK("UNDOCUMENTED_SETUP",
5682 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5683 }
5684 }
5685
5686# check for pointless casting of kmalloc return
5687 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5688 WARN("UNNECESSARY_CASTS",
5689 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5690 }
5691
5692# alloc style
5693# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5694 if ($^V && $^V ge 5.10.0 &&
5695 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5696 CHK("ALLOC_SIZEOF_STRUCT",
5697 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5698 }
5699
5700# check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5701 if ($^V && $^V ge 5.10.0 &&
5702 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5703 my $oldfunc = $3;
5704 my $a1 = $4;
5705 my $a2 = $10;
5706 my $newfunc = "kmalloc_array";
5707 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5708 my $r1 = $a1;
5709 my $r2 = $a2;
5710 if ($a1 =~ /^sizeof\s*\S/) {
5711 $r1 = $a2;
5712 $r2 = $a1;
5713 }
5714 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5715 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5716 if (WARN("ALLOC_WITH_MULTIPLY",
5717 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5718 $fix) {
5719 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
5720
5721 }
5722 }
5723 }
5724
5725# check for krealloc arg reuse
5726 if ($^V && $^V ge 5.10.0 &&
5727 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5728 WARN("KREALLOC_ARG_REUSE",
5729 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5730 }
5731
5732# check for alloc argument mismatch
5733 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5734 WARN("ALLOC_ARRAY_ARGS",
5735 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5736 }
5737
5738# check for multiple semicolons
5739 if ($line =~ /;\s*;\s*$/) {
5740 if (WARN("ONE_SEMICOLON",
5741 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5742 $fix) {
5743 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5744 }
5745 }
5746
5747# check for #defines like: 1 << <digit> that could be BIT(digit)
5748 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5749 my $ull = "";
5750 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5751 if (CHK("BIT_MACRO",
5752 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5753 $fix) {
5754 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5755 }
5756 }
5757
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005758# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
5759 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
5760 my $config = $1;
5761 if (WARN("PREFER_IS_ENABLED",
5762 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
5763 $fix) {
5764 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
5765 }
5766 }
5767
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005768# check for case / default statements not preceded by break/fallthrough/switch
5769 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5770 my $has_break = 0;
5771 my $has_statement = 0;
5772 my $count = 0;
5773 my $prevline = $linenr;
5774 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5775 $prevline--;
5776 my $rline = $rawlines[$prevline - 1];
5777 my $fline = $lines[$prevline - 1];
5778 last if ($fline =~ /^\@\@/);
5779 next if ($fline =~ /^\-/);
5780 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5781 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5782 next if ($fline =~ /^.[\s$;]*$/);
5783 $has_statement = 1;
5784 $count++;
5785 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5786 }
5787 if (!$has_break && $has_statement) {
5788 WARN("MISSING_BREAK",
5789 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5790 }
5791 }
5792
5793# check for switch/default statements without a break;
5794 if ($^V && $^V ge 5.10.0 &&
5795 defined $stat &&
5796 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5797 my $ctx = '';
5798 my $herectx = $here . "\n";
5799 my $cnt = statement_rawlines($stat);
5800 for (my $n = 0; $n < $cnt; $n++) {
5801 $herectx .= raw_line($linenr, $n) . "\n";
5802 }
5803 WARN("DEFAULT_NO_BREAK",
5804 "switch default: should use break\n" . $herectx);
5805 }
5806
5807# check for gcc specific __FUNCTION__
5808 if ($line =~ /\b__FUNCTION__\b/) {
5809 if (WARN("USE_FUNC",
5810 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5811 $fix) {
5812 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5813 }
5814 }
5815
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005816# check for uses of __DATE__, __TIME__, __TIMESTAMP__
5817 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5818 ERROR("DATE_TIME",
5819 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5820 }
5821
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005822# check for use of yield()
5823 if ($line =~ /\byield\s*\(\s*\)/) {
5824 WARN("YIELD",
5825 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5826 }
5827
5828# check for comparisons against true and false
5829 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5830 my $lead = $1;
5831 my $arg = $2;
5832 my $test = $3;
5833 my $otype = $4;
5834 my $trail = $5;
5835 my $op = "!";
5836
5837 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5838
5839 my $type = lc($otype);
5840 if ($type =~ /^(?:true|false)$/) {
5841 if (("$test" eq "==" && "$type" eq "true") ||
5842 ("$test" eq "!=" && "$type" eq "false")) {
5843 $op = "";
5844 }
5845
5846 CHK("BOOL_COMPARISON",
5847 "Using comparison to $otype is error prone\n" . $herecurr);
5848
5849## maybe suggesting a correct construct would better
5850## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5851
5852 }
5853 }
5854
5855# check for semaphores initialized locked
5856 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5857 WARN("CONSIDER_COMPLETION",
5858 "consider using a completion\n" . $herecurr);
5859 }
5860
5861# recommend kstrto* over simple_strto* and strict_strto*
5862 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5863 WARN("CONSIDER_KSTRTO",
5864 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5865 }
5866
5867# check for __initcall(), use device_initcall() explicitly or more appropriate function please
5868 if ($line =~ /^.\s*__initcall\s*\(/) {
5869 WARN("USE_DEVICE_INITCALL",
5870 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5871 }
5872
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005873# check for various structs that are normally const (ops, kgdb, device_tree)
5874 my $const_structs = qr{
5875 acpi_dock_ops|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005876 address_space_operations|
5877 backlight_ops|
5878 block_device_operations|
5879 dentry_operations|
5880 dev_pm_ops|
5881 dma_map_ops|
5882 extent_io_ops|
5883 file_lock_operations|
5884 file_operations|
5885 hv_ops|
5886 ide_dma_ops|
5887 intel_dvo_dev_ops|
5888 item_operations|
5889 iwl_ops|
5890 kgdb_arch|
5891 kgdb_io|
5892 kset_uevent_ops|
5893 lock_manager_operations|
5894 microcode_ops|
5895 mtrr_ops|
5896 neigh_ops|
5897 nlmsvc_binding|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005898 of_device_id|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005899 pci_raw_ops|
5900 pipe_buf_operations|
5901 platform_hibernation_ops|
5902 platform_suspend_ops|
5903 proto_ops|
5904 rpc_pipe_ops|
5905 seq_operations|
5906 snd_ac97_build_ops|
5907 soc_pcmcia_socket_ops|
5908 stacktrace_ops|
5909 sysfs_ops|
5910 tty_operations|
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005911 uart_ops|
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005912 usb_mon_operations|
5913 wd_ops}x;
5914 if ($line !~ /\bconst\b/ &&
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005915 $line =~ /\bstruct\s+($const_structs)\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005916 WARN("CONST_STRUCT",
5917 "struct $1 should normally be const\n" .
5918 $herecurr);
5919 }
5920
5921# use of NR_CPUS is usually wrong
5922# ignore definitions of NR_CPUS and usage to define arrays as likely right
5923 if ($line =~ /\bNR_CPUS\b/ &&
5924 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5925 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5926 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5927 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5928 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5929 {
5930 WARN("NR_CPUS",
5931 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5932 }
5933
5934# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5935 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5936 ERROR("DEFINE_ARCH_HAS",
5937 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5938 }
5939
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005940# likely/unlikely comparisons similar to "(likely(foo) > 0)"
5941 if ($^V && $^V ge 5.10.0 &&
5942 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5943 WARN("LIKELY_MISUSE",
5944 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5945 }
5946
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005947# whine mightly about in_atomic
5948 if ($line =~ /\bin_atomic\s*\(/) {
5949 if ($realfile =~ m@^drivers/@) {
5950 ERROR("IN_ATOMIC",
5951 "do not use in_atomic in drivers\n" . $herecurr);
5952 } elsif ($realfile !~ m@^kernel/@) {
5953 WARN("IN_ATOMIC",
5954 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5955 }
5956 }
5957
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005958# whine about ACCESS_ONCE
5959 if ($^V && $^V ge 5.10.0 &&
5960 $line =~ /\bACCESS_ONCE\s*$balanced_parens\s*(=(?!=))?\s*($FuncArg)?/) {
5961 my $par = $1;
5962 my $eq = $2;
5963 my $fun = $3;
5964 $par =~ s/^\(\s*(.*)\s*\)$/$1/;
5965 if (defined($eq)) {
5966 if (WARN("PREFER_WRITE_ONCE",
5967 "Prefer WRITE_ONCE(<FOO>, <BAR>) over ACCESS_ONCE(<FOO>) = <BAR>\n" . $herecurr) &&
5968 $fix) {
5969 $fixed[$fixlinenr] =~ s/\bACCESS_ONCE\s*\(\s*\Q$par\E\s*\)\s*$eq\s*\Q$fun\E/WRITE_ONCE($par, $fun)/;
5970 }
5971 } else {
5972 if (WARN("PREFER_READ_ONCE",
5973 "Prefer READ_ONCE(<FOO>) over ACCESS_ONCE(<FOO>)\n" . $herecurr) &&
5974 $fix) {
5975 $fixed[$fixlinenr] =~ s/\bACCESS_ONCE\s*\(\s*\Q$par\E\s*\)/READ_ONCE($par)/;
5976 }
5977 }
5978 }
5979
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005980# check for lockdep_set_novalidate_class
5981 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5982 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5983 if ($realfile !~ m@^kernel/lockdep@ &&
5984 $realfile !~ m@^include/linux/lockdep@ &&
5985 $realfile !~ m@^drivers/base/core@) {
5986 ERROR("LOCKDEP",
5987 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5988 }
5989 }
5990
Stefan Reinauerc6080c62016-07-29 16:01:40 -07005991 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
5992 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01005993 WARN("EXPORTED_WORLD_WRITABLE",
5994 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5995 }
5996
5997# Mode permission misuses where it seems decimal should be octal
5998# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5999 if ($^V && $^V ge 5.10.0 &&
6000 $line =~ /$mode_perms_search/) {
6001 foreach my $entry (@mode_permission_funcs) {
6002 my $func = $entry->[0];
6003 my $arg_pos = $entry->[1];
6004
6005 my $skip_args = "";
6006 if ($arg_pos > 1) {
6007 $arg_pos--;
6008 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6009 }
6010 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
6011 if ($line =~ /$test/) {
6012 my $val = $1;
6013 $val = $6 if ($skip_args ne "");
6014
6015 if ($val !~ /^0$/ &&
6016 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6017 length($val) ne 4)) {
6018 ERROR("NON_OCTAL_PERMISSIONS",
6019 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006020 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6021 ERROR("EXPORTED_WORLD_WRITABLE",
6022 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006023 }
6024 }
6025 }
6026 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006027
6028# validate content of MODULE_LICENSE against list from include/linux/module.h
6029 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6030 my $extracted_string = get_quoted_string($line, $rawline);
6031 my $valid_licenses = qr{
6032 GPL|
6033 GPL\ v2|
6034 GPL\ and\ additional\ rights|
6035 Dual\ BSD/GPL|
6036 Dual\ MIT/GPL|
6037 Dual\ MPL/GPL|
6038 Proprietary
6039 }x;
6040 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6041 WARN("MODULE_LICENSE",
6042 "unknown module license " . $extracted_string . "\n" . $herecurr);
6043 }
6044 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006045 }
6046
6047 # If we have no input at all, then there is nothing to report on
6048 # so just keep quiet.
6049 if ($#rawlines == -1) {
6050 exit(0);
6051 }
6052
6053 # In mailback mode only produce a report in the negative, for
6054 # things that appear to be patches.
6055 if ($mailback && ($clean == 1 || !$is_patch)) {
6056 exit(0);
6057 }
6058
6059 # This is not a patch, and we are are in 'no-patch' mode so
6060 # just keep quiet.
6061 if (!$chk_patch && !$is_patch) {
6062 exit(0);
6063 }
6064
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006065 if (!$is_patch && $file !~ /cover-letter\.patch$/) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006066 ERROR("NOT_UNIFIED_DIFF",
6067 "Does not appear to be a unified-diff format patch\n");
6068 }
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006069 if ($is_patch && $filename ne '-' && $chk_signoff && $signoff == 0) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006070 ERROR("MISSING_SIGN_OFF",
6071 "Missing Signed-off-by: line(s)\n");
6072 }
6073
6074 print report_dump();
6075 if ($summary && !($clean == 1 && $quiet == 1)) {
6076 print "$filename " if ($summary_file);
6077 print "total: $cnt_error errors, $cnt_warn warnings, " .
6078 (($check)? "$cnt_chk checks, " : "") .
6079 "$cnt_lines lines checked\n";
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006080 }
6081
6082 if ($quiet == 0) {
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006083 # If there were any defects found and not already fixing them
6084 if (!$clean and !$fix) {
6085 print << "EOM"
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006086
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006087NOTE: For some of the reported defects, checkpatch may be able to
6088 mechanically convert to the typical style using --fix or --fix-inplace.
6089EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006090 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006091 # If there were whitespace errors which cleanpatch can fix
6092 # then suggest that.
6093 if ($rpt_cleaners) {
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006094 $rpt_cleaners = 0;
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006095 print << "EOM"
6096
6097NOTE: Whitespace errors detected.
6098 You may wish to use scripts/cleanpatch or scripts/cleanfile
6099EOM
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006100 }
6101 }
6102
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006103 if ($clean == 0 && $fix &&
6104 ("@rawlines" ne "@fixed" ||
6105 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6106 my $newfile = $filename;
6107 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6108 my $linecount = 0;
6109 my $f;
6110
6111 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6112
6113 open($f, '>', $newfile)
6114 or die "$P: Can't open $newfile for write\n";
6115 foreach my $fixed_line (@fixed) {
6116 $linecount++;
6117 if ($file) {
6118 if ($linecount > 3) {
6119 $fixed_line =~ s/^\+//;
6120 print $f $fixed_line . "\n";
6121 }
6122 } else {
6123 print $f $fixed_line . "\n";
6124 }
6125 }
6126 close($f);
6127
6128 if (!$quiet) {
6129 print << "EOM";
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006130
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006131Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6132
6133Do _NOT_ trust the results written to this file.
6134Do _NOT_ submit these changes without inspecting them for correctness.
6135
6136This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6137No warranties, expressed or implied...
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006138EOM
6139 }
6140 }
6141
Stefan Reinauerc6080c62016-07-29 16:01:40 -07006142 if ($quiet == 0) {
6143 print "\n";
6144 if ($clean == 1) {
6145 print "$vname has no obvious style problems and is ready for submission.\n";
6146 } else {
6147 print "$vname has style problems, please review.\n";
6148 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006149 }
Stefan Reinauer44d0fd92015-02-11 01:49:00 +01006150 return $clean;
6151}