2 # SPDX-License-Identifier: GPL-2.0
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>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
46 my $gitroot = $ENV{'GIT_DIR'};
47 $gitroot = ".git" if !defined($gitroot);
55 my $configuration_file = ".checkpatch.conf";
56 my $max_line_length = 100;
57 my $ignore_perl_version = 0;
58 my $minimum_perl_version = 5.10.0;
59 my $min_conf_desc_length = 4;
60 my $spelling_file = "$D/spelling.txt";
62 my $codespellfile = "/usr/share/codespell/dictionary.txt";
63 my $conststructsfile = "$D/const_structs.checkpatch";
66 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
67 # git output parsing needs US English output, so first set backtick child process LANGUAGE
68 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
70 my ${CONFIG_} = "CONFIG_";
76 Usage: $P [OPTION]... [FILE]...
81 --no-tree run without a kernel tree
82 --no-signoff do not check for 'Signed-off-by' line
83 --patch treat FILE as patchfile (default)
84 --emacs emacs compile window format
85 --terse one line per report
86 --showfile emit diffed file position, not input file position
87 -g, --git treat FILE as a single commit or git revision range
88 single git commit with:
92 multiple git commits with:
96 git merges are ignored
97 -f, --file treat FILE as regular source file
98 --subjective, --strict enable more subjective tests
99 --list-types list the possible message types
100 --types TYPE(,TYPE2...) show only these comma separated message types
101 --ignore TYPE(,TYPE2...) ignore various comma separated message types
102 --show-types show the specific message type in the output
103 --max-line-length=n set the maximum line length, (default $max_line_length)
104 if exceeded, warn on patches
105 requires --strict for use with --file
106 --min-conf-desc-length=n set the min description length, if shorter, warn
107 --tab-size=n set the number of spaces for tab (default $tabsize)
108 --root=PATH PATH to the kernel tree root
109 --no-summary suppress the per-file summary
110 --mailback only produce a report in case of warnings/errors
111 --summary-file include the filename in summary
112 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
113 'values', 'possible', 'type', and 'attr' (default
115 --test-only=WORD report only warnings/errors containing WORD
117 --fix EXPERIMENTAL - may create horrible results
118 If correctable single-line errors exist, create
119 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
120 with potential errors corrected to the preferred
122 --fix-inplace EXPERIMENTAL - may create horrible results
123 Is the same as --fix, but overwrites the input
124 file. It's your fault if there's no backup or git
125 --ignore-perl-version override checking of perl version. expect
127 --codespell Use the codespell dictionary for spelling/typos
128 (default:/usr/share/codespell/dictionary.txt)
129 --codespellfile Use this codespell dictionary
130 --typedefsfile Read additional types from this file
131 --color[=WHEN] Use colors 'always', 'never', or only when output
132 is a terminal ('auto'). Default is 'auto'.
133 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
135 -h, --help, --version display this help and exit
137 When FILE is - read standard input.
145 return grep { !$seen{$_}++ } @_;
155 open(my $script, '<', abs_path($P)) or
156 die "$P: Can't read '$P' $!\n";
158 my $text = <$script>;
162 # Also catch when type or level is passed through a variable
163 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
166 @types = sort(uniq(@types));
167 print("#\tMessage type\n\n");
168 foreach my $type (@types) {
169 print(++$count . "\t" . $type . "\n");
175 my $conf = which_conf($configuration_file);
178 open(my $conffile, '<', "$conf")
179 or warn "$P: Can't find a readable $configuration_file file $!\n";
181 while (<$conffile>) {
184 $line =~ s/\s*\n?$//g;
188 next if ($line =~ m/^\s*#/);
189 next if ($line =~ m/^\s*$/);
191 my @words = split(" ", $line);
192 foreach my $word (@words) {
193 last if ($word =~ m/^#/);
194 push (@conf_args, $word);
198 unshift(@ARGV, @conf_args) if @conf_args;
201 # Perl's Getopt::Long allows options to take optional arguments after a space.
202 # Prevent --color by itself from consuming other arguments
204 if ($_ eq "--color" || $_ eq "-color") {
205 $_ = "--color=$color";
210 'q|quiet+' => \$quiet,
212 'signoff!' => \$chk_signoff,
213 'patch!' => \$chk_patch,
216 'showfile!' => \$showfile,
219 'subjective!' => \$check,
220 'strict!' => \$check,
221 'ignore=s' => \@ignore,
223 'show-types!' => \$show_types,
224 'list-types!' => \$list_types,
225 'max-line-length=i' => \$max_line_length,
226 'min-conf-desc-length=i' => \$min_conf_desc_length,
227 'tab-size=i' => \$tabsize,
229 'summary!' => \$summary,
230 'mailback!' => \$mailback,
231 'summary-file!' => \$summary_file,
233 'fix-inplace!' => \$fix_inplace,
234 'ignore-perl-version!' => \$ignore_perl_version,
235 'debug=s' => \%debug,
236 'test-only=s' => \$tst_only,
237 'codespell!' => \$codespell,
238 'codespellfile=s' => \$codespellfile,
239 'typedefsfile=s' => \$typedefsfile,
240 'color=s' => \$color,
241 'no-color' => \$color, #keep old behaviors of -nocolor
242 'nocolor' => \$color, #keep old behaviors of -nocolor
243 'kconfig-prefix=s' => \${CONFIG_},
250 list_types(0) if ($list_types);
252 $fix = 1 if ($fix_inplace);
253 $check_orig = $check;
255 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
259 my $perl_version_ok = 1;
260 if ($^V && $^V lt $minimum_perl_version) {
261 $perl_version_ok = 0;
262 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
263 exit(1) if (!$ignore_perl_version);
266 #if no filenames are given, push '-' to read patch from stdin
271 if ($color =~ /^[01]$/) {
273 } elsif ($color =~ /^always$/i) {
275 } elsif ($color =~ /^never$/i) {
277 } elsif ($color =~ /^auto$/i) {
278 $color = (-t STDOUT);
280 die "$P: Invalid color mode: $color\n";
283 # skip TAB size 1 to avoid additional checks on $tabsize - 1
284 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
286 sub hash_save_array_words {
287 my ($hashRef, $arrayRef) = @_;
289 my @array = split(/,/, join(',', @$arrayRef));
290 foreach my $word (@array) {
291 $word =~ s/\s*\n?$//g;
294 $word =~ tr/[a-z]/[A-Z]/;
296 next if ($word =~ m/^\s*#/);
297 next if ($word =~ m/^\s*$/);
303 sub hash_show_words {
304 my ($hashRef, $prefix) = @_;
306 if (keys %$hashRef) {
307 print "\nNOTE: $prefix message types:";
308 foreach my $word (sort keys %$hashRef) {
315 hash_save_array_words(\%ignore_type, \@ignore);
316 hash_save_array_words(\%use_type, \@use);
319 my $dbg_possible = 0;
322 for my $key (keys %debug) {
324 eval "\${dbg_$key} = '$debug{$key}';";
328 my $rpt_cleaners = 0;
337 if (!top_of_kernel_tree($root)) {
338 die "$P: $root: --root does not point at a valid tree\n";
341 if (top_of_kernel_tree('.')) {
343 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
344 top_of_kernel_tree($1)) {
349 if (!defined $root) {
350 print "Must be run from the top-level dir. of a kernel tree\n";
355 my $emitted_corrupt = 0;
358 [A-Za-z_][A-Za-z\d_]*
359 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
361 our $Storage = qr{extern|static|asmlinkage};
375 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
376 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
377 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
378 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
379 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
381 # Notes to $Attribute:
382 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
405 ____cacheline_aligned|
406 ____cacheline_aligned_in_smp|
407 ____cacheline_internodealigned_in_smp|
411 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
412 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
413 our $Lval = qr{$Ident(?:$Member)*};
415 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
416 our $Binary = qr{(?i)0b[01]+$Int_type?};
417 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
418 our $Int = qr{[0-9]+$Int_type?};
419 our $Octal = qr{0[0-7]+$Int_type?};
420 our $String = qr{"[X\t]*"};
421 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
422 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
423 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
424 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
425 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
426 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
427 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
428 our $Arithmetic = qr{\+|-|\*|\/|%};
432 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
435 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
439 our $NonptrTypeMisordered;
440 our $NonptrTypeWithAttr;
444 our $DeclareMisordered;
446 our $NON_ASCII_UTF8 = qr{
447 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
448 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
449 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
450 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
451 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
452 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
453 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
457 [\x09\x0A\x0D\x20-\x7E] # ASCII
461 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
462 our $typeOtherOSTypedefs = qr{(?x:
463 u_(?:char|short|int|long) | # bsd
464 u(?:nchar|short|int|long) # sysv
466 our $typeKernelTypedefs = qr{(?x:
467 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
470 our $typeTypedefs = qr{(?x:
472 $typeOtherOSTypedefs\b|
473 $typeKernelTypedefs\b
476 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
478 our $logFunctions = qr{(?x:
479 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
480 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
482 WARN(?:_RATELIMIT|_ONCE|)|
485 seq_vprintf|seq_printf|seq_puts
488 our $allocFunctions = qr{(?x:
490 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
493 (?:\w+)?alloc_skb(?:_ip_align)? |
494 # dev_alloc_skb/netdev_alloc_skb, et al
498 our $signature_tags = qr{(?xi:
510 our $tracing_logging_tags = qr{(?xi:
534 sub edit_distance_min {
536 my $len = scalar @arr;
537 if ((scalar @arr) < 1) {
538 # if underflow, return
542 for my $i (0 .. ($len-1)) {
543 if ($arr[$i] < $min) {
550 sub get_edit_distance {
551 my ($str1, $str2) = @_;
556 my $len1 = length($str1);
557 my $len2 = length($str2);
558 # two dimensional array storing minimum edit distance
560 for my $i (0 .. $len1) {
561 for my $j (0 .. $len2) {
563 $distance[$i][$j] = $j;
565 $distance[$i][$j] = $i;
566 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
567 $distance[$i][$j] = $distance[$i - 1][$j - 1];
569 my $dist1 = $distance[$i][$j - 1]; #insert distance
570 my $dist2 = $distance[$i - 1][$j]; # remove
571 my $dist3 = $distance[$i - 1][$j - 1]; #replace
572 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
576 return $distance[$len1][$len2];
579 sub find_standard_signature {
581 my @standard_signature_tags = (
582 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
583 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
585 foreach my $signature (@standard_signature_tags) {
586 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
592 our @typeListMisordered = (
593 qr{char\s+(?:un)?signed},
594 qr{int\s+(?:(?:un)?signed\s+)?short\s},
595 qr{int\s+short(?:\s+(?:un)?signed)},
596 qr{short\s+int(?:\s+(?:un)?signed)},
597 qr{(?:un)?signed\s+int\s+short},
598 qr{short\s+(?:un)?signed},
599 qr{long\s+int\s+(?:un)?signed},
600 qr{int\s+long\s+(?:un)?signed},
601 qr{long\s+(?:un)?signed\s+int},
602 qr{int\s+(?:un)?signed\s+long},
603 qr{int\s+(?:un)?signed},
604 qr{int\s+long\s+long\s+(?:un)?signed},
605 qr{long\s+long\s+int\s+(?:un)?signed},
606 qr{long\s+long\s+(?:un)?signed\s+int},
607 qr{long\s+long\s+(?:un)?signed},
608 qr{long\s+(?:un)?signed},
613 qr{(?:(?:un)?signed\s+)?char},
614 qr{(?:(?:un)?signed\s+)?short\s+int},
615 qr{(?:(?:un)?signed\s+)?short},
616 qr{(?:(?:un)?signed\s+)?int},
617 qr{(?:(?:un)?signed\s+)?long\s+int},
618 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
619 qr{(?:(?:un)?signed\s+)?long\s+long},
620 qr{(?:(?:un)?signed\s+)?long},
629 qr{${Ident}_handler},
630 qr{${Ident}_handler_fn},
634 our $C90_int_types = qr{(?x:
635 long\s+long\s+int\s+(?:un)?signed|
636 long\s+long\s+(?:un)?signed\s+int|
637 long\s+long\s+(?:un)?signed|
638 (?:(?:un)?signed\s+)?long\s+long\s+int|
639 (?:(?:un)?signed\s+)?long\s+long|
640 int\s+long\s+long\s+(?:un)?signed|
641 int\s+(?:(?:un)?signed\s+)?long\s+long|
643 long\s+int\s+(?:un)?signed|
644 long\s+(?:un)?signed\s+int|
645 long\s+(?:un)?signed|
646 (?:(?:un)?signed\s+)?long\s+int|
647 (?:(?:un)?signed\s+)?long|
648 int\s+long\s+(?:un)?signed|
649 int\s+(?:(?:un)?signed\s+)?long|
652 (?:(?:un)?signed\s+)?int
655 our @typeListFile = ();
656 our @typeListWithAttr = (
658 qr{struct\s+$InitAttribute\s+$Ident},
659 qr{union\s+$InitAttribute\s+$Ident},
662 our @modifierList = (
665 our @modifierListFile = ();
667 our @mode_permission_funcs = (
669 ["module_param_(?:array|named|string)", 4],
670 ["module_param_array_named", 5],
671 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
672 ["proc_create(?:_data|)", 2],
673 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
674 ["IIO_DEV_ATTR_[A-Z_]+", 1],
675 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
676 ["SENSOR_TEMPLATE(?:_2|)", 3],
680 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
682 #Create a search pattern for all these functions to speed up a loop below
683 our $mode_perms_search = "";
684 foreach my $entry (@mode_permission_funcs) {
685 $mode_perms_search .= '|' if ($mode_perms_search ne "");
686 $mode_perms_search .= $entry->[0];
688 $mode_perms_search = "(?:${mode_perms_search})";
690 our %deprecated_apis = (
691 "synchronize_rcu_bh" => "synchronize_rcu",
692 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
693 "call_rcu_bh" => "call_rcu",
694 "rcu_barrier_bh" => "rcu_barrier",
695 "synchronize_sched" => "synchronize_rcu",
696 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
697 "call_rcu_sched" => "call_rcu",
698 "rcu_barrier_sched" => "rcu_barrier",
699 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
700 "cond_synchronize_sched" => "cond_synchronize_rcu",
703 #Create a search pattern for all these strings to speed up a loop below
704 our $deprecated_apis_search = "";
705 foreach my $entry (keys %deprecated_apis) {
706 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
707 $deprecated_apis_search .= $entry;
709 $deprecated_apis_search = "(?:${deprecated_apis_search})";
711 our $mode_perms_world_writable = qr{
719 our %mode_permission_string_types = (
738 #Create a search pattern for all these strings to speed up a loop below
739 our $mode_perms_string_search = "";
740 foreach my $entry (keys %mode_permission_string_types) {
741 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
742 $mode_perms_string_search .= $entry;
744 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
745 our $multi_mode_perms_string_search = qr{
746 ${single_mode_perms_string_search}
747 (?:\s*\|\s*${single_mode_perms_string_search})*
753 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
760 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
761 $curpos = pos($string);
764 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
766 $to |= $mode_permission_string_types{$match};
767 $val .= '\s*\|\s*' if ($val ne "");
771 $oval =~ s/^\s*\|\s*//;
772 $oval =~ s/\s*\|\s*$//;
773 return sprintf("%04o", $to);
776 our $allowed_asm_includes = qr{(?x:
782 # memory.h: ARM has a custom one
784 # Load common spelling mistakes and build regular expression list.
788 if (open(my $spelling, '<', $spelling_file)) {
789 while (<$spelling>) {
792 $line =~ s/\s*\n?$//g;
795 next if ($line =~ m/^\s*#/);
796 next if ($line =~ m/^\s*$/);
798 my ($suspect, $fix) = split(/\|\|/, $line);
800 $spelling_fix{$suspect} = $fix;
804 warn "No typos will be found - file '$spelling_file': $!\n";
808 if (open(my $spelling, '<', $codespellfile)) {
809 while (<$spelling>) {
812 $line =~ s/\s*\n?$//g;
815 next if ($line =~ m/^\s*#/);
816 next if ($line =~ m/^\s*$/);
817 next if ($line =~ m/, disabled/i);
821 my ($suspect, $fix) = split(/->/, $line);
823 $spelling_fix{$suspect} = $fix;
827 warn "No codespell typos will be found - file '$codespellfile': $!\n";
831 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
834 my ($wordsRef, $file) = @_;
836 if (open(my $words, '<', $file)) {
840 $line =~ s/\s*\n?$//g;
843 next if ($line =~ m/^\s*#/);
844 next if ($line =~ m/^\s*$/);
846 print("$file: '$line' invalid - ignored\n");
850 $$wordsRef .= '|' if (defined $$wordsRef);
861 if (show_type("CONST_STRUCT")) {
862 read_words(\$const_structs, $conststructsfile)
863 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
866 if (defined($typedefsfile)) {
867 my $typeOtherTypedefs;
868 read_words(\$typeOtherTypedefs, $typedefsfile)
869 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
870 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
874 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
875 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
876 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
877 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
878 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
884 (?:$Modifier\s+|const\s+)*
886 (?:typeof|__typeof__)\s*\([^\)]*\)|
890 (?:\s+$Modifier|\s+const)*
892 $NonptrTypeMisordered = qr{
893 (?:$Modifier\s+|const\s+)*
897 (?:\s+$Modifier|\s+const)*
899 $NonptrTypeWithAttr = qr{
900 (?:$Modifier\s+|const\s+)*
902 (?:typeof|__typeof__)\s*\([^\)]*\)|
906 (?:\s+$Modifier|\s+const)*
910 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
911 (?:\s+$Inline|\s+$Modifier)*
913 $TypeMisordered = qr{
914 $NonptrTypeMisordered
915 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
916 (?:\s+$Inline|\s+$Modifier)*
918 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
919 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
923 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
925 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
926 # requires at least perl version v5.10.0
927 # Any use must be runtime checked with $^V
929 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
930 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
931 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
933 our $declaration_macros = qr{(?x:
934 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
935 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
936 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
939 our %allow_repeated_words = (
948 return "" if (!defined($string));
950 while ($string =~ /^\s*\(.*\)\s*$/) {
951 $string =~ s@^\s*\(\s*@@;
952 $string =~ s@\s*\)\s*$@@;
955 $string =~ s@\s+@ @g;
960 sub seed_camelcase_file {
963 return if (!(-f $file));
967 open(my $include_file, '<', "$file")
968 or warn "$P: Can't read '$file' $!\n";
969 my $text = <$include_file>;
970 close($include_file);
972 my @lines = split('\n', $text);
974 foreach my $line (@lines) {
975 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
976 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
978 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
980 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
986 our %maintained_status = ();
988 sub is_maintained_obsolete {
991 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
993 if (!exists($maintained_status{$filename})) {
994 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
997 return $maintained_status{$filename} =~ /obsolete/i;
1000 sub is_SPDX_License_valid {
1003 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1005 my $root_path = abs_path($root);
1006 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
1007 return 0 if ($status ne "");
1011 my $camelcase_seeded = 0;
1012 sub seed_camelcase_includes {
1013 return if ($camelcase_seeded);
1016 my $camelcase_cache = "";
1017 my @include_files = ();
1019 $camelcase_seeded = 1;
1021 if (-e "$gitroot") {
1022 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1023 chomp $git_last_include_commit;
1024 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1026 my $last_mod_date = 0;
1027 $files = `find $root/include -name "*.h"`;
1028 @include_files = split('\n', $files);
1029 foreach my $file (@include_files) {
1030 my $date = POSIX::strftime("%Y%m%d%H%M",
1031 localtime((stat $file)[9]));
1032 $last_mod_date = $date if ($last_mod_date < $date);
1034 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1037 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1038 open(my $camelcase_file, '<', "$camelcase_cache")
1039 or warn "$P: Can't read '$camelcase_cache' $!\n";
1040 while (<$camelcase_file>) {
1044 close($camelcase_file);
1049 if (-e "$gitroot") {
1050 $files = `${git_command} ls-files "include/*.h"`;
1051 @include_files = split('\n', $files);
1054 foreach my $file (@include_files) {
1055 seed_camelcase_file($file);
1058 if ($camelcase_cache ne "") {
1059 unlink glob ".checkpatch-camelcase.*";
1060 open(my $camelcase_file, '>', "$camelcase_cache")
1061 or warn "$P: Can't write '$camelcase_cache' $!\n";
1062 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1063 print $camelcase_file ("$_\n");
1065 close($camelcase_file);
1069 sub git_is_single_file {
1070 my ($filename) = @_;
1072 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1074 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1075 my $count = $output =~ tr/\n//;
1076 return $count eq 1 && $output =~ m{^${filename}$};
1079 sub git_commit_info {
1080 my ($commit, $id, $desc) = @_;
1082 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1084 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1085 $output =~ s/^\s*//gm;
1086 my @lines = split("\n", $output);
1088 return ($id, $desc) if ($#lines < 0);
1090 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1091 # Maybe one day convert this block of bash into something that returns
1092 # all matching commit ids, but it's very slow...
1094 # echo "checking commits $1..."
1095 # git rev-list --remotes | grep -i "^$1" |
1096 # while read line ; do
1097 # git log --format='%H %s' -1 $line |
1098 # echo "commit $(cut -c 1-12,41-)"
1100 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1103 $id = substr($lines[0], 0, 12);
1104 $desc = substr($lines[0], 41);
1107 return ($id, $desc);
1110 $chk_signoff = 0 if ($file);
1115 my @fixed_inserted = ();
1116 my @fixed_deleted = ();
1119 # If input is git commits, extract all commits from the commit expressions.
1120 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1121 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1125 foreach my $commit_expr (@ARGV) {
1127 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1128 $git_range = "-$2 $1";
1129 } elsif ($commit_expr =~ m/\.\./) {
1130 $git_range = "$commit_expr";
1132 $git_range = "-1 $commit_expr";
1134 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1135 foreach my $line (split(/\n/, $lines)) {
1136 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1137 next if (!defined($1) || !defined($2));
1140 unshift(@commits, $sha1);
1141 $git_commits{$sha1} = $subject;
1144 die "$P: no git commits after extraction!\n" if (@commits == 0);
1149 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1150 for my $filename (@ARGV) {
1152 my $is_git_file = git_is_single_file($filename);
1153 my $oldfile = $file;
1154 $file = 1 if ($is_git_file);
1156 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1157 die "$P: $filename: git format-patch failed - $!\n";
1159 open($FILE, '-|', "diff -u /dev/null $filename") ||
1160 die "$P: $filename: diff failed - $!\n";
1161 } elsif ($filename eq '-') {
1162 open($FILE, '<&STDIN');
1164 open($FILE, '<', "$filename") ||
1165 die "$P: $filename: open failed - $!\n";
1167 if ($filename eq '-') {
1168 $vname = 'Your patch';
1170 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1176 push(@rawlines, $_);
1177 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1181 if ($#ARGV > 0 && $quiet == 0) {
1182 print '-' x length($vname) . "\n";
1184 print '-' x length($vname) . "\n";
1187 if (!process($filename)) {
1193 @fixed_inserted = ();
1194 @fixed_deleted = ();
1196 @modifierListFile = ();
1199 $file = $oldfile if ($is_git_file);
1203 hash_show_words(\%use_type, "Used");
1204 hash_show_words(\%ignore_type, "Ignored");
1206 if (!$perl_version_ok) {
1209 NOTE: perl $^V is not modern enough to detect all possible issues.
1210 An upgrade to at least perl $minimum_perl_version is suggested.
1216 NOTE: If any of the errors are false positives, please report
1217 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1224 sub top_of_kernel_tree {
1228 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1229 "README", "Documentation", "arch", "include", "drivers",
1230 "fs", "init", "ipc", "kernel", "lib", "scripts",
1233 foreach my $check (@tree_check) {
1234 if (! -e $root . '/' . $check) {
1242 my ($formatted_email) = @_;
1246 my $name_comment = "";
1250 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1253 $comment = $3 if defined $3;
1254 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1256 $comment = $2 if defined $2;
1257 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1259 $comment = $2 if defined $2;
1260 $formatted_email =~ s/\Q$address\E.*$//;
1261 $name = $formatted_email;
1262 $name = trim($name);
1263 $name =~ s/^\"|\"$//g;
1264 # If there's a name left after stripping spaces and
1265 # leading quotes, and the address doesn't have both
1266 # leading and trailing angle brackets, the address
1268 # "joe smith joe@smith.com" bad
1269 # "joe smith <joe@smith.com" bad
1270 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1277 # Extract comments from names excluding quoted parts
1278 # "John D. (Doe)" - Do not extract
1279 if ($name =~ s/\"(.+)\"//) {
1282 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1283 $name_comment .= trim($1);
1285 $name =~ s/^[ \"]+|[ \"]+$//g;
1286 $name = trim("$quoted $name");
1288 $address = trim($address);
1289 $address =~ s/^\<|\>$//g;
1290 $comment = trim($comment);
1292 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1293 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1294 $name = "\"$name\"";
1297 return ($name, $name_comment, $address, $comment);
1301 my ($name, $name_comment, $address, $comment) = @_;
1303 my $formatted_email;
1305 $name =~ s/^[ \"]+|[ \"]+$//g;
1306 $address = trim($address);
1307 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1309 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1310 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1311 $name = "\"$name\"";
1314 $name_comment = trim($name_comment);
1315 $name_comment = " $name_comment" if ($name_comment ne "");
1316 $comment = trim($comment);
1317 $comment = " $comment" if ($comment ne "");
1319 if ("$name" eq "") {
1320 $formatted_email = "$address";
1322 $formatted_email = "$name$name_comment <$address>";
1324 $formatted_email .= "$comment";
1325 return $formatted_email;
1328 sub reformat_email {
1331 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1332 return format_email($email_name, $name_comment, $email_address, $comment);
1335 sub same_email_addresses {
1336 my ($email1, $email2) = @_;
1338 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1339 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1341 return $email1_name eq $email2_name &&
1342 $email1_address eq $email2_address &&
1343 $name1_comment eq $name2_comment &&
1344 $comment1 eq $comment2;
1350 foreach my $path (split(/:/, $ENV{PATH})) {
1351 if (-e "$path/$bin") {
1352 return "$path/$bin";
1362 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1363 if (-e "$path/$conf") {
1364 return "$path/$conf";
1376 for my $c (split(//, $str)) {
1380 for (; ($n % $tabsize) != 0; $n++) {
1392 (my $res = shift) =~ tr/\t/ /c;
1399 # Drop the diff line leader and expand tabs
1401 $line = expand_tabs($line);
1403 # Pick the indent from the front of the line.
1404 my ($white) = ($line =~ /^(\s*)/);
1406 return (length($line), length($white));
1409 my $sanitise_quote = '';
1411 sub sanitise_line_reset {
1412 my ($in_comment) = @_;
1415 $sanitise_quote = '*/';
1417 $sanitise_quote = '';
1430 # Always copy over the diff marker.
1431 $res = substr($line, 0, 1);
1433 for ($off = 1; $off < length($line); $off++) {
1434 $c = substr($line, $off, 1);
1436 # Comments we are whacking completely including the begin
1437 # and end, all to $;.
1438 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1439 $sanitise_quote = '*/';
1441 substr($res, $off, 2, "$;$;");
1445 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1446 $sanitise_quote = '';
1447 substr($res, $off, 2, "$;$;");
1451 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1452 $sanitise_quote = '//';
1454 substr($res, $off, 2, $sanitise_quote);
1459 # A \ in a string means ignore the next character.
1460 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1462 substr($res, $off, 2, 'XX');
1467 if ($c eq "'" || $c eq '"') {
1468 if ($sanitise_quote eq '') {
1469 $sanitise_quote = $c;
1471 substr($res, $off, 1, $c);
1473 } elsif ($sanitise_quote eq $c) {
1474 $sanitise_quote = '';
1478 #print "c<$c> SQ<$sanitise_quote>\n";
1479 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1480 substr($res, $off, 1, $;);
1481 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1482 substr($res, $off, 1, $;);
1483 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1484 substr($res, $off, 1, 'X');
1486 substr($res, $off, 1, $c);
1490 if ($sanitise_quote eq '//') {
1491 $sanitise_quote = '';
1494 # The pathname on a #include may be surrounded by '<' and '>'.
1495 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1496 my $clean = 'X' x length($1);
1497 $res =~ s@\<.*\>@<$clean>@;
1499 # The whole of a #error is a string.
1500 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1501 my $clean = 'X' x length($1);
1502 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1505 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1507 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1513 sub get_quoted_string {
1514 my ($line, $rawline) = @_;
1516 return "" if (!defined($line) || !defined($rawline));
1517 return "" if ($line !~ m/($String)/g);
1518 return substr($rawline, $-[0], $+[0] - $-[0]);
1521 sub ctx_statement_block {
1522 my ($linenr, $remain, $off) = @_;
1523 my $line = $linenr - 1;
1526 my $coff = $off - 1;
1540 @stack = (['', 0]) if ($#stack == -1);
1542 #warn "CSB: blk<$blk> remain<$remain>\n";
1543 # If we are about to drop off the end, pull in more
1546 for (; $remain > 0; $line++) {
1547 last if (!defined $lines[$line]);
1548 next if ($lines[$line] =~ /^-/);
1551 $blk .= $lines[$line] . "\n";
1552 $len = length($blk);
1556 # Bail if there is no further context.
1557 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1561 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1567 $c = substr($blk, $off, 1);
1568 $remainder = substr($blk, $off);
1570 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1572 # Handle nested #if/#else.
1573 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1574 push(@stack, [ $type, $level ]);
1575 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1576 ($type, $level) = @{$stack[$#stack - 1]};
1577 } elsif ($remainder =~ /^#\s*endif\b/) {
1578 ($type, $level) = @{pop(@stack)};
1581 # Statement ends at the ';' or a close '}' at the
1583 if ($level == 0 && $c eq ';') {
1587 # An else is really a conditional as long as its not else if
1588 if ($level == 0 && $coff_set == 0 &&
1589 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1590 $remainder =~ /^(else)(?:\s|{)/ &&
1591 $remainder !~ /^else\s+if\b/) {
1592 $coff = $off + length($1) - 1;
1594 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1595 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1598 if (($type eq '' || $type eq '(') && $c eq '(') {
1602 if ($type eq '(' && $c eq ')') {
1604 $type = ($level != 0)? '(' : '';
1606 if ($level == 0 && $coff < $soff) {
1609 #warn "CSB: mark coff<$coff>\n";
1612 if (($type eq '' || $type eq '{') && $c eq '{') {
1616 if ($type eq '{' && $c eq '}') {
1618 $type = ($level != 0)? '{' : '';
1621 if (substr($blk, $off + 1, 1) eq ';') {
1627 # Preprocessor commands end at the newline unless escaped.
1628 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1636 # We are truly at the end, so shuffle to the next line.
1643 my $statement = substr($blk, $soff, $off - $soff + 1);
1644 my $condition = substr($blk, $soff, $coff - $soff + 1);
1646 #warn "STATEMENT<$statement>\n";
1647 #warn "CONDITION<$condition>\n";
1649 #print "coff<$coff> soff<$off> loff<$loff>\n";
1651 return ($statement, $condition,
1652 $line, $remain + 1, $off - $loff + 1, $level);
1655 sub statement_lines {
1658 # Strip the diff line prefixes and rip blank lines at start and end.
1659 $stmt =~ s/(^|\n)./$1/g;
1663 my @stmt_lines = ($stmt =~ /\n/g);
1665 return $#stmt_lines + 2;
1668 sub statement_rawlines {
1671 my @stmt_lines = ($stmt =~ /\n/g);
1673 return $#stmt_lines + 2;
1676 sub statement_block_size {
1679 $stmt =~ s/(^|\n)./$1/g;
1685 my @stmt_lines = ($stmt =~ /\n/g);
1686 my @stmt_statements = ($stmt =~ /;/g);
1688 my $stmt_lines = $#stmt_lines + 2;
1689 my $stmt_statements = $#stmt_statements + 1;
1691 if ($stmt_lines > $stmt_statements) {
1694 return $stmt_statements;
1698 sub ctx_statement_full {
1699 my ($linenr, $remain, $off) = @_;
1700 my ($statement, $condition, $level);
1704 # Grab the first conditional/block pair.
1705 ($statement, $condition, $linenr, $remain, $off, $level) =
1706 ctx_statement_block($linenr, $remain, $off);
1707 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1708 push(@chunks, [ $condition, $statement ]);
1709 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1710 return ($level, $linenr, @chunks);
1713 # Pull in the following conditional/block pairs and see if they
1714 # could continue the statement.
1716 ($statement, $condition, $linenr, $remain, $off, $level) =
1717 ctx_statement_block($linenr, $remain, $off);
1718 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1719 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1721 push(@chunks, [ $condition, $statement ]);
1724 return ($level, $linenr, @chunks);
1728 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1730 my $start = $linenr - 1;
1737 my @stack = ($level);
1738 for ($line = $start; $remain > 0; $line++) {
1739 next if ($rawlines[$line] =~ /^-/);
1742 $blk .= $rawlines[$line];
1744 # Handle nested #if/#else.
1745 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1746 push(@stack, $level);
1747 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1748 $level = $stack[$#stack - 1];
1749 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1750 $level = pop(@stack);
1753 foreach my $c (split(//, $lines[$line])) {
1754 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1760 if ($c eq $close && $level > 0) {
1762 last if ($level == 0);
1763 } elsif ($c eq $open) {
1768 if (!$outer || $level <= 1) {
1769 push(@res, $rawlines[$line]);
1772 last if ($level == 0);
1775 return ($level, @res);
1777 sub ctx_block_outer {
1778 my ($linenr, $remain) = @_;
1780 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1784 my ($linenr, $remain) = @_;
1786 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1790 my ($linenr, $remain, $off) = @_;
1792 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1795 sub ctx_block_level {
1796 my ($linenr, $remain) = @_;
1798 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1800 sub ctx_statement_level {
1801 my ($linenr, $remain, $off) = @_;
1803 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1806 sub ctx_locate_comment {
1807 my ($first_line, $end_line) = @_;
1809 # If c99 comment on the current line, or the line before or after
1810 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1811 return $current_comment if (defined $current_comment);
1812 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1813 return $current_comment if (defined $current_comment);
1814 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1815 return $current_comment if (defined $current_comment);
1817 # Catch a comment on the end of the line itself.
1818 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1819 return $current_comment if (defined $current_comment);
1821 # Look through the context and try and figure out if there is a
1824 $current_comment = '';
1825 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1826 my $line = $rawlines[$linenr - 1];
1828 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1831 if ($line =~ m@/\*@) {
1834 if (!$in_comment && $current_comment ne '') {
1835 $current_comment = '';
1837 $current_comment .= $line . "\n" if ($in_comment);
1838 if ($line =~ m@\*/@) {
1843 chomp($current_comment);
1844 return($current_comment);
1846 sub ctx_has_comment {
1847 my ($first_line, $end_line) = @_;
1848 my $cmt = ctx_locate_comment($first_line, $end_line);
1850 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1851 ##print "CMMT: $cmt\n";
1853 return ($cmt ne '');
1857 my ($linenr, $cnt) = @_;
1859 my $offset = $linenr - 1;
1864 $line = $rawlines[$offset++];
1865 next if (defined($line) && $line =~ /^-/);
1873 my ($linenr, $lc) = @_;
1875 my $stat_real = raw_line($linenr, 0);
1876 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1877 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1884 my ($linenr, $cnt, $here) = @_;
1886 my $herectx = $here . "\n";
1887 for (my $n = 0; $n < $cnt; $n++) {
1888 $herectx .= raw_line($linenr, $n) . "\n";
1899 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1902 $coded = sprintf("^%c", unpack('C', $2) + 64);
1911 my $av_preprocessor = 0;
1916 sub annotate_reset {
1917 $av_preprocessor = 0;
1919 @av_paren_type = ('E');
1920 $av_pend_colon = 'O';
1923 sub annotate_values {
1924 my ($stream, $type) = @_;
1927 my $var = '_' x length($stream);
1930 print "$stream\n" if ($dbg_values > 1);
1932 while (length($cur)) {
1933 @av_paren_type = ('E') if ($#av_paren_type < 0);
1934 print " <" . join('', @av_paren_type) .
1935 "> <$type> <$av_pending>" if ($dbg_values > 1);
1936 if ($cur =~ /^(\s+)/o) {
1937 print "WS($1)\n" if ($dbg_values > 1);
1938 if ($1 =~ /\n/ && $av_preprocessor) {
1939 $type = pop(@av_paren_type);
1940 $av_preprocessor = 0;
1943 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1944 print "CAST($1)\n" if ($dbg_values > 1);
1945 push(@av_paren_type, $type);
1948 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1949 print "DECLARE($1)\n" if ($dbg_values > 1);
1952 } elsif ($cur =~ /^($Modifier)\s*/) {
1953 print "MODIFIER($1)\n" if ($dbg_values > 1);
1956 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1957 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1958 $av_preprocessor = 1;
1959 push(@av_paren_type, $type);
1965 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1966 print "UNDEF($1)\n" if ($dbg_values > 1);
1967 $av_preprocessor = 1;
1968 push(@av_paren_type, $type);
1970 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1971 print "PRE_START($1)\n" if ($dbg_values > 1);
1972 $av_preprocessor = 1;
1974 push(@av_paren_type, $type);
1975 push(@av_paren_type, $type);
1978 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1979 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1980 $av_preprocessor = 1;
1982 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1986 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1987 print "PRE_END($1)\n" if ($dbg_values > 1);
1989 $av_preprocessor = 1;
1991 # Assume all arms of the conditional end as this
1992 # one does, and continue as if the #endif was not here.
1993 pop(@av_paren_type);
1994 push(@av_paren_type, $type);
1997 } elsif ($cur =~ /^(\\\n)/o) {
1998 print "PRECONT($1)\n" if ($dbg_values > 1);
2000 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2001 print "ATTR($1)\n" if ($dbg_values > 1);
2002 $av_pending = $type;
2005 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2006 print "SIZEOF($1)\n" if ($dbg_values > 1);
2012 } elsif ($cur =~ /^(if|while|for)\b/o) {
2013 print "COND($1)\n" if ($dbg_values > 1);
2017 } elsif ($cur =~/^(case)/o) {
2018 print "CASE($1)\n" if ($dbg_values > 1);
2019 $av_pend_colon = 'C';
2022 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2023 print "KEYWORD($1)\n" if ($dbg_values > 1);
2026 } elsif ($cur =~ /^(\()/o) {
2027 print "PAREN('$1')\n" if ($dbg_values > 1);
2028 push(@av_paren_type, $av_pending);
2032 } elsif ($cur =~ /^(\))/o) {
2033 my $new_type = pop(@av_paren_type);
2034 if ($new_type ne '_') {
2036 print "PAREN('$1') -> $type\n"
2037 if ($dbg_values > 1);
2039 print "PAREN('$1')\n" if ($dbg_values > 1);
2042 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2043 print "FUNC($1)\n" if ($dbg_values > 1);
2047 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2048 if (defined $2 && $type eq 'C' || $type eq 'T') {
2049 $av_pend_colon = 'B';
2050 } elsif ($type eq 'E') {
2051 $av_pend_colon = 'L';
2053 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2056 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2057 print "IDENT($1)\n" if ($dbg_values > 1);
2060 } elsif ($cur =~ /^($Assignment)/o) {
2061 print "ASSIGN($1)\n" if ($dbg_values > 1);
2064 } elsif ($cur =~/^(;|{|})/) {
2065 print "END($1)\n" if ($dbg_values > 1);
2067 $av_pend_colon = 'O';
2069 } elsif ($cur =~/^(,)/) {
2070 print "COMMA($1)\n" if ($dbg_values > 1);
2073 } elsif ($cur =~ /^(\?)/o) {
2074 print "QUESTION($1)\n" if ($dbg_values > 1);
2077 } elsif ($cur =~ /^(:)/o) {
2078 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2080 substr($var, length($res), 1, $av_pend_colon);
2081 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2086 $av_pend_colon = 'O';
2088 } elsif ($cur =~ /^(\[)/o) {
2089 print "CLOSE($1)\n" if ($dbg_values > 1);
2092 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2095 print "OPV($1)\n" if ($dbg_values > 1);
2102 substr($var, length($res), 1, $variant);
2105 } elsif ($cur =~ /^($Operators)/o) {
2106 print "OP($1)\n" if ($dbg_values > 1);
2107 if ($1 ne '++' && $1 ne '--') {
2111 } elsif ($cur =~ /(^.)/o) {
2112 print "C($1)\n" if ($dbg_values > 1);
2115 $cur = substr($cur, length($1));
2116 $res .= $type x length($1);
2120 return ($res, $var);
2124 my ($possible, $line) = @_;
2125 my $notPermitted = qr{(?:
2142 ^(?:typedef|struct|enum)\b
2144 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2145 if ($possible !~ $notPermitted) {
2146 # Check for modifiers.
2147 $possible =~ s/\s*$Storage\s*//g;
2148 $possible =~ s/\s*$Sparse\s*//g;
2149 if ($possible =~ /^\s*$/) {
2151 } elsif ($possible =~ /\s/) {
2152 $possible =~ s/\s*$Type\s*//g;
2153 for my $modifier (split(' ', $possible)) {
2154 if ($modifier !~ $notPermitted) {
2155 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2156 push(@modifierListFile, $modifier);
2161 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2162 push(@typeListFile, $possible);
2166 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2175 $type =~ tr/[a-z]/[A-Z]/;
2177 return defined $use_type{$type} if (scalar keys %use_type > 0);
2179 return !defined $ignore_type{$type};
2183 my ($level, $type, $msg) = @_;
2185 if (!show_type($type) ||
2186 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2191 if ($level eq 'ERROR') {
2193 } elsif ($level eq 'WARNING') {
2199 $output .= $prefix . $level . ':';
2201 $output .= BLUE if ($color);
2202 $output .= "$type:";
2204 $output .= RESET if ($color);
2205 $output .= ' ' . $msg . "\n";
2208 my @lines = split("\n", $output, -1);
2209 splice(@lines, 1, 1);
2210 $output = join("\n", @lines);
2212 $output = (split('\n', $output))[0] . "\n" if ($terse);
2214 push(our @report, $output);
2223 sub fixup_current_range {
2224 my ($lineRef, $offset, $length) = @_;
2226 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2229 my $no = $o + $offset;
2230 my $nl = $l + $length;
2231 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2235 sub fix_inserted_deleted_lines {
2236 my ($linesRef, $insertedRef, $deletedRef) = @_;
2238 my $range_last_linenr = 0;
2239 my $delta_offset = 0;
2244 my $next_insert = 0;
2245 my $next_delete = 0;
2249 my $inserted = @{$insertedRef}[$next_insert++];
2250 my $deleted = @{$deletedRef}[$next_delete++];
2252 foreach my $old_line (@{$linesRef}) {
2254 my $line = $old_line; #don't modify the array
2255 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2257 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2258 $range_last_linenr = $new_linenr;
2259 fixup_current_range(\$line, $delta_offset, 0);
2262 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2263 $deleted = @{$deletedRef}[$next_delete++];
2265 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2268 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2269 push(@lines, ${$inserted}{'LINE'});
2270 $inserted = @{$insertedRef}[$next_insert++];
2272 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2276 push(@lines, $line);
2286 sub fix_insert_line {
2287 my ($linenr, $line) = @_;
2293 push(@fixed_inserted, $inserted);
2296 sub fix_delete_line {
2297 my ($linenr, $line) = @_;
2304 push(@fixed_deleted, $deleted);
2308 my ($type, $msg) = @_;
2310 if (report("ERROR", $type, $msg)) {
2318 my ($type, $msg) = @_;
2320 if (report("WARNING", $type, $msg)) {
2328 my ($type, $msg) = @_;
2330 if ($check && report("CHECK", $type, $msg)) {
2338 sub check_absolute_file {
2339 my ($absolute, $herecurr) = @_;
2340 my $file = $absolute;
2342 ##print "absolute<$absolute>\n";
2344 # See if any suffix of this path is a path within the tree.
2345 while ($file =~ s@^[^/]*/@@) {
2346 if (-f "$root/$file") {
2347 ##print "file<$file>\n";
2355 # It is, so see if the prefix is acceptable.
2356 my $prefix = $absolute;
2357 substr($prefix, -length($file)) = '';
2359 ##print "prefix<$prefix>\n";
2360 if ($prefix ne ".../") {
2361 WARN("USE_RELATIVE_PATH",
2362 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2369 $string =~ s/^\s+|\s+$//g;
2377 $string =~ s/^\s+//;
2385 $string =~ s/\s+$//;
2390 sub string_find_replace {
2391 my ($string, $find, $replace) = @_;
2393 $string =~ s/$find/$replace/g;
2401 my $source_indent = $tabsize;
2402 my $max_spaces_before_tab = $source_indent - 1;
2403 my $spaces_to_tab = " " x $source_indent;
2405 #convert leading spaces to tabs
2406 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2407 #Remove spaces before a tab
2408 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2413 sub pos_last_openparen {
2418 my $opens = $line =~ tr/\(/\(/;
2419 my $closes = $line =~ tr/\)/\)/;
2421 my $last_openparen = 0;
2423 if (($opens == 0) || ($closes >= $opens)) {
2427 my $len = length($line);
2429 for ($pos = 0; $pos < $len; $pos++) {
2430 my $string = substr($line, $pos);
2431 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2432 $pos += length($1) - 1;
2433 } elsif (substr($line, $pos, 1) eq '(') {
2434 $last_openparen = $pos;
2435 } elsif (index($string, '(') == -1) {
2440 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2443 sub get_raw_comment {
2444 my ($line, $rawline) = @_;
2447 for my $i (0 .. (length($line) - 1)) {
2448 if (substr($line, $i, 1) eq "$;") {
2449 $comment .= substr($rawline, $i, 1);
2457 my $filename = shift;
2463 my $stashrawline="";
2473 my $authorsignoff = 0;
2474 my $author_sob = '';
2476 my $is_binding_patch = -1;
2477 my $in_header_lines = $file ? 0 : 1;
2478 my $in_commit_log = 0; #Scanning lines before patch
2479 my $has_patch_separator = 0; #Found a --- line
2480 my $has_commit_log = 0; #Encountered lines before patch
2481 my $commit_log_lines = 0; #Number of commit log lines
2482 my $commit_log_possible_stack_dump = 0;
2483 my $commit_log_long_line = 0;
2484 my $commit_log_has_diff = 0;
2485 my $reported_maintainer_file = 0;
2486 my $non_utf8_charset = 0;
2488 my $last_blank_line = 0;
2489 my $last_coalesced_string_linenr = -1;
2497 # Trace the real file/line as we go.
2502 my $context_function; #undef'd unless there's a known function
2504 my $comment_edge = 0;
2508 my $prev_values = 'E';
2511 my %suppress_ifbraces;
2512 my %suppress_whiletrailers;
2513 my %suppress_export;
2514 my $suppress_statement = 0;
2516 my %signatures = ();
2518 # Pre-scan the patch sanitizing the lines.
2519 # Pre-scan the patch looking for any __setup documentation.
2521 my @setup_docs = ();
2524 my $camelcase_file_seeded = 0;
2526 my $checklicenseline = 1;
2528 sanitise_line_reset();
2530 foreach my $rawline (@rawlines) {
2534 push(@fixed, $rawline) if ($fix);
2536 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2538 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2543 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2552 # Guestimate if this is a continuing comment. Run
2553 # the context looking for a comment "edge". If this
2554 # edge is a close comment then we must be in a comment
2558 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2559 next if (defined $rawlines[$ln - 1] &&
2560 $rawlines[$ln - 1] =~ /^-/);
2562 #print "RAW<$rawlines[$ln - 1]>\n";
2563 last if (!defined $rawlines[$ln - 1]);
2564 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2565 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2570 if (defined $edge && $edge eq '*/') {
2574 # Guestimate if this is a continuing comment. If this
2575 # is the start of a diff block and this line starts
2576 # ' *' then it is very likely a comment.
2577 if (!defined $edge &&
2578 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2583 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2584 sanitise_line_reset($in_comment);
2586 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2587 # Standardise the strings and chars within the input to
2588 # simplify matching -- only bother with positive lines.
2589 $line = sanitise_line($rawline);
2591 push(@lines, $line);
2594 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2599 #print "==>$rawline\n";
2600 #print "-->$line\n";
2602 if ($setup_docs && $line =~ /^\+/) {
2603 push(@setup_docs, $line);
2612 foreach my $line (@lines) {
2615 my $sline = $line; #copy of $line
2616 $sline =~ s/$;/ /g; #with comments as spaces
2618 my $rawline = $rawlines[$linenr - 1];
2619 my $raw_comment = get_raw_comment($line, $rawline);
2621 # check if it's a mode change, rename or start of a patch
2622 if (!$in_commit_log &&
2623 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2624 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2625 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2629 #extract the line range in the file after the patch is applied
2630 if (!$in_commit_log &&
2631 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2634 $first_line = $linenr + 1;
2644 %suppress_ifbraces = ();
2645 %suppress_whiletrailers = ();
2646 %suppress_export = ();
2647 $suppress_statement = 0;
2648 if ($context =~ /\b(\w+)\s*\(/) {
2649 $context_function = $1;
2651 undef $context_function;
2655 # track the line number as we move through the hunk, note that
2656 # new versions of GNU diff omit the leading space on completely
2657 # blank context lines so we need to count that too.
2658 } elsif ($line =~ /^( |\+|$)/) {
2660 $realcnt-- if ($realcnt != 0);
2662 # Measure the line length and indent.
2663 ($length, $indent) = line_stats($rawline);
2665 # Track the previous line.
2666 ($prevline, $stashline) = ($stashline, $line);
2667 ($previndent, $stashindent) = ($stashindent, $indent);
2668 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2670 #warn "line<$line>\n";
2672 } elsif ($realcnt == 1) {
2676 my $hunk_line = ($realcnt != 0);
2678 $here = "#$linenr: " if (!$file);
2679 $here = "#$realline: " if ($file);
2682 # extract the filename as it passes
2683 if ($line =~ /^diff --git.*?(\S+)$/) {
2685 $realfile =~ s@^([^/]*)/@@ if (!$file);
2688 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2690 $realfile =~ s@^([^/]*)/@@ if (!$file);
2694 if (!$file && $tree && $p1_prefix ne '' &&
2695 -e "$root/$p1_prefix") {
2696 WARN("PATCH_PREFIX",
2697 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2700 if ($realfile =~ m@^include/asm/@) {
2701 ERROR("MODIFIED_INCLUDE_ASM",
2702 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2707 #make up the handle for any error we report on this line
2709 $prefix = "$realfile:$realline: "
2712 $prefix = "$filename:$realline: ";
2714 $prefix = "$filename:$linenr: ";
2719 if (is_maintained_obsolete($realfile)) {
2721 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2723 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2726 $check = $check_orig;
2728 $checklicenseline = 1;
2730 if ($realfile !~ /^MAINTAINERS/) {
2731 my $last_binding_patch = $is_binding_patch;
2733 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2735 if (($last_binding_patch != -1) &&
2736 ($last_binding_patch ^ $is_binding_patch)) {
2737 WARN("DT_SPLIT_BINDING_PATCH",
2738 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2745 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2747 my $hereline = "$here\n$rawline\n";
2748 my $herecurr = "$here\n$rawline\n";
2749 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2751 $cnt_lines++ if ($realcnt != 0);
2753 # Verify the existence of a commit log if appropriate
2754 # 2 is used because a $signature is counted in $commit_log_lines
2755 if ($in_commit_log) {
2756 if ($line !~ /^\s*$/) {
2757 $commit_log_lines++; #could be a $signature
2759 } elsif ($has_commit_log && $commit_log_lines < 2) {
2760 WARN("COMMIT_MESSAGE",
2761 "Missing commit description - Add an appropriate one\n");
2762 $commit_log_lines = 2; #warn only once
2765 # Check if the commit log has what seems like a diff which can confuse patch
2766 if ($in_commit_log && !$commit_log_has_diff &&
2767 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2768 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2769 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2770 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2771 ERROR("DIFF_IN_COMMIT_MSG",
2772 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2773 $commit_log_has_diff = 1;
2776 # Check for incorrect file permissions
2777 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2778 my $permhere = $here . "FILE: $realfile\n";
2779 if ($realfile !~ m@scripts/@ &&
2780 $realfile !~ /\.(py|pl|awk|sh)$/) {
2781 ERROR("EXECUTE_PERMISSIONS",
2782 "do not set execute permissions for source files\n" . $permhere);
2786 # Check the patch for a From:
2787 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2789 my $curline = $linenr;
2790 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2793 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2795 $author = reformat_email($author);
2798 # Check the patch for a signoff:
2799 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2802 if ($author ne '' && $authorsignoff != 1) {
2803 if (same_email_addresses($1, $author)) {
2807 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2808 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2810 if ($email_address eq $author_address && $email_name eq $author_name) {
2813 } elsif ($email_address eq $author_address) {
2816 } elsif ($email_name eq $author_name) {
2820 my $address1 = $email_address;
2821 my $address2 = $author_address;
2823 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2826 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2829 if ($address1 eq $address2) {
2837 # Check for patch separator
2838 if ($line =~ /^---$/) {
2839 $has_patch_separator = 1;
2843 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2844 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2845 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2846 $reported_maintainer_file = 1;
2849 # Check signature styles
2850 if (!$in_header_lines &&
2851 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2852 my $space_before = $1;
2854 my $space_after = $3;
2856 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2858 if ($sign_off !~ /$signature_tags/) {
2859 my $suggested_signature = find_standard_signature($sign_off);
2860 if ($suggested_signature eq "") {
2861 WARN("BAD_SIGN_OFF",
2862 "Non-standard signature: $sign_off\n" . $herecurr);
2864 if (WARN("BAD_SIGN_OFF",
2865 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
2867 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
2871 if (defined $space_before && $space_before ne "") {
2872 if (WARN("BAD_SIGN_OFF",
2873 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2875 $fixed[$fixlinenr] =
2876 "$ucfirst_sign_off $email";
2879 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2880 if (WARN("BAD_SIGN_OFF",
2881 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2883 $fixed[$fixlinenr] =
2884 "$ucfirst_sign_off $email";
2888 if (!defined $space_after || $space_after ne " ") {
2889 if (WARN("BAD_SIGN_OFF",
2890 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2892 $fixed[$fixlinenr] =
2893 "$ucfirst_sign_off $email";
2897 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2898 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
2899 if ($suggested_email eq "") {
2900 ERROR("BAD_SIGN_OFF",
2901 "Unrecognized email address: '$email'\n" . $herecurr);
2903 my $dequoted = $suggested_email;
2904 $dequoted =~ s/^"//;
2905 $dequoted =~ s/" </ </;
2906 # Don't force email to have quotes
2907 # Allow just an angle bracketed address
2908 if (!same_email_addresses($email, $suggested_email)) {
2909 if (WARN("BAD_SIGN_OFF",
2910 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
2912 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
2916 # Address part shouldn't have comments
2917 my $stripped_address = $email_address;
2918 $stripped_address =~ s/\([^\(\)]*\)//g;
2919 if ($email_address ne $stripped_address) {
2920 if (WARN("BAD_SIGN_OFF",
2921 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
2923 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
2927 # Only one name comment should be allowed
2928 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
2929 if ($comment_count > 1) {
2930 WARN("BAD_SIGN_OFF",
2931 "Use a single name comment in email: '$email'\n" . $herecurr);
2935 # stable@vger.kernel.org or stable@kernel.org shouldn't
2936 # have an email name. In addition comments should strictly
2938 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
2939 if (($comment ne "" && $comment !~ /^#.+/) ||
2940 ($email_name ne "")) {
2941 my $cur_name = $email_name;
2942 my $new_comment = $comment;
2943 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
2945 # Remove brackets enclosing comment text
2946 # and # from start of comments to get comment text
2947 $new_comment =~ s/^\((.*)\)$/$1/;
2948 $new_comment =~ s/^\[(.*)\]$/$1/;
2949 $new_comment =~ s/^[\s\#]+|\s+$//g;
2951 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
2952 $new_comment = " # $new_comment" if ($new_comment ne "");
2953 my $new_email = "$email_address$new_comment";
2955 if (WARN("BAD_STABLE_ADDRESS_STYLE",
2956 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
2958 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2961 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
2962 my $new_comment = $comment;
2964 # Extract comment text from within brackets or
2965 # c89 style /*...*/ comments
2966 $new_comment =~ s/^\[(.*)\]$/$1/;
2967 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
2969 $new_comment = trim($new_comment);
2970 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
2971 $new_comment = "($new_comment)" if ($new_comment ne "");
2972 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
2974 if (WARN("BAD_SIGN_OFF",
2975 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
2977 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2982 # Check for duplicate signatures
2983 my $sig_nospace = $line;
2984 $sig_nospace =~ s/\s//g;
2985 $sig_nospace = lc($sig_nospace);
2986 if (defined $signatures{$sig_nospace}) {
2987 WARN("BAD_SIGN_OFF",
2988 "Duplicate signature\n" . $herecurr);
2990 $signatures{$sig_nospace} = 1;
2993 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2994 if ($sign_off =~ /^co-developed-by:$/i) {
2995 if ($email eq $author) {
2996 WARN("BAD_SIGN_OFF",
2997 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2999 if (!defined $lines[$linenr]) {
3000 WARN("BAD_SIGN_OFF",
3001 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3002 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3003 WARN("BAD_SIGN_OFF",
3004 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3005 } elsif ($1 ne $email) {
3006 WARN("BAD_SIGN_OFF",
3007 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3012 # Check email subject for common tools that don't need to be mentioned
3013 if ($in_header_lines &&
3014 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3015 WARN("EMAIL_SUBJECT",
3016 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3019 # Check for Gerrit Change-Ids not in any patch context
3020 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3021 if (ERROR("GERRIT_CHANGE_ID",
3022 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3024 fix_delete_line($fixlinenr, $rawline);
3028 # Check if the commit log is in a possible stack dump
3029 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3030 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3031 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3033 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3034 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3035 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3036 # stack dump address styles
3037 $commit_log_possible_stack_dump = 1;
3040 # Check for line lengths > 75 in commit log, warn once
3041 if ($in_commit_log && !$commit_log_long_line &&
3042 length($line) > 75 &&
3043 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3044 # file delta changes
3045 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
3047 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3048 # A Fixes: or Link: line or signature tag line
3049 $commit_log_possible_stack_dump)) {
3050 WARN("COMMIT_LOG_LONG_LINE",
3051 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3052 $commit_log_long_line = 1;
3055 # Reset possible stack dump if a blank line is found
3056 if ($in_commit_log && $commit_log_possible_stack_dump &&
3058 $commit_log_possible_stack_dump = 0;
3061 # Check for lines starting with a #
3062 if ($in_commit_log && $line =~ /^#/) {
3063 if (WARN("COMMIT_COMMENT_SYMBOL",
3064 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3066 $fixed[$fixlinenr] =~ s/^/ /;
3070 # Check for git id commit length and improperly formed commit descriptions
3071 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3072 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3073 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3074 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3075 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3076 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3077 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3078 my $init_char = "c";
3079 my $orig_commit = "";
3086 my $id = '0123456789ab';
3087 my $orig_desc = "commit description";
3088 my $description = "";
3090 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3092 $orig_commit = lc($2);
3093 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
3094 $orig_commit = lc($1);
3097 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3098 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
3099 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
3100 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3101 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
3104 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
3105 defined $rawlines[$linenr] &&
3106 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
3109 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
3110 defined $rawlines[$linenr] &&
3111 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
3112 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
3114 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
3115 $orig_desc .= " " . $1;
3119 ($id, $description) = git_commit_info($orig_commit,
3123 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
3124 ERROR("GIT_COMMIT_ID",
3125 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
3129 # Check for added, moved or deleted files
3130 if (!$reported_maintainer_file && !$in_commit_log &&
3131 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3132 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3133 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3134 (defined($1) || defined($2))))) {
3136 $reported_maintainer_file = 1;
3137 WARN("FILE_PATH_CHANGES",
3138 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3141 # Check for adding new DT bindings not in schema format
3142 if (!$in_commit_log &&
3143 ($line =~ /^new file mode\s*\d+\s*$/) &&
3144 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3145 WARN("DT_SCHEMA_BINDING_PATCH",
3146 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
3149 # Check for wrappage within a valid hunk of the file
3150 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3151 ERROR("CORRUPTED_PATCH",
3152 "patch seems to be corrupt (line wrapped?)\n" .
3153 $herecurr) if (!$emitted_corrupt++);
3156 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3157 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3158 $rawline !~ m/^$UTF8*$/) {
3159 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3161 my $blank = copy_spacing($rawline);
3162 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3163 my $hereptr = "$hereline$ptr\n";
3166 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3169 # Check if it's the start of a commit log
3170 # (not a header line and we haven't seen the patch filename)
3171 if ($in_header_lines && $realfile =~ /^$/ &&
3172 !($rawline =~ /^\s+(?:\S|$)/ ||
3173 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3174 $in_header_lines = 0;
3176 $has_commit_log = 1;
3179 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3180 # declined it, i.e defined some charset where it is missing.
3181 if ($in_header_lines &&
3182 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3184 $non_utf8_charset = 1;
3187 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3188 $rawline =~ /$NON_ASCII_UTF8/) {
3189 WARN("UTF8_BEFORE_PATCH",
3190 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3193 # Check for absolute kernel paths in commit message
3194 if ($tree && $in_commit_log) {
3195 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3198 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3199 check_absolute_file($1, $herecurr)) {
3202 check_absolute_file($file, $herecurr);
3207 # Check for various typo / spelling mistakes
3208 if (defined($misspellings) &&
3209 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3210 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3212 my $blank = copy_spacing($rawline);
3213 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3214 my $hereptr = "$hereline$ptr\n";
3215 my $typo_fix = $spelling_fix{lc($typo)};
3216 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3217 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3218 my $msg_level = \&WARN;
3219 $msg_level = \&CHK if ($file);
3220 if (&{$msg_level}("TYPO_SPELLING",
3221 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3223 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3228 # check for invalid commit id
3229 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3232 ($id, $description) = git_commit_info($2, undef, undef);
3233 if (!defined($id)) {
3234 WARN("UNKNOWN_COMMIT_ID",
3235 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3239 # check for repeated words separated by a single space
3240 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3241 if (($rawline =~ /^\+/ || $in_commit_log) &&
3242 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3243 pos($rawline) = 1 if (!$in_commit_log);
3244 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3248 my $start_pos = $-[1];
3249 my $end_pos = $+[2];
3250 if ($first =~ /(?:struct|union|enum)/) {
3251 pos($rawline) += length($first) + length($second) + 1;
3255 next if (lc($first) ne lc($second));
3256 next if ($first eq 'long');
3258 # check for character before and after the word matches
3259 my $start_char = '';
3261 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3262 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3264 next if ($start_char =~ /^\S$/);
3265 next if (index(" \t.,;?!", $end_char) == -1);
3267 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3268 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3269 next if (!exists($allow_repeated_words{lc($first)}));
3272 if (WARN("REPEATED_WORD",
3273 "Possible repeated word: '$first'\n" . $herecurr) &&
3275 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3279 # if it's a repeated word on consecutive lines in a comment block
3280 if ($prevline =~ /$;+\s*$/ &&
3281 $prevrawline =~ /($word_pattern)\s*$/) {
3283 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3284 if (WARN("REPEATED_WORD",
3285 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3287 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3293 # ignore non-hunk lines and lines being removed
3294 next if (!$hunk_line || $line =~ /^-/);
3296 #trailing whitespace
3297 if ($line =~ /^\+.*\015/) {
3298 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3299 if (ERROR("DOS_LINE_ENDINGS",
3300 "DOS line endings\n" . $herevet) &&
3302 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3304 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3305 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3306 if (ERROR("TRAILING_WHITESPACE",
3307 "trailing whitespace\n" . $herevet) &&
3309 $fixed[$fixlinenr] =~ s/\s+$//;
3315 # Check for FSF mailing addresses.
3316 if ($rawline =~ /\bwrite to the Free/i ||
3317 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3318 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3319 $rawline =~ /\b51\s+Franklin\s+St/i) {
3320 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3321 my $msg_level = \&ERROR;
3322 $msg_level = \&CHK if ($file);
3323 &{$msg_level}("FSF_MAILING_ADDRESS",
3324 "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)
3327 # check for Kconfig help text having a real description
3328 # Only applies when adding the entry originally, after that we do not have
3329 # sufficient context to determine whether it is indeed long enough.
3330 if ($realfile =~ /Kconfig/ &&
3331 # 'choice' is usually the last thing on the line (though
3332 # Kconfig supports named choices), so use a word boundary
3333 # (\b) rather than a whitespace character (\s)
3334 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3337 my $ln = $linenr + 1;
3341 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3342 $f = $lines[$ln - 1];
3343 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3344 $is_end = $lines[$ln - 1] =~ /^\+/;
3346 next if ($f =~ /^-/);
3347 last if (!$file && $f =~ /^\@\@/);
3349 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3351 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3358 next if ($f =~ /^$/);
3360 # This only checks context lines in the patch
3361 # and so hopefully shouldn't trigger false
3362 # positives, even though some of these are
3363 # common words in help texts
3364 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3365 if|endif|menu|endmenu|source)\b/x) {
3371 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3372 WARN("CONFIG_DESCRIPTION",
3373 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3375 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3378 # check MAINTAINERS entries
3379 if ($realfile =~ /^MAINTAINERS$/) {
3380 # check MAINTAINERS entries for the right form
3381 if ($rawline =~ /^\+[A-Z]:/ &&
3382 $rawline !~ /^\+[A-Z]:\t\S/) {
3383 if (WARN("MAINTAINERS_STYLE",
3384 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3386 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3389 # check MAINTAINERS entries for the right ordering too
3390 my $preferred_order = 'MRLSWQBCPTFXNK';
3391 if ($rawline =~ /^\+[A-Z]:/ &&
3392 $prevrawline =~ /^[\+ ][A-Z]:/) {
3393 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3396 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3399 my $curindex = index($preferred_order, $cur);
3400 my $previndex = index($preferred_order, $prev);
3401 if ($curindex < 0) {
3402 WARN("MAINTAINERS_STYLE",
3403 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3405 if ($previndex >= 0 && $curindex < $previndex) {
3406 WARN("MAINTAINERS_STYLE",
3407 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3408 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3409 ($prev eq 'X' && $cur eq 'X')) &&
3410 ($prevval cmp $curval) > 0) {
3411 WARN("MAINTAINERS_STYLE",
3412 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3418 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3419 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3422 'EXTRA_AFLAGS' => 'asflags-y',
3423 'EXTRA_CFLAGS' => 'ccflags-y',
3424 'EXTRA_CPPFLAGS' => 'cppflags-y',
3425 'EXTRA_LDFLAGS' => 'ldflags-y',
3428 WARN("DEPRECATED_VARIABLE",
3429 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3432 # check for DT compatible documentation
3433 if (defined $root &&
3434 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3435 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3437 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3439 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3440 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3442 foreach my $compat (@compats) {
3443 my $compat2 = $compat;
3444 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3445 my $compat3 = $compat;
3446 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3447 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3449 WARN("UNDOCUMENTED_DT_STRING",
3450 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3453 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3455 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3457 WARN("UNDOCUMENTED_DT_STRING",
3458 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3463 # check for using SPDX license tag at beginning of files
3464 if ($realline == $checklicenseline) {
3465 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3466 $checklicenseline = 2;
3467 } elsif ($rawline =~ /^\+/) {
3469 if ($realfile =~ /\.(h|s|S)$/) {
3471 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3473 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3475 } elsif ($realfile =~ /\.rst$/) {
3479 # check SPDX comment style for .[chsS] files
3480 if ($realfile =~ /\.[chsS]$/ &&
3481 $rawline =~ /SPDX-License-Identifier:/ &&
3482 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3483 WARN("SPDX_LICENSE_TAG",
3484 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3487 if ($comment !~ /^$/ &&
3488 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3489 WARN("SPDX_LICENSE_TAG",
3490 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3491 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3492 my $spdx_license = $1;
3493 if (!is_SPDX_License_valid($spdx_license)) {
3494 WARN("SPDX_LICENSE_TAG",
3495 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3497 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3498 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3499 my $msg_level = \&WARN;
3500 $msg_level = \&CHK if ($file);
3501 if (&{$msg_level}("SPDX_LICENSE_TAG",
3503 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3505 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3512 # check for embedded filenames
3513 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3514 WARN("EMBEDDED_FILENAME",
3515 "It's generally not useful to have the filename in the file\n" . $herecurr);
3518 # check we are in a valid source file if not then ignore this hunk
3519 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3521 # check for using SPDX-License-Identifier on the wrong line number
3522 if ($realline != $checklicenseline &&
3523 $rawline =~ /\bSPDX-License-Identifier:/ &&
3524 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3525 WARN("SPDX_LICENSE_TAG",
3526 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3529 # line length limit (with some exclusions)
3531 # There are a few types of lines that may extend beyond $max_line_length:
3532 # logging functions like pr_info that end in a string
3533 # lines with a single string
3534 # #defines that are a single string
3535 # lines with an RFC3986 like URL
3537 # There are 3 different line length message types:
3538 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3539 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3540 # LONG_LINE all other lines longer than $max_line_length
3542 # if LONG_LINE is ignored, the other 2 types are also ignored
3545 if ($line =~ /^\+/ && $length > $max_line_length) {
3546 my $msg_type = "LONG_LINE";
3548 # Check the allowed long line types first
3550 # logging functions that end in a string that starts
3551 # before $max_line_length
3552 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3553 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3556 # lines with only strings (w/ possible termination)
3557 # #defines with only strings
3558 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3559 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3562 # More special cases
3563 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3564 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3567 # URL ($rawline is used in case the URL is in a comment)
3568 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3571 # Otherwise set the alternate message types
3573 # a comment starts before $max_line_length
3574 } elsif ($line =~ /($;[\s$;]*)$/ &&
3575 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3576 $msg_type = "LONG_LINE_COMMENT"
3578 # a quoted string starts before $max_line_length
3579 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3580 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3581 $msg_type = "LONG_LINE_STRING"
3584 if ($msg_type ne "" &&
3585 (show_type("LONG_LINE") || show_type($msg_type))) {
3586 my $msg_level = \&WARN;
3587 $msg_level = \&CHK if ($file);
3588 &{$msg_level}($msg_type,
3589 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3593 # check for adding lines without a newline.
3594 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3595 if (WARN("MISSING_EOF_NEWLINE",
3596 "adding a line without newline at end of file\n" . $herecurr) &&
3598 fix_delete_line($fixlinenr+1, "No newline at end of file");
3602 # check for .L prefix local symbols in .S files
3603 if ($realfile =~ /\.S$/ &&
3604 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3605 WARN("AVOID_L_PREFIX",
3606 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/asm-annotations.rst\n" . $herecurr);
3609 # check we are in a valid source file C or perl if not then ignore this hunk
3610 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3612 # at the beginning of a line any tabs must come first and anything
3613 # more than $tabsize must use tabs.
3614 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3615 $rawline =~ /^\+\s* \s*/) {
3616 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3618 if (ERROR("CODE_INDENT",
3619 "code indent should use tabs where possible\n" . $herevet) &&
3621 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3625 # check for space before tabs.
3626 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3627 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3628 if (WARN("SPACE_BEFORE_TAB",
3629 "please, no space before tabs\n" . $herevet) &&
3631 while ($fixed[$fixlinenr] =~
3632 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3633 while ($fixed[$fixlinenr] =~
3634 s/(^\+.*) +\t/$1\t/) {}
3638 # check for assignments on the start of a line
3639 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3641 if (CHK("ASSIGNMENT_CONTINUATIONS",
3642 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3643 $fix && $prevrawline =~ /^\+/) {
3644 # add assignment operator to the previous line, remove from current line
3645 $fixed[$fixlinenr - 1] .= " $operator";
3646 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3650 # check for && or || at the start of a line
3651 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3653 if (CHK("LOGICAL_CONTINUATIONS",
3654 "Logical continuations should be on the previous line\n" . $hereprev) &&
3655 $fix && $prevrawline =~ /^\+/) {
3656 # insert logical operator at last non-comment, non-whitepsace char on previous line
3657 $prevline =~ /[\s$;]*$/;
3658 my $line_end = substr($prevrawline, $-[0]);
3659 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3660 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3664 # check indentation starts on a tab stop
3665 if ($perl_version_ok &&
3666 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3667 my $indent = length($1);
3668 if ($indent % $tabsize) {
3670 "Statements should start on a tabstop\n" . $herecurr) &&
3672 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3677 # check multi-line statement indentation matches previous line
3678 if ($perl_version_ok &&
3679 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3680 $prevline =~ /^\+(\t*)(.*)$/;
3684 my $pos = pos_last_openparen($rest);
3686 $line =~ /^(\+| )([ \t]*)/;
3689 my $goodtabindent = $oldindent .
3690 "\t" x ($pos / $tabsize) .
3691 " " x ($pos % $tabsize);
3692 my $goodspaceindent = $oldindent . " " x $pos;
3694 if ($newindent ne $goodtabindent &&
3695 $newindent ne $goodspaceindent) {
3697 if (CHK("PARENTHESIS_ALIGNMENT",
3698 "Alignment should match open parenthesis\n" . $hereprev) &&
3699 $fix && $line =~ /^\+/) {
3700 $fixed[$fixlinenr] =~
3701 s/^\+[ \t]*/\+$goodtabindent/;
3707 # check for space after cast like "(int) foo" or "(struct foo) bar"
3708 # avoid checking a few false positives:
3709 # "sizeof(<type>)" or "__alignof__(<type>)"
3710 # function pointer declarations like "(*foo)(int) = bar;"
3711 # structure definitions like "(struct foo) { 0 };"
3712 # multiline macros that define functions
3713 # known attributes or the __attribute__ keyword
3714 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3715 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3717 "No space is necessary after a cast\n" . $herecurr) &&
3719 $fixed[$fixlinenr] =~
3720 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3724 # Block comment styles
3725 # Networking with an initial /*
3726 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3727 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3728 $rawline =~ /^\+[ \t]*\*/ &&
3729 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3730 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3731 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3734 # Block comments use * on subsequent lines
3735 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3736 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3737 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3738 $rawline =~ /^\+/ && #line is new
3739 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3740 WARN("BLOCK_COMMENT_STYLE",
3741 "Block comments use * on subsequent lines\n" . $hereprev);
3744 # Block comments use */ on trailing lines
3745 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3746 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3747 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3748 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3749 WARN("BLOCK_COMMENT_STYLE",
3750 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3753 # Block comment * alignment
3754 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3755 $line =~ /^\+[ \t]*$;/ && #leading comment
3756 $rawline =~ /^\+[ \t]*\*/ && #leading *
3757 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3758 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3759 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3761 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3763 $oldindent = expand_tabs($1);
3765 $prevrawline =~ m@^\+(.*/?)\*@;
3766 $oldindent = expand_tabs($1);
3768 $rawline =~ m@^\+([ \t]*)\*@;
3770 $newindent = expand_tabs($newindent);
3771 if (length($oldindent) ne length($newindent)) {
3772 WARN("BLOCK_COMMENT_STYLE",
3773 "Block comments should align the * on each line\n" . $hereprev);
3777 # check for missing blank lines after struct/union declarations
3778 # with exceptions for various attributes and macros
3779 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3781 !($line =~ /^\+\s*$/ ||
3782 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3783 $line =~ /^\+\s*MODULE_/i ||
3784 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3785 $line =~ /^\+[a-z_]*init/ ||
3786 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3787 $line =~ /^\+\s*DECLARE/ ||
3788 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3789 $line =~ /^\+\s*__setup/)) {
3790 if (CHK("LINE_SPACING",
3791 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3793 fix_insert_line($fixlinenr, "\+");
3797 # check for multiple consecutive blank lines
3798 if ($prevline =~ /^[\+ ]\s*$/ &&
3799 $line =~ /^\+\s*$/ &&
3800 $last_blank_line != ($linenr - 1)) {
3801 if (CHK("LINE_SPACING",
3802 "Please don't use multiple blank lines\n" . $hereprev) &&
3804 fix_delete_line($fixlinenr, $rawline);
3807 $last_blank_line = $linenr;
3810 # check for missing blank lines after declarations
3811 # (declarations must have the same indentation and not be at the start of line)
3812 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3816 # remove $Attribute/$Sparse uses to simplify comparisons
3817 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3818 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3819 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3820 # function pointer declarations
3821 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3822 # foo bar; where foo is some local typedef or #define
3823 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3824 # known declaration macros
3825 $pl =~ /^\+\s+$declaration_macros/) &&
3826 # for "else if" which can look like "$Ident $Ident"
3827 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3828 # other possible extensions of declaration lines
3829 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3830 # not starting a section or a macro "\" extended line
3831 $pl =~ /(?:\{\s*|\\)$/) &&
3832 # looks like a declaration
3833 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3834 # function pointer declarations
3835 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3836 # foo bar; where foo is some local typedef or #define
3837 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3838 # known declaration macros
3839 $sl =~ /^\+\s+$declaration_macros/ ||
3840 # start of struct or union or enum
3841 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3842 # start or end of block or continuation of declaration
3843 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3844 # bitfield continuation
3845 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3846 # other possible extensions of declaration lines
3847 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3848 if (WARN("LINE_SPACING",
3849 "Missing a blank line after declarations\n" . $hereprev) &&
3851 fix_insert_line($fixlinenr, "\+");
3856 # check for spaces at the beginning of a line.
3858 # 1) within comments
3859 # 2) indented preprocessor commands
3861 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3862 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3863 if (WARN("LEADING_SPACE",
3864 "please, no spaces at the start of a line\n" . $herevet) &&
3866 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3870 # check we are in a valid C source file if not then ignore this hunk
3871 next if ($realfile !~ /\.(h|c)$/);
3873 # check for unusual line ending [ or (
3874 if ($line =~ /^\+.*([\[\(])\s*$/) {
3875 CHK("OPEN_ENDED_LINE",
3876 "Lines should not end with a '$1'\n" . $herecurr);
3879 # check if this appears to be the start function declaration, save the name
3880 if ($sline =~ /^\+\{\s*$/ &&
3881 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3882 $context_function = $1;
3885 # check if this appears to be the end of function declaration
3886 if ($sline =~ /^\+\}\s*$/) {
3887 undef $context_function;
3890 # check indentation of any line with a bare else
3891 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3892 # if the previous line is a break or return and is indented 1 tab more...
3893 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3894 my $tabs = length($1) + 1;
3895 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3896 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3897 defined $lines[$linenr] &&
3898 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3899 WARN("UNNECESSARY_ELSE",
3900 "else is not generally useful after a break or return\n" . $hereprev);
3904 # check indentation of a line with a break;
3905 # if the previous line is a goto, return or break
3906 # and is indented the same # of tabs
3907 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3909 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3910 if (WARN("UNNECESSARY_BREAK",
3911 "break is not useful after a $1\n" . $hereprev) &&
3913 fix_delete_line($fixlinenr, $rawline);
3918 # check for RCS/CVS revision markers
3919 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3921 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3924 # check for old HOTPLUG __dev<foo> section markings
3925 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3926 WARN("HOTPLUG_SECTION",
3927 "Using $1 is unnecessary\n" . $herecurr);
3930 # Check for potential 'bare' types
3931 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3933 #print "LINE<$line>\n";
3934 if ($linenr > $suppress_statement &&
3935 $realcnt && $sline =~ /.\s*\S/) {
3936 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3937 ctx_statement_block($linenr, $realcnt, 0);
3938 $stat =~ s/\n./\n /g;
3939 $cond =~ s/\n./\n /g;
3941 #print "linenr<$linenr> <$stat>\n";
3942 # If this statement has no statement boundaries within
3943 # it there is no point in retrying a statement scan
3944 # until we hit end of it.
3945 my $frag = $stat; $frag =~ s/;+\s*$//;
3946 if ($frag !~ /(?:{|;)/) {
3947 #print "skip<$line_nr_next>\n";
3948 $suppress_statement = $line_nr_next;
3951 # Find the real next line.
3952 $realline_next = $line_nr_next;
3953 if (defined $realline_next &&
3954 (!defined $lines[$realline_next - 1] ||
3955 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3962 # Ignore goto labels.
3963 if ($s =~ /$Ident:\*$/s) {
3965 # Ignore functions being called
3966 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3968 } elsif ($s =~ /^.\s*else\b/s) {
3970 # declarations always start with types
3971 } 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) {
3974 possible($type, "A:" . $s);
3976 # definitions in global scope can only start with types
3977 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3978 possible($1, "B:" . $s);
3981 # any (foo ... *) is a pointer cast, and foo is a type
3982 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3983 possible($1, "C:" . $s);
3986 # Check for any sort of function declaration.
3987 # int foo(something bar, other baz);
3988 # void (*store_gdt)(x86_descr_ptr *);
3989 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3990 my ($name_len) = length($1);
3993 substr($ctx, 0, $name_len + 1, '');
3994 $ctx =~ s/\)[^\)]*$//;
3996 for my $arg (split(/\s*,\s*/, $ctx)) {
3997 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3999 possible($1, "D:" . $s);
4007 # Checks which may be anchored in the context.
4010 # Check for switch () and associated case and default
4011 # statements should be at the same indent.
4012 if ($line=~/\bswitch\s*\(.*\)/) {
4015 my @ctx = ctx_block_outer($linenr, $realcnt);
4017 for my $ctx (@ctx) {
4018 my ($clen, $cindent) = line_stats($ctx);
4019 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4020 $indent != $cindent) {
4021 $err .= "$sep$ctx\n";
4028 ERROR("SWITCH_CASE_INDENT_LEVEL",
4029 "switch and case should be at the same indent\n$hereline$err");
4033 # if/while/etc brace do not go on next line, unless defining a do while loop,
4034 # or if that brace on the next line is for something else
4035 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4036 my $pre_ctx = "$1$2";
4038 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4040 if ($line =~ /^\+\t{6,}/) {
4041 WARN("DEEP_INDENTATION",
4042 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4045 my $ctx_cnt = $realcnt - $#ctx - 1;
4046 my $ctx = join("\n", @ctx);
4048 my $ctx_ln = $linenr;
4049 my $ctx_skip = $realcnt;
4051 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4052 defined $lines[$ctx_ln - 1] &&
4053 $lines[$ctx_ln - 1] =~ /^-/)) {
4054 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4055 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4059 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4060 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4062 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4064 "that open brace { should be on the previous line\n" .
4065 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4067 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4068 $ctx =~ /\)\s*\;\s*$/ &&
4069 defined $lines[$ctx_ln - 1])
4071 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4072 if ($nindent > $indent) {
4073 WARN("TRAILING_SEMICOLON",
4074 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4075 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4080 # Check relative indent for conditionals and blocks.
4081 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4082 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4083 ctx_statement_block($linenr, $realcnt, 0)
4084 if (!defined $stat);
4085 my ($s, $c) = ($stat, $cond);
4087 substr($s, 0, length($c), '');
4089 # remove inline comments
4093 # Find out how long the conditional actually is.
4094 my @newlines = ($c =~ /\n/gs);
4095 my $cond_lines = 1 + $#newlines;
4097 # Make sure we remove the line prefixes as we have
4098 # none on the first line, and are going to readd them
4101 while ($s =~ /\n\s+\\\n/) {
4102 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4105 # We want to check the first line inside the block
4106 # starting at the end of the conditional, so remove:
4107 # 1) any blank line termination
4108 # 2) any opening brace { on end of the line
4110 my $continuation = 0;
4112 $s =~ s/^.*\bdo\b//;
4114 if ($s =~ s/^\s*\\//) {
4117 if ($s =~ s/^\s*?\n//) {
4122 # Also ignore a loop construct at the end of a
4123 # preprocessor statement.
4124 if (($prevline =~ /^.\s*#\s*define\s/ ||
4125 $prevline =~ /\\\s*$/) && $continuation == 0) {
4131 while ($cond_ptr != $cond_lines) {
4132 $cond_ptr = $cond_lines;
4134 # If we see an #else/#elif then the code
4136 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4141 # 1) blank lines, they should be at 0,
4142 # 2) preprocessor lines, and
4144 if ($continuation ||
4146 $s =~ /^\s*#\s*?/ ||
4147 $s =~ /^\s*$Ident\s*:/) {
4148 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4149 if ($s =~ s/^.*?\n//) {
4155 my (undef, $sindent) = line_stats("+" . $s);
4156 my $stat_real = raw_line($linenr, $cond_lines);
4158 # Check if either of these lines are modified, else
4159 # this is not this patch's fault.
4160 if (!defined($stat_real) ||
4161 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4164 if (defined($stat_real) && $cond_lines > 1) {
4165 $stat_real = "[...]\n$stat_real";
4168 #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";
4170 if ($check && $s ne '' &&
4171 (($sindent % $tabsize) != 0 ||
4172 ($sindent < $indent) ||
4173 ($sindent == $indent &&
4174 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4175 ($sindent > $indent + $tabsize))) {
4176 WARN("SUSPECT_CODE_INDENT",
4177 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4181 # Track the 'values' across context and added lines.
4182 my $opline = $line; $opline =~ s/^./ /;
4183 my ($curr_values, $curr_vars) =
4184 annotate_values($opline . "\n", $prev_values);
4185 $curr_values = $prev_values . $curr_values;
4187 my $outline = $opline; $outline =~ s/\t/ /g;
4188 print "$linenr > .$outline\n";
4189 print "$linenr > $curr_values\n";
4190 print "$linenr > $curr_vars\n";
4192 $prev_values = substr($curr_values, -1);
4194 #ignore lines not being added
4195 next if ($line =~ /^[^\+]/);
4197 # check for self assignments used to avoid compiler warnings
4198 # e.g.: int foo = foo, *bar = NULL;
4199 # struct foo bar = *(&(bar));
4200 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4202 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4203 WARN("SELF_ASSIGNMENT",
4204 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4208 # check for dereferences that span multiple lines
4209 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4210 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4211 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4213 $line =~ /^.\s*($Lval)/;
4216 WARN("MULTILINE_DEREFERENCE",
4217 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4220 # check for declarations of signed or unsigned without int
4221 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4224 $var = "" if (!defined $var);
4225 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4229 $pointer = "" if (!defined $pointer);
4231 if (WARN("UNSPECIFIED_INT",
4232 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4234 my $decl = trim($sign) . " int ";
4235 my $comp_pointer = $pointer;
4236 $comp_pointer =~ s/\s//g;
4237 $decl .= $comp_pointer;
4238 $decl = rtrim($decl) if ($var eq "");
4239 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4244 # TEST: allow direct testing of the type matcher.
4246 if ($line =~ /^.\s*$Declare\s*$/) {
4248 "TEST: is type\n" . $herecurr);
4249 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4250 ERROR("TEST_NOT_TYPE",
4251 "TEST: is not type ($1 is)\n". $herecurr);
4255 # TEST: allow direct testing of the attribute matcher.
4257 if ($line =~ /^.\s*$Modifier\s*$/) {
4259 "TEST: is attr\n" . $herecurr);
4260 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4261 ERROR("TEST_NOT_ATTR",
4262 "TEST: is not attr ($1 is)\n". $herecurr);
4267 # check for initialisation to aggregates open brace on the next line
4268 if ($line =~ /^.\s*{/ &&
4269 $prevline =~ /(?:^|[^=])=\s*$/) {
4270 if (ERROR("OPEN_BRACE",
4271 "that open brace { should be on the previous line\n" . $hereprev) &&
4272 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4273 fix_delete_line($fixlinenr - 1, $prevrawline);
4274 fix_delete_line($fixlinenr, $rawline);
4275 my $fixedline = $prevrawline;
4276 $fixedline =~ s/\s*=\s*$/ = {/;
4277 fix_insert_line($fixlinenr, $fixedline);
4279 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4280 fix_insert_line($fixlinenr, $fixedline);
4285 # Checks which are anchored on the added line.
4288 # check for malformed paths in #include statements (uses RAW line)
4289 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4291 if ($path =~ m{//}) {
4292 ERROR("MALFORMED_INCLUDE",
4293 "malformed #include filename\n" . $herecurr);
4295 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4296 ERROR("UAPI_INCLUDE",
4297 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4301 # no C99 // comments
4302 if ($line =~ m{//}) {
4303 if (ERROR("C99_COMMENTS",
4304 "do not use C99 // comments\n" . $herecurr) &&
4306 my $line = $fixed[$fixlinenr];
4307 if ($line =~ /\/\/(.*)$/) {
4308 my $comment = trim($1);
4309 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4313 # Remove C99 comments.
4315 $opline =~ s@//.*@@;
4317 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4318 # the whole statement.
4319 #print "APW <$lines[$realline_next - 1]>\n";
4320 if (defined $realline_next &&
4321 exists $lines[$realline_next - 1] &&
4322 !defined $suppress_export{$realline_next} &&
4323 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4324 # Handle definitions which produce identifiers with
4327 # EXPORT_SYMBOL(something_foo);
4329 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4330 $name =~ /^${Ident}_$2/) {
4331 #print "FOO C name<$name>\n";
4332 $suppress_export{$realline_next} = 1;
4334 } elsif ($stat !~ /(?:
4336 ^.DEFINE_$Ident\(\Q$name\E\)|
4337 ^.DECLARE_$Ident\(\Q$name\E\)|
4338 ^.LIST_HEAD\(\Q$name\E\)|
4339 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4340 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4342 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4343 $suppress_export{$realline_next} = 2;
4345 $suppress_export{$realline_next} = 1;
4348 if (!defined $suppress_export{$linenr} &&
4349 $prevline =~ /^.\s*$/ &&
4350 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4351 #print "FOO B <$lines[$linenr - 1]>\n";
4352 $suppress_export{$linenr} = 2;
4354 if (defined $suppress_export{$linenr} &&
4355 $suppress_export{$linenr} == 2) {
4356 WARN("EXPORT_SYMBOL",
4357 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4360 # check for global initialisers.
4361 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4362 if (ERROR("GLOBAL_INITIALISERS",
4363 "do not initialise globals to $1\n" . $herecurr) &&
4365 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4368 # check for static initialisers.
4369 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4370 if (ERROR("INITIALISED_STATIC",
4371 "do not initialise statics to $1\n" .
4374 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4378 # check for misordered declarations of char/short/int/long with signed/unsigned
4379 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4381 WARN("MISORDERED_TYPE",
4382 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4385 # check for unnecessary <signed> int declarations of short/long/long long
4386 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4387 my $type = trim($1);
4388 next if ($type !~ /\bint\b/);
4389 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4390 my $new_type = $type;
4391 $new_type =~ s/\b\s*int\s*\b/ /;
4392 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4393 $new_type =~ s/^const\s+//;
4394 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4395 $new_type = "const $new_type" if ($type =~ /^const\b/);
4396 $new_type =~ s/\s+/ /g;
4397 $new_type = trim($new_type);
4398 if (WARN("UNNECESSARY_INT",
4399 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4401 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4405 # check for static const char * arrays.
4406 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4407 WARN("STATIC_CONST_CHAR_ARRAY",
4408 "static const char * array should probably be static const char * const\n" .
4412 # check for initialized const char arrays that should be static const
4413 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4414 if (WARN("STATIC_CONST_CHAR_ARRAY",
4415 "const array should probably be static const\n" . $herecurr) &&
4417 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4421 # check for static char foo[] = "bar" declarations.
4422 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4423 WARN("STATIC_CONST_CHAR_ARRAY",
4424 "static char array declaration should probably be static const char\n" .
4428 # check for const <foo> const where <foo> is not a pointer or array type
4429 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4431 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4433 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4434 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4436 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4440 # check for const static or static <non ptr type> const declarations
4441 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4442 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4443 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4444 if (WARN("STATIC_CONST",
4445 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4447 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4448 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4452 # check for non-global char *foo[] = {"bar", ...} declarations.
4453 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4454 WARN("STATIC_CONST_CHAR_ARRAY",
4455 "char * array declaration might be better as static const\n" .
4459 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4460 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4462 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4464 if (WARN("ARRAY_SIZE",
4465 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4467 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4472 # check for function declarations without arguments like "int foo()"
4473 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4474 if (ERROR("FUNCTION_WITHOUT_ARGS",
4475 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4477 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4481 # check for new typedefs, only function parameters and sparse annotations
4483 if ($line =~ /\btypedef\s/ &&
4484 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4485 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4486 $line !~ /\b$typeTypedefs\b/ &&
4487 $line !~ /\b__bitwise\b/) {
4488 WARN("NEW_TYPEDEFS",
4489 "do not add new typedefs\n" . $herecurr);
4492 # * goes on variable not on type
4494 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4496 my ($ident, $from, $to) = ($1, $2, $2);
4498 # Should start with a space.
4499 $to =~ s/^(\S)/ $1/;
4500 # Should not end with a space.
4502 # '*'s should not have spaces between.
4503 while ($to =~ s/\*\s+\*/\*\*/) {
4506 ## print "1: from<$from> to<$to> ident<$ident>\n";
4508 if (ERROR("POINTER_LOCATION",
4509 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4511 my $sub_from = $ident;
4512 my $sub_to = $ident;
4513 $sub_to =~ s/\Q$from\E/$to/;
4514 $fixed[$fixlinenr] =~
4515 s@\Q$sub_from\E@$sub_to@;
4519 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4521 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4523 # Should start with a space.
4524 $to =~ s/^(\S)/ $1/;
4525 # Should not end with a space.
4527 # '*'s should not have spaces between.
4528 while ($to =~ s/\*\s+\*/\*\*/) {
4530 # Modifiers should have spaces.
4531 $to =~ s/(\b$Modifier$)/$1 /;
4533 ## print "2: from<$from> to<$to> ident<$ident>\n";
4534 if ($from ne $to && $ident !~ /^$Modifier$/) {
4535 if (ERROR("POINTER_LOCATION",
4536 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4539 my $sub_from = $match;
4540 my $sub_to = $match;
4541 $sub_to =~ s/\Q$from\E/$to/;
4542 $fixed[$fixlinenr] =~
4543 s@\Q$sub_from\E@$sub_to@;
4548 # avoid BUG() or BUG_ON()
4549 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4550 my $msg_level = \&WARN;
4551 $msg_level = \&CHK if ($file);
4552 &{$msg_level}("AVOID_BUG",
4553 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4556 # avoid LINUX_VERSION_CODE
4557 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4558 WARN("LINUX_VERSION_CODE",
4559 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4562 # check for uses of printk_ratelimit
4563 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4564 WARN("PRINTK_RATELIMITED",
4565 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4568 # printk should use KERN_* levels
4569 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4570 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4571 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4574 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4575 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4579 $modifier = "" if (!defined($modifier));
4580 my $level = lc($orig);
4581 $level = "warn" if ($level eq "warning");
4582 my $level2 = $level;
4583 $level2 = "dbg" if ($level eq "debug");
4584 $level .= $modifier;
4585 $level2 .= $modifier;
4586 WARN("PREFER_PR_LEVEL",
4587 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4590 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4591 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4593 my $level = lc($orig);
4594 $level = "warn" if ($level eq "warning");
4595 $level = "dbg" if ($level eq "debug");
4596 WARN("PREFER_DEV_LEVEL",
4597 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4600 # trace_printk should not be used in production code.
4601 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4602 WARN("TRACE_PRINTK",
4603 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4606 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4607 # number of false positives, but assembly files are not checked, so at
4608 # least the arch entry code will not trigger this warning.
4609 if ($line =~ /\bENOSYS\b/) {
4611 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4614 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4615 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4616 # Similarly to ENOSYS warning a small number of false positives is expected.
4617 if (!$file && $line =~ /\bENOTSUPP\b/) {
4618 if (WARN("ENOTSUPP",
4619 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4621 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4625 # function brace can't be on same line, except for #defines of do while,
4626 # or if closed on same line
4627 if ($perl_version_ok &&
4628 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4629 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4631 if (ERROR("OPEN_BRACE",
4632 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4634 fix_delete_line($fixlinenr, $rawline);
4635 my $fixed_line = $rawline;
4636 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4639 fix_insert_line($fixlinenr, ltrim($line1));
4640 fix_insert_line($fixlinenr, "\+{");
4641 if ($line2 !~ /^\s*$/) {
4642 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4647 # open braces for enum, union and struct go on the same line.
4648 if ($line =~ /^.\s*{/ &&
4649 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4650 if (ERROR("OPEN_BRACE",
4651 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4652 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4653 fix_delete_line($fixlinenr - 1, $prevrawline);
4654 fix_delete_line($fixlinenr, $rawline);
4655 my $fixedline = rtrim($prevrawline) . " {";
4656 fix_insert_line($fixlinenr, $fixedline);
4657 $fixedline = $rawline;
4658 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4659 if ($fixedline !~ /^\+\s*$/) {
4660 fix_insert_line($fixlinenr, $fixedline);
4665 # missing space after union, struct or enum definition
4666 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4668 "missing space after $1 definition\n" . $herecurr) &&
4670 $fixed[$fixlinenr] =~
4671 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4675 # Function pointer declarations
4676 # check spacing between type, funcptr, and args
4677 # canonical declaration is "type (*funcptr)(args...)"
4678 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4680 my $pre_pointer_space = $2;
4681 my $post_pointer_space = $3;
4683 my $post_funcname_space = $5;
4684 my $pre_args_space = $6;
4686 # the $Declare variable will capture all spaces after the type
4687 # so check it for a missing trailing missing space but pointer return types
4688 # don't need a space so don't warn for those.
4689 my $post_declare_space = "";
4690 if ($declare =~ /(\s+)$/) {
4691 $post_declare_space = $1;
4692 $declare = rtrim($declare);
4694 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4696 "missing space after return type\n" . $herecurr);
4697 $post_declare_space = " ";
4700 # unnecessary space "type (*funcptr)(args...)"
4701 # This test is not currently implemented because these declarations are
4703 # int foo(int bar, ...)
4704 # and this is form shouldn't/doesn't generate a checkpatch warning.
4706 # elsif ($declare =~ /\s{2,}$/) {
4708 # "Multiple spaces after return type\n" . $herecurr);
4711 # unnecessary space "type ( *funcptr)(args...)"
4712 if (defined $pre_pointer_space &&
4713 $pre_pointer_space =~ /^\s/) {
4715 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4718 # unnecessary space "type (* funcptr)(args...)"
4719 if (defined $post_pointer_space &&
4720 $post_pointer_space =~ /^\s/) {
4722 "Unnecessary space before function pointer name\n" . $herecurr);
4725 # unnecessary space "type (*funcptr )(args...)"
4726 if (defined $post_funcname_space &&
4727 $post_funcname_space =~ /^\s/) {
4729 "Unnecessary space after function pointer name\n" . $herecurr);
4732 # unnecessary space "type (*funcptr) (args...)"
4733 if (defined $pre_args_space &&
4734 $pre_args_space =~ /^\s/) {
4736 "Unnecessary space before function pointer arguments\n" . $herecurr);
4739 if (show_type("SPACING") && $fix) {
4740 $fixed[$fixlinenr] =~
4741 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4745 # check for spacing round square brackets; allowed:
4746 # 1. with a type on the left -- int [] a;
4747 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4748 # 3. inside a curly brace -- = { [0...10] = 5 }
4749 while ($line =~ /(.*?\s)\[/g) {
4750 my ($where, $prefix) = ($-[1], $1);
4751 if ($prefix !~ /$Type\s+$/ &&
4752 ($where != 0 || $prefix !~ /^.\s+$/) &&
4753 $prefix !~ /[{,:]\s+$/) {
4754 if (ERROR("BRACKET_SPACE",
4755 "space prohibited before open square bracket '['\n" . $herecurr) &&
4757 $fixed[$fixlinenr] =~
4758 s/^(\+.*?)\s+\[/$1\[/;
4763 # check for spaces between functions and their parentheses.
4764 while ($line =~ /($Ident)\s+\(/g) {
4766 my $ctx_before = substr($line, 0, $-[1]);
4767 my $ctx = "$ctx_before$name";
4769 # Ignore those directives where spaces _are_ permitted.
4771 if|for|while|switch|return|case|
4772 volatile|__volatile__|
4773 __attribute__|format|__extension__|
4776 # cpp #define statements have non-optional spaces, ie
4777 # if there is a space between the name and the open
4778 # parenthesis it is simply not a parameter group.
4779 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4781 # cpp #elif statement condition may start with a (
4782 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4784 # If this whole things ends with a type its most
4785 # likely a typedef for a function.
4786 } elsif ($ctx =~ /$Type$/) {
4790 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4792 $fixed[$fixlinenr] =~
4793 s/\b$name\s+\(/$name\(/;
4798 # Check operator spacing.
4799 if (!($line=~/\#\s*include/)) {
4800 my $fixed_line = "";
4804 <<=|>>=|<=|>=|==|!=|
4805 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4806 =>|->|<<|>>|<|>|=|!|~|
4807 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4810 my @elements = split(/($ops|;)/, $opline);
4812 ## print("element count: <" . $#elements . ">\n");
4813 ## foreach my $el (@elements) {
4814 ## print("el: <$el>\n");
4817 my @fix_elements = ();
4820 foreach my $el (@elements) {
4821 push(@fix_elements, substr($rawline, $off, length($el)));
4822 $off += length($el);
4827 my $blank = copy_spacing($opline);
4828 my $last_after = -1;
4830 for (my $n = 0; $n < $#elements; $n += 2) {
4832 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4834 ## print("n: <$n> good: <$good>\n");
4836 $off += length($elements[$n]);
4838 # Pick up the preceding and succeeding characters.
4839 my $ca = substr($opline, 0, $off);
4841 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4842 $cc = substr($opline, $off + length($elements[$n + 1]));
4844 my $cb = "$ca$;$cc";
4847 $a = 'V' if ($elements[$n] ne '');
4848 $a = 'W' if ($elements[$n] =~ /\s$/);
4849 $a = 'C' if ($elements[$n] =~ /$;$/);
4850 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4851 $a = 'O' if ($elements[$n] eq '');
4852 $a = 'E' if ($ca =~ /^\s*$/);
4854 my $op = $elements[$n + 1];
4857 if (defined $elements[$n + 2]) {
4858 $c = 'V' if ($elements[$n + 2] ne '');
4859 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4860 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4861 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4862 $c = 'O' if ($elements[$n + 2] eq '');
4863 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4868 my $ctx = "${a}x${c}";
4870 my $at = "(ctx:$ctx)";
4872 my $ptr = substr($blank, 0, $off) . "^";
4873 my $hereptr = "$hereline$ptr\n";
4875 # Pull out the value of this operator.
4876 my $op_type = substr($curr_values, $off + 1, 1);
4878 # Get the full operator variant.
4879 my $opv = $op . substr($curr_vars, $off, 1);
4881 # Ignore operators passed as parameters.
4882 if ($op_type ne 'V' &&
4883 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4886 # } elsif ($op =~ /^$;+$/) {
4888 # ; should have either the end of line or a space or \ after it
4889 } elsif ($op eq ';') {
4890 if ($ctx !~ /.x[WEBC]/ &&
4891 $cc !~ /^\\/ && $cc !~ /^;/) {
4892 if (ERROR("SPACING",
4893 "space required after that '$op' $at\n" . $hereptr)) {
4894 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4900 } elsif ($op eq '//') {
4902 # : when part of a bitfield
4903 } elsif ($opv eq ':B') {
4904 # skip the bitfield test for now
4908 } elsif ($op eq '->') {
4909 if ($ctx =~ /Wx.|.xW/) {
4910 if (ERROR("SPACING",
4911 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4912 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4913 if (defined $fix_elements[$n + 2]) {
4914 $fix_elements[$n + 2] =~ s/^\s+//;
4920 # , must not have a space before and must have a space on the right.
4921 } elsif ($op eq ',') {
4922 my $rtrim_before = 0;
4923 my $space_after = 0;
4924 if ($ctx =~ /Wx./) {
4925 if (ERROR("SPACING",
4926 "space prohibited before that '$op' $at\n" . $hereptr)) {
4931 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4932 if (ERROR("SPACING",
4933 "space required after that '$op' $at\n" . $hereptr)) {
4939 if ($rtrim_before || $space_after) {
4940 if ($rtrim_before) {
4941 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4943 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4950 # '*' as part of a type definition -- reported already.
4951 } elsif ($opv eq '*_') {
4952 #warn "'*' is part of type\n";
4954 # unary operators should have a space before and
4955 # none after. May be left adjacent to another
4956 # unary operator, or a cast
4957 } elsif ($op eq '!' || $op eq '~' ||
4958 $opv eq '*U' || $opv eq '-U' ||
4959 $opv eq '&U' || $opv eq '&&U') {
4960 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4961 if (ERROR("SPACING",
4962 "space required before that '$op' $at\n" . $hereptr)) {
4963 if ($n != $last_after + 2) {
4964 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4969 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4970 # A unary '*' may be const
4972 } elsif ($ctx =~ /.xW/) {
4973 if (ERROR("SPACING",
4974 "space prohibited after that '$op' $at\n" . $hereptr)) {
4975 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4976 if (defined $fix_elements[$n + 2]) {
4977 $fix_elements[$n + 2] =~ s/^\s+//;
4983 # unary ++ and unary -- are allowed no space on one side.
4984 } elsif ($op eq '++' or $op eq '--') {
4985 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4986 if (ERROR("SPACING",
4987 "space required one side of that '$op' $at\n" . $hereptr)) {
4988 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4992 if ($ctx =~ /Wx[BE]/ ||
4993 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4994 if (ERROR("SPACING",
4995 "space prohibited before that '$op' $at\n" . $hereptr)) {
4996 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5000 if ($ctx =~ /ExW/) {
5001 if (ERROR("SPACING",
5002 "space prohibited after that '$op' $at\n" . $hereptr)) {
5003 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5004 if (defined $fix_elements[$n + 2]) {
5005 $fix_elements[$n + 2] =~ s/^\s+//;
5011 # << and >> may either have or not have spaces both sides
5012 } elsif ($op eq '<<' or $op eq '>>' or
5013 $op eq '&' or $op eq '^' or $op eq '|' or
5014 $op eq '+' or $op eq '-' or
5015 $op eq '*' or $op eq '/' or
5019 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5021 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5022 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5023 $fix_elements[$n + 2] =~ s/^\s+//;
5026 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5028 "space preferred before that '$op' $at\n" . $hereptr)) {
5029 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5033 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5034 if (ERROR("SPACING",
5035 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5036 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5037 if (defined $fix_elements[$n + 2]) {
5038 $fix_elements[$n + 2] =~ s/^\s+//;
5044 # A colon needs no spaces before when it is
5045 # terminating a case value or a label.
5046 } elsif ($opv eq ':C' || $opv eq ':L') {
5047 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5048 if (ERROR("SPACING",
5049 "space prohibited before that '$op' $at\n" . $hereptr)) {
5050 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5055 # All the others need spaces both sides.
5056 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5059 # Ignore email addresses <foo@bar>
5061 $cc =~ /^\S+\@\S+>/) ||
5063 $ca =~ /<\S+\@\S+$/))
5068 # for asm volatile statements
5069 # ignore a colon with another
5070 # colon immediately before or after
5072 ($ca =~ /:$/ || $cc =~ /^:/)) {
5076 # messages are ERROR, but ?: are CHK
5078 my $msg_level = \&ERROR;
5079 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5081 if (&{$msg_level}("SPACING",
5082 "spaces required around that '$op' $at\n" . $hereptr)) {
5083 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5084 if (defined $fix_elements[$n + 2]) {
5085 $fix_elements[$n + 2] =~ s/^\s+//;
5091 $off += length($elements[$n + 1]);
5093 ## print("n: <$n> GOOD: <$good>\n");
5095 $fixed_line = $fixed_line . $good;
5098 if (($#elements % 2) == 0) {
5099 $fixed_line = $fixed_line . $fix_elements[$#elements];
5102 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5103 $fixed[$fixlinenr] = $fixed_line;
5109 # check for whitespace before a non-naked semicolon
5110 if ($line =~ /^\+.*\S\s+;\s*$/) {
5112 "space prohibited before semicolon\n" . $herecurr) &&
5114 1 while $fixed[$fixlinenr] =~
5115 s/^(\+.*\S)\s+;/$1;/;
5119 # check for multiple assignments
5120 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5121 CHK("MULTIPLE_ASSIGNMENTS",
5122 "multiple assignments should be avoided\n" . $herecurr);
5125 ## # check for multiple declarations, allowing for a function declaration
5127 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5128 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5130 ## # Remove any bracketed sections to ensure we do not
5131 ## # falsely report the parameters of functions.
5133 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5135 ## if ($ln =~ /,/) {
5136 ## WARN("MULTIPLE_DECLARATION",
5137 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5141 #need space before brace following if, while, etc
5142 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5143 $line =~ /\b(?:else|do)\{/) {
5144 if (ERROR("SPACING",
5145 "space required before the open brace '{'\n" . $herecurr) &&
5147 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5151 ## # check for blank lines before declarations
5152 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5153 ## $prevrawline =~ /^.\s*$/) {
5155 ## "No blank lines before declarations\n" . $hereprev);
5159 # closing brace should have a space following it when it has anything
5161 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5162 if (ERROR("SPACING",
5163 "space required after that close brace '}'\n" . $herecurr) &&
5165 $fixed[$fixlinenr] =~
5166 s/}((?!(?:,|;|\)))\S)/} $1/;
5170 # check spacing on square brackets
5171 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5172 if (ERROR("SPACING",
5173 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5175 $fixed[$fixlinenr] =~
5179 if ($line =~ /\s\]/) {
5180 if (ERROR("SPACING",
5181 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5183 $fixed[$fixlinenr] =~
5188 # check spacing on parentheses
5189 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5190 $line !~ /for\s*\(\s+;/) {
5191 if (ERROR("SPACING",
5192 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5194 $fixed[$fixlinenr] =~
5198 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5199 $line !~ /for\s*\(.*;\s+\)/ &&
5200 $line !~ /:\s+\)/) {
5201 if (ERROR("SPACING",
5202 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5204 $fixed[$fixlinenr] =~
5209 # check unnecessary parentheses around addressof/dereference single $Lvals
5210 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5212 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5214 if (CHK("UNNECESSARY_PARENTHESES",
5215 "Unnecessary parentheses around $var\n" . $herecurr) &&
5217 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5221 # check for unnecessary parentheses around function pointer uses
5222 # ie: (foo->bar)(); should be foo->bar();
5223 # but not "if (foo->bar) (" to avoid some false positives
5224 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5226 if (CHK("UNNECESSARY_PARENTHESES",
5227 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5229 my $var2 = deparenthesize($var);
5231 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5235 # check for unnecessary parentheses around comparisons in if uses
5236 # when !drivers/staging or command-line uses --strict
5237 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5238 $perl_version_ok && defined($stat) &&
5239 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5241 my $test = substr($2, 1, -1);
5243 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5245 # avoid parentheses around potential macro args
5246 next if ($match =~ /^\s*\w+\s*$/);
5247 if (!defined($herectx)) {
5248 $herectx = $here . "\n";
5249 my $cnt = statement_rawlines($if_stat);
5250 for (my $n = 0; $n < $cnt; $n++) {
5251 my $rl = raw_line($linenr, $n);
5252 $herectx .= $rl . "\n";
5253 last if $rl =~ /^[ \+].*\{/;
5256 CHK("UNNECESSARY_PARENTHESES",
5257 "Unnecessary parentheses around '$match'\n" . $herectx);
5261 #goto labels aren't indented, allow a single space however
5262 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
5263 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
5264 if (WARN("INDENTED_LABEL",
5265 "labels should not be indented\n" . $herecurr) &&
5267 $fixed[$fixlinenr] =~
5272 # check if a statement with a comma should be two statements like:
5273 # foo = bar(), /* comma should be semicolon */
5275 if (defined($stat) &&
5276 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5277 my $cnt = statement_rawlines($stat);
5278 my $herectx = get_stat_here($linenr, $cnt, $here);
5279 WARN("SUSPECT_COMMA_SEMICOLON",
5280 "Possible comma where semicolon could be used\n" . $herectx);
5283 # return is not a function
5284 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5286 if ($perl_version_ok &&
5287 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5289 $value = deparenthesize($value);
5290 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5291 ERROR("RETURN_PARENTHESES",
5292 "return is not a function, parentheses are not required\n" . $herecurr);
5294 } elsif ($spacing !~ /\s+/) {
5296 "space required before the open parenthesis '('\n" . $herecurr);
5300 # unnecessary return in a void function
5301 # at end-of-function, with the previous line a single leading tab, then return;
5302 # and the line before that not a goto label target like "out:"
5303 if ($sline =~ /^[ \+]}\s*$/ &&
5304 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5306 $lines[$linenr - 3] =~ /^[ +]/ &&
5307 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5309 "void function return statements are not generally useful\n" . $hereprev);
5312 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5313 if ($perl_version_ok &&
5314 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5315 my $openparens = $1;
5316 my $count = $openparens =~ tr@\(@\(@;
5318 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5319 my $comp = $4; #Not $1 because of $LvalOrFunc
5320 $msg = " - maybe == should be = ?" if ($comp eq "==");
5321 WARN("UNNECESSARY_PARENTHESES",
5322 "Unnecessary parentheses$msg\n" . $herecurr);
5326 # comparisons with a constant or upper case identifier on the left
5327 # avoid cases like "foo + BAR < baz"
5328 # only fix matches surrounded by parentheses to avoid incorrect
5329 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5330 if ($perl_version_ok &&
5331 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5336 my $newcomp = $comp;
5337 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5338 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5339 WARN("CONSTANT_COMPARISON",
5340 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5344 } elsif ($comp eq "<=") {
5346 } elsif ($comp eq ">") {
5348 } elsif ($comp eq ">=") {
5351 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5355 # Return of what appears to be an errno should normally be negative
5356 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5358 if ($name ne 'EOF' && $name ne 'ERROR') {
5359 WARN("USE_NEGATIVE_ERRNO",
5360 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5364 # Need a space before open parenthesis after if, while etc
5365 if ($line =~ /\b(if|while|for|switch)\(/) {
5366 if (ERROR("SPACING",
5367 "space required before the open parenthesis '('\n" . $herecurr) &&
5369 $fixed[$fixlinenr] =~
5370 s/\b(if|while|for|switch)\(/$1 \(/;
5374 # Check for illegal assignment in if conditional -- and check for trailing
5375 # statements after the conditional.
5376 if ($line =~ /do\s*(?!{)/) {
5377 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5378 ctx_statement_block($linenr, $realcnt, 0)
5379 if (!defined $stat);
5380 my ($stat_next) = ctx_statement_block($line_nr_next,
5381 $remain_next, $off_next);
5382 $stat_next =~ s/\n./\n /g;
5383 ##print "stat<$stat> stat_next<$stat_next>\n";
5385 if ($stat_next =~ /^\s*while\b/) {
5386 # If the statement carries leading newlines,
5387 # then count those as offsets.
5389 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5391 statement_rawlines($whitespace) - 1;
5393 $suppress_whiletrailers{$line_nr_next +
5397 if (!defined $suppress_whiletrailers{$linenr} &&
5398 defined($stat) && defined($cond) &&
5399 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5400 my ($s, $c) = ($stat, $cond);
5402 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5403 if (ERROR("ASSIGN_IN_IF",
5404 "do not use assignment in if condition\n" . $herecurr) &&
5405 $fix && $perl_version_ok) {
5406 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5414 fix_delete_line($fixlinenr, $rawline);
5415 fix_insert_line($fixlinenr, "$space$statement;");
5416 my $newline = "${space}if (";
5417 $newline .= '!' if defined($not);
5418 $newline .= '(' if (defined $not && defined($test) && defined($against));
5419 $newline .= "$assigned";
5420 $newline .= " $test $against" if (defined($test) && defined($against));
5421 $newline .= ')' if (defined $not && defined($test) && defined($against));
5423 $newline .= " {" if (defined($brace));
5424 fix_insert_line($fixlinenr + 1, $newline);
5429 # Find out what is on the end of the line after the
5431 substr($s, 0, length($c), '');
5433 $s =~ s/$;//g; # Remove any comments
5434 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5435 $c !~ /}\s*while\s*/)
5437 # Find out how long the conditional actually is.
5438 my @newlines = ($c =~ /\n/gs);
5439 my $cond_lines = 1 + $#newlines;
5442 $stat_real = raw_line($linenr, $cond_lines)
5443 . "\n" if ($cond_lines);
5444 if (defined($stat_real) && $cond_lines > 1) {
5445 $stat_real = "[...]\n$stat_real";
5448 ERROR("TRAILING_STATEMENTS",
5449 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5453 # Check for bitwise tests written as boolean
5465 WARN("HEXADECIMAL_BOOLEAN_TEST",
5466 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5469 # if and else should not have general statements after it
5470 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5472 $s =~ s/$;//g; # Remove any comments
5473 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5474 ERROR("TRAILING_STATEMENTS",
5475 "trailing statements should be on next line\n" . $herecurr);
5478 # if should not continue a brace
5479 if ($line =~ /}\s*if\b/) {
5480 ERROR("TRAILING_STATEMENTS",
5481 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5484 # case and default should not have general statements after them
5485 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5487 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5491 ERROR("TRAILING_STATEMENTS",
5492 "trailing statements should be on next line\n" . $herecurr);
5495 # Check for }<nl>else {, these must be at the same
5496 # indent level to be relevant to each other.
5497 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5498 $previndent == $indent) {
5499 if (ERROR("ELSE_AFTER_BRACE",
5500 "else should follow close brace '}'\n" . $hereprev) &&
5501 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5502 fix_delete_line($fixlinenr - 1, $prevrawline);
5503 fix_delete_line($fixlinenr, $rawline);
5504 my $fixedline = $prevrawline;
5505 $fixedline =~ s/}\s*$//;
5506 if ($fixedline !~ /^\+\s*$/) {
5507 fix_insert_line($fixlinenr, $fixedline);
5509 $fixedline = $rawline;
5510 $fixedline =~ s/^(.\s*)else/$1} else/;
5511 fix_insert_line($fixlinenr, $fixedline);
5515 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5516 $previndent == $indent) {
5517 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5519 # Find out what is on the end of the line after the
5521 substr($s, 0, length($c), '');
5524 if ($s =~ /^\s*;/) {
5525 if (ERROR("WHILE_AFTER_BRACE",
5526 "while should follow close brace '}'\n" . $hereprev) &&
5527 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5528 fix_delete_line($fixlinenr - 1, $prevrawline);
5529 fix_delete_line($fixlinenr, $rawline);
5530 my $fixedline = $prevrawline;
5531 my $trailing = $rawline;
5532 $trailing =~ s/^\+//;
5533 $trailing = trim($trailing);
5534 $fixedline =~ s/}\s*$/} $trailing/;
5535 fix_insert_line($fixlinenr, $fixedline);
5540 #Specific variable tests
5541 while ($line =~ m{($Constant|$Lval)}g) {
5545 if ($var !~ /^$Constant$/ &&
5546 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5547 #Ignore some autogenerated defines and enum values
5548 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5549 #Ignore Page<foo> variants
5550 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5551 #Ignore SI style variants like nS, mV and dB
5552 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5553 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5554 #Ignore some three character SI units explicitly, like MiB and KHz
5555 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5556 while ($var =~ m{($Ident)}g) {
5558 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5560 seed_camelcase_includes();
5561 if (!$file && !$camelcase_file_seeded) {
5562 seed_camelcase_file($realfile);
5563 $camelcase_file_seeded = 1;
5566 if (!defined $camelcase{$word}) {
5567 $camelcase{$word} = 1;
5569 "Avoid CamelCase: <$word>\n" . $herecurr);
5575 #no spaces allowed after \ in define
5576 if ($line =~ /\#\s*define.*\\\s+$/) {
5577 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5578 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5580 $fixed[$fixlinenr] =~ s/\s+$//;
5584 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5585 # itself <asm/foo.h> (uses RAW line)
5586 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5588 my $checkfile = "include/linux/$file";
5589 if (-f "$root/$checkfile" &&
5590 $realfile ne $checkfile &&
5591 $1 !~ /$allowed_asm_includes/)
5593 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5594 if ($asminclude > 0) {
5595 if ($realfile =~ m{^arch/}) {
5596 CHK("ARCH_INCLUDE_LINUX",
5597 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5599 WARN("INCLUDE_LINUX",
5600 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5606 # multi-statement macros should be enclosed in a do while loop, grab the
5607 # first statement and ensure its the whole macro if its not enclosed
5608 # in a known good container
5609 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5610 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5613 my ($off, $dstat, $dcond, $rest);
5615 my $has_flow_statement = 0;
5616 my $has_arg_concat = 0;
5617 ($dstat, $dcond, $ln, $cnt, $off) =
5618 ctx_statement_block($linenr, $realcnt, 0);
5620 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5621 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5623 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5624 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5626 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5627 my $define_args = $1;
5628 my $define_stmt = $dstat;
5631 if (defined $define_args && $define_args ne "") {
5632 $define_args = substr($define_args, 1, length($define_args) - 2);
5633 $define_args =~ s/\s*//g;
5634 $define_args =~ s/\\\+?//g;
5635 @def_args = split(",", $define_args);
5639 $dstat =~ s/\\\n.//g;
5640 $dstat =~ s/^\s*//s;
5641 $dstat =~ s/\s*$//s;
5643 # Flatten any parentheses and braces
5644 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5645 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5646 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5650 # Flatten any obvious string concatenation.
5651 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5652 $dstat =~ s/$Ident\s*($String)/$1/)
5656 # Make asm volatile uses seem like a generic function
5657 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5659 my $exceptions = qr{
5672 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5675 my $stmt_cnt = statement_rawlines($ctx);
5676 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5679 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5680 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5681 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5682 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5683 $dstat !~ /$exceptions/ &&
5684 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5685 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5686 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5687 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5688 $dstat !~ /^for\s*$Constant$/ && # for (...)
5689 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5690 $dstat !~ /^do\s*{/ && # do {...
5691 $dstat !~ /^\(\{/ && # ({...
5692 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5694 if ($dstat =~ /^\s*if\b/) {
5695 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5696 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5697 } elsif ($dstat =~ /;/) {
5698 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5699 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5701 ERROR("COMPLEX_MACRO",
5702 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5707 # Make $define_stmt single line, comment-free, etc
5708 my @stmt_array = split('\n', $define_stmt);
5711 foreach my $l (@stmt_array) {
5716 } elsif ($l =~ /^[\+ ]/) {
5717 $define_stmt .= substr($l, 1);
5720 $define_stmt =~ s/$;//g;
5721 $define_stmt =~ s/\s+/ /g;
5722 $define_stmt = trim($define_stmt);
5724 # check if any macro arguments are reused (ignore '...' and 'type')
5725 foreach my $arg (@def_args) {
5726 next if ($arg =~ /\.\.\./);
5727 next if ($arg =~ /^type$/i);
5728 my $tmp_stmt = $define_stmt;
5729 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5730 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5731 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5732 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5734 CHK("MACRO_ARG_REUSE",
5735 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5737 # check if any macro arguments may have other precedence issues
5738 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5739 ((defined($1) && $1 ne ',') ||
5740 (defined($2) && $2 ne ','))) {
5741 CHK("MACRO_ARG_PRECEDENCE",
5742 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5746 # check for macros with flow control, but without ## concatenation
5747 # ## concatenation is commonly a macro that defines a function so ignore those
5748 if ($has_flow_statement && !$has_arg_concat) {
5749 my $cnt = statement_rawlines($ctx);
5750 my $herectx = get_stat_here($linenr, $cnt, $here);
5752 WARN("MACRO_WITH_FLOW_CONTROL",
5753 "Macros with flow control statements should be avoided\n" . "$herectx");
5756 # check for line continuations outside of #defines, preprocessor #, and asm
5759 if ($prevline !~ /^..*\\$/ &&
5760 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5761 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5762 $line =~ /^\+.*\\$/) {
5763 WARN("LINE_CONTINUATIONS",
5764 "Avoid unnecessary line continuations\n" . $herecurr);
5768 # do {} while (0) macro tests:
5769 # single-statement macros do not need to be enclosed in do while (0) loop,
5770 # macro should not end with a semicolon
5771 if ($perl_version_ok &&
5772 $realfile !~ m@/vmlinux.lds.h$@ &&
5773 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5776 my ($off, $dstat, $dcond, $rest);
5778 ($dstat, $dcond, $ln, $cnt, $off) =
5779 ctx_statement_block($linenr, $realcnt, 0);
5782 $dstat =~ s/\\\n.//g;
5785 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5790 my $cnt = statement_rawlines($ctx);
5791 my $herectx = get_stat_here($linenr, $cnt, $here);
5793 if (($stmts =~ tr/;/;/) == 1 &&
5794 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5795 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5796 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5798 if (defined $semis && $semis ne "") {
5799 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5800 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5802 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5804 my $cnt = statement_rawlines($ctx);
5805 my $herectx = get_stat_here($linenr, $cnt, $here);
5807 WARN("TRAILING_SEMICOLON",
5808 "macros should not use a trailing semicolon\n" . "$herectx");
5812 # check for redundant bracing round if etc
5813 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5814 my ($level, $endln, @chunks) =
5815 ctx_statement_full($linenr, $realcnt, 1);
5816 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5817 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5818 if ($#chunks > 0 && $level == 0) {
5822 my $herectx = $here . "\n";
5823 my $ln = $linenr - 1;
5824 for my $chunk (@chunks) {
5825 my ($cond, $block) = @{$chunk};
5827 # If the condition carries leading newlines, then count those as offsets.
5828 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5829 my $offset = statement_rawlines($whitespace) - 1;
5831 $allowed[$allow] = 0;
5832 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5834 # We have looked at and allowed this specific line.
5835 $suppress_ifbraces{$ln + $offset} = 1;
5837 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5838 $ln += statement_rawlines($block) - 1;
5840 substr($block, 0, length($cond), '');
5842 $seen++ if ($block =~ /^\s*{/);
5844 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5845 if (statement_lines($cond) > 1) {
5846 #print "APW: ALLOWED: cond<$cond>\n";
5847 $allowed[$allow] = 1;
5849 if ($block =~/\b(?:if|for|while)\b/) {
5850 #print "APW: ALLOWED: block<$block>\n";
5851 $allowed[$allow] = 1;
5853 if (statement_block_size($block) > 1) {
5854 #print "APW: ALLOWED: lines block<$block>\n";
5855 $allowed[$allow] = 1;
5860 my $sum_allowed = 0;
5861 foreach (@allowed) {
5864 if ($sum_allowed == 0) {
5866 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5867 } elsif ($sum_allowed != $allow &&
5870 "braces {} should be used on all arms of this statement\n" . $herectx);
5875 if (!defined $suppress_ifbraces{$linenr - 1} &&
5876 $line =~ /\b(if|while|for|else)\b/) {
5879 # Check the pre-context.
5880 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5881 #print "APW: ALLOWED: pre<$1>\n";
5885 my ($level, $endln, @chunks) =
5886 ctx_statement_full($linenr, $realcnt, $-[0]);
5888 # Check the condition.
5889 my ($cond, $block) = @{$chunks[0]};
5890 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5891 if (defined $cond) {
5892 substr($block, 0, length($cond), '');
5894 if (statement_lines($cond) > 1) {
5895 #print "APW: ALLOWED: cond<$cond>\n";
5898 if ($block =~/\b(?:if|for|while)\b/) {
5899 #print "APW: ALLOWED: block<$block>\n";
5902 if (statement_block_size($block) > 1) {
5903 #print "APW: ALLOWED: lines block<$block>\n";
5906 # Check the post-context.
5907 if (defined $chunks[1]) {
5908 my ($cond, $block) = @{$chunks[1]};
5909 if (defined $cond) {
5910 substr($block, 0, length($cond), '');
5912 if ($block =~ /^\s*\{/) {
5913 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5917 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5918 my $cnt = statement_rawlines($block);
5919 my $herectx = get_stat_here($linenr, $cnt, $here);
5922 "braces {} are not necessary for single statement blocks\n" . $herectx);
5926 # check for single line unbalanced braces
5927 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5928 $sline =~ /^.\s*else\s*\{\s*$/) {
5929 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5932 # check for unnecessary blank lines around braces
5933 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5935 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5936 $fix && $prevrawline =~ /^\+/) {
5937 fix_delete_line($fixlinenr - 1, $prevrawline);
5940 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5942 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5944 fix_delete_line($fixlinenr, $rawline);
5948 # no volatiles please
5949 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5950 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5952 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5955 # Check for user-visible strings broken across lines, which breaks the ability
5956 # to grep for the string. Make exceptions when the previous string ends in a
5957 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5958 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5959 if ($line =~ /^\+\s*$String/ &&
5960 $prevline =~ /"\s*$/ &&
5961 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5962 if (WARN("SPLIT_STRING",
5963 "quoted string split across lines\n" . $hereprev) &&
5965 $prevrawline =~ /^\+.*"\s*$/ &&
5966 $last_coalesced_string_linenr != $linenr - 1) {
5967 my $extracted_string = get_quoted_string($line, $rawline);
5968 my $comma_close = "";
5969 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5973 fix_delete_line($fixlinenr - 1, $prevrawline);
5974 fix_delete_line($fixlinenr, $rawline);
5975 my $fixedline = $prevrawline;
5976 $fixedline =~ s/"\s*$//;
5977 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5978 fix_insert_line($fixlinenr - 1, $fixedline);
5979 $fixedline = $rawline;
5980 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5981 if ($fixedline !~ /\+\s*$/) {
5982 fix_insert_line($fixlinenr, $fixedline);
5984 $last_coalesced_string_linenr = $linenr;
5988 # check for missing a space in a string concatenation
5989 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5990 WARN('MISSING_SPACE',
5991 "break quoted strings at a space character\n" . $hereprev);
5994 # check for an embedded function name in a string when the function is known
5995 # This does not work very well for -f --file checking as it depends on patch
5996 # context providing the function name or a single line form for in-file
5997 # function declarations
5998 if ($line =~ /^\+.*$String/ &&
5999 defined($context_function) &&
6000 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6001 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6002 WARN("EMBEDDED_FUNCTION_NAME",
6003 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6006 # check for unnecessary function tracing like uses
6007 # This does not use $logFunctions because there are many instances like
6008 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6009 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6010 if (WARN("TRACING_LOGGING",
6011 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6013 fix_delete_line($fixlinenr, $rawline);
6017 # check for spaces before a quoted newline
6018 if ($rawline =~ /^.*\".*\s\\n/) {
6019 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6020 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6022 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6027 # concatenated string without spaces between elements
6028 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
6029 if (CHK("CONCATENATED_STRING",
6030 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6032 while ($line =~ /($String)/g) {
6033 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6034 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6035 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6040 # uncoalesced string fragments
6041 if ($line =~ /$String\s*"/) {
6042 if (WARN("STRING_FRAGMENTS",
6043 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6045 while ($line =~ /($String)(?=\s*")/g) {
6046 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6047 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6052 # check for non-standard and hex prefixed decimal printf formats
6053 my $show_L = 1; #don't show the same defect twice
6055 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6056 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6057 $string =~ s/%%/__/g;
6059 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6061 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6065 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6067 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6070 # check for 0x<decimal>
6071 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6072 ERROR("PRINTF_0XDECIMAL",
6073 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6077 # check for line continuations in quoted strings with odd counts of "
6078 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6079 WARN("LINE_CONTINUATIONS",
6080 "Avoid line continuations in quoted strings\n" . $herecurr);
6084 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6086 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6090 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6092 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6095 # check for needless "if (<foo>) fn(<foo>)" uses
6096 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6097 my $tested = quotemeta($1);
6098 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6099 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6101 if (WARN('NEEDLESS_IF',
6102 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6105 my $leading_tabs = "";
6106 my $new_leading_tabs = "";
6107 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6112 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6113 $new_leading_tabs = $1;
6114 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6121 fix_delete_line($fixlinenr - 1, $prevrawline);
6122 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6128 # check for unnecessary "Out of Memory" messages
6129 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6130 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6131 (defined $1 || defined $3) &&
6134 my $testline = $lines[$linenr - 3];
6136 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6137 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6139 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6140 $s !~ /\b__GFP_NOWARN\b/ ) {
6142 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6146 # check for logging functions with KERN_<LEVEL>
6147 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6148 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6150 if (WARN("UNNECESSARY_KERN_LEVEL",
6151 "Possible unnecessary $level\n" . $herecurr) &&
6153 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6157 # check for logging continuations
6158 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6159 WARN("LOGGING_CONTINUATION",
6160 "Avoid logging continuation uses where feasible\n" . $herecurr);
6163 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6164 if (defined $stat &&
6165 $line =~ /\b$logFunctions\s*\(/ &&
6166 index($stat, '"') >= 0) {
6167 my $lc = $stat =~ tr@\n@@;
6168 $lc = $lc + $linenr;
6169 my $stat_real = get_stat_real($linenr, $lc);
6170 pos($stat_real) = index($stat_real, '"');
6171 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6174 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6175 if (WARN("UNNECESSARY_MODIFIER",
6176 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6177 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6180 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6185 # check for mask then right shift without a parentheses
6186 if ($perl_version_ok &&
6187 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6188 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6189 WARN("MASK_THEN_SHIFT",
6190 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6193 # check for pointer comparisons to NULL
6194 if ($perl_version_ok) {
6195 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6198 $equal = "" if ($4 eq "!=");
6199 if (CHK("COMPARISON_TO_NULL",
6200 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6202 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6207 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6208 if ($line =~ /(\b$InitAttribute\b)/) {
6210 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6213 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6214 ERROR("MISPLACED_INIT",
6215 "$attr should be placed after $var\n" . $herecurr)) ||
6216 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6217 WARN("MISPLACED_INIT",
6218 "$attr should be placed after $var\n" . $herecurr))) &&
6220 $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;
6225 # check for $InitAttributeData (ie: __initdata) with const
6226 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6228 $attr =~ /($InitAttributePrefix)(.*)/;
6229 my $attr_prefix = $1;
6231 if (ERROR("INIT_ATTRIBUTE",
6232 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6234 $fixed[$fixlinenr] =~
6235 s/$InitAttributeData/${attr_prefix}initconst/;
6239 # check for $InitAttributeConst (ie: __initconst) without const
6240 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6242 if (ERROR("INIT_ATTRIBUTE",
6243 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6245 my $lead = $fixed[$fixlinenr] =~
6246 /(^\+\s*(?:static\s+))/;
6248 $lead = "$lead " if ($lead !~ /^\+$/);
6249 $lead = "${lead}const ";
6250 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6254 # check for __read_mostly with const non-pointer (should just be const)
6255 if ($line =~ /\b__read_mostly\b/ &&
6256 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6257 if (ERROR("CONST_READ_MOSTLY",
6258 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6260 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6264 # don't use __constant_<foo> functions outside of include/uapi/
6265 if ($realfile !~ m@^include/uapi/@ &&
6266 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6267 my $constant_func = $1;
6268 my $func = $constant_func;
6269 $func =~ s/^__constant_//;
6270 if (WARN("CONSTANT_CONVERSION",
6271 "$constant_func should be $func\n" . $herecurr) &&
6273 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6277 # prefer usleep_range over udelay
6278 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6280 # ignore udelay's < 10, however
6281 if (! ($delay < 10) ) {
6283 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6285 if ($delay > 2000) {
6287 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6291 # warn about unexpectedly long msleep's
6292 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6295 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6299 # check for comparisons of jiffies
6300 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6301 WARN("JIFFIES_COMPARISON",
6302 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6305 # check for comparisons of get_jiffies_64()
6306 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6307 WARN("JIFFIES_COMPARISON",
6308 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6311 # warn about #ifdefs in C files
6312 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6313 # print "#ifdef in C files should be avoided\n";
6314 # print "$herecurr";
6318 # warn about spacing in #ifdefs
6319 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6320 if (ERROR("SPACING",
6321 "exactly one space required after that #$1\n" . $herecurr) &&
6323 $fixed[$fixlinenr] =~
6324 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6329 # check for spinlock_t definitions without a comment.
6330 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6331 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6333 if (!ctx_has_comment($first_line, $linenr)) {
6334 CHK("UNCOMMENTED_DEFINITION",
6335 "$1 definition without comment\n" . $herecurr);
6338 # check for memory barriers without a comment.
6345 my $barrier_stems = qr{
6353 my $all_barriers = qr{
6355 smp_(?:$barrier_stems)|
6356 virt_(?:$barrier_stems)
6359 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6360 if (!ctx_has_comment($first_line, $linenr)) {
6361 WARN("MEMORY_BARRIER",
6362 "memory barrier without comment\n" . $herecurr);
6366 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6368 if ($realfile !~ m@^include/asm-generic/@ &&
6369 $realfile !~ m@/barrier\.h$@ &&
6370 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6371 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6372 WARN("MEMORY_BARRIER",
6373 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6376 # check for waitqueue_active without a comment.
6377 if ($line =~ /\bwaitqueue_active\s*\(/) {
6378 if (!ctx_has_comment($first_line, $linenr)) {
6379 WARN("WAITQUEUE_ACTIVE",
6380 "waitqueue_active without comment\n" . $herecurr);
6384 # check for data_race without a comment.
6385 if ($line =~ /\bdata_race\s*\(/) {
6386 if (!ctx_has_comment($first_line, $linenr)) {
6388 "data_race without comment\n" . $herecurr);
6392 # check of hardware specific defines
6393 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6395 "architecture specific defines should be avoided\n" . $herecurr);
6398 # check that the storage class is not after a type
6399 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6400 WARN("STORAGE_CLASS",
6401 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6403 # Check that the storage class is at the beginning of a declaration
6404 if ($line =~ /\b$Storage\b/ &&
6405 $line !~ /^.\s*$Storage/ &&
6406 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6407 $1 !~ /[\,\)]\s*$/) {
6408 WARN("STORAGE_CLASS",
6409 "storage class should be at the beginning of the declaration\n" . $herecurr);
6412 # check the location of the inline attribute, that it is between
6413 # storage class and type.
6414 if ($line =~ /\b$Type\s+$Inline\b/ ||
6415 $line =~ /\b$Inline\s+$Storage\b/) {
6416 ERROR("INLINE_LOCATION",
6417 "inline keyword should sit between storage class and type\n" . $herecurr);
6420 # Check for __inline__ and __inline, prefer inline
6421 if ($realfile !~ m@\binclude/uapi/@ &&
6422 $line =~ /\b(__inline__|__inline)\b/) {
6424 "plain inline is preferred over $1\n" . $herecurr) &&
6426 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6431 # Check for compiler attributes
6432 if ($realfile !~ m@\binclude/uapi/@ &&
6433 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6435 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6438 "alias" => "__alias",
6439 "aligned" => "__aligned",
6440 "always_inline" => "__always_inline",
6441 "assume_aligned" => "__assume_aligned",
6443 "const" => "__attribute_const__",
6445 "designated_init" => "__designated_init",
6446 "externally_visible" => "__visible",
6447 "format" => "printf|scanf",
6448 "gnu_inline" => "__gnu_inline",
6449 "malloc" => "__malloc",
6451 "no_caller_saved_registers" => "__no_caller_saved_registers",
6452 "noclone" => "__noclone",
6453 "noinline" => "noinline",
6454 "nonstring" => "__nonstring",
6455 "noreturn" => "__noreturn",
6456 "packed" => "__packed",
6458 "section" => "__section",
6463 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6466 $params = $2 if defined($2);
6467 my $curr_attr = $orig_attr;
6468 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6469 if (exists($attr_list{$curr_attr})) {
6470 my $new = $attr_list{$curr_attr};
6471 if ($curr_attr eq "format" && $params) {
6472 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6475 $new = "$new$params";
6477 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6478 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6480 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6481 $fixed[$fixlinenr] =~ s/$remove//;
6482 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6483 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6484 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6489 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6490 if ($attr =~ /^_*unused/) {
6491 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6492 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6496 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6497 if ($perl_version_ok &&
6498 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6499 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6500 $line =~ /\b__weak\b/)) {
6501 ERROR("WEAK_DECLARATION",
6502 "Using weak declarations can have unintended link defects\n" . $herecurr);
6505 # check for c99 types like uint8_t used outside of uapi/ and tools/
6506 if ($realfile !~ m@\binclude/uapi/@ &&
6507 $realfile !~ m@\btools/@ &&
6508 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6510 if ($type =~ /\b($typeC99Typedefs)\b/) {
6512 my $kernel_type = 'u';
6513 $kernel_type = 's' if ($type =~ /^_*[si]/);
6516 if (CHK("PREFER_KERNEL_TYPES",
6517 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6519 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6524 # check for cast of C90 native int or longer types constants
6525 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6529 my $newconst = $const;
6530 $newconst =~ s/${Int_type}$//;
6531 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6532 if ($cast =~ /\blong\s+long\b/) {
6534 } elsif ($cast =~ /\blong\b/) {
6537 if (WARN("TYPECAST_INT_CONSTANT",
6538 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6540 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6544 # check for sizeof(&)
6545 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6546 WARN("SIZEOF_ADDRESS",
6547 "sizeof(& should be avoided\n" . $herecurr);
6550 # check for sizeof without parenthesis
6551 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6552 if (WARN("SIZEOF_PARENTHESIS",
6553 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6555 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6559 # check for struct spinlock declarations
6560 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6561 WARN("USE_SPINLOCK_T",
6562 "struct spinlock should be spinlock_t\n" . $herecurr);
6565 # check for seq_printf uses that could be seq_puts
6566 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6567 my $fmt = get_quoted_string($line, $rawline);
6570 if (WARN("PREFER_SEQ_PUTS",
6571 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6573 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6578 # check for vsprintf extension %p<foo> misuses
6579 if ($perl_version_ok &&
6581 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6582 $1 !~ /^_*volatile_*$/) {
6585 my $lc = $stat =~ tr@\n@@;
6586 $lc = $lc + $linenr;
6587 for (my $count = $linenr; $count <= $lc; $count++) {
6591 my $bad_specifier = "";
6592 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6595 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6599 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6600 ($extension eq "f" &&
6601 defined $qualifier && $qualifier !~ /^w/)) {
6602 $bad_specifier = $specifier;
6605 if ($extension eq "x" && !defined($stat_real)) {
6606 if (!defined($stat_real)) {
6607 $stat_real = get_stat_real($linenr, $lc);
6609 WARN("VSPRINTF_SPECIFIER_PX",
6610 "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");
6613 if ($bad_specifier ne "") {
6614 my $stat_real = get_stat_real($linenr, $lc);
6615 my $ext_type = "Invalid";
6617 if ($bad_specifier =~ /p[Ff]/) {
6618 $use = " - use %pS instead";
6619 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6622 WARN("VSPRINTF_POINTER_EXTENSION",
6623 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6628 # Check for misused memsets
6629 if ($perl_version_ok &&
6631 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6637 if ($ms_size =~ /^(0x|)0$/i) {
6639 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6640 } elsif ($ms_size =~ /^(0x|)1$/i) {
6642 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6646 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6647 # if ($perl_version_ok &&
6649 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6650 # if (WARN("PREFER_ETHER_ADDR_COPY",
6651 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6653 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6657 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6658 # if ($perl_version_ok &&
6660 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6661 # WARN("PREFER_ETHER_ADDR_EQUAL",
6662 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6665 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6666 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6667 # if ($perl_version_ok &&
6669 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6673 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6674 # if (WARN("PREFER_ETH_ZERO_ADDR",
6675 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6677 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6679 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6680 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6681 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6683 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6688 # strlcpy uses that should likely be strscpy
6689 if ($line =~ /\bstrlcpy\s*\(/) {
6691 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6694 # typecasts on min/max could be min_t/max_t
6695 if ($perl_version_ok &&
6697 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6698 if (defined $2 || defined $7) {
6700 my $cast1 = deparenthesize($2);
6702 my $cast2 = deparenthesize($7);
6706 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6707 $cast = "$cast1 or $cast2";
6708 } elsif ($cast1 ne "") {
6714 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6718 # check usleep_range arguments
6719 if ($perl_version_ok &&
6721 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6725 WARN("USLEEP_RANGE",
6726 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6727 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6729 WARN("USLEEP_RANGE",
6730 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6734 # check for naked sscanf
6735 if ($perl_version_ok &&
6737 $line =~ /\bsscanf\b/ &&
6738 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6739 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6740 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6741 my $lc = $stat =~ tr@\n@@;
6742 $lc = $lc + $linenr;
6743 my $stat_real = get_stat_real($linenr, $lc);
6744 WARN("NAKED_SSCANF",
6745 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6748 # check for simple sscanf that should be kstrto<foo>
6749 if ($perl_version_ok &&
6751 $line =~ /\bsscanf\b/) {
6752 my $lc = $stat =~ tr@\n@@;
6753 $lc = $lc + $linenr;
6754 my $stat_real = get_stat_real($linenr, $lc);
6755 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6757 my $count = $format =~ tr@%@%@;
6759 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6760 WARN("SSCANF_TO_KSTRTO",
6761 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6766 # check for new externs in .h files.
6767 if ($realfile =~ /\.h$/ &&
6768 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6769 if (CHK("AVOID_EXTERNS",
6770 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6772 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6776 # check for new externs in .c files.
6777 if ($realfile =~ /\.c$/ && defined $stat &&
6778 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6780 my $function_name = $1;
6781 my $paren_space = $2;
6784 if (defined $cond) {
6785 substr($s, 0, length($cond), '');
6789 WARN("AVOID_EXTERNS",
6790 "externs should be avoided in .c files\n" . $herecurr);
6793 if ($paren_space =~ /\n/) {
6794 WARN("FUNCTION_ARGUMENTS",
6795 "arguments for function declarations should follow identifier\n" . $herecurr);
6798 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6799 $stat =~ /^.\s*extern\s+/)
6801 WARN("AVOID_EXTERNS",
6802 "externs should be avoided in .c files\n" . $herecurr);
6805 # check for function declarations that have arguments without identifier names
6806 if (defined $stat &&
6807 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6809 my $args = trim($1);
6810 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6812 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6813 WARN("FUNCTION_ARGUMENTS",
6814 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6819 # check for function definitions
6820 if ($perl_version_ok &&
6822 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6823 $context_function = $1;
6825 # check for multiline function definition with misplaced open brace
6827 my $cnt = statement_rawlines($stat);
6828 my $herectx = $here . "\n";
6829 for (my $n = 0; $n < $cnt; $n++) {
6830 my $rl = raw_line($linenr, $n);
6831 $herectx .= $rl . "\n";
6832 $ok = 1 if ($rl =~ /^[ \+]\{/);
6833 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6834 last if $rl =~ /^[ \+].*\{/;
6838 "open brace '{' following function definitions go on the next line\n" . $herectx);
6842 # checks for new __setup's
6843 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6846 if (!grep(/$name/, @setup_docs)) {
6847 CHK("UNDOCUMENTED_SETUP",
6848 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6852 # check for pointless casting of alloc functions
6853 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6854 WARN("UNNECESSARY_CASTS",
6855 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6859 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6860 if ($perl_version_ok &&
6861 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6862 CHK("ALLOC_SIZEOF_STRUCT",
6863 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6866 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6867 if ($perl_version_ok &&
6869 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6873 my $newfunc = "kmalloc_array";
6874 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6877 if ($a1 =~ /^sizeof\s*\S/) {
6881 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6882 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6883 my $cnt = statement_rawlines($stat);
6884 my $herectx = get_stat_here($linenr, $cnt, $here);
6886 if (WARN("ALLOC_WITH_MULTIPLY",
6887 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6890 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
6895 # check for krealloc arg reuse
6896 if ($perl_version_ok &&
6897 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6899 WARN("KREALLOC_ARG_REUSE",
6900 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6903 # check for alloc argument mismatch
6904 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6905 WARN("ALLOC_ARRAY_ARGS",
6906 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6909 # check for multiple semicolons
6910 if ($line =~ /;\s*;\s*$/) {
6911 if (WARN("ONE_SEMICOLON",
6912 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6914 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6918 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6919 if ($realfile !~ m@^include/uapi/@ &&
6920 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6922 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6923 if (CHK("BIT_MACRO",
6924 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6926 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6930 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6931 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6932 WARN("IS_ENABLED_CONFIG",
6933 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6936 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6937 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6939 if (WARN("PREFER_IS_ENABLED",
6940 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6942 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6946 # check for /* fallthrough */ like comment, prefer fallthrough;
6947 my @fallthroughs = (
6950 'lint -fallthrough[ \t]*',
6951 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6952 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6953 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6954 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6956 if ($raw_comment ne '') {
6957 foreach my $ft (@fallthroughs) {
6958 if ($raw_comment =~ /$ft/) {
6959 my $msg_level = \&WARN;
6960 $msg_level = \&CHK if ($file);
6961 &{$msg_level}("PREFER_FALLTHROUGH",
6962 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6968 # check for switch/default statements without a break;
6969 if ($perl_version_ok &&
6971 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6972 my $cnt = statement_rawlines($stat);
6973 my $herectx = get_stat_here($linenr, $cnt, $here);
6975 WARN("DEFAULT_NO_BREAK",
6976 "switch default: should use break\n" . $herectx);
6979 # check for gcc specific __FUNCTION__
6980 if ($line =~ /\b__FUNCTION__\b/) {
6981 if (WARN("USE_FUNC",
6982 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6984 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6988 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6989 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6991 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6994 # check for use of yield()
6995 if ($line =~ /\byield\s*\(\s*\)/) {
6997 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7000 # check for comparisons against true and false
7001 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7009 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7011 my $type = lc($otype);
7012 if ($type =~ /^(?:true|false)$/) {
7013 if (("$test" eq "==" && "$type" eq "true") ||
7014 ("$test" eq "!=" && "$type" eq "false")) {
7018 CHK("BOOL_COMPARISON",
7019 "Using comparison to $otype is error prone\n" . $herecurr);
7021 ## maybe suggesting a correct construct would better
7022 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7027 # check for semaphores initialized locked
7028 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7029 WARN("CONSIDER_COMPLETION",
7030 "consider using a completion\n" . $herecurr);
7033 # recommend kstrto* over simple_strto* and strict_strto*
7034 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7035 WARN("CONSIDER_KSTRTO",
7036 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7039 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7040 if ($line =~ /^.\s*__initcall\s*\(/) {
7041 WARN("USE_DEVICE_INITCALL",
7042 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7045 # check for spin_is_locked(), suggest lockdep instead
7046 if ($line =~ /\bspin_is_locked\(/) {
7048 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7051 # check for deprecated apis
7052 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7053 my $deprecated_api = $1;
7054 my $new_api = $deprecated_apis{$deprecated_api};
7055 WARN("DEPRECATED_API",
7056 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7059 # check for various structs that are normally const (ops, kgdb, device_tree)
7060 # and avoid what seem like struct definitions 'struct foo {'
7061 if (defined($const_structs) &&
7062 $line !~ /\bconst\b/ &&
7063 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7064 WARN("CONST_STRUCT",
7065 "struct $1 should normally be const\n" . $herecurr);
7068 # use of NR_CPUS is usually wrong
7069 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7070 # ignore designated initializers using NR_CPUS
7071 if ($line =~ /\bNR_CPUS\b/ &&
7072 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7073 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7074 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7075 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7076 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7077 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7080 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7083 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7084 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7085 ERROR("DEFINE_ARCH_HAS",
7086 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7089 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7090 if ($perl_version_ok &&
7091 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7092 WARN("LIKELY_MISUSE",
7093 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7096 # nested likely/unlikely calls
7097 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7098 WARN("LIKELY_MISUSE",
7099 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7102 # whine mightly about in_atomic
7103 if ($line =~ /\bin_atomic\s*\(/) {
7104 if ($realfile =~ m@^drivers/@) {
7106 "do not use in_atomic in drivers\n" . $herecurr);
7107 } elsif ($realfile !~ m@^kernel/@) {
7109 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7113 # check for lockdep_set_novalidate_class
7114 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7115 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7116 if ($realfile !~ m@^kernel/lockdep@ &&
7117 $realfile !~ m@^include/linux/lockdep@ &&
7118 $realfile !~ m@^drivers/base/core@) {
7120 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7124 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7125 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7126 WARN("EXPORTED_WORLD_WRITABLE",
7127 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7130 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7131 # and whether or not function naming is typical and if
7132 # DEVICE_ATTR permissions uses are unusual too
7133 if ($perl_version_ok &&
7135 $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*\)/) {
7140 my $octal_perms = perms_to_octal($perms);
7141 if ($show =~ /^${var}_show$/ &&
7142 $store =~ /^${var}_store$/ &&
7143 $octal_perms eq "0644") {
7144 if (WARN("DEVICE_ATTR_RW",
7145 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7147 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7149 } elsif ($show =~ /^${var}_show$/ &&
7150 $store =~ /^NULL$/ &&
7151 $octal_perms eq "0444") {
7152 if (WARN("DEVICE_ATTR_RO",
7153 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7155 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7157 } elsif ($show =~ /^NULL$/ &&
7158 $store =~ /^${var}_store$/ &&
7159 $octal_perms eq "0200") {
7160 if (WARN("DEVICE_ATTR_WO",
7161 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7163 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7165 } elsif ($octal_perms eq "0644" ||
7166 $octal_perms eq "0444" ||
7167 $octal_perms eq "0200") {
7168 my $newshow = "$show";
7169 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7170 my $newstore = $store;
7171 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7173 if ($show ne $newshow) {
7174 $rename .= " '$show' to '$newshow'";
7176 if ($store ne $newstore) {
7177 $rename .= " '$store' to '$newstore'";
7179 WARN("DEVICE_ATTR_FUNCTIONS",
7180 "Consider renaming function(s)$rename\n" . $herecurr);
7182 WARN("DEVICE_ATTR_PERMS",
7183 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7187 # Mode permission misuses where it seems decimal should be octal
7188 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7189 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7190 # specific definition of not visible in sysfs.
7191 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7192 # use the default permissions
7193 if ($perl_version_ok &&
7195 $line =~ /$mode_perms_search/) {
7196 foreach my $entry (@mode_permission_funcs) {
7197 my $func = $entry->[0];
7198 my $arg_pos = $entry->[1];
7200 my $lc = $stat =~ tr@\n@@;
7201 $lc = $lc + $linenr;
7202 my $stat_real = get_stat_real($linenr, $lc);
7207 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7209 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7210 if ($stat =~ /$test/) {
7212 $val = $6 if ($skip_args ne "");
7213 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7214 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7215 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7216 ERROR("NON_OCTAL_PERMISSIONS",
7217 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7219 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7220 ERROR("EXPORTED_WORLD_WRITABLE",
7221 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7227 # check for uses of S_<PERMS> that could be octal for readability
7228 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7230 my $octal = perms_to_octal($oval);
7231 if (WARN("SYMBOLIC_PERMS",
7232 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7234 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7238 # validate content of MODULE_LICENSE against list from include/linux/module.h
7239 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7240 my $extracted_string = get_quoted_string($line, $rawline);
7241 my $valid_licenses = qr{
7244 GPL\ and\ additional\ rights|
7250 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7251 WARN("MODULE_LICENSE",
7252 "unknown module license " . $extracted_string . "\n" . $herecurr);
7256 # check for sysctl duplicate constants
7257 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7258 WARN("DUPLICATED_SYSCTL_CONST",
7259 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7263 # If we have no input at all, then there is nothing to report on
7264 # so just keep quiet.
7265 if ($#rawlines == -1) {
7269 # In mailback mode only produce a report in the negative, for
7270 # things that appear to be patches.
7271 if ($mailback && ($clean == 1 || !$is_patch)) {
7275 # This is not a patch, and we are in 'no-patch' mode so
7277 if (!$chk_patch && !$is_patch) {
7281 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7282 ERROR("NOT_UNIFIED_DIFF",
7283 "Does not appear to be a unified-diff format patch\n");
7285 if ($is_patch && $has_commit_log && $chk_signoff) {
7286 if ($signoff == 0) {
7287 ERROR("MISSING_SIGN_OFF",
7288 "Missing Signed-off-by: line(s)\n");
7289 } elsif ($authorsignoff != 1) {
7290 # authorsignoff values:
7291 # 0 -> missing sign off
7292 # 1 -> sign off identical
7293 # 2 -> names and addresses match, comments mismatch
7294 # 3 -> addresses match, names different
7295 # 4 -> names match, addresses different
7296 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7298 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7300 if ($authorsignoff == 0) {
7301 ERROR("NO_AUTHOR_SIGN_OFF",
7302 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7303 } elsif ($authorsignoff == 2) {
7304 CHK("FROM_SIGN_OFF_MISMATCH",
7305 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7306 } elsif ($authorsignoff == 3) {
7307 WARN("FROM_SIGN_OFF_MISMATCH",
7308 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7309 } elsif ($authorsignoff == 4) {
7310 WARN("FROM_SIGN_OFF_MISMATCH",
7311 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7312 } elsif ($authorsignoff == 5) {
7313 WARN("FROM_SIGN_OFF_MISMATCH",
7314 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7319 print report_dump();
7320 if ($summary && !($clean == 1 && $quiet == 1)) {
7321 print "$filename " if ($summary_file);
7322 print "total: $cnt_error errors, $cnt_warn warnings, " .
7323 (($check)? "$cnt_chk checks, " : "") .
7324 "$cnt_lines lines checked\n";
7328 # If there were any defects found and not already fixing them
7329 if (!$clean and !$fix) {
7332 NOTE: For some of the reported defects, checkpatch may be able to
7333 mechanically convert to the typical style using --fix or --fix-inplace.
7336 # If there were whitespace errors which cleanpatch can fix
7337 # then suggest that.
7338 if ($rpt_cleaners) {
7342 NOTE: Whitespace errors detected.
7343 You may wish to use scripts/cleanpatch or scripts/cleanfile
7348 if ($clean == 0 && $fix &&
7349 ("@rawlines" ne "@fixed" ||
7350 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7351 my $newfile = $filename;
7352 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7356 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7358 open($f, '>', $newfile)
7359 or die "$P: Can't open $newfile for write\n";
7360 foreach my $fixed_line (@fixed) {
7363 if ($linecount > 3) {
7364 $fixed_line =~ s/^\+//;
7365 print $f $fixed_line . "\n";
7368 print $f $fixed_line . "\n";
7376 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7378 Do _NOT_ trust the results written to this file.
7379 Do _NOT_ submit these changes without inspecting them for correctness.
7381 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7382 No warranties, expressed or implied...
7390 print "$vname has no obvious style problems and is ready for submission.\n";
7392 print "$vname has style problems, please review.\n";