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