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