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