2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
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
404 ____cacheline_aligned|
405 ____cacheline_aligned_in_smp|
406 ____cacheline_internodealigned_in_smp|
410 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
411 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
412 our $Lval = qr{$Ident(?:$Member)*};
414 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
415 our $Binary = qr{(?i)0b[01]+$Int_type?};
416 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
417 our $Int = qr{[0-9]+$Int_type?};
418 our $Octal = qr{0[0-7]+$Int_type?};
419 our $String = qr{"[X\t]*"};
420 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
421 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
422 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
423 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
424 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
425 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
426 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
427 our $Arithmetic = qr{\+|-|\*|\/|%};
431 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
434 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
438 our $NonptrTypeMisordered;
439 our $NonptrTypeWithAttr;
443 our $DeclareMisordered;
445 our $NON_ASCII_UTF8 = qr{
446 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
447 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
448 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
449 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
450 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
451 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
452 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
456 [\x09\x0A\x0D\x20-\x7E] # ASCII
460 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
461 our $typeOtherOSTypedefs = qr{(?x:
462 u_(?:char|short|int|long) | # bsd
463 u(?:nchar|short|int|long) # sysv
465 our $typeKernelTypedefs = qr{(?x:
466 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
469 our $typeTypedefs = qr{(?x:
471 $typeOtherOSTypedefs\b|
472 $typeKernelTypedefs\b
475 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
477 our $logFunctions = qr{(?x:
478 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
479 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
481 WARN(?:_RATELIMIT|_ONCE|)|
484 seq_vprintf|seq_printf|seq_puts
487 our $allocFunctions = qr{(?x:
489 (?:kv|k|v)[czm]alloc(?:_node|_array)? |
492 (?:\w+)?alloc_skb(?:_ip_align)? |
493 # dev_alloc_skb/netdev_alloc_skb, et al
497 our $signature_tags = qr{(?xi:
509 sub edit_distance_min {
511 my $len = scalar @arr;
512 if ((scalar @arr) < 1) {
513 # if underflow, return
517 for my $i (0 .. ($len-1)) {
518 if ($arr[$i] < $min) {
525 sub get_edit_distance {
526 my ($str1, $str2) = @_;
531 my $len1 = length($str1);
532 my $len2 = length($str2);
533 # two dimensional array storing minimum edit distance
535 for my $i (0 .. $len1) {
536 for my $j (0 .. $len2) {
538 $distance[$i][$j] = $j;
540 $distance[$i][$j] = $i;
541 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
542 $distance[$i][$j] = $distance[$i - 1][$j - 1];
544 my $dist1 = $distance[$i][$j - 1]; #insert distance
545 my $dist2 = $distance[$i - 1][$j]; # remove
546 my $dist3 = $distance[$i - 1][$j - 1]; #replace
547 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
551 return $distance[$len1][$len2];
554 sub find_standard_signature {
556 my @standard_signature_tags = (
557 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
558 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
560 foreach my $signature (@standard_signature_tags) {
561 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
567 our @typeListMisordered = (
568 qr{char\s+(?:un)?signed},
569 qr{int\s+(?:(?:un)?signed\s+)?short\s},
570 qr{int\s+short(?:\s+(?:un)?signed)},
571 qr{short\s+int(?:\s+(?:un)?signed)},
572 qr{(?:un)?signed\s+int\s+short},
573 qr{short\s+(?:un)?signed},
574 qr{long\s+int\s+(?:un)?signed},
575 qr{int\s+long\s+(?:un)?signed},
576 qr{long\s+(?:un)?signed\s+int},
577 qr{int\s+(?:un)?signed\s+long},
578 qr{int\s+(?:un)?signed},
579 qr{int\s+long\s+long\s+(?:un)?signed},
580 qr{long\s+long\s+int\s+(?:un)?signed},
581 qr{long\s+long\s+(?:un)?signed\s+int},
582 qr{long\s+long\s+(?:un)?signed},
583 qr{long\s+(?:un)?signed},
588 qr{(?:(?:un)?signed\s+)?char},
589 qr{(?:(?:un)?signed\s+)?short\s+int},
590 qr{(?:(?:un)?signed\s+)?short},
591 qr{(?:(?:un)?signed\s+)?int},
592 qr{(?:(?:un)?signed\s+)?long\s+int},
593 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
594 qr{(?:(?:un)?signed\s+)?long\s+long},
595 qr{(?:(?:un)?signed\s+)?long},
604 qr{${Ident}_handler},
605 qr{${Ident}_handler_fn},
609 our $C90_int_types = qr{(?x:
610 long\s+long\s+int\s+(?:un)?signed|
611 long\s+long\s+(?:un)?signed\s+int|
612 long\s+long\s+(?:un)?signed|
613 (?:(?:un)?signed\s+)?long\s+long\s+int|
614 (?:(?:un)?signed\s+)?long\s+long|
615 int\s+long\s+long\s+(?:un)?signed|
616 int\s+(?:(?:un)?signed\s+)?long\s+long|
618 long\s+int\s+(?:un)?signed|
619 long\s+(?:un)?signed\s+int|
620 long\s+(?:un)?signed|
621 (?:(?:un)?signed\s+)?long\s+int|
622 (?:(?:un)?signed\s+)?long|
623 int\s+long\s+(?:un)?signed|
624 int\s+(?:(?:un)?signed\s+)?long|
627 (?:(?:un)?signed\s+)?int
630 our @typeListFile = ();
631 our @typeListWithAttr = (
633 qr{struct\s+$InitAttribute\s+$Ident},
634 qr{union\s+$InitAttribute\s+$Ident},
637 our @modifierList = (
640 our @modifierListFile = ();
642 our @mode_permission_funcs = (
644 ["module_param_(?:array|named|string)", 4],
645 ["module_param_array_named", 5],
646 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
647 ["proc_create(?:_data|)", 2],
648 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
649 ["IIO_DEV_ATTR_[A-Z_]+", 1],
650 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
651 ["SENSOR_TEMPLATE(?:_2|)", 3],
655 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
657 #Create a search pattern for all these functions to speed up a loop below
658 our $mode_perms_search = "";
659 foreach my $entry (@mode_permission_funcs) {
660 $mode_perms_search .= '|' if ($mode_perms_search ne "");
661 $mode_perms_search .= $entry->[0];
663 $mode_perms_search = "(?:${mode_perms_search})";
665 our %deprecated_apis = (
666 "synchronize_rcu_bh" => "synchronize_rcu",
667 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
668 "call_rcu_bh" => "call_rcu",
669 "rcu_barrier_bh" => "rcu_barrier",
670 "synchronize_sched" => "synchronize_rcu",
671 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
672 "call_rcu_sched" => "call_rcu",
673 "rcu_barrier_sched" => "rcu_barrier",
674 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
675 "cond_synchronize_sched" => "cond_synchronize_rcu",
678 #Create a search pattern for all these strings to speed up a loop below
679 our $deprecated_apis_search = "";
680 foreach my $entry (keys %deprecated_apis) {
681 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
682 $deprecated_apis_search .= $entry;
684 $deprecated_apis_search = "(?:${deprecated_apis_search})";
686 our $mode_perms_world_writable = qr{
694 our %mode_permission_string_types = (
713 #Create a search pattern for all these strings to speed up a loop below
714 our $mode_perms_string_search = "";
715 foreach my $entry (keys %mode_permission_string_types) {
716 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
717 $mode_perms_string_search .= $entry;
719 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
720 our $multi_mode_perms_string_search = qr{
721 ${single_mode_perms_string_search}
722 (?:\s*\|\s*${single_mode_perms_string_search})*
728 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
735 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
736 $curpos = pos($string);
739 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
741 $to |= $mode_permission_string_types{$match};
742 $val .= '\s*\|\s*' if ($val ne "");
746 $oval =~ s/^\s*\|\s*//;
747 $oval =~ s/\s*\|\s*$//;
748 return sprintf("%04o", $to);
751 our $allowed_asm_includes = qr{(?x:
757 # memory.h: ARM has a custom one
759 # Load common spelling mistakes and build regular expression list.
763 if (open(my $spelling, '<', $spelling_file)) {
764 while (<$spelling>) {
767 $line =~ s/\s*\n?$//g;
770 next if ($line =~ m/^\s*#/);
771 next if ($line =~ m/^\s*$/);
773 my ($suspect, $fix) = split(/\|\|/, $line);
775 $spelling_fix{$suspect} = $fix;
779 warn "No typos will be found - file '$spelling_file': $!\n";
783 if (open(my $spelling, '<', $codespellfile)) {
784 while (<$spelling>) {
787 $line =~ s/\s*\n?$//g;
790 next if ($line =~ m/^\s*#/);
791 next if ($line =~ m/^\s*$/);
792 next if ($line =~ m/, disabled/i);
796 my ($suspect, $fix) = split(/->/, $line);
798 $spelling_fix{$suspect} = $fix;
802 warn "No codespell typos will be found - file '$codespellfile': $!\n";
806 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
809 my ($wordsRef, $file) = @_;
811 if (open(my $words, '<', $file)) {
815 $line =~ s/\s*\n?$//g;
818 next if ($line =~ m/^\s*#/);
819 next if ($line =~ m/^\s*$/);
821 print("$file: '$line' invalid - ignored\n");
825 $$wordsRef .= '|' if (defined $$wordsRef);
836 if (show_type("CONST_STRUCT")) {
837 read_words(\$const_structs, $conststructsfile)
838 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
841 if (defined($typedefsfile)) {
842 my $typeOtherTypedefs;
843 read_words(\$typeOtherTypedefs, $typedefsfile)
844 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
845 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
849 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
850 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
851 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
852 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
853 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
859 (?:$Modifier\s+|const\s+)*
861 (?:typeof|__typeof__)\s*\([^\)]*\)|
865 (?:\s+$Modifier|\s+const)*
867 $NonptrTypeMisordered = qr{
868 (?:$Modifier\s+|const\s+)*
872 (?:\s+$Modifier|\s+const)*
874 $NonptrTypeWithAttr = qr{
875 (?:$Modifier\s+|const\s+)*
877 (?:typeof|__typeof__)\s*\([^\)]*\)|
881 (?:\s+$Modifier|\s+const)*
885 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
886 (?:\s+$Inline|\s+$Modifier)*
888 $TypeMisordered = qr{
889 $NonptrTypeMisordered
890 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
891 (?:\s+$Inline|\s+$Modifier)*
893 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
894 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
898 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
900 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
901 # requires at least perl version v5.10.0
902 # Any use must be runtime checked with $^V
904 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
905 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
906 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
908 our $declaration_macros = qr{(?x:
909 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
910 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
911 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
914 our %allow_repeated_words = (
923 return "" if (!defined($string));
925 while ($string =~ /^\s*\(.*\)\s*$/) {
926 $string =~ s@^\s*\(\s*@@;
927 $string =~ s@\s*\)\s*$@@;
930 $string =~ s@\s+@ @g;
935 sub seed_camelcase_file {
938 return if (!(-f $file));
942 open(my $include_file, '<', "$file")
943 or warn "$P: Can't read '$file' $!\n";
944 my $text = <$include_file>;
945 close($include_file);
947 my @lines = split('\n', $text);
949 foreach my $line (@lines) {
950 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
951 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
953 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
955 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
961 our %maintained_status = ();
963 sub is_maintained_obsolete {
966 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
968 if (!exists($maintained_status{$filename})) {
969 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
972 return $maintained_status{$filename} =~ /obsolete/i;
975 sub is_SPDX_License_valid {
978 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
980 my $root_path = abs_path($root);
981 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
982 return 0 if ($status ne "");
986 my $camelcase_seeded = 0;
987 sub seed_camelcase_includes {
988 return if ($camelcase_seeded);
991 my $camelcase_cache = "";
992 my @include_files = ();
994 $camelcase_seeded = 1;
997 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
998 chomp $git_last_include_commit;
999 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1001 my $last_mod_date = 0;
1002 $files = `find $root/include -name "*.h"`;
1003 @include_files = split('\n', $files);
1004 foreach my $file (@include_files) {
1005 my $date = POSIX::strftime("%Y%m%d%H%M",
1006 localtime((stat $file)[9]));
1007 $last_mod_date = $date if ($last_mod_date < $date);
1009 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1012 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1013 open(my $camelcase_file, '<', "$camelcase_cache")
1014 or warn "$P: Can't read '$camelcase_cache' $!\n";
1015 while (<$camelcase_file>) {
1019 close($camelcase_file);
1024 if (-e "$gitroot") {
1025 $files = `${git_command} ls-files "include/*.h"`;
1026 @include_files = split('\n', $files);
1029 foreach my $file (@include_files) {
1030 seed_camelcase_file($file);
1033 if ($camelcase_cache ne "") {
1034 unlink glob ".checkpatch-camelcase.*";
1035 open(my $camelcase_file, '>', "$camelcase_cache")
1036 or warn "$P: Can't write '$camelcase_cache' $!\n";
1037 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1038 print $camelcase_file ("$_\n");
1040 close($camelcase_file);
1044 sub git_is_single_file {
1045 my ($filename) = @_;
1047 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1049 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1050 my $count = $output =~ tr/\n//;
1051 return $count eq 1 && $output =~ m{^${filename}$};
1054 sub git_commit_info {
1055 my ($commit, $id, $desc) = @_;
1057 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1059 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1060 $output =~ s/^\s*//gm;
1061 my @lines = split("\n", $output);
1063 return ($id, $desc) if ($#lines < 0);
1065 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1066 # Maybe one day convert this block of bash into something that returns
1067 # all matching commit ids, but it's very slow...
1069 # echo "checking commits $1..."
1070 # git rev-list --remotes | grep -i "^$1" |
1071 # while read line ; do
1072 # git log --format='%H %s' -1 $line |
1073 # echo "commit $(cut -c 1-12,41-)"
1075 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1078 $id = substr($lines[0], 0, 12);
1079 $desc = substr($lines[0], 41);
1082 return ($id, $desc);
1085 $chk_signoff = 0 if ($file);
1090 my @fixed_inserted = ();
1091 my @fixed_deleted = ();
1094 # If input is git commits, extract all commits from the commit expressions.
1095 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1096 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1100 foreach my $commit_expr (@ARGV) {
1102 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1103 $git_range = "-$2 $1";
1104 } elsif ($commit_expr =~ m/\.\./) {
1105 $git_range = "$commit_expr";
1107 $git_range = "-1 $commit_expr";
1109 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1110 foreach my $line (split(/\n/, $lines)) {
1111 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1112 next if (!defined($1) || !defined($2));
1115 unshift(@commits, $sha1);
1116 $git_commits{$sha1} = $subject;
1119 die "$P: no git commits after extraction!\n" if (@commits == 0);
1124 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1125 for my $filename (@ARGV) {
1127 my $is_git_file = git_is_single_file($filename);
1128 my $oldfile = $file;
1129 $file = 1 if ($is_git_file);
1131 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1132 die "$P: $filename: git format-patch failed - $!\n";
1134 open($FILE, '-|', "diff -u /dev/null $filename") ||
1135 die "$P: $filename: diff failed - $!\n";
1136 } elsif ($filename eq '-') {
1137 open($FILE, '<&STDIN');
1139 open($FILE, '<', "$filename") ||
1140 die "$P: $filename: open failed - $!\n";
1142 if ($filename eq '-') {
1143 $vname = 'Your patch';
1145 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1151 push(@rawlines, $_);
1152 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1156 if ($#ARGV > 0 && $quiet == 0) {
1157 print '-' x length($vname) . "\n";
1159 print '-' x length($vname) . "\n";
1162 if (!process($filename)) {
1168 @fixed_inserted = ();
1169 @fixed_deleted = ();
1171 @modifierListFile = ();
1174 $file = $oldfile if ($is_git_file);
1178 hash_show_words(\%use_type, "Used");
1179 hash_show_words(\%ignore_type, "Ignored");
1181 if (!$perl_version_ok) {
1184 NOTE: perl $^V is not modern enough to detect all possible issues.
1185 An upgrade to at least perl $minimum_perl_version is suggested.
1191 NOTE: If any of the errors are false positives, please report
1192 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1199 sub top_of_kernel_tree {
1203 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1204 "README", "Documentation", "arch", "include", "drivers",
1205 "fs", "init", "ipc", "kernel", "lib", "scripts",
1208 foreach my $check (@tree_check) {
1209 if (! -e $root . '/' . $check) {
1217 my ($formatted_email) = @_;
1221 my $name_comment = "";
1225 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1228 $comment = $3 if defined $3;
1229 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1231 $comment = $2 if defined $2;
1232 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1234 $comment = $2 if defined $2;
1235 $formatted_email =~ s/\Q$address\E.*$//;
1236 $name = $formatted_email;
1237 $name = trim($name);
1238 $name =~ s/^\"|\"$//g;
1239 # If there's a name left after stripping spaces and
1240 # leading quotes, and the address doesn't have both
1241 # leading and trailing angle brackets, the address
1245 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1252 # Extract comments from names excluding quoted parts
1253 # "John D. (Doe)" - Do not extract
1254 if ($name =~ s/\"(.+)\"//) {
1257 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1258 $name_comment .= trim($1);
1260 $name =~ s/^[ \"]+|[ \"]+$//g;
1261 $name = trim("$quoted $name");
1263 $address = trim($address);
1264 $address =~ s/^\<|\>$//g;
1265 $comment = trim($comment);
1267 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1268 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1269 $name = "\"$name\"";
1272 return ($name, $name_comment, $address, $comment);
1276 my ($name, $name_comment, $address, $comment) = @_;
1278 my $formatted_email;
1280 $name =~ s/^[ \"]+|[ \"]+$//g;
1281 $address = trim($address);
1282 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1284 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1285 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1286 $name = "\"$name\"";
1289 $name_comment = trim($name_comment);
1290 $name_comment = " $name_comment" if ($name_comment ne "");
1291 $comment = trim($comment);
1292 $comment = " $comment" if ($comment ne "");
1294 if ("$name" eq "") {
1295 $formatted_email = "$address";
1297 $formatted_email = "$name$name_comment <$address>";
1299 $formatted_email .= "$comment";
1300 return $formatted_email;
1303 sub reformat_email {
1306 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1307 return format_email($email_name, $name_comment, $email_address, $comment);
1310 sub same_email_addresses {
1311 my ($email1, $email2) = @_;
1313 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1314 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1316 return $email1_name eq $email2_name &&
1317 $email1_address eq $email2_address &&
1318 $name1_comment eq $name2_comment &&
1319 $comment1 eq $comment2;
1325 foreach my $path (split(/:/, $ENV{PATH})) {
1326 if (-e "$path/$bin") {
1327 return "$path/$bin";
1337 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1338 if (-e "$path/$conf") {
1339 return "$path/$conf";
1351 for my $c (split(//, $str)) {
1355 for (; ($n % $tabsize) != 0; $n++) {
1367 (my $res = shift) =~ tr/\t/ /c;
1374 # Drop the diff line leader and expand tabs
1376 $line = expand_tabs($line);
1378 # Pick the indent from the front of the line.
1379 my ($white) = ($line =~ /^(\s*)/);
1381 return (length($line), length($white));
1384 my $sanitise_quote = '';
1386 sub sanitise_line_reset {
1387 my ($in_comment) = @_;
1390 $sanitise_quote = '*/';
1392 $sanitise_quote = '';
1405 # Always copy over the diff marker.
1406 $res = substr($line, 0, 1);
1408 for ($off = 1; $off < length($line); $off++) {
1409 $c = substr($line, $off, 1);
1411 # Comments we are whacking completely including the begin
1412 # and end, all to $;.
1413 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1414 $sanitise_quote = '*/';
1416 substr($res, $off, 2, "$;$;");
1420 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1421 $sanitise_quote = '';
1422 substr($res, $off, 2, "$;$;");
1426 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1427 $sanitise_quote = '//';
1429 substr($res, $off, 2, $sanitise_quote);
1434 # A \ in a string means ignore the next character.
1435 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1437 substr($res, $off, 2, 'XX');
1442 if ($c eq "'" || $c eq '"') {
1443 if ($sanitise_quote eq '') {
1444 $sanitise_quote = $c;
1446 substr($res, $off, 1, $c);
1448 } elsif ($sanitise_quote eq $c) {
1449 $sanitise_quote = '';
1453 #print "c<$c> SQ<$sanitise_quote>\n";
1454 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1455 substr($res, $off, 1, $;);
1456 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1457 substr($res, $off, 1, $;);
1458 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1459 substr($res, $off, 1, 'X');
1461 substr($res, $off, 1, $c);
1465 if ($sanitise_quote eq '//') {
1466 $sanitise_quote = '';
1469 # The pathname on a #include may be surrounded by '<' and '>'.
1470 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1471 my $clean = 'X' x length($1);
1472 $res =~ s@\<.*\>@<$clean>@;
1474 # The whole of a #error is a string.
1475 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1476 my $clean = 'X' x length($1);
1477 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1480 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1482 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1488 sub get_quoted_string {
1489 my ($line, $rawline) = @_;
1491 return "" if (!defined($line) || !defined($rawline));
1492 return "" if ($line !~ m/($String)/g);
1493 return substr($rawline, $-[0], $+[0] - $-[0]);
1496 sub ctx_statement_block {
1497 my ($linenr, $remain, $off) = @_;
1498 my $line = $linenr - 1;
1501 my $coff = $off - 1;
1515 @stack = (['', 0]) if ($#stack == -1);
1517 #warn "CSB: blk<$blk> remain<$remain>\n";
1518 # If we are about to drop off the end, pull in more
1521 for (; $remain > 0; $line++) {
1522 last if (!defined $lines[$line]);
1523 next if ($lines[$line] =~ /^-/);
1526 $blk .= $lines[$line] . "\n";
1527 $len = length($blk);
1531 # Bail if there is no further context.
1532 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1536 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1542 $c = substr($blk, $off, 1);
1543 $remainder = substr($blk, $off);
1545 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1547 # Handle nested #if/#else.
1548 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1549 push(@stack, [ $type, $level ]);
1550 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1551 ($type, $level) = @{$stack[$#stack - 1]};
1552 } elsif ($remainder =~ /^#\s*endif\b/) {
1553 ($type, $level) = @{pop(@stack)};
1556 # Statement ends at the ';' or a close '}' at the
1558 if ($level == 0 && $c eq ';') {
1562 # An else is really a conditional as long as its not else if
1563 if ($level == 0 && $coff_set == 0 &&
1564 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1565 $remainder =~ /^(else)(?:\s|{)/ &&
1566 $remainder !~ /^else\s+if\b/) {
1567 $coff = $off + length($1) - 1;
1569 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1570 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1573 if (($type eq '' || $type eq '(') && $c eq '(') {
1577 if ($type eq '(' && $c eq ')') {
1579 $type = ($level != 0)? '(' : '';
1581 if ($level == 0 && $coff < $soff) {
1584 #warn "CSB: mark coff<$coff>\n";
1587 if (($type eq '' || $type eq '{') && $c eq '{') {
1591 if ($type eq '{' && $c eq '}') {
1593 $type = ($level != 0)? '{' : '';
1596 if (substr($blk, $off + 1, 1) eq ';') {
1602 # Preprocessor commands end at the newline unless escaped.
1603 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1611 # We are truly at the end, so shuffle to the next line.
1618 my $statement = substr($blk, $soff, $off - $soff + 1);
1619 my $condition = substr($blk, $soff, $coff - $soff + 1);
1621 #warn "STATEMENT<$statement>\n";
1622 #warn "CONDITION<$condition>\n";
1624 #print "coff<$coff> soff<$off> loff<$loff>\n";
1626 return ($statement, $condition,
1627 $line, $remain + 1, $off - $loff + 1, $level);
1630 sub statement_lines {
1633 # Strip the diff line prefixes and rip blank lines at start and end.
1634 $stmt =~ s/(^|\n)./$1/g;
1638 my @stmt_lines = ($stmt =~ /\n/g);
1640 return $#stmt_lines + 2;
1643 sub statement_rawlines {
1646 my @stmt_lines = ($stmt =~ /\n/g);
1648 return $#stmt_lines + 2;
1651 sub statement_block_size {
1654 $stmt =~ s/(^|\n)./$1/g;
1660 my @stmt_lines = ($stmt =~ /\n/g);
1661 my @stmt_statements = ($stmt =~ /;/g);
1663 my $stmt_lines = $#stmt_lines + 2;
1664 my $stmt_statements = $#stmt_statements + 1;
1666 if ($stmt_lines > $stmt_statements) {
1669 return $stmt_statements;
1673 sub ctx_statement_full {
1674 my ($linenr, $remain, $off) = @_;
1675 my ($statement, $condition, $level);
1679 # Grab the first conditional/block pair.
1680 ($statement, $condition, $linenr, $remain, $off, $level) =
1681 ctx_statement_block($linenr, $remain, $off);
1682 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1683 push(@chunks, [ $condition, $statement ]);
1684 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1685 return ($level, $linenr, @chunks);
1688 # Pull in the following conditional/block pairs and see if they
1689 # could continue the statement.
1691 ($statement, $condition, $linenr, $remain, $off, $level) =
1692 ctx_statement_block($linenr, $remain, $off);
1693 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1694 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1696 push(@chunks, [ $condition, $statement ]);
1699 return ($level, $linenr, @chunks);
1703 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1705 my $start = $linenr - 1;
1712 my @stack = ($level);
1713 for ($line = $start; $remain > 0; $line++) {
1714 next if ($rawlines[$line] =~ /^-/);
1717 $blk .= $rawlines[$line];
1719 # Handle nested #if/#else.
1720 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1721 push(@stack, $level);
1722 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1723 $level = $stack[$#stack - 1];
1724 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1725 $level = pop(@stack);
1728 foreach my $c (split(//, $lines[$line])) {
1729 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1735 if ($c eq $close && $level > 0) {
1737 last if ($level == 0);
1738 } elsif ($c eq $open) {
1743 if (!$outer || $level <= 1) {
1744 push(@res, $rawlines[$line]);
1747 last if ($level == 0);
1750 return ($level, @res);
1752 sub ctx_block_outer {
1753 my ($linenr, $remain) = @_;
1755 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1759 my ($linenr, $remain) = @_;
1761 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1765 my ($linenr, $remain, $off) = @_;
1767 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1770 sub ctx_block_level {
1771 my ($linenr, $remain) = @_;
1773 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1775 sub ctx_statement_level {
1776 my ($linenr, $remain, $off) = @_;
1778 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1781 sub ctx_locate_comment {
1782 my ($first_line, $end_line) = @_;
1784 # If c99 comment on the current line, or the line before or after
1785 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1786 return $current_comment if (defined $current_comment);
1787 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1788 return $current_comment if (defined $current_comment);
1789 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1790 return $current_comment if (defined $current_comment);
1792 # Catch a comment on the end of the line itself.
1793 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1794 return $current_comment if (defined $current_comment);
1796 # Look through the context and try and figure out if there is a
1799 $current_comment = '';
1800 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1801 my $line = $rawlines[$linenr - 1];
1803 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1806 if ($line =~ m@/\*@) {
1809 if (!$in_comment && $current_comment ne '') {
1810 $current_comment = '';
1812 $current_comment .= $line . "\n" if ($in_comment);
1813 if ($line =~ m@\*/@) {
1818 chomp($current_comment);
1819 return($current_comment);
1821 sub ctx_has_comment {
1822 my ($first_line, $end_line) = @_;
1823 my $cmt = ctx_locate_comment($first_line, $end_line);
1825 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1826 ##print "CMMT: $cmt\n";
1828 return ($cmt ne '');
1832 my ($linenr, $cnt) = @_;
1834 my $offset = $linenr - 1;
1839 $line = $rawlines[$offset++];
1840 next if (defined($line) && $line =~ /^-/);
1848 my ($linenr, $lc) = @_;
1850 my $stat_real = raw_line($linenr, 0);
1851 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1852 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1859 my ($linenr, $cnt, $here) = @_;
1861 my $herectx = $here . "\n";
1862 for (my $n = 0; $n < $cnt; $n++) {
1863 $herectx .= raw_line($linenr, $n) . "\n";
1874 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1877 $coded = sprintf("^%c", unpack('C', $2) + 64);
1886 my $av_preprocessor = 0;
1891 sub annotate_reset {
1892 $av_preprocessor = 0;
1894 @av_paren_type = ('E');
1895 $av_pend_colon = 'O';
1898 sub annotate_values {
1899 my ($stream, $type) = @_;
1902 my $var = '_' x length($stream);
1905 print "$stream\n" if ($dbg_values > 1);
1907 while (length($cur)) {
1908 @av_paren_type = ('E') if ($#av_paren_type < 0);
1909 print " <" . join('', @av_paren_type) .
1910 "> <$type> <$av_pending>" if ($dbg_values > 1);
1911 if ($cur =~ /^(\s+)/o) {
1912 print "WS($1)\n" if ($dbg_values > 1);
1913 if ($1 =~ /\n/ && $av_preprocessor) {
1914 $type = pop(@av_paren_type);
1915 $av_preprocessor = 0;
1918 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1919 print "CAST($1)\n" if ($dbg_values > 1);
1920 push(@av_paren_type, $type);
1923 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1924 print "DECLARE($1)\n" if ($dbg_values > 1);
1927 } elsif ($cur =~ /^($Modifier)\s*/) {
1928 print "MODIFIER($1)\n" if ($dbg_values > 1);
1931 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1932 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1933 $av_preprocessor = 1;
1934 push(@av_paren_type, $type);
1940 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1941 print "UNDEF($1)\n" if ($dbg_values > 1);
1942 $av_preprocessor = 1;
1943 push(@av_paren_type, $type);
1945 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1946 print "PRE_START($1)\n" if ($dbg_values > 1);
1947 $av_preprocessor = 1;
1949 push(@av_paren_type, $type);
1950 push(@av_paren_type, $type);
1953 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1954 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1955 $av_preprocessor = 1;
1957 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1961 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1962 print "PRE_END($1)\n" if ($dbg_values > 1);
1964 $av_preprocessor = 1;
1966 # Assume all arms of the conditional end as this
1967 # one does, and continue as if the #endif was not here.
1968 pop(@av_paren_type);
1969 push(@av_paren_type, $type);
1972 } elsif ($cur =~ /^(\\\n)/o) {
1973 print "PRECONT($1)\n" if ($dbg_values > 1);
1975 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1976 print "ATTR($1)\n" if ($dbg_values > 1);
1977 $av_pending = $type;
1980 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1981 print "SIZEOF($1)\n" if ($dbg_values > 1);
1987 } elsif ($cur =~ /^(if|while|for)\b/o) {
1988 print "COND($1)\n" if ($dbg_values > 1);
1992 } elsif ($cur =~/^(case)/o) {
1993 print "CASE($1)\n" if ($dbg_values > 1);
1994 $av_pend_colon = 'C';
1997 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1998 print "KEYWORD($1)\n" if ($dbg_values > 1);
2001 } elsif ($cur =~ /^(\()/o) {
2002 print "PAREN('$1')\n" if ($dbg_values > 1);
2003 push(@av_paren_type, $av_pending);
2007 } elsif ($cur =~ /^(\))/o) {
2008 my $new_type = pop(@av_paren_type);
2009 if ($new_type ne '_') {
2011 print "PAREN('$1') -> $type\n"
2012 if ($dbg_values > 1);
2014 print "PAREN('$1')\n" if ($dbg_values > 1);
2017 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2018 print "FUNC($1)\n" if ($dbg_values > 1);
2022 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2023 if (defined $2 && $type eq 'C' || $type eq 'T') {
2024 $av_pend_colon = 'B';
2025 } elsif ($type eq 'E') {
2026 $av_pend_colon = 'L';
2028 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2031 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2032 print "IDENT($1)\n" if ($dbg_values > 1);
2035 } elsif ($cur =~ /^($Assignment)/o) {
2036 print "ASSIGN($1)\n" if ($dbg_values > 1);
2039 } elsif ($cur =~/^(;|{|})/) {
2040 print "END($1)\n" if ($dbg_values > 1);
2042 $av_pend_colon = 'O';
2044 } elsif ($cur =~/^(,)/) {
2045 print "COMMA($1)\n" if ($dbg_values > 1);
2048 } elsif ($cur =~ /^(\?)/o) {
2049 print "QUESTION($1)\n" if ($dbg_values > 1);
2052 } elsif ($cur =~ /^(:)/o) {
2053 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2055 substr($var, length($res), 1, $av_pend_colon);
2056 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2061 $av_pend_colon = 'O';
2063 } elsif ($cur =~ /^(\[)/o) {
2064 print "CLOSE($1)\n" if ($dbg_values > 1);
2067 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2070 print "OPV($1)\n" if ($dbg_values > 1);
2077 substr($var, length($res), 1, $variant);
2080 } elsif ($cur =~ /^($Operators)/o) {
2081 print "OP($1)\n" if ($dbg_values > 1);
2082 if ($1 ne '++' && $1 ne '--') {
2086 } elsif ($cur =~ /(^.)/o) {
2087 print "C($1)\n" if ($dbg_values > 1);
2090 $cur = substr($cur, length($1));
2091 $res .= $type x length($1);
2095 return ($res, $var);
2099 my ($possible, $line) = @_;
2100 my $notPermitted = qr{(?:
2117 ^(?:typedef|struct|enum)\b
2119 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2120 if ($possible !~ $notPermitted) {
2121 # Check for modifiers.
2122 $possible =~ s/\s*$Storage\s*//g;
2123 $possible =~ s/\s*$Sparse\s*//g;
2124 if ($possible =~ /^\s*$/) {
2126 } elsif ($possible =~ /\s/) {
2127 $possible =~ s/\s*$Type\s*//g;
2128 for my $modifier (split(' ', $possible)) {
2129 if ($modifier !~ $notPermitted) {
2130 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2131 push(@modifierListFile, $modifier);
2136 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2137 push(@typeListFile, $possible);
2141 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2150 $type =~ tr/[a-z]/[A-Z]/;
2152 return defined $use_type{$type} if (scalar keys %use_type > 0);
2154 return !defined $ignore_type{$type};
2158 my ($level, $type, $msg) = @_;
2160 if (!show_type($type) ||
2161 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2166 if ($level eq 'ERROR') {
2168 } elsif ($level eq 'WARNING') {
2174 $output .= $prefix . $level . ':';
2176 $output .= BLUE if ($color);
2177 $output .= "$type:";
2179 $output .= RESET if ($color);
2180 $output .= ' ' . $msg . "\n";
2183 my @lines = split("\n", $output, -1);
2184 splice(@lines, 1, 1);
2185 $output = join("\n", @lines);
2187 $output = (split('\n', $output))[0] . "\n" if ($terse);
2189 push(our @report, $output);
2198 sub fixup_current_range {
2199 my ($lineRef, $offset, $length) = @_;
2201 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2204 my $no = $o + $offset;
2205 my $nl = $l + $length;
2206 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2210 sub fix_inserted_deleted_lines {
2211 my ($linesRef, $insertedRef, $deletedRef) = @_;
2213 my $range_last_linenr = 0;
2214 my $delta_offset = 0;
2219 my $next_insert = 0;
2220 my $next_delete = 0;
2224 my $inserted = @{$insertedRef}[$next_insert++];
2225 my $deleted = @{$deletedRef}[$next_delete++];
2227 foreach my $old_line (@{$linesRef}) {
2229 my $line = $old_line; #don't modify the array
2230 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2232 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2233 $range_last_linenr = $new_linenr;
2234 fixup_current_range(\$line, $delta_offset, 0);
2237 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2238 $deleted = @{$deletedRef}[$next_delete++];
2240 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2243 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2244 push(@lines, ${$inserted}{'LINE'});
2245 $inserted = @{$insertedRef}[$next_insert++];
2247 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2251 push(@lines, $line);
2261 sub fix_insert_line {
2262 my ($linenr, $line) = @_;
2268 push(@fixed_inserted, $inserted);
2271 sub fix_delete_line {
2272 my ($linenr, $line) = @_;
2279 push(@fixed_deleted, $deleted);
2283 my ($type, $msg) = @_;
2285 if (report("ERROR", $type, $msg)) {
2293 my ($type, $msg) = @_;
2295 if (report("WARNING", $type, $msg)) {
2303 my ($type, $msg) = @_;
2305 if ($check && report("CHECK", $type, $msg)) {
2313 sub check_absolute_file {
2314 my ($absolute, $herecurr) = @_;
2315 my $file = $absolute;
2317 ##print "absolute<$absolute>\n";
2319 # See if any suffix of this path is a path within the tree.
2320 while ($file =~ s@^[^/]*/@@) {
2321 if (-f "$root/$file") {
2322 ##print "file<$file>\n";
2330 # It is, so see if the prefix is acceptable.
2331 my $prefix = $absolute;
2332 substr($prefix, -length($file)) = '';
2334 ##print "prefix<$prefix>\n";
2335 if ($prefix ne ".../") {
2336 WARN("USE_RELATIVE_PATH",
2337 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2344 $string =~ s/^\s+|\s+$//g;
2352 $string =~ s/^\s+//;
2360 $string =~ s/\s+$//;
2365 sub string_find_replace {
2366 my ($string, $find, $replace) = @_;
2368 $string =~ s/$find/$replace/g;
2376 my $source_indent = $tabsize;
2377 my $max_spaces_before_tab = $source_indent - 1;
2378 my $spaces_to_tab = " " x $source_indent;
2380 #convert leading spaces to tabs
2381 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2382 #Remove spaces before a tab
2383 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2388 sub pos_last_openparen {
2393 my $opens = $line =~ tr/\(/\(/;
2394 my $closes = $line =~ tr/\)/\)/;
2396 my $last_openparen = 0;
2398 if (($opens == 0) || ($closes >= $opens)) {
2402 my $len = length($line);
2404 for ($pos = 0; $pos < $len; $pos++) {
2405 my $string = substr($line, $pos);
2406 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2407 $pos += length($1) - 1;
2408 } elsif (substr($line, $pos, 1) eq '(') {
2409 $last_openparen = $pos;
2410 } elsif (index($string, '(') == -1) {
2415 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2418 sub get_raw_comment {
2419 my ($line, $rawline) = @_;
2422 for my $i (0 .. (length($line) - 1)) {
2423 if (substr($line, $i, 1) eq "$;") {
2424 $comment .= substr($rawline, $i, 1);
2432 my $filename = shift;
2438 my $stashrawline="";
2448 my $authorsignoff = 0;
2449 my $author_sob = '';
2451 my $is_binding_patch = -1;
2452 my $in_header_lines = $file ? 0 : 1;
2453 my $in_commit_log = 0; #Scanning lines before patch
2454 my $has_patch_separator = 0; #Found a --- line
2455 my $has_commit_log = 0; #Encountered lines before patch
2456 my $commit_log_lines = 0; #Number of commit log lines
2457 my $commit_log_possible_stack_dump = 0;
2458 my $commit_log_long_line = 0;
2459 my $commit_log_has_diff = 0;
2460 my $reported_maintainer_file = 0;
2461 my $non_utf8_charset = 0;
2463 my $last_blank_line = 0;
2464 my $last_coalesced_string_linenr = -1;
2472 # Trace the real file/line as we go.
2477 my $context_function; #undef'd unless there's a known function
2479 my $comment_edge = 0;
2483 my $prev_values = 'E';
2486 my %suppress_ifbraces;
2487 my %suppress_whiletrailers;
2488 my %suppress_export;
2489 my $suppress_statement = 0;
2491 my %signatures = ();
2493 # Pre-scan the patch sanitizing the lines.
2494 # Pre-scan the patch looking for any __setup documentation.
2496 my @setup_docs = ();
2499 my $camelcase_file_seeded = 0;
2501 my $checklicenseline = 1;
2503 sanitise_line_reset();
2505 foreach my $rawline (@rawlines) {
2509 push(@fixed, $rawline) if ($fix);
2511 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2513 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2518 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2527 # Guestimate if this is a continuing comment. Run
2528 # the context looking for a comment "edge". If this
2529 # edge is a close comment then we must be in a comment
2533 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2534 next if (defined $rawlines[$ln - 1] &&
2535 $rawlines[$ln - 1] =~ /^-/);
2537 #print "RAW<$rawlines[$ln - 1]>\n";
2538 last if (!defined $rawlines[$ln - 1]);
2539 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2540 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2545 if (defined $edge && $edge eq '*/') {
2549 # Guestimate if this is a continuing comment. If this
2550 # is the start of a diff block and this line starts
2551 # ' *' then it is very likely a comment.
2552 if (!defined $edge &&
2553 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2558 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2559 sanitise_line_reset($in_comment);
2561 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2562 # Standardise the strings and chars within the input to
2563 # simplify matching -- only bother with positive lines.
2564 $line = sanitise_line($rawline);
2566 push(@lines, $line);
2569 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2574 #print "==>$rawline\n";
2575 #print "-->$line\n";
2577 if ($setup_docs && $line =~ /^\+/) {
2578 push(@setup_docs, $line);
2587 foreach my $line (@lines) {
2590 my $sline = $line; #copy of $line
2591 $sline =~ s/$;/ /g; #with comments as spaces
2593 my $rawline = $rawlines[$linenr - 1];
2594 my $raw_comment = get_raw_comment($line, $rawline);
2596 # check if it's a mode change, rename or start of a patch
2597 if (!$in_commit_log &&
2598 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2599 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2600 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2604 #extract the line range in the file after the patch is applied
2605 if (!$in_commit_log &&
2606 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2609 $first_line = $linenr + 1;
2619 %suppress_ifbraces = ();
2620 %suppress_whiletrailers = ();
2621 %suppress_export = ();
2622 $suppress_statement = 0;
2623 if ($context =~ /\b(\w+)\s*\(/) {
2624 $context_function = $1;
2626 undef $context_function;
2630 # track the line number as we move through the hunk, note that
2631 # new versions of GNU diff omit the leading space on completely
2632 # blank context lines so we need to count that too.
2633 } elsif ($line =~ /^( |\+|$)/) {
2635 $realcnt-- if ($realcnt != 0);
2637 # Measure the line length and indent.
2638 ($length, $indent) = line_stats($rawline);
2640 # Track the previous line.
2641 ($prevline, $stashline) = ($stashline, $line);
2642 ($previndent, $stashindent) = ($stashindent, $indent);
2643 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2645 #warn "line<$line>\n";
2647 } elsif ($realcnt == 1) {
2651 my $hunk_line = ($realcnt != 0);
2653 $here = "#$linenr: " if (!$file);
2654 $here = "#$realline: " if ($file);
2657 # extract the filename as it passes
2658 if ($line =~ /^diff --git.*?(\S+)$/) {
2660 $realfile =~ s@^([^/]*)/@@ if (!$file);
2663 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2665 $realfile =~ s@^([^/]*)/@@ if (!$file);
2669 if (!$file && $tree && $p1_prefix ne '' &&
2670 -e "$root/$p1_prefix") {
2671 WARN("PATCH_PREFIX",
2672 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2675 if ($realfile =~ m@^include/asm/@) {
2676 ERROR("MODIFIED_INCLUDE_ASM",
2677 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2682 #make up the handle for any error we report on this line
2684 $prefix = "$realfile:$realline: "
2687 $prefix = "$filename:$realline: ";
2689 $prefix = "$filename:$linenr: ";
2694 if (is_maintained_obsolete($realfile)) {
2696 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2698 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2701 $check = $check_orig;
2703 $checklicenseline = 1;
2705 if ($realfile !~ /^MAINTAINERS/) {
2706 my $last_binding_patch = $is_binding_patch;
2708 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2710 if (($last_binding_patch != -1) &&
2711 ($last_binding_patch ^ $is_binding_patch)) {
2712 WARN("DT_SPLIT_BINDING_PATCH",
2713 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2720 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2722 my $hereline = "$here\n$rawline\n";
2723 my $herecurr = "$here\n$rawline\n";
2724 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2726 $cnt_lines++ if ($realcnt != 0);
2728 # Verify the existence of a commit log if appropriate
2729 # 2 is used because a $signature is counted in $commit_log_lines
2730 if ($in_commit_log) {
2731 if ($line !~ /^\s*$/) {
2732 $commit_log_lines++; #could be a $signature
2734 } elsif ($has_commit_log && $commit_log_lines < 2) {
2735 WARN("COMMIT_MESSAGE",
2736 "Missing commit description - Add an appropriate one\n");
2737 $commit_log_lines = 2; #warn only once
2740 # Check if the commit log has what seems like a diff which can confuse patch
2741 if ($in_commit_log && !$commit_log_has_diff &&
2742 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2743 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2744 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2745 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2746 ERROR("DIFF_IN_COMMIT_MSG",
2747 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2748 $commit_log_has_diff = 1;
2751 # Check for incorrect file permissions
2752 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2753 my $permhere = $here . "FILE: $realfile\n";
2754 if ($realfile !~ m@scripts/@ &&
2755 $realfile !~ /\.(py|pl|awk|sh)$/) {
2756 ERROR("EXECUTE_PERMISSIONS",
2757 "do not set execute permissions for source files\n" . $permhere);
2761 # Check the patch for a From:
2762 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2764 my $curline = $linenr;
2765 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2768 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2770 $author = reformat_email($author);
2773 # Check the patch for a signoff:
2774 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2777 if ($author ne '' && $authorsignoff != 1) {
2778 if (same_email_addresses($1, $author)) {
2782 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2783 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2785 if ($email_address eq $author_address && $email_name eq $author_name) {
2788 } elsif ($email_address eq $author_address) {
2791 } elsif ($email_name eq $author_name) {
2795 my $address1 = $email_address;
2796 my $address2 = $author_address;
2798 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2801 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2804 if ($address1 eq $address2) {
2812 # Check for patch separator
2813 if ($line =~ /^---$/) {
2814 $has_patch_separator = 1;
2818 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2819 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2820 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2821 $reported_maintainer_file = 1;
2824 # Check signature styles
2825 if (!$in_header_lines &&
2826 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2827 my $space_before = $1;
2829 my $space_after = $3;
2831 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2833 if ($sign_off !~ /$signature_tags/) {
2834 my $suggested_signature = find_standard_signature($sign_off);
2835 if ($suggested_signature eq "") {
2836 WARN("BAD_SIGN_OFF",
2837 "Non-standard signature: $sign_off\n" . $herecurr);
2839 if (WARN("BAD_SIGN_OFF",
2840 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
2842 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
2846 if (defined $space_before && $space_before ne "") {
2847 if (WARN("BAD_SIGN_OFF",
2848 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2850 $fixed[$fixlinenr] =
2851 "$ucfirst_sign_off $email";
2854 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2855 if (WARN("BAD_SIGN_OFF",
2856 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2858 $fixed[$fixlinenr] =
2859 "$ucfirst_sign_off $email";
2863 if (!defined $space_after || $space_after ne " ") {
2864 if (WARN("BAD_SIGN_OFF",
2865 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2867 $fixed[$fixlinenr] =
2868 "$ucfirst_sign_off $email";
2872 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2873 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
2874 if ($suggested_email eq "") {
2875 ERROR("BAD_SIGN_OFF",
2876 "Unrecognized email address: '$email'\n" . $herecurr);
2878 my $dequoted = $suggested_email;
2879 $dequoted =~ s/^"//;
2880 $dequoted =~ s/" </ </;
2881 # Don't force email to have quotes
2882 # Allow just an angle bracketed address
2883 if (!same_email_addresses($email, $suggested_email)) {
2884 if (WARN("BAD_SIGN_OFF",
2885 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
2887 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
2891 # Address part shouldn't have comments
2892 my $stripped_address = $email_address;
2893 $stripped_address =~ s/\([^\(\)]*\)//g;
2894 if ($email_address ne $stripped_address) {
2895 if (WARN("BAD_SIGN_OFF",
2896 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
2898 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
2902 # Only one name comment should be allowed
2903 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
2904 if ($comment_count > 1) {
2905 WARN("BAD_SIGN_OFF",
2906 "Use a single name comment in email: '$email'\n" . $herecurr);
2911 # have an email name. In addition comments should strictly
2913 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
2914 if (($comment ne "" && $comment !~ /^#.+/) ||
2915 ($email_name ne "")) {
2916 my $cur_name = $email_name;
2917 my $new_comment = $comment;
2918 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
2920 # Remove brackets enclosing comment text
2921 # and # from start of comments to get comment text
2922 $new_comment =~ s/^\((.*)\)$/$1/;
2923 $new_comment =~ s/^\[(.*)\]$/$1/;
2924 $new_comment =~ s/^[\s\#]+|\s+$//g;
2926 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
2927 $new_comment = " # $new_comment" if ($new_comment ne "");
2928 my $new_email = "$email_address$new_comment";
2930 if (WARN("BAD_STABLE_ADDRESS_STYLE",
2931 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
2933 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2936 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
2937 my $new_comment = $comment;
2939 # Extract comment text from within brackets or
2940 # c89 style /*...*/ comments
2941 $new_comment =~ s/^\[(.*)\]$/$1/;
2942 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
2944 $new_comment = trim($new_comment);
2945 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
2946 $new_comment = "($new_comment)" if ($new_comment ne "");
2947 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
2949 if (WARN("BAD_SIGN_OFF",
2950 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
2952 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
2957 # Check for duplicate signatures
2958 my $sig_nospace = $line;
2959 $sig_nospace =~ s/\s//g;
2960 $sig_nospace = lc($sig_nospace);
2961 if (defined $signatures{$sig_nospace}) {
2962 WARN("BAD_SIGN_OFF",
2963 "Duplicate signature\n" . $herecurr);
2965 $signatures{$sig_nospace} = 1;
2968 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2969 if ($sign_off =~ /^co-developed-by:$/i) {
2970 if ($email eq $author) {
2971 WARN("BAD_SIGN_OFF",
2972 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2974 if (!defined $lines[$linenr]) {
2975 WARN("BAD_SIGN_OFF",
2976 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2977 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2978 WARN("BAD_SIGN_OFF",
2979 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2980 } elsif ($1 ne $email) {
2981 WARN("BAD_SIGN_OFF",
2982 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2987 # Check email subject for common tools that don't need to be mentioned
2988 if ($in_header_lines &&
2989 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2990 WARN("EMAIL_SUBJECT",
2991 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2994 # Check for Gerrit Change-Ids not in any patch context
2995 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2996 if (ERROR("GERRIT_CHANGE_ID",
2997 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
2999 fix_delete_line($fixlinenr, $rawline);
3003 # Check if the commit log is in a possible stack dump
3004 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3005 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3006 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3008 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3009 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3010 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3011 # stack dump address styles
3012 $commit_log_possible_stack_dump = 1;
3015 # Check for line lengths > 75 in commit log, warn once
3016 if ($in_commit_log && !$commit_log_long_line &&
3017 length($line) > 75 &&
3018 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3019 # file delta changes
3020 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
3022 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3023 # A Fixes: or Link: line or signature tag line
3024 $commit_log_possible_stack_dump)) {
3025 WARN("COMMIT_LOG_LONG_LINE",
3026 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3027 $commit_log_long_line = 1;
3030 # Reset possible stack dump if a blank line is found
3031 if ($in_commit_log && $commit_log_possible_stack_dump &&
3033 $commit_log_possible_stack_dump = 0;
3036 # Check for lines starting with a #
3037 if ($in_commit_log && $line =~ /^#/) {
3038 if (WARN("COMMIT_COMMENT_SYMBOL",
3039 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3041 $fixed[$fixlinenr] =~ s/^/ /;
3045 # Check for git id commit length and improperly formed commit descriptions
3046 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3047 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3048 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3049 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3050 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3051 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3052 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3053 my $init_char = "c";
3054 my $orig_commit = "";
3061 my $id = '0123456789ab';
3062 my $orig_desc = "commit description";
3063 my $description = "";
3065 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3067 $orig_commit = lc($2);
3068 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
3069 $orig_commit = lc($1);
3072 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3073 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
3074 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
3075 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3076 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
3079 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
3080 defined $rawlines[$linenr] &&
3081 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
3084 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
3085 defined $rawlines[$linenr] &&
3086 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
3087 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
3089 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
3090 $orig_desc .= " " . $1;
3094 ($id, $description) = git_commit_info($orig_commit,
3098 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
3099 ERROR("GIT_COMMIT_ID",
3100 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
3104 # Check for added, moved or deleted files
3105 if (!$reported_maintainer_file && !$in_commit_log &&
3106 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3107 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3108 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3109 (defined($1) || defined($2))))) {
3111 $reported_maintainer_file = 1;
3112 WARN("FILE_PATH_CHANGES",
3113 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3116 # Check for adding new DT bindings not in schema format
3117 if (!$in_commit_log &&
3118 ($line =~ /^new file mode\s*\d+\s*$/) &&
3119 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3120 WARN("DT_SCHEMA_BINDING_PATCH",
3121 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
3124 # Check for wrappage within a valid hunk of the file
3125 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3126 ERROR("CORRUPTED_PATCH",
3127 "patch seems to be corrupt (line wrapped?)\n" .
3128 $herecurr) if (!$emitted_corrupt++);
3131 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3132 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3133 $rawline !~ m/^$UTF8*$/) {
3134 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3136 my $blank = copy_spacing($rawline);
3137 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3138 my $hereptr = "$hereline$ptr\n";
3141 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3144 # Check if it's the start of a commit log
3145 # (not a header line and we haven't seen the patch filename)
3146 if ($in_header_lines && $realfile =~ /^$/ &&
3147 !($rawline =~ /^\s+(?:\S|$)/ ||
3148 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3149 $in_header_lines = 0;
3151 $has_commit_log = 1;
3154 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3155 # declined it, i.e defined some charset where it is missing.
3156 if ($in_header_lines &&
3157 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3159 $non_utf8_charset = 1;
3162 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3163 $rawline =~ /$NON_ASCII_UTF8/) {
3164 WARN("UTF8_BEFORE_PATCH",
3165 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3168 # Check for absolute kernel paths in commit message
3169 if ($tree && $in_commit_log) {
3170 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3173 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3174 check_absolute_file($1, $herecurr)) {
3177 check_absolute_file($file, $herecurr);
3182 # Check for various typo / spelling mistakes
3183 if (defined($misspellings) &&
3184 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3185 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3187 my $blank = copy_spacing($rawline);
3188 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3189 my $hereptr = "$hereline$ptr\n";
3190 my $typo_fix = $spelling_fix{lc($typo)};
3191 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3192 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3193 my $msg_level = \&WARN;
3194 $msg_level = \&CHK if ($file);
3195 if (&{$msg_level}("TYPO_SPELLING",
3196 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3198 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3203 # check for invalid commit id
3204 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3207 ($id, $description) = git_commit_info($2, undef, undef);
3208 if (!defined($id)) {
3209 WARN("UNKNOWN_COMMIT_ID",
3210 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3214 # check for repeated words separated by a single space
3215 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3216 if (($rawline =~ /^\+/ || $in_commit_log) &&
3217 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3218 pos($rawline) = 1 if (!$in_commit_log);
3219 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3223 my $start_pos = $-[1];
3224 my $end_pos = $+[2];
3225 if ($first =~ /(?:struct|union|enum)/) {
3226 pos($rawline) += length($first) + length($second) + 1;
3230 next if (lc($first) ne lc($second));
3231 next if ($first eq 'long');
3233 # check for character before and after the word matches
3234 my $start_char = '';
3236 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3237 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3239 next if ($start_char =~ /^\S$/);
3240 next if (index(" \t.,;?!", $end_char) == -1);
3242 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3243 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3244 next if (!exists($allow_repeated_words{lc($first)}));
3247 if (WARN("REPEATED_WORD",
3248 "Possible repeated word: '$first'\n" . $herecurr) &&
3250 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3254 # if it's a repeated word on consecutive lines in a comment block
3255 if ($prevline =~ /$;+\s*$/ &&
3256 $prevrawline =~ /($word_pattern)\s*$/) {
3258 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3259 if (WARN("REPEATED_WORD",
3260 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3262 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3268 # ignore non-hunk lines and lines being removed
3269 next if (!$hunk_line || $line =~ /^-/);
3271 #trailing whitespace
3272 if ($line =~ /^\+.*\015/) {
3273 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3274 if (ERROR("DOS_LINE_ENDINGS",
3275 "DOS line endings\n" . $herevet) &&
3277 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3279 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3280 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3281 if (ERROR("TRAILING_WHITESPACE",
3282 "trailing whitespace\n" . $herevet) &&
3284 $fixed[$fixlinenr] =~ s/\s+$//;
3290 # Check for FSF mailing addresses.
3291 if ($rawline =~ /\bwrite to the Free/i ||
3292 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3293 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3294 $rawline =~ /\b51\s+Franklin\s+St/i) {
3295 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3296 my $msg_level = \&ERROR;
3297 $msg_level = \&CHK if ($file);
3298 &{$msg_level}("FSF_MAILING_ADDRESS",
3299 "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)
3302 # check for Kconfig help text having a real description
3303 # Only applies when adding the entry originally, after that we do not have
3304 # sufficient context to determine whether it is indeed long enough.
3305 if ($realfile =~ /Kconfig/ &&
3306 # 'choice' is usually the last thing on the line (though
3307 # Kconfig supports named choices), so use a word boundary
3308 # (\b) rather than a whitespace character (\s)
3309 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3312 my $ln = $linenr + 1;
3316 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3317 $f = $lines[$ln - 1];
3318 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3319 $is_end = $lines[$ln - 1] =~ /^\+/;
3321 next if ($f =~ /^-/);
3322 last if (!$file && $f =~ /^\@\@/);
3324 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3326 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3333 next if ($f =~ /^$/);
3335 # This only checks context lines in the patch
3336 # and so hopefully shouldn't trigger false
3337 # positives, even though some of these are
3338 # common words in help texts
3339 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3340 if|endif|menu|endmenu|source)\b/x) {
3346 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3347 WARN("CONFIG_DESCRIPTION",
3348 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3350 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3353 # check MAINTAINERS entries
3354 if ($realfile =~ /^MAINTAINERS$/) {
3355 # check MAINTAINERS entries for the right form
3356 if ($rawline =~ /^\+[A-Z]:/ &&
3357 $rawline !~ /^\+[A-Z]:\t\S/) {
3358 if (WARN("MAINTAINERS_STYLE",
3359 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3361 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3364 # check MAINTAINERS entries for the right ordering too
3365 my $preferred_order = 'MRLSWQBCPTFXNK';
3366 if ($rawline =~ /^\+[A-Z]:/ &&
3367 $prevrawline =~ /^[\+ ][A-Z]:/) {
3368 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3371 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3374 my $curindex = index($preferred_order, $cur);
3375 my $previndex = index($preferred_order, $prev);
3376 if ($curindex < 0) {
3377 WARN("MAINTAINERS_STYLE",
3378 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3380 if ($previndex >= 0 && $curindex < $previndex) {
3381 WARN("MAINTAINERS_STYLE",
3382 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3383 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3384 ($prev eq 'X' && $cur eq 'X')) &&
3385 ($prevval cmp $curval) > 0) {
3386 WARN("MAINTAINERS_STYLE",
3387 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3393 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3394 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3397 'EXTRA_AFLAGS' => 'asflags-y',
3398 'EXTRA_CFLAGS' => 'ccflags-y',
3399 'EXTRA_CPPFLAGS' => 'cppflags-y',
3400 'EXTRA_LDFLAGS' => 'ldflags-y',
3403 WARN("DEPRECATED_VARIABLE",
3404 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3407 # check for DT compatible documentation
3408 if (defined $root &&
3409 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3410 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3412 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3414 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3415 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3417 foreach my $compat (@compats) {
3418 my $compat2 = $compat;
3419 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3420 my $compat3 = $compat;
3421 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3422 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3424 WARN("UNDOCUMENTED_DT_STRING",
3425 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3428 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3430 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3432 WARN("UNDOCUMENTED_DT_STRING",
3433 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3438 # check for using SPDX license tag at beginning of files
3439 if ($realline == $checklicenseline) {
3440 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3441 $checklicenseline = 2;
3442 } elsif ($rawline =~ /^\+/) {
3444 if ($realfile =~ /\.(h|s|S)$/) {
3446 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3448 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3450 } elsif ($realfile =~ /\.rst$/) {
3454 # check SPDX comment style for .[chsS] files
3455 if ($realfile =~ /\.[chsS]$/ &&
3456 $rawline =~ /SPDX-License-Identifier:/ &&
3457 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3458 WARN("SPDX_LICENSE_TAG",
3459 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3462 if ($comment !~ /^$/ &&
3463 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3464 WARN("SPDX_LICENSE_TAG",
3465 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3466 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3467 my $spdx_license = $1;
3468 if (!is_SPDX_License_valid($spdx_license)) {
3469 WARN("SPDX_LICENSE_TAG",
3470 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3472 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3473 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3474 my $msg_level = \&WARN;
3475 $msg_level = \&CHK if ($file);
3476 if (&{$msg_level}("SPDX_LICENSE_TAG",
3478 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3480 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3487 # check for embedded filenames
3488 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3489 WARN("EMBEDDED_FILENAME",
3490 "It's generally not useful to have the filename in the file\n" . $herecurr);
3493 # check we are in a valid source file if not then ignore this hunk
3494 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3496 # check for using SPDX-License-Identifier on the wrong line number
3497 if ($realline != $checklicenseline &&
3498 $rawline =~ /\bSPDX-License-Identifier:/ &&
3499 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3500 WARN("SPDX_LICENSE_TAG",
3501 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3504 # line length limit (with some exclusions)
3506 # There are a few types of lines that may extend beyond $max_line_length:
3507 # logging functions like pr_info that end in a string
3508 # lines with a single string
3509 # #defines that are a single string
3510 # lines with an RFC3986 like URL
3512 # There are 3 different line length message types:
3513 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3514 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3515 # LONG_LINE all other lines longer than $max_line_length
3517 # if LONG_LINE is ignored, the other 2 types are also ignored
3520 if ($line =~ /^\+/ && $length > $max_line_length) {
3521 my $msg_type = "LONG_LINE";
3523 # Check the allowed long line types first
3525 # logging functions that end in a string that starts
3526 # before $max_line_length
3527 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3528 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3531 # lines with only strings (w/ possible termination)
3532 # #defines with only strings
3533 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3534 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3537 # More special cases
3538 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3539 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3542 # URL ($rawline is used in case the URL is in a comment)
3543 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3546 # Otherwise set the alternate message types
3548 # a comment starts before $max_line_length
3549 } elsif ($line =~ /($;[\s$;]*)$/ &&
3550 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3551 $msg_type = "LONG_LINE_COMMENT"
3553 # a quoted string starts before $max_line_length
3554 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3555 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3556 $msg_type = "LONG_LINE_STRING"
3559 if ($msg_type ne "" &&
3560 (show_type("LONG_LINE") || show_type($msg_type))) {
3561 my $msg_level = \&WARN;
3562 $msg_level = \&CHK if ($file);
3563 &{$msg_level}($msg_type,
3564 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3568 # check for adding lines without a newline.
3569 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3570 if (WARN("MISSING_EOF_NEWLINE",
3571 "adding a line without newline at end of file\n" . $herecurr) &&
3573 fix_delete_line($fixlinenr+1, "No newline at end of file");
3577 # check we are in a valid source file C or perl if not then ignore this hunk
3578 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3580 # at the beginning of a line any tabs must come first and anything
3581 # more than $tabsize must use tabs.
3582 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3583 $rawline =~ /^\+\s* \s*/) {
3584 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3586 if (ERROR("CODE_INDENT",
3587 "code indent should use tabs where possible\n" . $herevet) &&
3589 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3593 # check for space before tabs.
3594 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3595 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3596 if (WARN("SPACE_BEFORE_TAB",
3597 "please, no space before tabs\n" . $herevet) &&
3599 while ($fixed[$fixlinenr] =~
3600 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3601 while ($fixed[$fixlinenr] =~
3602 s/(^\+.*) +\t/$1\t/) {}
3606 # check for assignments on the start of a line
3607 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3609 if (CHK("ASSIGNMENT_CONTINUATIONS",
3610 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3611 $fix && $prevrawline =~ /^\+/) {
3612 # add assignment operator to the previous line, remove from current line
3613 $fixed[$fixlinenr - 1] .= " $operator";
3614 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3618 # check for && or || at the start of a line
3619 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3621 if (CHK("LOGICAL_CONTINUATIONS",
3622 "Logical continuations should be on the previous line\n" . $hereprev) &&
3623 $fix && $prevrawline =~ /^\+/) {
3624 # insert logical operator at last non-comment, non-whitepsace char on previous line
3625 $prevline =~ /[\s$;]*$/;
3626 my $line_end = substr($prevrawline, $-[0]);
3627 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3628 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3632 # check indentation starts on a tab stop
3633 if ($perl_version_ok &&
3634 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3635 my $indent = length($1);
3636 if ($indent % $tabsize) {
3638 "Statements should start on a tabstop\n" . $herecurr) &&
3640 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3645 # check multi-line statement indentation matches previous line
3646 if ($perl_version_ok &&
3647 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3648 $prevline =~ /^\+(\t*)(.*)$/;
3652 my $pos = pos_last_openparen($rest);
3654 $line =~ /^(\+| )([ \t]*)/;
3657 my $goodtabindent = $oldindent .
3658 "\t" x ($pos / $tabsize) .
3659 " " x ($pos % $tabsize);
3660 my $goodspaceindent = $oldindent . " " x $pos;
3662 if ($newindent ne $goodtabindent &&
3663 $newindent ne $goodspaceindent) {
3665 if (CHK("PARENTHESIS_ALIGNMENT",
3666 "Alignment should match open parenthesis\n" . $hereprev) &&
3667 $fix && $line =~ /^\+/) {
3668 $fixed[$fixlinenr] =~
3669 s/^\+[ \t]*/\+$goodtabindent/;
3675 # check for space after cast like "(int) foo" or "(struct foo) bar"
3676 # avoid checking a few false positives:
3677 # "sizeof(<type>)" or "__alignof__(<type>)"
3678 # function pointer declarations like "(*foo)(int) = bar;"
3679 # structure definitions like "(struct foo) { 0 };"
3680 # multiline macros that define functions
3681 # known attributes or the __attribute__ keyword
3682 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3683 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3685 "No space is necessary after a cast\n" . $herecurr) &&
3687 $fixed[$fixlinenr] =~
3688 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3692 # Block comment styles
3693 # Networking with an initial /*
3694 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3695 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3696 $rawline =~ /^\+[ \t]*\*/ &&
3697 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3698 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3699 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3702 # Block comments use * on subsequent lines
3703 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3704 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3705 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3706 $rawline =~ /^\+/ && #line is new
3707 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3708 WARN("BLOCK_COMMENT_STYLE",
3709 "Block comments use * on subsequent lines\n" . $hereprev);
3712 # Block comments use */ on trailing lines
3713 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3714 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3715 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3716 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3717 WARN("BLOCK_COMMENT_STYLE",
3718 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3721 # Block comment * alignment
3722 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3723 $line =~ /^\+[ \t]*$;/ && #leading comment
3724 $rawline =~ /^\+[ \t]*\*/ && #leading *
3725 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3726 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3727 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3729 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3731 $oldindent = expand_tabs($1);
3733 $prevrawline =~ m@^\+(.*/?)\*@;
3734 $oldindent = expand_tabs($1);
3736 $rawline =~ m@^\+([ \t]*)\*@;
3738 $newindent = expand_tabs($newindent);
3739 if (length($oldindent) ne length($newindent)) {
3740 WARN("BLOCK_COMMENT_STYLE",
3741 "Block comments should align the * on each line\n" . $hereprev);
3745 # check for missing blank lines after struct/union declarations
3746 # with exceptions for various attributes and macros
3747 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3749 !($line =~ /^\+\s*$/ ||
3750 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3751 $line =~ /^\+\s*MODULE_/i ||
3752 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3753 $line =~ /^\+[a-z_]*init/ ||
3754 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3755 $line =~ /^\+\s*DECLARE/ ||
3756 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3757 $line =~ /^\+\s*__setup/)) {
3758 if (CHK("LINE_SPACING",
3759 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3761 fix_insert_line($fixlinenr, "\+");
3765 # check for multiple consecutive blank lines
3766 if ($prevline =~ /^[\+ ]\s*$/ &&
3767 $line =~ /^\+\s*$/ &&
3768 $last_blank_line != ($linenr - 1)) {
3769 if (CHK("LINE_SPACING",
3770 "Please don't use multiple blank lines\n" . $hereprev) &&
3772 fix_delete_line($fixlinenr, $rawline);
3775 $last_blank_line = $linenr;
3778 # check for missing blank lines after declarations
3779 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3780 # actual declarations
3781 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3782 # function pointer declarations
3783 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3784 # foo bar; where foo is some local typedef or #define
3785 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3786 # known declaration macros
3787 $prevline =~ /^\+\s+$declaration_macros/) &&
3788 # for "else if" which can look like "$Ident $Ident"
3789 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3790 # other possible extensions of declaration lines
3791 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3792 # not starting a section or a macro "\" extended line
3793 $prevline =~ /(?:\{\s*|\\)$/) &&
3794 # looks like a declaration
3795 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3796 # function pointer declarations
3797 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3798 # foo bar; where foo is some local typedef or #define
3799 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3800 # known declaration macros
3801 $sline =~ /^\+\s+$declaration_macros/ ||
3802 # start of struct or union or enum
3803 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3804 # start or end of block or continuation of declaration
3805 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3806 # bitfield continuation
3807 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3808 # other possible extensions of declaration lines
3809 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3810 # indentation of previous and current line are the same
3811 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3812 if (WARN("LINE_SPACING",
3813 "Missing a blank line after declarations\n" . $hereprev) &&
3815 fix_insert_line($fixlinenr, "\+");
3819 # check for spaces at the beginning of a line.
3821 # 1) within comments
3822 # 2) indented preprocessor commands
3824 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3825 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3826 if (WARN("LEADING_SPACE",
3827 "please, no spaces at the start of a line\n" . $herevet) &&
3829 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3833 # check we are in a valid C source file if not then ignore this hunk
3834 next if ($realfile !~ /\.(h|c)$/);
3836 # check for unusual line ending [ or (
3837 if ($line =~ /^\+.*([\[\(])\s*$/) {
3838 CHK("OPEN_ENDED_LINE",
3839 "Lines should not end with a '$1'\n" . $herecurr);
3842 # check if this appears to be the start function declaration, save the name
3843 if ($sline =~ /^\+\{\s*$/ &&
3844 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3845 $context_function = $1;
3848 # check if this appears to be the end of function declaration
3849 if ($sline =~ /^\+\}\s*$/) {
3850 undef $context_function;
3853 # check indentation of any line with a bare else
3854 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3855 # if the previous line is a break or return and is indented 1 tab more...
3856 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3857 my $tabs = length($1) + 1;
3858 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3859 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3860 defined $lines[$linenr] &&
3861 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3862 WARN("UNNECESSARY_ELSE",
3863 "else is not generally useful after a break or return\n" . $hereprev);
3867 # check indentation of a line with a break;
3868 # if the previous line is a goto, return or break
3869 # and is indented the same # of tabs
3870 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3872 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3873 if (WARN("UNNECESSARY_BREAK",
3874 "break is not useful after a $1\n" . $hereprev) &&
3876 fix_delete_line($fixlinenr, $rawline);
3881 # check for RCS/CVS revision markers
3882 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3884 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3887 # check for old HOTPLUG __dev<foo> section markings
3888 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3889 WARN("HOTPLUG_SECTION",
3890 "Using $1 is unnecessary\n" . $herecurr);
3893 # Check for potential 'bare' types
3894 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3896 #print "LINE<$line>\n";
3897 if ($linenr > $suppress_statement &&
3898 $realcnt && $sline =~ /.\s*\S/) {
3899 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3900 ctx_statement_block($linenr, $realcnt, 0);
3901 $stat =~ s/\n./\n /g;
3902 $cond =~ s/\n./\n /g;
3904 #print "linenr<$linenr> <$stat>\n";
3905 # If this statement has no statement boundaries within
3906 # it there is no point in retrying a statement scan
3907 # until we hit end of it.
3908 my $frag = $stat; $frag =~ s/;+\s*$//;
3909 if ($frag !~ /(?:{|;)/) {
3910 #print "skip<$line_nr_next>\n";
3911 $suppress_statement = $line_nr_next;
3914 # Find the real next line.
3915 $realline_next = $line_nr_next;
3916 if (defined $realline_next &&
3917 (!defined $lines[$realline_next - 1] ||
3918 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3925 # Ignore goto labels.
3926 if ($s =~ /$Ident:\*$/s) {
3928 # Ignore functions being called
3929 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3931 } elsif ($s =~ /^.\s*else\b/s) {
3933 # declarations always start with types
3934 } 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) {
3937 possible($type, "A:" . $s);
3939 # definitions in global scope can only start with types
3940 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3941 possible($1, "B:" . $s);
3944 # any (foo ... *) is a pointer cast, and foo is a type
3945 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3946 possible($1, "C:" . $s);
3949 # Check for any sort of function declaration.
3950 # int foo(something bar, other baz);
3951 # void (*store_gdt)(x86_descr_ptr *);
3952 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3953 my ($name_len) = length($1);
3956 substr($ctx, 0, $name_len + 1, '');
3957 $ctx =~ s/\)[^\)]*$//;
3959 for my $arg (split(/\s*,\s*/, $ctx)) {
3960 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3962 possible($1, "D:" . $s);
3970 # Checks which may be anchored in the context.
3973 # Check for switch () and associated case and default
3974 # statements should be at the same indent.
3975 if ($line=~/\bswitch\s*\(.*\)/) {
3978 my @ctx = ctx_block_outer($linenr, $realcnt);
3980 for my $ctx (@ctx) {
3981 my ($clen, $cindent) = line_stats($ctx);
3982 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3983 $indent != $cindent) {
3984 $err .= "$sep$ctx\n";
3991 ERROR("SWITCH_CASE_INDENT_LEVEL",
3992 "switch and case should be at the same indent\n$hereline$err");
3996 # if/while/etc brace do not go on next line, unless defining a do while loop,
3997 # or if that brace on the next line is for something else
3998 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3999 my $pre_ctx = "$1$2";
4001 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4003 if ($line =~ /^\+\t{6,}/) {
4004 WARN("DEEP_INDENTATION",
4005 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4008 my $ctx_cnt = $realcnt - $#ctx - 1;
4009 my $ctx = join("\n", @ctx);
4011 my $ctx_ln = $linenr;
4012 my $ctx_skip = $realcnt;
4014 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4015 defined $lines[$ctx_ln - 1] &&
4016 $lines[$ctx_ln - 1] =~ /^-/)) {
4017 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4018 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4022 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4023 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4025 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4027 "that open brace { should be on the previous line\n" .
4028 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4030 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4031 $ctx =~ /\)\s*\;\s*$/ &&
4032 defined $lines[$ctx_ln - 1])
4034 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4035 if ($nindent > $indent) {
4036 WARN("TRAILING_SEMICOLON",
4037 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4038 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4043 # Check relative indent for conditionals and blocks.
4044 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4045 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4046 ctx_statement_block($linenr, $realcnt, 0)
4047 if (!defined $stat);
4048 my ($s, $c) = ($stat, $cond);
4050 substr($s, 0, length($c), '');
4052 # remove inline comments
4056 # Find out how long the conditional actually is.
4057 my @newlines = ($c =~ /\n/gs);
4058 my $cond_lines = 1 + $#newlines;
4060 # Make sure we remove the line prefixes as we have
4061 # none on the first line, and are going to readd them
4064 while ($s =~ /\n\s+\\\n/) {
4065 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4068 # We want to check the first line inside the block
4069 # starting at the end of the conditional, so remove:
4070 # 1) any blank line termination
4071 # 2) any opening brace { on end of the line
4073 my $continuation = 0;
4075 $s =~ s/^.*\bdo\b//;
4077 if ($s =~ s/^\s*\\//) {
4080 if ($s =~ s/^\s*?\n//) {
4085 # Also ignore a loop construct at the end of a
4086 # preprocessor statement.
4087 if (($prevline =~ /^.\s*#\s*define\s/ ||
4088 $prevline =~ /\\\s*$/) && $continuation == 0) {
4094 while ($cond_ptr != $cond_lines) {
4095 $cond_ptr = $cond_lines;
4097 # If we see an #else/#elif then the code
4099 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4104 # 1) blank lines, they should be at 0,
4105 # 2) preprocessor lines, and
4107 if ($continuation ||
4109 $s =~ /^\s*#\s*?/ ||
4110 $s =~ /^\s*$Ident\s*:/) {
4111 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4112 if ($s =~ s/^.*?\n//) {
4118 my (undef, $sindent) = line_stats("+" . $s);
4119 my $stat_real = raw_line($linenr, $cond_lines);
4121 # Check if either of these lines are modified, else
4122 # this is not this patch's fault.
4123 if (!defined($stat_real) ||
4124 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4127 if (defined($stat_real) && $cond_lines > 1) {
4128 $stat_real = "[...]\n$stat_real";
4131 #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";
4133 if ($check && $s ne '' &&
4134 (($sindent % $tabsize) != 0 ||
4135 ($sindent < $indent) ||
4136 ($sindent == $indent &&
4137 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4138 ($sindent > $indent + $tabsize))) {
4139 WARN("SUSPECT_CODE_INDENT",
4140 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4144 # Track the 'values' across context and added lines.
4145 my $opline = $line; $opline =~ s/^./ /;
4146 my ($curr_values, $curr_vars) =
4147 annotate_values($opline . "\n", $prev_values);
4148 $curr_values = $prev_values . $curr_values;
4150 my $outline = $opline; $outline =~ s/\t/ /g;
4151 print "$linenr > .$outline\n";
4152 print "$linenr > $curr_values\n";
4153 print "$linenr > $curr_vars\n";
4155 $prev_values = substr($curr_values, -1);
4157 #ignore lines not being added
4158 next if ($line =~ /^[^\+]/);
4160 # check for self assignments used to avoid compiler warnings
4161 # e.g.: int foo = foo, *bar = NULL;
4162 # struct foo bar = *(&(bar));
4163 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4165 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4166 WARN("SELF_ASSIGNMENT",
4167 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4171 # check for dereferences that span multiple lines
4172 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4173 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4174 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4176 $line =~ /^.\s*($Lval)/;
4179 WARN("MULTILINE_DEREFERENCE",
4180 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4183 # check for declarations of signed or unsigned without int
4184 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4187 $var = "" if (!defined $var);
4188 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4192 $pointer = "" if (!defined $pointer);
4194 if (WARN("UNSPECIFIED_INT",
4195 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4197 my $decl = trim($sign) . " int ";
4198 my $comp_pointer = $pointer;
4199 $comp_pointer =~ s/\s//g;
4200 $decl .= $comp_pointer;
4201 $decl = rtrim($decl) if ($var eq "");
4202 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4207 # TEST: allow direct testing of the type matcher.
4209 if ($line =~ /^.\s*$Declare\s*$/) {
4211 "TEST: is type\n" . $herecurr);
4212 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4213 ERROR("TEST_NOT_TYPE",
4214 "TEST: is not type ($1 is)\n". $herecurr);
4218 # TEST: allow direct testing of the attribute matcher.
4220 if ($line =~ /^.\s*$Modifier\s*$/) {
4222 "TEST: is attr\n" . $herecurr);
4223 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4224 ERROR("TEST_NOT_ATTR",
4225 "TEST: is not attr ($1 is)\n". $herecurr);
4230 # check for initialisation to aggregates open brace on the next line
4231 if ($line =~ /^.\s*{/ &&
4232 $prevline =~ /(?:^|[^=])=\s*$/) {
4233 if (ERROR("OPEN_BRACE",
4234 "that open brace { should be on the previous line\n" . $hereprev) &&
4235 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4236 fix_delete_line($fixlinenr - 1, $prevrawline);
4237 fix_delete_line($fixlinenr, $rawline);
4238 my $fixedline = $prevrawline;
4239 $fixedline =~ s/\s*=\s*$/ = {/;
4240 fix_insert_line($fixlinenr, $fixedline);
4242 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4243 fix_insert_line($fixlinenr, $fixedline);
4248 # Checks which are anchored on the added line.
4251 # check for malformed paths in #include statements (uses RAW line)
4252 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4254 if ($path =~ m{//}) {
4255 ERROR("MALFORMED_INCLUDE",
4256 "malformed #include filename\n" . $herecurr);
4258 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4259 ERROR("UAPI_INCLUDE",
4260 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4264 # no C99 // comments
4265 if ($line =~ m{//}) {
4266 if (ERROR("C99_COMMENTS",
4267 "do not use C99 // comments\n" . $herecurr) &&
4269 my $line = $fixed[$fixlinenr];
4270 if ($line =~ /\/\/(.*)$/) {
4271 my $comment = trim($1);
4272 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4276 # Remove C99 comments.
4278 $opline =~ s@//.*@@;
4280 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4281 # the whole statement.
4282 #print "APW <$lines[$realline_next - 1]>\n";
4283 if (defined $realline_next &&
4284 exists $lines[$realline_next - 1] &&
4285 !defined $suppress_export{$realline_next} &&
4286 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4287 # Handle definitions which produce identifiers with
4290 # EXPORT_SYMBOL(something_foo);
4292 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4293 $name =~ /^${Ident}_$2/) {
4294 #print "FOO C name<$name>\n";
4295 $suppress_export{$realline_next} = 1;
4297 } elsif ($stat !~ /(?:
4299 ^.DEFINE_$Ident\(\Q$name\E\)|
4300 ^.DECLARE_$Ident\(\Q$name\E\)|
4301 ^.LIST_HEAD\(\Q$name\E\)|
4302 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4303 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4305 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4306 $suppress_export{$realline_next} = 2;
4308 $suppress_export{$realline_next} = 1;
4311 if (!defined $suppress_export{$linenr} &&
4312 $prevline =~ /^.\s*$/ &&
4313 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4314 #print "FOO B <$lines[$linenr - 1]>\n";
4315 $suppress_export{$linenr} = 2;
4317 if (defined $suppress_export{$linenr} &&
4318 $suppress_export{$linenr} == 2) {
4319 WARN("EXPORT_SYMBOL",
4320 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4323 # check for global initialisers.
4324 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4325 if (ERROR("GLOBAL_INITIALISERS",
4326 "do not initialise globals to $1\n" . $herecurr) &&
4328 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4331 # check for static initialisers.
4332 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4333 if (ERROR("INITIALISED_STATIC",
4334 "do not initialise statics to $1\n" .
4337 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4341 # check for misordered declarations of char/short/int/long with signed/unsigned
4342 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4344 WARN("MISORDERED_TYPE",
4345 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4348 # check for unnecessary <signed> int declarations of short/long/long long
4349 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4350 my $type = trim($1);
4351 next if ($type !~ /\bint\b/);
4352 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4353 my $new_type = $type;
4354 $new_type =~ s/\b\s*int\s*\b/ /;
4355 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4356 $new_type =~ s/^const\s+//;
4357 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4358 $new_type = "const $new_type" if ($type =~ /^const\b/);
4359 $new_type =~ s/\s+/ /g;
4360 $new_type = trim($new_type);
4361 if (WARN("UNNECESSARY_INT",
4362 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4364 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4368 # check for static const char * arrays.
4369 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4370 WARN("STATIC_CONST_CHAR_ARRAY",
4371 "static const char * array should probably be static const char * const\n" .
4375 # check for initialized const char arrays that should be static const
4376 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4377 if (WARN("STATIC_CONST_CHAR_ARRAY",
4378 "const array should probably be static const\n" . $herecurr) &&
4380 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4384 # check for static char foo[] = "bar" declarations.
4385 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4386 WARN("STATIC_CONST_CHAR_ARRAY",
4387 "static char array declaration should probably be static const char\n" .
4391 # check for const <foo> const where <foo> is not a pointer or array type
4392 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4394 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4396 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4397 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4399 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4403 # check for const static or static <non ptr type> const declarations
4404 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4405 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4406 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4407 if (WARN("STATIC_CONST",
4408 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4410 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4411 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4415 # check for non-global char *foo[] = {"bar", ...} declarations.
4416 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4417 WARN("STATIC_CONST_CHAR_ARRAY",
4418 "char * array declaration might be better as static const\n" .
4422 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4423 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4425 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4427 if (WARN("ARRAY_SIZE",
4428 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4430 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4435 # check for function declarations without arguments like "int foo()"
4436 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4437 if (ERROR("FUNCTION_WITHOUT_ARGS",
4438 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4440 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4444 # check for new typedefs, only function parameters and sparse annotations
4446 if ($line =~ /\btypedef\s/ &&
4447 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4448 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4449 $line !~ /\b$typeTypedefs\b/ &&
4450 $line !~ /\b__bitwise\b/) {
4451 WARN("NEW_TYPEDEFS",
4452 "do not add new typedefs\n" . $herecurr);
4455 # * goes on variable not on type
4457 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4459 my ($ident, $from, $to) = ($1, $2, $2);
4461 # Should start with a space.
4462 $to =~ s/^(\S)/ $1/;
4463 # Should not end with a space.
4465 # '*'s should not have spaces between.
4466 while ($to =~ s/\*\s+\*/\*\*/) {
4469 ## print "1: from<$from> to<$to> ident<$ident>\n";
4471 if (ERROR("POINTER_LOCATION",
4472 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4474 my $sub_from = $ident;
4475 my $sub_to = $ident;
4476 $sub_to =~ s/\Q$from\E/$to/;
4477 $fixed[$fixlinenr] =~
4478 s@\Q$sub_from\E@$sub_to@;
4482 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4484 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4486 # Should start with a space.
4487 $to =~ s/^(\S)/ $1/;
4488 # Should not end with a space.
4490 # '*'s should not have spaces between.
4491 while ($to =~ s/\*\s+\*/\*\*/) {
4493 # Modifiers should have spaces.
4494 $to =~ s/(\b$Modifier$)/$1 /;
4496 ## print "2: from<$from> to<$to> ident<$ident>\n";
4497 if ($from ne $to && $ident !~ /^$Modifier$/) {
4498 if (ERROR("POINTER_LOCATION",
4499 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4502 my $sub_from = $match;
4503 my $sub_to = $match;
4504 $sub_to =~ s/\Q$from\E/$to/;
4505 $fixed[$fixlinenr] =~
4506 s@\Q$sub_from\E@$sub_to@;
4511 # avoid BUG() or BUG_ON()
4512 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4513 my $msg_level = \&WARN;
4514 $msg_level = \&CHK if ($file);
4515 &{$msg_level}("AVOID_BUG",
4516 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4519 # avoid LINUX_VERSION_CODE
4520 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4521 WARN("LINUX_VERSION_CODE",
4522 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4525 # check for uses of printk_ratelimit
4526 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4527 WARN("PRINTK_RATELIMITED",
4528 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4531 # printk should use KERN_* levels
4532 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4533 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4534 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4537 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4538 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4542 $modifier = "" if (!defined($modifier));
4543 my $level = lc($orig);
4544 $level = "warn" if ($level eq "warning");
4545 my $level2 = $level;
4546 $level2 = "dbg" if ($level eq "debug");
4547 $level .= $modifier;
4548 $level2 .= $modifier;
4549 WARN("PREFER_PR_LEVEL",
4550 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4553 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4554 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4556 my $level = lc($orig);
4557 $level = "warn" if ($level eq "warning");
4558 $level = "dbg" if ($level eq "debug");
4559 WARN("PREFER_DEV_LEVEL",
4560 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4563 # trace_printk should not be used in production code.
4564 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4565 WARN("TRACE_PRINTK",
4566 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4569 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4570 # number of false positives, but assembly files are not checked, so at
4571 # least the arch entry code will not trigger this warning.
4572 if ($line =~ /\bENOSYS\b/) {
4574 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4577 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4578 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4579 # Similarly to ENOSYS warning a small number of false positives is expected.
4580 if (!$file && $line =~ /\bENOTSUPP\b/) {
4581 if (WARN("ENOTSUPP",
4582 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4584 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4588 # function brace can't be on same line, except for #defines of do while,
4589 # or if closed on same line
4590 if ($perl_version_ok &&
4591 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4592 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4594 if (ERROR("OPEN_BRACE",
4595 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4597 fix_delete_line($fixlinenr, $rawline);
4598 my $fixed_line = $rawline;
4599 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4602 fix_insert_line($fixlinenr, ltrim($line1));
4603 fix_insert_line($fixlinenr, "\+{");
4604 if ($line2 !~ /^\s*$/) {
4605 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4610 # open braces for enum, union and struct go on the same line.
4611 if ($line =~ /^.\s*{/ &&
4612 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4613 if (ERROR("OPEN_BRACE",
4614 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4615 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4616 fix_delete_line($fixlinenr - 1, $prevrawline);
4617 fix_delete_line($fixlinenr, $rawline);
4618 my $fixedline = rtrim($prevrawline) . " {";
4619 fix_insert_line($fixlinenr, $fixedline);
4620 $fixedline = $rawline;
4621 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4622 if ($fixedline !~ /^\+\s*$/) {
4623 fix_insert_line($fixlinenr, $fixedline);
4628 # missing space after union, struct or enum definition
4629 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4631 "missing space after $1 definition\n" . $herecurr) &&
4633 $fixed[$fixlinenr] =~
4634 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4638 # Function pointer declarations
4639 # check spacing between type, funcptr, and args
4640 # canonical declaration is "type (*funcptr)(args...)"
4641 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4643 my $pre_pointer_space = $2;
4644 my $post_pointer_space = $3;
4646 my $post_funcname_space = $5;
4647 my $pre_args_space = $6;
4649 # the $Declare variable will capture all spaces after the type
4650 # so check it for a missing trailing missing space but pointer return types
4651 # don't need a space so don't warn for those.
4652 my $post_declare_space = "";
4653 if ($declare =~ /(\s+)$/) {
4654 $post_declare_space = $1;
4655 $declare = rtrim($declare);
4657 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4659 "missing space after return type\n" . $herecurr);
4660 $post_declare_space = " ";
4663 # unnecessary space "type (*funcptr)(args...)"
4664 # This test is not currently implemented because these declarations are
4666 # int foo(int bar, ...)
4667 # and this is form shouldn't/doesn't generate a checkpatch warning.
4669 # elsif ($declare =~ /\s{2,}$/) {
4671 # "Multiple spaces after return type\n" . $herecurr);
4674 # unnecessary space "type ( *funcptr)(args...)"
4675 if (defined $pre_pointer_space &&
4676 $pre_pointer_space =~ /^\s/) {
4678 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4681 # unnecessary space "type (* funcptr)(args...)"
4682 if (defined $post_pointer_space &&
4683 $post_pointer_space =~ /^\s/) {
4685 "Unnecessary space before function pointer name\n" . $herecurr);
4688 # unnecessary space "type (*funcptr )(args...)"
4689 if (defined $post_funcname_space &&
4690 $post_funcname_space =~ /^\s/) {
4692 "Unnecessary space after function pointer name\n" . $herecurr);
4695 # unnecessary space "type (*funcptr) (args...)"
4696 if (defined $pre_args_space &&
4697 $pre_args_space =~ /^\s/) {
4699 "Unnecessary space before function pointer arguments\n" . $herecurr);
4702 if (show_type("SPACING") && $fix) {
4703 $fixed[$fixlinenr] =~
4704 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4708 # check for spacing round square brackets; allowed:
4709 # 1. with a type on the left -- int [] a;
4710 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4711 # 3. inside a curly brace -- = { [0...10] = 5 }
4712 while ($line =~ /(.*?\s)\[/g) {
4713 my ($where, $prefix) = ($-[1], $1);
4714 if ($prefix !~ /$Type\s+$/ &&
4715 ($where != 0 || $prefix !~ /^.\s+$/) &&
4716 $prefix !~ /[{,:]\s+$/) {
4717 if (ERROR("BRACKET_SPACE",
4718 "space prohibited before open square bracket '['\n" . $herecurr) &&
4720 $fixed[$fixlinenr] =~
4721 s/^(\+.*?)\s+\[/$1\[/;
4726 # check for spaces between functions and their parentheses.
4727 while ($line =~ /($Ident)\s+\(/g) {
4729 my $ctx_before = substr($line, 0, $-[1]);
4730 my $ctx = "$ctx_before$name";
4732 # Ignore those directives where spaces _are_ permitted.
4734 if|for|while|switch|return|case|
4735 volatile|__volatile__|
4736 __attribute__|format|__extension__|
4739 # cpp #define statements have non-optional spaces, ie
4740 # if there is a space between the name and the open
4741 # parenthesis it is simply not a parameter group.
4742 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4744 # cpp #elif statement condition may start with a (
4745 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4747 # If this whole things ends with a type its most
4748 # likely a typedef for a function.
4749 } elsif ($ctx =~ /$Type$/) {
4753 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4755 $fixed[$fixlinenr] =~
4756 s/\b$name\s+\(/$name\(/;
4761 # Check operator spacing.
4762 if (!($line=~/\#\s*include/)) {
4763 my $fixed_line = "";
4767 <<=|>>=|<=|>=|==|!=|
4768 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4769 =>|->|<<|>>|<|>|=|!|~|
4770 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4773 my @elements = split(/($ops|;)/, $opline);
4775 ## print("element count: <" . $#elements . ">\n");
4776 ## foreach my $el (@elements) {
4777 ## print("el: <$el>\n");
4780 my @fix_elements = ();
4783 foreach my $el (@elements) {
4784 push(@fix_elements, substr($rawline, $off, length($el)));
4785 $off += length($el);
4790 my $blank = copy_spacing($opline);
4791 my $last_after = -1;
4793 for (my $n = 0; $n < $#elements; $n += 2) {
4795 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4797 ## print("n: <$n> good: <$good>\n");
4799 $off += length($elements[$n]);
4801 # Pick up the preceding and succeeding characters.
4802 my $ca = substr($opline, 0, $off);
4804 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4805 $cc = substr($opline, $off + length($elements[$n + 1]));
4807 my $cb = "$ca$;$cc";
4810 $a = 'V' if ($elements[$n] ne '');
4811 $a = 'W' if ($elements[$n] =~ /\s$/);
4812 $a = 'C' if ($elements[$n] =~ /$;$/);
4813 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4814 $a = 'O' if ($elements[$n] eq '');
4815 $a = 'E' if ($ca =~ /^\s*$/);
4817 my $op = $elements[$n + 1];
4820 if (defined $elements[$n + 2]) {
4821 $c = 'V' if ($elements[$n + 2] ne '');
4822 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4823 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4824 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4825 $c = 'O' if ($elements[$n + 2] eq '');
4826 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4831 my $ctx = "${a}x${c}";
4833 my $at = "(ctx:$ctx)";
4835 my $ptr = substr($blank, 0, $off) . "^";
4836 my $hereptr = "$hereline$ptr\n";
4838 # Pull out the value of this operator.
4839 my $op_type = substr($curr_values, $off + 1, 1);
4841 # Get the full operator variant.
4842 my $opv = $op . substr($curr_vars, $off, 1);
4844 # Ignore operators passed as parameters.
4845 if ($op_type ne 'V' &&
4846 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4849 # } elsif ($op =~ /^$;+$/) {
4851 # ; should have either the end of line or a space or \ after it
4852 } elsif ($op eq ';') {
4853 if ($ctx !~ /.x[WEBC]/ &&
4854 $cc !~ /^\\/ && $cc !~ /^;/) {
4855 if (ERROR("SPACING",
4856 "space required after that '$op' $at\n" . $hereptr)) {
4857 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4863 } elsif ($op eq '//') {
4865 # : when part of a bitfield
4866 } elsif ($opv eq ':B') {
4867 # skip the bitfield test for now
4871 } elsif ($op eq '->') {
4872 if ($ctx =~ /Wx.|.xW/) {
4873 if (ERROR("SPACING",
4874 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4875 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4876 if (defined $fix_elements[$n + 2]) {
4877 $fix_elements[$n + 2] =~ s/^\s+//;
4883 # , must not have a space before and must have a space on the right.
4884 } elsif ($op eq ',') {
4885 my $rtrim_before = 0;
4886 my $space_after = 0;
4887 if ($ctx =~ /Wx./) {
4888 if (ERROR("SPACING",
4889 "space prohibited before that '$op' $at\n" . $hereptr)) {
4894 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4895 if (ERROR("SPACING",
4896 "space required after that '$op' $at\n" . $hereptr)) {
4902 if ($rtrim_before || $space_after) {
4903 if ($rtrim_before) {
4904 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4906 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4913 # '*' as part of a type definition -- reported already.
4914 } elsif ($opv eq '*_') {
4915 #warn "'*' is part of type\n";
4917 # unary operators should have a space before and
4918 # none after. May be left adjacent to another
4919 # unary operator, or a cast
4920 } elsif ($op eq '!' || $op eq '~' ||
4921 $opv eq '*U' || $opv eq '-U' ||
4922 $opv eq '&U' || $opv eq '&&U') {
4923 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4924 if (ERROR("SPACING",
4925 "space required before that '$op' $at\n" . $hereptr)) {
4926 if ($n != $last_after + 2) {
4927 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4932 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4933 # A unary '*' may be const
4935 } elsif ($ctx =~ /.xW/) {
4936 if (ERROR("SPACING",
4937 "space prohibited after that '$op' $at\n" . $hereptr)) {
4938 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4939 if (defined $fix_elements[$n + 2]) {
4940 $fix_elements[$n + 2] =~ s/^\s+//;
4946 # unary ++ and unary -- are allowed no space on one side.
4947 } elsif ($op eq '++' or $op eq '--') {
4948 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4949 if (ERROR("SPACING",
4950 "space required one side of that '$op' $at\n" . $hereptr)) {
4951 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4955 if ($ctx =~ /Wx[BE]/ ||
4956 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4957 if (ERROR("SPACING",
4958 "space prohibited before that '$op' $at\n" . $hereptr)) {
4959 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4963 if ($ctx =~ /ExW/) {
4964 if (ERROR("SPACING",
4965 "space prohibited after that '$op' $at\n" . $hereptr)) {
4966 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4967 if (defined $fix_elements[$n + 2]) {
4968 $fix_elements[$n + 2] =~ s/^\s+//;
4974 # << and >> may either have or not have spaces both sides
4975 } elsif ($op eq '<<' or $op eq '>>' or
4976 $op eq '&' or $op eq '^' or $op eq '|' or
4977 $op eq '+' or $op eq '-' or
4978 $op eq '*' or $op eq '/' or
4982 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4984 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4985 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4986 $fix_elements[$n + 2] =~ s/^\s+//;
4989 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4991 "space preferred before that '$op' $at\n" . $hereptr)) {
4992 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4996 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4997 if (ERROR("SPACING",
4998 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4999 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5000 if (defined $fix_elements[$n + 2]) {
5001 $fix_elements[$n + 2] =~ s/^\s+//;
5007 # A colon needs no spaces before when it is
5008 # terminating a case value or a label.
5009 } elsif ($opv eq ':C' || $opv eq ':L') {
5010 if ($ctx =~ /Wx./) {
5011 if (ERROR("SPACING",
5012 "space prohibited before that '$op' $at\n" . $hereptr)) {
5013 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5018 # All the others need spaces both sides.
5019 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5022 # Ignore email addresses <foo@bar>
5024 $cc =~ /^\S+\@\S+>/) ||
5026 $ca =~ /<\S+\@\S+$/))
5031 # for asm volatile statements
5032 # ignore a colon with another
5033 # colon immediately before or after
5035 ($ca =~ /:$/ || $cc =~ /^:/)) {
5039 # messages are ERROR, but ?: are CHK
5041 my $msg_level = \&ERROR;
5042 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5044 if (&{$msg_level}("SPACING",
5045 "spaces required around that '$op' $at\n" . $hereptr)) {
5046 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5047 if (defined $fix_elements[$n + 2]) {
5048 $fix_elements[$n + 2] =~ s/^\s+//;
5054 $off += length($elements[$n + 1]);
5056 ## print("n: <$n> GOOD: <$good>\n");
5058 $fixed_line = $fixed_line . $good;
5061 if (($#elements % 2) == 0) {
5062 $fixed_line = $fixed_line . $fix_elements[$#elements];
5065 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5066 $fixed[$fixlinenr] = $fixed_line;
5072 # check for whitespace before a non-naked semicolon
5073 if ($line =~ /^\+.*\S\s+;\s*$/) {
5075 "space prohibited before semicolon\n" . $herecurr) &&
5077 1 while $fixed[$fixlinenr] =~
5078 s/^(\+.*\S)\s+;/$1;/;
5082 # check for multiple assignments
5083 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5084 CHK("MULTIPLE_ASSIGNMENTS",
5085 "multiple assignments should be avoided\n" . $herecurr);
5088 ## # check for multiple declarations, allowing for a function declaration
5090 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5091 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5093 ## # Remove any bracketed sections to ensure we do not
5094 ## # falsely report the parameters of functions.
5096 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5098 ## if ($ln =~ /,/) {
5099 ## WARN("MULTIPLE_DECLARATION",
5100 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5104 #need space before brace following if, while, etc
5105 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5106 $line =~ /\b(?:else|do)\{/) {
5107 if (ERROR("SPACING",
5108 "space required before the open brace '{'\n" . $herecurr) &&
5110 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5114 ## # check for blank lines before declarations
5115 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5116 ## $prevrawline =~ /^.\s*$/) {
5118 ## "No blank lines before declarations\n" . $hereprev);
5122 # closing brace should have a space following it when it has anything
5124 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5125 if (ERROR("SPACING",
5126 "space required after that close brace '}'\n" . $herecurr) &&
5128 $fixed[$fixlinenr] =~
5129 s/}((?!(?:,|;|\)))\S)/} $1/;
5133 # check spacing on square brackets
5134 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5135 if (ERROR("SPACING",
5136 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5138 $fixed[$fixlinenr] =~
5142 if ($line =~ /\s\]/) {
5143 if (ERROR("SPACING",
5144 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5146 $fixed[$fixlinenr] =~
5151 # check spacing on parentheses
5152 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5153 $line !~ /for\s*\(\s+;/) {
5154 if (ERROR("SPACING",
5155 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5157 $fixed[$fixlinenr] =~
5161 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5162 $line !~ /for\s*\(.*;\s+\)/ &&
5163 $line !~ /:\s+\)/) {
5164 if (ERROR("SPACING",
5165 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5167 $fixed[$fixlinenr] =~
5172 # check unnecessary parentheses around addressof/dereference single $Lvals
5173 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5175 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5177 if (CHK("UNNECESSARY_PARENTHESES",
5178 "Unnecessary parentheses around $var\n" . $herecurr) &&
5180 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5184 # check for unnecessary parentheses around function pointer uses
5185 # ie: (foo->bar)(); should be foo->bar();
5186 # but not "if (foo->bar) (" to avoid some false positives
5187 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5189 if (CHK("UNNECESSARY_PARENTHESES",
5190 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5192 my $var2 = deparenthesize($var);
5194 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5198 # check for unnecessary parentheses around comparisons in if uses
5199 # when !drivers/staging or command-line uses --strict
5200 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5201 $perl_version_ok && defined($stat) &&
5202 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5204 my $test = substr($2, 1, -1);
5206 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5208 # avoid parentheses around potential macro args
5209 next if ($match =~ /^\s*\w+\s*$/);
5210 if (!defined($herectx)) {
5211 $herectx = $here . "\n";
5212 my $cnt = statement_rawlines($if_stat);
5213 for (my $n = 0; $n < $cnt; $n++) {
5214 my $rl = raw_line($linenr, $n);
5215 $herectx .= $rl . "\n";
5216 last if $rl =~ /^[ \+].*\{/;
5219 CHK("UNNECESSARY_PARENTHESES",
5220 "Unnecessary parentheses around '$match'\n" . $herectx);
5224 #goto labels aren't indented, allow a single space however
5225 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
5226 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
5227 if (WARN("INDENTED_LABEL",
5228 "labels should not be indented\n" . $herecurr) &&
5230 $fixed[$fixlinenr] =~
5235 # check if a statement with a comma should be two statements like:
5236 # foo = bar(), /* comma should be semicolon */
5238 if (defined($stat) &&
5239 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5240 my $cnt = statement_rawlines($stat);
5241 my $herectx = get_stat_here($linenr, $cnt, $here);
5242 WARN("SUSPECT_COMMA_SEMICOLON",
5243 "Possible comma where semicolon could be used\n" . $herectx);
5246 # return is not a function
5247 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5249 if ($perl_version_ok &&
5250 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5252 $value = deparenthesize($value);
5253 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5254 ERROR("RETURN_PARENTHESES",
5255 "return is not a function, parentheses are not required\n" . $herecurr);
5257 } elsif ($spacing !~ /\s+/) {
5259 "space required before the open parenthesis '('\n" . $herecurr);
5263 # unnecessary return in a void function
5264 # at end-of-function, with the previous line a single leading tab, then return;
5265 # and the line before that not a goto label target like "out:"
5266 if ($sline =~ /^[ \+]}\s*$/ &&
5267 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5269 $lines[$linenr - 3] =~ /^[ +]/ &&
5270 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5272 "void function return statements are not generally useful\n" . $hereprev);
5275 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5276 if ($perl_version_ok &&
5277 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5278 my $openparens = $1;
5279 my $count = $openparens =~ tr@\(@\(@;
5281 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5282 my $comp = $4; #Not $1 because of $LvalOrFunc
5283 $msg = " - maybe == should be = ?" if ($comp eq "==");
5284 WARN("UNNECESSARY_PARENTHESES",
5285 "Unnecessary parentheses$msg\n" . $herecurr);
5289 # comparisons with a constant or upper case identifier on the left
5290 # avoid cases like "foo + BAR < baz"
5291 # only fix matches surrounded by parentheses to avoid incorrect
5292 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5293 if ($perl_version_ok &&
5294 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5299 my $newcomp = $comp;
5300 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5301 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5302 WARN("CONSTANT_COMPARISON",
5303 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5307 } elsif ($comp eq "<=") {
5309 } elsif ($comp eq ">") {
5311 } elsif ($comp eq ">=") {
5314 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5318 # Return of what appears to be an errno should normally be negative
5319 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5321 if ($name ne 'EOF' && $name ne 'ERROR') {
5322 WARN("USE_NEGATIVE_ERRNO",
5323 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5327 # Need a space before open parenthesis after if, while etc
5328 if ($line =~ /\b(if|while|for|switch)\(/) {
5329 if (ERROR("SPACING",
5330 "space required before the open parenthesis '('\n" . $herecurr) &&
5332 $fixed[$fixlinenr] =~
5333 s/\b(if|while|for|switch)\(/$1 \(/;
5337 # Check for illegal assignment in if conditional -- and check for trailing
5338 # statements after the conditional.
5339 if ($line =~ /do\s*(?!{)/) {
5340 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5341 ctx_statement_block($linenr, $realcnt, 0)
5342 if (!defined $stat);
5343 my ($stat_next) = ctx_statement_block($line_nr_next,
5344 $remain_next, $off_next);
5345 $stat_next =~ s/\n./\n /g;
5346 ##print "stat<$stat> stat_next<$stat_next>\n";
5348 if ($stat_next =~ /^\s*while\b/) {
5349 # If the statement carries leading newlines,
5350 # then count those as offsets.
5352 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5354 statement_rawlines($whitespace) - 1;
5356 $suppress_whiletrailers{$line_nr_next +
5360 if (!defined $suppress_whiletrailers{$linenr} &&
5361 defined($stat) && defined($cond) &&
5362 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5363 my ($s, $c) = ($stat, $cond);
5365 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5366 if (ERROR("ASSIGN_IN_IF",
5367 "do not use assignment in if condition\n" . $herecurr) &&
5368 $fix && $perl_version_ok) {
5369 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5377 fix_delete_line($fixlinenr, $rawline);
5378 fix_insert_line($fixlinenr, "$space$statement;");
5379 my $newline = "${space}if (";
5380 $newline .= '!' if defined($not);
5381 $newline .= '(' if (defined $not && defined($test) && defined($against));
5382 $newline .= "$assigned";
5383 $newline .= " $test $against" if (defined($test) && defined($against));
5384 $newline .= ')' if (defined $not && defined($test) && defined($against));
5386 $newline .= " {" if (defined($brace));
5387 fix_insert_line($fixlinenr + 1, $newline);
5392 # Find out what is on the end of the line after the
5394 substr($s, 0, length($c), '');
5396 $s =~ s/$;//g; # Remove any comments
5397 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5398 $c !~ /}\s*while\s*/)
5400 # Find out how long the conditional actually is.
5401 my @newlines = ($c =~ /\n/gs);
5402 my $cond_lines = 1 + $#newlines;
5405 $stat_real = raw_line($linenr, $cond_lines)
5406 . "\n" if ($cond_lines);
5407 if (defined($stat_real) && $cond_lines > 1) {
5408 $stat_real = "[...]\n$stat_real";
5411 ERROR("TRAILING_STATEMENTS",
5412 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5416 # Check for bitwise tests written as boolean
5428 WARN("HEXADECIMAL_BOOLEAN_TEST",
5429 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5432 # if and else should not have general statements after it
5433 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5435 $s =~ s/$;//g; # Remove any comments
5436 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5437 ERROR("TRAILING_STATEMENTS",
5438 "trailing statements should be on next line\n" . $herecurr);
5441 # if should not continue a brace
5442 if ($line =~ /}\s*if\b/) {
5443 ERROR("TRAILING_STATEMENTS",
5444 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5447 # case and default should not have general statements after them
5448 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5450 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5454 ERROR("TRAILING_STATEMENTS",
5455 "trailing statements should be on next line\n" . $herecurr);
5458 # Check for }<nl>else {, these must be at the same
5459 # indent level to be relevant to each other.
5460 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5461 $previndent == $indent) {
5462 if (ERROR("ELSE_AFTER_BRACE",
5463 "else should follow close brace '}'\n" . $hereprev) &&
5464 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5465 fix_delete_line($fixlinenr - 1, $prevrawline);
5466 fix_delete_line($fixlinenr, $rawline);
5467 my $fixedline = $prevrawline;
5468 $fixedline =~ s/}\s*$//;
5469 if ($fixedline !~ /^\+\s*$/) {
5470 fix_insert_line($fixlinenr, $fixedline);
5472 $fixedline = $rawline;
5473 $fixedline =~ s/^(.\s*)else/$1} else/;
5474 fix_insert_line($fixlinenr, $fixedline);
5478 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5479 $previndent == $indent) {
5480 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5482 # Find out what is on the end of the line after the
5484 substr($s, 0, length($c), '');
5487 if ($s =~ /^\s*;/) {
5488 if (ERROR("WHILE_AFTER_BRACE",
5489 "while should follow close brace '}'\n" . $hereprev) &&
5490 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5491 fix_delete_line($fixlinenr - 1, $prevrawline);
5492 fix_delete_line($fixlinenr, $rawline);
5493 my $fixedline = $prevrawline;
5494 my $trailing = $rawline;
5495 $trailing =~ s/^\+//;
5496 $trailing = trim($trailing);
5497 $fixedline =~ s/}\s*$/} $trailing/;
5498 fix_insert_line($fixlinenr, $fixedline);
5503 #Specific variable tests
5504 while ($line =~ m{($Constant|$Lval)}g) {
5508 if ($var !~ /^$Constant$/ &&
5509 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5510 #Ignore some autogenerated defines and enum values
5511 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5512 #Ignore Page<foo> variants
5513 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5514 #Ignore SI style variants like nS, mV and dB
5515 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5516 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5517 #Ignore some three character SI units explicitly, like MiB and KHz
5518 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5519 while ($var =~ m{($Ident)}g) {
5521 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5523 seed_camelcase_includes();
5524 if (!$file && !$camelcase_file_seeded) {
5525 seed_camelcase_file($realfile);
5526 $camelcase_file_seeded = 1;
5529 if (!defined $camelcase{$word}) {
5530 $camelcase{$word} = 1;
5532 "Avoid CamelCase: <$word>\n" . $herecurr);
5538 #no spaces allowed after \ in define
5539 if ($line =~ /\#\s*define.*\\\s+$/) {
5540 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5541 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5543 $fixed[$fixlinenr] =~ s/\s+$//;
5547 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5548 # itself <asm/foo.h> (uses RAW line)
5549 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5551 my $checkfile = "include/linux/$file";
5552 if (-f "$root/$checkfile" &&
5553 $realfile ne $checkfile &&
5554 $1 !~ /$allowed_asm_includes/)
5556 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5557 if ($asminclude > 0) {
5558 if ($realfile =~ m{^arch/}) {
5559 CHK("ARCH_INCLUDE_LINUX",
5560 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5562 WARN("INCLUDE_LINUX",
5563 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5569 # multi-statement macros should be enclosed in a do while loop, grab the
5570 # first statement and ensure its the whole macro if its not enclosed
5571 # in a known good container
5572 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5573 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5576 my ($off, $dstat, $dcond, $rest);
5578 my $has_flow_statement = 0;
5579 my $has_arg_concat = 0;
5580 ($dstat, $dcond, $ln, $cnt, $off) =
5581 ctx_statement_block($linenr, $realcnt, 0);
5583 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5584 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5586 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5587 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5589 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5590 my $define_args = $1;
5591 my $define_stmt = $dstat;
5594 if (defined $define_args && $define_args ne "") {
5595 $define_args = substr($define_args, 1, length($define_args) - 2);
5596 $define_args =~ s/\s*//g;
5597 $define_args =~ s/\\\+?//g;
5598 @def_args = split(",", $define_args);
5602 $dstat =~ s/\\\n.//g;
5603 $dstat =~ s/^\s*//s;
5604 $dstat =~ s/\s*$//s;
5606 # Flatten any parentheses and braces
5607 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5608 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5609 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5613 # Flatten any obvious string concatenation.
5614 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5615 $dstat =~ s/$Ident\s*($String)/$1/)
5619 # Make asm volatile uses seem like a generic function
5620 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5622 my $exceptions = qr{
5635 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5638 my $stmt_cnt = statement_rawlines($ctx);
5639 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5642 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5643 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5644 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5645 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5646 $dstat !~ /$exceptions/ &&
5647 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5648 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5649 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5650 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5651 $dstat !~ /^for\s*$Constant$/ && # for (...)
5652 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5653 $dstat !~ /^do\s*{/ && # do {...
5654 $dstat !~ /^\(\{/ && # ({...
5655 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5657 if ($dstat =~ /^\s*if\b/) {
5658 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5659 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5660 } elsif ($dstat =~ /;/) {
5661 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5662 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5664 ERROR("COMPLEX_MACRO",
5665 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5670 # Make $define_stmt single line, comment-free, etc
5671 my @stmt_array = split('\n', $define_stmt);
5674 foreach my $l (@stmt_array) {
5679 } elsif ($l =~ /^[\+ ]/) {
5680 $define_stmt .= substr($l, 1);
5683 $define_stmt =~ s/$;//g;
5684 $define_stmt =~ s/\s+/ /g;
5685 $define_stmt = trim($define_stmt);
5687 # check if any macro arguments are reused (ignore '...' and 'type')
5688 foreach my $arg (@def_args) {
5689 next if ($arg =~ /\.\.\./);
5690 next if ($arg =~ /^type$/i);
5691 my $tmp_stmt = $define_stmt;
5692 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5693 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5694 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5695 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5697 CHK("MACRO_ARG_REUSE",
5698 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5700 # check if any macro arguments may have other precedence issues
5701 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5702 ((defined($1) && $1 ne ',') ||
5703 (defined($2) && $2 ne ','))) {
5704 CHK("MACRO_ARG_PRECEDENCE",
5705 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5709 # check for macros with flow control, but without ## concatenation
5710 # ## concatenation is commonly a macro that defines a function so ignore those
5711 if ($has_flow_statement && !$has_arg_concat) {
5712 my $cnt = statement_rawlines($ctx);
5713 my $herectx = get_stat_here($linenr, $cnt, $here);
5715 WARN("MACRO_WITH_FLOW_CONTROL",
5716 "Macros with flow control statements should be avoided\n" . "$herectx");
5719 # check for line continuations outside of #defines, preprocessor #, and asm
5722 if ($prevline !~ /^..*\\$/ &&
5723 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5724 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5725 $line =~ /^\+.*\\$/) {
5726 WARN("LINE_CONTINUATIONS",
5727 "Avoid unnecessary line continuations\n" . $herecurr);
5731 # do {} while (0) macro tests:
5732 # single-statement macros do not need to be enclosed in do while (0) loop,
5733 # macro should not end with a semicolon
5734 if ($perl_version_ok &&
5735 $realfile !~ m@/vmlinux.lds.h$@ &&
5736 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5739 my ($off, $dstat, $dcond, $rest);
5741 ($dstat, $dcond, $ln, $cnt, $off) =
5742 ctx_statement_block($linenr, $realcnt, 0);
5745 $dstat =~ s/\\\n.//g;
5748 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5753 my $cnt = statement_rawlines($ctx);
5754 my $herectx = get_stat_here($linenr, $cnt, $here);
5756 if (($stmts =~ tr/;/;/) == 1 &&
5757 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5758 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5759 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5761 if (defined $semis && $semis ne "") {
5762 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5763 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5765 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5767 my $cnt = statement_rawlines($ctx);
5768 my $herectx = get_stat_here($linenr, $cnt, $here);
5770 WARN("TRAILING_SEMICOLON",
5771 "macros should not use a trailing semicolon\n" . "$herectx");
5775 # check for redundant bracing round if etc
5776 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5777 my ($level, $endln, @chunks) =
5778 ctx_statement_full($linenr, $realcnt, 1);
5779 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5780 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5781 if ($#chunks > 0 && $level == 0) {
5785 my $herectx = $here . "\n";
5786 my $ln = $linenr - 1;
5787 for my $chunk (@chunks) {
5788 my ($cond, $block) = @{$chunk};
5790 # If the condition carries leading newlines, then count those as offsets.
5791 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5792 my $offset = statement_rawlines($whitespace) - 1;
5794 $allowed[$allow] = 0;
5795 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5797 # We have looked at and allowed this specific line.
5798 $suppress_ifbraces{$ln + $offset} = 1;
5800 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5801 $ln += statement_rawlines($block) - 1;
5803 substr($block, 0, length($cond), '');
5805 $seen++ if ($block =~ /^\s*{/);
5807 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5808 if (statement_lines($cond) > 1) {
5809 #print "APW: ALLOWED: cond<$cond>\n";
5810 $allowed[$allow] = 1;
5812 if ($block =~/\b(?:if|for|while)\b/) {
5813 #print "APW: ALLOWED: block<$block>\n";
5814 $allowed[$allow] = 1;
5816 if (statement_block_size($block) > 1) {
5817 #print "APW: ALLOWED: lines block<$block>\n";
5818 $allowed[$allow] = 1;
5823 my $sum_allowed = 0;
5824 foreach (@allowed) {
5827 if ($sum_allowed == 0) {
5829 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5830 } elsif ($sum_allowed != $allow &&
5833 "braces {} should be used on all arms of this statement\n" . $herectx);
5838 if (!defined $suppress_ifbraces{$linenr - 1} &&
5839 $line =~ /\b(if|while|for|else)\b/) {
5842 # Check the pre-context.
5843 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5844 #print "APW: ALLOWED: pre<$1>\n";
5848 my ($level, $endln, @chunks) =
5849 ctx_statement_full($linenr, $realcnt, $-[0]);
5851 # Check the condition.
5852 my ($cond, $block) = @{$chunks[0]};
5853 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5854 if (defined $cond) {
5855 substr($block, 0, length($cond), '');
5857 if (statement_lines($cond) > 1) {
5858 #print "APW: ALLOWED: cond<$cond>\n";
5861 if ($block =~/\b(?:if|for|while)\b/) {
5862 #print "APW: ALLOWED: block<$block>\n";
5865 if (statement_block_size($block) > 1) {
5866 #print "APW: ALLOWED: lines block<$block>\n";
5869 # Check the post-context.
5870 if (defined $chunks[1]) {
5871 my ($cond, $block) = @{$chunks[1]};
5872 if (defined $cond) {
5873 substr($block, 0, length($cond), '');
5875 if ($block =~ /^\s*\{/) {
5876 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5880 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5881 my $cnt = statement_rawlines($block);
5882 my $herectx = get_stat_here($linenr, $cnt, $here);
5885 "braces {} are not necessary for single statement blocks\n" . $herectx);
5889 # check for single line unbalanced braces
5890 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5891 $sline =~ /^.\s*else\s*\{\s*$/) {
5892 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5895 # check for unnecessary blank lines around braces
5896 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5898 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5899 $fix && $prevrawline =~ /^\+/) {
5900 fix_delete_line($fixlinenr - 1, $prevrawline);
5903 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5905 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5907 fix_delete_line($fixlinenr, $rawline);
5911 # no volatiles please
5912 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5913 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5915 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5918 # Check for user-visible strings broken across lines, which breaks the ability
5919 # to grep for the string. Make exceptions when the previous string ends in a
5920 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5921 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5922 if ($line =~ /^\+\s*$String/ &&
5923 $prevline =~ /"\s*$/ &&
5924 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5925 if (WARN("SPLIT_STRING",
5926 "quoted string split across lines\n" . $hereprev) &&
5928 $prevrawline =~ /^\+.*"\s*$/ &&
5929 $last_coalesced_string_linenr != $linenr - 1) {
5930 my $extracted_string = get_quoted_string($line, $rawline);
5931 my $comma_close = "";
5932 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5936 fix_delete_line($fixlinenr - 1, $prevrawline);
5937 fix_delete_line($fixlinenr, $rawline);
5938 my $fixedline = $prevrawline;
5939 $fixedline =~ s/"\s*$//;
5940 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5941 fix_insert_line($fixlinenr - 1, $fixedline);
5942 $fixedline = $rawline;
5943 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5944 if ($fixedline !~ /\+\s*$/) {
5945 fix_insert_line($fixlinenr, $fixedline);
5947 $last_coalesced_string_linenr = $linenr;
5951 # check for missing a space in a string concatenation
5952 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5953 WARN('MISSING_SPACE',
5954 "break quoted strings at a space character\n" . $hereprev);
5957 # check for an embedded function name in a string when the function is known
5958 # This does not work very well for -f --file checking as it depends on patch
5959 # context providing the function name or a single line form for in-file
5960 # function declarations
5961 if ($line =~ /^\+.*$String/ &&
5962 defined($context_function) &&
5963 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5964 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5965 WARN("EMBEDDED_FUNCTION_NAME",
5966 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5969 # check for spaces before a quoted newline
5970 if ($rawline =~ /^.*\".*\s\\n/) {
5971 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5972 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5974 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5979 # concatenated string without spaces between elements
5980 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5981 if (CHK("CONCATENATED_STRING",
5982 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5984 while ($line =~ /($String)/g) {
5985 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5986 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5987 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5992 # uncoalesced string fragments
5993 if ($line =~ /$String\s*"/) {
5994 if (WARN("STRING_FRAGMENTS",
5995 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5997 while ($line =~ /($String)(?=\s*")/g) {
5998 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5999 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6004 # check for non-standard and hex prefixed decimal printf formats
6005 my $show_L = 1; #don't show the same defect twice
6007 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6008 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6009 $string =~ s/%%/__/g;
6011 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6013 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6017 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6019 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6022 # check for 0x<decimal>
6023 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6024 ERROR("PRINTF_0XDECIMAL",
6025 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6029 # check for line continuations in quoted strings with odd counts of "
6030 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6031 WARN("LINE_CONTINUATIONS",
6032 "Avoid line continuations in quoted strings\n" . $herecurr);
6036 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6038 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6042 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6044 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6047 # check for needless "if (<foo>) fn(<foo>)" uses
6048 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6049 my $tested = quotemeta($1);
6050 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6051 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6053 if (WARN('NEEDLESS_IF',
6054 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6057 my $leading_tabs = "";
6058 my $new_leading_tabs = "";
6059 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6064 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6065 $new_leading_tabs = $1;
6066 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6073 fix_delete_line($fixlinenr - 1, $prevrawline);
6074 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6080 # check for unnecessary "Out of Memory" messages
6081 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6082 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6083 (defined $1 || defined $3) &&
6086 my $testline = $lines[$linenr - 3];
6088 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6089 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6091 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6092 $s !~ /\b__GFP_NOWARN\b/ ) {
6094 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6098 # check for logging functions with KERN_<LEVEL>
6099 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6100 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6102 if (WARN("UNNECESSARY_KERN_LEVEL",
6103 "Possible unnecessary $level\n" . $herecurr) &&
6105 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6109 # check for logging continuations
6110 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6111 WARN("LOGGING_CONTINUATION",
6112 "Avoid logging continuation uses where feasible\n" . $herecurr);
6115 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6116 if (defined $stat &&
6117 $line =~ /\b$logFunctions\s*\(/ &&
6118 index($stat, '"') >= 0) {
6119 my $lc = $stat =~ tr@\n@@;
6120 $lc = $lc + $linenr;
6121 my $stat_real = get_stat_real($linenr, $lc);
6122 pos($stat_real) = index($stat_real, '"');
6123 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6126 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6127 if (WARN("UNNECESSARY_MODIFIER",
6128 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6129 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6132 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6137 # check for mask then right shift without a parentheses
6138 if ($perl_version_ok &&
6139 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6140 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6141 WARN("MASK_THEN_SHIFT",
6142 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6145 # check for pointer comparisons to NULL
6146 if ($perl_version_ok) {
6147 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6150 $equal = "" if ($4 eq "!=");
6151 if (CHK("COMPARISON_TO_NULL",
6152 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6154 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6159 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6160 if ($line =~ /(\b$InitAttribute\b)/) {
6162 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6165 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6166 ERROR("MISPLACED_INIT",
6167 "$attr should be placed after $var\n" . $herecurr)) ||
6168 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6169 WARN("MISPLACED_INIT",
6170 "$attr should be placed after $var\n" . $herecurr))) &&
6172 $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;
6177 # check for $InitAttributeData (ie: __initdata) with const
6178 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6180 $attr =~ /($InitAttributePrefix)(.*)/;
6181 my $attr_prefix = $1;
6183 if (ERROR("INIT_ATTRIBUTE",
6184 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6186 $fixed[$fixlinenr] =~
6187 s/$InitAttributeData/${attr_prefix}initconst/;
6191 # check for $InitAttributeConst (ie: __initconst) without const
6192 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6194 if (ERROR("INIT_ATTRIBUTE",
6195 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6197 my $lead = $fixed[$fixlinenr] =~
6198 /(^\+\s*(?:static\s+))/;
6200 $lead = "$lead " if ($lead !~ /^\+$/);
6201 $lead = "${lead}const ";
6202 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6206 # check for __read_mostly with const non-pointer (should just be const)
6207 if ($line =~ /\b__read_mostly\b/ &&
6208 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6209 if (ERROR("CONST_READ_MOSTLY",
6210 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6212 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6216 # don't use __constant_<foo> functions outside of include/uapi/
6217 if ($realfile !~ m@^include/uapi/@ &&
6218 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6219 my $constant_func = $1;
6220 my $func = $constant_func;
6221 $func =~ s/^__constant_//;
6222 if (WARN("CONSTANT_CONVERSION",
6223 "$constant_func should be $func\n" . $herecurr) &&
6225 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6229 # prefer usleep_range over udelay
6230 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6232 # ignore udelay's < 10, however
6233 if (! ($delay < 10) ) {
6235 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6237 if ($delay > 2000) {
6239 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6243 # warn about unexpectedly long msleep's
6244 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6247 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6251 # check for comparisons of jiffies
6252 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6253 WARN("JIFFIES_COMPARISON",
6254 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6257 # check for comparisons of get_jiffies_64()
6258 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6259 WARN("JIFFIES_COMPARISON",
6260 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6263 # warn about #ifdefs in C files
6264 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6265 # print "#ifdef in C files should be avoided\n";
6266 # print "$herecurr";
6270 # warn about spacing in #ifdefs
6271 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6272 if (ERROR("SPACING",
6273 "exactly one space required after that #$1\n" . $herecurr) &&
6275 $fixed[$fixlinenr] =~
6276 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6281 # check for spinlock_t definitions without a comment.
6282 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6283 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6285 if (!ctx_has_comment($first_line, $linenr)) {
6286 CHK("UNCOMMENTED_DEFINITION",
6287 "$1 definition without comment\n" . $herecurr);
6290 # check for memory barriers without a comment.
6297 my $barrier_stems = qr{
6305 my $all_barriers = qr{
6307 smp_(?:$barrier_stems)|
6308 virt_(?:$barrier_stems)
6311 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6312 if (!ctx_has_comment($first_line, $linenr)) {
6313 WARN("MEMORY_BARRIER",
6314 "memory barrier without comment\n" . $herecurr);
6318 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6320 if ($realfile !~ m@^include/asm-generic/@ &&
6321 $realfile !~ m@/barrier\.h$@ &&
6322 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6323 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6324 WARN("MEMORY_BARRIER",
6325 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6328 # check for waitqueue_active without a comment.
6329 if ($line =~ /\bwaitqueue_active\s*\(/) {
6330 if (!ctx_has_comment($first_line, $linenr)) {
6331 WARN("WAITQUEUE_ACTIVE",
6332 "waitqueue_active without comment\n" . $herecurr);
6336 # check for data_race without a comment.
6337 if ($line =~ /\bdata_race\s*\(/) {
6338 if (!ctx_has_comment($first_line, $linenr)) {
6340 "data_race without comment\n" . $herecurr);
6344 # check of hardware specific defines
6345 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6347 "architecture specific defines should be avoided\n" . $herecurr);
6350 # check that the storage class is not after a type
6351 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6352 WARN("STORAGE_CLASS",
6353 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6355 # Check that the storage class is at the beginning of a declaration
6356 if ($line =~ /\b$Storage\b/ &&
6357 $line !~ /^.\s*$Storage/ &&
6358 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6359 $1 !~ /[\,\)]\s*$/) {
6360 WARN("STORAGE_CLASS",
6361 "storage class should be at the beginning of the declaration\n" . $herecurr);
6364 # check the location of the inline attribute, that it is between
6365 # storage class and type.
6366 if ($line =~ /\b$Type\s+$Inline\b/ ||
6367 $line =~ /\b$Inline\s+$Storage\b/) {
6368 ERROR("INLINE_LOCATION",
6369 "inline keyword should sit between storage class and type\n" . $herecurr);
6372 # Check for __inline__ and __inline, prefer inline
6373 if ($realfile !~ m@\binclude/uapi/@ &&
6374 $line =~ /\b(__inline__|__inline)\b/) {
6376 "plain inline is preferred over $1\n" . $herecurr) &&
6378 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6383 # Check for compiler attributes
6384 if ($realfile !~ m@\binclude/uapi/@ &&
6385 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6387 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6390 "alias" => "__alias",
6391 "aligned" => "__aligned",
6392 "always_inline" => "__always_inline",
6393 "assume_aligned" => "__assume_aligned",
6395 "const" => "__attribute_const__",
6397 "designated_init" => "__designated_init",
6398 "externally_visible" => "__visible",
6399 "format" => "printf|scanf",
6400 "gnu_inline" => "__gnu_inline",
6401 "malloc" => "__malloc",
6403 "no_caller_saved_registers" => "__no_caller_saved_registers",
6404 "noclone" => "__noclone",
6405 "noinline" => "noinline",
6406 "nonstring" => "__nonstring",
6407 "noreturn" => "__noreturn",
6408 "packed" => "__packed",
6410 "section" => "__section",
6415 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6418 $params = $2 if defined($2);
6419 my $curr_attr = $orig_attr;
6420 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6421 if (exists($attr_list{$curr_attr})) {
6422 my $new = $attr_list{$curr_attr};
6423 if ($curr_attr eq "format" && $params) {
6424 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6427 $new = "$new$params";
6429 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6430 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6432 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6433 $fixed[$fixlinenr] =~ s/$remove//;
6434 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6435 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6436 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6441 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6442 if ($attr =~ /^_*unused/) {
6443 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6444 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6448 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6449 if ($perl_version_ok &&
6450 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6451 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6452 $line =~ /\b__weak\b/)) {
6453 ERROR("WEAK_DECLARATION",
6454 "Using weak declarations can have unintended link defects\n" . $herecurr);
6457 # check for c99 types like uint8_t used outside of uapi/ and tools/
6458 if ($realfile !~ m@\binclude/uapi/@ &&
6459 $realfile !~ m@\btools/@ &&
6460 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6462 if ($type =~ /\b($typeC99Typedefs)\b/) {
6464 my $kernel_type = 'u';
6465 $kernel_type = 's' if ($type =~ /^_*[si]/);
6468 if (CHK("PREFER_KERNEL_TYPES",
6469 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6471 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6476 # check for cast of C90 native int or longer types constants
6477 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6480 if (WARN("TYPECAST_INT_CONSTANT",
6481 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6484 my $newconst = $const;
6485 $newconst =~ s/${Int_type}$//;
6486 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6487 if ($cast =~ /\blong\s+long\b/) {
6489 } elsif ($cast =~ /\blong\b/) {
6492 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6496 # check for sizeof(&)
6497 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6498 WARN("SIZEOF_ADDRESS",
6499 "sizeof(& should be avoided\n" . $herecurr);
6502 # check for sizeof without parenthesis
6503 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6504 if (WARN("SIZEOF_PARENTHESIS",
6505 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6507 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6511 # check for struct spinlock declarations
6512 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6513 WARN("USE_SPINLOCK_T",
6514 "struct spinlock should be spinlock_t\n" . $herecurr);
6517 # check for seq_printf uses that could be seq_puts
6518 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6519 my $fmt = get_quoted_string($line, $rawline);
6522 if (WARN("PREFER_SEQ_PUTS",
6523 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6525 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6530 # check for vsprintf extension %p<foo> misuses
6531 if ($perl_version_ok &&
6533 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6534 $1 !~ /^_*volatile_*$/) {
6537 my $lc = $stat =~ tr@\n@@;
6538 $lc = $lc + $linenr;
6539 for (my $count = $linenr; $count <= $lc; $count++) {
6543 my $bad_specifier = "";
6544 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6547 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6551 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6552 ($extension eq "f" &&
6553 defined $qualifier && $qualifier !~ /^w/)) {
6554 $bad_specifier = $specifier;
6557 if ($extension eq "x" && !defined($stat_real)) {
6558 if (!defined($stat_real)) {
6559 $stat_real = get_stat_real($linenr, $lc);
6561 WARN("VSPRINTF_SPECIFIER_PX",
6562 "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");
6565 if ($bad_specifier ne "") {
6566 my $stat_real = get_stat_real($linenr, $lc);
6567 my $ext_type = "Invalid";
6569 if ($bad_specifier =~ /p[Ff]/) {
6570 $use = " - use %pS instead";
6571 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6574 WARN("VSPRINTF_POINTER_EXTENSION",
6575 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6580 # Check for misused memsets
6581 if ($perl_version_ok &&
6583 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6589 if ($ms_size =~ /^(0x|)0$/i) {
6591 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6592 } elsif ($ms_size =~ /^(0x|)1$/i) {
6594 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6598 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6599 # if ($perl_version_ok &&
6601 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6602 # if (WARN("PREFER_ETHER_ADDR_COPY",
6603 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6605 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6609 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6610 # if ($perl_version_ok &&
6612 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6613 # WARN("PREFER_ETHER_ADDR_EQUAL",
6614 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6617 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6618 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6619 # if ($perl_version_ok &&
6621 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6625 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6626 # if (WARN("PREFER_ETH_ZERO_ADDR",
6627 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6629 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6631 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6632 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6633 # "Prefer eth_broadcast_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_broadcast_addr($2)/;
6640 # strlcpy uses that should likely be strscpy
6641 if ($line =~ /\bstrlcpy\s*\(/) {
6643 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6646 # typecasts on min/max could be min_t/max_t
6647 if ($perl_version_ok &&
6649 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6650 if (defined $2 || defined $7) {
6652 my $cast1 = deparenthesize($2);
6654 my $cast2 = deparenthesize($7);
6658 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6659 $cast = "$cast1 or $cast2";
6660 } elsif ($cast1 ne "") {
6666 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6670 # check usleep_range arguments
6671 if ($perl_version_ok &&
6673 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6677 WARN("USLEEP_RANGE",
6678 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6679 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6681 WARN("USLEEP_RANGE",
6682 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6686 # check for naked sscanf
6687 if ($perl_version_ok &&
6689 $line =~ /\bsscanf\b/ &&
6690 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6691 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6692 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6693 my $lc = $stat =~ tr@\n@@;
6694 $lc = $lc + $linenr;
6695 my $stat_real = get_stat_real($linenr, $lc);
6696 WARN("NAKED_SSCANF",
6697 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6700 # check for simple sscanf that should be kstrto<foo>
6701 if ($perl_version_ok &&
6703 $line =~ /\bsscanf\b/) {
6704 my $lc = $stat =~ tr@\n@@;
6705 $lc = $lc + $linenr;
6706 my $stat_real = get_stat_real($linenr, $lc);
6707 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6709 my $count = $format =~ tr@%@%@;
6711 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6712 WARN("SSCANF_TO_KSTRTO",
6713 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6718 # check for new externs in .h files.
6719 if ($realfile =~ /\.h$/ &&
6720 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6721 if (CHK("AVOID_EXTERNS",
6722 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6724 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6728 # check for new externs in .c files.
6729 if ($realfile =~ /\.c$/ && defined $stat &&
6730 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6732 my $function_name = $1;
6733 my $paren_space = $2;
6736 if (defined $cond) {
6737 substr($s, 0, length($cond), '');
6741 WARN("AVOID_EXTERNS",
6742 "externs should be avoided in .c files\n" . $herecurr);
6745 if ($paren_space =~ /\n/) {
6746 WARN("FUNCTION_ARGUMENTS",
6747 "arguments for function declarations should follow identifier\n" . $herecurr);
6750 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6751 $stat =~ /^.\s*extern\s+/)
6753 WARN("AVOID_EXTERNS",
6754 "externs should be avoided in .c files\n" . $herecurr);
6757 # check for function declarations that have arguments without identifier names
6758 if (defined $stat &&
6759 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6761 my $args = trim($1);
6762 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6764 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6765 WARN("FUNCTION_ARGUMENTS",
6766 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6771 # check for function definitions
6772 if ($perl_version_ok &&
6774 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6775 $context_function = $1;
6777 # check for multiline function definition with misplaced open brace
6779 my $cnt = statement_rawlines($stat);
6780 my $herectx = $here . "\n";
6781 for (my $n = 0; $n < $cnt; $n++) {
6782 my $rl = raw_line($linenr, $n);
6783 $herectx .= $rl . "\n";
6784 $ok = 1 if ($rl =~ /^[ \+]\{/);
6785 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6786 last if $rl =~ /^[ \+].*\{/;
6790 "open brace '{' following function definitions go on the next line\n" . $herectx);
6794 # checks for new __setup's
6795 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6798 if (!grep(/$name/, @setup_docs)) {
6799 CHK("UNDOCUMENTED_SETUP",
6800 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6804 # check for pointless casting of alloc functions
6805 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6806 WARN("UNNECESSARY_CASTS",
6807 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6811 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6812 if ($perl_version_ok &&
6813 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6814 CHK("ALLOC_SIZEOF_STRUCT",
6815 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6818 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6819 if ($perl_version_ok &&
6821 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6825 my $newfunc = "kmalloc_array";
6826 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6829 if ($a1 =~ /^sizeof\s*\S/) {
6833 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6834 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6835 my $cnt = statement_rawlines($stat);
6836 my $herectx = get_stat_here($linenr, $cnt, $here);
6838 if (WARN("ALLOC_WITH_MULTIPLY",
6839 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6842 $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;
6847 # check for krealloc arg reuse
6848 if ($perl_version_ok &&
6849 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6851 WARN("KREALLOC_ARG_REUSE",
6852 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6855 # check for alloc argument mismatch
6856 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6857 WARN("ALLOC_ARRAY_ARGS",
6858 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6861 # check for multiple semicolons
6862 if ($line =~ /;\s*;\s*$/) {
6863 if (WARN("ONE_SEMICOLON",
6864 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6866 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6870 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6871 if ($realfile !~ m@^include/uapi/@ &&
6872 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6874 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6875 if (CHK("BIT_MACRO",
6876 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6878 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6882 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6883 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6884 WARN("IS_ENABLED_CONFIG",
6885 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6888 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6889 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6891 if (WARN("PREFER_IS_ENABLED",
6892 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6894 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6898 # check for /* fallthrough */ like comment, prefer fallthrough;
6899 my @fallthroughs = (
6902 'lint -fallthrough[ \t]*',
6903 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6904 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6905 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6906 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6908 if ($raw_comment ne '') {
6909 foreach my $ft (@fallthroughs) {
6910 if ($raw_comment =~ /$ft/) {
6911 my $msg_level = \&WARN;
6912 $msg_level = \&CHK if ($file);
6913 &{$msg_level}("PREFER_FALLTHROUGH",
6914 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6920 # check for switch/default statements without a break;
6921 if ($perl_version_ok &&
6923 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6924 my $cnt = statement_rawlines($stat);
6925 my $herectx = get_stat_here($linenr, $cnt, $here);
6927 WARN("DEFAULT_NO_BREAK",
6928 "switch default: should use break\n" . $herectx);
6931 # check for gcc specific __FUNCTION__
6932 if ($line =~ /\b__FUNCTION__\b/) {
6933 if (WARN("USE_FUNC",
6934 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6936 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6940 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6941 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6943 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6946 # check for use of yield()
6947 if ($line =~ /\byield\s*\(\s*\)/) {
6949 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6952 # check for comparisons against true and false
6953 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6961 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6963 my $type = lc($otype);
6964 if ($type =~ /^(?:true|false)$/) {
6965 if (("$test" eq "==" && "$type" eq "true") ||
6966 ("$test" eq "!=" && "$type" eq "false")) {
6970 CHK("BOOL_COMPARISON",
6971 "Using comparison to $otype is error prone\n" . $herecurr);
6973 ## maybe suggesting a correct construct would better
6974 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6979 # check for semaphores initialized locked
6980 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6981 WARN("CONSIDER_COMPLETION",
6982 "consider using a completion\n" . $herecurr);
6985 # recommend kstrto* over simple_strto* and strict_strto*
6986 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6987 WARN("CONSIDER_KSTRTO",
6988 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6991 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6992 if ($line =~ /^.\s*__initcall\s*\(/) {
6993 WARN("USE_DEVICE_INITCALL",
6994 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6997 # check for spin_is_locked(), suggest lockdep instead
6998 if ($line =~ /\bspin_is_locked\(/) {
7000 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7003 # check for deprecated apis
7004 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7005 my $deprecated_api = $1;
7006 my $new_api = $deprecated_apis{$deprecated_api};
7007 WARN("DEPRECATED_API",
7008 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7011 # check for various structs that are normally const (ops, kgdb, device_tree)
7012 # and avoid what seem like struct definitions 'struct foo {'
7013 if (defined($const_structs) &&
7014 $line !~ /\bconst\b/ &&
7015 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7016 WARN("CONST_STRUCT",
7017 "struct $1 should normally be const\n" . $herecurr);
7020 # use of NR_CPUS is usually wrong
7021 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7022 if ($line =~ /\bNR_CPUS\b/ &&
7023 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7024 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7025 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7026 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7027 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
7030 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7033 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7034 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7035 ERROR("DEFINE_ARCH_HAS",
7036 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7039 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7040 if ($perl_version_ok &&
7041 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7042 WARN("LIKELY_MISUSE",
7043 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7046 # nested likely/unlikely calls
7047 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7048 WARN("LIKELY_MISUSE",
7049 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7052 # whine mightly about in_atomic
7053 if ($line =~ /\bin_atomic\s*\(/) {
7054 if ($realfile =~ m@^drivers/@) {
7056 "do not use in_atomic in drivers\n" . $herecurr);
7057 } elsif ($realfile !~ m@^kernel/@) {
7059 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7063 # check for lockdep_set_novalidate_class
7064 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7065 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7066 if ($realfile !~ m@^kernel/lockdep@ &&
7067 $realfile !~ m@^include/linux/lockdep@ &&
7068 $realfile !~ m@^drivers/base/core@) {
7070 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7074 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7075 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7076 WARN("EXPORTED_WORLD_WRITABLE",
7077 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7080 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7081 # and whether or not function naming is typical and if
7082 # DEVICE_ATTR permissions uses are unusual too
7083 if ($perl_version_ok &&
7085 $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*\)/) {
7090 my $octal_perms = perms_to_octal($perms);
7091 if ($show =~ /^${var}_show$/ &&
7092 $store =~ /^${var}_store$/ &&
7093 $octal_perms eq "0644") {
7094 if (WARN("DEVICE_ATTR_RW",
7095 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7097 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7099 } elsif ($show =~ /^${var}_show$/ &&
7100 $store =~ /^NULL$/ &&
7101 $octal_perms eq "0444") {
7102 if (WARN("DEVICE_ATTR_RO",
7103 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7105 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7107 } elsif ($show =~ /^NULL$/ &&
7108 $store =~ /^${var}_store$/ &&
7109 $octal_perms eq "0200") {
7110 if (WARN("DEVICE_ATTR_WO",
7111 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7113 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7115 } elsif ($octal_perms eq "0644" ||
7116 $octal_perms eq "0444" ||
7117 $octal_perms eq "0200") {
7118 my $newshow = "$show";
7119 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7120 my $newstore = $store;
7121 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7123 if ($show ne $newshow) {
7124 $rename .= " '$show' to '$newshow'";
7126 if ($store ne $newstore) {
7127 $rename .= " '$store' to '$newstore'";
7129 WARN("DEVICE_ATTR_FUNCTIONS",
7130 "Consider renaming function(s)$rename\n" . $herecurr);
7132 WARN("DEVICE_ATTR_PERMS",
7133 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7137 # Mode permission misuses where it seems decimal should be octal
7138 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7139 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7140 # specific definition of not visible in sysfs.
7141 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7142 # use the default permissions
7143 if ($perl_version_ok &&
7145 $line =~ /$mode_perms_search/) {
7146 foreach my $entry (@mode_permission_funcs) {
7147 my $func = $entry->[0];
7148 my $arg_pos = $entry->[1];
7150 my $lc = $stat =~ tr@\n@@;
7151 $lc = $lc + $linenr;
7152 my $stat_real = get_stat_real($linenr, $lc);
7157 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7159 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7160 if ($stat =~ /$test/) {
7162 $val = $6 if ($skip_args ne "");
7163 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7164 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7165 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7166 ERROR("NON_OCTAL_PERMISSIONS",
7167 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7169 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7170 ERROR("EXPORTED_WORLD_WRITABLE",
7171 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7177 # check for uses of S_<PERMS> that could be octal for readability
7178 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7180 my $octal = perms_to_octal($oval);
7181 if (WARN("SYMBOLIC_PERMS",
7182 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7184 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7188 # validate content of MODULE_LICENSE against list from include/linux/module.h
7189 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7190 my $extracted_string = get_quoted_string($line, $rawline);
7191 my $valid_licenses = qr{
7194 GPL\ and\ additional\ rights|
7200 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7201 WARN("MODULE_LICENSE",
7202 "unknown module license " . $extracted_string . "\n" . $herecurr);
7206 # check for sysctl duplicate constants
7207 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7208 WARN("DUPLICATED_SYSCTL_CONST",
7209 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7213 # If we have no input at all, then there is nothing to report on
7214 # so just keep quiet.
7215 if ($#rawlines == -1) {
7219 # In mailback mode only produce a report in the negative, for
7220 # things that appear to be patches.
7221 if ($mailback && ($clean == 1 || !$is_patch)) {
7225 # This is not a patch, and we are in 'no-patch' mode so
7227 if (!$chk_patch && !$is_patch) {
7231 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7232 ERROR("NOT_UNIFIED_DIFF",
7233 "Does not appear to be a unified-diff format patch\n");
7235 if ($is_patch && $has_commit_log && $chk_signoff) {
7236 if ($signoff == 0) {
7237 ERROR("MISSING_SIGN_OFF",
7238 "Missing Signed-off-by: line(s)\n");
7239 } elsif ($authorsignoff != 1) {
7240 # authorsignoff values:
7241 # 0 -> missing sign off
7242 # 1 -> sign off identical
7243 # 2 -> names and addresses match, comments mismatch
7244 # 3 -> addresses match, names different
7245 # 4 -> names match, addresses different
7246 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7248 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7250 if ($authorsignoff == 0) {
7251 ERROR("NO_AUTHOR_SIGN_OFF",
7252 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7253 } elsif ($authorsignoff == 2) {
7254 CHK("FROM_SIGN_OFF_MISMATCH",
7255 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7256 } elsif ($authorsignoff == 3) {
7257 WARN("FROM_SIGN_OFF_MISMATCH",
7258 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7259 } elsif ($authorsignoff == 4) {
7260 WARN("FROM_SIGN_OFF_MISMATCH",
7261 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7262 } elsif ($authorsignoff == 5) {
7263 WARN("FROM_SIGN_OFF_MISMATCH",
7264 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7269 print report_dump();
7270 if ($summary && !($clean == 1 && $quiet == 1)) {
7271 print "$filename " if ($summary_file);
7272 print "total: $cnt_error errors, $cnt_warn warnings, " .
7273 (($check)? "$cnt_chk checks, " : "") .
7274 "$cnt_lines lines checked\n";
7278 # If there were any defects found and not already fixing them
7279 if (!$clean and !$fix) {
7282 NOTE: For some of the reported defects, checkpatch may be able to
7283 mechanically convert to the typical style using --fix or --fix-inplace.
7286 # If there were whitespace errors which cleanpatch can fix
7287 # then suggest that.
7288 if ($rpt_cleaners) {
7292 NOTE: Whitespace errors detected.
7293 You may wish to use scripts/cleanpatch or scripts/cleanfile
7298 if ($clean == 0 && $fix &&
7299 ("@rawlines" ne "@fixed" ||
7300 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7301 my $newfile = $filename;
7302 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7306 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7308 open($f, '>', $newfile)
7309 or die "$P: Can't open $newfile for write\n";
7310 foreach my $fixed_line (@fixed) {
7313 if ($linecount > 3) {
7314 $fixed_line =~ s/^\+//;
7315 print $f $fixed_line . "\n";
7318 print $f $fixed_line . "\n";
7326 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7328 Do _NOT_ trust the results written to this file.
7329 Do _NOT_ submit these changes without inspecting them for correctness.
7331 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7332 No warranties, expressed or implied...
7340 print "$vname has no obvious style problems and is ready for submission.\n";
7342 print "$vname has style problems, please review.\n";