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