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(?:_node|_array)? |
493 (?:\w+)?alloc_skb(?:_ip_align)? |
494 # dev_alloc_skb/netdev_alloc_skb, et al
498 our $signature_tags = qr{(?xi:
510 sub edit_distance_min {
512 my $len = scalar @arr;
513 if ((scalar @arr) < 1) {
514 # if underflow, return
518 for my $i (0 .. ($len-1)) {
519 if ($arr[$i] < $min) {
526 sub get_edit_distance {
527 my ($str1, $str2) = @_;
532 my $len1 = length($str1);
533 my $len2 = length($str2);
534 # two dimensional array storing minimum edit distance
536 for my $i (0 .. $len1) {
537 for my $j (0 .. $len2) {
539 $distance[$i][$j] = $j;
541 $distance[$i][$j] = $i;
542 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
543 $distance[$i][$j] = $distance[$i - 1][$j - 1];
545 my $dist1 = $distance[$i][$j - 1]; #insert distance
546 my $dist2 = $distance[$i - 1][$j]; # remove
547 my $dist3 = $distance[$i - 1][$j - 1]; #replace
548 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
552 return $distance[$len1][$len2];
555 sub find_standard_signature {
557 my @standard_signature_tags = (
558 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
559 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
561 foreach my $signature (@standard_signature_tags) {
562 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
568 our @typeListMisordered = (
569 qr{char\s+(?:un)?signed},
570 qr{int\s+(?:(?:un)?signed\s+)?short\s},
571 qr{int\s+short(?:\s+(?:un)?signed)},
572 qr{short\s+int(?:\s+(?:un)?signed)},
573 qr{(?:un)?signed\s+int\s+short},
574 qr{short\s+(?:un)?signed},
575 qr{long\s+int\s+(?:un)?signed},
576 qr{int\s+long\s+(?:un)?signed},
577 qr{long\s+(?:un)?signed\s+int},
578 qr{int\s+(?:un)?signed\s+long},
579 qr{int\s+(?:un)?signed},
580 qr{int\s+long\s+long\s+(?:un)?signed},
581 qr{long\s+long\s+int\s+(?:un)?signed},
582 qr{long\s+long\s+(?:un)?signed\s+int},
583 qr{long\s+long\s+(?:un)?signed},
584 qr{long\s+(?:un)?signed},
589 qr{(?:(?:un)?signed\s+)?char},
590 qr{(?:(?:un)?signed\s+)?short\s+int},
591 qr{(?:(?:un)?signed\s+)?short},
592 qr{(?:(?:un)?signed\s+)?int},
593 qr{(?:(?:un)?signed\s+)?long\s+int},
594 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
595 qr{(?:(?:un)?signed\s+)?long\s+long},
596 qr{(?:(?:un)?signed\s+)?long},
605 qr{${Ident}_handler},
606 qr{${Ident}_handler_fn},
610 our $C90_int_types = qr{(?x:
611 long\s+long\s+int\s+(?:un)?signed|
612 long\s+long\s+(?:un)?signed\s+int|
613 long\s+long\s+(?:un)?signed|
614 (?:(?:un)?signed\s+)?long\s+long\s+int|
615 (?:(?:un)?signed\s+)?long\s+long|
616 int\s+long\s+long\s+(?:un)?signed|
617 int\s+(?:(?:un)?signed\s+)?long\s+long|
619 long\s+int\s+(?:un)?signed|
620 long\s+(?:un)?signed\s+int|
621 long\s+(?:un)?signed|
622 (?:(?:un)?signed\s+)?long\s+int|
623 (?:(?:un)?signed\s+)?long|
624 int\s+long\s+(?:un)?signed|
625 int\s+(?:(?:un)?signed\s+)?long|
628 (?:(?:un)?signed\s+)?int
631 our @typeListFile = ();
632 our @typeListWithAttr = (
634 qr{struct\s+$InitAttribute\s+$Ident},
635 qr{union\s+$InitAttribute\s+$Ident},
638 our @modifierList = (
641 our @modifierListFile = ();
643 our @mode_permission_funcs = (
645 ["module_param_(?:array|named|string)", 4],
646 ["module_param_array_named", 5],
647 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
648 ["proc_create(?:_data|)", 2],
649 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
650 ["IIO_DEV_ATTR_[A-Z_]+", 1],
651 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
652 ["SENSOR_TEMPLATE(?:_2|)", 3],
656 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
658 #Create a search pattern for all these functions to speed up a loop below
659 our $mode_perms_search = "";
660 foreach my $entry (@mode_permission_funcs) {
661 $mode_perms_search .= '|' if ($mode_perms_search ne "");
662 $mode_perms_search .= $entry->[0];
664 $mode_perms_search = "(?:${mode_perms_search})";
666 our %deprecated_apis = (
667 "synchronize_rcu_bh" => "synchronize_rcu",
668 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
669 "call_rcu_bh" => "call_rcu",
670 "rcu_barrier_bh" => "rcu_barrier",
671 "synchronize_sched" => "synchronize_rcu",
672 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
673 "call_rcu_sched" => "call_rcu",
674 "rcu_barrier_sched" => "rcu_barrier",
675 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
676 "cond_synchronize_sched" => "cond_synchronize_rcu",
679 #Create a search pattern for all these strings to speed up a loop below
680 our $deprecated_apis_search = "";
681 foreach my $entry (keys %deprecated_apis) {
682 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
683 $deprecated_apis_search .= $entry;
685 $deprecated_apis_search = "(?:${deprecated_apis_search})";
687 our $mode_perms_world_writable = qr{
695 our %mode_permission_string_types = (
714 #Create a search pattern for all these strings to speed up a loop below
715 our $mode_perms_string_search = "";
716 foreach my $entry (keys %mode_permission_string_types) {
717 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
718 $mode_perms_string_search .= $entry;
720 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
721 our $multi_mode_perms_string_search = qr{
722 ${single_mode_perms_string_search}
723 (?:\s*\|\s*${single_mode_perms_string_search})*
729 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
736 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
737 $curpos = pos($string);
740 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
742 $to |= $mode_permission_string_types{$match};
743 $val .= '\s*\|\s*' if ($val ne "");
747 $oval =~ s/^\s*\|\s*//;
748 $oval =~ s/\s*\|\s*$//;
749 return sprintf("%04o", $to);
752 our $allowed_asm_includes = qr{(?x:
758 # memory.h: ARM has a custom one
760 # Load common spelling mistakes and build regular expression list.
764 if (open(my $spelling, '<', $spelling_file)) {
765 while (<$spelling>) {
768 $line =~ s/\s*\n?$//g;
771 next if ($line =~ m/^\s*#/);
772 next if ($line =~ m/^\s*$/);
774 my ($suspect, $fix) = split(/\|\|/, $line);
776 $spelling_fix{$suspect} = $fix;
780 warn "No typos will be found - file '$spelling_file': $!\n";
784 if (open(my $spelling, '<', $codespellfile)) {
785 while (<$spelling>) {
788 $line =~ s/\s*\n?$//g;
791 next if ($line =~ m/^\s*#/);
792 next if ($line =~ m/^\s*$/);
793 next if ($line =~ m/, disabled/i);
797 my ($suspect, $fix) = split(/->/, $line);
799 $spelling_fix{$suspect} = $fix;
803 warn "No codespell typos will be found - file '$codespellfile': $!\n";
807 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
810 my ($wordsRef, $file) = @_;
812 if (open(my $words, '<', $file)) {
816 $line =~ s/\s*\n?$//g;
819 next if ($line =~ m/^\s*#/);
820 next if ($line =~ m/^\s*$/);
822 print("$file: '$line' invalid - ignored\n");
826 $$wordsRef .= '|' if (defined $$wordsRef);
837 if (show_type("CONST_STRUCT")) {
838 read_words(\$const_structs, $conststructsfile)
839 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
842 if (defined($typedefsfile)) {
843 my $typeOtherTypedefs;
844 read_words(\$typeOtherTypedefs, $typedefsfile)
845 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
846 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
850 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
851 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
852 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
853 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
854 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
860 (?:$Modifier\s+|const\s+)*
862 (?:typeof|__typeof__)\s*\([^\)]*\)|
866 (?:\s+$Modifier|\s+const)*
868 $NonptrTypeMisordered = qr{
869 (?:$Modifier\s+|const\s+)*
873 (?:\s+$Modifier|\s+const)*
875 $NonptrTypeWithAttr = qr{
876 (?:$Modifier\s+|const\s+)*
878 (?:typeof|__typeof__)\s*\([^\)]*\)|
882 (?:\s+$Modifier|\s+const)*
886 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
887 (?:\s+$Inline|\s+$Modifier)*
889 $TypeMisordered = qr{
890 $NonptrTypeMisordered
891 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
892 (?:\s+$Inline|\s+$Modifier)*
894 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
895 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
899 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
901 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
902 # requires at least perl version v5.10.0
903 # Any use must be runtime checked with $^V
905 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
906 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
907 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
909 our $declaration_macros = qr{(?x:
910 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
911 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
912 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
915 our %allow_repeated_words = (
924 return "" if (!defined($string));
926 while ($string =~ /^\s*\(.*\)\s*$/) {
927 $string =~ s@^\s*\(\s*@@;
928 $string =~ s@\s*\)\s*$@@;
931 $string =~ s@\s+@ @g;
936 sub seed_camelcase_file {
939 return if (!(-f $file));
943 open(my $include_file, '<', "$file")
944 or warn "$P: Can't read '$file' $!\n";
945 my $text = <$include_file>;
946 close($include_file);
948 my @lines = split('\n', $text);
950 foreach my $line (@lines) {
951 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
952 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
954 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
956 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
962 our %maintained_status = ();
964 sub is_maintained_obsolete {
967 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
969 if (!exists($maintained_status{$filename})) {
970 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
973 return $maintained_status{$filename} =~ /obsolete/i;
976 sub is_SPDX_License_valid {
979 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
981 my $root_path = abs_path($root);
982 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
983 return 0 if ($status ne "");
987 my $camelcase_seeded = 0;
988 sub seed_camelcase_includes {
989 return if ($camelcase_seeded);
992 my $camelcase_cache = "";
993 my @include_files = ();
995 $camelcase_seeded = 1;
998 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
999 chomp $git_last_include_commit;
1000 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1002 my $last_mod_date = 0;
1003 $files = `find $root/include -name "*.h"`;
1004 @include_files = split('\n', $files);
1005 foreach my $file (@include_files) {
1006 my $date = POSIX::strftime("%Y%m%d%H%M",
1007 localtime((stat $file)[9]));
1008 $last_mod_date = $date if ($last_mod_date < $date);
1010 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1013 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1014 open(my $camelcase_file, '<', "$camelcase_cache")
1015 or warn "$P: Can't read '$camelcase_cache' $!\n";
1016 while (<$camelcase_file>) {
1020 close($camelcase_file);
1025 if (-e "$gitroot") {
1026 $files = `${git_command} ls-files "include/*.h"`;
1027 @include_files = split('\n', $files);
1030 foreach my $file (@include_files) {
1031 seed_camelcase_file($file);
1034 if ($camelcase_cache ne "") {
1035 unlink glob ".checkpatch-camelcase.*";
1036 open(my $camelcase_file, '>', "$camelcase_cache")
1037 or warn "$P: Can't write '$camelcase_cache' $!\n";
1038 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1039 print $camelcase_file ("$_\n");
1041 close($camelcase_file);
1045 sub git_is_single_file {
1046 my ($filename) = @_;
1048 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1050 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1051 my $count = $output =~ tr/\n//;
1052 return $count eq 1 && $output =~ m{^${filename}$};
1055 sub git_commit_info {
1056 my ($commit, $id, $desc) = @_;
1058 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1060 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1061 $output =~ s/^\s*//gm;
1062 my @lines = split("\n", $output);
1064 return ($id, $desc) if ($#lines < 0);
1066 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1067 # Maybe one day convert this block of bash into something that returns
1068 # all matching commit ids, but it's very slow...
1070 # echo "checking commits $1..."
1071 # git rev-list --remotes | grep -i "^$1" |
1072 # while read line ; do
1073 # git log --format='%H %s' -1 $line |
1074 # echo "commit $(cut -c 1-12,41-)"
1076 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1079 $id = substr($lines[0], 0, 12);
1080 $desc = substr($lines[0], 41);
1083 return ($id, $desc);
1086 $chk_signoff = 0 if ($file);
1091 my @fixed_inserted = ();
1092 my @fixed_deleted = ();
1095 # If input is git commits, extract all commits from the commit expressions.
1096 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1097 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1101 foreach my $commit_expr (@ARGV) {
1103 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1104 $git_range = "-$2 $1";
1105 } elsif ($commit_expr =~ m/\.\./) {
1106 $git_range = "$commit_expr";
1108 $git_range = "-1 $commit_expr";
1110 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1111 foreach my $line (split(/\n/, $lines)) {
1112 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1113 next if (!defined($1) || !defined($2));
1116 unshift(@commits, $sha1);
1117 $git_commits{$sha1} = $subject;
1120 die "$P: no git commits after extraction!\n" if (@commits == 0);
1125 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1126 for my $filename (@ARGV) {
1128 my $is_git_file = git_is_single_file($filename);
1129 my $oldfile = $file;
1130 $file = 1 if ($is_git_file);
1132 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1133 die "$P: $filename: git format-patch failed - $!\n";
1135 open($FILE, '-|', "diff -u /dev/null $filename") ||
1136 die "$P: $filename: diff failed - $!\n";
1137 } elsif ($filename eq '-') {
1138 open($FILE, '<&STDIN');
1140 open($FILE, '<', "$filename") ||
1141 die "$P: $filename: open failed - $!\n";
1143 if ($filename eq '-') {
1144 $vname = 'Your patch';
1146 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1152 push(@rawlines, $_);
1153 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1157 if ($#ARGV > 0 && $quiet == 0) {
1158 print '-' x length($vname) . "\n";
1160 print '-' x length($vname) . "\n";
1163 if (!process($filename)) {
1169 @fixed_inserted = ();
1170 @fixed_deleted = ();
1172 @modifierListFile = ();
1175 $file = $oldfile if ($is_git_file);
1179 hash_show_words(\%use_type, "Used");
1180 hash_show_words(\%ignore_type, "Ignored");
1182 if (!$perl_version_ok) {
1185 NOTE: perl $^V is not modern enough to detect all possible issues.
1186 An upgrade to at least perl $minimum_perl_version is suggested.
1192 NOTE: If any of the errors are false positives, please report
1193 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1200 sub top_of_kernel_tree {
1204 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1205 "README", "Documentation", "arch", "include", "drivers",
1206 "fs", "init", "ipc", "kernel", "lib", "scripts",
1209 foreach my $check (@tree_check) {
1210 if (! -e $root . '/' . $check) {
1218 my ($formatted_email) = @_;
1222 my $name_comment = "";
1226 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1229 $comment = $3 if defined $3;
1230 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1232 $comment = $2 if defined $2;
1233 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1235 $comment = $2 if defined $2;
1236 $formatted_email =~ s/\Q$address\E.*$//;
1237 $name = $formatted_email;
1238 $name = trim($name);
1239 $name =~ s/^\"|\"$//g;
1240 # If there's a name left after stripping spaces and
1241 # leading quotes, and the address doesn't have both
1242 # leading and trailing angle brackets, the address
1244 # "joe smith joe@smith.com" bad
1245 # "joe smith <joe@smith.com" bad
1246 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1253 # Extract comments from names excluding quoted parts
1254 # "John D. (Doe)" - Do not extract
1255 if ($name =~ s/\"(.+)\"//) {
1258 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1259 $name_comment .= trim($1);
1261 $name =~ s/^[ \"]+|[ \"]+$//g;
1262 $name = trim("$quoted $name");
1264 $address = trim($address);
1265 $address =~ s/^\<|\>$//g;
1266 $comment = trim($comment);
1268 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1269 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1270 $name = "\"$name\"";
1273 return ($name, $name_comment, $address, $comment);
1277 my ($name, $name_comment, $address, $comment) = @_;
1279 my $formatted_email;
1281 $name =~ s/^[ \"]+|[ \"]+$//g;
1282 $address = trim($address);
1283 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1285 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1286 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1287 $name = "\"$name\"";
1290 $name_comment = trim($name_comment);
1291 $name_comment = " $name_comment" if ($name_comment ne "");
1292 $comment = trim($comment);
1293 $comment = " $comment" if ($comment ne "");
1295 if ("$name" eq "") {
1296 $formatted_email = "$address";
1298 $formatted_email = "$name$name_comment <$address>";
1300 $formatted_email .= "$comment";
1301 return $formatted_email;
1304 sub reformat_email {
1307 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1308 return format_email($email_name, $name_comment, $email_address, $comment);
1311 sub same_email_addresses {
1312 my ($email1, $email2) = @_;
1314 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1315 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1317 return $email1_name eq $email2_name &&
1318 $email1_address eq $email2_address &&
1319 $name1_comment eq $name2_comment &&
1320 $comment1 eq $comment2;
1326 foreach my $path (split(/:/, $ENV{PATH})) {
1327 if (-e "$path/$bin") {
1328 return "$path/$bin";
1338 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1339 if (-e "$path/$conf") {
1340 return "$path/$conf";
1352 for my $c (split(//, $str)) {
1356 for (; ($n % $tabsize) != 0; $n++) {
1368 (my $res = shift) =~ tr/\t/ /c;
1375 # Drop the diff line leader and expand tabs
1377 $line = expand_tabs($line);
1379 # Pick the indent from the front of the line.
1380 my ($white) = ($line =~ /^(\s*)/);
1382 return (length($line), length($white));
1385 my $sanitise_quote = '';
1387 sub sanitise_line_reset {
1388 my ($in_comment) = @_;
1391 $sanitise_quote = '*/';
1393 $sanitise_quote = '';
1406 # Always copy over the diff marker.
1407 $res = substr($line, 0, 1);
1409 for ($off = 1; $off < length($line); $off++) {
1410 $c = substr($line, $off, 1);
1412 # Comments we are whacking completely including the begin
1413 # and end, all to $;.
1414 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1415 $sanitise_quote = '*/';
1417 substr($res, $off, 2, "$;$;");
1421 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1422 $sanitise_quote = '';
1423 substr($res, $off, 2, "$;$;");
1427 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1428 $sanitise_quote = '//';
1430 substr($res, $off, 2, $sanitise_quote);
1435 # A \ in a string means ignore the next character.
1436 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1438 substr($res, $off, 2, 'XX');
1443 if ($c eq "'" || $c eq '"') {
1444 if ($sanitise_quote eq '') {
1445 $sanitise_quote = $c;
1447 substr($res, $off, 1, $c);
1449 } elsif ($sanitise_quote eq $c) {
1450 $sanitise_quote = '';
1454 #print "c<$c> SQ<$sanitise_quote>\n";
1455 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1456 substr($res, $off, 1, $;);
1457 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1458 substr($res, $off, 1, $;);
1459 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1460 substr($res, $off, 1, 'X');
1462 substr($res, $off, 1, $c);
1466 if ($sanitise_quote eq '//') {
1467 $sanitise_quote = '';
1470 # The pathname on a #include may be surrounded by '<' and '>'.
1471 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1472 my $clean = 'X' x length($1);
1473 $res =~ s@\<.*\>@<$clean>@;
1475 # The whole of a #error is a string.
1476 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1477 my $clean = 'X' x length($1);
1478 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1481 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1483 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1489 sub get_quoted_string {
1490 my ($line, $rawline) = @_;
1492 return "" if (!defined($line) || !defined($rawline));
1493 return "" if ($line !~ m/($String)/g);
1494 return substr($rawline, $-[0], $+[0] - $-[0]);
1497 sub ctx_statement_block {
1498 my ($linenr, $remain, $off) = @_;
1499 my $line = $linenr - 1;
1502 my $coff = $off - 1;
1516 @stack = (['', 0]) if ($#stack == -1);
1518 #warn "CSB: blk<$blk> remain<$remain>\n";
1519 # If we are about to drop off the end, pull in more
1522 for (; $remain > 0; $line++) {
1523 last if (!defined $lines[$line]);
1524 next if ($lines[$line] =~ /^-/);
1527 $blk .= $lines[$line] . "\n";
1528 $len = length($blk);
1532 # Bail if there is no further context.
1533 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1537 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1543 $c = substr($blk, $off, 1);
1544 $remainder = substr($blk, $off);
1546 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1548 # Handle nested #if/#else.
1549 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1550 push(@stack, [ $type, $level ]);
1551 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1552 ($type, $level) = @{$stack[$#stack - 1]};
1553 } elsif ($remainder =~ /^#\s*endif\b/) {
1554 ($type, $level) = @{pop(@stack)};
1557 # Statement ends at the ';' or a close '}' at the
1559 if ($level == 0 && $c eq ';') {
1563 # An else is really a conditional as long as its not else if
1564 if ($level == 0 && $coff_set == 0 &&
1565 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1566 $remainder =~ /^(else)(?:\s|{)/ &&
1567 $remainder !~ /^else\s+if\b/) {
1568 $coff = $off + length($1) - 1;
1570 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1571 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1574 if (($type eq '' || $type eq '(') && $c eq '(') {
1578 if ($type eq '(' && $c eq ')') {
1580 $type = ($level != 0)? '(' : '';
1582 if ($level == 0 && $coff < $soff) {
1585 #warn "CSB: mark coff<$coff>\n";
1588 if (($type eq '' || $type eq '{') && $c eq '{') {
1592 if ($type eq '{' && $c eq '}') {
1594 $type = ($level != 0)? '{' : '';
1597 if (substr($blk, $off + 1, 1) eq ';') {
1603 # Preprocessor commands end at the newline unless escaped.
1604 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1612 # We are truly at the end, so shuffle to the next line.
1619 my $statement = substr($blk, $soff, $off - $soff + 1);
1620 my $condition = substr($blk, $soff, $coff - $soff + 1);
1622 #warn "STATEMENT<$statement>\n";
1623 #warn "CONDITION<$condition>\n";
1625 #print "coff<$coff> soff<$off> loff<$loff>\n";
1627 return ($statement, $condition,
1628 $line, $remain + 1, $off - $loff + 1, $level);
1631 sub statement_lines {
1634 # Strip the diff line prefixes and rip blank lines at start and end.
1635 $stmt =~ s/(^|\n)./$1/g;
1639 my @stmt_lines = ($stmt =~ /\n/g);
1641 return $#stmt_lines + 2;
1644 sub statement_rawlines {
1647 my @stmt_lines = ($stmt =~ /\n/g);
1649 return $#stmt_lines + 2;
1652 sub statement_block_size {
1655 $stmt =~ s/(^|\n)./$1/g;
1661 my @stmt_lines = ($stmt =~ /\n/g);
1662 my @stmt_statements = ($stmt =~ /;/g);
1664 my $stmt_lines = $#stmt_lines + 2;
1665 my $stmt_statements = $#stmt_statements + 1;
1667 if ($stmt_lines > $stmt_statements) {
1670 return $stmt_statements;
1674 sub ctx_statement_full {
1675 my ($linenr, $remain, $off) = @_;
1676 my ($statement, $condition, $level);
1680 # Grab the first conditional/block pair.
1681 ($statement, $condition, $linenr, $remain, $off, $level) =
1682 ctx_statement_block($linenr, $remain, $off);
1683 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1684 push(@chunks, [ $condition, $statement ]);
1685 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1686 return ($level, $linenr, @chunks);
1689 # Pull in the following conditional/block pairs and see if they
1690 # could continue the statement.
1692 ($statement, $condition, $linenr, $remain, $off, $level) =
1693 ctx_statement_block($linenr, $remain, $off);
1694 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1695 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1697 push(@chunks, [ $condition, $statement ]);
1700 return ($level, $linenr, @chunks);
1704 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1706 my $start = $linenr - 1;
1713 my @stack = ($level);
1714 for ($line = $start; $remain > 0; $line++) {
1715 next if ($rawlines[$line] =~ /^-/);
1718 $blk .= $rawlines[$line];
1720 # Handle nested #if/#else.
1721 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1722 push(@stack, $level);
1723 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1724 $level = $stack[$#stack - 1];
1725 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1726 $level = pop(@stack);
1729 foreach my $c (split(//, $lines[$line])) {
1730 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1736 if ($c eq $close && $level > 0) {
1738 last if ($level == 0);
1739 } elsif ($c eq $open) {
1744 if (!$outer || $level <= 1) {
1745 push(@res, $rawlines[$line]);
1748 last if ($level == 0);
1751 return ($level, @res);
1753 sub ctx_block_outer {
1754 my ($linenr, $remain) = @_;
1756 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1760 my ($linenr, $remain) = @_;
1762 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1766 my ($linenr, $remain, $off) = @_;
1768 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1771 sub ctx_block_level {
1772 my ($linenr, $remain) = @_;
1774 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1776 sub ctx_statement_level {
1777 my ($linenr, $remain, $off) = @_;
1779 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1782 sub ctx_locate_comment {
1783 my ($first_line, $end_line) = @_;
1785 # If c99 comment on the current line, or the line before or after
1786 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1787 return $current_comment if (defined $current_comment);
1788 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1789 return $current_comment if (defined $current_comment);
1790 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1791 return $current_comment if (defined $current_comment);
1793 # Catch a comment on the end of the line itself.
1794 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1795 return $current_comment if (defined $current_comment);
1797 # Look through the context and try and figure out if there is a
1800 $current_comment = '';
1801 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1802 my $line = $rawlines[$linenr - 1];
1804 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1807 if ($line =~ m@/\*@) {
1810 if (!$in_comment && $current_comment ne '') {
1811 $current_comment = '';
1813 $current_comment .= $line . "\n" if ($in_comment);
1814 if ($line =~ m@\*/@) {
1819 chomp($current_comment);
1820 return($current_comment);
1822 sub ctx_has_comment {
1823 my ($first_line, $end_line) = @_;
1824 my $cmt = ctx_locate_comment($first_line, $end_line);
1826 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1827 ##print "CMMT: $cmt\n";
1829 return ($cmt ne '');
1833 my ($linenr, $cnt) = @_;
1835 my $offset = $linenr - 1;
1840 $line = $rawlines[$offset++];
1841 next if (defined($line) && $line =~ /^-/);
1849 my ($linenr, $lc) = @_;
1851 my $stat_real = raw_line($linenr, 0);
1852 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1853 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1860 my ($linenr, $cnt, $here) = @_;
1862 my $herectx = $here . "\n";
1863 for (my $n = 0; $n < $cnt; $n++) {
1864 $herectx .= raw_line($linenr, $n) . "\n";
1875 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1878 $coded = sprintf("^%c", unpack('C', $2) + 64);
1887 my $av_preprocessor = 0;
1892 sub annotate_reset {
1893 $av_preprocessor = 0;
1895 @av_paren_type = ('E');
1896 $av_pend_colon = 'O';
1899 sub annotate_values {
1900 my ($stream, $type) = @_;
1903 my $var = '_' x length($stream);
1906 print "$stream\n" if ($dbg_values > 1);
1908 while (length($cur)) {
1909 @av_paren_type = ('E') if ($#av_paren_type < 0);
1910 print " <" . join('', @av_paren_type) .
1911 "> <$type> <$av_pending>" if ($dbg_values > 1);
1912 if ($cur =~ /^(\s+)/o) {
1913 print "WS($1)\n" if ($dbg_values > 1);
1914 if ($1 =~ /\n/ && $av_preprocessor) {
1915 $type = pop(@av_paren_type);
1916 $av_preprocessor = 0;
1919 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1920 print "CAST($1)\n" if ($dbg_values > 1);
1921 push(@av_paren_type, $type);
1924 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1925 print "DECLARE($1)\n" if ($dbg_values > 1);
1928 } elsif ($cur =~ /^($Modifier)\s*/) {
1929 print "MODIFIER($1)\n" if ($dbg_values > 1);
1932 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1933 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1934 $av_preprocessor = 1;
1935 push(@av_paren_type, $type);
1941 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1942 print "UNDEF($1)\n" if ($dbg_values > 1);
1943 $av_preprocessor = 1;
1944 push(@av_paren_type, $type);
1946 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1947 print "PRE_START($1)\n" if ($dbg_values > 1);
1948 $av_preprocessor = 1;
1950 push(@av_paren_type, $type);
1951 push(@av_paren_type, $type);
1954 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1955 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1956 $av_preprocessor = 1;
1958 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1962 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1963 print "PRE_END($1)\n" if ($dbg_values > 1);
1965 $av_preprocessor = 1;
1967 # Assume all arms of the conditional end as this
1968 # one does, and continue as if the #endif was not here.
1969 pop(@av_paren_type);
1970 push(@av_paren_type, $type);
1973 } elsif ($cur =~ /^(\\\n)/o) {
1974 print "PRECONT($1)\n" if ($dbg_values > 1);
1976 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1977 print "ATTR($1)\n" if ($dbg_values > 1);
1978 $av_pending = $type;
1981 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1982 print "SIZEOF($1)\n" if ($dbg_values > 1);
1988 } elsif ($cur =~ /^(if|while|for)\b/o) {
1989 print "COND($1)\n" if ($dbg_values > 1);
1993 } elsif ($cur =~/^(case)/o) {
1994 print "CASE($1)\n" if ($dbg_values > 1);
1995 $av_pend_colon = 'C';
1998 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1999 print "KEYWORD($1)\n" if ($dbg_values > 1);
2002 } elsif ($cur =~ /^(\()/o) {
2003 print "PAREN('$1')\n" if ($dbg_values > 1);
2004 push(@av_paren_type, $av_pending);
2008 } elsif ($cur =~ /^(\))/o) {
2009 my $new_type = pop(@av_paren_type);
2010 if ($new_type ne '_') {
2012 print "PAREN('$1') -> $type\n"
2013 if ($dbg_values > 1);
2015 print "PAREN('$1')\n" if ($dbg_values > 1);
2018 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2019 print "FUNC($1)\n" if ($dbg_values > 1);
2023 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2024 if (defined $2 && $type eq 'C' || $type eq 'T') {
2025 $av_pend_colon = 'B';
2026 } elsif ($type eq 'E') {
2027 $av_pend_colon = 'L';
2029 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2032 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2033 print "IDENT($1)\n" if ($dbg_values > 1);
2036 } elsif ($cur =~ /^($Assignment)/o) {
2037 print "ASSIGN($1)\n" if ($dbg_values > 1);
2040 } elsif ($cur =~/^(;|{|})/) {
2041 print "END($1)\n" if ($dbg_values > 1);
2043 $av_pend_colon = 'O';
2045 } elsif ($cur =~/^(,)/) {
2046 print "COMMA($1)\n" if ($dbg_values > 1);
2049 } elsif ($cur =~ /^(\?)/o) {
2050 print "QUESTION($1)\n" if ($dbg_values > 1);
2053 } elsif ($cur =~ /^(:)/o) {
2054 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2056 substr($var, length($res), 1, $av_pend_colon);
2057 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2062 $av_pend_colon = 'O';
2064 } elsif ($cur =~ /^(\[)/o) {
2065 print "CLOSE($1)\n" if ($dbg_values > 1);
2068 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2071 print "OPV($1)\n" if ($dbg_values > 1);
2078 substr($var, length($res), 1, $variant);
2081 } elsif ($cur =~ /^($Operators)/o) {
2082 print "OP($1)\n" if ($dbg_values > 1);
2083 if ($1 ne '++' && $1 ne '--') {
2087 } elsif ($cur =~ /(^.)/o) {
2088 print "C($1)\n" if ($dbg_values > 1);
2091 $cur = substr($cur, length($1));
2092 $res .= $type x length($1);
2096 return ($res, $var);
2100 my ($possible, $line) = @_;
2101 my $notPermitted = qr{(?:
2118 ^(?:typedef|struct|enum)\b
2120 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2121 if ($possible !~ $notPermitted) {
2122 # Check for modifiers.
2123 $possible =~ s/\s*$Storage\s*//g;
2124 $possible =~ s/\s*$Sparse\s*//g;
2125 if ($possible =~ /^\s*$/) {
2127 } elsif ($possible =~ /\s/) {
2128 $possible =~ s/\s*$Type\s*//g;
2129 for my $modifier (split(' ', $possible)) {
2130 if ($modifier !~ $notPermitted) {
2131 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2132 push(@modifierListFile, $modifier);
2137 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2138 push(@typeListFile, $possible);
2142 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2151 $type =~ tr/[a-z]/[A-Z]/;
2153 return defined $use_type{$type} if (scalar keys %use_type > 0);
2155 return !defined $ignore_type{$type};
2159 my ($level, $type, $msg) = @_;
2161 if (!show_type($type) ||
2162 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2167 if ($level eq 'ERROR') {
2169 } elsif ($level eq 'WARNING') {
2175 $output .= $prefix . $level . ':';
2177 $output .= BLUE if ($color);
2178 $output .= "$type:";
2180 $output .= RESET if ($color);
2181 $output .= ' ' . $msg . "\n";
2184 my @lines = split("\n", $output, -1);
2185 splice(@lines, 1, 1);
2186 $output = join("\n", @lines);
2188 $output = (split('\n', $output))[0] . "\n" if ($terse);
2190 push(our @report, $output);
2199 sub fixup_current_range {
2200 my ($lineRef, $offset, $length) = @_;
2202 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2205 my $no = $o + $offset;
2206 my $nl = $l + $length;
2207 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2211 sub fix_inserted_deleted_lines {
2212 my ($linesRef, $insertedRef, $deletedRef) = @_;
2214 my $range_last_linenr = 0;
2215 my $delta_offset = 0;
2220 my $next_insert = 0;
2221 my $next_delete = 0;
2225 my $inserted = @{$insertedRef}[$next_insert++];
2226 my $deleted = @{$deletedRef}[$next_delete++];
2228 foreach my $old_line (@{$linesRef}) {
2230 my $line = $old_line; #don't modify the array
2231 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2233 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2234 $range_last_linenr = $new_linenr;
2235 fixup_current_range(\$line, $delta_offset, 0);
2238 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2239 $deleted = @{$deletedRef}[$next_delete++];
2241 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2244 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2245 push(@lines, ${$inserted}{'LINE'});
2246 $inserted = @{$insertedRef}[$next_insert++];
2248 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2252 push(@lines, $line);
2262 sub fix_insert_line {
2263 my ($linenr, $line) = @_;
2269 push(@fixed_inserted, $inserted);
2272 sub fix_delete_line {
2273 my ($linenr, $line) = @_;
2280 push(@fixed_deleted, $deleted);
2284 my ($type, $msg) = @_;
2286 if (report("ERROR", $type, $msg)) {
2294 my ($type, $msg) = @_;
2296 if (report("WARNING", $type, $msg)) {
2304 my ($type, $msg) = @_;
2306 if ($check && report("CHECK", $type, $msg)) {
2314 sub check_absolute_file {
2315 my ($absolute, $herecurr) = @_;
2316 my $file = $absolute;
2318 ##print "absolute<$absolute>\n";
2320 # See if any suffix of this path is a path within the tree.
2321 while ($file =~ s@^[^/]*/@@) {
2322 if (-f "$root/$file") {
2323 ##print "file<$file>\n";
2331 # It is, so see if the prefix is acceptable.
2332 my $prefix = $absolute;
2333 substr($prefix, -length($file)) = '';
2335 ##print "prefix<$prefix>\n";
2336 if ($prefix ne ".../") {
2337 WARN("USE_RELATIVE_PATH",
2338 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2345 $string =~ s/^\s+|\s+$//g;
2353 $string =~ s/^\s+//;
2361 $string =~ s/\s+$//;
2366 sub string_find_replace {
2367 my ($string, $find, $replace) = @_;
2369 $string =~ s/$find/$replace/g;
2377 my $source_indent = $tabsize;
2378 my $max_spaces_before_tab = $source_indent - 1;
2379 my $spaces_to_tab = " " x $source_indent;
2381 #convert leading spaces to tabs
2382 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2383 #Remove spaces before a tab
2384 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2389 sub pos_last_openparen {
2394 my $opens = $line =~ tr/\(/\(/;
2395 my $closes = $line =~ tr/\)/\)/;
2397 my $last_openparen = 0;
2399 if (($opens == 0) || ($closes >= $opens)) {
2403 my $len = length($line);
2405 for ($pos = 0; $pos < $len; $pos++) {
2406 my $string = substr($line, $pos);
2407 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2408 $pos += length($1) - 1;
2409 } elsif (substr($line, $pos, 1) eq '(') {
2410 $last_openparen = $pos;
2411 } elsif (index($string, '(') == -1) {
2416 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2419 sub get_raw_comment {
2420 my ($line, $rawline) = @_;
2423 for my $i (0 .. (length($line) - 1)) {
2424 if (substr($line, $i, 1) eq "$;") {
2425 $comment .= substr($rawline, $i, 1);
2433 my $filename = shift;
2439 my $stashrawline="";
2449 my $authorsignoff = 0;
2450 my $author_sob = '';
2452 my $is_binding_patch = -1;
2453 my $in_header_lines = $file ? 0 : 1;
2454 my $in_commit_log = 0; #Scanning lines before patch
2455 my $has_patch_separator = 0; #Found a --- line
2456 my $has_commit_log = 0; #Encountered lines before patch
2457 my $commit_log_lines = 0; #Number of commit log lines
2458 my $commit_log_possible_stack_dump = 0;
2459 my $commit_log_long_line = 0;
2460 my $commit_log_has_diff = 0;
2461 my $reported_maintainer_file = 0;
2462 my $non_utf8_charset = 0;
2464 my $last_blank_line = 0;
2465 my $last_coalesced_string_linenr = -1;
2473 # Trace the real file/line as we go.
2478 my $context_function; #undef'd unless there's a known function
2480 my $comment_edge = 0;
2484 my $prev_values = 'E';
2487 my %suppress_ifbraces;
2488 my %suppress_whiletrailers;
2489 my %suppress_export;
2490 my $suppress_statement = 0;
2492 my %signatures = ();
2494 # Pre-scan the patch sanitizing the lines.
2495 # Pre-scan the patch looking for any __setup documentation.
2497 my @setup_docs = ();
2500 my $camelcase_file_seeded = 0;
2502 my $checklicenseline = 1;
2504 sanitise_line_reset();
2506 foreach my $rawline (@rawlines) {
2510 push(@fixed, $rawline) if ($fix);
2512 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2514 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2519 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2528 # Guestimate if this is a continuing comment. Run
2529 # the context looking for a comment "edge". If this
2530 # edge is a close comment then we must be in a comment
2534 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2535 next if (defined $rawlines[$ln - 1] &&
2536 $rawlines[$ln - 1] =~ /^-/);
2538 #print "RAW<$rawlines[$ln - 1]>\n";
2539 last if (!defined $rawlines[$ln - 1]);
2540 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2541 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2546 if (defined $edge && $edge eq '*/') {
2550 # Guestimate if this is a continuing comment. If this
2551 # is the start of a diff block and this line starts
2552 # ' *' then it is very likely a comment.
2553 if (!defined $edge &&
2554 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2559 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2560 sanitise_line_reset($in_comment);
2562 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2563 # Standardise the strings and chars within the input to
2564 # simplify matching -- only bother with positive lines.
2565 $line = sanitise_line($rawline);
2567 push(@lines, $line);
2570 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2575 #print "==>$rawline\n";
2576 #print "-->$line\n";
2578 if ($setup_docs && $line =~ /^\+/) {
2579 push(@setup_docs, $line);
2588 foreach my $line (@lines) {
2591 my $sline = $line; #copy of $line
2592 $sline =~ s/$;/ /g; #with comments as spaces
2594 my $rawline = $rawlines[$linenr - 1];
2595 my $raw_comment = get_raw_comment($line, $rawline);
2597 # check if it's a mode change, rename or start of a patch
2598 if (!$in_commit_log &&
2599 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2600 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2601 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2605 #extract the line range in the file after the patch is applied
2606 if (!$in_commit_log &&
2607 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2610 $first_line = $linenr + 1;
2620 %suppress_ifbraces = ();
2621 %suppress_whiletrailers = ();
2622 %suppress_export = ();
2623 $suppress_statement = 0;
2624 if ($context =~ /\b(\w+)\s*\(/) {
2625 $context_function = $1;
2627 undef $context_function;
2631 # track the line number as we move through the hunk, note that
2632 # new versions of GNU diff omit the leading space on completely
2633 # blank context lines so we need to count that too.
2634 } elsif ($line =~ /^( |\+|$)/) {
2636 $realcnt-- if ($realcnt != 0);
2638 # Measure the line length and indent.
2639 ($length, $indent) = line_stats($rawline);
2641 # Track the previous line.
2642 ($prevline, $stashline) = ($stashline, $line);
2643 ($previndent, $stashindent) = ($stashindent, $indent);
2644 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2646 #warn "line<$line>\n";
2648 } elsif ($realcnt == 1) {
2652 my $hunk_line = ($realcnt != 0);
2654 $here = "#$linenr: " if (!$file);
2655 $here = "#$realline: " if ($file);
2658 # extract the filename as it passes
2659 if ($line =~ /^diff --git.*?(\S+)$/) {
2661 $realfile =~ s@^([^/]*)/@@ if (!$file);
2664 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2666 $realfile =~ s@^([^/]*)/@@ if (!$file);
2670 if (!$file && $tree && $p1_prefix ne '' &&
2671 -e "$root/$p1_prefix") {
2672 WARN("PATCH_PREFIX",
2673 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2676 if ($realfile =~ m@^include/asm/@) {
2677 ERROR("MODIFIED_INCLUDE_ASM",
2678 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2683 #make up the handle for any error we report on this line
2685 $prefix = "$realfile:$realline: "
2688 $prefix = "$filename:$realline: ";
2690 $prefix = "$filename:$linenr: ";
2695 if (is_maintained_obsolete($realfile)) {
2697 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2699 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2702 $check = $check_orig;
2704 $checklicenseline = 1;
2706 if ($realfile !~ /^MAINTAINERS/) {
2707 my $last_binding_patch = $is_binding_patch;
2709 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2711 if (($last_binding_patch != -1) &&
2712 ($last_binding_patch ^ $is_binding_patch)) {
2713 WARN("DT_SPLIT_BINDING_PATCH",
2714 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2721 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2723 my $hereline = "$here\n$rawline\n";
2724 my $herecurr = "$here\n$rawline\n";
2725 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2727 $cnt_lines++ if ($realcnt != 0);
2729 # Verify the existence of a commit log if appropriate
2730 # 2 is used because a $signature is counted in $commit_log_lines
2731 if ($in_commit_log) {
2732 if ($line !~ /^\s*$/) {
2733 $commit_log_lines++; #could be a $signature
2735 } elsif ($has_commit_log && $commit_log_lines < 2) {
2736 WARN("COMMIT_MESSAGE",
2737 "Missing commit description - Add an appropriate one\n");
2738 $commit_log_lines = 2; #warn only once
2741 # Check if the commit log has what seems like a diff which can confuse patch
2742 if ($in_commit_log && !$commit_log_has_diff &&
2743 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2744 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2745 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2746 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2747 ERROR("DIFF_IN_COMMIT_MSG",
2748 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2749 $commit_log_has_diff = 1;
2752 # Check for incorrect file permissions
2753 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2754 my $permhere = $here . "FILE: $realfile\n";
2755 if ($realfile !~ m@scripts/@ &&
2756 $realfile !~ /\.(py|pl|awk|sh)$/) {
2757 ERROR("EXECUTE_PERMISSIONS",
2758 "do not set execute permissions for source files\n" . $permhere);
2762 # Check the patch for a From:
2763 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2765 my $curline = $linenr;
2766 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2769 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2771 $author = reformat_email($author);
2774 # Check the patch for a signoff:
2775 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2778 if ($author ne '' && $authorsignoff != 1) {
2779 if (same_email_addresses($1, $author)) {
2783 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2784 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2786 if ($email_address eq $author_address && $email_name eq $author_name) {
2789 } elsif ($email_address eq $author_address) {
2792 } elsif ($email_name eq $author_name) {
2796 my $address1 = $email_address;
2797 my $address2 = $author_address;
2799 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2802 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2805 if ($address1 eq $address2) {
2813 # Check for patch separator
2814 if ($line =~ /^---$/) {
2815 $has_patch_separator = 1;
2819 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2820 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2821 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2822 $reported_maintainer_file = 1;
2825 # Check signature styles
2826 if (!$in_header_lines &&
2827 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2828 my $space_before = $1;
2830 my $space_after = $3;
2832 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2834 if ($sign_off !~ /$signature_tags/) {
2835 my $suggested_signature = find_standard_signature($sign_off);
2836 if ($suggested_signature eq "") {
2837 WARN("BAD_SIGN_OFF",
2838 "Non-standard signature: $sign_off\n" . $herecurr);
2840 if (WARN("BAD_SIGN_OFF",
2841 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
2843 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
2847 if (defined $space_before && $space_before ne "") {
2848 if (WARN("BAD_SIGN_OFF",
2849 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2851 $fixed[$fixlinenr] =
2852 "$ucfirst_sign_off $email";
2855 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2856 if (WARN("BAD_SIGN_OFF",
2857 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2859 $fixed[$fixlinenr] =
2860 "$ucfirst_sign_off $email";
2864 if (!defined $space_after || $space_after ne " ") {
2865 if (WARN("BAD_SIGN_OFF",
2866 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2868 $fixed[$fixlinenr] =
2869 "$ucfirst_sign_off $email";
2873 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2874 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
2875 if ($suggested_email eq "") {
2876 ERROR("BAD_SIGN_OFF",
2877 "Unrecognized email address: '$email'\n" . $herecurr);
2879 my $dequoted = $suggested_email;
2880 $dequoted =~ s/^"//;
2881 $dequoted =~ s/" </ </;
2882 # Don't force email to have quotes
2883 # Allow just an angle bracketed address
2884 if (!same_email_addresses($email, $suggested_email)) {
2885 if (WARN("BAD_SIGN_OFF",
2886 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
2888 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
2892 # Address part shouldn't have comments
2893 my $stripped_address = $email_address;
2894 $stripped_address =~ s/\([^\(\)]*\)//g;
2895 if ($email_address ne $stripped_address) {
2896 if (WARN("BAD_SIGN_OFF",
2897 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
2899 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
2903 # Only one name comment should be allowed
2904 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
2905 if ($comment_count > 1) {
2906 WARN("BAD_SIGN_OFF",
2907 "Use a single name comment in email: '$email'\n" . $herecurr);
2911 # stable@vger.kernel.org or stable@kernel.org shouldn't
2912 # have an email name. In addition comments should strictly
2914 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
2915 if (($comment ne "" && $comment !~ /^#.+/) ||
2916 ($email_name ne "")) {
2917 my $cur_name = $email_name;
2918 my $new_comment = $comment;
2919 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
2921 # Remove brackets enclosing comment text
2922 # and # from start of comments to get comment text
2923 $new_comment =~ s/^\((.*)\)$/$1/;
2924 $new_comment =~ s/^\[(.*)\]$/$1/;
2925 $new_comment =~ s/^[\s\#]+|\s+$//g;
2927 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
2928 $new_comment = " # $new_comment" if ($new_comment ne "");
2929 my $new_email = "$email_address$new_comment";
2931 if (WARN("BAD_STABLE_ADDRESS_STYLE",
2932 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
2934 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2937 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
2938 my $new_comment = $comment;
2940 # Extract comment text from within brackets or
2941 # c89 style /*...*/ comments
2942 $new_comment =~ s/^\[(.*)\]$/$1/;
2943 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
2945 $new_comment = trim($new_comment);
2946 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
2947 $new_comment = "($new_comment)" if ($new_comment ne "");
2948 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
2950 if (WARN("BAD_SIGN_OFF",
2951 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
2953 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2958 # Check for duplicate signatures
2959 my $sig_nospace = $line;
2960 $sig_nospace =~ s/\s//g;
2961 $sig_nospace = lc($sig_nospace);
2962 if (defined $signatures{$sig_nospace}) {
2963 WARN("BAD_SIGN_OFF",
2964 "Duplicate signature\n" . $herecurr);
2966 $signatures{$sig_nospace} = 1;
2969 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2970 if ($sign_off =~ /^co-developed-by:$/i) {
2971 if ($email eq $author) {
2972 WARN("BAD_SIGN_OFF",
2973 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2975 if (!defined $lines[$linenr]) {
2976 WARN("BAD_SIGN_OFF",
2977 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2978 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2979 WARN("BAD_SIGN_OFF",
2980 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2981 } elsif ($1 ne $email) {
2982 WARN("BAD_SIGN_OFF",
2983 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2988 # Check email subject for common tools that don't need to be mentioned
2989 if ($in_header_lines &&
2990 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2991 WARN("EMAIL_SUBJECT",
2992 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2995 # Check for Gerrit Change-Ids not in any patch context
2996 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2997 if (ERROR("GERRIT_CHANGE_ID",
2998 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3000 fix_delete_line($fixlinenr, $rawline);
3004 # Check if the commit log is in a possible stack dump
3005 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3006 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3007 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3009 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3010 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3011 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3012 # stack dump address styles
3013 $commit_log_possible_stack_dump = 1;
3016 # Check for line lengths > 75 in commit log, warn once
3017 if ($in_commit_log && !$commit_log_long_line &&
3018 length($line) > 75 &&
3019 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3020 # file delta changes
3021 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
3023 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3024 # A Fixes: or Link: line or signature tag line
3025 $commit_log_possible_stack_dump)) {
3026 WARN("COMMIT_LOG_LONG_LINE",
3027 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3028 $commit_log_long_line = 1;
3031 # Reset possible stack dump if a blank line is found
3032 if ($in_commit_log && $commit_log_possible_stack_dump &&
3034 $commit_log_possible_stack_dump = 0;
3037 # Check for lines starting with a #
3038 if ($in_commit_log && $line =~ /^#/) {
3039 if (WARN("COMMIT_COMMENT_SYMBOL",
3040 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3042 $fixed[$fixlinenr] =~ s/^/ /;
3046 # Check for git id commit length and improperly formed commit descriptions
3047 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3048 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3049 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3050 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3051 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3052 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3053 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3054 my $init_char = "c";
3055 my $orig_commit = "";
3062 my $id = '0123456789ab';
3063 my $orig_desc = "commit description";
3064 my $description = "";
3066 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3068 $orig_commit = lc($2);
3069 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
3070 $orig_commit = lc($1);
3073 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3074 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
3075 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
3076 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3077 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
3080 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
3081 defined $rawlines[$linenr] &&
3082 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
3085 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
3086 defined $rawlines[$linenr] &&
3087 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
3088 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
3090 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
3091 $orig_desc .= " " . $1;
3095 ($id, $description) = git_commit_info($orig_commit,
3099 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
3100 ERROR("GIT_COMMIT_ID",
3101 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
3105 # Check for added, moved or deleted files
3106 if (!$reported_maintainer_file && !$in_commit_log &&
3107 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3108 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3109 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3110 (defined($1) || defined($2))))) {
3112 $reported_maintainer_file = 1;
3113 WARN("FILE_PATH_CHANGES",
3114 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3117 # Check for adding new DT bindings not in schema format
3118 if (!$in_commit_log &&
3119 ($line =~ /^new file mode\s*\d+\s*$/) &&
3120 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3121 WARN("DT_SCHEMA_BINDING_PATCH",
3122 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
3125 # Check for wrappage within a valid hunk of the file
3126 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3127 ERROR("CORRUPTED_PATCH",
3128 "patch seems to be corrupt (line wrapped?)\n" .
3129 $herecurr) if (!$emitted_corrupt++);
3132 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3133 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3134 $rawline !~ m/^$UTF8*$/) {
3135 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3137 my $blank = copy_spacing($rawline);
3138 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3139 my $hereptr = "$hereline$ptr\n";
3142 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3145 # Check if it's the start of a commit log
3146 # (not a header line and we haven't seen the patch filename)
3147 if ($in_header_lines && $realfile =~ /^$/ &&
3148 !($rawline =~ /^\s+(?:\S|$)/ ||
3149 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3150 $in_header_lines = 0;
3152 $has_commit_log = 1;
3155 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3156 # declined it, i.e defined some charset where it is missing.
3157 if ($in_header_lines &&
3158 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3160 $non_utf8_charset = 1;
3163 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3164 $rawline =~ /$NON_ASCII_UTF8/) {
3165 WARN("UTF8_BEFORE_PATCH",
3166 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3169 # Check for absolute kernel paths in commit message
3170 if ($tree && $in_commit_log) {
3171 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3174 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3175 check_absolute_file($1, $herecurr)) {
3178 check_absolute_file($file, $herecurr);
3183 # Check for various typo / spelling mistakes
3184 if (defined($misspellings) &&
3185 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3186 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3188 my $blank = copy_spacing($rawline);
3189 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3190 my $hereptr = "$hereline$ptr\n";
3191 my $typo_fix = $spelling_fix{lc($typo)};
3192 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3193 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3194 my $msg_level = \&WARN;
3195 $msg_level = \&CHK if ($file);
3196 if (&{$msg_level}("TYPO_SPELLING",
3197 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3199 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3204 # check for invalid commit id
3205 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3208 ($id, $description) = git_commit_info($2, undef, undef);
3209 if (!defined($id)) {
3210 WARN("UNKNOWN_COMMIT_ID",
3211 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3215 # check for repeated words separated by a single space
3216 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3217 if (($rawline =~ /^\+/ || $in_commit_log) &&
3218 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3219 pos($rawline) = 1 if (!$in_commit_log);
3220 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3224 my $start_pos = $-[1];
3225 my $end_pos = $+[2];
3226 if ($first =~ /(?:struct|union|enum)/) {
3227 pos($rawline) += length($first) + length($second) + 1;
3231 next if (lc($first) ne lc($second));
3232 next if ($first eq 'long');
3234 # check for character before and after the word matches
3235 my $start_char = '';
3237 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3238 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3240 next if ($start_char =~ /^\S$/);
3241 next if (index(" \t.,;?!", $end_char) == -1);
3243 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3244 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3245 next if (!exists($allow_repeated_words{lc($first)}));
3248 if (WARN("REPEATED_WORD",
3249 "Possible repeated word: '$first'\n" . $herecurr) &&
3251 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3255 # if it's a repeated word on consecutive lines in a comment block
3256 if ($prevline =~ /$;+\s*$/ &&
3257 $prevrawline =~ /($word_pattern)\s*$/) {
3259 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3260 if (WARN("REPEATED_WORD",
3261 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3263 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3269 # ignore non-hunk lines and lines being removed
3270 next if (!$hunk_line || $line =~ /^-/);
3272 #trailing whitespace
3273 if ($line =~ /^\+.*\015/) {
3274 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3275 if (ERROR("DOS_LINE_ENDINGS",
3276 "DOS line endings\n" . $herevet) &&
3278 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3280 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3281 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3282 if (ERROR("TRAILING_WHITESPACE",
3283 "trailing whitespace\n" . $herevet) &&
3285 $fixed[$fixlinenr] =~ s/\s+$//;
3291 # Check for FSF mailing addresses.
3292 if ($rawline =~ /\bwrite to the Free/i ||
3293 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3294 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3295 $rawline =~ /\b51\s+Franklin\s+St/i) {
3296 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3297 my $msg_level = \&ERROR;
3298 $msg_level = \&CHK if ($file);
3299 &{$msg_level}("FSF_MAILING_ADDRESS",
3300 "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)
3303 # check for Kconfig help text having a real description
3304 # Only applies when adding the entry originally, after that we do not have
3305 # sufficient context to determine whether it is indeed long enough.
3306 if ($realfile =~ /Kconfig/ &&
3307 # 'choice' is usually the last thing on the line (though
3308 # Kconfig supports named choices), so use a word boundary
3309 # (\b) rather than a whitespace character (\s)
3310 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3313 my $ln = $linenr + 1;
3317 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3318 $f = $lines[$ln - 1];
3319 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3320 $is_end = $lines[$ln - 1] =~ /^\+/;
3322 next if ($f =~ /^-/);
3323 last if (!$file && $f =~ /^\@\@/);
3325 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3327 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3334 next if ($f =~ /^$/);
3336 # This only checks context lines in the patch
3337 # and so hopefully shouldn't trigger false
3338 # positives, even though some of these are
3339 # common words in help texts
3340 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3341 if|endif|menu|endmenu|source)\b/x) {
3347 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3348 WARN("CONFIG_DESCRIPTION",
3349 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3351 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3354 # check MAINTAINERS entries
3355 if ($realfile =~ /^MAINTAINERS$/) {
3356 # check MAINTAINERS entries for the right form
3357 if ($rawline =~ /^\+[A-Z]:/ &&
3358 $rawline !~ /^\+[A-Z]:\t\S/) {
3359 if (WARN("MAINTAINERS_STYLE",
3360 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3362 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3365 # check MAINTAINERS entries for the right ordering too
3366 my $preferred_order = 'MRLSWQBCPTFXNK';
3367 if ($rawline =~ /^\+[A-Z]:/ &&
3368 $prevrawline =~ /^[\+ ][A-Z]:/) {
3369 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3372 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3375 my $curindex = index($preferred_order, $cur);
3376 my $previndex = index($preferred_order, $prev);
3377 if ($curindex < 0) {
3378 WARN("MAINTAINERS_STYLE",
3379 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3381 if ($previndex >= 0 && $curindex < $previndex) {
3382 WARN("MAINTAINERS_STYLE",
3383 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3384 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3385 ($prev eq 'X' && $cur eq 'X')) &&
3386 ($prevval cmp $curval) > 0) {
3387 WARN("MAINTAINERS_STYLE",
3388 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3394 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3395 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3398 'EXTRA_AFLAGS' => 'asflags-y',
3399 'EXTRA_CFLAGS' => 'ccflags-y',
3400 'EXTRA_CPPFLAGS' => 'cppflags-y',
3401 'EXTRA_LDFLAGS' => 'ldflags-y',
3404 WARN("DEPRECATED_VARIABLE",
3405 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3408 # check for DT compatible documentation
3409 if (defined $root &&
3410 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3411 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3413 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3415 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3416 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3418 foreach my $compat (@compats) {
3419 my $compat2 = $compat;
3420 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3421 my $compat3 = $compat;
3422 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3423 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3425 WARN("UNDOCUMENTED_DT_STRING",
3426 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3429 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3431 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3433 WARN("UNDOCUMENTED_DT_STRING",
3434 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3439 # check for using SPDX license tag at beginning of files
3440 if ($realline == $checklicenseline) {
3441 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3442 $checklicenseline = 2;
3443 } elsif ($rawline =~ /^\+/) {
3445 if ($realfile =~ /\.(h|s|S)$/) {
3447 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3449 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3451 } elsif ($realfile =~ /\.rst$/) {
3455 # check SPDX comment style for .[chsS] files
3456 if ($realfile =~ /\.[chsS]$/ &&
3457 $rawline =~ /SPDX-License-Identifier:/ &&
3458 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3459 WARN("SPDX_LICENSE_TAG",
3460 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3463 if ($comment !~ /^$/ &&
3464 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3465 WARN("SPDX_LICENSE_TAG",
3466 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3467 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3468 my $spdx_license = $1;
3469 if (!is_SPDX_License_valid($spdx_license)) {
3470 WARN("SPDX_LICENSE_TAG",
3471 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3473 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3474 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3475 my $msg_level = \&WARN;
3476 $msg_level = \&CHK if ($file);
3477 if (&{$msg_level}("SPDX_LICENSE_TAG",
3479 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3481 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3488 # check for embedded filenames
3489 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3490 WARN("EMBEDDED_FILENAME",
3491 "It's generally not useful to have the filename in the file\n" . $herecurr);
3494 # check we are in a valid source file if not then ignore this hunk
3495 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3497 # check for using SPDX-License-Identifier on the wrong line number
3498 if ($realline != $checklicenseline &&
3499 $rawline =~ /\bSPDX-License-Identifier:/ &&
3500 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3501 WARN("SPDX_LICENSE_TAG",
3502 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3505 # line length limit (with some exclusions)
3507 # There are a few types of lines that may extend beyond $max_line_length:
3508 # logging functions like pr_info that end in a string
3509 # lines with a single string
3510 # #defines that are a single string
3511 # lines with an RFC3986 like URL
3513 # There are 3 different line length message types:
3514 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3515 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3516 # LONG_LINE all other lines longer than $max_line_length
3518 # if LONG_LINE is ignored, the other 2 types are also ignored
3521 if ($line =~ /^\+/ && $length > $max_line_length) {
3522 my $msg_type = "LONG_LINE";
3524 # Check the allowed long line types first
3526 # logging functions that end in a string that starts
3527 # before $max_line_length
3528 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3529 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3532 # lines with only strings (w/ possible termination)
3533 # #defines with only strings
3534 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3535 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3538 # More special cases
3539 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3540 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3543 # URL ($rawline is used in case the URL is in a comment)
3544 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3547 # Otherwise set the alternate message types
3549 # a comment starts before $max_line_length
3550 } elsif ($line =~ /($;[\s$;]*)$/ &&
3551 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3552 $msg_type = "LONG_LINE_COMMENT"
3554 # a quoted string starts before $max_line_length
3555 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3556 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3557 $msg_type = "LONG_LINE_STRING"
3560 if ($msg_type ne "" &&
3561 (show_type("LONG_LINE") || show_type($msg_type))) {
3562 my $msg_level = \&WARN;
3563 $msg_level = \&CHK if ($file);
3564 &{$msg_level}($msg_type,
3565 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3569 # check for adding lines without a newline.
3570 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3571 if (WARN("MISSING_EOF_NEWLINE",
3572 "adding a line without newline at end of file\n" . $herecurr) &&
3574 fix_delete_line($fixlinenr+1, "No newline at end of file");
3578 # check we are in a valid source file C or perl if not then ignore this hunk
3579 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3581 # at the beginning of a line any tabs must come first and anything
3582 # more than $tabsize must use tabs.
3583 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3584 $rawline =~ /^\+\s* \s*/) {
3585 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3587 if (ERROR("CODE_INDENT",
3588 "code indent should use tabs where possible\n" . $herevet) &&
3590 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3594 # check for space before tabs.
3595 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3596 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3597 if (WARN("SPACE_BEFORE_TAB",
3598 "please, no space before tabs\n" . $herevet) &&
3600 while ($fixed[$fixlinenr] =~
3601 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3602 while ($fixed[$fixlinenr] =~
3603 s/(^\+.*) +\t/$1\t/) {}
3607 # check for assignments on the start of a line
3608 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3610 if (CHK("ASSIGNMENT_CONTINUATIONS",
3611 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3612 $fix && $prevrawline =~ /^\+/) {
3613 # add assignment operator to the previous line, remove from current line
3614 $fixed[$fixlinenr - 1] .= " $operator";
3615 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3619 # check for && or || at the start of a line
3620 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3622 if (CHK("LOGICAL_CONTINUATIONS",
3623 "Logical continuations should be on the previous line\n" . $hereprev) &&
3624 $fix && $prevrawline =~ /^\+/) {
3625 # insert logical operator at last non-comment, non-whitepsace char on previous line
3626 $prevline =~ /[\s$;]*$/;
3627 my $line_end = substr($prevrawline, $-[0]);
3628 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3629 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3633 # check indentation starts on a tab stop
3634 if ($perl_version_ok &&
3635 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3636 my $indent = length($1);
3637 if ($indent % $tabsize) {
3639 "Statements should start on a tabstop\n" . $herecurr) &&
3641 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3646 # check multi-line statement indentation matches previous line
3647 if ($perl_version_ok &&
3648 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3649 $prevline =~ /^\+(\t*)(.*)$/;
3653 my $pos = pos_last_openparen($rest);
3655 $line =~ /^(\+| )([ \t]*)/;
3658 my $goodtabindent = $oldindent .
3659 "\t" x ($pos / $tabsize) .
3660 " " x ($pos % $tabsize);
3661 my $goodspaceindent = $oldindent . " " x $pos;
3663 if ($newindent ne $goodtabindent &&
3664 $newindent ne $goodspaceindent) {
3666 if (CHK("PARENTHESIS_ALIGNMENT",
3667 "Alignment should match open parenthesis\n" . $hereprev) &&
3668 $fix && $line =~ /^\+/) {
3669 $fixed[$fixlinenr] =~
3670 s/^\+[ \t]*/\+$goodtabindent/;
3676 # check for space after cast like "(int) foo" or "(struct foo) bar"
3677 # avoid checking a few false positives:
3678 # "sizeof(<type>)" or "__alignof__(<type>)"
3679 # function pointer declarations like "(*foo)(int) = bar;"
3680 # structure definitions like "(struct foo) { 0 };"
3681 # multiline macros that define functions
3682 # known attributes or the __attribute__ keyword
3683 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3684 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3686 "No space is necessary after a cast\n" . $herecurr) &&
3688 $fixed[$fixlinenr] =~
3689 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3693 # Block comment styles
3694 # Networking with an initial /*
3695 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3696 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3697 $rawline =~ /^\+[ \t]*\*/ &&
3698 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3699 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3700 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3703 # Block comments use * on subsequent lines
3704 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3705 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3706 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3707 $rawline =~ /^\+/ && #line is new
3708 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3709 WARN("BLOCK_COMMENT_STYLE",
3710 "Block comments use * on subsequent lines\n" . $hereprev);
3713 # Block comments use */ on trailing lines
3714 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3715 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3716 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3717 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3718 WARN("BLOCK_COMMENT_STYLE",
3719 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3722 # Block comment * alignment
3723 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3724 $line =~ /^\+[ \t]*$;/ && #leading comment
3725 $rawline =~ /^\+[ \t]*\*/ && #leading *
3726 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3727 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3728 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3730 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3732 $oldindent = expand_tabs($1);
3734 $prevrawline =~ m@^\+(.*/?)\*@;
3735 $oldindent = expand_tabs($1);
3737 $rawline =~ m@^\+([ \t]*)\*@;
3739 $newindent = expand_tabs($newindent);
3740 if (length($oldindent) ne length($newindent)) {
3741 WARN("BLOCK_COMMENT_STYLE",
3742 "Block comments should align the * on each line\n" . $hereprev);
3746 # check for missing blank lines after struct/union declarations
3747 # with exceptions for various attributes and macros
3748 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3750 !($line =~ /^\+\s*$/ ||
3751 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3752 $line =~ /^\+\s*MODULE_/i ||
3753 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3754 $line =~ /^\+[a-z_]*init/ ||
3755 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3756 $line =~ /^\+\s*DECLARE/ ||
3757 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3758 $line =~ /^\+\s*__setup/)) {
3759 if (CHK("LINE_SPACING",
3760 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3762 fix_insert_line($fixlinenr, "\+");
3766 # check for multiple consecutive blank lines
3767 if ($prevline =~ /^[\+ ]\s*$/ &&
3768 $line =~ /^\+\s*$/ &&
3769 $last_blank_line != ($linenr - 1)) {
3770 if (CHK("LINE_SPACING",
3771 "Please don't use multiple blank lines\n" . $hereprev) &&
3773 fix_delete_line($fixlinenr, $rawline);
3776 $last_blank_line = $linenr;
3779 # check for missing blank lines after declarations
3780 # (declarations must have the same indentation and not be at the start of line)
3781 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3785 # remove $Attribute/$Sparse uses to simplify comparisons
3786 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3787 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3788 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3789 # function pointer declarations
3790 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3791 # foo bar; where foo is some local typedef or #define
3792 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3793 # known declaration macros
3794 $pl =~ /^\+\s+$declaration_macros/) &&
3795 # for "else if" which can look like "$Ident $Ident"
3796 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3797 # other possible extensions of declaration lines
3798 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3799 # not starting a section or a macro "\" extended line
3800 $pl =~ /(?:\{\s*|\\)$/) &&
3801 # looks like a declaration
3802 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3803 # function pointer declarations
3804 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3805 # foo bar; where foo is some local typedef or #define
3806 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3807 # known declaration macros
3808 $sl =~ /^\+\s+$declaration_macros/ ||
3809 # start of struct or union or enum
3810 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3811 # start or end of block or continuation of declaration
3812 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3813 # bitfield continuation
3814 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3815 # other possible extensions of declaration lines
3816 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3817 if (WARN("LINE_SPACING",
3818 "Missing a blank line after declarations\n" . $hereprev) &&
3820 fix_insert_line($fixlinenr, "\+");
3825 # check for spaces at the beginning of a line.
3827 # 1) within comments
3828 # 2) indented preprocessor commands
3830 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3831 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3832 if (WARN("LEADING_SPACE",
3833 "please, no spaces at the start of a line\n" . $herevet) &&
3835 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3839 # check we are in a valid C source file if not then ignore this hunk
3840 next if ($realfile !~ /\.(h|c)$/);
3842 # check for unusual line ending [ or (
3843 if ($line =~ /^\+.*([\[\(])\s*$/) {
3844 CHK("OPEN_ENDED_LINE",
3845 "Lines should not end with a '$1'\n" . $herecurr);
3848 # check if this appears to be the start function declaration, save the name
3849 if ($sline =~ /^\+\{\s*$/ &&
3850 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3851 $context_function = $1;
3854 # check if this appears to be the end of function declaration
3855 if ($sline =~ /^\+\}\s*$/) {
3856 undef $context_function;
3859 # check indentation of any line with a bare else
3860 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3861 # if the previous line is a break or return and is indented 1 tab more...
3862 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3863 my $tabs = length($1) + 1;
3864 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3865 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3866 defined $lines[$linenr] &&
3867 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3868 WARN("UNNECESSARY_ELSE",
3869 "else is not generally useful after a break or return\n" . $hereprev);
3873 # check indentation of a line with a break;
3874 # if the previous line is a goto, return or break
3875 # and is indented the same # of tabs
3876 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3878 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3879 if (WARN("UNNECESSARY_BREAK",
3880 "break is not useful after a $1\n" . $hereprev) &&
3882 fix_delete_line($fixlinenr, $rawline);
3887 # check for RCS/CVS revision markers
3888 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3890 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3893 # check for old HOTPLUG __dev<foo> section markings
3894 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3895 WARN("HOTPLUG_SECTION",
3896 "Using $1 is unnecessary\n" . $herecurr);
3899 # Check for potential 'bare' types
3900 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3902 #print "LINE<$line>\n";
3903 if ($linenr > $suppress_statement &&
3904 $realcnt && $sline =~ /.\s*\S/) {
3905 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3906 ctx_statement_block($linenr, $realcnt, 0);
3907 $stat =~ s/\n./\n /g;
3908 $cond =~ s/\n./\n /g;
3910 #print "linenr<$linenr> <$stat>\n";
3911 # If this statement has no statement boundaries within
3912 # it there is no point in retrying a statement scan
3913 # until we hit end of it.
3914 my $frag = $stat; $frag =~ s/;+\s*$//;
3915 if ($frag !~ /(?:{|;)/) {
3916 #print "skip<$line_nr_next>\n";
3917 $suppress_statement = $line_nr_next;
3920 # Find the real next line.
3921 $realline_next = $line_nr_next;
3922 if (defined $realline_next &&
3923 (!defined $lines[$realline_next - 1] ||
3924 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3931 # Ignore goto labels.
3932 if ($s =~ /$Ident:\*$/s) {
3934 # Ignore functions being called
3935 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3937 } elsif ($s =~ /^.\s*else\b/s) {
3939 # declarations always start with types
3940 } 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) {
3943 possible($type, "A:" . $s);
3945 # definitions in global scope can only start with types
3946 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3947 possible($1, "B:" . $s);
3950 # any (foo ... *) is a pointer cast, and foo is a type
3951 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3952 possible($1, "C:" . $s);
3955 # Check for any sort of function declaration.
3956 # int foo(something bar, other baz);
3957 # void (*store_gdt)(x86_descr_ptr *);
3958 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3959 my ($name_len) = length($1);
3962 substr($ctx, 0, $name_len + 1, '');
3963 $ctx =~ s/\)[^\)]*$//;
3965 for my $arg (split(/\s*,\s*/, $ctx)) {
3966 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3968 possible($1, "D:" . $s);
3976 # Checks which may be anchored in the context.
3979 # Check for switch () and associated case and default
3980 # statements should be at the same indent.
3981 if ($line=~/\bswitch\s*\(.*\)/) {
3984 my @ctx = ctx_block_outer($linenr, $realcnt);
3986 for my $ctx (@ctx) {
3987 my ($clen, $cindent) = line_stats($ctx);
3988 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3989 $indent != $cindent) {
3990 $err .= "$sep$ctx\n";
3997 ERROR("SWITCH_CASE_INDENT_LEVEL",
3998 "switch and case should be at the same indent\n$hereline$err");
4002 # if/while/etc brace do not go on next line, unless defining a do while loop,
4003 # or if that brace on the next line is for something else
4004 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4005 my $pre_ctx = "$1$2";
4007 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4009 if ($line =~ /^\+\t{6,}/) {
4010 WARN("DEEP_INDENTATION",
4011 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4014 my $ctx_cnt = $realcnt - $#ctx - 1;
4015 my $ctx = join("\n", @ctx);
4017 my $ctx_ln = $linenr;
4018 my $ctx_skip = $realcnt;
4020 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4021 defined $lines[$ctx_ln - 1] &&
4022 $lines[$ctx_ln - 1] =~ /^-/)) {
4023 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4024 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4028 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4029 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4031 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4033 "that open brace { should be on the previous line\n" .
4034 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4036 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4037 $ctx =~ /\)\s*\;\s*$/ &&
4038 defined $lines[$ctx_ln - 1])
4040 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4041 if ($nindent > $indent) {
4042 WARN("TRAILING_SEMICOLON",
4043 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4044 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4049 # Check relative indent for conditionals and blocks.
4050 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4051 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4052 ctx_statement_block($linenr, $realcnt, 0)
4053 if (!defined $stat);
4054 my ($s, $c) = ($stat, $cond);
4056 substr($s, 0, length($c), '');
4058 # remove inline comments
4062 # Find out how long the conditional actually is.
4063 my @newlines = ($c =~ /\n/gs);
4064 my $cond_lines = 1 + $#newlines;
4066 # Make sure we remove the line prefixes as we have
4067 # none on the first line, and are going to readd them
4070 while ($s =~ /\n\s+\\\n/) {
4071 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4074 # We want to check the first line inside the block
4075 # starting at the end of the conditional, so remove:
4076 # 1) any blank line termination
4077 # 2) any opening brace { on end of the line
4079 my $continuation = 0;
4081 $s =~ s/^.*\bdo\b//;
4083 if ($s =~ s/^\s*\\//) {
4086 if ($s =~ s/^\s*?\n//) {
4091 # Also ignore a loop construct at the end of a
4092 # preprocessor statement.
4093 if (($prevline =~ /^.\s*#\s*define\s/ ||
4094 $prevline =~ /\\\s*$/) && $continuation == 0) {
4100 while ($cond_ptr != $cond_lines) {
4101 $cond_ptr = $cond_lines;
4103 # If we see an #else/#elif then the code
4105 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4110 # 1) blank lines, they should be at 0,
4111 # 2) preprocessor lines, and
4113 if ($continuation ||
4115 $s =~ /^\s*#\s*?/ ||
4116 $s =~ /^\s*$Ident\s*:/) {
4117 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4118 if ($s =~ s/^.*?\n//) {
4124 my (undef, $sindent) = line_stats("+" . $s);
4125 my $stat_real = raw_line($linenr, $cond_lines);
4127 # Check if either of these lines are modified, else
4128 # this is not this patch's fault.
4129 if (!defined($stat_real) ||
4130 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4133 if (defined($stat_real) && $cond_lines > 1) {
4134 $stat_real = "[...]\n$stat_real";
4137 #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";
4139 if ($check && $s ne '' &&
4140 (($sindent % $tabsize) != 0 ||
4141 ($sindent < $indent) ||
4142 ($sindent == $indent &&
4143 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4144 ($sindent > $indent + $tabsize))) {
4145 WARN("SUSPECT_CODE_INDENT",
4146 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4150 # Track the 'values' across context and added lines.
4151 my $opline = $line; $opline =~ s/^./ /;
4152 my ($curr_values, $curr_vars) =
4153 annotate_values($opline . "\n", $prev_values);
4154 $curr_values = $prev_values . $curr_values;
4156 my $outline = $opline; $outline =~ s/\t/ /g;
4157 print "$linenr > .$outline\n";
4158 print "$linenr > $curr_values\n";
4159 print "$linenr > $curr_vars\n";
4161 $prev_values = substr($curr_values, -1);
4163 #ignore lines not being added
4164 next if ($line =~ /^[^\+]/);
4166 # check for self assignments used to avoid compiler warnings
4167 # e.g.: int foo = foo, *bar = NULL;
4168 # struct foo bar = *(&(bar));
4169 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4171 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4172 WARN("SELF_ASSIGNMENT",
4173 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4177 # check for dereferences that span multiple lines
4178 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4179 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4180 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4182 $line =~ /^.\s*($Lval)/;
4185 WARN("MULTILINE_DEREFERENCE",
4186 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4189 # check for declarations of signed or unsigned without int
4190 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4193 $var = "" if (!defined $var);
4194 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4198 $pointer = "" if (!defined $pointer);
4200 if (WARN("UNSPECIFIED_INT",
4201 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4203 my $decl = trim($sign) . " int ";
4204 my $comp_pointer = $pointer;
4205 $comp_pointer =~ s/\s//g;
4206 $decl .= $comp_pointer;
4207 $decl = rtrim($decl) if ($var eq "");
4208 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4213 # TEST: allow direct testing of the type matcher.
4215 if ($line =~ /^.\s*$Declare\s*$/) {
4217 "TEST: is type\n" . $herecurr);
4218 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4219 ERROR("TEST_NOT_TYPE",
4220 "TEST: is not type ($1 is)\n". $herecurr);
4224 # TEST: allow direct testing of the attribute matcher.
4226 if ($line =~ /^.\s*$Modifier\s*$/) {
4228 "TEST: is attr\n" . $herecurr);
4229 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4230 ERROR("TEST_NOT_ATTR",
4231 "TEST: is not attr ($1 is)\n". $herecurr);
4236 # check for initialisation to aggregates open brace on the next line
4237 if ($line =~ /^.\s*{/ &&
4238 $prevline =~ /(?:^|[^=])=\s*$/) {
4239 if (ERROR("OPEN_BRACE",
4240 "that open brace { should be on the previous line\n" . $hereprev) &&
4241 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4242 fix_delete_line($fixlinenr - 1, $prevrawline);
4243 fix_delete_line($fixlinenr, $rawline);
4244 my $fixedline = $prevrawline;
4245 $fixedline =~ s/\s*=\s*$/ = {/;
4246 fix_insert_line($fixlinenr, $fixedline);
4248 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4249 fix_insert_line($fixlinenr, $fixedline);
4254 # Checks which are anchored on the added line.
4257 # check for malformed paths in #include statements (uses RAW line)
4258 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4260 if ($path =~ m{//}) {
4261 ERROR("MALFORMED_INCLUDE",
4262 "malformed #include filename\n" . $herecurr);
4264 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4265 ERROR("UAPI_INCLUDE",
4266 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4270 # no C99 // comments
4271 if ($line =~ m{//}) {
4272 if (ERROR("C99_COMMENTS",
4273 "do not use C99 // comments\n" . $herecurr) &&
4275 my $line = $fixed[$fixlinenr];
4276 if ($line =~ /\/\/(.*)$/) {
4277 my $comment = trim($1);
4278 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4282 # Remove C99 comments.
4284 $opline =~ s@//.*@@;
4286 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4287 # the whole statement.
4288 #print "APW <$lines[$realline_next - 1]>\n";
4289 if (defined $realline_next &&
4290 exists $lines[$realline_next - 1] &&
4291 !defined $suppress_export{$realline_next} &&
4292 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4293 # Handle definitions which produce identifiers with
4296 # EXPORT_SYMBOL(something_foo);
4298 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4299 $name =~ /^${Ident}_$2/) {
4300 #print "FOO C name<$name>\n";
4301 $suppress_export{$realline_next} = 1;
4303 } elsif ($stat !~ /(?:
4305 ^.DEFINE_$Ident\(\Q$name\E\)|
4306 ^.DECLARE_$Ident\(\Q$name\E\)|
4307 ^.LIST_HEAD\(\Q$name\E\)|
4308 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4309 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4311 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4312 $suppress_export{$realline_next} = 2;
4314 $suppress_export{$realline_next} = 1;
4317 if (!defined $suppress_export{$linenr} &&
4318 $prevline =~ /^.\s*$/ &&
4319 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4320 #print "FOO B <$lines[$linenr - 1]>\n";
4321 $suppress_export{$linenr} = 2;
4323 if (defined $suppress_export{$linenr} &&
4324 $suppress_export{$linenr} == 2) {
4325 WARN("EXPORT_SYMBOL",
4326 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4329 # check for global initialisers.
4330 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4331 if (ERROR("GLOBAL_INITIALISERS",
4332 "do not initialise globals to $1\n" . $herecurr) &&
4334 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4337 # check for static initialisers.
4338 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4339 if (ERROR("INITIALISED_STATIC",
4340 "do not initialise statics to $1\n" .
4343 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4347 # check for misordered declarations of char/short/int/long with signed/unsigned
4348 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4350 WARN("MISORDERED_TYPE",
4351 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4354 # check for unnecessary <signed> int declarations of short/long/long long
4355 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4356 my $type = trim($1);
4357 next if ($type !~ /\bint\b/);
4358 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4359 my $new_type = $type;
4360 $new_type =~ s/\b\s*int\s*\b/ /;
4361 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4362 $new_type =~ s/^const\s+//;
4363 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4364 $new_type = "const $new_type" if ($type =~ /^const\b/);
4365 $new_type =~ s/\s+/ /g;
4366 $new_type = trim($new_type);
4367 if (WARN("UNNECESSARY_INT",
4368 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4370 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4374 # check for static const char * arrays.
4375 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4376 WARN("STATIC_CONST_CHAR_ARRAY",
4377 "static const char * array should probably be static const char * const\n" .
4381 # check for initialized const char arrays that should be static const
4382 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4383 if (WARN("STATIC_CONST_CHAR_ARRAY",
4384 "const array should probably be static const\n" . $herecurr) &&
4386 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4390 # check for static char foo[] = "bar" declarations.
4391 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4392 WARN("STATIC_CONST_CHAR_ARRAY",
4393 "static char array declaration should probably be static const char\n" .
4397 # check for const <foo> const where <foo> is not a pointer or array type
4398 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4400 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4402 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4403 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4405 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4409 # check for const static or static <non ptr type> const declarations
4410 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4411 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4412 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4413 if (WARN("STATIC_CONST",
4414 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4416 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4417 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4421 # check for non-global char *foo[] = {"bar", ...} declarations.
4422 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4423 WARN("STATIC_CONST_CHAR_ARRAY",
4424 "char * array declaration might be better as static const\n" .
4428 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4429 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4431 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4433 if (WARN("ARRAY_SIZE",
4434 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4436 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4441 # check for function declarations without arguments like "int foo()"
4442 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4443 if (ERROR("FUNCTION_WITHOUT_ARGS",
4444 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4446 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4450 # check for new typedefs, only function parameters and sparse annotations
4452 if ($line =~ /\btypedef\s/ &&
4453 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4454 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4455 $line !~ /\b$typeTypedefs\b/ &&
4456 $line !~ /\b__bitwise\b/) {
4457 WARN("NEW_TYPEDEFS",
4458 "do not add new typedefs\n" . $herecurr);
4461 # * goes on variable not on type
4463 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4465 my ($ident, $from, $to) = ($1, $2, $2);
4467 # Should start with a space.
4468 $to =~ s/^(\S)/ $1/;
4469 # Should not end with a space.
4471 # '*'s should not have spaces between.
4472 while ($to =~ s/\*\s+\*/\*\*/) {
4475 ## print "1: from<$from> to<$to> ident<$ident>\n";
4477 if (ERROR("POINTER_LOCATION",
4478 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4480 my $sub_from = $ident;
4481 my $sub_to = $ident;
4482 $sub_to =~ s/\Q$from\E/$to/;
4483 $fixed[$fixlinenr] =~
4484 s@\Q$sub_from\E@$sub_to@;
4488 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4490 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4492 # Should start with a space.
4493 $to =~ s/^(\S)/ $1/;
4494 # Should not end with a space.
4496 # '*'s should not have spaces between.
4497 while ($to =~ s/\*\s+\*/\*\*/) {
4499 # Modifiers should have spaces.
4500 $to =~ s/(\b$Modifier$)/$1 /;
4502 ## print "2: from<$from> to<$to> ident<$ident>\n";
4503 if ($from ne $to && $ident !~ /^$Modifier$/) {
4504 if (ERROR("POINTER_LOCATION",
4505 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4508 my $sub_from = $match;
4509 my $sub_to = $match;
4510 $sub_to =~ s/\Q$from\E/$to/;
4511 $fixed[$fixlinenr] =~
4512 s@\Q$sub_from\E@$sub_to@;
4517 # avoid BUG() or BUG_ON()
4518 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4519 my $msg_level = \&WARN;
4520 $msg_level = \&CHK if ($file);
4521 &{$msg_level}("AVOID_BUG",
4522 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4525 # avoid LINUX_VERSION_CODE
4526 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4527 WARN("LINUX_VERSION_CODE",
4528 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4531 # check for uses of printk_ratelimit
4532 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4533 WARN("PRINTK_RATELIMITED",
4534 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4537 # printk should use KERN_* levels
4538 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4539 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4540 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4543 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4544 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4548 $modifier = "" if (!defined($modifier));
4549 my $level = lc($orig);
4550 $level = "warn" if ($level eq "warning");
4551 my $level2 = $level;
4552 $level2 = "dbg" if ($level eq "debug");
4553 $level .= $modifier;
4554 $level2 .= $modifier;
4555 WARN("PREFER_PR_LEVEL",
4556 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4559 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4560 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4562 my $level = lc($orig);
4563 $level = "warn" if ($level eq "warning");
4564 $level = "dbg" if ($level eq "debug");
4565 WARN("PREFER_DEV_LEVEL",
4566 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4569 # trace_printk should not be used in production code.
4570 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4571 WARN("TRACE_PRINTK",
4572 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4575 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4576 # number of false positives, but assembly files are not checked, so at
4577 # least the arch entry code will not trigger this warning.
4578 if ($line =~ /\bENOSYS\b/) {
4580 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4583 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4584 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4585 # Similarly to ENOSYS warning a small number of false positives is expected.
4586 if (!$file && $line =~ /\bENOTSUPP\b/) {
4587 if (WARN("ENOTSUPP",
4588 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4590 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4594 # function brace can't be on same line, except for #defines of do while,
4595 # or if closed on same line
4596 if ($perl_version_ok &&
4597 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4598 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4600 if (ERROR("OPEN_BRACE",
4601 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4603 fix_delete_line($fixlinenr, $rawline);
4604 my $fixed_line = $rawline;
4605 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4608 fix_insert_line($fixlinenr, ltrim($line1));
4609 fix_insert_line($fixlinenr, "\+{");
4610 if ($line2 !~ /^\s*$/) {
4611 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4616 # open braces for enum, union and struct go on the same line.
4617 if ($line =~ /^.\s*{/ &&
4618 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4619 if (ERROR("OPEN_BRACE",
4620 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4621 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4622 fix_delete_line($fixlinenr - 1, $prevrawline);
4623 fix_delete_line($fixlinenr, $rawline);
4624 my $fixedline = rtrim($prevrawline) . " {";
4625 fix_insert_line($fixlinenr, $fixedline);
4626 $fixedline = $rawline;
4627 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4628 if ($fixedline !~ /^\+\s*$/) {
4629 fix_insert_line($fixlinenr, $fixedline);
4634 # missing space after union, struct or enum definition
4635 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4637 "missing space after $1 definition\n" . $herecurr) &&
4639 $fixed[$fixlinenr] =~
4640 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4644 # Function pointer declarations
4645 # check spacing between type, funcptr, and args
4646 # canonical declaration is "type (*funcptr)(args...)"
4647 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4649 my $pre_pointer_space = $2;
4650 my $post_pointer_space = $3;
4652 my $post_funcname_space = $5;
4653 my $pre_args_space = $6;
4655 # the $Declare variable will capture all spaces after the type
4656 # so check it for a missing trailing missing space but pointer return types
4657 # don't need a space so don't warn for those.
4658 my $post_declare_space = "";
4659 if ($declare =~ /(\s+)$/) {
4660 $post_declare_space = $1;
4661 $declare = rtrim($declare);
4663 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4665 "missing space after return type\n" . $herecurr);
4666 $post_declare_space = " ";
4669 # unnecessary space "type (*funcptr)(args...)"
4670 # This test is not currently implemented because these declarations are
4672 # int foo(int bar, ...)
4673 # and this is form shouldn't/doesn't generate a checkpatch warning.
4675 # elsif ($declare =~ /\s{2,}$/) {
4677 # "Multiple spaces after return type\n" . $herecurr);
4680 # unnecessary space "type ( *funcptr)(args...)"
4681 if (defined $pre_pointer_space &&
4682 $pre_pointer_space =~ /^\s/) {
4684 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4687 # unnecessary space "type (* funcptr)(args...)"
4688 if (defined $post_pointer_space &&
4689 $post_pointer_space =~ /^\s/) {
4691 "Unnecessary space before function pointer name\n" . $herecurr);
4694 # unnecessary space "type (*funcptr )(args...)"
4695 if (defined $post_funcname_space &&
4696 $post_funcname_space =~ /^\s/) {
4698 "Unnecessary space after function pointer name\n" . $herecurr);
4701 # unnecessary space "type (*funcptr) (args...)"
4702 if (defined $pre_args_space &&
4703 $pre_args_space =~ /^\s/) {
4705 "Unnecessary space before function pointer arguments\n" . $herecurr);
4708 if (show_type("SPACING") && $fix) {
4709 $fixed[$fixlinenr] =~
4710 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4714 # check for spacing round square brackets; allowed:
4715 # 1. with a type on the left -- int [] a;
4716 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4717 # 3. inside a curly brace -- = { [0...10] = 5 }
4718 while ($line =~ /(.*?\s)\[/g) {
4719 my ($where, $prefix) = ($-[1], $1);
4720 if ($prefix !~ /$Type\s+$/ &&
4721 ($where != 0 || $prefix !~ /^.\s+$/) &&
4722 $prefix !~ /[{,:]\s+$/) {
4723 if (ERROR("BRACKET_SPACE",
4724 "space prohibited before open square bracket '['\n" . $herecurr) &&
4726 $fixed[$fixlinenr] =~
4727 s/^(\+.*?)\s+\[/$1\[/;
4732 # check for spaces between functions and their parentheses.
4733 while ($line =~ /($Ident)\s+\(/g) {
4735 my $ctx_before = substr($line, 0, $-[1]);
4736 my $ctx = "$ctx_before$name";
4738 # Ignore those directives where spaces _are_ permitted.
4740 if|for|while|switch|return|case|
4741 volatile|__volatile__|
4742 __attribute__|format|__extension__|
4745 # cpp #define statements have non-optional spaces, ie
4746 # if there is a space between the name and the open
4747 # parenthesis it is simply not a parameter group.
4748 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4750 # cpp #elif statement condition may start with a (
4751 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4753 # If this whole things ends with a type its most
4754 # likely a typedef for a function.
4755 } elsif ($ctx =~ /$Type$/) {
4759 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4761 $fixed[$fixlinenr] =~
4762 s/\b$name\s+\(/$name\(/;
4767 # Check operator spacing.
4768 if (!($line=~/\#\s*include/)) {
4769 my $fixed_line = "";
4773 <<=|>>=|<=|>=|==|!=|
4774 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4775 =>|->|<<|>>|<|>|=|!|~|
4776 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4779 my @elements = split(/($ops|;)/, $opline);
4781 ## print("element count: <" . $#elements . ">\n");
4782 ## foreach my $el (@elements) {
4783 ## print("el: <$el>\n");
4786 my @fix_elements = ();
4789 foreach my $el (@elements) {
4790 push(@fix_elements, substr($rawline, $off, length($el)));
4791 $off += length($el);
4796 my $blank = copy_spacing($opline);
4797 my $last_after = -1;
4799 for (my $n = 0; $n < $#elements; $n += 2) {
4801 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4803 ## print("n: <$n> good: <$good>\n");
4805 $off += length($elements[$n]);
4807 # Pick up the preceding and succeeding characters.
4808 my $ca = substr($opline, 0, $off);
4810 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4811 $cc = substr($opline, $off + length($elements[$n + 1]));
4813 my $cb = "$ca$;$cc";
4816 $a = 'V' if ($elements[$n] ne '');
4817 $a = 'W' if ($elements[$n] =~ /\s$/);
4818 $a = 'C' if ($elements[$n] =~ /$;$/);
4819 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4820 $a = 'O' if ($elements[$n] eq '');
4821 $a = 'E' if ($ca =~ /^\s*$/);
4823 my $op = $elements[$n + 1];
4826 if (defined $elements[$n + 2]) {
4827 $c = 'V' if ($elements[$n + 2] ne '');
4828 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4829 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4830 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4831 $c = 'O' if ($elements[$n + 2] eq '');
4832 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4837 my $ctx = "${a}x${c}";
4839 my $at = "(ctx:$ctx)";
4841 my $ptr = substr($blank, 0, $off) . "^";
4842 my $hereptr = "$hereline$ptr\n";
4844 # Pull out the value of this operator.
4845 my $op_type = substr($curr_values, $off + 1, 1);
4847 # Get the full operator variant.
4848 my $opv = $op . substr($curr_vars, $off, 1);
4850 # Ignore operators passed as parameters.
4851 if ($op_type ne 'V' &&
4852 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4855 # } elsif ($op =~ /^$;+$/) {
4857 # ; should have either the end of line or a space or \ after it
4858 } elsif ($op eq ';') {
4859 if ($ctx !~ /.x[WEBC]/ &&
4860 $cc !~ /^\\/ && $cc !~ /^;/) {
4861 if (ERROR("SPACING",
4862 "space required after that '$op' $at\n" . $hereptr)) {
4863 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4869 } elsif ($op eq '//') {
4871 # : when part of a bitfield
4872 } elsif ($opv eq ':B') {
4873 # skip the bitfield test for now
4877 } elsif ($op eq '->') {
4878 if ($ctx =~ /Wx.|.xW/) {
4879 if (ERROR("SPACING",
4880 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4881 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4882 if (defined $fix_elements[$n + 2]) {
4883 $fix_elements[$n + 2] =~ s/^\s+//;
4889 # , must not have a space before and must have a space on the right.
4890 } elsif ($op eq ',') {
4891 my $rtrim_before = 0;
4892 my $space_after = 0;
4893 if ($ctx =~ /Wx./) {
4894 if (ERROR("SPACING",
4895 "space prohibited before that '$op' $at\n" . $hereptr)) {
4900 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4901 if (ERROR("SPACING",
4902 "space required after that '$op' $at\n" . $hereptr)) {
4908 if ($rtrim_before || $space_after) {
4909 if ($rtrim_before) {
4910 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4912 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4919 # '*' as part of a type definition -- reported already.
4920 } elsif ($opv eq '*_') {
4921 #warn "'*' is part of type\n";
4923 # unary operators should have a space before and
4924 # none after. May be left adjacent to another
4925 # unary operator, or a cast
4926 } elsif ($op eq '!' || $op eq '~' ||
4927 $opv eq '*U' || $opv eq '-U' ||
4928 $opv eq '&U' || $opv eq '&&U') {
4929 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4930 if (ERROR("SPACING",
4931 "space required before that '$op' $at\n" . $hereptr)) {
4932 if ($n != $last_after + 2) {
4933 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4938 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4939 # A unary '*' may be const
4941 } elsif ($ctx =~ /.xW/) {
4942 if (ERROR("SPACING",
4943 "space prohibited after that '$op' $at\n" . $hereptr)) {
4944 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4945 if (defined $fix_elements[$n + 2]) {
4946 $fix_elements[$n + 2] =~ s/^\s+//;
4952 # unary ++ and unary -- are allowed no space on one side.
4953 } elsif ($op eq '++' or $op eq '--') {
4954 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4955 if (ERROR("SPACING",
4956 "space required one side of that '$op' $at\n" . $hereptr)) {
4957 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4961 if ($ctx =~ /Wx[BE]/ ||
4962 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4963 if (ERROR("SPACING",
4964 "space prohibited before that '$op' $at\n" . $hereptr)) {
4965 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4969 if ($ctx =~ /ExW/) {
4970 if (ERROR("SPACING",
4971 "space prohibited after that '$op' $at\n" . $hereptr)) {
4972 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4973 if (defined $fix_elements[$n + 2]) {
4974 $fix_elements[$n + 2] =~ s/^\s+//;
4980 # << and >> may either have or not have spaces both sides
4981 } elsif ($op eq '<<' or $op eq '>>' or
4982 $op eq '&' or $op eq '^' or $op eq '|' or
4983 $op eq '+' or $op eq '-' or
4984 $op eq '*' or $op eq '/' or
4988 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4990 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4991 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4992 $fix_elements[$n + 2] =~ s/^\s+//;
4995 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4997 "space preferred before that '$op' $at\n" . $hereptr)) {
4998 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5002 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5003 if (ERROR("SPACING",
5004 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5005 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5006 if (defined $fix_elements[$n + 2]) {
5007 $fix_elements[$n + 2] =~ s/^\s+//;
5013 # A colon needs no spaces before when it is
5014 # terminating a case value or a label.
5015 } elsif ($opv eq ':C' || $opv eq ':L') {
5016 if ($ctx =~ /Wx./) {
5017 if (ERROR("SPACING",
5018 "space prohibited before that '$op' $at\n" . $hereptr)) {
5019 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5024 # All the others need spaces both sides.
5025 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5028 # Ignore email addresses <foo@bar>
5030 $cc =~ /^\S+\@\S+>/) ||
5032 $ca =~ /<\S+\@\S+$/))
5037 # for asm volatile statements
5038 # ignore a colon with another
5039 # colon immediately before or after
5041 ($ca =~ /:$/ || $cc =~ /^:/)) {
5045 # messages are ERROR, but ?: are CHK
5047 my $msg_level = \&ERROR;
5048 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5050 if (&{$msg_level}("SPACING",
5051 "spaces required around that '$op' $at\n" . $hereptr)) {
5052 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5053 if (defined $fix_elements[$n + 2]) {
5054 $fix_elements[$n + 2] =~ s/^\s+//;
5060 $off += length($elements[$n + 1]);
5062 ## print("n: <$n> GOOD: <$good>\n");
5064 $fixed_line = $fixed_line . $good;
5067 if (($#elements % 2) == 0) {
5068 $fixed_line = $fixed_line . $fix_elements[$#elements];
5071 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5072 $fixed[$fixlinenr] = $fixed_line;
5078 # check for whitespace before a non-naked semicolon
5079 if ($line =~ /^\+.*\S\s+;\s*$/) {
5081 "space prohibited before semicolon\n" . $herecurr) &&
5083 1 while $fixed[$fixlinenr] =~
5084 s/^(\+.*\S)\s+;/$1;/;
5088 # check for multiple assignments
5089 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5090 CHK("MULTIPLE_ASSIGNMENTS",
5091 "multiple assignments should be avoided\n" . $herecurr);
5094 ## # check for multiple declarations, allowing for a function declaration
5096 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5097 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5099 ## # Remove any bracketed sections to ensure we do not
5100 ## # falsely report the parameters of functions.
5102 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5104 ## if ($ln =~ /,/) {
5105 ## WARN("MULTIPLE_DECLARATION",
5106 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5110 #need space before brace following if, while, etc
5111 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5112 $line =~ /\b(?:else|do)\{/) {
5113 if (ERROR("SPACING",
5114 "space required before the open brace '{'\n" . $herecurr) &&
5116 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5120 ## # check for blank lines before declarations
5121 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5122 ## $prevrawline =~ /^.\s*$/) {
5124 ## "No blank lines before declarations\n" . $hereprev);
5128 # closing brace should have a space following it when it has anything
5130 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5131 if (ERROR("SPACING",
5132 "space required after that close brace '}'\n" . $herecurr) &&
5134 $fixed[$fixlinenr] =~
5135 s/}((?!(?:,|;|\)))\S)/} $1/;
5139 # check spacing on square brackets
5140 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5141 if (ERROR("SPACING",
5142 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5144 $fixed[$fixlinenr] =~
5148 if ($line =~ /\s\]/) {
5149 if (ERROR("SPACING",
5150 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5152 $fixed[$fixlinenr] =~
5157 # check spacing on parentheses
5158 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5159 $line !~ /for\s*\(\s+;/) {
5160 if (ERROR("SPACING",
5161 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5163 $fixed[$fixlinenr] =~
5167 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5168 $line !~ /for\s*\(.*;\s+\)/ &&
5169 $line !~ /:\s+\)/) {
5170 if (ERROR("SPACING",
5171 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5173 $fixed[$fixlinenr] =~
5178 # check unnecessary parentheses around addressof/dereference single $Lvals
5179 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5181 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5183 if (CHK("UNNECESSARY_PARENTHESES",
5184 "Unnecessary parentheses around $var\n" . $herecurr) &&
5186 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5190 # check for unnecessary parentheses around function pointer uses
5191 # ie: (foo->bar)(); should be foo->bar();
5192 # but not "if (foo->bar) (" to avoid some false positives
5193 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5195 if (CHK("UNNECESSARY_PARENTHESES",
5196 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5198 my $var2 = deparenthesize($var);
5200 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5204 # check for unnecessary parentheses around comparisons in if uses
5205 # when !drivers/staging or command-line uses --strict
5206 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5207 $perl_version_ok && defined($stat) &&
5208 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5210 my $test = substr($2, 1, -1);
5212 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5214 # avoid parentheses around potential macro args
5215 next if ($match =~ /^\s*\w+\s*$/);
5216 if (!defined($herectx)) {
5217 $herectx = $here . "\n";
5218 my $cnt = statement_rawlines($if_stat);
5219 for (my $n = 0; $n < $cnt; $n++) {
5220 my $rl = raw_line($linenr, $n);
5221 $herectx .= $rl . "\n";
5222 last if $rl =~ /^[ \+].*\{/;
5225 CHK("UNNECESSARY_PARENTHESES",
5226 "Unnecessary parentheses around '$match'\n" . $herectx);
5230 #goto labels aren't indented, allow a single space however
5231 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
5232 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
5233 if (WARN("INDENTED_LABEL",
5234 "labels should not be indented\n" . $herecurr) &&
5236 $fixed[$fixlinenr] =~
5241 # check if a statement with a comma should be two statements like:
5242 # foo = bar(), /* comma should be semicolon */
5244 if (defined($stat) &&
5245 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5246 my $cnt = statement_rawlines($stat);
5247 my $herectx = get_stat_here($linenr, $cnt, $here);
5248 WARN("SUSPECT_COMMA_SEMICOLON",
5249 "Possible comma where semicolon could be used\n" . $herectx);
5252 # return is not a function
5253 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5255 if ($perl_version_ok &&
5256 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5258 $value = deparenthesize($value);
5259 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5260 ERROR("RETURN_PARENTHESES",
5261 "return is not a function, parentheses are not required\n" . $herecurr);
5263 } elsif ($spacing !~ /\s+/) {
5265 "space required before the open parenthesis '('\n" . $herecurr);
5269 # unnecessary return in a void function
5270 # at end-of-function, with the previous line a single leading tab, then return;
5271 # and the line before that not a goto label target like "out:"
5272 if ($sline =~ /^[ \+]}\s*$/ &&
5273 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5275 $lines[$linenr - 3] =~ /^[ +]/ &&
5276 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5278 "void function return statements are not generally useful\n" . $hereprev);
5281 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5282 if ($perl_version_ok &&
5283 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5284 my $openparens = $1;
5285 my $count = $openparens =~ tr@\(@\(@;
5287 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5288 my $comp = $4; #Not $1 because of $LvalOrFunc
5289 $msg = " - maybe == should be = ?" if ($comp eq "==");
5290 WARN("UNNECESSARY_PARENTHESES",
5291 "Unnecessary parentheses$msg\n" . $herecurr);
5295 # comparisons with a constant or upper case identifier on the left
5296 # avoid cases like "foo + BAR < baz"
5297 # only fix matches surrounded by parentheses to avoid incorrect
5298 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5299 if ($perl_version_ok &&
5300 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5305 my $newcomp = $comp;
5306 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5307 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5308 WARN("CONSTANT_COMPARISON",
5309 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5313 } elsif ($comp eq "<=") {
5315 } elsif ($comp eq ">") {
5317 } elsif ($comp eq ">=") {
5320 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5324 # Return of what appears to be an errno should normally be negative
5325 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5327 if ($name ne 'EOF' && $name ne 'ERROR') {
5328 WARN("USE_NEGATIVE_ERRNO",
5329 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5333 # Need a space before open parenthesis after if, while etc
5334 if ($line =~ /\b(if|while|for|switch)\(/) {
5335 if (ERROR("SPACING",
5336 "space required before the open parenthesis '('\n" . $herecurr) &&
5338 $fixed[$fixlinenr] =~
5339 s/\b(if|while|for|switch)\(/$1 \(/;
5343 # Check for illegal assignment in if conditional -- and check for trailing
5344 # statements after the conditional.
5345 if ($line =~ /do\s*(?!{)/) {
5346 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5347 ctx_statement_block($linenr, $realcnt, 0)
5348 if (!defined $stat);
5349 my ($stat_next) = ctx_statement_block($line_nr_next,
5350 $remain_next, $off_next);
5351 $stat_next =~ s/\n./\n /g;
5352 ##print "stat<$stat> stat_next<$stat_next>\n";
5354 if ($stat_next =~ /^\s*while\b/) {
5355 # If the statement carries leading newlines,
5356 # then count those as offsets.
5358 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5360 statement_rawlines($whitespace) - 1;
5362 $suppress_whiletrailers{$line_nr_next +
5366 if (!defined $suppress_whiletrailers{$linenr} &&
5367 defined($stat) && defined($cond) &&
5368 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5369 my ($s, $c) = ($stat, $cond);
5371 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5372 if (ERROR("ASSIGN_IN_IF",
5373 "do not use assignment in if condition\n" . $herecurr) &&
5374 $fix && $perl_version_ok) {
5375 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5383 fix_delete_line($fixlinenr, $rawline);
5384 fix_insert_line($fixlinenr, "$space$statement;");
5385 my $newline = "${space}if (";
5386 $newline .= '!' if defined($not);
5387 $newline .= '(' if (defined $not && defined($test) && defined($against));
5388 $newline .= "$assigned";
5389 $newline .= " $test $against" if (defined($test) && defined($against));
5390 $newline .= ')' if (defined $not && defined($test) && defined($against));
5392 $newline .= " {" if (defined($brace));
5393 fix_insert_line($fixlinenr + 1, $newline);
5398 # Find out what is on the end of the line after the
5400 substr($s, 0, length($c), '');
5402 $s =~ s/$;//g; # Remove any comments
5403 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5404 $c !~ /}\s*while\s*/)
5406 # Find out how long the conditional actually is.
5407 my @newlines = ($c =~ /\n/gs);
5408 my $cond_lines = 1 + $#newlines;
5411 $stat_real = raw_line($linenr, $cond_lines)
5412 . "\n" if ($cond_lines);
5413 if (defined($stat_real) && $cond_lines > 1) {
5414 $stat_real = "[...]\n$stat_real";
5417 ERROR("TRAILING_STATEMENTS",
5418 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5422 # Check for bitwise tests written as boolean
5434 WARN("HEXADECIMAL_BOOLEAN_TEST",
5435 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5438 # if and else should not have general statements after it
5439 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5441 $s =~ s/$;//g; # Remove any comments
5442 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5443 ERROR("TRAILING_STATEMENTS",
5444 "trailing statements should be on next line\n" . $herecurr);
5447 # if should not continue a brace
5448 if ($line =~ /}\s*if\b/) {
5449 ERROR("TRAILING_STATEMENTS",
5450 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5453 # case and default should not have general statements after them
5454 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5456 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5460 ERROR("TRAILING_STATEMENTS",
5461 "trailing statements should be on next line\n" . $herecurr);
5464 # Check for }<nl>else {, these must be at the same
5465 # indent level to be relevant to each other.
5466 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5467 $previndent == $indent) {
5468 if (ERROR("ELSE_AFTER_BRACE",
5469 "else should follow close brace '}'\n" . $hereprev) &&
5470 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5471 fix_delete_line($fixlinenr - 1, $prevrawline);
5472 fix_delete_line($fixlinenr, $rawline);
5473 my $fixedline = $prevrawline;
5474 $fixedline =~ s/}\s*$//;
5475 if ($fixedline !~ /^\+\s*$/) {
5476 fix_insert_line($fixlinenr, $fixedline);
5478 $fixedline = $rawline;
5479 $fixedline =~ s/^(.\s*)else/$1} else/;
5480 fix_insert_line($fixlinenr, $fixedline);
5484 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5485 $previndent == $indent) {
5486 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5488 # Find out what is on the end of the line after the
5490 substr($s, 0, length($c), '');
5493 if ($s =~ /^\s*;/) {
5494 if (ERROR("WHILE_AFTER_BRACE",
5495 "while should follow close brace '}'\n" . $hereprev) &&
5496 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5497 fix_delete_line($fixlinenr - 1, $prevrawline);
5498 fix_delete_line($fixlinenr, $rawline);
5499 my $fixedline = $prevrawline;
5500 my $trailing = $rawline;
5501 $trailing =~ s/^\+//;
5502 $trailing = trim($trailing);
5503 $fixedline =~ s/}\s*$/} $trailing/;
5504 fix_insert_line($fixlinenr, $fixedline);
5509 #Specific variable tests
5510 while ($line =~ m{($Constant|$Lval)}g) {
5514 if ($var !~ /^$Constant$/ &&
5515 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5516 #Ignore some autogenerated defines and enum values
5517 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5518 #Ignore Page<foo> variants
5519 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5520 #Ignore SI style variants like nS, mV and dB
5521 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5522 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5523 #Ignore some three character SI units explicitly, like MiB and KHz
5524 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5525 while ($var =~ m{($Ident)}g) {
5527 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5529 seed_camelcase_includes();
5530 if (!$file && !$camelcase_file_seeded) {
5531 seed_camelcase_file($realfile);
5532 $camelcase_file_seeded = 1;
5535 if (!defined $camelcase{$word}) {
5536 $camelcase{$word} = 1;
5538 "Avoid CamelCase: <$word>\n" . $herecurr);
5544 #no spaces allowed after \ in define
5545 if ($line =~ /\#\s*define.*\\\s+$/) {
5546 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5547 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5549 $fixed[$fixlinenr] =~ s/\s+$//;
5553 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5554 # itself <asm/foo.h> (uses RAW line)
5555 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5557 my $checkfile = "include/linux/$file";
5558 if (-f "$root/$checkfile" &&
5559 $realfile ne $checkfile &&
5560 $1 !~ /$allowed_asm_includes/)
5562 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5563 if ($asminclude > 0) {
5564 if ($realfile =~ m{^arch/}) {
5565 CHK("ARCH_INCLUDE_LINUX",
5566 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5568 WARN("INCLUDE_LINUX",
5569 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5575 # multi-statement macros should be enclosed in a do while loop, grab the
5576 # first statement and ensure its the whole macro if its not enclosed
5577 # in a known good container
5578 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5579 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5582 my ($off, $dstat, $dcond, $rest);
5584 my $has_flow_statement = 0;
5585 my $has_arg_concat = 0;
5586 ($dstat, $dcond, $ln, $cnt, $off) =
5587 ctx_statement_block($linenr, $realcnt, 0);
5589 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5590 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5592 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5593 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5595 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5596 my $define_args = $1;
5597 my $define_stmt = $dstat;
5600 if (defined $define_args && $define_args ne "") {
5601 $define_args = substr($define_args, 1, length($define_args) - 2);
5602 $define_args =~ s/\s*//g;
5603 $define_args =~ s/\\\+?//g;
5604 @def_args = split(",", $define_args);
5608 $dstat =~ s/\\\n.//g;
5609 $dstat =~ s/^\s*//s;
5610 $dstat =~ s/\s*$//s;
5612 # Flatten any parentheses and braces
5613 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5614 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5615 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5619 # Flatten any obvious string concatenation.
5620 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5621 $dstat =~ s/$Ident\s*($String)/$1/)
5625 # Make asm volatile uses seem like a generic function
5626 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5628 my $exceptions = qr{
5641 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5644 my $stmt_cnt = statement_rawlines($ctx);
5645 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5648 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5649 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5650 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5651 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5652 $dstat !~ /$exceptions/ &&
5653 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5654 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5655 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5656 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5657 $dstat !~ /^for\s*$Constant$/ && # for (...)
5658 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5659 $dstat !~ /^do\s*{/ && # do {...
5660 $dstat !~ /^\(\{/ && # ({...
5661 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5663 if ($dstat =~ /^\s*if\b/) {
5664 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5665 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5666 } elsif ($dstat =~ /;/) {
5667 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5668 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5670 ERROR("COMPLEX_MACRO",
5671 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5676 # Make $define_stmt single line, comment-free, etc
5677 my @stmt_array = split('\n', $define_stmt);
5680 foreach my $l (@stmt_array) {
5685 } elsif ($l =~ /^[\+ ]/) {
5686 $define_stmt .= substr($l, 1);
5689 $define_stmt =~ s/$;//g;
5690 $define_stmt =~ s/\s+/ /g;
5691 $define_stmt = trim($define_stmt);
5693 # check if any macro arguments are reused (ignore '...' and 'type')
5694 foreach my $arg (@def_args) {
5695 next if ($arg =~ /\.\.\./);
5696 next if ($arg =~ /^type$/i);
5697 my $tmp_stmt = $define_stmt;
5698 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5699 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5700 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5701 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5703 CHK("MACRO_ARG_REUSE",
5704 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5706 # check if any macro arguments may have other precedence issues
5707 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5708 ((defined($1) && $1 ne ',') ||
5709 (defined($2) && $2 ne ','))) {
5710 CHK("MACRO_ARG_PRECEDENCE",
5711 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5715 # check for macros with flow control, but without ## concatenation
5716 # ## concatenation is commonly a macro that defines a function so ignore those
5717 if ($has_flow_statement && !$has_arg_concat) {
5718 my $cnt = statement_rawlines($ctx);
5719 my $herectx = get_stat_here($linenr, $cnt, $here);
5721 WARN("MACRO_WITH_FLOW_CONTROL",
5722 "Macros with flow control statements should be avoided\n" . "$herectx");
5725 # check for line continuations outside of #defines, preprocessor #, and asm
5728 if ($prevline !~ /^..*\\$/ &&
5729 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5730 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5731 $line =~ /^\+.*\\$/) {
5732 WARN("LINE_CONTINUATIONS",
5733 "Avoid unnecessary line continuations\n" . $herecurr);
5737 # do {} while (0) macro tests:
5738 # single-statement macros do not need to be enclosed in do while (0) loop,
5739 # macro should not end with a semicolon
5740 if ($perl_version_ok &&
5741 $realfile !~ m@/vmlinux.lds.h$@ &&
5742 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5745 my ($off, $dstat, $dcond, $rest);
5747 ($dstat, $dcond, $ln, $cnt, $off) =
5748 ctx_statement_block($linenr, $realcnt, 0);
5751 $dstat =~ s/\\\n.//g;
5754 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5759 my $cnt = statement_rawlines($ctx);
5760 my $herectx = get_stat_here($linenr, $cnt, $here);
5762 if (($stmts =~ tr/;/;/) == 1 &&
5763 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5764 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5765 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5767 if (defined $semis && $semis ne "") {
5768 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5769 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5771 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5773 my $cnt = statement_rawlines($ctx);
5774 my $herectx = get_stat_here($linenr, $cnt, $here);
5776 WARN("TRAILING_SEMICOLON",
5777 "macros should not use a trailing semicolon\n" . "$herectx");
5781 # check for redundant bracing round if etc
5782 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5783 my ($level, $endln, @chunks) =
5784 ctx_statement_full($linenr, $realcnt, 1);
5785 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5786 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5787 if ($#chunks > 0 && $level == 0) {
5791 my $herectx = $here . "\n";
5792 my $ln = $linenr - 1;
5793 for my $chunk (@chunks) {
5794 my ($cond, $block) = @{$chunk};
5796 # If the condition carries leading newlines, then count those as offsets.
5797 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5798 my $offset = statement_rawlines($whitespace) - 1;
5800 $allowed[$allow] = 0;
5801 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5803 # We have looked at and allowed this specific line.
5804 $suppress_ifbraces{$ln + $offset} = 1;
5806 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5807 $ln += statement_rawlines($block) - 1;
5809 substr($block, 0, length($cond), '');
5811 $seen++ if ($block =~ /^\s*{/);
5813 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5814 if (statement_lines($cond) > 1) {
5815 #print "APW: ALLOWED: cond<$cond>\n";
5816 $allowed[$allow] = 1;
5818 if ($block =~/\b(?:if|for|while)\b/) {
5819 #print "APW: ALLOWED: block<$block>\n";
5820 $allowed[$allow] = 1;
5822 if (statement_block_size($block) > 1) {
5823 #print "APW: ALLOWED: lines block<$block>\n";
5824 $allowed[$allow] = 1;
5829 my $sum_allowed = 0;
5830 foreach (@allowed) {
5833 if ($sum_allowed == 0) {
5835 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5836 } elsif ($sum_allowed != $allow &&
5839 "braces {} should be used on all arms of this statement\n" . $herectx);
5844 if (!defined $suppress_ifbraces{$linenr - 1} &&
5845 $line =~ /\b(if|while|for|else)\b/) {
5848 # Check the pre-context.
5849 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5850 #print "APW: ALLOWED: pre<$1>\n";
5854 my ($level, $endln, @chunks) =
5855 ctx_statement_full($linenr, $realcnt, $-[0]);
5857 # Check the condition.
5858 my ($cond, $block) = @{$chunks[0]};
5859 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5860 if (defined $cond) {
5861 substr($block, 0, length($cond), '');
5863 if (statement_lines($cond) > 1) {
5864 #print "APW: ALLOWED: cond<$cond>\n";
5867 if ($block =~/\b(?:if|for|while)\b/) {
5868 #print "APW: ALLOWED: block<$block>\n";
5871 if (statement_block_size($block) > 1) {
5872 #print "APW: ALLOWED: lines block<$block>\n";
5875 # Check the post-context.
5876 if (defined $chunks[1]) {
5877 my ($cond, $block) = @{$chunks[1]};
5878 if (defined $cond) {
5879 substr($block, 0, length($cond), '');
5881 if ($block =~ /^\s*\{/) {
5882 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5886 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5887 my $cnt = statement_rawlines($block);
5888 my $herectx = get_stat_here($linenr, $cnt, $here);
5891 "braces {} are not necessary for single statement blocks\n" . $herectx);
5895 # check for single line unbalanced braces
5896 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5897 $sline =~ /^.\s*else\s*\{\s*$/) {
5898 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5901 # check for unnecessary blank lines around braces
5902 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5904 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5905 $fix && $prevrawline =~ /^\+/) {
5906 fix_delete_line($fixlinenr - 1, $prevrawline);
5909 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5911 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5913 fix_delete_line($fixlinenr, $rawline);
5917 # no volatiles please
5918 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5919 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5921 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5924 # Check for user-visible strings broken across lines, which breaks the ability
5925 # to grep for the string. Make exceptions when the previous string ends in a
5926 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5927 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5928 if ($line =~ /^\+\s*$String/ &&
5929 $prevline =~ /"\s*$/ &&
5930 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5931 if (WARN("SPLIT_STRING",
5932 "quoted string split across lines\n" . $hereprev) &&
5934 $prevrawline =~ /^\+.*"\s*$/ &&
5935 $last_coalesced_string_linenr != $linenr - 1) {
5936 my $extracted_string = get_quoted_string($line, $rawline);
5937 my $comma_close = "";
5938 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5942 fix_delete_line($fixlinenr - 1, $prevrawline);
5943 fix_delete_line($fixlinenr, $rawline);
5944 my $fixedline = $prevrawline;
5945 $fixedline =~ s/"\s*$//;
5946 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5947 fix_insert_line($fixlinenr - 1, $fixedline);
5948 $fixedline = $rawline;
5949 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5950 if ($fixedline !~ /\+\s*$/) {
5951 fix_insert_line($fixlinenr, $fixedline);
5953 $last_coalesced_string_linenr = $linenr;
5957 # check for missing a space in a string concatenation
5958 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5959 WARN('MISSING_SPACE',
5960 "break quoted strings at a space character\n" . $hereprev);
5963 # check for an embedded function name in a string when the function is known
5964 # This does not work very well for -f --file checking as it depends on patch
5965 # context providing the function name or a single line form for in-file
5966 # function declarations
5967 if ($line =~ /^\+.*$String/ &&
5968 defined($context_function) &&
5969 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5970 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5971 WARN("EMBEDDED_FUNCTION_NAME",
5972 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5975 # check for spaces before a quoted newline
5976 if ($rawline =~ /^.*\".*\s\\n/) {
5977 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5978 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5980 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5985 # concatenated string without spaces between elements
5986 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5987 if (CHK("CONCATENATED_STRING",
5988 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5990 while ($line =~ /($String)/g) {
5991 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5992 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5993 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5998 # uncoalesced string fragments
5999 if ($line =~ /$String\s*"/) {
6000 if (WARN("STRING_FRAGMENTS",
6001 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6003 while ($line =~ /($String)(?=\s*")/g) {
6004 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6005 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6010 # check for non-standard and hex prefixed decimal printf formats
6011 my $show_L = 1; #don't show the same defect twice
6013 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6014 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6015 $string =~ s/%%/__/g;
6017 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6019 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6023 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6025 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6028 # check for 0x<decimal>
6029 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6030 ERROR("PRINTF_0XDECIMAL",
6031 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6035 # check for line continuations in quoted strings with odd counts of "
6036 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6037 WARN("LINE_CONTINUATIONS",
6038 "Avoid line continuations in quoted strings\n" . $herecurr);
6042 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6044 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6048 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6050 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6053 # check for needless "if (<foo>) fn(<foo>)" uses
6054 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6055 my $tested = quotemeta($1);
6056 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6057 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6059 if (WARN('NEEDLESS_IF',
6060 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6063 my $leading_tabs = "";
6064 my $new_leading_tabs = "";
6065 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6070 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6071 $new_leading_tabs = $1;
6072 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6079 fix_delete_line($fixlinenr - 1, $prevrawline);
6080 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6086 # check for unnecessary "Out of Memory" messages
6087 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6088 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6089 (defined $1 || defined $3) &&
6092 my $testline = $lines[$linenr - 3];
6094 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6095 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6097 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6098 $s !~ /\b__GFP_NOWARN\b/ ) {
6100 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6104 # check for logging functions with KERN_<LEVEL>
6105 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6106 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6108 if (WARN("UNNECESSARY_KERN_LEVEL",
6109 "Possible unnecessary $level\n" . $herecurr) &&
6111 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6115 # check for logging continuations
6116 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6117 WARN("LOGGING_CONTINUATION",
6118 "Avoid logging continuation uses where feasible\n" . $herecurr);
6121 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6122 if (defined $stat &&
6123 $line =~ /\b$logFunctions\s*\(/ &&
6124 index($stat, '"') >= 0) {
6125 my $lc = $stat =~ tr@\n@@;
6126 $lc = $lc + $linenr;
6127 my $stat_real = get_stat_real($linenr, $lc);
6128 pos($stat_real) = index($stat_real, '"');
6129 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6132 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6133 if (WARN("UNNECESSARY_MODIFIER",
6134 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6135 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6138 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6143 # check for mask then right shift without a parentheses
6144 if ($perl_version_ok &&
6145 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6146 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6147 WARN("MASK_THEN_SHIFT",
6148 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6151 # check for pointer comparisons to NULL
6152 if ($perl_version_ok) {
6153 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6156 $equal = "" if ($4 eq "!=");
6157 if (CHK("COMPARISON_TO_NULL",
6158 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6160 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6165 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6166 if ($line =~ /(\b$InitAttribute\b)/) {
6168 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6171 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6172 ERROR("MISPLACED_INIT",
6173 "$attr should be placed after $var\n" . $herecurr)) ||
6174 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6175 WARN("MISPLACED_INIT",
6176 "$attr should be placed after $var\n" . $herecurr))) &&
6178 $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;
6183 # check for $InitAttributeData (ie: __initdata) with const
6184 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6186 $attr =~ /($InitAttributePrefix)(.*)/;
6187 my $attr_prefix = $1;
6189 if (ERROR("INIT_ATTRIBUTE",
6190 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6192 $fixed[$fixlinenr] =~
6193 s/$InitAttributeData/${attr_prefix}initconst/;
6197 # check for $InitAttributeConst (ie: __initconst) without const
6198 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6200 if (ERROR("INIT_ATTRIBUTE",
6201 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6203 my $lead = $fixed[$fixlinenr] =~
6204 /(^\+\s*(?:static\s+))/;
6206 $lead = "$lead " if ($lead !~ /^\+$/);
6207 $lead = "${lead}const ";
6208 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6212 # check for __read_mostly with const non-pointer (should just be const)
6213 if ($line =~ /\b__read_mostly\b/ &&
6214 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6215 if (ERROR("CONST_READ_MOSTLY",
6216 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6218 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6222 # don't use __constant_<foo> functions outside of include/uapi/
6223 if ($realfile !~ m@^include/uapi/@ &&
6224 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6225 my $constant_func = $1;
6226 my $func = $constant_func;
6227 $func =~ s/^__constant_//;
6228 if (WARN("CONSTANT_CONVERSION",
6229 "$constant_func should be $func\n" . $herecurr) &&
6231 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6235 # prefer usleep_range over udelay
6236 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6238 # ignore udelay's < 10, however
6239 if (! ($delay < 10) ) {
6241 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6243 if ($delay > 2000) {
6245 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6249 # warn about unexpectedly long msleep's
6250 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6253 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6257 # check for comparisons of jiffies
6258 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6259 WARN("JIFFIES_COMPARISON",
6260 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6263 # check for comparisons of get_jiffies_64()
6264 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6265 WARN("JIFFIES_COMPARISON",
6266 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6269 # warn about #ifdefs in C files
6270 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6271 # print "#ifdef in C files should be avoided\n";
6272 # print "$herecurr";
6276 # warn about spacing in #ifdefs
6277 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6278 if (ERROR("SPACING",
6279 "exactly one space required after that #$1\n" . $herecurr) &&
6281 $fixed[$fixlinenr] =~
6282 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6287 # check for spinlock_t definitions without a comment.
6288 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6289 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6291 if (!ctx_has_comment($first_line, $linenr)) {
6292 CHK("UNCOMMENTED_DEFINITION",
6293 "$1 definition without comment\n" . $herecurr);
6296 # check for memory barriers without a comment.
6303 my $barrier_stems = qr{
6311 my $all_barriers = qr{
6313 smp_(?:$barrier_stems)|
6314 virt_(?:$barrier_stems)
6317 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6318 if (!ctx_has_comment($first_line, $linenr)) {
6319 WARN("MEMORY_BARRIER",
6320 "memory barrier without comment\n" . $herecurr);
6324 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6326 if ($realfile !~ m@^include/asm-generic/@ &&
6327 $realfile !~ m@/barrier\.h$@ &&
6328 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6329 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6330 WARN("MEMORY_BARRIER",
6331 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6334 # check for waitqueue_active without a comment.
6335 if ($line =~ /\bwaitqueue_active\s*\(/) {
6336 if (!ctx_has_comment($first_line, $linenr)) {
6337 WARN("WAITQUEUE_ACTIVE",
6338 "waitqueue_active without comment\n" . $herecurr);
6342 # check for data_race without a comment.
6343 if ($line =~ /\bdata_race\s*\(/) {
6344 if (!ctx_has_comment($first_line, $linenr)) {
6346 "data_race without comment\n" . $herecurr);
6350 # check of hardware specific defines
6351 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6353 "architecture specific defines should be avoided\n" . $herecurr);
6356 # check that the storage class is not after a type
6357 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6358 WARN("STORAGE_CLASS",
6359 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6361 # Check that the storage class is at the beginning of a declaration
6362 if ($line =~ /\b$Storage\b/ &&
6363 $line !~ /^.\s*$Storage/ &&
6364 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6365 $1 !~ /[\,\)]\s*$/) {
6366 WARN("STORAGE_CLASS",
6367 "storage class should be at the beginning of the declaration\n" . $herecurr);
6370 # check the location of the inline attribute, that it is between
6371 # storage class and type.
6372 if ($line =~ /\b$Type\s+$Inline\b/ ||
6373 $line =~ /\b$Inline\s+$Storage\b/) {
6374 ERROR("INLINE_LOCATION",
6375 "inline keyword should sit between storage class and type\n" . $herecurr);
6378 # Check for __inline__ and __inline, prefer inline
6379 if ($realfile !~ m@\binclude/uapi/@ &&
6380 $line =~ /\b(__inline__|__inline)\b/) {
6382 "plain inline is preferred over $1\n" . $herecurr) &&
6384 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6389 # Check for compiler attributes
6390 if ($realfile !~ m@\binclude/uapi/@ &&
6391 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6393 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6396 "alias" => "__alias",
6397 "aligned" => "__aligned",
6398 "always_inline" => "__always_inline",
6399 "assume_aligned" => "__assume_aligned",
6401 "const" => "__attribute_const__",
6403 "designated_init" => "__designated_init",
6404 "externally_visible" => "__visible",
6405 "format" => "printf|scanf",
6406 "gnu_inline" => "__gnu_inline",
6407 "malloc" => "__malloc",
6409 "no_caller_saved_registers" => "__no_caller_saved_registers",
6410 "noclone" => "__noclone",
6411 "noinline" => "noinline",
6412 "nonstring" => "__nonstring",
6413 "noreturn" => "__noreturn",
6414 "packed" => "__packed",
6416 "section" => "__section",
6421 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6424 $params = $2 if defined($2);
6425 my $curr_attr = $orig_attr;
6426 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6427 if (exists($attr_list{$curr_attr})) {
6428 my $new = $attr_list{$curr_attr};
6429 if ($curr_attr eq "format" && $params) {
6430 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6433 $new = "$new$params";
6435 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6436 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6438 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6439 $fixed[$fixlinenr] =~ s/$remove//;
6440 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6441 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6442 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6447 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6448 if ($attr =~ /^_*unused/) {
6449 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6450 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6454 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6455 if ($perl_version_ok &&
6456 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6457 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6458 $line =~ /\b__weak\b/)) {
6459 ERROR("WEAK_DECLARATION",
6460 "Using weak declarations can have unintended link defects\n" . $herecurr);
6463 # check for c99 types like uint8_t used outside of uapi/ and tools/
6464 if ($realfile !~ m@\binclude/uapi/@ &&
6465 $realfile !~ m@\btools/@ &&
6466 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6468 if ($type =~ /\b($typeC99Typedefs)\b/) {
6470 my $kernel_type = 'u';
6471 $kernel_type = 's' if ($type =~ /^_*[si]/);
6474 if (CHK("PREFER_KERNEL_TYPES",
6475 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6477 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6482 # check for cast of C90 native int or longer types constants
6483 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6486 if (WARN("TYPECAST_INT_CONSTANT",
6487 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6490 my $newconst = $const;
6491 $newconst =~ s/${Int_type}$//;
6492 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6493 if ($cast =~ /\blong\s+long\b/) {
6495 } elsif ($cast =~ /\blong\b/) {
6498 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6502 # check for sizeof(&)
6503 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6504 WARN("SIZEOF_ADDRESS",
6505 "sizeof(& should be avoided\n" . $herecurr);
6508 # check for sizeof without parenthesis
6509 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6510 if (WARN("SIZEOF_PARENTHESIS",
6511 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6513 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6517 # check for struct spinlock declarations
6518 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6519 WARN("USE_SPINLOCK_T",
6520 "struct spinlock should be spinlock_t\n" . $herecurr);
6523 # check for seq_printf uses that could be seq_puts
6524 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6525 my $fmt = get_quoted_string($line, $rawline);
6528 if (WARN("PREFER_SEQ_PUTS",
6529 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6531 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6536 # check for vsprintf extension %p<foo> misuses
6537 if ($perl_version_ok &&
6539 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6540 $1 !~ /^_*volatile_*$/) {
6543 my $lc = $stat =~ tr@\n@@;
6544 $lc = $lc + $linenr;
6545 for (my $count = $linenr; $count <= $lc; $count++) {
6549 my $bad_specifier = "";
6550 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6553 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6557 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6558 ($extension eq "f" &&
6559 defined $qualifier && $qualifier !~ /^w/)) {
6560 $bad_specifier = $specifier;
6563 if ($extension eq "x" && !defined($stat_real)) {
6564 if (!defined($stat_real)) {
6565 $stat_real = get_stat_real($linenr, $lc);
6567 WARN("VSPRINTF_SPECIFIER_PX",
6568 "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");
6571 if ($bad_specifier ne "") {
6572 my $stat_real = get_stat_real($linenr, $lc);
6573 my $ext_type = "Invalid";
6575 if ($bad_specifier =~ /p[Ff]/) {
6576 $use = " - use %pS instead";
6577 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6580 WARN("VSPRINTF_POINTER_EXTENSION",
6581 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6586 # Check for misused memsets
6587 if ($perl_version_ok &&
6589 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6595 if ($ms_size =~ /^(0x|)0$/i) {
6597 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6598 } elsif ($ms_size =~ /^(0x|)1$/i) {
6600 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6604 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6605 # if ($perl_version_ok &&
6607 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6608 # if (WARN("PREFER_ETHER_ADDR_COPY",
6609 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6611 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6615 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6616 # if ($perl_version_ok &&
6618 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6619 # WARN("PREFER_ETHER_ADDR_EQUAL",
6620 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6623 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6624 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6625 # if ($perl_version_ok &&
6627 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6631 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6632 # if (WARN("PREFER_ETH_ZERO_ADDR",
6633 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6635 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6637 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6638 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6639 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6641 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6646 # strlcpy uses that should likely be strscpy
6647 if ($line =~ /\bstrlcpy\s*\(/) {
6649 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6652 # typecasts on min/max could be min_t/max_t
6653 if ($perl_version_ok &&
6655 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6656 if (defined $2 || defined $7) {
6658 my $cast1 = deparenthesize($2);
6660 my $cast2 = deparenthesize($7);
6664 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6665 $cast = "$cast1 or $cast2";
6666 } elsif ($cast1 ne "") {
6672 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6676 # check usleep_range arguments
6677 if ($perl_version_ok &&
6679 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6683 WARN("USLEEP_RANGE",
6684 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6685 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6687 WARN("USLEEP_RANGE",
6688 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6692 # check for naked sscanf
6693 if ($perl_version_ok &&
6695 $line =~ /\bsscanf\b/ &&
6696 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6697 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6698 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6699 my $lc = $stat =~ tr@\n@@;
6700 $lc = $lc + $linenr;
6701 my $stat_real = get_stat_real($linenr, $lc);
6702 WARN("NAKED_SSCANF",
6703 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6706 # check for simple sscanf that should be kstrto<foo>
6707 if ($perl_version_ok &&
6709 $line =~ /\bsscanf\b/) {
6710 my $lc = $stat =~ tr@\n@@;
6711 $lc = $lc + $linenr;
6712 my $stat_real = get_stat_real($linenr, $lc);
6713 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6715 my $count = $format =~ tr@%@%@;
6717 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6718 WARN("SSCANF_TO_KSTRTO",
6719 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6724 # check for new externs in .h files.
6725 if ($realfile =~ /\.h$/ &&
6726 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6727 if (CHK("AVOID_EXTERNS",
6728 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6730 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6734 # check for new externs in .c files.
6735 if ($realfile =~ /\.c$/ && defined $stat &&
6736 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6738 my $function_name = $1;
6739 my $paren_space = $2;
6742 if (defined $cond) {
6743 substr($s, 0, length($cond), '');
6747 WARN("AVOID_EXTERNS",
6748 "externs should be avoided in .c files\n" . $herecurr);
6751 if ($paren_space =~ /\n/) {
6752 WARN("FUNCTION_ARGUMENTS",
6753 "arguments for function declarations should follow identifier\n" . $herecurr);
6756 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6757 $stat =~ /^.\s*extern\s+/)
6759 WARN("AVOID_EXTERNS",
6760 "externs should be avoided in .c files\n" . $herecurr);
6763 # check for function declarations that have arguments without identifier names
6764 if (defined $stat &&
6765 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6767 my $args = trim($1);
6768 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6770 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6771 WARN("FUNCTION_ARGUMENTS",
6772 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6777 # check for function definitions
6778 if ($perl_version_ok &&
6780 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6781 $context_function = $1;
6783 # check for multiline function definition with misplaced open brace
6785 my $cnt = statement_rawlines($stat);
6786 my $herectx = $here . "\n";
6787 for (my $n = 0; $n < $cnt; $n++) {
6788 my $rl = raw_line($linenr, $n);
6789 $herectx .= $rl . "\n";
6790 $ok = 1 if ($rl =~ /^[ \+]\{/);
6791 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6792 last if $rl =~ /^[ \+].*\{/;
6796 "open brace '{' following function definitions go on the next line\n" . $herectx);
6800 # checks for new __setup's
6801 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6804 if (!grep(/$name/, @setup_docs)) {
6805 CHK("UNDOCUMENTED_SETUP",
6806 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6810 # check for pointless casting of alloc functions
6811 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6812 WARN("UNNECESSARY_CASTS",
6813 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6817 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6818 if ($perl_version_ok &&
6819 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6820 CHK("ALLOC_SIZEOF_STRUCT",
6821 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6824 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6825 if ($perl_version_ok &&
6827 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6831 my $newfunc = "kmalloc_array";
6832 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6835 if ($a1 =~ /^sizeof\s*\S/) {
6839 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6840 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6841 my $cnt = statement_rawlines($stat);
6842 my $herectx = get_stat_here($linenr, $cnt, $here);
6844 if (WARN("ALLOC_WITH_MULTIPLY",
6845 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6848 $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;
6853 # check for krealloc arg reuse
6854 if ($perl_version_ok &&
6855 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6857 WARN("KREALLOC_ARG_REUSE",
6858 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6861 # check for alloc argument mismatch
6862 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6863 WARN("ALLOC_ARRAY_ARGS",
6864 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6867 # check for multiple semicolons
6868 if ($line =~ /;\s*;\s*$/) {
6869 if (WARN("ONE_SEMICOLON",
6870 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6872 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6876 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6877 if ($realfile !~ m@^include/uapi/@ &&
6878 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6880 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6881 if (CHK("BIT_MACRO",
6882 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6884 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6888 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6889 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6890 WARN("IS_ENABLED_CONFIG",
6891 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6894 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6895 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6897 if (WARN("PREFER_IS_ENABLED",
6898 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6900 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6904 # check for /* fallthrough */ like comment, prefer fallthrough;
6905 my @fallthroughs = (
6908 'lint -fallthrough[ \t]*',
6909 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6910 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6911 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6912 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6914 if ($raw_comment ne '') {
6915 foreach my $ft (@fallthroughs) {
6916 if ($raw_comment =~ /$ft/) {
6917 my $msg_level = \&WARN;
6918 $msg_level = \&CHK if ($file);
6919 &{$msg_level}("PREFER_FALLTHROUGH",
6920 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6926 # check for switch/default statements without a break;
6927 if ($perl_version_ok &&
6929 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6930 my $cnt = statement_rawlines($stat);
6931 my $herectx = get_stat_here($linenr, $cnt, $here);
6933 WARN("DEFAULT_NO_BREAK",
6934 "switch default: should use break\n" . $herectx);
6937 # check for gcc specific __FUNCTION__
6938 if ($line =~ /\b__FUNCTION__\b/) {
6939 if (WARN("USE_FUNC",
6940 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6942 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6946 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6947 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6949 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6952 # check for use of yield()
6953 if ($line =~ /\byield\s*\(\s*\)/) {
6955 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6958 # check for comparisons against true and false
6959 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6967 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6969 my $type = lc($otype);
6970 if ($type =~ /^(?:true|false)$/) {
6971 if (("$test" eq "==" && "$type" eq "true") ||
6972 ("$test" eq "!=" && "$type" eq "false")) {
6976 CHK("BOOL_COMPARISON",
6977 "Using comparison to $otype is error prone\n" . $herecurr);
6979 ## maybe suggesting a correct construct would better
6980 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6985 # check for semaphores initialized locked
6986 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6987 WARN("CONSIDER_COMPLETION",
6988 "consider using a completion\n" . $herecurr);
6991 # recommend kstrto* over simple_strto* and strict_strto*
6992 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6993 WARN("CONSIDER_KSTRTO",
6994 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6997 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6998 if ($line =~ /^.\s*__initcall\s*\(/) {
6999 WARN("USE_DEVICE_INITCALL",
7000 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7003 # check for spin_is_locked(), suggest lockdep instead
7004 if ($line =~ /\bspin_is_locked\(/) {
7006 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7009 # check for deprecated apis
7010 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7011 my $deprecated_api = $1;
7012 my $new_api = $deprecated_apis{$deprecated_api};
7013 WARN("DEPRECATED_API",
7014 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7017 # check for various structs that are normally const (ops, kgdb, device_tree)
7018 # and avoid what seem like struct definitions 'struct foo {'
7019 if (defined($const_structs) &&
7020 $line !~ /\bconst\b/ &&
7021 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7022 WARN("CONST_STRUCT",
7023 "struct $1 should normally be const\n" . $herecurr);
7026 # use of NR_CPUS is usually wrong
7027 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7028 # ignore designated initializers using NR_CPUS
7029 if ($line =~ /\bNR_CPUS\b/ &&
7030 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7031 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7032 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7033 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7034 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7035 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7038 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7041 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7042 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7043 ERROR("DEFINE_ARCH_HAS",
7044 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7047 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7048 if ($perl_version_ok &&
7049 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7050 WARN("LIKELY_MISUSE",
7051 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7054 # nested likely/unlikely calls
7055 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7056 WARN("LIKELY_MISUSE",
7057 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7060 # whine mightly about in_atomic
7061 if ($line =~ /\bin_atomic\s*\(/) {
7062 if ($realfile =~ m@^drivers/@) {
7064 "do not use in_atomic in drivers\n" . $herecurr);
7065 } elsif ($realfile !~ m@^kernel/@) {
7067 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7071 # check for lockdep_set_novalidate_class
7072 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7073 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7074 if ($realfile !~ m@^kernel/lockdep@ &&
7075 $realfile !~ m@^include/linux/lockdep@ &&
7076 $realfile !~ m@^drivers/base/core@) {
7078 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7082 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7083 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7084 WARN("EXPORTED_WORLD_WRITABLE",
7085 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7088 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7089 # and whether or not function naming is typical and if
7090 # DEVICE_ATTR permissions uses are unusual too
7091 if ($perl_version_ok &&
7093 $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*\)/) {
7098 my $octal_perms = perms_to_octal($perms);
7099 if ($show =~ /^${var}_show$/ &&
7100 $store =~ /^${var}_store$/ &&
7101 $octal_perms eq "0644") {
7102 if (WARN("DEVICE_ATTR_RW",
7103 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7105 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7107 } elsif ($show =~ /^${var}_show$/ &&
7108 $store =~ /^NULL$/ &&
7109 $octal_perms eq "0444") {
7110 if (WARN("DEVICE_ATTR_RO",
7111 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7113 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7115 } elsif ($show =~ /^NULL$/ &&
7116 $store =~ /^${var}_store$/ &&
7117 $octal_perms eq "0200") {
7118 if (WARN("DEVICE_ATTR_WO",
7119 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7121 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7123 } elsif ($octal_perms eq "0644" ||
7124 $octal_perms eq "0444" ||
7125 $octal_perms eq "0200") {
7126 my $newshow = "$show";
7127 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7128 my $newstore = $store;
7129 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7131 if ($show ne $newshow) {
7132 $rename .= " '$show' to '$newshow'";
7134 if ($store ne $newstore) {
7135 $rename .= " '$store' to '$newstore'";
7137 WARN("DEVICE_ATTR_FUNCTIONS",
7138 "Consider renaming function(s)$rename\n" . $herecurr);
7140 WARN("DEVICE_ATTR_PERMS",
7141 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7145 # Mode permission misuses where it seems decimal should be octal
7146 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7147 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7148 # specific definition of not visible in sysfs.
7149 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7150 # use the default permissions
7151 if ($perl_version_ok &&
7153 $line =~ /$mode_perms_search/) {
7154 foreach my $entry (@mode_permission_funcs) {
7155 my $func = $entry->[0];
7156 my $arg_pos = $entry->[1];
7158 my $lc = $stat =~ tr@\n@@;
7159 $lc = $lc + $linenr;
7160 my $stat_real = get_stat_real($linenr, $lc);
7165 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7167 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7168 if ($stat =~ /$test/) {
7170 $val = $6 if ($skip_args ne "");
7171 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7172 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7173 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7174 ERROR("NON_OCTAL_PERMISSIONS",
7175 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7177 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7178 ERROR("EXPORTED_WORLD_WRITABLE",
7179 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7185 # check for uses of S_<PERMS> that could be octal for readability
7186 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7188 my $octal = perms_to_octal($oval);
7189 if (WARN("SYMBOLIC_PERMS",
7190 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7192 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7196 # validate content of MODULE_LICENSE against list from include/linux/module.h
7197 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7198 my $extracted_string = get_quoted_string($line, $rawline);
7199 my $valid_licenses = qr{
7202 GPL\ and\ additional\ rights|
7208 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7209 WARN("MODULE_LICENSE",
7210 "unknown module license " . $extracted_string . "\n" . $herecurr);
7214 # check for sysctl duplicate constants
7215 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7216 WARN("DUPLICATED_SYSCTL_CONST",
7217 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7221 # If we have no input at all, then there is nothing to report on
7222 # so just keep quiet.
7223 if ($#rawlines == -1) {
7227 # In mailback mode only produce a report in the negative, for
7228 # things that appear to be patches.
7229 if ($mailback && ($clean == 1 || !$is_patch)) {
7233 # This is not a patch, and we are in 'no-patch' mode so
7235 if (!$chk_patch && !$is_patch) {
7239 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7240 ERROR("NOT_UNIFIED_DIFF",
7241 "Does not appear to be a unified-diff format patch\n");
7243 if ($is_patch && $has_commit_log && $chk_signoff) {
7244 if ($signoff == 0) {
7245 ERROR("MISSING_SIGN_OFF",
7246 "Missing Signed-off-by: line(s)\n");
7247 } elsif ($authorsignoff != 1) {
7248 # authorsignoff values:
7249 # 0 -> missing sign off
7250 # 1 -> sign off identical
7251 # 2 -> names and addresses match, comments mismatch
7252 # 3 -> addresses match, names different
7253 # 4 -> names match, addresses different
7254 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7256 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7258 if ($authorsignoff == 0) {
7259 ERROR("NO_AUTHOR_SIGN_OFF",
7260 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7261 } elsif ($authorsignoff == 2) {
7262 CHK("FROM_SIGN_OFF_MISMATCH",
7263 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7264 } elsif ($authorsignoff == 3) {
7265 WARN("FROM_SIGN_OFF_MISMATCH",
7266 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7267 } elsif ($authorsignoff == 4) {
7268 WARN("FROM_SIGN_OFF_MISMATCH",
7269 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7270 } elsif ($authorsignoff == 5) {
7271 WARN("FROM_SIGN_OFF_MISMATCH",
7272 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7277 print report_dump();
7278 if ($summary && !($clean == 1 && $quiet == 1)) {
7279 print "$filename " if ($summary_file);
7280 print "total: $cnt_error errors, $cnt_warn warnings, " .
7281 (($check)? "$cnt_chk checks, " : "") .
7282 "$cnt_lines lines checked\n";
7286 # If there were any defects found and not already fixing them
7287 if (!$clean and !$fix) {
7290 NOTE: For some of the reported defects, checkpatch may be able to
7291 mechanically convert to the typical style using --fix or --fix-inplace.
7294 # If there were whitespace errors which cleanpatch can fix
7295 # then suggest that.
7296 if ($rpt_cleaners) {
7300 NOTE: Whitespace errors detected.
7301 You may wish to use scripts/cleanpatch or scripts/cleanfile
7306 if ($clean == 0 && $fix &&
7307 ("@rawlines" ne "@fixed" ||
7308 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7309 my $newfile = $filename;
7310 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7314 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7316 open($f, '>', $newfile)
7317 or die "$P: Can't open $newfile for write\n";
7318 foreach my $fixed_line (@fixed) {
7321 if ($linecount > 3) {
7322 $fixed_line =~ s/^\+//;
7323 print $f $fixed_line . "\n";
7326 print $f $fixed_line . "\n";
7334 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7336 Do _NOT_ trust the results written to this file.
7337 Do _NOT_ submit these changes without inspecting them for correctness.
7339 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7340 No warranties, expressed or implied...
7348 print "$vname has no obvious style problems and is ready for submission.\n";
7350 print "$vname has style problems, please review.\n";